diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/atn/LexerATNSimulator.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/atn/LexerATNSimulator.py new file mode 100644 index 0000000000000000000000000000000000000000..71201ff5f989820d340aac8672ab31db8579b55c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/atn/LexerATNSimulator.py @@ -0,0 +1,570 @@ +# +# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. +# Use of this file is governed by the BSD 3-clause license that +# can be found in the LICENSE.txt file in the project root. +#/ + +# When we hit an accept state in either the DFA or the ATN, we +# have to notify the character stream to start buffering characters +# via {@link IntStream#mark} and record the current state. The current sim state +# includes the current index into the input, the current line, +# and current character position in that line. Note that the Lexer is +# tracking the starting line and characterization of the token. These +# variables track the "state" of the simulator when it hits an accept state. +# +#

We track these variables separately for the DFA and ATN simulation +# because the DFA simulation often has to fail over to the ATN +# simulation. If the ATN simulation fails, we need the DFA to fall +# back to its previously accepted state, if any. If the ATN succeeds, +# then the ATN does the accept and the DFA simulator that invoked it +# can simply return the predicted token type.

+#/ + +from antlr4.PredictionContext import PredictionContextCache, SingletonPredictionContext, PredictionContext +from antlr4.InputStream import InputStream +from antlr4.Token import Token +from antlr4.atn.ATN import ATN +from antlr4.atn.ATNConfig import LexerATNConfig +from antlr4.atn.ATNSimulator import ATNSimulator +from antlr4.atn.ATNConfigSet import ATNConfigSet, OrderedATNConfigSet +from antlr4.atn.ATNState import RuleStopState, ATNState +from antlr4.atn.LexerActionExecutor import LexerActionExecutor +from antlr4.atn.Transition import Transition +from antlr4.dfa.DFAState import DFAState +from antlr4.error.Errors import LexerNoViableAltException, UnsupportedOperationException + +class SimState(object): + __slots__ = ('index', 'line', 'column', 'dfaState') + + def __init__(self): + self.reset() + + def reset(self): + self.index = -1 + self.line = 0 + self.column = -1 + self.dfaState = None + +# need forward declaration +Lexer = None +LexerATNSimulator = None + +class LexerATNSimulator(ATNSimulator): + __slots__ = ( + 'decisionToDFA', 'recog', 'startIndex', 'line', 'column', 'mode', + 'DEFAULT_MODE', 'MAX_CHAR_VALUE', 'prevAccept' + ) + + debug = False + dfa_debug = False + + MIN_DFA_EDGE = 0 + MAX_DFA_EDGE = 127 # forces unicode to stay in ATN + + ERROR = None + + def __init__(self, recog:Lexer, atn:ATN, decisionToDFA:list, sharedContextCache:PredictionContextCache): + super().__init__(atn, sharedContextCache) + self.decisionToDFA = decisionToDFA + self.recog = recog + # The current token's starting index into the character stream. + # Shared across DFA to ATN simulation in case the ATN fails and the + # DFA did not have a previous accept state. In this case, we use the + # ATN-generated exception object. + self.startIndex = -1 + # line number 1..n within the input#/ + self.line = 1 + # The index of the character relative to the beginning of the line 0..n-1#/ + self.column = 0 + from antlr4.Lexer import Lexer + self.mode = Lexer.DEFAULT_MODE + # Cache Lexer properties to avoid further imports + self.DEFAULT_MODE = Lexer.DEFAULT_MODE + self.MAX_CHAR_VALUE = Lexer.MAX_CHAR_VALUE + # Used during DFA/ATN exec to record the most recent accept configuration info + self.prevAccept = SimState() + + + def copyState(self, simulator:LexerATNSimulator ): + self.column = simulator.column + self.line = simulator.line + self.mode = simulator.mode + self.startIndex = simulator.startIndex + + def match(self, input:InputStream , mode:int): + self.mode = mode + mark = input.mark() + try: + self.startIndex = input.index + self.prevAccept.reset() + dfa = self.decisionToDFA[mode] + if dfa.s0 is None: + return self.matchATN(input) + else: + return self.execATN(input, dfa.s0) + finally: + input.release(mark) + + def reset(self): + self.prevAccept.reset() + self.startIndex = -1 + self.line = 1 + self.column = 0 + self.mode = self.DEFAULT_MODE + + def matchATN(self, input:InputStream): + startState = self.atn.modeToStartState[self.mode] + + if LexerATNSimulator.debug: + print("matchATN mode " + str(self.mode) + " start: " + str(startState)) + + old_mode = self.mode + s0_closure = self.computeStartState(input, startState) + suppressEdge = s0_closure.hasSemanticContext + s0_closure.hasSemanticContext = False + + next = self.addDFAState(s0_closure) + if not suppressEdge: + self.decisionToDFA[self.mode].s0 = next + + predict = self.execATN(input, next) + + if LexerATNSimulator.debug: + print("DFA after matchATN: " + str(self.decisionToDFA[old_mode].toLexerString())) + + return predict + + def execATN(self, input:InputStream, ds0:DFAState): + if LexerATNSimulator.debug: + print("start state closure=" + str(ds0.configs)) + + if ds0.isAcceptState: + # allow zero-length tokens + self.captureSimState(self.prevAccept, input, ds0) + + t = input.LA(1) + s = ds0 # s is current/from DFA state + + while True: # while more work + if LexerATNSimulator.debug: + print("execATN loop starting closure:", str(s.configs)) + + # As we move src->trg, src->trg, we keep track of the previous trg to + # avoid looking up the DFA state again, which is expensive. + # If the previous target was already part of the DFA, we might + # be able to avoid doing a reach operation upon t. If s!=null, + # it means that semantic predicates didn't prevent us from + # creating a DFA state. Once we know s!=null, we check to see if + # the DFA state has an edge already for t. If so, we can just reuse + # it's configuration set; there's no point in re-computing it. + # This is kind of like doing DFA simulation within the ATN + # simulation because DFA simulation is really just a way to avoid + # computing reach/closure sets. Technically, once we know that + # we have a previously added DFA state, we could jump over to + # the DFA simulator. But, that would mean popping back and forth + # a lot and making things more complicated algorithmically. + # This optimization makes a lot of sense for loops within DFA. + # A character will take us back to an existing DFA state + # that already has lots of edges out of it. e.g., .* in comments. + # print("Target for:" + str(s) + " and:" + str(t)) + target = self.getExistingTargetState(s, t) + # print("Existing:" + str(target)) + if target is None: + target = self.computeTargetState(input, s, t) + # print("Computed:" + str(target)) + + if target == self.ERROR: + break + + # If this is a consumable input element, make sure to consume before + # capturing the accept state so the input index, line, and char + # position accurately reflect the state of the interpreter at the + # end of the token. + if t != Token.EOF: + self.consume(input) + + if target.isAcceptState: + self.captureSimState(self.prevAccept, input, target) + if t == Token.EOF: + break + + t = input.LA(1) + + s = target # flip; current DFA target becomes new src/from state + + return self.failOrAccept(self.prevAccept, input, s.configs, t) + + # Get an existing target state for an edge in the DFA. If the target state + # for the edge has not yet been computed or is otherwise not available, + # this method returns {@code null}. + # + # @param s The current DFA state + # @param t The next input symbol + # @return The existing target DFA state for the given input symbol + # {@code t}, or {@code null} if the target state for this edge is not + # already cached + def getExistingTargetState(self, s:DFAState, t:int): + if s.edges is None or t < self.MIN_DFA_EDGE or t > self.MAX_DFA_EDGE: + return None + + target = s.edges[t - self.MIN_DFA_EDGE] + if LexerATNSimulator.debug and target is not None: + print("reuse state", str(s.stateNumber), "edge to", str(target.stateNumber)) + + return target + + # Compute a target state for an edge in the DFA, and attempt to add the + # computed state and corresponding edge to the DFA. + # + # @param input The input stream + # @param s The current DFA state + # @param t The next input symbol + # + # @return The computed target DFA state for the given input symbol + # {@code t}. If {@code t} does not lead to a valid DFA state, this method + # returns {@link #ERROR}. + def computeTargetState(self, input:InputStream, s:DFAState, t:int): + reach = OrderedATNConfigSet() + + # if we don't find an existing DFA state + # Fill reach starting from closure, following t transitions + self.getReachableConfigSet(input, s.configs, reach, t) + + if len(reach)==0: # we got nowhere on t from s + if not reach.hasSemanticContext: + # we got nowhere on t, don't throw out this knowledge; it'd + # cause a failover from DFA later. + self. addDFAEdge(s, t, self.ERROR) + + # stop when we can't match any more char + return self.ERROR + + # Add an edge from s to target DFA found/created for reach + return self.addDFAEdge(s, t, cfgs=reach) + + def failOrAccept(self, prevAccept:SimState , input:InputStream, reach:ATNConfigSet, t:int): + if self.prevAccept.dfaState is not None: + lexerActionExecutor = prevAccept.dfaState.lexerActionExecutor + self.accept(input, lexerActionExecutor, self.startIndex, prevAccept.index, prevAccept.line, prevAccept.column) + return prevAccept.dfaState.prediction + else: + # if no accept and EOF is first char, return EOF + if t==Token.EOF and input.index==self.startIndex: + return Token.EOF + raise LexerNoViableAltException(self.recog, input, self.startIndex, reach) + + # Given a starting configuration set, figure out all ATN configurations + # we can reach upon input {@code t}. Parameter {@code reach} is a return + # parameter. + def getReachableConfigSet(self, input:InputStream, closure:ATNConfigSet, reach:ATNConfigSet, t:int): + # this is used to skip processing for configs which have a lower priority + # than a config that already reached an accept state for the same rule + skipAlt = ATN.INVALID_ALT_NUMBER + for cfg in closure: + currentAltReachedAcceptState = ( cfg.alt == skipAlt ) + if currentAltReachedAcceptState and cfg.passedThroughNonGreedyDecision: + continue + + if LexerATNSimulator.debug: + print("testing", self.getTokenName(t), "at", str(cfg)) + + for trans in cfg.state.transitions: # for each transition + target = self.getReachableTarget(trans, t) + if target is not None: + lexerActionExecutor = cfg.lexerActionExecutor + if lexerActionExecutor is not None: + lexerActionExecutor = lexerActionExecutor.fixOffsetBeforeMatch(input.index - self.startIndex) + + treatEofAsEpsilon = (t == Token.EOF) + config = LexerATNConfig(state=target, lexerActionExecutor=lexerActionExecutor, config=cfg) + if self.closure(input, config, reach, currentAltReachedAcceptState, True, treatEofAsEpsilon): + # any remaining configs for this alt have a lower priority than + # the one that just reached an accept state. + skipAlt = cfg.alt + + def accept(self, input:InputStream, lexerActionExecutor:LexerActionExecutor, startIndex:int, index:int, line:int, charPos:int): + if LexerATNSimulator.debug: + print("ACTION", lexerActionExecutor) + + # seek to after last char in token + input.seek(index) + self.line = line + self.column = charPos + + if lexerActionExecutor is not None and self.recog is not None: + lexerActionExecutor.execute(self.recog, input, startIndex) + + def getReachableTarget(self, trans:Transition, t:int): + if trans.matches(t, 0, self.MAX_CHAR_VALUE): + return trans.target + else: + return None + + def computeStartState(self, input:InputStream, p:ATNState): + initialContext = PredictionContext.EMPTY + configs = OrderedATNConfigSet() + for i in range(0,len(p.transitions)): + target = p.transitions[i].target + c = LexerATNConfig(state=target, alt=i+1, context=initialContext) + self.closure(input, c, configs, False, False, False) + return configs + + # Since the alternatives within any lexer decision are ordered by + # preference, this method stops pursuing the closure as soon as an accept + # state is reached. After the first accept state is reached by depth-first + # search from {@code config}, all other (potentially reachable) states for + # this rule would have a lower priority. + # + # @return {@code true} if an accept state is reached, otherwise + # {@code false}. + def closure(self, input:InputStream, config:LexerATNConfig, configs:ATNConfigSet, currentAltReachedAcceptState:bool, + speculative:bool, treatEofAsEpsilon:bool): + if LexerATNSimulator.debug: + print("closure(" + str(config) + ")") + + if isinstance( config.state, RuleStopState ): + if LexerATNSimulator.debug: + if self.recog is not None: + print("closure at", self.recog.symbolicNames[config.state.ruleIndex], "rule stop", str(config)) + else: + print("closure at rule stop", str(config)) + + if config.context is None or config.context.hasEmptyPath(): + if config.context is None or config.context.isEmpty(): + configs.add(config) + return True + else: + configs.add(LexerATNConfig(state=config.state, config=config, context=PredictionContext.EMPTY)) + currentAltReachedAcceptState = True + + if config.context is not None and not config.context.isEmpty(): + for i in range(0,len(config.context)): + if config.context.getReturnState(i) != PredictionContext.EMPTY_RETURN_STATE: + newContext = config.context.getParent(i) # "pop" return state + returnState = self.atn.states[config.context.getReturnState(i)] + c = LexerATNConfig(state=returnState, config=config, context=newContext) + currentAltReachedAcceptState = self.closure(input, c, configs, + currentAltReachedAcceptState, speculative, treatEofAsEpsilon) + + return currentAltReachedAcceptState + + # optimization + if not config.state.epsilonOnlyTransitions: + if not currentAltReachedAcceptState or not config.passedThroughNonGreedyDecision: + configs.add(config) + + for t in config.state.transitions: + c = self.getEpsilonTarget(input, config, t, configs, speculative, treatEofAsEpsilon) + if c is not None: + currentAltReachedAcceptState = self.closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon) + + return currentAltReachedAcceptState + + # side-effect: can alter configs.hasSemanticContext + def getEpsilonTarget(self, input:InputStream, config:LexerATNConfig, t:Transition, configs:ATNConfigSet, + speculative:bool, treatEofAsEpsilon:bool): + c = None + if t.serializationType==Transition.RULE: + newContext = SingletonPredictionContext.create(config.context, t.followState.stateNumber) + c = LexerATNConfig(state=t.target, config=config, context=newContext) + + elif t.serializationType==Transition.PRECEDENCE: + raise UnsupportedOperationException("Precedence predicates are not supported in lexers.") + + elif t.serializationType==Transition.PREDICATE: + # Track traversing semantic predicates. If we traverse, + # we cannot add a DFA state for this "reach" computation + # because the DFA would not test the predicate again in the + # future. Rather than creating collections of semantic predicates + # like v3 and testing them on prediction, v4 will test them on the + # fly all the time using the ATN not the DFA. This is slower but + # semantically it's not used that often. One of the key elements to + # this predicate mechanism is not adding DFA states that see + # predicates immediately afterwards in the ATN. For example, + + # a : ID {p1}? | ID {p2}? ; + + # should create the start state for rule 'a' (to save start state + # competition), but should not create target of ID state. The + # collection of ATN states the following ID references includes + # states reached by traversing predicates. Since this is when we + # test them, we cannot cash the DFA state target of ID. + + if LexerATNSimulator.debug: + print("EVAL rule "+ str(t.ruleIndex) + ":" + str(t.predIndex)) + configs.hasSemanticContext = True + if self.evaluatePredicate(input, t.ruleIndex, t.predIndex, speculative): + c = LexerATNConfig(state=t.target, config=config) + + elif t.serializationType==Transition.ACTION: + if config.context is None or config.context.hasEmptyPath(): + # execute actions anywhere in the start rule for a token. + # + # TODO: if the entry rule is invoked recursively, some + # actions may be executed during the recursive call. The + # problem can appear when hasEmptyPath() is true but + # isEmpty() is false. In this case, the config needs to be + # split into two contexts - one with just the empty path + # and another with everything but the empty path. + # Unfortunately, the current algorithm does not allow + # getEpsilonTarget to return two configurations, so + # additional modifications are needed before we can support + # the split operation. + lexerActionExecutor = LexerActionExecutor.append(config.lexerActionExecutor, + self.atn.lexerActions[t.actionIndex]) + c = LexerATNConfig(state=t.target, config=config, lexerActionExecutor=lexerActionExecutor) + + else: + # ignore actions in referenced rules + c = LexerATNConfig(state=t.target, config=config) + + elif t.serializationType==Transition.EPSILON: + c = LexerATNConfig(state=t.target, config=config) + + elif t.serializationType in [ Transition.ATOM, Transition.RANGE, Transition.SET ]: + if treatEofAsEpsilon: + if t.matches(Token.EOF, 0, self.MAX_CHAR_VALUE): + c = LexerATNConfig(state=t.target, config=config) + + return c + + # Evaluate a predicate specified in the lexer. + # + #

If {@code speculative} is {@code true}, this method was called before + # {@link #consume} for the matched character. This method should call + # {@link #consume} before evaluating the predicate to ensure position + # sensitive values, including {@link Lexer#getText}, {@link Lexer#getLine}, + # and {@link Lexer#getcolumn}, properly reflect the current + # lexer state. This method should restore {@code input} and the simulator + # to the original state before returning (i.e. undo the actions made by the + # call to {@link #consume}.

+ # + # @param input The input stream. + # @param ruleIndex The rule containing the predicate. + # @param predIndex The index of the predicate within the rule. + # @param speculative {@code true} if the current index in {@code input} is + # one character before the predicate's location. + # + # @return {@code true} if the specified predicate evaluates to + # {@code true}. + #/ + def evaluatePredicate(self, input:InputStream, ruleIndex:int, predIndex:int, speculative:bool): + # assume true if no recognizer was provided + if self.recog is None: + return True + + if not speculative: + return self.recog.sempred(None, ruleIndex, predIndex) + + savedcolumn = self.column + savedLine = self.line + index = input.index + marker = input.mark() + try: + self.consume(input) + return self.recog.sempred(None, ruleIndex, predIndex) + finally: + self.column = savedcolumn + self.line = savedLine + input.seek(index) + input.release(marker) + + def captureSimState(self, settings:SimState, input:InputStream, dfaState:DFAState): + settings.index = input.index + settings.line = self.line + settings.column = self.column + settings.dfaState = dfaState + + def addDFAEdge(self, from_:DFAState, tk:int, to:DFAState=None, cfgs:ATNConfigSet=None) -> DFAState: + + if to is None and cfgs is not None: + # leading to this call, ATNConfigSet.hasSemanticContext is used as a + # marker indicating dynamic predicate evaluation makes this edge + # dependent on the specific input sequence, so the static edge in the + # DFA should be omitted. The target DFAState is still created since + # execATN has the ability to resynchronize with the DFA state cache + # following the predicate evaluation step. + # + # TJP notes: next time through the DFA, we see a pred again and eval. + # If that gets us to a previously created (but dangling) DFA + # state, we can continue in pure DFA mode from there. + #/ + suppressEdge = cfgs.hasSemanticContext + cfgs.hasSemanticContext = False + + to = self.addDFAState(cfgs) + + if suppressEdge: + return to + + # add the edge + if tk < self.MIN_DFA_EDGE or tk > self.MAX_DFA_EDGE: + # Only track edges within the DFA bounds + return to + + if LexerATNSimulator.debug: + print("EDGE " + str(from_) + " -> " + str(to) + " upon "+ chr(tk)) + + if from_.edges is None: + # make room for tokens 1..n and -1 masquerading as index 0 + from_.edges = [ None ] * (self.MAX_DFA_EDGE - self.MIN_DFA_EDGE + 1) + + from_.edges[tk - self.MIN_DFA_EDGE] = to # connect + + return to + + + # Add a new DFA state if there isn't one with this set of + # configurations already. This method also detects the first + # configuration containing an ATN rule stop state. Later, when + # traversing the DFA, we will know which rule to accept. + def addDFAState(self, configs:ATNConfigSet) -> DFAState: + + proposed = DFAState(configs=configs) + firstConfigWithRuleStopState = next((cfg for cfg in configs if isinstance(cfg.state, RuleStopState)), None) + + if firstConfigWithRuleStopState is not None: + proposed.isAcceptState = True + proposed.lexerActionExecutor = firstConfigWithRuleStopState.lexerActionExecutor + proposed.prediction = self.atn.ruleToTokenType[firstConfigWithRuleStopState.state.ruleIndex] + + dfa = self.decisionToDFA[self.mode] + existing = dfa.states.get(proposed, None) + if existing is not None: + return existing + + newState = proposed + + newState.stateNumber = len(dfa.states) + configs.setReadonly(True) + newState.configs = configs + dfa.states[newState] = newState + return newState + + def getDFA(self, mode:int): + return self.decisionToDFA[mode] + + # Get the text matched so far for the current token. + def getText(self, input:InputStream): + # index is first lookahead char, don't include. + return input.getText(self.startIndex, input.index-1) + + def consume(self, input:InputStream): + curChar = input.LA(1) + if curChar==ord('\n'): + self.line += 1 + self.column = 0 + else: + self.column += 1 + input.consume() + + def getTokenName(self, t:int): + if t==-1: + return "EOF" + else: + return "'" + chr(t) + "'" + + +LexerATNSimulator.ERROR = DFAState(0x7FFFFFFF, ATNConfigSet()) + +del Lexer diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/atn/LexerAction.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/atn/LexerAction.py new file mode 100644 index 0000000000000000000000000000000000000000..0fa7a895f31cea4415b71def30ca1ec90167f1b3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/atn/LexerAction.py @@ -0,0 +1,298 @@ +# +# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. +# Use of this file is governed by the BSD 3-clause license that +# can be found in the LICENSE.txt file in the project root. + # + +from enum import IntEnum + +# need forward declaration +Lexer = None + + +class LexerActionType(IntEnum): + + CHANNEL = 0 #The type of a {@link LexerChannelAction} action. + CUSTOM = 1 #The type of a {@link LexerCustomAction} action. + MODE = 2 #The type of a {@link LexerModeAction} action. + MORE = 3 #The type of a {@link LexerMoreAction} action. + POP_MODE = 4 #The type of a {@link LexerPopModeAction} action. + PUSH_MODE = 5 #The type of a {@link LexerPushModeAction} action. + SKIP = 6 #The type of a {@link LexerSkipAction} action. + TYPE = 7 #The type of a {@link LexerTypeAction} action. + +class LexerAction(object): + __slots__ = ('actionType', 'isPositionDependent') + + def __init__(self, action:LexerActionType): + self.actionType = action + self.isPositionDependent = False + + def __hash__(self): + return hash(self.actionType) + + def __eq__(self, other): + return self is other + + +# +# Implements the {@code skip} lexer action by calling {@link Lexer#skip}. +# +#

The {@code skip} command does not have any parameters, so this action is +# implemented as a singleton instance exposed by {@link #INSTANCE}.

+class LexerSkipAction(LexerAction): + + # Provides a singleton instance of this parameterless lexer action. + INSTANCE = None + + def __init__(self): + super().__init__(LexerActionType.SKIP) + + def execute(self, lexer:Lexer): + lexer.skip() + + def __str__(self): + return "skip" + +LexerSkipAction.INSTANCE = LexerSkipAction() + +# Implements the {@code type} lexer action by calling {@link Lexer#setType} +# with the assigned type. +class LexerTypeAction(LexerAction): + __slots__ = 'type' + + def __init__(self, type:int): + super().__init__(LexerActionType.TYPE) + self.type = type + + def execute(self, lexer:Lexer): + lexer.type = self.type + + def __hash__(self): + return hash((self.actionType, self.type)) + + def __eq__(self, other): + if self is other: + return True + elif not isinstance(other, LexerTypeAction): + return False + else: + return self.type == other.type + + def __str__(self): + return "type(" + str(self.type) + ")" + + +# Implements the {@code pushMode} lexer action by calling +# {@link Lexer#pushMode} with the assigned mode. +class LexerPushModeAction(LexerAction): + __slots__ = 'mode' + + def __init__(self, mode:int): + super().__init__(LexerActionType.PUSH_MODE) + self.mode = mode + + #

This action is implemented by calling {@link Lexer#pushMode} with the + # value provided by {@link #getMode}.

+ def execute(self, lexer:Lexer): + lexer.pushMode(self.mode) + + def __hash__(self): + return hash((self.actionType, self.mode)) + + def __eq__(self, other): + if self is other: + return True + elif not isinstance(other, LexerPushModeAction): + return False + else: + return self.mode == other.mode + + def __str__(self): + return "pushMode(" + str(self.mode) + ")" + + +# Implements the {@code popMode} lexer action by calling {@link Lexer#popMode}. +# +#

The {@code popMode} command does not have any parameters, so this action is +# implemented as a singleton instance exposed by {@link #INSTANCE}.

+class LexerPopModeAction(LexerAction): + + INSTANCE = None + + def __init__(self): + super().__init__(LexerActionType.POP_MODE) + + #

This action is implemented by calling {@link Lexer#popMode}.

+ def execute(self, lexer:Lexer): + lexer.popMode() + + def __str__(self): + return "popMode" + +LexerPopModeAction.INSTANCE = LexerPopModeAction() + +# Implements the {@code more} lexer action by calling {@link Lexer#more}. +# +#

The {@code more} command does not have any parameters, so this action is +# implemented as a singleton instance exposed by {@link #INSTANCE}.

+class LexerMoreAction(LexerAction): + + INSTANCE = None + + def __init__(self): + super().__init__(LexerActionType.MORE) + + #

This action is implemented by calling {@link Lexer#popMode}.

+ def execute(self, lexer:Lexer): + lexer.more() + + def __str__(self): + return "more" + +LexerMoreAction.INSTANCE = LexerMoreAction() + +# Implements the {@code mode} lexer action by calling {@link Lexer#mode} with +# the assigned mode. +class LexerModeAction(LexerAction): + __slots__ = 'mode' + + def __init__(self, mode:int): + super().__init__(LexerActionType.MODE) + self.mode = mode + + #

This action is implemented by calling {@link Lexer#mode} with the + # value provided by {@link #getMode}.

+ def execute(self, lexer:Lexer): + lexer.mode(self.mode) + + def __hash__(self): + return hash((self.actionType, self.mode)) + + def __eq__(self, other): + if self is other: + return True + elif not isinstance(other, LexerModeAction): + return False + else: + return self.mode == other.mode + + def __str__(self): + return "mode(" + str(self.mode) + ")" + +# Executes a custom lexer action by calling {@link Recognizer#action} with the +# rule and action indexes assigned to the custom action. The implementation of +# a custom action is added to the generated code for the lexer in an override +# of {@link Recognizer#action} when the grammar is compiled. +# +#

This class may represent embedded actions created with the {...} +# syntax in ANTLR 4, as well as actions created for lexer commands where the +# command argument could not be evaluated when the grammar was compiled.

+ +class LexerCustomAction(LexerAction): + __slots__ = ('ruleIndex', 'actionIndex') + + # Constructs a custom lexer action with the specified rule and action + # indexes. + # + # @param ruleIndex The rule index to use for calls to + # {@link Recognizer#action}. + # @param actionIndex The action index to use for calls to + # {@link Recognizer#action}. + #/ + def __init__(self, ruleIndex:int, actionIndex:int): + super().__init__(LexerActionType.CUSTOM) + self.ruleIndex = ruleIndex + self.actionIndex = actionIndex + self.isPositionDependent = True + + #

Custom actions are implemented by calling {@link Lexer#action} with the + # appropriate rule and action indexes.

+ def execute(self, lexer:Lexer): + lexer.action(None, self.ruleIndex, self.actionIndex) + + def __hash__(self): + return hash((self.actionType, self.ruleIndex, self.actionIndex)) + + def __eq__(self, other): + if self is other: + return True + elif not isinstance(other, LexerCustomAction): + return False + else: + return self.ruleIndex == other.ruleIndex and self.actionIndex == other.actionIndex + +# Implements the {@code channel} lexer action by calling +# {@link Lexer#setChannel} with the assigned channel. +class LexerChannelAction(LexerAction): + __slots__ = 'channel' + + # Constructs a new {@code channel} action with the specified channel value. + # @param channel The channel value to pass to {@link Lexer#setChannel}. + def __init__(self, channel:int): + super().__init__(LexerActionType.CHANNEL) + self.channel = channel + + #

This action is implemented by calling {@link Lexer#setChannel} with the + # value provided by {@link #getChannel}.

+ def execute(self, lexer:Lexer): + lexer._channel = self.channel + + def __hash__(self): + return hash((self.actionType, self.channel)) + + def __eq__(self, other): + if self is other: + return True + elif not isinstance(other, LexerChannelAction): + return False + else: + return self.channel == other.channel + + def __str__(self): + return "channel(" + str(self.channel) + ")" + +# This implementation of {@link LexerAction} is used for tracking input offsets +# for position-dependent actions within a {@link LexerActionExecutor}. +# +#

This action is not serialized as part of the ATN, and is only required for +# position-dependent lexer actions which appear at a location other than the +# end of a rule. For more information about DFA optimizations employed for +# lexer actions, see {@link LexerActionExecutor#append} and +# {@link LexerActionExecutor#fixOffsetBeforeMatch}.

+class LexerIndexedCustomAction(LexerAction): + __slots__ = ('offset', 'action') + + # Constructs a new indexed custom action by associating a character offset + # with a {@link LexerAction}. + # + #

Note: This class is only required for lexer actions for which + # {@link LexerAction#isPositionDependent} returns {@code true}.

+ # + # @param offset The offset into the input {@link CharStream}, relative to + # the token start index, at which the specified lexer action should be + # executed. + # @param action The lexer action to execute at a particular offset in the + # input {@link CharStream}. + def __init__(self, offset:int, action:LexerAction): + super().__init__(action.actionType) + self.offset = offset + self.action = action + self.isPositionDependent = True + + #

This method calls {@link #execute} on the result of {@link #getAction} + # using the provided {@code lexer}.

+ def execute(self, lexer:Lexer): + # assume the input stream position was properly set by the calling code + self.action.execute(lexer) + + def __hash__(self): + return hash((self.actionType, self.offset, self.action)) + + def __eq__(self, other): + if self is other: + return True + elif not isinstance(other, LexerIndexedCustomAction): + return False + else: + return self.offset == other.offset and self.action == other.action diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/atn/LexerActionExecutor.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/atn/LexerActionExecutor.py new file mode 100644 index 0000000000000000000000000000000000000000..5c6462c3a28f4ccbcb0a65dcde96f497dd392416 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/atn/LexerActionExecutor.py @@ -0,0 +1,143 @@ +# +# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. +# Use of this file is governed by the BSD 3-clause license that +# can be found in the LICENSE.txt file in the project root. +#/ + +# Represents an executor for a sequence of lexer actions which traversed during +# the matching operation of a lexer rule (token). +# +#

The executor tracks position information for position-dependent lexer actions +# efficiently, ensuring that actions appearing only at the end of the rule do +# not cause bloating of the {@link DFA} created for the lexer.

+ + +from antlr4.InputStream import InputStream +from antlr4.atn.LexerAction import LexerAction, LexerIndexedCustomAction + +# need a forward declaration +Lexer = None +LexerActionExecutor = None + +class LexerActionExecutor(object): + __slots__ = ('lexerActions', 'hashCode') + + def __init__(self, lexerActions:list=list()): + self.lexerActions = lexerActions + # Caches the result of {@link #hashCode} since the hash code is an element + # of the performance-critical {@link LexerATNConfig#hashCode} operation. + self.hashCode = hash("".join([str(la) for la in lexerActions])) + + + # Creates a {@link LexerActionExecutor} which executes the actions for + # the input {@code lexerActionExecutor} followed by a specified + # {@code lexerAction}. + # + # @param lexerActionExecutor The executor for actions already traversed by + # the lexer while matching a token within a particular + # {@link LexerATNConfig}. If this is {@code null}, the method behaves as + # though it were an empty executor. + # @param lexerAction The lexer action to execute after the actions + # specified in {@code lexerActionExecutor}. + # + # @return A {@link LexerActionExecutor} for executing the combine actions + # of {@code lexerActionExecutor} and {@code lexerAction}. + @staticmethod + def append(lexerActionExecutor:LexerActionExecutor , lexerAction:LexerAction ): + if lexerActionExecutor is None: + return LexerActionExecutor([ lexerAction ]) + + lexerActions = lexerActionExecutor.lexerActions + [ lexerAction ] + return LexerActionExecutor(lexerActions) + + # Creates a {@link LexerActionExecutor} which encodes the current offset + # for position-dependent lexer actions. + # + #

Normally, when the executor encounters lexer actions where + # {@link LexerAction#isPositionDependent} returns {@code true}, it calls + # {@link IntStream#seek} on the input {@link CharStream} to set the input + # position to the end of the current token. This behavior provides + # for efficient DFA representation of lexer actions which appear at the end + # of a lexer rule, even when the lexer rule matches a variable number of + # characters.

+ # + #

Prior to traversing a match transition in the ATN, the current offset + # from the token start index is assigned to all position-dependent lexer + # actions which have not already been assigned a fixed offset. By storing + # the offsets relative to the token start index, the DFA representation of + # lexer actions which appear in the middle of tokens remains efficient due + # to sharing among tokens of the same length, regardless of their absolute + # position in the input stream.

+ # + #

If the current executor already has offsets assigned to all + # position-dependent lexer actions, the method returns {@code this}.

+ # + # @param offset The current offset to assign to all position-dependent + # lexer actions which do not already have offsets assigned. + # + # @return A {@link LexerActionExecutor} which stores input stream offsets + # for all position-dependent lexer actions. + #/ + def fixOffsetBeforeMatch(self, offset:int): + updatedLexerActions = None + for i in range(0, len(self.lexerActions)): + if self.lexerActions[i].isPositionDependent and not isinstance(self.lexerActions[i], LexerIndexedCustomAction): + if updatedLexerActions is None: + updatedLexerActions = [ la for la in self.lexerActions ] + updatedLexerActions[i] = LexerIndexedCustomAction(offset, self.lexerActions[i]) + + if updatedLexerActions is None: + return self + else: + return LexerActionExecutor(updatedLexerActions) + + + # Execute the actions encapsulated by this executor within the context of a + # particular {@link Lexer}. + # + #

This method calls {@link IntStream#seek} to set the position of the + # {@code input} {@link CharStream} prior to calling + # {@link LexerAction#execute} on a position-dependent action. Before the + # method returns, the input position will be restored to the same position + # it was in when the method was invoked.

+ # + # @param lexer The lexer instance. + # @param input The input stream which is the source for the current token. + # When this method is called, the current {@link IntStream#index} for + # {@code input} should be the start of the following token, i.e. 1 + # character past the end of the current token. + # @param startIndex The token start index. This value may be passed to + # {@link IntStream#seek} to set the {@code input} position to the beginning + # of the token. + #/ + def execute(self, lexer:Lexer, input:InputStream, startIndex:int): + requiresSeek = False + stopIndex = input.index + try: + for lexerAction in self.lexerActions: + if isinstance(lexerAction, LexerIndexedCustomAction): + offset = lexerAction.offset + input.seek(startIndex + offset) + lexerAction = lexerAction.action + requiresSeek = (startIndex + offset) != stopIndex + elif lexerAction.isPositionDependent: + input.seek(stopIndex) + requiresSeek = False + lexerAction.execute(lexer) + finally: + if requiresSeek: + input.seek(stopIndex) + + def __hash__(self): + return self.hashCode + + def __eq__(self, other): + if self is other: + return True + elif not isinstance(other, LexerActionExecutor): + return False + else: + return self.hashCode == other.hashCode \ + and self.lexerActions == other.lexerActions + +del Lexer diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/atn/ParserATNSimulator.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/atn/ParserATNSimulator.py new file mode 100644 index 0000000000000000000000000000000000000000..d1fb3d7ed8bab47fb851d85da88d20dc39715627 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/atn/ParserATNSimulator.py @@ -0,0 +1,1649 @@ +# +# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. +# Use of this file is governed by the BSD 3-clause license that +# can be found in the LICENSE.txt file in the project root. +# + +# +# The embodiment of the adaptive LL(*), ALL(*), parsing strategy. +# +#

+# The basic complexity of the adaptive strategy makes it harder to understand. +# We begin with ATN simulation to build paths in a DFA. Subsequent prediction +# requests go through the DFA first. If they reach a state without an edge for +# the current symbol, the algorithm fails over to the ATN simulation to +# complete the DFA path for the current input (until it finds a conflict state +# or uniquely predicting state).

+# +#

+# All of that is done without using the outer context because we want to create +# a DFA that is not dependent upon the rule invocation stack when we do a +# prediction. One DFA works in all contexts. We avoid using context not +# necessarily because it's slower, although it can be, but because of the DFA +# caching problem. The closure routine only considers the rule invocation stack +# created during prediction beginning in the decision rule. For example, if +# prediction occurs without invoking another rule's ATN, there are no context +# stacks in the configurations. When lack of context leads to a conflict, we +# don't know if it's an ambiguity or a weakness in the strong LL(*) parsing +# strategy (versus full LL(*)).

+# +#

+# When SLL yields a configuration set with conflict, we rewind the input and +# retry the ATN simulation, this time using full outer context without adding +# to the DFA. Configuration context stacks will be the full invocation stacks +# from the start rule. If we get a conflict using full context, then we can +# definitively say we have a true ambiguity for that input sequence. If we +# don't get a conflict, it implies that the decision is sensitive to the outer +# context. (It is not context-sensitive in the sense of context-sensitive +# grammars.)

+# +#

+# The next time we reach this DFA state with an SLL conflict, through DFA +# simulation, we will again retry the ATN simulation using full context mode. +# This is slow because we can't save the results and have to "interpret" the +# ATN each time we get that input.

+# +#

+# CACHING FULL CONTEXT PREDICTIONS

+# +#

+# We could cache results from full context to predicted alternative easily and +# that saves a lot of time but doesn't work in presence of predicates. The set +# of visible predicates from the ATN start state changes depending on the +# context, because closure can fall off the end of a rule. I tried to cache +# tuples (stack context, semantic context, predicted alt) but it was slower +# than interpreting and much more complicated. Also required a huge amount of +# memory. The goal is not to create the world's fastest parser anyway. I'd like +# to keep this algorithm simple. By launching multiple threads, we can improve +# the speed of parsing across a large number of files.

+# +#

+# There is no strict ordering between the amount of input used by SLL vs LL, +# which makes it really hard to build a cache for full context. Let's say that +# we have input A B C that leads to an SLL conflict with full context X. That +# implies that using X we might only use A B but we could also use A B C D to +# resolve conflict. Input A B C D could predict alternative 1 in one position +# in the input and A B C E could predict alternative 2 in another position in +# input. The conflicting SLL configurations could still be non-unique in the +# full context prediction, which would lead us to requiring more input than the +# original A B C. To make a prediction cache work, we have to track the exact +# input used during the previous prediction. That amounts to a cache that maps +# X to a specific DFA for that context.

+# +#

+# Something should be done for left-recursive expression predictions. They are +# likely LL(1) + pred eval. Easier to do the whole SLL unless error and retry +# with full LL thing Sam does.

+# +#

+# AVOIDING FULL CONTEXT PREDICTION

+# +#

+# We avoid doing full context retry when the outer context is empty, we did not +# dip into the outer context by falling off the end of the decision state rule, +# or when we force SLL mode.

+# +#

+# As an example of the not dip into outer context case, consider as super +# constructor calls versus function calls. One grammar might look like +# this:

+# +#
+# ctorBody
+#   : '{' superCall? stat* '}'
+#   ;
+# 
+# +#

+# Or, you might see something like

+# +#
+# stat
+#   : superCall ';'
+#   | expression ';'
+#   | ...
+#   ;
+# 
+# +#

+# In both cases I believe that no closure operations will dip into the outer +# context. In the first case ctorBody in the worst case will stop at the '}'. +# In the 2nd case it should stop at the ';'. Both cases should stay within the +# entry rule and not dip into the outer context.

+# +#

+# PREDICATES

+# +#

+# Predicates are always evaluated if present in either SLL or LL both. SLL and +# LL simulation deals with predicates differently. SLL collects predicates as +# it performs closure operations like ANTLR v3 did. It delays predicate +# evaluation until it reaches and accept state. This allows us to cache the SLL +# ATN simulation whereas, if we had evaluated predicates on-the-fly during +# closure, the DFA state configuration sets would be different and we couldn't +# build up a suitable DFA.

+# +#

+# When building a DFA accept state during ATN simulation, we evaluate any +# predicates and return the sole semantically valid alternative. If there is +# more than 1 alternative, we report an ambiguity. If there are 0 alternatives, +# we throw an exception. Alternatives without predicates act like they have +# true predicates. The simple way to think about it is to strip away all +# alternatives with false predicates and choose the minimum alternative that +# remains.

+# +#

+# When we start in the DFA and reach an accept state that's predicated, we test +# those and return the minimum semantically viable alternative. If no +# alternatives are viable, we throw an exception.

+# +#

+# During full LL ATN simulation, closure always evaluates predicates and +# on-the-fly. This is crucial to reducing the configuration set size during +# closure. It hits a landmine when parsing with the Java grammar, for example, +# without this on-the-fly evaluation.

+# +#

+# SHARING DFA

+# +#

+# All instances of the same parser share the same decision DFAs through a +# static field. Each instance gets its own ATN simulator but they share the +# same {@link #decisionToDFA} field. They also share a +# {@link PredictionContextCache} object that makes sure that all +# {@link PredictionContext} objects are shared among the DFA states. This makes +# a big size difference.

+# +#

+# THREAD SAFETY

+# +#

+# The {@link ParserATNSimulator} locks on the {@link #decisionToDFA} field when +# it adds a new DFA object to that array. {@link #addDFAEdge} +# locks on the DFA for the current decision when setting the +# {@link DFAState#edges} field. {@link #addDFAState} locks on +# the DFA for the current decision when looking up a DFA state to see if it +# already exists. We must make sure that all requests to add DFA states that +# are equivalent result in the same shared DFA object. This is because lots of +# threads will be trying to update the DFA at once. The +# {@link #addDFAState} method also locks inside the DFA lock +# but this time on the shared context cache when it rebuilds the +# configurations' {@link PredictionContext} objects using cached +# subgraphs/nodes. No other locking occurs, even during DFA simulation. This is +# safe as long as we can guarantee that all threads referencing +# {@code s.edge[t]} get the same physical target {@link DFAState}, or +# {@code null}. Once into the DFA, the DFA simulation does not reference the +# {@link DFA#states} map. It follows the {@link DFAState#edges} field to new +# targets. The DFA simulator will either find {@link DFAState#edges} to be +# {@code null}, to be non-{@code null} and {@code dfa.edges[t]} null, or +# {@code dfa.edges[t]} to be non-null. The +# {@link #addDFAEdge} method could be racing to set the field +# but in either case the DFA simulator works; if {@code null}, and requests ATN +# simulation. It could also race trying to get {@code dfa.edges[t]}, but either +# way it will work because it's not doing a test and set operation.

+# +#

+# Starting with SLL then failing to combined SLL/LL (Two-Stage +# Parsing)

+# +#

+# Sam pointed out that if SLL does not give a syntax error, then there is no +# point in doing full LL, which is slower. We only have to try LL if we get a +# syntax error. For maximum speed, Sam starts the parser set to pure SLL +# mode with the {@link BailErrorStrategy}:

+# +#
+# parser.{@link Parser#getInterpreter() getInterpreter()}.{@link #setPredictionMode setPredictionMode}{@code (}{@link PredictionMode#SLL}{@code )};
+# parser.{@link Parser#setErrorHandler setErrorHandler}(new {@link BailErrorStrategy}());
+# 
+# +#

+# If it does not get a syntax error, then we're done. If it does get a syntax +# error, we need to retry with the combined SLL/LL strategy.

+# +#

+# The reason this works is as follows. If there are no SLL conflicts, then the +# grammar is SLL (at least for that input set). If there is an SLL conflict, +# the full LL analysis must yield a set of viable alternatives which is a +# subset of the alternatives reported by SLL. If the LL set is a singleton, +# then the grammar is LL but not SLL. If the LL set is the same size as the SLL +# set, the decision is SLL. If the LL set has size > 1, then that decision +# is truly ambiguous on the current input. If the LL set is smaller, then the +# SLL conflict resolution might choose an alternative that the full LL would +# rule out as a possibility based upon better context information. If that's +# the case, then the SLL parse will definitely get an error because the full LL +# analysis says it's not viable. If SLL conflict resolution chooses an +# alternative within the LL set, them both SLL and LL would choose the same +# alternative because they both choose the minimum of multiple conflicting +# alternatives.

+# +#

+# Let's say we have a set of SLL conflicting alternatives {@code {1, 2, 3}} and +# a smaller LL set called s. If s is {@code {2, 3}}, then SLL +# parsing will get an error because SLL will pursue alternative 1. If +# s is {@code {1, 2}} or {@code {1, 3}} then both SLL and LL will +# choose the same alternative because alternative one is the minimum of either +# set. If s is {@code {2}} or {@code {3}} then SLL will get a syntax +# error. If s is {@code {1}} then SLL will succeed.

+# +#

+# Of course, if the input is invalid, then we will get an error for sure in +# both SLL and LL parsing. Erroneous input will therefore require 2 passes over +# the input.

+# +import sys +from antlr4 import DFA +from antlr4.PredictionContext import PredictionContextCache, PredictionContext, SingletonPredictionContext, \ + PredictionContextFromRuleContext +from antlr4.BufferedTokenStream import TokenStream +from antlr4.Parser import Parser +from antlr4.ParserRuleContext import ParserRuleContext +from antlr4.RuleContext import RuleContext +from antlr4.Token import Token +from antlr4.Utils import str_list +from antlr4.atn.ATN import ATN +from antlr4.atn.ATNConfig import ATNConfig +from antlr4.atn.ATNConfigSet import ATNConfigSet +from antlr4.atn.ATNSimulator import ATNSimulator +from antlr4.atn.ATNState import StarLoopEntryState, DecisionState, RuleStopState, ATNState +from antlr4.atn.PredictionMode import PredictionMode +from antlr4.atn.SemanticContext import SemanticContext, AND, andContext, orContext +from antlr4.atn.Transition import Transition, RuleTransition, ActionTransition, PrecedencePredicateTransition, \ + PredicateTransition, AtomTransition, SetTransition, NotSetTransition +from antlr4.dfa.DFAState import DFAState, PredPrediction +from antlr4.error.Errors import NoViableAltException + + +class ParserATNSimulator(ATNSimulator): + __slots__ = ( + 'parser', 'decisionToDFA', 'predictionMode', '_input', '_startIndex', + '_outerContext', '_dfa', 'mergeCache' + ) + + debug = False + debug_list_atn_decisions = False + dfa_debug = False + retry_debug = False + + + def __init__(self, parser:Parser, atn:ATN, decisionToDFA:list, sharedContextCache:PredictionContextCache): + super().__init__(atn, sharedContextCache) + self.parser = parser + self.decisionToDFA = decisionToDFA + # SLL, LL, or LL + exact ambig detection?# + self.predictionMode = PredictionMode.LL + # LAME globals to avoid parameters!!!!! I need these down deep in predTransition + self._input = None + self._startIndex = 0 + self._outerContext = None + self._dfa = None + # Each prediction operation uses a cache for merge of prediction contexts. + # Don't keep around as it wastes huge amounts of memory. DoubleKeyMap + # isn't synchronized but we're ok since two threads shouldn't reuse same + # parser/atnsim object because it can only handle one input at a time. + # This maps graphs a and b to merged result c. (a,b)→c. We can avoid + # the merge if we ever see a and b again. Note that (b,a)→c should + # also be examined during cache lookup. + # + self.mergeCache = None + + + def reset(self): + pass + + def adaptivePredict(self, input:TokenStream, decision:int, outerContext:ParserRuleContext): + if ParserATNSimulator.debug or ParserATNSimulator.debug_list_atn_decisions: + print("adaptivePredict decision " + str(decision) + + " exec LA(1)==" + self.getLookaheadName(input) + + " line " + str(input.LT(1).line) + ":" + + str(input.LT(1).column)) + self._input = input + self._startIndex = input.index + self._outerContext = outerContext + + dfa = self.decisionToDFA[decision] + self._dfa = dfa + m = input.mark() + index = input.index + + # Now we are certain to have a specific decision's DFA + # But, do we still need an initial state? + try: + if dfa.precedenceDfa: + # the start state for a precedence DFA depends on the current + # parser precedence, and is provided by a DFA method. + s0 = dfa.getPrecedenceStartState(self.parser.getPrecedence()) + else: + # the start state for a "regular" DFA is just s0 + s0 = dfa.s0 + + if s0 is None: + if outerContext is None: + outerContext = ParserRuleContext.EMPTY + if ParserATNSimulator.debug or ParserATNSimulator.debug_list_atn_decisions: + print("predictATN decision " + str(dfa.decision) + + " exec LA(1)==" + self.getLookaheadName(input) + + ", outerContext=" + outerContext.toString(self.parser.literalNames, None)) + + fullCtx = False + s0_closure = self.computeStartState(dfa.atnStartState, ParserRuleContext.EMPTY, fullCtx) + + if dfa.precedenceDfa: + # If this is a precedence DFA, we use applyPrecedenceFilter + # to convert the computed start state to a precedence start + # state. We then use DFA.setPrecedenceStartState to set the + # appropriate start state for the precedence level rather + # than simply setting DFA.s0. + # + dfa.s0.configs = s0_closure # not used for prediction but useful to know start configs anyway + s0_closure = self.applyPrecedenceFilter(s0_closure) + s0 = self.addDFAState(dfa, DFAState(configs=s0_closure)) + dfa.setPrecedenceStartState(self.parser.getPrecedence(), s0) + else: + s0 = self.addDFAState(dfa, DFAState(configs=s0_closure)) + dfa.s0 = s0 + + alt = self.execATN(dfa, s0, input, index, outerContext) + if ParserATNSimulator.debug: + print("DFA after predictATN: " + dfa.toString(self.parser.literalNames)) + return alt + finally: + self._dfa = None + self.mergeCache = None # wack cache after each prediction + input.seek(index) + input.release(m) + + # Performs ATN simulation to compute a predicted alternative based + # upon the remaining input, but also updates the DFA cache to avoid + # having to traverse the ATN again for the same input sequence. + + # There are some key conditions we're looking for after computing a new + # set of ATN configs (proposed DFA state): + # if the set is empty, there is no viable alternative for current symbol + # does the state uniquely predict an alternative? + # does the state have a conflict that would prevent us from + # putting it on the work list? + + # We also have some key operations to do: + # add an edge from previous DFA state to potentially new DFA state, D, + # upon current symbol but only if adding to work list, which means in all + # cases except no viable alternative (and possibly non-greedy decisions?) + # collecting predicates and adding semantic context to DFA accept states + # adding rule context to context-sensitive DFA accept states + # consuming an input symbol + # reporting a conflict + # reporting an ambiguity + # reporting a context sensitivity + # reporting insufficient predicates + + # cover these cases: + # dead end + # single alt + # single alt + preds + # conflict + # conflict + preds + # + def execATN(self, dfa:DFA, s0:DFAState, input:TokenStream, startIndex:int, outerContext:ParserRuleContext ): + if ParserATNSimulator.debug or ParserATNSimulator.debug_list_atn_decisions: + print("execATN decision " + str(dfa.decision) + + " exec LA(1)==" + self.getLookaheadName(input) + + " line " + str(input.LT(1).line) + ":" + str(input.LT(1).column)) + + previousD = s0 + + if ParserATNSimulator.debug: + print("s0 = " + str(s0)) + + t = input.LA(1) + + while True: # while more work + D = self.getExistingTargetState(previousD, t) + if D is None: + D = self.computeTargetState(dfa, previousD, t) + if D is self.ERROR: + # if any configs in previous dipped into outer context, that + # means that input up to t actually finished entry rule + # at least for SLL decision. Full LL doesn't dip into outer + # so don't need special case. + # We will get an error no matter what so delay until after + # decision; better error message. Also, no reachable target + # ATN states in SLL implies LL will also get nowhere. + # If conflict in states that dip out, choose min since we + # will get error no matter what. + e = self.noViableAlt(input, outerContext, previousD.configs, startIndex) + input.seek(startIndex) + alt = self.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previousD.configs, outerContext) + if alt!=ATN.INVALID_ALT_NUMBER: + return alt + raise e + + if D.requiresFullContext and self.predictionMode != PredictionMode.SLL: + # IF PREDS, MIGHT RESOLVE TO SINGLE ALT => SLL (or syntax error) + conflictingAlts = D.configs.conflictingAlts + if D.predicates is not None: + if ParserATNSimulator.debug: + print("DFA state has preds in DFA sim LL failover") + conflictIndex = input.index + if conflictIndex != startIndex: + input.seek(startIndex) + + conflictingAlts = self.evalSemanticContext(D.predicates, outerContext, True) + if len(conflictingAlts)==1: + if ParserATNSimulator.debug: + print("Full LL avoided") + return min(conflictingAlts) + + if conflictIndex != startIndex: + # restore the index so reporting the fallback to full + # context occurs with the index at the correct spot + input.seek(conflictIndex) + + if ParserATNSimulator.dfa_debug: + print("ctx sensitive state " + str(outerContext) +" in " + str(D)) + fullCtx = True + s0_closure = self.computeStartState(dfa.atnStartState, outerContext, fullCtx) + self.reportAttemptingFullContext(dfa, conflictingAlts, D.configs, startIndex, input.index) + alt = self.execATNWithFullContext(dfa, D, s0_closure, input, startIndex, outerContext) + return alt + + if D.isAcceptState: + if D.predicates is None: + return D.prediction + + stopIndex = input.index + input.seek(startIndex) + alts = self.evalSemanticContext(D.predicates, outerContext, True) + if len(alts)==0: + raise self.noViableAlt(input, outerContext, D.configs, startIndex) + elif len(alts)==1: + return min(alts) + else: + # report ambiguity after predicate evaluation to make sure the correct + # set of ambig alts is reported. + self.reportAmbiguity(dfa, D, startIndex, stopIndex, False, alts, D.configs) + return min(alts) + + previousD = D + + if t != Token.EOF: + input.consume() + t = input.LA(1) + + # + # Get an existing target state for an edge in the DFA. If the target state + # for the edge has not yet been computed or is otherwise not available, + # this method returns {@code null}. + # + # @param previousD The current DFA state + # @param t The next input symbol + # @return The existing target DFA state for the given input symbol + # {@code t}, or {@code null} if the target state for this edge is not + # already cached + # + def getExistingTargetState(self, previousD:DFAState, t:int): + edges = previousD.edges + if edges is None or t + 1 < 0 or t + 1 >= len(edges): + return None + else: + return edges[t + 1] + + # + # Compute a target state for an edge in the DFA, and attempt to add the + # computed state and corresponding edge to the DFA. + # + # @param dfa The DFA + # @param previousD The current DFA state + # @param t The next input symbol + # + # @return The computed target DFA state for the given input symbol + # {@code t}. If {@code t} does not lead to a valid DFA state, this method + # returns {@link #ERROR}. + # + def computeTargetState(self, dfa:DFA, previousD:DFAState, t:int): + reach = self.computeReachSet(previousD.configs, t, False) + if reach is None: + self.addDFAEdge(dfa, previousD, t, self.ERROR) + return self.ERROR + + # create new target state; we'll add to DFA after it's complete + D = DFAState(configs=reach) + + predictedAlt = self.getUniqueAlt(reach) + + if ParserATNSimulator.debug: + altSubSets = PredictionMode.getConflictingAltSubsets(reach) + print("SLL altSubSets=" + str(altSubSets) + ", configs=" + str(reach) + + ", predict=" + str(predictedAlt) + ", allSubsetsConflict=" + + str(PredictionMode.allSubsetsConflict(altSubSets)) + ", conflictingAlts=" + + str(self.getConflictingAlts(reach))) + + if predictedAlt!=ATN.INVALID_ALT_NUMBER: + # NO CONFLICT, UNIQUELY PREDICTED ALT + D.isAcceptState = True + D.configs.uniqueAlt = predictedAlt + D.prediction = predictedAlt + elif PredictionMode.hasSLLConflictTerminatingPrediction(self.predictionMode, reach): + # MORE THAN ONE VIABLE ALTERNATIVE + D.configs.conflictingAlts = self.getConflictingAlts(reach) + D.requiresFullContext = True + # in SLL-only mode, we will stop at this state and return the minimum alt + D.isAcceptState = True + D.prediction = min(D.configs.conflictingAlts) + + if D.isAcceptState and D.configs.hasSemanticContext: + self.predicateDFAState(D, self.atn.getDecisionState(dfa.decision)) + if D.predicates is not None: + D.prediction = ATN.INVALID_ALT_NUMBER + + # all adds to dfa are done after we've created full D state + D = self.addDFAEdge(dfa, previousD, t, D) + return D + + def predicateDFAState(self, dfaState:DFAState, decisionState:DecisionState): + # We need to test all predicates, even in DFA states that + # uniquely predict alternative. + nalts = len(decisionState.transitions) + # Update DFA so reach becomes accept state with (predicate,alt) + # pairs if preds found for conflicting alts + altsToCollectPredsFrom = self.getConflictingAltsOrUniqueAlt(dfaState.configs) + altToPred = self.getPredsForAmbigAlts(altsToCollectPredsFrom, dfaState.configs, nalts) + if altToPred is not None: + dfaState.predicates = self.getPredicatePredictions(altsToCollectPredsFrom, altToPred) + dfaState.prediction = ATN.INVALID_ALT_NUMBER # make sure we use preds + else: + # There are preds in configs but they might go away + # when OR'd together like {p}? || NONE == NONE. If neither + # alt has preds, resolve to min alt + dfaState.prediction = min(altsToCollectPredsFrom) + + # comes back with reach.uniqueAlt set to a valid alt + def execATNWithFullContext(self, dfa:DFA, D:DFAState, # how far we got before failing over + s0:ATNConfigSet, + input:TokenStream, + startIndex:int, + outerContext:ParserRuleContext): + if ParserATNSimulator.debug or ParserATNSimulator.debug_list_atn_decisions: + print("execATNWithFullContext", str(s0)) + fullCtx = True + foundExactAmbig = False + reach = None + previous = s0 + input.seek(startIndex) + t = input.LA(1) + predictedAlt = -1 + while (True): # while more work + reach = self.computeReachSet(previous, t, fullCtx) + if reach is None: + # if any configs in previous dipped into outer context, that + # means that input up to t actually finished entry rule + # at least for LL decision. Full LL doesn't dip into outer + # so don't need special case. + # We will get an error no matter what so delay until after + # decision; better error message. Also, no reachable target + # ATN states in SLL implies LL will also get nowhere. + # If conflict in states that dip out, choose min since we + # will get error no matter what. + e = self.noViableAlt(input, outerContext, previous, startIndex) + input.seek(startIndex) + alt = self.getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(previous, outerContext) + if alt!=ATN.INVALID_ALT_NUMBER: + return alt + else: + raise e + + altSubSets = PredictionMode.getConflictingAltSubsets(reach) + if ParserATNSimulator.debug: + print("LL altSubSets=" + str(altSubSets) + ", predict=" + + str(PredictionMode.getUniqueAlt(altSubSets)) + ", resolvesToJustOneViableAlt=" + + str(PredictionMode.resolvesToJustOneViableAlt(altSubSets))) + + reach.uniqueAlt = self.getUniqueAlt(reach) + # unique prediction? + if reach.uniqueAlt!=ATN.INVALID_ALT_NUMBER: + predictedAlt = reach.uniqueAlt + break + elif self.predictionMode is not PredictionMode.LL_EXACT_AMBIG_DETECTION: + predictedAlt = PredictionMode.resolvesToJustOneViableAlt(altSubSets) + if predictedAlt != ATN.INVALID_ALT_NUMBER: + break + else: + # In exact ambiguity mode, we never try to terminate early. + # Just keeps scarfing until we know what the conflict is + if PredictionMode.allSubsetsConflict(altSubSets) and PredictionMode.allSubsetsEqual(altSubSets): + foundExactAmbig = True + predictedAlt = PredictionMode.getSingleViableAlt(altSubSets) + break + # else there are multiple non-conflicting subsets or + # we're not sure what the ambiguity is yet. + # So, keep going. + + previous = reach + if t != Token.EOF: + input.consume() + t = input.LA(1) + + # If the configuration set uniquely predicts an alternative, + # without conflict, then we know that it's a full LL decision + # not SLL. + if reach.uniqueAlt != ATN.INVALID_ALT_NUMBER : + self.reportContextSensitivity(dfa, predictedAlt, reach, startIndex, input.index) + return predictedAlt + + # We do not check predicates here because we have checked them + # on-the-fly when doing full context prediction. + + # + # In non-exact ambiguity detection mode, we might actually be able to + # detect an exact ambiguity, but I'm not going to spend the cycles + # needed to check. We only emit ambiguity warnings in exact ambiguity + # mode. + # + # For example, we might know that we have conflicting configurations. + # But, that does not mean that there is no way forward without a + # conflict. It's possible to have nonconflicting alt subsets as in: + + # altSubSets=[{1, 2}, {1, 2}, {1}, {1, 2}] + + # from + # + # [(17,1,[5 $]), (13,1,[5 10 $]), (21,1,[5 10 $]), (11,1,[$]), + # (13,2,[5 10 $]), (21,2,[5 10 $]), (11,2,[$])] + # + # In this case, (17,1,[5 $]) indicates there is some next sequence that + # would resolve this without conflict to alternative 1. Any other viable + # next sequence, however, is associated with a conflict. We stop + # looking for input because no amount of further lookahead will alter + # the fact that we should predict alternative 1. We just can't say for + # sure that there is an ambiguity without looking further. + + self.reportAmbiguity(dfa, D, startIndex, input.index, foundExactAmbig, None, reach) + + return predictedAlt + + def computeReachSet(self, closure:ATNConfigSet, t:int, fullCtx:bool): + if ParserATNSimulator.debug: + print("in computeReachSet, starting closure: " + str(closure)) + + if self.mergeCache is None: + self.mergeCache = dict() + + intermediate = ATNConfigSet(fullCtx) + + # Configurations already in a rule stop state indicate reaching the end + # of the decision rule (local context) or end of the start rule (full + # context). Once reached, these configurations are never updated by a + # closure operation, so they are handled separately for the performance + # advantage of having a smaller intermediate set when calling closure. + # + # For full-context reach operations, separate handling is required to + # ensure that the alternative matching the longest overall sequence is + # chosen when multiple such configurations can match the input. + + skippedStopStates = None + + # First figure out where we can reach on input t + for c in closure: + if ParserATNSimulator.debug: + print("testing " + self.getTokenName(t) + " at " + str(c)) + + if isinstance(c.state, RuleStopState): + if fullCtx or t == Token.EOF: + if skippedStopStates is None: + skippedStopStates = list() + skippedStopStates.append(c) + continue + + for trans in c.state.transitions: + target = self.getReachableTarget(trans, t) + if target is not None: + intermediate.add(ATNConfig(state=target, config=c), self.mergeCache) + + # Now figure out where the reach operation can take us... + + reach = None + + # This block optimizes the reach operation for intermediate sets which + # trivially indicate a termination state for the overall + # adaptivePredict operation. + # + # The conditions assume that intermediate + # contains all configurations relevant to the reach set, but this + # condition is not true when one or more configurations have been + # withheld in skippedStopStates, or when the current symbol is EOF. + # + if skippedStopStates is None and t!=Token.EOF: + if len(intermediate)==1: + # Don't pursue the closure if there is just one state. + # It can only have one alternative; just add to result + # Also don't pursue the closure if there is unique alternative + # among the configurations. + reach = intermediate + elif self.getUniqueAlt(intermediate)!=ATN.INVALID_ALT_NUMBER: + # Also don't pursue the closure if there is unique alternative + # among the configurations. + reach = intermediate + + # If the reach set could not be trivially determined, perform a closure + # operation on the intermediate set to compute its initial value. + # + if reach is None: + reach = ATNConfigSet(fullCtx) + closureBusy = set() + treatEofAsEpsilon = t == Token.EOF + for c in intermediate: + self.closure(c, reach, closureBusy, False, fullCtx, treatEofAsEpsilon) + + if t == Token.EOF: + # After consuming EOF no additional input is possible, so we are + # only interested in configurations which reached the end of the + # decision rule (local context) or end of the start rule (full + # context). Update reach to contain only these configurations. This + # handles both explicit EOF transitions in the grammar and implicit + # EOF transitions following the end of the decision or start rule. + # + # When reach==intermediate, no closure operation was performed. In + # this case, removeAllConfigsNotInRuleStopState needs to check for + # reachable rule stop states as well as configurations already in + # a rule stop state. + # + # This is handled before the configurations in skippedStopStates, + # because any configurations potentially added from that list are + # already guaranteed to meet this condition whether or not it's + # required. + # + reach = self.removeAllConfigsNotInRuleStopState(reach, reach is intermediate) + + # If skippedStopStates is not null, then it contains at least one + # configuration. For full-context reach operations, these + # configurations reached the end of the start rule, in which case we + # only add them back to reach if no configuration during the current + # closure operation reached such a state. This ensures adaptivePredict + # chooses an alternative matching the longest overall sequence when + # multiple alternatives are viable. + # + if skippedStopStates is not None and ( (not fullCtx) or (not PredictionMode.hasConfigInRuleStopState(reach))): + for c in skippedStopStates: + reach.add(c, self.mergeCache) + if len(reach)==0: + return None + else: + return reach + + # + # Return a configuration set containing only the configurations from + # {@code configs} which are in a {@link RuleStopState}. If all + # configurations in {@code configs} are already in a rule stop state, this + # method simply returns {@code configs}. + # + #

When {@code lookToEndOfRule} is true, this method uses + # {@link ATN#nextTokens} for each configuration in {@code configs} which is + # not already in a rule stop state to see if a rule stop state is reachable + # from the configuration via epsilon-only transitions.

+ # + # @param configs the configuration set to update + # @param lookToEndOfRule when true, this method checks for rule stop states + # reachable by epsilon-only transitions from each configuration in + # {@code configs}. + # + # @return {@code configs} if all configurations in {@code configs} are in a + # rule stop state, otherwise return a new configuration set containing only + # the configurations from {@code configs} which are in a rule stop state + # + def removeAllConfigsNotInRuleStopState(self, configs:ATNConfigSet, lookToEndOfRule:bool): + if PredictionMode.allConfigsInRuleStopStates(configs): + return configs + result = ATNConfigSet(configs.fullCtx) + for config in configs: + if isinstance(config.state, RuleStopState): + result.add(config, self.mergeCache) + continue + if lookToEndOfRule and config.state.epsilonOnlyTransitions: + nextTokens = self.atn.nextTokens(config.state) + if Token.EPSILON in nextTokens: + endOfRuleState = self.atn.ruleToStopState[config.state.ruleIndex] + result.add(ATNConfig(state=endOfRuleState, config=config), self.mergeCache) + return result + + def computeStartState(self, p:ATNState, ctx:RuleContext, fullCtx:bool): + # always at least the implicit call to start rule + initialContext = PredictionContextFromRuleContext(self.atn, ctx) + configs = ATNConfigSet(fullCtx) + + for i in range(0, len(p.transitions)): + target = p.transitions[i].target + c = ATNConfig(target, i+1, initialContext) + closureBusy = set() + self.closure(c, configs, closureBusy, True, fullCtx, False) + return configs + + # + # This method transforms the start state computed by + # {@link #computeStartState} to the special start state used by a + # precedence DFA for a particular precedence value. The transformation + # process applies the following changes to the start state's configuration + # set. + # + #
    + #
  1. Evaluate the precedence predicates for each configuration using + # {@link SemanticContext#evalPrecedence}.
  2. + #
  3. Remove all configurations which predict an alternative greater than + # 1, for which another configuration that predicts alternative 1 is in the + # same ATN state with the same prediction context. This transformation is + # valid for the following reasons: + # + #
  4. + #
+ # + #

+ # The prediction context must be considered by this filter to address + # situations like the following. + #

+ # + #
+    # grammar TA;
+    # prog: statement* EOF;
+    # statement: letterA | statement letterA 'b' ;
+    # letterA: 'a';
+    # 
+ #
+ #

+ # If the above grammar, the ATN state immediately before the token + # reference {@code 'a'} in {@code letterA} is reachable from the left edge + # of both the primary and closure blocks of the left-recursive rule + # {@code statement}. The prediction context associated with each of these + # configurations distinguishes between them, and prevents the alternative + # which stepped out to {@code prog} (and then back in to {@code statement} + # from being eliminated by the filter. + #

+ # + # @param configs The configuration set computed by + # {@link #computeStartState} as the start state for the DFA. + # @return The transformed configuration set representing the start state + # for a precedence DFA at a particular precedence level (determined by + # calling {@link Parser#getPrecedence}). + # + def applyPrecedenceFilter(self, configs:ATNConfigSet): + statesFromAlt1 = dict() + configSet = ATNConfigSet(configs.fullCtx) + for config in configs: + # handle alt 1 first + if config.alt != 1: + continue + updatedContext = config.semanticContext.evalPrecedence(self.parser, self._outerContext) + if updatedContext is None: + # the configuration was eliminated + continue + + statesFromAlt1[config.state.stateNumber] = config.context + if updatedContext is not config.semanticContext: + configSet.add(ATNConfig(config=config, semantic=updatedContext), self.mergeCache) + else: + configSet.add(config, self.mergeCache) + + for config in configs: + if config.alt == 1: + # already handled + continue + + # In the future, this elimination step could be updated to also + # filter the prediction context for alternatives predicting alt>1 + # (basically a graph subtraction algorithm). + # + if not config.precedenceFilterSuppressed: + context = statesFromAlt1.get(config.state.stateNumber, None) + if context==config.context: + # eliminated + continue + + configSet.add(config, self.mergeCache) + + return configSet + + def getReachableTarget(self, trans:Transition, ttype:int): + if trans.matches(ttype, 0, self.atn.maxTokenType): + return trans.target + else: + return None + + def getPredsForAmbigAlts(self, ambigAlts:set, configs:ATNConfigSet, nalts:int): + # REACH=[1|1|[]|0:0, 1|2|[]|0:1] + # altToPred starts as an array of all null contexts. The entry at index i + # corresponds to alternative i. altToPred[i] may have one of three values: + # 1. null: no ATNConfig c is found such that c.alt==i + # 2. SemanticContext.NONE: At least one ATNConfig c exists such that + # c.alt==i and c.semanticContext==SemanticContext.NONE. In other words, + # alt i has at least one unpredicated config. + # 3. Non-NONE Semantic Context: There exists at least one, and for all + # ATNConfig c such that c.alt==i, c.semanticContext!=SemanticContext.NONE. + # + # From this, it is clear that NONE||anything==NONE. + # + altToPred = [None] * (nalts + 1) + for c in configs: + if c.alt in ambigAlts: + altToPred[c.alt] = orContext(altToPred[c.alt], c.semanticContext) + + nPredAlts = 0 + for i in range(1, nalts+1): + if altToPred[i] is None: + altToPred[i] = SemanticContext.NONE + elif altToPred[i] is not SemanticContext.NONE: + nPredAlts += 1 + + # nonambig alts are null in altToPred + if nPredAlts==0: + altToPred = None + if ParserATNSimulator.debug: + print("getPredsForAmbigAlts result " + str_list(altToPred)) + return altToPred + + def getPredicatePredictions(self, ambigAlts:set, altToPred:list): + pairs = [] + containsPredicate = False + for i in range(1, len(altToPred)): + pred = altToPred[i] + # unpredicated is indicated by SemanticContext.NONE + if ambigAlts is not None and i in ambigAlts: + pairs.append(PredPrediction(pred, i)) + if pred is not SemanticContext.NONE: + containsPredicate = True + + if not containsPredicate: + return None + + return pairs + + # + # This method is used to improve the localization of error messages by + # choosing an alternative rather than throwing a + # {@link NoViableAltException} in particular prediction scenarios where the + # {@link #ERROR} state was reached during ATN simulation. + # + #

+ # The default implementation of this method uses the following + # algorithm to identify an ATN configuration which successfully parsed the + # decision entry rule. Choosing such an alternative ensures that the + # {@link ParserRuleContext} returned by the calling rule will be complete + # and valid, and the syntax error will be reported later at a more + # localized location.

+ # + # + # + #

+ # In some scenarios, the algorithm described above could predict an + # alternative which will result in a {@link FailedPredicateException} in + # the parser. Specifically, this could occur if the only configuration + # capable of successfully parsing to the end of the decision rule is + # blocked by a semantic predicate. By choosing this alternative within + # {@link #adaptivePredict} instead of throwing a + # {@link NoViableAltException}, the resulting + # {@link FailedPredicateException} in the parser will identify the specific + # predicate which is preventing the parser from successfully parsing the + # decision rule, which helps developers identify and correct logic errors + # in semantic predicates. + #

+ # + # @param configs The ATN configurations which were valid immediately before + # the {@link #ERROR} state was reached + # @param outerContext The is the \gamma_0 initial parser context from the paper + # or the parser stack at the instant before prediction commences. + # + # @return The value to return from {@link #adaptivePredict}, or + # {@link ATN#INVALID_ALT_NUMBER} if a suitable alternative was not + # identified and {@link #adaptivePredict} should report an error instead. + # + def getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(self, configs:ATNConfigSet, outerContext:ParserRuleContext): + semValidConfigs, semInvalidConfigs = self.splitAccordingToSemanticValidity(configs, outerContext) + alt = self.getAltThatFinishedDecisionEntryRule(semValidConfigs) + if alt!=ATN.INVALID_ALT_NUMBER: # semantically/syntactically viable path exists + return alt + # Is there a syntactically valid path with a failed pred? + if len(semInvalidConfigs)>0: + alt = self.getAltThatFinishedDecisionEntryRule(semInvalidConfigs) + if alt!=ATN.INVALID_ALT_NUMBER: # syntactically viable path exists + return alt + return ATN.INVALID_ALT_NUMBER + + def getAltThatFinishedDecisionEntryRule(self, configs:ATNConfigSet): + alts = set() + for c in configs: + if c.reachesIntoOuterContext>0 or (isinstance(c.state, RuleStopState) and c.context.hasEmptyPath() ): + alts.add(c.alt) + if len(alts)==0: + return ATN.INVALID_ALT_NUMBER + else: + return min(alts) + + # Walk the list of configurations and split them according to + # those that have preds evaluating to true/false. If no pred, assume + # true pred and include in succeeded set. Returns Pair of sets. + # + # Create a new set so as not to alter the incoming parameter. + # + # Assumption: the input stream has been restored to the starting point + # prediction, which is where predicates need to evaluate. + # + def splitAccordingToSemanticValidity(self, configs:ATNConfigSet, outerContext:ParserRuleContext): + succeeded = ATNConfigSet(configs.fullCtx) + failed = ATNConfigSet(configs.fullCtx) + for c in configs: + if c.semanticContext is not SemanticContext.NONE: + predicateEvaluationResult = c.semanticContext.eval(self.parser, outerContext) + if predicateEvaluationResult: + succeeded.add(c) + else: + failed.add(c) + else: + succeeded.add(c) + return (succeeded,failed) + + # Look through a list of predicate/alt pairs, returning alts for the + # pairs that win. A {@code NONE} predicate indicates an alt containing an + # unpredicated config which behaves as "always true." If !complete + # then we stop at the first predicate that evaluates to true. This + # includes pairs with null predicates. + # + def evalSemanticContext(self, predPredictions:list, outerContext:ParserRuleContext, complete:bool): + predictions = set() + for pair in predPredictions: + if pair.pred is SemanticContext.NONE: + predictions.add(pair.alt) + if not complete: + break + continue + predicateEvaluationResult = pair.pred.eval(self.parser, outerContext) + if ParserATNSimulator.debug or ParserATNSimulator.dfa_debug: + print("eval pred " + str(pair) + "=" + str(predicateEvaluationResult)) + + if predicateEvaluationResult: + if ParserATNSimulator.debug or ParserATNSimulator.dfa_debug: + print("PREDICT " + str(pair.alt)) + predictions.add(pair.alt) + if not complete: + break + return predictions + + + # TODO: If we are doing predicates, there is no point in pursuing + # closure operations if we reach a DFA state that uniquely predicts + # alternative. We will not be caching that DFA state and it is a + # waste to pursue the closure. Might have to advance when we do + # ambig detection thought :( + # + + def closure(self, config:ATNConfig, configs:ATNConfigSet, closureBusy:set, collectPredicates:bool, fullCtx:bool, treatEofAsEpsilon:bool): + initialDepth = 0 + self.closureCheckingStopState(config, configs, closureBusy, collectPredicates, + fullCtx, initialDepth, treatEofAsEpsilon) + + + def closureCheckingStopState(self, config:ATNConfig, configs:ATNConfigSet, closureBusy:set, collectPredicates:bool, fullCtx:bool, depth:int, treatEofAsEpsilon:bool): + if ParserATNSimulator.debug: + print("closure(" + str(config) + ")") + + if isinstance(config.state, RuleStopState): + # We hit rule end. If we have context info, use it + # run thru all possible stack tops in ctx + if not config.context.isEmpty(): + for i in range(0, len(config.context)): + state = config.context.getReturnState(i) + if state is PredictionContext.EMPTY_RETURN_STATE: + if fullCtx: + configs.add(ATNConfig(state=config.state, context=PredictionContext.EMPTY, config=config), self.mergeCache) + continue + else: + # we have no context info, just chase follow links (if greedy) + if ParserATNSimulator.debug: + print("FALLING off rule " + self.getRuleName(config.state.ruleIndex)) + self.closure_(config, configs, closureBusy, collectPredicates, + fullCtx, depth, treatEofAsEpsilon) + continue + returnState = self.atn.states[state] + newContext = config.context.getParent(i) # "pop" return state + c = ATNConfig(state=returnState, alt=config.alt, context=newContext, semantic=config.semanticContext) + # While we have context to pop back from, we may have + # gotten that context AFTER having falling off a rule. + # Make sure we track that we are now out of context. + c.reachesIntoOuterContext = config.reachesIntoOuterContext + self.closureCheckingStopState(c, configs, closureBusy, collectPredicates, fullCtx, depth - 1, treatEofAsEpsilon) + return + elif fullCtx: + # reached end of start rule + configs.add(config, self.mergeCache) + return + else: + # else if we have no context info, just chase follow links (if greedy) + if ParserATNSimulator.debug: + print("FALLING off rule " + self.getRuleName(config.state.ruleIndex)) + + self.closure_(config, configs, closureBusy, collectPredicates, fullCtx, depth, treatEofAsEpsilon) + + # Do the actual work of walking epsilon edges# + def closure_(self, config:ATNConfig, configs:ATNConfigSet, closureBusy:set, collectPredicates:bool, fullCtx:bool, depth:int, treatEofAsEpsilon:bool): + p = config.state + # optimization + if not p.epsilonOnlyTransitions: + configs.add(config, self.mergeCache) + # make sure to not return here, because EOF transitions can act as + # both epsilon transitions and non-epsilon transitions. + + first = True + for t in p.transitions: + if first: + first = False + if self.canDropLoopEntryEdgeInLeftRecursiveRule(config): + continue + + continueCollecting = collectPredicates and not isinstance(t, ActionTransition) + c = self.getEpsilonTarget(config, t, continueCollecting, depth == 0, fullCtx, treatEofAsEpsilon) + if c is not None: + newDepth = depth + if isinstance( config.state, RuleStopState): + # target fell off end of rule; mark resulting c as having dipped into outer context + # We can't get here if incoming config was rule stop and we had context + # track how far we dip into outer context. Might + # come in handy and we avoid evaluating context dependent + # preds if this is > 0. + if self._dfa is not None and self._dfa.precedenceDfa: + if t.outermostPrecedenceReturn == self._dfa.atnStartState.ruleIndex: + c.precedenceFilterSuppressed = True + c.reachesIntoOuterContext += 1 + if c in closureBusy: + # avoid infinite recursion for right-recursive rules + continue + closureBusy.add(c) + configs.dipsIntoOuterContext = True # TODO: can remove? only care when we add to set per middle of this method + newDepth -= 1 + if ParserATNSimulator.debug: + print("dips into outer ctx: " + str(c)) + else: + if not t.isEpsilon: + if c in closureBusy: + # avoid infinite recursion for EOF* and EOF+ + continue + closureBusy.add(c) + if isinstance(t, RuleTransition): + # latch when newDepth goes negative - once we step out of the entry context we can't return + if newDepth >= 0: + newDepth += 1 + + self.closureCheckingStopState(c, configs, closureBusy, continueCollecting, fullCtx, newDepth, treatEofAsEpsilon) + + + + # Implements first-edge (loop entry) elimination as an optimization + # during closure operations. See antlr/antlr4#1398. + # + # The optimization is to avoid adding the loop entry config when + # the exit path can only lead back to the same + # StarLoopEntryState after popping context at the rule end state + # (traversing only epsilon edges, so we're still in closure, in + # this same rule). + # + # We need to detect any state that can reach loop entry on + # epsilon w/o exiting rule. We don't have to look at FOLLOW + # links, just ensure that all stack tops for config refer to key + # states in LR rule. + # + # To verify we are in the right situation we must first check + # closure is at a StarLoopEntryState generated during LR removal. + # Then we check that each stack top of context is a return state + # from one of these cases: + # + # 1. 'not' expr, '(' type ')' expr. The return state points at loop entry state + # 2. expr op expr. The return state is the block end of internal block of (...)* + # 3. 'between' expr 'and' expr. The return state of 2nd expr reference. + # That state points at block end of internal block of (...)*. + # 4. expr '?' expr ':' expr. The return state points at block end, + # which points at loop entry state. + # + # If any is true for each stack top, then closure does not add a + # config to the current config set for edge[0], the loop entry branch. + # + # Conditions fail if any context for the current config is: + # + # a. empty (we'd fall out of expr to do a global FOLLOW which could + # even be to some weird spot in expr) or, + # b. lies outside of expr or, + # c. lies within expr but at a state not the BlockEndState + # generated during LR removal + # + # Do we need to evaluate predicates ever in closure for this case? + # + # No. Predicates, including precedence predicates, are only + # evaluated when computing a DFA start state. I.e., only before + # the lookahead (but not parser) consumes a token. + # + # There are no epsilon edges allowed in LR rule alt blocks or in + # the "primary" part (ID here). If closure is in + # StarLoopEntryState any lookahead operation will have consumed a + # token as there are no epsilon-paths that lead to + # StarLoopEntryState. We do not have to evaluate predicates + # therefore if we are in the generated StarLoopEntryState of a LR + # rule. Note that when making a prediction starting at that + # decision point, decision d=2, compute-start-state performs + # closure starting at edges[0], edges[1] emanating from + # StarLoopEntryState. That means it is not performing closure on + # StarLoopEntryState during compute-start-state. + # + # How do we know this always gives same prediction answer? + # + # Without predicates, loop entry and exit paths are ambiguous + # upon remaining input +b (in, say, a+b). Either paths lead to + # valid parses. Closure can lead to consuming + immediately or by + # falling out of this call to expr back into expr and loop back + # again to StarLoopEntryState to match +b. In this special case, + # we choose the more efficient path, which is to take the bypass + # path. + # + # The lookahead language has not changed because closure chooses + # one path over the other. Both paths lead to consuming the same + # remaining input during a lookahead operation. If the next token + # is an operator, lookahead will enter the choice block with + # operators. If it is not, lookahead will exit expr. Same as if + # closure had chosen to enter the choice block immediately. + # + # Closure is examining one config (some loopentrystate, some alt, + # context) which means it is considering exactly one alt. Closure + # always copies the same alt to any derived configs. + # + # How do we know this optimization doesn't mess up precedence in + # our parse trees? + # + # Looking through expr from left edge of stat only has to confirm + # that an input, say, a+b+c; begins with any valid interpretation + # of an expression. The precedence actually doesn't matter when + # making a decision in stat seeing through expr. It is only when + # parsing rule expr that we must use the precedence to get the + # right interpretation and, hence, parse tree. + # + # @since 4.6 + # + def canDropLoopEntryEdgeInLeftRecursiveRule(self, config): + # return False + p = config.state + # First check to see if we are in StarLoopEntryState generated during + # left-recursion elimination. For efficiency, also check if + # the context has an empty stack case. If so, it would mean + # global FOLLOW so we can't perform optimization + # Are we the special loop entry/exit state? or SLL wildcard + if p.stateType != ATNState.STAR_LOOP_ENTRY \ + or not p.isPrecedenceDecision \ + or config.context.isEmpty() \ + or config.context.hasEmptyPath(): + return False + + # Require all return states to return back to the same rule + # that p is in. + numCtxs = len(config.context) + for i in range(0, numCtxs): # for each stack context + returnState = self.atn.states[config.context.getReturnState(i)] + if returnState.ruleIndex != p.ruleIndex: + return False + + decisionStartState = p.transitions[0].target + blockEndStateNum = decisionStartState.endState.stateNumber + blockEndState = self.atn.states[blockEndStateNum] + + # Verify that the top of each stack context leads to loop entry/exit + # state through epsilon edges and w/o leaving rule. + for i in range(0, numCtxs): # for each stack context + returnStateNumber = config.context.getReturnState(i) + returnState = self.atn.states[returnStateNumber] + # all states must have single outgoing epsilon edge + if len(returnState.transitions) != 1 or not returnState.transitions[0].isEpsilon: + return False + + # Look for prefix op case like 'not expr', (' type ')' expr + returnStateTarget = returnState.transitions[0].target + if returnState.stateType == ATNState.BLOCK_END and returnStateTarget is p: + continue + + # Look for 'expr op expr' or case where expr's return state is block end + # of (...)* internal block; the block end points to loop back + # which points to p but we don't need to check that + if returnState is blockEndState: + continue + + # Look for ternary expr ? expr : expr. The return state points at block end, + # which points at loop entry state + if returnStateTarget is blockEndState: + continue + + # Look for complex prefix 'between expr and expr' case where 2nd expr's + # return state points at block end state of (...)* internal block + if returnStateTarget.stateType == ATNState.BLOCK_END \ + and len(returnStateTarget.transitions) == 1 \ + and returnStateTarget.transitions[0].isEpsilon \ + and returnStateTarget.transitions[0].target is p: + continue + + # anything else ain't conforming + return False + + return True + + + def getRuleName(self, index:int): + if self.parser is not None and index>=0: + return self.parser.ruleNames[index] + else: + return "" + + epsilonTargetMethods = dict() + epsilonTargetMethods[Transition.RULE] = lambda sim, config, t, collectPredicates, inContext, fullCtx, treatEofAsEpsilon: \ + sim.ruleTransition(config, t) + epsilonTargetMethods[Transition.PRECEDENCE] = lambda sim, config, t, collectPredicates, inContext, fullCtx, treatEofAsEpsilon: \ + sim.precedenceTransition(config, t, collectPredicates, inContext, fullCtx) + epsilonTargetMethods[Transition.PREDICATE] = lambda sim, config, t, collectPredicates, inContext, fullCtx, treatEofAsEpsilon: \ + sim.predTransition(config, t, collectPredicates, inContext, fullCtx) + epsilonTargetMethods[Transition.ACTION] = lambda sim, config, t, collectPredicates, inContext, fullCtx, treatEofAsEpsilon: \ + sim.actionTransition(config, t) + epsilonTargetMethods[Transition.EPSILON] = lambda sim, config, t, collectPredicates, inContext, fullCtx, treatEofAsEpsilon: \ + ATNConfig(state=t.target, config=config) + epsilonTargetMethods[Transition.ATOM] = lambda sim, config, t, collectPredicates, inContext, fullCtx, treatEofAsEpsilon: \ + ATNConfig(state=t.target, config=config) if treatEofAsEpsilon and t.matches(Token.EOF, 0, 1) else None + epsilonTargetMethods[Transition.RANGE] = lambda sim, config, t, collectPredicates, inContext, fullCtx, treatEofAsEpsilon: \ + ATNConfig(state=t.target, config=config) if treatEofAsEpsilon and t.matches(Token.EOF, 0, 1) else None + epsilonTargetMethods[Transition.SET] = lambda sim, config, t, collectPredicates, inContext, fullCtx, treatEofAsEpsilon: \ + ATNConfig(state=t.target, config=config) if treatEofAsEpsilon and t.matches(Token.EOF, 0, 1) else None + + def getEpsilonTarget(self, config:ATNConfig, t:Transition, collectPredicates:bool, inContext:bool, fullCtx:bool, treatEofAsEpsilon:bool): + m = self.epsilonTargetMethods.get(t.serializationType, None) + if m is None: + return None + else: + return m(self, config, t, collectPredicates, inContext, fullCtx, treatEofAsEpsilon) + + def actionTransition(self, config:ATNConfig, t:ActionTransition): + if ParserATNSimulator.debug: + print("ACTION edge " + str(t.ruleIndex) + ":" + str(t.actionIndex)) + return ATNConfig(state=t.target, config=config) + + def precedenceTransition(self, config:ATNConfig, pt:PrecedencePredicateTransition, collectPredicates:bool, inContext:bool, fullCtx:bool): + if ParserATNSimulator.debug: + print("PRED (collectPredicates=" + str(collectPredicates) + ") " + + str(pt.precedence) + ">=_p, ctx dependent=true") + if self.parser is not None: + print("context surrounding pred is " + str(self.parser.getRuleInvocationStack())) + + c = None + if collectPredicates and inContext: + if fullCtx: + # In full context mode, we can evaluate predicates on-the-fly + # during closure, which dramatically reduces the size of + # the config sets. It also obviates the need to test predicates + # later during conflict resolution. + currentPosition = self._input.index + self._input.seek(self._startIndex) + predSucceeds = pt.getPredicate().eval(self.parser, self._outerContext) + self._input.seek(currentPosition) + if predSucceeds: + c = ATNConfig(state=pt.target, config=config) # no pred context + else: + newSemCtx = andContext(config.semanticContext, pt.getPredicate()) + c = ATNConfig(state=pt.target, semantic=newSemCtx, config=config) + else: + c = ATNConfig(state=pt.target, config=config) + + if ParserATNSimulator.debug: + print("config from pred transition=" + str(c)) + return c + + def predTransition(self, config:ATNConfig, pt:PredicateTransition, collectPredicates:bool, inContext:bool, fullCtx:bool): + if ParserATNSimulator.debug: + print("PRED (collectPredicates=" + str(collectPredicates) + ") " + str(pt.ruleIndex) + + ":" + str(pt.predIndex) + ", ctx dependent=" + str(pt.isCtxDependent)) + if self.parser is not None: + print("context surrounding pred is " + str(self.parser.getRuleInvocationStack())) + + c = None + if collectPredicates and (not pt.isCtxDependent or (pt.isCtxDependent and inContext)): + if fullCtx: + # In full context mode, we can evaluate predicates on-the-fly + # during closure, which dramatically reduces the size of + # the config sets. It also obviates the need to test predicates + # later during conflict resolution. + currentPosition = self._input.index + self._input.seek(self._startIndex) + predSucceeds = pt.getPredicate().eval(self.parser, self._outerContext) + self._input.seek(currentPosition) + if predSucceeds: + c = ATNConfig(state=pt.target, config=config) # no pred context + else: + newSemCtx = andContext(config.semanticContext, pt.getPredicate()) + c = ATNConfig(state=pt.target, semantic=newSemCtx, config=config) + else: + c = ATNConfig(state=pt.target, config=config) + + if ParserATNSimulator.debug: + print("config from pred transition=" + str(c)) + return c + + def ruleTransition(self, config:ATNConfig, t:RuleTransition): + if ParserATNSimulator.debug: + print("CALL rule " + self.getRuleName(t.target.ruleIndex) + ", ctx=" + str(config.context)) + returnState = t.followState + newContext = SingletonPredictionContext.create(config.context, returnState.stateNumber) + return ATNConfig(state=t.target, context=newContext, config=config ) + + def getConflictingAlts(self, configs:ATNConfigSet): + altsets = PredictionMode.getConflictingAltSubsets(configs) + return PredictionMode.getAlts(altsets) + + # Sam pointed out a problem with the previous definition, v3, of + # ambiguous states. If we have another state associated with conflicting + # alternatives, we should keep going. For example, the following grammar + # + # s : (ID | ID ID?) ';' ; + # + # When the ATN simulation reaches the state before ';', it has a DFA + # state that looks like: [12|1|[], 6|2|[], 12|2|[]]. Naturally + # 12|1|[] and 12|2|[] conflict, but we cannot stop processing this node + # because alternative to has another way to continue, via [6|2|[]]. + # The key is that we have a single state that has config's only associated + # with a single alternative, 2, and crucially the state transitions + # among the configurations are all non-epsilon transitions. That means + # we don't consider any conflicts that include alternative 2. So, we + # ignore the conflict between alts 1 and 2. We ignore a set of + # conflicting alts when there is an intersection with an alternative + # associated with a single alt state in the state→config-list map. + # + # It's also the case that we might have two conflicting configurations but + # also a 3rd nonconflicting configuration for a different alternative: + # [1|1|[], 1|2|[], 8|3|[]]. This can come about from grammar: + # + # a : A | A | A B ; + # + # After matching input A, we reach the stop state for rule A, state 1. + # State 8 is the state right before B. Clearly alternatives 1 and 2 + # conflict and no amount of further lookahead will separate the two. + # However, alternative 3 will be able to continue and so we do not + # stop working on this state. In the previous example, we're concerned + # with states associated with the conflicting alternatives. Here alt + # 3 is not associated with the conflicting configs, but since we can continue + # looking for input reasonably, I don't declare the state done. We + # ignore a set of conflicting alts when we have an alternative + # that we still need to pursue. + # + + def getConflictingAltsOrUniqueAlt(self, configs:ATNConfigSet): + conflictingAlts = None + if configs.uniqueAlt!= ATN.INVALID_ALT_NUMBER: + conflictingAlts = set() + conflictingAlts.add(configs.uniqueAlt) + else: + conflictingAlts = configs.conflictingAlts + return conflictingAlts + + def getTokenName(self, t:int): + if t==Token.EOF: + return "EOF" + if self.parser is not None and \ + self.parser.literalNames is not None and \ + t < len(self.parser.literalNames): + return self.parser.literalNames[t] + "<" + str(t) + ">" + else: + return str(t) + + def getLookaheadName(self, input:TokenStream): + return self.getTokenName(input.LA(1)) + + # Used for debugging in adaptivePredict around execATN but I cut + # it out for clarity now that alg. works well. We can leave this + # "dead" code for a bit. + # + def dumpDeadEndConfigs(self, nvae:NoViableAltException): + print("dead end configs: ") + for c in nvae.getDeadEndConfigs(): + trans = "no edges" + if len(c.state.transitions)>0: + t = c.state.transitions[0] + if isinstance(t, AtomTransition): + trans = "Atom "+ self.getTokenName(t.label) + elif isinstance(t, SetTransition): + neg = isinstance(t, NotSetTransition) + trans = ("~" if neg else "")+"Set "+ str(t.set) + print(c.toString(self.parser, True) + ":" + trans, file=sys.stderr) + + def noViableAlt(self, input:TokenStream, outerContext:ParserRuleContext, configs:ATNConfigSet, startIndex:int): + return NoViableAltException(self.parser, input, input.get(startIndex), input.LT(1), configs, outerContext) + + def getUniqueAlt(self, configs:ATNConfigSet): + alt = ATN.INVALID_ALT_NUMBER + for c in configs: + if alt == ATN.INVALID_ALT_NUMBER: + alt = c.alt # found first alt + elif c.alt!=alt: + return ATN.INVALID_ALT_NUMBER + return alt + + # + # Add an edge to the DFA, if possible. This method calls + # {@link #addDFAState} to ensure the {@code to} state is present in the + # DFA. If {@code from} is {@code null}, or if {@code t} is outside the + # range of edges that can be represented in the DFA tables, this method + # returns without adding the edge to the DFA. + # + #

If {@code to} is {@code null}, this method returns {@code null}. + # Otherwise, this method returns the {@link DFAState} returned by calling + # {@link #addDFAState} for the {@code to} state.

+ # + # @param dfa The DFA + # @param from The source state for the edge + # @param t The input symbol + # @param to The target state for the edge + # + # @return If {@code to} is {@code null}, this method returns {@code null}; + # otherwise this method returns the result of calling {@link #addDFAState} + # on {@code to} + # + def addDFAEdge(self, dfa:DFA, from_:DFAState, t:int, to:DFAState): + if ParserATNSimulator.debug: + print("EDGE " + str(from_) + " -> " + str(to) + " upon " + self.getTokenName(t)) + + if to is None: + return None + + to = self.addDFAState(dfa, to) # used existing if possible not incoming + if from_ is None or t < -1 or t > self.atn.maxTokenType: + return to + + if from_.edges is None: + from_.edges = [None] * (self.atn.maxTokenType + 2) + from_.edges[t+1] = to # connect + + if ParserATNSimulator.debug: + names = None if self.parser is None else self.parser.literalNames + print("DFA=\n" + dfa.toString(names)) + + return to + + # + # Add state {@code D} to the DFA if it is not already present, and return + # the actual instance stored in the DFA. If a state equivalent to {@code D} + # is already in the DFA, the existing state is returned. Otherwise this + # method returns {@code D} after adding it to the DFA. + # + #

If {@code D} is {@link #ERROR}, this method returns {@link #ERROR} and + # does not change the DFA.

+ # + # @param dfa The dfa + # @param D The DFA state to add + # @return The state stored in the DFA. This will be either the existing + # state if {@code D} is already in the DFA, or {@code D} itself if the + # state was not already present. + # + def addDFAState(self, dfa:DFA, D:DFAState): + if D is self.ERROR: + return D + + + existing = dfa.states.get(D, None) + if existing is not None: + return existing + + D.stateNumber = len(dfa.states) + if not D.configs.readonly: + D.configs.optimizeConfigs(self) + D.configs.setReadonly(True) + dfa.states[D] = D + if ParserATNSimulator.debug: + print("adding new DFA state: " + str(D)) + return D + + def reportAttemptingFullContext(self, dfa:DFA, conflictingAlts:set, configs:ATNConfigSet, startIndex:int, stopIndex:int): + if ParserATNSimulator.debug or ParserATNSimulator.retry_debug: + print("reportAttemptingFullContext decision=" + str(dfa.decision) + ":" + str(configs) + + ", input=" + self.parser.getTokenStream().getText(startIndex, stopIndex)) + if self.parser is not None: + self.parser.getErrorListenerDispatch().reportAttemptingFullContext(self.parser, dfa, startIndex, stopIndex, conflictingAlts, configs) + + def reportContextSensitivity(self, dfa:DFA, prediction:int, configs:ATNConfigSet, startIndex:int, stopIndex:int): + if ParserATNSimulator.debug or ParserATNSimulator.retry_debug: + print("reportContextSensitivity decision=" + str(dfa.decision) + ":" + str(configs) + + ", input=" + self.parser.getTokenStream().getText(startIndex, stopIndex)) + if self.parser is not None: + self.parser.getErrorListenerDispatch().reportContextSensitivity(self.parser, dfa, startIndex, stopIndex, prediction, configs) + + # If context sensitive parsing, we know it's ambiguity not conflict# + def reportAmbiguity(self, dfa:DFA, D:DFAState, startIndex:int, stopIndex:int, + exact:bool, ambigAlts:set, configs:ATNConfigSet ): + if ParserATNSimulator.debug or ParserATNSimulator.retry_debug: +# ParserATNPathFinder finder = new ParserATNPathFinder(parser, atn); +# int i = 1; +# for (Transition t : dfa.atnStartState.transitions) { +# print("ALT "+i+"="); +# print(startIndex+".."+stopIndex+", len(input)="+parser.getInputStream().size()); +# TraceTree path = finder.trace(t.target, parser.getContext(), (TokenStream)parser.getInputStream(), +# startIndex, stopIndex); +# if ( path!=null ) { +# print("path = "+path.toStringTree()); +# for (TraceTree leaf : path.leaves) { +# List states = path.getPathToNode(leaf); +# print("states="+states); +# } +# } +# i++; +# } + print("reportAmbiguity " + str(ambigAlts) + ":" + str(configs) + + ", input=" + self.parser.getTokenStream().getText(startIndex, stopIndex)) + if self.parser is not None: + self.parser.getErrorListenerDispatch().reportAmbiguity(self.parser, dfa, startIndex, stopIndex, exact, ambigAlts, configs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/atn/PredictionMode.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/atn/PredictionMode.py new file mode 100644 index 0000000000000000000000000000000000000000..8e5c73bb47f329d519f4e574ba3a36fc6c4ac29f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/atn/PredictionMode.py @@ -0,0 +1,499 @@ +# +# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. +# Use of this file is governed by the BSD 3-clause license that +# can be found in the LICENSE.txt file in the project root. +# +# +# This enumeration defines the prediction modes available in ANTLR 4 along with +# utility methods for analyzing configuration sets for conflicts and/or +# ambiguities. + + +from enum import Enum +from antlr4.atn.ATN import ATN +from antlr4.atn.ATNConfig import ATNConfig +from antlr4.atn.ATNConfigSet import ATNConfigSet +from antlr4.atn.ATNState import RuleStopState +from antlr4.atn.SemanticContext import SemanticContext + +PredictionMode = None + +class PredictionMode(Enum): + # + # The SLL(*) prediction mode. This prediction mode ignores the current + # parser context when making predictions. This is the fastest prediction + # mode, and provides correct results for many grammars. This prediction + # mode is more powerful than the prediction mode provided by ANTLR 3, but + # may result in syntax errors for grammar and input combinations which are + # not SLL. + # + #

+ # When using this prediction mode, the parser will either return a correct + # parse tree (i.e. the same parse tree that would be returned with the + # {@link #LL} prediction mode), or it will report a syntax error. If a + # syntax error is encountered when using the {@link #SLL} prediction mode, + # it may be due to either an actual syntax error in the input or indicate + # that the particular combination of grammar and input requires the more + # powerful {@link #LL} prediction abilities to complete successfully.

+ # + #

+ # This prediction mode does not provide any guarantees for prediction + # behavior for syntactically-incorrect inputs.

+ # + SLL = 0 + # + # The LL(*) prediction mode. This prediction mode allows the current parser + # context to be used for resolving SLL conflicts that occur during + # prediction. This is the fastest prediction mode that guarantees correct + # parse results for all combinations of grammars with syntactically correct + # inputs. + # + #

+ # When using this prediction mode, the parser will make correct decisions + # for all syntactically-correct grammar and input combinations. However, in + # cases where the grammar is truly ambiguous this prediction mode might not + # report a precise answer for exactly which alternatives are + # ambiguous.

+ # + #

+ # This prediction mode does not provide any guarantees for prediction + # behavior for syntactically-incorrect inputs.

+ # + LL = 1 + # + # The LL(*) prediction mode with exact ambiguity detection. In addition to + # the correctness guarantees provided by the {@link #LL} prediction mode, + # this prediction mode instructs the prediction algorithm to determine the + # complete and exact set of ambiguous alternatives for every ambiguous + # decision encountered while parsing. + # + #

+ # This prediction mode may be used for diagnosing ambiguities during + # grammar development. Due to the performance overhead of calculating sets + # of ambiguous alternatives, this prediction mode should be avoided when + # the exact results are not necessary.

+ # + #

+ # This prediction mode does not provide any guarantees for prediction + # behavior for syntactically-incorrect inputs.

+ # + LL_EXACT_AMBIG_DETECTION = 2 + + + # + # Computes the SLL prediction termination condition. + # + #

+ # This method computes the SLL prediction termination condition for both of + # the following cases.

+ # + # + # + #

COMBINED SLL+LL PARSING

+ # + #

When LL-fallback is enabled upon SLL conflict, correct predictions are + # ensured regardless of how the termination condition is computed by this + # method. Due to the substantially higher cost of LL prediction, the + # prediction should only fall back to LL when the additional lookahead + # cannot lead to a unique SLL prediction.

+ # + #

Assuming combined SLL+LL parsing, an SLL configuration set with only + # conflicting subsets should fall back to full LL, even if the + # configuration sets don't resolve to the same alternative (e.g. + # {@code {1,2}} and {@code {3,4}}. If there is at least one non-conflicting + # configuration, SLL could continue with the hopes that more lookahead will + # resolve via one of those non-conflicting configurations.

+ # + #

Here's the prediction termination rule them: SLL (for SLL+LL parsing) + # stops when it sees only conflicting configuration subsets. In contrast, + # full LL keeps going when there is uncertainty.

+ # + #

HEURISTIC

+ # + #

As a heuristic, we stop prediction when we see any conflicting subset + # unless we see a state that only has one alternative associated with it. + # The single-alt-state thing lets prediction continue upon rules like + # (otherwise, it would admit defeat too soon):

+ # + #

{@code [12|1|[], 6|2|[], 12|2|[]]. s : (ID | ID ID?) ';' ;}

+ # + #

When the ATN simulation reaches the state before {@code ';'}, it has a + # DFA state that looks like: {@code [12|1|[], 6|2|[], 12|2|[]]}. Naturally + # {@code 12|1|[]} and {@code 12|2|[]} conflict, but we cannot stop + # processing this node because alternative to has another way to continue, + # via {@code [6|2|[]]}.

+ # + #

It also let's us continue for this rule:

+ # + #

{@code [1|1|[], 1|2|[], 8|3|[]] a : A | A | A B ;}

+ # + #

After matching input A, we reach the stop state for rule A, state 1. + # State 8 is the state right before B. Clearly alternatives 1 and 2 + # conflict and no amount of further lookahead will separate the two. + # However, alternative 3 will be able to continue and so we do not stop + # working on this state. In the previous example, we're concerned with + # states associated with the conflicting alternatives. Here alt 3 is not + # associated with the conflicting configs, but since we can continue + # looking for input reasonably, don't declare the state done.

+ # + #

PURE SLL PARSING

+ # + #

To handle pure SLL parsing, all we have to do is make sure that we + # combine stack contexts for configurations that differ only by semantic + # predicate. From there, we can do the usual SLL termination heuristic.

+ # + #

PREDICATES IN SLL+LL PARSING

+ # + #

SLL decisions don't evaluate predicates until after they reach DFA stop + # states because they need to create the DFA cache that works in all + # semantic situations. In contrast, full LL evaluates predicates collected + # during start state computation so it can ignore predicates thereafter. + # This means that SLL termination detection can totally ignore semantic + # predicates.

+ # + #

Implementation-wise, {@link ATNConfigSet} combines stack contexts but not + # semantic predicate contexts so we might see two configurations like the + # following.

+ # + #

{@code (s, 1, x, {}), (s, 1, x', {p})}

+ # + #

Before testing these configurations against others, we have to merge + # {@code x} and {@code x'} (without modifying the existing configurations). + # For example, we test {@code (x+x')==x''} when looking for conflicts in + # the following configurations.

+ # + #

{@code (s, 1, x, {}), (s, 1, x', {p}), (s, 2, x'', {})}

+ # + #

If the configuration set has predicates (as indicated by + # {@link ATNConfigSet#hasSemanticContext}), this algorithm makes a copy of + # the configurations to strip out all of the predicates so that a standard + # {@link ATNConfigSet} will merge everything ignoring predicates.

+ # + @classmethod + def hasSLLConflictTerminatingPrediction(cls, mode:PredictionMode, configs:ATNConfigSet): + # Configs in rule stop states indicate reaching the end of the decision + # rule (local context) or end of start rule (full context). If all + # configs meet this condition, then none of the configurations is able + # to match additional input so we terminate prediction. + # + if cls.allConfigsInRuleStopStates(configs): + return True + + # pure SLL mode parsing + if mode == PredictionMode.SLL: + # Don't bother with combining configs from different semantic + # contexts if we can fail over to full LL; costs more time + # since we'll often fail over anyway. + if configs.hasSemanticContext: + # dup configs, tossing out semantic predicates + dup = ATNConfigSet() + for c in configs: + c = ATNConfig(config=c, semantic=SemanticContext.NONE) + dup.add(c) + configs = dup + # now we have combined contexts for configs with dissimilar preds + + # pure SLL or combined SLL+LL mode parsing + altsets = cls.getConflictingAltSubsets(configs) + return cls.hasConflictingAltSet(altsets) and not cls.hasStateAssociatedWithOneAlt(configs) + + # Checks if any configuration in {@code configs} is in a + # {@link RuleStopState}. Configurations meeting this condition have reached + # the end of the decision rule (local context) or end of start rule (full + # context). + # + # @param configs the configuration set to test + # @return {@code true} if any configuration in {@code configs} is in a + # {@link RuleStopState}, otherwise {@code false} + @classmethod + def hasConfigInRuleStopState(cls, configs:ATNConfigSet): + return any(isinstance(cfg.state, RuleStopState) for cfg in configs) + + # Checks if all configurations in {@code configs} are in a + # {@link RuleStopState}. Configurations meeting this condition have reached + # the end of the decision rule (local context) or end of start rule (full + # context). + # + # @param configs the configuration set to test + # @return {@code true} if all configurations in {@code configs} are in a + # {@link RuleStopState}, otherwise {@code false} + @classmethod + def allConfigsInRuleStopStates(cls, configs:ATNConfigSet): + return all(isinstance(cfg.state, RuleStopState) for cfg in configs) + + # + # Full LL prediction termination. + # + #

Can we stop looking ahead during ATN simulation or is there some + # uncertainty as to which alternative we will ultimately pick, after + # consuming more input? Even if there are partial conflicts, we might know + # that everything is going to resolve to the same minimum alternative. That + # means we can stop since no more lookahead will change that fact. On the + # other hand, there might be multiple conflicts that resolve to different + # minimums. That means we need more look ahead to decide which of those + # alternatives we should predict.

+ # + #

The basic idea is to split the set of configurations {@code C}, into + # conflicting subsets {@code (s, _, ctx, _)} and singleton subsets with + # non-conflicting configurations. Two configurations conflict if they have + # identical {@link ATNConfig#state} and {@link ATNConfig#context} values + # but different {@link ATNConfig#alt} value, e.g. {@code (s, i, ctx, _)} + # and {@code (s, j, ctx, _)} for {@code i!=j}.

+ # + #

Reduce these configuration subsets to the set of possible alternatives. + # You can compute the alternative subsets in one pass as follows:

+ # + #

{@code A_s,ctx = {i | (s, i, ctx, _)}} for each configuration in + # {@code C} holding {@code s} and {@code ctx} fixed.

+ # + #

Or in pseudo-code, for each configuration {@code c} in {@code C}:

+ # + #
+    # map[c] U= c.{@link ATNConfig#alt alt} # map hash/equals uses s and x, not
+    # alt and not pred
+    # 
+ # + #

The values in {@code map} are the set of {@code A_s,ctx} sets.

+ # + #

If {@code |A_s,ctx|=1} then there is no conflict associated with + # {@code s} and {@code ctx}.

+ # + #

Reduce the subsets to singletons by choosing a minimum of each subset. If + # the union of these alternative subsets is a singleton, then no amount of + # more lookahead will help us. We will always pick that alternative. If, + # however, there is more than one alternative, then we are uncertain which + # alternative to predict and must continue looking for resolution. We may + # or may not discover an ambiguity in the future, even if there are no + # conflicting subsets this round.

+ # + #

The biggest sin is to terminate early because it means we've made a + # decision but were uncertain as to the eventual outcome. We haven't used + # enough lookahead. On the other hand, announcing a conflict too late is no + # big deal; you will still have the conflict. It's just inefficient. It + # might even look until the end of file.

+ # + #

No special consideration for semantic predicates is required because + # predicates are evaluated on-the-fly for full LL prediction, ensuring that + # no configuration contains a semantic context during the termination + # check.

+ # + #

CONFLICTING CONFIGS

+ # + #

Two configurations {@code (s, i, x)} and {@code (s, j, x')}, conflict + # when {@code i!=j} but {@code x=x'}. Because we merge all + # {@code (s, i, _)} configurations together, that means that there are at + # most {@code n} configurations associated with state {@code s} for + # {@code n} possible alternatives in the decision. The merged stacks + # complicate the comparison of configuration contexts {@code x} and + # {@code x'}. Sam checks to see if one is a subset of the other by calling + # merge and checking to see if the merged result is either {@code x} or + # {@code x'}. If the {@code x} associated with lowest alternative {@code i} + # is the superset, then {@code i} is the only possible prediction since the + # others resolve to {@code min(i)} as well. However, if {@code x} is + # associated with {@code j>i} then at least one stack configuration for + # {@code j} is not in conflict with alternative {@code i}. The algorithm + # should keep going, looking for more lookahead due to the uncertainty.

+ # + #

For simplicity, I'm doing a equality check between {@code x} and + # {@code x'} that lets the algorithm continue to consume lookahead longer + # than necessary. The reason I like the equality is of course the + # simplicity but also because that is the test you need to detect the + # alternatives that are actually in conflict.

+ # + #

CONTINUE/STOP RULE

+ # + #

Continue if union of resolved alternative sets from non-conflicting and + # conflicting alternative subsets has more than one alternative. We are + # uncertain about which alternative to predict.

+ # + #

The complete set of alternatives, {@code [i for (_,i,_)]}, tells us which + # alternatives are still in the running for the amount of input we've + # consumed at this point. The conflicting sets let us to strip away + # configurations that won't lead to more states because we resolve + # conflicts to the configuration with a minimum alternate for the + # conflicting set.

+ # + #

CASES

+ # + # + # + #

EXACT AMBIGUITY DETECTION

+ # + #

If all states report the same conflicting set of alternatives, then we + # know we have the exact ambiguity set.

+ # + #

|A_i|>1 and + # A_i = A_j for all i, j.

+ # + #

In other words, we continue examining lookahead until all {@code A_i} + # have more than one alternative and all {@code A_i} are the same. If + # {@code A={{1,2}, {1,3}}}, then regular LL prediction would terminate + # because the resolved set is {@code {1}}. To determine what the real + # ambiguity is, we have to know whether the ambiguity is between one and + # two or one and three so we keep going. We can only stop prediction when + # we need exact ambiguity detection when the sets look like + # {@code A={{1,2}}} or {@code {{1,2},{1,2}}}, etc...

+ # + @classmethod + def resolvesToJustOneViableAlt(cls, altsets:list): + return cls.getSingleViableAlt(altsets) + + # + # Determines if every alternative subset in {@code altsets} contains more + # than one alternative. + # + # @param altsets a collection of alternative subsets + # @return {@code true} if every {@link BitSet} in {@code altsets} has + # {@link BitSet#cardinality cardinality} > 1, otherwise {@code false} + # + @classmethod + def allSubsetsConflict(cls, altsets:list): + return not cls.hasNonConflictingAltSet(altsets) + + # + # Determines if any single alternative subset in {@code altsets} contains + # exactly one alternative. + # + # @param altsets a collection of alternative subsets + # @return {@code true} if {@code altsets} contains a {@link BitSet} with + # {@link BitSet#cardinality cardinality} 1, otherwise {@code false} + # + @classmethod + def hasNonConflictingAltSet(cls, altsets:list): + return any(len(alts) == 1 for alts in altsets) + + # + # Determines if any single alternative subset in {@code altsets} contains + # more than one alternative. + # + # @param altsets a collection of alternative subsets + # @return {@code true} if {@code altsets} contains a {@link BitSet} with + # {@link BitSet#cardinality cardinality} > 1, otherwise {@code false} + # + @classmethod + def hasConflictingAltSet(cls, altsets:list): + return any(len(alts) > 1 for alts in altsets) + + # + # Determines if every alternative subset in {@code altsets} is equivalent. + # + # @param altsets a collection of alternative subsets + # @return {@code true} if every member of {@code altsets} is equal to the + # others, otherwise {@code false} + # + @classmethod + def allSubsetsEqual(cls, altsets:list): + if not altsets: + return True + first = next(iter(altsets)) + return all(alts == first for alts in iter(altsets)) + + # + # Returns the unique alternative predicted by all alternative subsets in + # {@code altsets}. If no such alternative exists, this method returns + # {@link ATN#INVALID_ALT_NUMBER}. + # + # @param altsets a collection of alternative subsets + # + @classmethod + def getUniqueAlt(cls, altsets:list): + all = cls.getAlts(altsets) + if len(all)==1: + return next(iter(all)) + return ATN.INVALID_ALT_NUMBER + + # Gets the complete set of represented alternatives for a collection of + # alternative subsets. This method returns the union of each {@link BitSet} + # in {@code altsets}. + # + # @param altsets a collection of alternative subsets + # @return the set of represented alternatives in {@code altsets} + # + @classmethod + def getAlts(cls, altsets:list): + return set.union(*altsets) + + # + # This function gets the conflicting alt subsets from a configuration set. + # For each configuration {@code c} in {@code configs}: + # + #
+    # map[c] U= c.{@link ATNConfig#alt alt} # map hash/equals uses s and x, not
+    # alt and not pred
+    # 
+ # + @classmethod + def getConflictingAltSubsets(cls, configs:ATNConfigSet): + configToAlts = dict() + for c in configs: + h = hash((c.state.stateNumber, c.context)) + alts = configToAlts.get(h, None) + if alts is None: + alts = set() + configToAlts[h] = alts + alts.add(c.alt) + return configToAlts.values() + + # + # Get a map from state to alt subset from a configuration set. For each + # configuration {@code c} in {@code configs}: + # + #
+    # map[c.{@link ATNConfig#state state}] U= c.{@link ATNConfig#alt alt}
+    # 
+ # + @classmethod + def getStateToAltMap(cls, configs:ATNConfigSet): + m = dict() + for c in configs: + alts = m.get(c.state, None) + if alts is None: + alts = set() + m[c.state] = alts + alts.add(c.alt) + return m + + @classmethod + def hasStateAssociatedWithOneAlt(cls, configs:ATNConfigSet): + return any(len(alts) == 1 for alts in cls.getStateToAltMap(configs).values()) + + @classmethod + def getSingleViableAlt(cls, altsets:list): + viableAlts = set() + for alts in altsets: + minAlt = min(alts) + viableAlts.add(minAlt) + if len(viableAlts)>1 : # more than 1 viable alt + return ATN.INVALID_ALT_NUMBER + return min(viableAlts) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/atn/SemanticContext.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/atn/SemanticContext.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4dc31088d35b73304432c46c54e31c1ab92700 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/atn/SemanticContext.py @@ -0,0 +1,323 @@ +# +# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. +# Use of this file is governed by the BSD 3-clause license that +# can be found in the LICENSE.txt file in the project root. +# + +# A tree structure used to record the semantic context in which +# an ATN configuration is valid. It's either a single predicate, +# a conjunction {@code p1&&p2}, or a sum of products {@code p1||p2}. +# +#

I have scoped the {@link AND}, {@link OR}, and {@link Predicate} subclasses of +# {@link SemanticContext} within the scope of this outer class.

+# +from antlr4.Recognizer import Recognizer +from antlr4.RuleContext import RuleContext +from io import StringIO + + +class SemanticContext(object): + # + # The default {@link SemanticContext}, which is semantically equivalent to + # a predicate of the form {@code {true}?}. + # + NONE = None + + # + # For context independent predicates, we evaluate them without a local + # context (i.e., null context). That way, we can evaluate them without + # having to create proper rule-specific context during prediction (as + # opposed to the parser, which creates them naturally). In a practical + # sense, this avoids a cast exception from RuleContext to myruleContext. + # + #

For context dependent predicates, we must pass in a local context so that + # references such as $arg evaluate properly as _localctx.arg. We only + # capture context dependent predicates in the context in which we begin + # prediction, so we passed in the outer context here in case of context + # dependent predicate evaluation.

+ # + def eval(self, parser:Recognizer , outerContext:RuleContext ): + pass + + # + # Evaluate the precedence predicates for the context and reduce the result. + # + # @param parser The parser instance. + # @param outerContext The current parser context object. + # @return The simplified semantic context after precedence predicates are + # evaluated, which will be one of the following values. + # + # + def evalPrecedence(self, parser:Recognizer, outerContext:RuleContext): + return self + +# need forward declaration +AND = None + +def andContext(a:SemanticContext, b:SemanticContext): + if a is None or a is SemanticContext.NONE: + return b + if b is None or b is SemanticContext.NONE: + return a + result = AND(a, b) + if len(result.opnds) == 1: + return result.opnds[0] + else: + return result + +# need forward declaration +OR = None + +def orContext(a:SemanticContext, b:SemanticContext): + if a is None: + return b + if b is None: + return a + if a is SemanticContext.NONE or b is SemanticContext.NONE: + return SemanticContext.NONE + result = OR(a, b) + if len(result.opnds) == 1: + return result.opnds[0] + else: + return result + +def filterPrecedencePredicates(collection:set): + return [context for context in collection if isinstance(context, PrecedencePredicate)] + + +class Predicate(SemanticContext): + __slots__ = ('ruleIndex', 'predIndex', 'isCtxDependent') + + def __init__(self, ruleIndex:int=-1, predIndex:int=-1, isCtxDependent:bool=False): + self.ruleIndex = ruleIndex + self.predIndex = predIndex + self.isCtxDependent = isCtxDependent # e.g., $i ref in pred + + def eval(self, parser:Recognizer , outerContext:RuleContext ): + localctx = outerContext if self.isCtxDependent else None + return parser.sempred(localctx, self.ruleIndex, self.predIndex) + + def __hash__(self): + return hash((self.ruleIndex, self.predIndex, self.isCtxDependent)) + + def __eq__(self, other): + if self is other: + return True + elif not isinstance(other, Predicate): + return False + return self.ruleIndex == other.ruleIndex and \ + self.predIndex == other.predIndex and \ + self.isCtxDependent == other.isCtxDependent + + def __str__(self): + return "{" + str(self.ruleIndex) + ":" + str(self.predIndex) + "}?" + + +class PrecedencePredicate(SemanticContext): + + def __init__(self, precedence:int=0): + self.precedence = precedence + + def eval(self, parser:Recognizer , outerContext:RuleContext ): + return parser.precpred(outerContext, self.precedence) + + def evalPrecedence(self, parser:Recognizer, outerContext:RuleContext): + if parser.precpred(outerContext, self.precedence): + return SemanticContext.NONE + else: + return None + + def __lt__(self, other): + return self.precedence < other.precedence + + def __hash__(self): + return 31 + + def __eq__(self, other): + if self is other: + return True + elif not isinstance(other, PrecedencePredicate): + return False + else: + return self.precedence == other.precedence + +# A semantic context which is true whenever none of the contained contexts +# is false. +del AND +class AND(SemanticContext): + __slots__ = 'opnds' + + def __init__(self, a:SemanticContext, b:SemanticContext): + operands = set() + if isinstance( a, AND ): + operands.update(a.opnds) + else: + operands.add(a) + if isinstance( b, AND ): + operands.update(b.opnds) + else: + operands.add(b) + + precedencePredicates = filterPrecedencePredicates(operands) + if len(precedencePredicates)>0: + # interested in the transition with the lowest precedence + reduced = min(precedencePredicates) + operands.add(reduced) + + self.opnds = list(operands) + + def __eq__(self, other): + if self is other: + return True + elif not isinstance(other, AND): + return False + else: + return self.opnds == other.opnds + + def __hash__(self): + h = 0 + for o in self.opnds: + h = hash((h, o)) + return hash((h, "AND")) + + # + # {@inheritDoc} + # + #

+ # The evaluation of predicates by this context is short-circuiting, but + # unordered.

+ # + def eval(self, parser:Recognizer, outerContext:RuleContext): + return all(opnd.eval(parser, outerContext) for opnd in self.opnds) + + def evalPrecedence(self, parser:Recognizer, outerContext:RuleContext): + differs = False + operands = [] + for context in self.opnds: + evaluated = context.evalPrecedence(parser, outerContext) + differs |= evaluated is not context + if evaluated is None: + # The AND context is false if any element is false + return None + elif evaluated is not SemanticContext.NONE: + # Reduce the result by skipping true elements + operands.append(evaluated) + + if not differs: + return self + + if len(operands)==0: + # all elements were true, so the AND context is true + return SemanticContext.NONE + + result = None + for o in operands: + result = o if result is None else andContext(result, o) + + return result + + def __str__(self): + with StringIO() as buf: + first = True + for o in self.opnds: + if not first: + buf.write("&&") + buf.write(str(o)) + first = False + return buf.getvalue() + +# +# A semantic context which is true whenever at least one of the contained +# contexts is true. +del OR +class OR (SemanticContext): + __slots__ = 'opnds' + + def __init__(self, a:SemanticContext, b:SemanticContext): + operands = set() + if isinstance( a, OR ): + operands.update(a.opnds) + else: + operands.add(a) + if isinstance( b, OR ): + operands.update(b.opnds) + else: + operands.add(b) + + precedencePredicates = filterPrecedencePredicates(operands) + if len(precedencePredicates)>0: + # interested in the transition with the highest precedence + s = sorted(precedencePredicates) + reduced = s[-1] + operands.add(reduced) + + self.opnds = list(operands) + + def __eq__(self, other): + if self is other: + return True + elif not isinstance(other, OR): + return False + else: + return self.opnds == other.opnds + + def __hash__(self): + h = 0 + for o in self.opnds: + h = hash((h, o)) + return hash((h, "OR")) + + #

+ # The evaluation of predicates by this context is short-circuiting, but + # unordered.

+ # + def eval(self, parser:Recognizer, outerContext:RuleContext): + return any(opnd.eval(parser, outerContext) for opnd in self.opnds) + + def evalPrecedence(self, parser:Recognizer, outerContext:RuleContext): + differs = False + operands = [] + for context in self.opnds: + evaluated = context.evalPrecedence(parser, outerContext) + differs |= evaluated is not context + if evaluated is SemanticContext.NONE: + # The OR context is true if any element is true + return SemanticContext.NONE + elif evaluated is not None: + # Reduce the result by skipping false elements + operands.append(evaluated) + + if not differs: + return self + + if len(operands)==0: + # all elements were false, so the OR context is false + return None + + result = None + for o in operands: + result = o if result is None else orContext(result, o) + + return result + + def __str__(self): + with StringIO() as buf: + first = True + for o in self.opnds: + if not first: + buf.write("||") + buf.write(str(o)) + first = False + return buf.getvalue() + + +SemanticContext.NONE = Predicate() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/atn/Transition.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/atn/Transition.py new file mode 100644 index 0000000000000000000000000000000000000000..2e4c9971763c34dbb2690660434c5c99d44193e1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/atn/Transition.py @@ -0,0 +1,268 @@ +# +# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. +# Use of this file is governed by the BSD 3-clause license that +# can be found in the LICENSE.txt file in the project root. +# + +# An ATN transition between any two ATN states. Subclasses define +# atom, set, epsilon, action, predicate, rule transitions. +# +#

This is a one way link. It emanates from a state (usually via a list of +# transitions) and has a target state.

+# +#

Since we never have to change the ATN transitions once we construct it, +# we can fix these transitions as specific classes. The DFA transitions +# on the other hand need to update the labels as it adds transitions to +# the states. We'll use the term Edge for the DFA to distinguish them from +# ATN transitions.

+# +from antlr4.IntervalSet import IntervalSet +from antlr4.Token import Token + +# need forward declarations +from antlr4.atn.SemanticContext import Predicate, PrecedencePredicate + +ATNState = None +RuleStartState = None + +class Transition (object): + __slots__ = ('target','isEpsilon','label') + + # constants for serialization + EPSILON = 1 + RANGE = 2 + RULE = 3 + PREDICATE = 4 # e.g., {isType(input.LT(1))}? + ATOM = 5 + ACTION = 6 + SET = 7 # ~(A|B) or ~atom, wildcard, which convert to next 2 + NOT_SET = 8 + WILDCARD = 9 + PRECEDENCE = 10 + + serializationNames = [ + "INVALID", + "EPSILON", + "RANGE", + "RULE", + "PREDICATE", + "ATOM", + "ACTION", + "SET", + "NOT_SET", + "WILDCARD", + "PRECEDENCE" + ] + + serializationTypes = dict() + + def __init__(self, target:ATNState): + # The target of this transition. + if target is None: + raise Exception("target cannot be null.") + self.target = target + # Are we epsilon, action, sempred? + self.isEpsilon = False + self.label = None + + +# TODO: make all transitions sets? no, should remove set edges +class AtomTransition(Transition): + __slots__ = ('label_', 'serializationType') + + def __init__(self, target:ATNState, label:int): + super().__init__(target) + self.label_ = label # The token type or character value; or, signifies special label. + self.label = self.makeLabel() + self.serializationType = self.ATOM + + def makeLabel(self): + s = IntervalSet() + s.addOne(self.label_) + return s + + def matches( self, symbol:int, minVocabSymbol:int, maxVocabSymbol:int): + return self.label_ == symbol + + def __str__(self): + return str(self.label_) + +class RuleTransition(Transition): + __slots__ = ('ruleIndex', 'precedence', 'followState', 'serializationType') + + def __init__(self, ruleStart:RuleStartState, ruleIndex:int, precedence:int, followState:ATNState): + super().__init__(ruleStart) + self.ruleIndex = ruleIndex # ptr to the rule definition object for this rule ref + self.precedence = precedence + self.followState = followState # what node to begin computations following ref to rule + self.serializationType = self.RULE + self.isEpsilon = True + + def matches( self, symbol:int, minVocabSymbol:int, maxVocabSymbol:int): + return False + + +class EpsilonTransition(Transition): + __slots__ = ('serializationType', 'outermostPrecedenceReturn') + + def __init__(self, target, outermostPrecedenceReturn=-1): + super(EpsilonTransition, self).__init__(target) + self.serializationType = self.EPSILON + self.isEpsilon = True + self.outermostPrecedenceReturn = outermostPrecedenceReturn + + def matches( self, symbol:int, minVocabSymbol:int, maxVocabSymbol:int): + return False + + def __str__(self): + return "epsilon" + +class RangeTransition(Transition): + __slots__ = ('serializationType', 'start', 'stop') + + def __init__(self, target:ATNState, start:int, stop:int): + super().__init__(target) + self.serializationType = self.RANGE + self.start = start + self.stop = stop + self.label = self.makeLabel() + + def makeLabel(self): + s = IntervalSet() + s.addRange(range(self.start, self.stop + 1)) + return s + + def matches( self, symbol:int, minVocabSymbol:int, maxVocabSymbol:int): + return symbol >= self.start and symbol <= self.stop + + def __str__(self): + return "'" + chr(self.start) + "'..'" + chr(self.stop) + "'" + +class AbstractPredicateTransition(Transition): + + def __init__(self, target:ATNState): + super().__init__(target) + + +class PredicateTransition(AbstractPredicateTransition): + __slots__ = ('serializationType', 'ruleIndex', 'predIndex', 'isCtxDependent') + + def __init__(self, target:ATNState, ruleIndex:int, predIndex:int, isCtxDependent:bool): + super().__init__(target) + self.serializationType = self.PREDICATE + self.ruleIndex = ruleIndex + self.predIndex = predIndex + self.isCtxDependent = isCtxDependent # e.g., $i ref in pred + self.isEpsilon = True + + def matches( self, symbol:int, minVocabSymbol:int, maxVocabSymbol:int): + return False + + def getPredicate(self): + return Predicate(self.ruleIndex, self.predIndex, self.isCtxDependent) + + def __str__(self): + return "pred_" + str(self.ruleIndex) + ":" + str(self.predIndex) + +class ActionTransition(Transition): + __slots__ = ('serializationType', 'ruleIndex', 'actionIndex', 'isCtxDependent') + + def __init__(self, target:ATNState, ruleIndex:int, actionIndex:int=-1, isCtxDependent:bool=False): + super().__init__(target) + self.serializationType = self.ACTION + self.ruleIndex = ruleIndex + self.actionIndex = actionIndex + self.isCtxDependent = isCtxDependent # e.g., $i ref in pred + self.isEpsilon = True + + def matches( self, symbol:int, minVocabSymbol:int, maxVocabSymbol:int): + return False + + def __str__(self): + return "action_"+self.ruleIndex+":"+self.actionIndex + +# A transition containing a set of values. +class SetTransition(Transition): + __slots__ = 'serializationType' + + def __init__(self, target:ATNState, set:IntervalSet): + super().__init__(target) + self.serializationType = self.SET + if set is not None: + self.label = set + else: + self.label = IntervalSet() + self.label.addRange(range(Token.INVALID_TYPE, Token.INVALID_TYPE + 1)) + + def matches( self, symbol:int, minVocabSymbol:int, maxVocabSymbol:int): + return symbol in self.label + + def __str__(self): + return str(self.label) + +class NotSetTransition(SetTransition): + + def __init__(self, target:ATNState, set:IntervalSet): + super().__init__(target, set) + self.serializationType = self.NOT_SET + + def matches( self, symbol:int, minVocabSymbol:int, maxVocabSymbol:int): + return symbol >= minVocabSymbol \ + and symbol <= maxVocabSymbol \ + and not super(type(self), self).matches(symbol, minVocabSymbol, maxVocabSymbol) + + def __str__(self): + return '~' + super(type(self), self).__str__() + + +class WildcardTransition(Transition): + __slots__ = 'serializationType' + + def __init__(self, target:ATNState): + super().__init__(target) + self.serializationType = self.WILDCARD + + def matches( self, symbol:int, minVocabSymbol:int, maxVocabSymbol:int): + return symbol >= minVocabSymbol and symbol <= maxVocabSymbol + + def __str__(self): + return "." + + +class PrecedencePredicateTransition(AbstractPredicateTransition): + __slots__ = ('serializationType', 'precedence') + + def __init__(self, target:ATNState, precedence:int): + super().__init__(target) + self.serializationType = self.PRECEDENCE + self.precedence = precedence + self.isEpsilon = True + + def matches( self, symbol:int, minVocabSymbol:int, maxVocabSymbol:int): + return False + + + def getPredicate(self): + return PrecedencePredicate(self.precedence) + + def __str__(self): + return self.precedence + " >= _p" + + +Transition.serializationTypes = { + EpsilonTransition: Transition.EPSILON, + RangeTransition: Transition.RANGE, + RuleTransition: Transition.RULE, + PredicateTransition: Transition.PREDICATE, + AtomTransition: Transition.ATOM, + ActionTransition: Transition.ACTION, + SetTransition: Transition.SET, + NotSetTransition: Transition.NOT_SET, + WildcardTransition: Transition.WILDCARD, + PrecedencePredicateTransition: Transition.PRECEDENCE + } + +del ATNState +del RuleStartState + +from antlr4.atn.ATNState import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/atn/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/atn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..216c000dc5ffc8e53cc9c596e420c1e67604d1aa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/atn/__init__.py @@ -0,0 +1 @@ +__author__ = 'ericvergnaud' diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/dfa/DFA.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/dfa/DFA.py new file mode 100644 index 0000000000000000000000000000000000000000..d80589a6834a48cc6bb718bf33f57156e32ec934 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/dfa/DFA.py @@ -0,0 +1,133 @@ +# +# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. +# Use of this file is governed by the BSD 3-clause license that +# can be found in the LICENSE.txt file in the project root. +from antlr4.atn.ATNState import StarLoopEntryState + +from antlr4.atn.ATNConfigSet import ATNConfigSet +from antlr4.atn.ATNState import DecisionState +from antlr4.dfa.DFAState import DFAState +from antlr4.error.Errors import IllegalStateException + + +class DFA(object): + __slots__ = ('atnStartState', 'decision', '_states', 's0', 'precedenceDfa') + + def __init__(self, atnStartState:DecisionState, decision:int=0): + # From which ATN state did we create this DFA? + self.atnStartState = atnStartState + self.decision = decision + # A set of all DFA states. Use {@link Map} so we can get old state back + # ({@link Set} only allows you to see if it's there). + self._states = dict() + self.s0 = None + # {@code true} if this DFA is for a precedence decision; otherwise, + # {@code false}. This is the backing field for {@link #isPrecedenceDfa}, + # {@link #setPrecedenceDfa}. + self.precedenceDfa = False + + if isinstance(atnStartState, StarLoopEntryState): + if atnStartState.isPrecedenceDecision: + self.precedenceDfa = True + precedenceState = DFAState(configs=ATNConfigSet()) + precedenceState.edges = [] + precedenceState.isAcceptState = False + precedenceState.requiresFullContext = False + self.s0 = precedenceState + + + # Get the start state for a specific precedence value. + # + # @param precedence The current precedence. + # @return The start state corresponding to the specified precedence, or + # {@code null} if no start state exists for the specified precedence. + # + # @throws IllegalStateException if this is not a precedence DFA. + # @see #isPrecedenceDfa() + + def getPrecedenceStartState(self, precedence:int): + if not self.precedenceDfa: + raise IllegalStateException("Only precedence DFAs may contain a precedence start state.") + + # s0.edges is never null for a precedence DFA + if precedence < 0 or precedence >= len(self.s0.edges): + return None + return self.s0.edges[precedence] + + # Set the start state for a specific precedence value. + # + # @param precedence The current precedence. + # @param startState The start state corresponding to the specified + # precedence. + # + # @throws IllegalStateException if this is not a precedence DFA. + # @see #isPrecedenceDfa() + # + def setPrecedenceStartState(self, precedence:int, startState:DFAState): + if not self.precedenceDfa: + raise IllegalStateException("Only precedence DFAs may contain a precedence start state.") + + if precedence < 0: + return + + # synchronization on s0 here is ok. when the DFA is turned into a + # precedence DFA, s0 will be initialized once and not updated again + # s0.edges is never null for a precedence DFA + if precedence >= len(self.s0.edges): + ext = [None] * (precedence + 1 - len(self.s0.edges)) + self.s0.edges.extend(ext) + self.s0.edges[precedence] = startState + # + # Sets whether this is a precedence DFA. If the specified value differs + # from the current DFA configuration, the following actions are taken; + # otherwise no changes are made to the current DFA. + # + # + # + # @param precedenceDfa {@code true} if this is a precedence DFA; otherwise, + # {@code false} + + def setPrecedenceDfa(self, precedenceDfa:bool): + if self.precedenceDfa != precedenceDfa: + self._states = dict() + if precedenceDfa: + precedenceState = DFAState(configs=ATNConfigSet()) + precedenceState.edges = [] + precedenceState.isAcceptState = False + precedenceState.requiresFullContext = False + self.s0 = precedenceState + else: + self.s0 = None + self.precedenceDfa = precedenceDfa + + @property + def states(self): + return self._states + + # Return a list of all states in this DFA, ordered by state number. + def sortedStates(self): + return sorted(self._states.keys(), key=lambda state: state.stateNumber) + + def __str__(self): + return self.toString(None) + + def toString(self, literalNames:list=None, symbolicNames:list=None): + if self.s0 is None: + return "" + from antlr4.dfa.DFASerializer import DFASerializer + serializer = DFASerializer(self,literalNames,symbolicNames) + return str(serializer) + + def toLexerString(self): + if self.s0 is None: + return "" + from antlr4.dfa.DFASerializer import LexerDFASerializer + serializer = LexerDFASerializer(self) + return str(serializer) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/dfa/DFASerializer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/dfa/DFASerializer.py new file mode 100644 index 0000000000000000000000000000000000000000..bca0727b76dc54909be0bf60b6d636ec8f539927 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/dfa/DFASerializer.py @@ -0,0 +1,73 @@ +# +# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. +# Use of this file is governed by the BSD 3-clause license that +# can be found in the LICENSE.txt file in the project root. +#/ + +# A DFA walker that knows how to dump them to serialized strings.#/ +from io import StringIO +from antlr4 import DFA +from antlr4.Utils import str_list +from antlr4.dfa.DFAState import DFAState + + +class DFASerializer(object): + __slots__ = ('dfa', 'literalNames', 'symbolicNames') + + def __init__(self, dfa:DFA, literalNames:list=None, symbolicNames:list=None): + self.dfa = dfa + self.literalNames = literalNames + self.symbolicNames = symbolicNames + + def __str__(self): + if self.dfa.s0 is None: + return None + with StringIO() as buf: + for s in self.dfa.sortedStates(): + n = 0 + if s.edges is not None: + n = len(s.edges) + for i in range(0, n): + t = s.edges[i] + if t is not None and t.stateNumber != 0x7FFFFFFF: + buf.write(self.getStateString(s)) + label = self.getEdgeLabel(i) + buf.write("-") + buf.write(label) + buf.write("->") + buf.write(self.getStateString(t)) + buf.write('\n') + output = buf.getvalue() + if len(output)==0: + return None + else: + return output + + def getEdgeLabel(self, i:int): + if i==0: + return "EOF" + if self.literalNames is not None and i<=len(self.literalNames): + return self.literalNames[i-1] + elif self.symbolicNames is not None and i<=len(self.symbolicNames): + return self.symbolicNames[i-1] + else: + return str(i-1) + + def getStateString(self, s:DFAState): + n = s.stateNumber + baseStateStr = ( ":" if s.isAcceptState else "") + "s" + str(n) + ( "^" if s.requiresFullContext else "") + if s.isAcceptState: + if s.predicates is not None: + return baseStateStr + "=>" + str_list(s.predicates) + else: + return baseStateStr + "=>" + str(s.prediction) + else: + return baseStateStr + +class LexerDFASerializer(DFASerializer): + + def __init__(self, dfa:DFA): + super().__init__(dfa, None) + + def getEdgeLabel(self, i:int): + return "'" + chr(i) + "'" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/dfa/DFAState.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/dfa/DFAState.py new file mode 100644 index 0000000000000000000000000000000000000000..51955a448886ea1fa34f0f4dff7fb0976edd1975 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/dfa/DFAState.py @@ -0,0 +1,126 @@ +# +# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. +# Use of this file is governed by the BSD 3-clause license that +# can be found in the LICENSE.txt file in the project root. +#/ + +# Map a predicate to a predicted alternative.#/ +from io import StringIO +from antlr4.atn.ATNConfigSet import ATNConfigSet +from antlr4.atn.SemanticContext import SemanticContext + + +class PredPrediction(object): + __slots__ = ('alt', 'pred') + + def __init__(self, pred:SemanticContext, alt:int): + self.alt = alt + self.pred = pred + + def __str__(self): + return "(" + str(self.pred) + ", " + str(self.alt) + ")" + +# A DFA state represents a set of possible ATN configurations. +# As Aho, Sethi, Ullman p. 117 says "The DFA uses its state +# to keep track of all possible states the ATN can be in after +# reading each input symbol. That is to say, after reading +# input a1a2..an, the DFA is in a state that represents the +# subset T of the states of the ATN that are reachable from the +# ATN's start state along some path labeled a1a2..an." +# In conventional NFA→DFA conversion, therefore, the subset T +# would be a bitset representing the set of states the +# ATN could be in. We need to track the alt predicted by each +# state as well, however. More importantly, we need to maintain +# a stack of states, tracking the closure operations as they +# jump from rule to rule, emulating rule invocations (method calls). +# I have to add a stack to simulate the proper lookahead sequences for +# the underlying LL grammar from which the ATN was derived. +# +#

I use a set of ATNConfig objects not simple states. An ATNConfig +# is both a state (ala normal conversion) and a RuleContext describing +# the chain of rules (if any) followed to arrive at that state.

+# +#

A DFA state may have multiple references to a particular state, +# but with different ATN contexts (with same or different alts) +# meaning that state was reached via a different set of rule invocations.

+#/ +class DFAState(object): + __slots__ = ( + 'stateNumber', 'configs', 'edges', 'isAcceptState', 'prediction', + 'lexerActionExecutor', 'requiresFullContext', 'predicates' + ) + + def __init__(self, stateNumber:int=-1, configs:ATNConfigSet=ATNConfigSet()): + self.stateNumber = stateNumber + self.configs = configs + # {@code edges[symbol]} points to target of symbol. Shift up by 1 so (-1) + # {@link Token#EOF} maps to {@code edges[0]}. + self.edges = None + self.isAcceptState = False + # if accept state, what ttype do we match or alt do we predict? + # This is set to {@link ATN#INVALID_ALT_NUMBER} when {@link #predicates}{@code !=null} or + # {@link #requiresFullContext}. + self.prediction = 0 + self.lexerActionExecutor = None + # Indicates that this state was created during SLL prediction that + # discovered a conflict between the configurations in the state. Future + # {@link ParserATNSimulator#execATN} invocations immediately jumped doing + # full context prediction if this field is true. + self.requiresFullContext = False + # During SLL parsing, this is a list of predicates associated with the + # ATN configurations of the DFA state. When we have predicates, + # {@link #requiresFullContext} is {@code false} since full context prediction evaluates predicates + # on-the-fly. If this is not null, then {@link #prediction} is + # {@link ATN#INVALID_ALT_NUMBER}. + # + #

We only use these for non-{@link #requiresFullContext} but conflicting states. That + # means we know from the context (it's $ or we don't dip into outer + # context) that it's an ambiguity not a conflict.

+ # + #

This list is computed by {@link ParserATNSimulator#predicateDFAState}.

+ self.predicates = None + + + + # Get the set of all alts mentioned by all ATN configurations in this + # DFA state. + def getAltSet(self): + if self.configs is not None: + return set(cfg.alt for cfg in self.configs) or None + return None + + def __hash__(self): + return hash(self.configs) + + # Two {@link DFAState} instances are equal if their ATN configuration sets + # are the same. This method is used to see if a state already exists. + # + #

Because the number of alternatives and number of ATN configurations are + # finite, there is a finite number of DFA states that can be processed. + # This is necessary to show that the algorithm terminates.

+ # + #

Cannot test the DFA state numbers here because in + # {@link ParserATNSimulator#addDFAState} we need to know if any other state + # exists that has this exact set of ATN configurations. The + # {@link #stateNumber} is irrelevant.

+ def __eq__(self, other): + # compare set of ATN configurations in this set with other + if self is other: + return True + elif not isinstance(other, DFAState): + return False + else: + return self.configs==other.configs + + def __str__(self): + with StringIO() as buf: + buf.write(str(self.stateNumber)) + buf.write(":") + buf.write(str(self.configs)) + if self.isAcceptState: + buf.write("=>") + if self.predicates is not None: + buf.write(str(self.predicates)) + else: + buf.write(str(self.prediction)) + return buf.getvalue() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/dfa/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/dfa/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..216c000dc5ffc8e53cc9c596e420c1e67604d1aa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/dfa/__init__.py @@ -0,0 +1 @@ +__author__ = 'ericvergnaud' diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/error/DiagnosticErrorListener.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/error/DiagnosticErrorListener.py new file mode 100644 index 0000000000000000000000000000000000000000..32ac14b63579ce7c984c2e34f2b1c80bebe328ed --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/error/DiagnosticErrorListener.py @@ -0,0 +1,107 @@ +# +# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. +# Use of this file is governed by the BSD 3-clause license that +# can be found in the LICENSE.txt file in the project root. +# + + +# +# This implementation of {@link ANTLRErrorListener} can be used to identify +# certain potential correctness and performance problems in grammars. "Reports" +# are made by calling {@link Parser#notifyErrorListeners} with the appropriate +# message. +# +# + +from io import StringIO +from antlr4 import Parser, DFA +from antlr4.atn.ATNConfigSet import ATNConfigSet +from antlr4.error.ErrorListener import ErrorListener + +class DiagnosticErrorListener(ErrorListener): + + def __init__(self, exactOnly:bool=True): + # whether all ambiguities or only exact ambiguities are reported. + self.exactOnly = exactOnly + + def reportAmbiguity(self, recognizer:Parser, dfa:DFA, startIndex:int, + stopIndex:int, exact:bool, ambigAlts:set, configs:ATNConfigSet): + if self.exactOnly and not exact: + return + + with StringIO() as buf: + buf.write("reportAmbiguity d=") + buf.write(self.getDecisionDescription(recognizer, dfa)) + buf.write(": ambigAlts=") + buf.write(str(self.getConflictingAlts(ambigAlts, configs))) + buf.write(", input='") + buf.write(recognizer.getTokenStream().getText(startIndex, stopIndex)) + buf.write("'") + recognizer.notifyErrorListeners(buf.getvalue()) + + + def reportAttemptingFullContext(self, recognizer:Parser, dfa:DFA, startIndex:int, + stopIndex:int, conflictingAlts:set, configs:ATNConfigSet): + with StringIO() as buf: + buf.write("reportAttemptingFullContext d=") + buf.write(self.getDecisionDescription(recognizer, dfa)) + buf.write(", input='") + buf.write(recognizer.getTokenStream().getText(startIndex, stopIndex)) + buf.write("'") + recognizer.notifyErrorListeners(buf.getvalue()) + + def reportContextSensitivity(self, recognizer:Parser, dfa:DFA, startIndex:int, + stopIndex:int, prediction:int, configs:ATNConfigSet): + with StringIO() as buf: + buf.write("reportContextSensitivity d=") + buf.write(self.getDecisionDescription(recognizer, dfa)) + buf.write(", input='") + buf.write(recognizer.getTokenStream().getText(startIndex, stopIndex)) + buf.write("'") + recognizer.notifyErrorListeners(buf.getvalue()) + + def getDecisionDescription(self, recognizer:Parser, dfa:DFA): + decision = dfa.decision + ruleIndex = dfa.atnStartState.ruleIndex + + ruleNames = recognizer.ruleNames + if ruleIndex < 0 or ruleIndex >= len(ruleNames): + return str(decision) + + ruleName = ruleNames[ruleIndex] + if ruleName is None or len(ruleName)==0: + return str(decision) + + return str(decision) + " (" + ruleName + ")" + + # + # Computes the set of conflicting or ambiguous alternatives from a + # configuration set, if that information was not already provided by the + # parser. + # + # @param reportedAlts The set of conflicting or ambiguous alternatives, as + # reported by the parser. + # @param configs The conflicting or ambiguous configuration set. + # @return Returns {@code reportedAlts} if it is not {@code null}, otherwise + # returns the set of alternatives represented in {@code configs}. + # + def getConflictingAlts(self, reportedAlts:set, configs:ATNConfigSet): + if reportedAlts is not None: + return reportedAlts + + result = set() + for config in configs: + result.add(config.alt) + + return result diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/error/ErrorListener.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/error/ErrorListener.py new file mode 100644 index 0000000000000000000000000000000000000000..933264d431b9829f43a38d5f0f07c83bbad703a0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/error/ErrorListener.py @@ -0,0 +1,72 @@ +# +# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. +# Use of this file is governed by the BSD 3-clause license that +# can be found in the LICENSE.txt file in the project root. + +# Provides an empty default implementation of {@link ANTLRErrorListener}. The +# default implementation of each method does nothing, but can be overridden as +# necessary. + + +import sys + +class ErrorListener(object): + + def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e): + pass + + def reportAmbiguity(self, recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs): + pass + + def reportAttemptingFullContext(self, recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs): + pass + + def reportContextSensitivity(self, recognizer, dfa, startIndex, stopIndex, prediction, configs): + pass + +class ConsoleErrorListener(ErrorListener): + # + # Provides a default instance of {@link ConsoleErrorListener}. + # + INSTANCE = None + + # + # {@inheritDoc} + # + #

+ # This implementation prints messages to {@link System#err} containing the + # values of {@code line}, {@code charPositionInLine}, and {@code msg} using + # the following format.

+ # + #
+    # line line:charPositionInLine msg
+    # 
+ # + def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e): + print("line " + str(line) + ":" + str(column) + " " + msg, file=sys.stderr) + +ConsoleErrorListener.INSTANCE = ConsoleErrorListener() + +class ProxyErrorListener(ErrorListener): + + def __init__(self, delegates): + super().__init__() + if delegates is None: + raise ReferenceError("delegates") + self.delegates = delegates + + def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e): + for delegate in self.delegates: + delegate.syntaxError(recognizer, offendingSymbol, line, column, msg, e) + + def reportAmbiguity(self, recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs): + for delegate in self.delegates: + delegate.reportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) + + def reportAttemptingFullContext(self, recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs): + for delegate in self.delegates: + delegate.reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) + + def reportContextSensitivity(self, recognizer, dfa, startIndex, stopIndex, prediction, configs): + for delegate in self.delegates: + delegate.reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/error/ErrorStrategy.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/error/ErrorStrategy.py new file mode 100644 index 0000000000000000000000000000000000000000..0f7caadb240445e6d997ad582a51836f95cab5c5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/error/ErrorStrategy.py @@ -0,0 +1,709 @@ +# +# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. +# Use of this file is governed by the BSD 3-clause license that +# can be found in the LICENSE.txt file in the project root. +# +import sys +from antlr4.IntervalSet import IntervalSet + +from antlr4.Token import Token +from antlr4.atn.ATNState import ATNState +from antlr4.error.Errors import RecognitionException, NoViableAltException, InputMismatchException, \ + FailedPredicateException, ParseCancellationException + +# need forward declaration +Parser = None + +class ErrorStrategy(object): + + def reset(self, recognizer:Parser): + pass + + def recoverInline(self, recognizer:Parser): + pass + + def recover(self, recognizer:Parser, e:RecognitionException): + pass + + def sync(self, recognizer:Parser): + pass + + def inErrorRecoveryMode(self, recognizer:Parser): + pass + + def reportError(self, recognizer:Parser, e:RecognitionException): + pass + + +# This is the default implementation of {@link ANTLRErrorStrategy} used for +# error reporting and recovery in ANTLR parsers. +# +class DefaultErrorStrategy(ErrorStrategy): + + def __init__(self): + super().__init__() + # Indicates whether the error strategy is currently "recovering from an + # error". This is used to suppress reporting multiple error messages while + # attempting to recover from a detected syntax error. + # + # @see #inErrorRecoveryMode + # + self.errorRecoveryMode = False + + # The index into the input stream where the last error occurred. + # This is used to prevent infinite loops where an error is found + # but no token is consumed during recovery...another error is found, + # ad nauseum. This is a failsafe mechanism to guarantee that at least + # one token/tree node is consumed for two errors. + # + self.lastErrorIndex = -1 + self.lastErrorStates = None + self.nextTokensContext = None + self.nextTokenState = 0 + + #

The default implementation simply calls {@link #endErrorCondition} to + # ensure that the handler is not in error recovery mode.

+ def reset(self, recognizer:Parser): + self.endErrorCondition(recognizer) + + # + # This method is called to enter error recovery mode when a recognition + # exception is reported. + # + # @param recognizer the parser instance + # + def beginErrorCondition(self, recognizer:Parser): + self.errorRecoveryMode = True + + def inErrorRecoveryMode(self, recognizer:Parser): + return self.errorRecoveryMode + + # + # This method is called to leave error recovery mode after recovering from + # a recognition exception. + # + # @param recognizer + # + def endErrorCondition(self, recognizer:Parser): + self.errorRecoveryMode = False + self.lastErrorStates = None + self.lastErrorIndex = -1 + + # + # {@inheritDoc} + # + #

The default implementation simply calls {@link #endErrorCondition}.

+ # + def reportMatch(self, recognizer:Parser): + self.endErrorCondition(recognizer) + + # + # {@inheritDoc} + # + #

The default implementation returns immediately if the handler is already + # in error recovery mode. Otherwise, it calls {@link #beginErrorCondition} + # and dispatches the reporting task based on the runtime type of {@code e} + # according to the following table.

+ # + # + # + def reportError(self, recognizer:Parser, e:RecognitionException): + # if we've already reported an error and have not matched a token + # yet successfully, don't report any errors. + if self.inErrorRecoveryMode(recognizer): + return # don't report spurious errors + self.beginErrorCondition(recognizer) + if isinstance( e, NoViableAltException ): + self.reportNoViableAlternative(recognizer, e) + elif isinstance( e, InputMismatchException ): + self.reportInputMismatch(recognizer, e) + elif isinstance( e, FailedPredicateException ): + self.reportFailedPredicate(recognizer, e) + else: + print("unknown recognition error type: " + type(e).__name__) + recognizer.notifyErrorListeners(e.message, e.offendingToken, e) + + # + # {@inheritDoc} + # + #

The default implementation resynchronizes the parser by consuming tokens + # until we find one in the resynchronization set--loosely the set of tokens + # that can follow the current rule.

+ # + def recover(self, recognizer:Parser, e:RecognitionException): + if self.lastErrorIndex==recognizer.getInputStream().index \ + and self.lastErrorStates is not None \ + and recognizer.state in self.lastErrorStates: + # uh oh, another error at same token index and previously-visited + # state in ATN; must be a case where LT(1) is in the recovery + # token set so nothing got consumed. Consume a single token + # at least to prevent an infinite loop; this is a failsafe. + recognizer.consume() + + self.lastErrorIndex = recognizer._input.index + if self.lastErrorStates is None: + self.lastErrorStates = [] + self.lastErrorStates.append(recognizer.state) + followSet = self.getErrorRecoverySet(recognizer) + self.consumeUntil(recognizer, followSet) + + # The default implementation of {@link ANTLRErrorStrategy#sync} makes sure + # that the current lookahead symbol is consistent with what were expecting + # at this point in the ATN. You can call this anytime but ANTLR only + # generates code to check before subrules/loops and each iteration. + # + #

Implements Jim Idle's magic sync mechanism in closures and optional + # subrules. E.g.,

+ # + #
+    # a : sync ( stuff sync )* ;
+    # sync : {consume to what can follow sync} ;
+    # 
+ # + # At the start of a sub rule upon error, {@link #sync} performs single + # token deletion, if possible. If it can't do that, it bails on the current + # rule and uses the default error recovery, which consumes until the + # resynchronization set of the current rule. + # + #

If the sub rule is optional ({@code (...)?}, {@code (...)*}, or block + # with an empty alternative), then the expected set includes what follows + # the subrule.

+ # + #

During loop iteration, it consumes until it sees a token that can start a + # sub rule or what follows loop. Yes, that is pretty aggressive. We opt to + # stay in the loop as long as possible.

+ # + #

ORIGINS

+ # + #

Previous versions of ANTLR did a poor job of their recovery within loops. + # A single mismatch token or missing token would force the parser to bail + # out of the entire rules surrounding the loop. So, for rule

+ # + #
+    # classDef : 'class' ID '{' member* '}'
+    # 
+ # + # input with an extra token between members would force the parser to + # consume until it found the next class definition rather than the next + # member definition of the current class. + # + #

This functionality cost a little bit of effort because the parser has to + # compare token set at the start of the loop and at each iteration. If for + # some reason speed is suffering for you, you can turn off this + # functionality by simply overriding this method as a blank { }.

+ # + def sync(self, recognizer:Parser): + # If already recovering, don't try to sync + if self.inErrorRecoveryMode(recognizer): + return + + s = recognizer._interp.atn.states[recognizer.state] + la = recognizer.getTokenStream().LA(1) + # try cheaper subset first; might get lucky. seems to shave a wee bit off + nextTokens = recognizer.atn.nextTokens(s) + if la in nextTokens: + self.nextTokensContext = None + self.nextTokenState = ATNState.INVALID_STATE_NUMBER + return + elif Token.EPSILON in nextTokens: + if self.nextTokensContext is None: + # It's possible the next token won't match information tracked + # by sync is restricted for performance. + self.nextTokensContext = recognizer._ctx + self.nextTokensState = recognizer._stateNumber + return + + if s.stateType in [ATNState.BLOCK_START, ATNState.STAR_BLOCK_START, + ATNState.PLUS_BLOCK_START, ATNState.STAR_LOOP_ENTRY]: + # report error and recover if possible + if self.singleTokenDeletion(recognizer)is not None: + return + else: + raise InputMismatchException(recognizer) + + elif s.stateType in [ATNState.PLUS_LOOP_BACK, ATNState.STAR_LOOP_BACK]: + self.reportUnwantedToken(recognizer) + expecting = recognizer.getExpectedTokens() + whatFollowsLoopIterationOrRule = expecting.addSet(self.getErrorRecoverySet(recognizer)) + self.consumeUntil(recognizer, whatFollowsLoopIterationOrRule) + + else: + # do nothing if we can't identify the exact kind of ATN state + pass + + # This is called by {@link #reportError} when the exception is a + # {@link NoViableAltException}. + # + # @see #reportError + # + # @param recognizer the parser instance + # @param e the recognition exception + # + def reportNoViableAlternative(self, recognizer:Parser, e:NoViableAltException): + tokens = recognizer.getTokenStream() + if tokens is not None: + if e.startToken.type==Token.EOF: + input = "" + else: + input = tokens.getText(e.startToken, e.offendingToken) + else: + input = "" + msg = "no viable alternative at input " + self.escapeWSAndQuote(input) + recognizer.notifyErrorListeners(msg, e.offendingToken, e) + + # + # This is called by {@link #reportError} when the exception is an + # {@link InputMismatchException}. + # + # @see #reportError + # + # @param recognizer the parser instance + # @param e the recognition exception + # + def reportInputMismatch(self, recognizer:Parser, e:InputMismatchException): + msg = "mismatched input " + self.getTokenErrorDisplay(e.offendingToken) \ + + " expecting " + e.getExpectedTokens().toString(recognizer.literalNames, recognizer.symbolicNames) + recognizer.notifyErrorListeners(msg, e.offendingToken, e) + + # + # This is called by {@link #reportError} when the exception is a + # {@link FailedPredicateException}. + # + # @see #reportError + # + # @param recognizer the parser instance + # @param e the recognition exception + # + def reportFailedPredicate(self, recognizer, e): + ruleName = recognizer.ruleNames[recognizer._ctx.getRuleIndex()] + msg = "rule " + ruleName + " " + e.message + recognizer.notifyErrorListeners(msg, e.offendingToken, e) + + # This method is called to report a syntax error which requires the removal + # of a token from the input stream. At the time this method is called, the + # erroneous symbol is current {@code LT(1)} symbol and has not yet been + # removed from the input stream. When this method returns, + # {@code recognizer} is in error recovery mode. + # + #

This method is called when {@link #singleTokenDeletion} identifies + # single-token deletion as a viable recovery strategy for a mismatched + # input error.

+ # + #

The default implementation simply returns if the handler is already in + # error recovery mode. Otherwise, it calls {@link #beginErrorCondition} to + # enter error recovery mode, followed by calling + # {@link Parser#notifyErrorListeners}.

+ # + # @param recognizer the parser instance + # + def reportUnwantedToken(self, recognizer:Parser): + if self.inErrorRecoveryMode(recognizer): + return + + self.beginErrorCondition(recognizer) + t = recognizer.getCurrentToken() + tokenName = self.getTokenErrorDisplay(t) + expecting = self.getExpectedTokens(recognizer) + msg = "extraneous input " + tokenName + " expecting " \ + + expecting.toString(recognizer.literalNames, recognizer.symbolicNames) + recognizer.notifyErrorListeners(msg, t, None) + + # This method is called to report a syntax error which requires the + # insertion of a missing token into the input stream. At the time this + # method is called, the missing token has not yet been inserted. When this + # method returns, {@code recognizer} is in error recovery mode. + # + #

This method is called when {@link #singleTokenInsertion} identifies + # single-token insertion as a viable recovery strategy for a mismatched + # input error.

+ # + #

The default implementation simply returns if the handler is already in + # error recovery mode. Otherwise, it calls {@link #beginErrorCondition} to + # enter error recovery mode, followed by calling + # {@link Parser#notifyErrorListeners}.

+ # + # @param recognizer the parser instance + # + def reportMissingToken(self, recognizer:Parser): + if self.inErrorRecoveryMode(recognizer): + return + self.beginErrorCondition(recognizer) + t = recognizer.getCurrentToken() + expecting = self.getExpectedTokens(recognizer) + msg = "missing " + expecting.toString(recognizer.literalNames, recognizer.symbolicNames) \ + + " at " + self.getTokenErrorDisplay(t) + recognizer.notifyErrorListeners(msg, t, None) + + #

The default implementation attempts to recover from the mismatched input + # by using single token insertion and deletion as described below. If the + # recovery attempt fails, this method throws an + # {@link InputMismatchException}.

+ # + #

EXTRA TOKEN (single token deletion)

+ # + #

{@code LA(1)} is not what we are looking for. If {@code LA(2)} has the + # right token, however, then assume {@code LA(1)} is some extra spurious + # token and delete it. Then consume and return the next token (which was + # the {@code LA(2)} token) as the successful result of the match operation.

+ # + #

This recovery strategy is implemented by {@link #singleTokenDeletion}.

+ # + #

MISSING TOKEN (single token insertion)

+ # + #

If current token (at {@code LA(1)}) is consistent with what could come + # after the expected {@code LA(1)} token, then assume the token is missing + # and use the parser's {@link TokenFactory} to create it on the fly. The + # "insertion" is performed by returning the created token as the successful + # result of the match operation.

+ # + #

This recovery strategy is implemented by {@link #singleTokenInsertion}.

+ # + #

EXAMPLE

+ # + #

For example, Input {@code i=(3;} is clearly missing the {@code ')'}. When + # the parser returns from the nested call to {@code expr}, it will have + # call chain:

+ # + #
+    # stat → expr → atom
+    # 
+ # + # and it will be trying to match the {@code ')'} at this point in the + # derivation: + # + #
+    # => ID '=' '(' INT ')' ('+' atom)* ';'
+    #                    ^
+    # 
+ # + # The attempt to match {@code ')'} will fail when it sees {@code ';'} and + # call {@link #recoverInline}. To recover, it sees that {@code LA(1)==';'} + # is in the set of tokens that can follow the {@code ')'} token reference + # in rule {@code atom}. It can assume that you forgot the {@code ')'}. + # + def recoverInline(self, recognizer:Parser): + # SINGLE TOKEN DELETION + matchedSymbol = self.singleTokenDeletion(recognizer) + if matchedSymbol is not None: + # we have deleted the extra token. + # now, move past ttype token as if all were ok + recognizer.consume() + return matchedSymbol + + # SINGLE TOKEN INSERTION + if self.singleTokenInsertion(recognizer): + return self.getMissingSymbol(recognizer) + + # even that didn't work; must throw the exception + raise InputMismatchException(recognizer) + + # + # This method implements the single-token insertion inline error recovery + # strategy. It is called by {@link #recoverInline} if the single-token + # deletion strategy fails to recover from the mismatched input. If this + # method returns {@code true}, {@code recognizer} will be in error recovery + # mode. + # + #

This method determines whether or not single-token insertion is viable by + # checking if the {@code LA(1)} input symbol could be successfully matched + # if it were instead the {@code LA(2)} symbol. If this method returns + # {@code true}, the caller is responsible for creating and inserting a + # token with the correct type to produce this behavior.

+ # + # @param recognizer the parser instance + # @return {@code true} if single-token insertion is a viable recovery + # strategy for the current mismatched input, otherwise {@code false} + # + def singleTokenInsertion(self, recognizer:Parser): + currentSymbolType = recognizer.getTokenStream().LA(1) + # if current token is consistent with what could come after current + # ATN state, then we know we're missing a token; error recovery + # is free to conjure up and insert the missing token + atn = recognizer._interp.atn + currentState = atn.states[recognizer.state] + next = currentState.transitions[0].target + expectingAtLL2 = atn.nextTokens(next, recognizer._ctx) + if currentSymbolType in expectingAtLL2: + self.reportMissingToken(recognizer) + return True + else: + return False + + # This method implements the single-token deletion inline error recovery + # strategy. It is called by {@link #recoverInline} to attempt to recover + # from mismatched input. If this method returns null, the parser and error + # handler state will not have changed. If this method returns non-null, + # {@code recognizer} will not be in error recovery mode since the + # returned token was a successful match. + # + #

If the single-token deletion is successful, this method calls + # {@link #reportUnwantedToken} to report the error, followed by + # {@link Parser#consume} to actually "delete" the extraneous token. Then, + # before returning {@link #reportMatch} is called to signal a successful + # match.

+ # + # @param recognizer the parser instance + # @return the successfully matched {@link Token} instance if single-token + # deletion successfully recovers from the mismatched input, otherwise + # {@code null} + # + def singleTokenDeletion(self, recognizer:Parser): + nextTokenType = recognizer.getTokenStream().LA(2) + expecting = self.getExpectedTokens(recognizer) + if nextTokenType in expecting: + self.reportUnwantedToken(recognizer) + # print("recoverFromMismatchedToken deleting " \ + # + str(recognizer.getTokenStream().LT(1)) \ + # + " since " + str(recognizer.getTokenStream().LT(2)) \ + # + " is what we want", file=sys.stderr) + recognizer.consume() # simply delete extra token + # we want to return the token we're actually matching + matchedSymbol = recognizer.getCurrentToken() + self.reportMatch(recognizer) # we know current token is correct + return matchedSymbol + else: + return None + + # Conjure up a missing token during error recovery. + # + # The recognizer attempts to recover from single missing + # symbols. But, actions might refer to that missing symbol. + # For example, x=ID {f($x);}. The action clearly assumes + # that there has been an identifier matched previously and that + # $x points at that token. If that token is missing, but + # the next token in the stream is what we want we assume that + # this token is missing and we keep going. Because we + # have to return some token to replace the missing token, + # we have to conjure one up. This method gives the user control + # over the tokens returned for missing tokens. Mostly, + # you will want to create something special for identifier + # tokens. For literals such as '{' and ',', the default + # action in the parser or tree parser works. It simply creates + # a CommonToken of the appropriate type. The text will be the token. + # If you change what tokens must be created by the lexer, + # override this method to create the appropriate tokens. + # + def getMissingSymbol(self, recognizer:Parser): + currentSymbol = recognizer.getCurrentToken() + expecting = self.getExpectedTokens(recognizer) + expectedTokenType = expecting[0] # get any element + if expectedTokenType==Token.EOF: + tokenText = "" + else: + name = None + if expectedTokenType < len(recognizer.literalNames): + name = recognizer.literalNames[expectedTokenType] + if name is None and expectedTokenType < len(recognizer.symbolicNames): + name = recognizer.symbolicNames[expectedTokenType] + tokenText = "" + current = currentSymbol + lookback = recognizer.getTokenStream().LT(-1) + if current.type==Token.EOF and lookback is not None: + current = lookback + return recognizer.getTokenFactory().create(current.source, + expectedTokenType, tokenText, Token.DEFAULT_CHANNEL, + -1, -1, current.line, current.column) + + def getExpectedTokens(self, recognizer:Parser): + return recognizer.getExpectedTokens() + + # How should a token be displayed in an error message? The default + # is to display just the text, but during development you might + # want to have a lot of information spit out. Override in that case + # to use t.toString() (which, for CommonToken, dumps everything about + # the token). This is better than forcing you to override a method in + # your token objects because you don't have to go modify your lexer + # so that it creates a new Java type. + # + def getTokenErrorDisplay(self, t:Token): + if t is None: + return "" + s = t.text + if s is None: + if t.type==Token.EOF: + s = "" + else: + s = "<" + str(t.type) + ">" + return self.escapeWSAndQuote(s) + + def escapeWSAndQuote(self, s:str): + s = s.replace("\n","\\n") + s = s.replace("\r","\\r") + s = s.replace("\t","\\t") + return "'" + s + "'" + + # Compute the error recovery set for the current rule. During + # rule invocation, the parser pushes the set of tokens that can + # follow that rule reference on the stack; this amounts to + # computing FIRST of what follows the rule reference in the + # enclosing rule. See LinearApproximator.FIRST(). + # This local follow set only includes tokens + # from within the rule; i.e., the FIRST computation done by + # ANTLR stops at the end of a rule. + # + # EXAMPLE + # + # When you find a "no viable alt exception", the input is not + # consistent with any of the alternatives for rule r. The best + # thing to do is to consume tokens until you see something that + # can legally follow a call to r#or* any rule that called r. + # You don't want the exact set of viable next tokens because the + # input might just be missing a token--you might consume the + # rest of the input looking for one of the missing tokens. + # + # Consider grammar: + # + # a : '[' b ']' + # | '(' b ')' + # ; + # b : c '^' INT ; + # c : ID + # | INT + # ; + # + # At each rule invocation, the set of tokens that could follow + # that rule is pushed on a stack. Here are the various + # context-sensitive follow sets: + # + # FOLLOW(b1_in_a) = FIRST(']') = ']' + # FOLLOW(b2_in_a) = FIRST(')') = ')' + # FOLLOW(c_in_b) = FIRST('^') = '^' + # + # Upon erroneous input "[]", the call chain is + # + # a -> b -> c + # + # and, hence, the follow context stack is: + # + # depth follow set start of rule execution + # 0 a (from main()) + # 1 ']' b + # 2 '^' c + # + # Notice that ')' is not included, because b would have to have + # been called from a different context in rule a for ')' to be + # included. + # + # For error recovery, we cannot consider FOLLOW(c) + # (context-sensitive or otherwise). We need the combined set of + # all context-sensitive FOLLOW sets--the set of all tokens that + # could follow any reference in the call chain. We need to + # resync to one of those tokens. Note that FOLLOW(c)='^' and if + # we resync'd to that token, we'd consume until EOF. We need to + # sync to context-sensitive FOLLOWs for a, b, and c: {']','^'}. + # In this case, for input "[]", LA(1) is ']' and in the set, so we would + # not consume anything. After printing an error, rule c would + # return normally. Rule b would not find the required '^' though. + # At this point, it gets a mismatched token error and throws an + # exception (since LA(1) is not in the viable following token + # set). The rule exception handler tries to recover, but finds + # the same recovery set and doesn't consume anything. Rule b + # exits normally returning to rule a. Now it finds the ']' (and + # with the successful match exits errorRecovery mode). + # + # So, you can see that the parser walks up the call chain looking + # for the token that was a member of the recovery set. + # + # Errors are not generated in errorRecovery mode. + # + # ANTLR's error recovery mechanism is based upon original ideas: + # + # "Algorithms + Data Structures = Programs" by Niklaus Wirth + # + # and + # + # "A note on error recovery in recursive descent parsers": + # http:#portal.acm.org/citation.cfm?id=947902.947905 + # + # Later, Josef Grosch had some good ideas: + # + # "Efficient and Comfortable Error Recovery in Recursive Descent + # Parsers": + # ftp:#www.cocolab.com/products/cocktail/doca4.ps/ell.ps.zip + # + # Like Grosch I implement context-sensitive FOLLOW sets that are combined + # at run-time upon error to avoid overhead during parsing. + # + def getErrorRecoverySet(self, recognizer:Parser): + atn = recognizer._interp.atn + ctx = recognizer._ctx + recoverSet = IntervalSet() + while ctx is not None and ctx.invokingState>=0: + # compute what follows who invoked us + invokingState = atn.states[ctx.invokingState] + rt = invokingState.transitions[0] + follow = atn.nextTokens(rt.followState) + recoverSet.addSet(follow) + ctx = ctx.parentCtx + recoverSet.removeOne(Token.EPSILON) + return recoverSet + + # Consume tokens until one matches the given token set.# + def consumeUntil(self, recognizer:Parser, set_:set): + ttype = recognizer.getTokenStream().LA(1) + while ttype != Token.EOF and not ttype in set_: + recognizer.consume() + ttype = recognizer.getTokenStream().LA(1) + + +# +# This implementation of {@link ANTLRErrorStrategy} responds to syntax errors +# by immediately canceling the parse operation with a +# {@link ParseCancellationException}. The implementation ensures that the +# {@link ParserRuleContext#exception} field is set for all parse tree nodes +# that were not completed prior to encountering the error. +# +#

+# This error strategy is useful in the following scenarios.

+# +#
    +#
  • Two-stage parsing: This error strategy allows the first +# stage of two-stage parsing to immediately terminate if an error is +# encountered, and immediately fall back to the second stage. In addition to +# avoiding wasted work by attempting to recover from errors here, the empty +# implementation of {@link BailErrorStrategy#sync} improves the performance of +# the first stage.
  • +#
  • Silent validation: When syntax errors are not being +# reported or logged, and the parse result is simply ignored if errors occur, +# the {@link BailErrorStrategy} avoids wasting work on recovering from errors +# when the result will be ignored either way.
  • +#
+# +#

+# {@code myparser.setErrorHandler(new BailErrorStrategy());}

+# +# @see Parser#setErrorHandler(ANTLRErrorStrategy) +# +class BailErrorStrategy(DefaultErrorStrategy): + # Instead of recovering from exception {@code e}, re-throw it wrapped + # in a {@link ParseCancellationException} so it is not caught by the + # rule function catches. Use {@link Exception#getCause()} to get the + # original {@link RecognitionException}. + # + def recover(self, recognizer:Parser, e:RecognitionException): + context = recognizer._ctx + while context is not None: + context.exception = e + context = context.parentCtx + raise ParseCancellationException(e) + + # Make sure we don't attempt to recover inline; if the parser + # successfully recovers, it won't throw an exception. + # + def recoverInline(self, recognizer:Parser): + self.recover(recognizer, InputMismatchException(recognizer)) + + # Make sure we don't attempt to recover from problems in subrules.# + def sync(self, recognizer:Parser): + pass + +del Parser \ No newline at end of file diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/error/Errors.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/error/Errors.py new file mode 100644 index 0000000000000000000000000000000000000000..e78ac05911d3c9569441fe376ff7d6c686c05c95 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/error/Errors.py @@ -0,0 +1,172 @@ +# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. +# Use of this file is governed by the BSD 3-clause license that +# can be found in the LICENSE.txt file in the project root. +# + +# need forward declaration +Token = None +Lexer = None +Parser = None +TokenStream = None +ATNConfigSet = None +ParserRulecontext = None +PredicateTransition = None +BufferedTokenStream = None + +class UnsupportedOperationException(Exception): + + def __init__(self, msg:str): + super().__init__(msg) + +class IllegalStateException(Exception): + + def __init__(self, msg:str): + super().__init__(msg) + +class CancellationException(IllegalStateException): + + def __init__(self, msg:str): + super().__init__(msg) + +# The root of the ANTLR exception hierarchy. In general, ANTLR tracks just +# 3 kinds of errors: prediction errors, failed predicate errors, and +# mismatched input errors. In each case, the parser knows where it is +# in the input, where it is in the ATN, the rule invocation stack, +# and what kind of problem occurred. + +from antlr4.InputStream import InputStream +from antlr4.ParserRuleContext import ParserRuleContext +from antlr4.Recognizer import Recognizer + +class RecognitionException(Exception): + + + def __init__(self, message:str=None, recognizer:Recognizer=None, input:InputStream=None, ctx:ParserRulecontext=None): + super().__init__(message) + self.message = message + self.recognizer = recognizer + self.input = input + self.ctx = ctx + # The current {@link Token} when an error occurred. Since not all streams + # support accessing symbols by index, we have to track the {@link Token} + # instance itself. + self.offendingToken = None + # Get the ATN state number the parser was in at the time the error + # occurred. For {@link NoViableAltException} and + # {@link LexerNoViableAltException} exceptions, this is the + # {@link DecisionState} number. For others, it is the state whose outgoing + # edge we couldn't match. + self.offendingState = -1 + if recognizer is not None: + self.offendingState = recognizer.state + + #

If the state number is not known, this method returns -1.

+ + # + # Gets the set of input symbols which could potentially follow the + # previously matched symbol at the time this exception was thrown. + # + #

If the set of expected tokens is not known and could not be computed, + # this method returns {@code null}.

+ # + # @return The set of token types that could potentially follow the current + # state in the ATN, or {@code null} if the information is not available. + #/ + def getExpectedTokens(self): + if self.recognizer is not None: + return self.recognizer.atn.getExpectedTokens(self.offendingState, self.ctx) + else: + return None + + +class LexerNoViableAltException(RecognitionException): + + def __init__(self, lexer:Lexer, input:InputStream, startIndex:int, deadEndConfigs:ATNConfigSet): + super().__init__(message=None, recognizer=lexer, input=input, ctx=None) + self.startIndex = startIndex + self.deadEndConfigs = deadEndConfigs + + def __str__(self): + symbol = "" + if self.startIndex >= 0 and self.startIndex < self.input.size: + symbol = self.input.getText(self.startIndex, self.startIndex) + # TODO symbol = Utils.escapeWhitespace(symbol, false); + return "LexerNoViableAltException('" + symbol + "')" + +# Indicates that the parser could not decide which of two or more paths +# to take based upon the remaining input. It tracks the starting token +# of the offending input and also knows where the parser was +# in the various paths when the error. Reported by reportNoViableAlternative() +# +class NoViableAltException(RecognitionException): + + def __init__(self, recognizer:Parser, input:TokenStream=None, startToken:Token=None, + offendingToken:Token=None, deadEndConfigs:ATNConfigSet=None, ctx:ParserRuleContext=None): + if ctx is None: + ctx = recognizer._ctx + if offendingToken is None: + offendingToken = recognizer.getCurrentToken() + if startToken is None: + startToken = recognizer.getCurrentToken() + if input is None: + input = recognizer.getInputStream() + super().__init__(recognizer=recognizer, input=input, ctx=ctx) + # Which configurations did we try at input.index() that couldn't match input.LT(1)?# + self.deadEndConfigs = deadEndConfigs + # The token object at the start index; the input stream might + # not be buffering tokens so get a reference to it. (At the + # time the error occurred, of course the stream needs to keep a + # buffer all of the tokens but later we might not have access to those.) + self.startToken = startToken + self.offendingToken = offendingToken + +# This signifies any kind of mismatched input exceptions such as +# when the current input does not match the expected token. +# +class InputMismatchException(RecognitionException): + + def __init__(self, recognizer:Parser): + super().__init__(recognizer=recognizer, input=recognizer.getInputStream(), ctx=recognizer._ctx) + self.offendingToken = recognizer.getCurrentToken() + + +# A semantic predicate failed during validation. Validation of predicates +# occurs when normally parsing the alternative just like matching a token. +# Disambiguating predicate evaluation occurs when we test a predicate during +# prediction. + +class FailedPredicateException(RecognitionException): + + def __init__(self, recognizer:Parser, predicate:str=None, message:str=None): + super().__init__(message=self.formatMessage(predicate,message), recognizer=recognizer, + input=recognizer.getInputStream(), ctx=recognizer._ctx) + s = recognizer._interp.atn.states[recognizer.state] + trans = s.transitions[0] + from antlr4.atn.Transition import PredicateTransition + if isinstance(trans, PredicateTransition): + self.ruleIndex = trans.ruleIndex + self.predicateIndex = trans.predIndex + else: + self.ruleIndex = 0 + self.predicateIndex = 0 + self.predicate = predicate + self.offendingToken = recognizer.getCurrentToken() + + def formatMessage(self, predicate:str, message:str): + if message is not None: + return message + else: + return "failed predicate: {" + predicate + "}?" + +class ParseCancellationException(CancellationException): + + pass + +del Token +del Lexer +del Parser +del TokenStream +del ATNConfigSet +del ParserRulecontext +del PredicateTransition +del BufferedTokenStream diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/error/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/error/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..216c000dc5ffc8e53cc9c596e420c1e67604d1aa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/error/__init__.py @@ -0,0 +1 @@ +__author__ = 'ericvergnaud' diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/Chunk.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/Chunk.py new file mode 100644 index 0000000000000000000000000000000000000000..081419a34f65463b370b848b141192bfe491befd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/Chunk.py @@ -0,0 +1,30 @@ +# +# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. +# Use of this file is governed by the BSD 3-clause license that +# can be found in the LICENSE.txt file in the project root. +# + +class Chunk(object): + pass + +class TagChunk(Chunk): + __slots__ = ('tag', 'label') + + def __init__(self, tag:str, label:str=None): + self.tag = tag + self.label = label + + def __str__(self): + if self.label is None: + return self.tag + else: + return self.label + ":" + self.tag + +class TextChunk(Chunk): + __slots__ = 'text' + + def __init__(self, text:str): + self.text = text + + def __str__(self): + return "'" + self.text + "'" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/ParseTreeMatch.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/ParseTreeMatch.py new file mode 100644 index 0000000000000000000000000000000000000000..c02bc0357d26b343a72307cda77ff62fe307a44a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/ParseTreeMatch.py @@ -0,0 +1,118 @@ +# +# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. +# Use of this file is governed by the BSD 3-clause license that +# can be found in the LICENSE.txt file in the project root. +# + + +# +# Represents the result of matching a {@link ParseTree} against a tree pattern. +# +from io import StringIO +from antlr4.tree.ParseTreePattern import ParseTreePattern +from antlr4.tree.Tree import ParseTree + + +class ParseTreeMatch(object): + __slots__ = ('tree', 'pattern', 'labels', 'mismatchedNode') + # + # Constructs a new instance of {@link ParseTreeMatch} from the specified + # parse tree and pattern. + # + # @param tree The parse tree to match against the pattern. + # @param pattern The parse tree pattern. + # @param labels A mapping from label names to collections of + # {@link ParseTree} objects located by the tree pattern matching process. + # @param mismatchedNode The first node which failed to match the tree + # pattern during the matching process. + # + # @exception IllegalArgumentException if {@code tree} is {@code null} + # @exception IllegalArgumentException if {@code pattern} is {@code null} + # @exception IllegalArgumentException if {@code labels} is {@code null} + # + def __init__(self, tree:ParseTree, pattern:ParseTreePattern, labels:dict, mismatchedNode:ParseTree): + if tree is None: + raise Exception("tree cannot be null") + if pattern is None: + raise Exception("pattern cannot be null") + if labels is None: + raise Exception("labels cannot be null") + self.tree = tree + self.pattern = pattern + self.labels = labels + self.mismatchedNode = mismatchedNode + + # + # Get the last node associated with a specific {@code label}. + # + #

For example, for pattern {@code }, {@code get("id")} returns the + # node matched for that {@code ID}. If more than one node + # matched the specified label, only the last is returned. If there is + # no node associated with the label, this returns {@code null}.

+ # + #

Pattern tags like {@code } and {@code } without labels are + # considered to be labeled with {@code ID} and {@code expr}, respectively.

+ # + # @param label The label to check. + # + # @return The last {@link ParseTree} to match a tag with the specified + # label, or {@code null} if no parse tree matched a tag with the label. + # + def get(self, label:str): + parseTrees = self.labels.get(label, None) + if parseTrees is None or len(parseTrees)==0: + return None + else: + return parseTrees[len(parseTrees)-1] + + # + # Return all nodes matching a rule or token tag with the specified label. + # + #

If the {@code label} is the name of a parser rule or token in the + # grammar, the resulting list will contain both the parse trees matching + # rule or tags explicitly labeled with the label and the complete set of + # parse trees matching the labeled and unlabeled tags in the pattern for + # the parser rule or token. For example, if {@code label} is {@code "foo"}, + # the result will contain all of the following.

+ # + #
    + #
  • Parse tree nodes matching tags of the form {@code } and + # {@code }.
  • + #
  • Parse tree nodes matching tags of the form {@code }.
  • + #
  • Parse tree nodes matching tags of the form {@code }.
  • + #
+ # + # @param label The label. + # + # @return A collection of all {@link ParseTree} nodes matching tags with + # the specified {@code label}. If no nodes matched the label, an empty list + # is returned. + # + def getAll(self, label:str): + nodes = self.labels.get(label, None) + if nodes is None: + return list() + else: + return nodes + + + # + # Gets a value indicating whether the match operation succeeded. + # + # @return {@code true} if the match operation succeeded; otherwise, + # {@code false}. + # + def succeeded(self): + return self.mismatchedNode is None + + # + # {@inheritDoc} + # + def __str__(self): + with StringIO() as buf: + buf.write("Match ") + buf.write("succeeded" if self.succeeded() else "failed") + buf.write("; found ") + buf.write(str(len(self.labels))) + buf.write(" labels") + return buf.getvalue() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/ParseTreePattern.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/ParseTreePattern.py new file mode 100644 index 0000000000000000000000000000000000000000..37fd0bf09f478d47f927b3fdf7d7a32da1c0b795 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/ParseTreePattern.py @@ -0,0 +1,72 @@ +# +# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. +# Use of this file is governed by the BSD 3-clause license that +# can be found in the LICENSE.txt file in the project root. +# + +# +# A pattern like {@code = ;} converted to a {@link ParseTree} by +# {@link ParseTreePatternMatcher#compile(String, int)}. +# +from antlr4.tree.ParseTreePatternMatcher import ParseTreePatternMatcher +from antlr4.tree.Tree import ParseTree +from antlr4.xpath.XPath import XPath + + +class ParseTreePattern(object): + __slots__ = ('matcher', 'patternRuleIndex', 'pattern', 'patternTree') + + # Construct a new instance of the {@link ParseTreePattern} class. + # + # @param matcher The {@link ParseTreePatternMatcher} which created this + # tree pattern. + # @param pattern The tree pattern in concrete syntax form. + # @param patternRuleIndex The parser rule which serves as the root of the + # tree pattern. + # @param patternTree The tree pattern in {@link ParseTree} form. + # + def __init__(self, matcher:ParseTreePatternMatcher, pattern:str, patternRuleIndex:int , patternTree:ParseTree): + self.matcher = matcher + self.patternRuleIndex = patternRuleIndex + self.pattern = pattern + self.patternTree = patternTree + + # + # Match a specific parse tree against this tree pattern. + # + # @param tree The parse tree to match against this tree pattern. + # @return A {@link ParseTreeMatch} object describing the result of the + # match operation. The {@link ParseTreeMatch#succeeded()} method can be + # used to determine whether or not the match was successful. + # + def match(self, tree:ParseTree): + return self.matcher.match(tree, self) + + # + # Determine whether or not a parse tree matches this tree pattern. + # + # @param tree The parse tree to match against this tree pattern. + # @return {@code true} if {@code tree} is a match for the current tree + # pattern; otherwise, {@code false}. + # + def matches(self, tree:ParseTree): + return self.matcher.match(tree, self).succeeded() + + # Find all nodes using XPath and then try to match those subtrees against + # this tree pattern. + # + # @param tree The {@link ParseTree} to match against this pattern. + # @param xpath An expression matching the nodes + # + # @return A collection of {@link ParseTreeMatch} objects describing the + # successful matches. Unsuccessful matches are omitted from the result, + # regardless of the reason for the failure. + # + def findAll(self, tree:ParseTree, xpath:str): + subtrees = XPath.findAll(tree, xpath, self.matcher.parser) + matches = list() + for t in subtrees: + match = self.match(t) + if match.succeeded(): + matches.append(match) + return matches diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/ParseTreePatternMatcher.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/ParseTreePatternMatcher.py new file mode 100644 index 0000000000000000000000000000000000000000..62fd197b0d143393fa187ead9b0c576112b486be --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/ParseTreePatternMatcher.py @@ -0,0 +1,374 @@ +# +# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. +# Use of this file is governed by the BSD 3-clause license that +# can be found in the LICENSE.txt file in the project root. +# + +# +# A tree pattern matching mechanism for ANTLR {@link ParseTree}s. +# +#

Patterns are strings of source input text with special tags representing +# token or rule references such as:

+# +#

{@code = ;}

+# +#

Given a pattern start rule such as {@code statement}, this object constructs +# a {@link ParseTree} with placeholders for the {@code ID} and {@code expr} +# subtree. Then the {@link #match} routines can compare an actual +# {@link ParseTree} from a parse with this pattern. Tag {@code } matches +# any {@code ID} token and tag {@code } references the result of the +# {@code expr} rule (generally an instance of {@code ExprContext}.

+# +#

Pattern {@code x = 0;} is a similar pattern that matches the same pattern +# except that it requires the identifier to be {@code x} and the expression to +# be {@code 0}.

+# +#

The {@link #matches} routines return {@code true} or {@code false} based +# upon a match for the tree rooted at the parameter sent in. The +# {@link #match} routines return a {@link ParseTreeMatch} object that +# contains the parse tree, the parse tree pattern, and a map from tag name to +# matched nodes (more below). A subtree that fails to match, returns with +# {@link ParseTreeMatch#mismatchedNode} set to the first tree node that did not +# match.

+# +#

For efficiency, you can compile a tree pattern in string form to a +# {@link ParseTreePattern} object.

+# +#

See {@code TestParseTreeMatcher} for lots of examples. +# {@link ParseTreePattern} has two static helper methods: +# {@link ParseTreePattern#findAll} and {@link ParseTreePattern#match} that +# are easy to use but not super efficient because they create new +# {@link ParseTreePatternMatcher} objects each time and have to compile the +# pattern in string form before using it.

+# +#

The lexer and parser that you pass into the {@link ParseTreePatternMatcher} +# constructor are used to parse the pattern in string form. The lexer converts +# the {@code = ;} into a sequence of four tokens (assuming lexer +# throws out whitespace or puts it on a hidden channel). Be aware that the +# input stream is reset for the lexer (but not the parser; a +# {@link ParserInterpreter} is created to parse the input.). Any user-defined +# fields you have put into the lexer might get changed when this mechanism asks +# it to scan the pattern string.

+# +#

Normally a parser does not accept token {@code } as a valid +# {@code expr} but, from the parser passed in, we create a special version of +# the underlying grammar representation (an {@link ATN}) that allows imaginary +# tokens representing rules ({@code }) to match entire rules. We call +# these bypass alternatives.

+# +#

Delimiters are {@code <} and {@code >}, with {@code \} as the escape string +# by default, but you can set them to whatever you want using +# {@link #setDelimiters}. You must escape both start and stop strings +# {@code \<} and {@code \>}.

+# +from antlr4.CommonTokenStream import CommonTokenStream +from antlr4.InputStream import InputStream +from antlr4.ParserRuleContext import ParserRuleContext +from antlr4.Lexer import Lexer +from antlr4.ListTokenSource import ListTokenSource +from antlr4.Token import Token +from antlr4.error.ErrorStrategy import BailErrorStrategy +from antlr4.error.Errors import RecognitionException, ParseCancellationException +from antlr4.tree.Chunk import TagChunk, TextChunk +from antlr4.tree.RuleTagToken import RuleTagToken +from antlr4.tree.TokenTagToken import TokenTagToken +from antlr4.tree.Tree import ParseTree, TerminalNode, RuleNode + +# need forward declaration +Parser = None +ParseTreePattern = None + +class CannotInvokeStartRule(Exception): + + def __init__(self, e:Exception): + super().__init__(e) + +class StartRuleDoesNotConsumeFullPattern(Exception): + + pass + + +class ParseTreePatternMatcher(object): + __slots__ = ('lexer', 'parser', 'start', 'stop', 'escape') + + # Constructs a {@link ParseTreePatternMatcher} or from a {@link Lexer} and + # {@link Parser} object. The lexer input stream is altered for tokenizing + # the tree patterns. The parser is used as a convenient mechanism to get + # the grammar name, plus token, rule names. + def __init__(self, lexer:Lexer, parser:Parser): + self.lexer = lexer + self.parser = parser + self.start = "<" + self.stop = ">" + self.escape = "\\" # e.g., \< and \> must escape BOTH! + + # Set the delimiters used for marking rule and token tags within concrete + # syntax used by the tree pattern parser. + # + # @param start The start delimiter. + # @param stop The stop delimiter. + # @param escapeLeft The escape sequence to use for escaping a start or stop delimiter. + # + # @exception IllegalArgumentException if {@code start} is {@code null} or empty. + # @exception IllegalArgumentException if {@code stop} is {@code null} or empty. + # + def setDelimiters(self, start:str, stop:str, escapeLeft:str): + if start is None or len(start)==0: + raise Exception("start cannot be null or empty") + if stop is None or len(stop)==0: + raise Exception("stop cannot be null or empty") + self.start = start + self.stop = stop + self.escape = escapeLeft + + # Does {@code pattern} matched as rule {@code patternRuleIndex} match {@code tree}?# + def matchesRuleIndex(self, tree:ParseTree, pattern:str, patternRuleIndex:int): + p = self.compileTreePattern(pattern, patternRuleIndex) + return self.matches(tree, p) + + # Does {@code pattern} matched as rule patternRuleIndex match tree? Pass in a + # compiled pattern instead of a string representation of a tree pattern. + # + def matchesPattern(self, tree:ParseTree, pattern:ParseTreePattern): + mismatchedNode = self.matchImpl(tree, pattern.patternTree, dict()) + return mismatchedNode is None + + # + # Compare {@code pattern} matched as rule {@code patternRuleIndex} against + # {@code tree} and return a {@link ParseTreeMatch} object that contains the + # matched elements, or the node at which the match failed. + # + def matchRuleIndex(self, tree:ParseTree, pattern:str, patternRuleIndex:int): + p = self.compileTreePattern(pattern, patternRuleIndex) + return self.matchPattern(tree, p) + + # + # Compare {@code pattern} matched against {@code tree} and return a + # {@link ParseTreeMatch} object that contains the matched elements, or the + # node at which the match failed. Pass in a compiled pattern instead of a + # string representation of a tree pattern. + # + def matchPattern(self, tree:ParseTree, pattern:ParseTreePattern): + labels = dict() + mismatchedNode = self.matchImpl(tree, pattern.patternTree, labels) + from antlr4.tree.ParseTreeMatch import ParseTreeMatch + return ParseTreeMatch(tree, pattern, labels, mismatchedNode) + + # + # For repeated use of a tree pattern, compile it to a + # {@link ParseTreePattern} using this method. + # + def compileTreePattern(self, pattern:str, patternRuleIndex:int): + tokenList = self.tokenize(pattern) + tokenSrc = ListTokenSource(tokenList) + tokens = CommonTokenStream(tokenSrc) + from antlr4.ParserInterpreter import ParserInterpreter + parserInterp = ParserInterpreter(self.parser.grammarFileName, self.parser.tokenNames, + self.parser.ruleNames, self.parser.getATNWithBypassAlts(),tokens) + tree = None + try: + parserInterp.setErrorHandler(BailErrorStrategy()) + tree = parserInterp.parse(patternRuleIndex) + except ParseCancellationException as e: + raise e.cause + except RecognitionException as e: + raise e + except Exception as e: + raise CannotInvokeStartRule(e) + + # Make sure tree pattern compilation checks for a complete parse + if tokens.LA(1)!=Token.EOF: + raise StartRuleDoesNotConsumeFullPattern() + + from antlr4.tree.ParseTreePattern import ParseTreePattern + return ParseTreePattern(self, pattern, patternRuleIndex, tree) + + # + # Recursively walk {@code tree} against {@code patternTree}, filling + # {@code match.}{@link ParseTreeMatch#labels labels}. + # + # @return the first node encountered in {@code tree} which does not match + # a corresponding node in {@code patternTree}, or {@code null} if the match + # was successful. The specific node returned depends on the matching + # algorithm used by the implementation, and may be overridden. + # + def matchImpl(self, tree:ParseTree, patternTree:ParseTree, labels:dict): + if tree is None: + raise Exception("tree cannot be null") + if patternTree is None: + raise Exception("patternTree cannot be null") + + # x and , x and y, or x and x; or could be mismatched types + if isinstance(tree, TerminalNode) and isinstance(patternTree, TerminalNode ): + mismatchedNode = None + # both are tokens and they have same type + if tree.symbol.type == patternTree.symbol.type: + if isinstance( patternTree.symbol, TokenTagToken ): # x and + tokenTagToken = patternTree.symbol + # track label->list-of-nodes for both token name and label (if any) + self.map(labels, tokenTagToken.tokenName, tree) + if tokenTagToken.label is not None: + self.map(labels, tokenTagToken.label, tree) + elif tree.getText()==patternTree.getText(): + # x and x + pass + else: + # x and y + if mismatchedNode is None: + mismatchedNode = tree + else: + if mismatchedNode is None: + mismatchedNode = tree + + return mismatchedNode + + if isinstance(tree, ParserRuleContext) and isinstance(patternTree, ParserRuleContext): + mismatchedNode = None + # (expr ...) and + ruleTagToken = self.getRuleTagToken(patternTree) + if ruleTagToken is not None: + m = None + if tree.ruleContext.ruleIndex == patternTree.ruleContext.ruleIndex: + # track label->list-of-nodes for both rule name and label (if any) + self.map(labels, ruleTagToken.ruleName, tree) + if ruleTagToken.label is not None: + self.map(labels, ruleTagToken.label, tree) + else: + if mismatchedNode is None: + mismatchedNode = tree + + return mismatchedNode + + # (expr ...) and (expr ...) + if tree.getChildCount()!=patternTree.getChildCount(): + if mismatchedNode is None: + mismatchedNode = tree + return mismatchedNode + + n = tree.getChildCount() + for i in range(0, n): + childMatch = self.matchImpl(tree.getChild(i), patternTree.getChild(i), labels) + if childMatch is not None: + return childMatch + + return mismatchedNode + + # if nodes aren't both tokens or both rule nodes, can't match + return tree + + def map(self, labels, label, tree): + v = labels.get(label, None) + if v is None: + v = list() + labels[label] = v + v.append(tree) + + # Is {@code t} {@code (expr )} subtree?# + def getRuleTagToken(self, tree:ParseTree): + if isinstance( tree, RuleNode ): + if tree.getChildCount()==1 and isinstance(tree.getChild(0), TerminalNode ): + c = tree.getChild(0) + if isinstance( c.symbol, RuleTagToken ): + return c.symbol + return None + + def tokenize(self, pattern:str): + # split pattern into chunks: sea (raw input) and islands (, ) + chunks = self.split(pattern) + + # create token stream from text and tags + tokens = list() + for chunk in chunks: + if isinstance( chunk, TagChunk ): + # add special rule token or conjure up new token from name + if chunk.tag[0].isupper(): + ttype = self.parser.getTokenType(chunk.tag) + if ttype==Token.INVALID_TYPE: + raise Exception("Unknown token " + str(chunk.tag) + " in pattern: " + pattern) + tokens.append(TokenTagToken(chunk.tag, ttype, chunk.label)) + elif chunk.tag[0].islower(): + ruleIndex = self.parser.getRuleIndex(chunk.tag) + if ruleIndex==-1: + raise Exception("Unknown rule " + str(chunk.tag) + " in pattern: " + pattern) + ruleImaginaryTokenType = self.parser.getATNWithBypassAlts().ruleToTokenType[ruleIndex] + tokens.append(RuleTagToken(chunk.tag, ruleImaginaryTokenType, chunk.label)) + else: + raise Exception("invalid tag: " + str(chunk.tag) + " in pattern: " + pattern) + else: + self.lexer.setInputStream(InputStream(chunk.text)) + t = self.lexer.nextToken() + while t.type!=Token.EOF: + tokens.append(t) + t = self.lexer.nextToken() + return tokens + + # Split {@code = ;} into 4 chunks for tokenizing by {@link #tokenize}.# + def split(self, pattern:str): + p = 0 + n = len(pattern) + chunks = list() + # find all start and stop indexes first, then collect + starts = list() + stops = list() + while p < n : + if p == pattern.find(self.escape + self.start, p): + p += len(self.escape) + len(self.start) + elif p == pattern.find(self.escape + self.stop, p): + p += len(self.escape) + len(self.stop) + elif p == pattern.find(self.start, p): + starts.append(p) + p += len(self.start) + elif p == pattern.find(self.stop, p): + stops.append(p) + p += len(self.stop) + else: + p += 1 + + nt = len(starts) + + if nt > len(stops): + raise Exception("unterminated tag in pattern: " + pattern) + if nt < len(stops): + raise Exception("missing start tag in pattern: " + pattern) + + for i in range(0, nt): + if starts[i] >= stops[i]: + raise Exception("tag delimiters out of order in pattern: " + pattern) + + # collect into chunks now + if nt==0: + chunks.append(TextChunk(pattern)) + + if nt>0 and starts[0]>0: # copy text up to first tag into chunks + text = pattern[0:starts[0]] + chunks.add(TextChunk(text)) + + for i in range(0, nt): + # copy inside of + tag = pattern[starts[i] + len(self.start) : stops[i]] + ruleOrToken = tag + label = None + colon = tag.find(':') + if colon >= 0: + label = tag[0:colon] + ruleOrToken = tag[colon+1 : len(tag)] + chunks.append(TagChunk(label, ruleOrToken)) + if i+1 < len(starts): + # copy from end of to start of next + text = pattern[stops[i] + len(self.stop) : starts[i + 1]] + chunks.append(TextChunk(text)) + + if nt > 0 : + afterLastTag = stops[nt - 1] + len(self.stop) + if afterLastTag < n : # copy text from end of last tag to end + text = pattern[afterLastTag : n] + chunks.append(TextChunk(text)) + + # strip out the escape sequences from text chunks but not tags + for i in range(0, len(chunks)): + c = chunks[i] + if isinstance( c, TextChunk ): + unescaped = c.text.replace(self.escape, "") + if len(unescaped) < len(c.text): + chunks[i] = TextChunk(unescaped) + return chunks diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/RuleTagToken.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/RuleTagToken.py new file mode 100644 index 0000000000000000000000000000000000000000..a198f7da13643d538ce96aeeb6a8ff4f757f1ecd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/RuleTagToken.py @@ -0,0 +1,50 @@ +# +# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. +# Use of this file is governed by the BSD 3-clause license that +# can be found in the LICENSE.txt file in the project root. +# + +# +# A {@link Token} object representing an entire subtree matched by a parser +# rule; e.g., {@code }. These tokens are created for {@link TagChunk} +# chunks where the tag corresponds to a parser rule. +# +from antlr4.Token import Token + + +class RuleTagToken(Token): + __slots__ = ('label', 'ruleName') + # + # Constructs a new instance of {@link RuleTagToken} with the specified rule + # name, bypass token type, and label. + # + # @param ruleName The name of the parser rule this rule tag matches. + # @param bypassTokenType The bypass token type assigned to the parser rule. + # @param label The label associated with the rule tag, or {@code null} if + # the rule tag is unlabeled. + # + # @exception IllegalArgumentException if {@code ruleName} is {@code null} + # or empty. + + def __init__(self, ruleName:str, bypassTokenType:int, label:str=None): + if ruleName is None or len(ruleName)==0: + raise Exception("ruleName cannot be null or empty.") + self.source = None + self.type = bypassTokenType # token type of the token + self.channel = Token.DEFAULT_CHANNEL # The parser ignores everything not on DEFAULT_CHANNEL + self.start = -1 # optional; return -1 if not implemented. + self.stop = -1 # optional; return -1 if not implemented. + self.tokenIndex = -1 # from 0..n-1 of the token object in the input stream + self.line = 0 # line=1..n of the 1st character + self.column = -1 # beginning of the line at which it occurs, 0..n-1 + self.label = label + self._text = self.getText() # text of the token. + + self.ruleName = ruleName + + + def getText(self): + if self.label is None: + return "<" + self.ruleName + ">" + else: + return "<" + self.label + ":" + self.ruleName + ">" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/TokenTagToken.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/TokenTagToken.py new file mode 100644 index 0000000000000000000000000000000000000000..b7beeb87684c06606e17053f0f74fcae36876959 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/TokenTagToken.py @@ -0,0 +1,47 @@ +# +# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. +# Use of this file is governed by the BSD 3-clause license that +# can be found in the LICENSE.txt file in the project root. +# + +# +# A {@link Token} object representing a token of a particular type; e.g., +# {@code }. These tokens are created for {@link TagChunk} chunks where the +# tag corresponds to a lexer rule or token type. +# +from antlr4.Token import CommonToken + + +class TokenTagToken(CommonToken): + __slots__ = ('tokenName', 'label') + # Constructs a new instance of {@link TokenTagToken} with the specified + # token name, type, and label. + # + # @param tokenName The token name. + # @param type The token type. + # @param label The label associated with the token tag, or {@code null} if + # the token tag is unlabeled. + # + def __init__(self, tokenName:str, type:int, label:str=None): + super().__init__(type=type) + self.tokenName = tokenName + self.label = label + self._text = self.getText() + + # + # {@inheritDoc} + # + #

The implementation for {@link TokenTagToken} returns the token tag + # formatted with {@code <} and {@code >} delimiters.

+ # + def getText(self): + if self.label is None: + return "<" + self.tokenName + ">" + else: + return "<" + self.label + ":" + self.tokenName + ">" + + #

The implementation for {@link TokenTagToken} returns a string of the form + # {@code tokenName:type}.

+ # + def __str__(self): + return self.tokenName + ":" + str(self.type) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/Tree.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/Tree.py new file mode 100644 index 0000000000000000000000000000000000000000..812acc96bbee97860bc8a914feedcd0584def050 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/Tree.py @@ -0,0 +1,191 @@ +# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. +# Use of this file is governed by the BSD 3-clause license that +# can be found in the LICENSE.txt file in the project root. +#/ + + +# The basic notion of a tree has a parent, a payload, and a list of children. +# It is the most abstract interface for all the trees used by ANTLR. +#/ +from antlr4.Token import Token + +INVALID_INTERVAL = (-1, -2) + +class Tree(object): + pass + +class SyntaxTree(Tree): + pass + +class ParseTree(SyntaxTree): + pass + +class RuleNode(ParseTree): + pass + +class TerminalNode(ParseTree): + pass + +class ErrorNode(TerminalNode): + pass + +class ParseTreeVisitor(object): + def visit(self, tree): + return tree.accept(self) + + def visitChildren(self, node): + result = self.defaultResult() + n = node.getChildCount() + for i in range(n): + if not self.shouldVisitNextChild(node, result): + return result + + c = node.getChild(i) + childResult = c.accept(self) + result = self.aggregateResult(result, childResult) + + return result + + def visitTerminal(self, node): + return self.defaultResult() + + def visitErrorNode(self, node): + return self.defaultResult() + + def defaultResult(self): + return None + + def aggregateResult(self, aggregate, nextResult): + return nextResult + + def shouldVisitNextChild(self, node, currentResult): + return True + +ParserRuleContext = None + +class ParseTreeListener(object): + + def visitTerminal(self, node:TerminalNode): + pass + + def visitErrorNode(self, node:ErrorNode): + pass + + def enterEveryRule(self, ctx:ParserRuleContext): + pass + + def exitEveryRule(self, ctx:ParserRuleContext): + pass + +del ParserRuleContext + +class TerminalNodeImpl(TerminalNode): + __slots__ = ('parentCtx', 'symbol') + + def __init__(self, symbol:Token): + self.parentCtx = None + self.symbol = symbol + def __setattr__(self, key, value): + super().__setattr__(key, value) + + def getChild(self, i:int): + return None + + def getSymbol(self): + return self.symbol + + def getParent(self): + return self.parentCtx + + def getPayload(self): + return self.symbol + + def getSourceInterval(self): + if self.symbol is None: + return INVALID_INTERVAL + tokenIndex = self.symbol.tokenIndex + return (tokenIndex, tokenIndex) + + def getChildCount(self): + return 0 + + def accept(self, visitor:ParseTreeVisitor): + return visitor.visitTerminal(self) + + def getText(self): + return self.symbol.text + + def __str__(self): + if self.symbol.type == Token.EOF: + return "" + else: + return self.symbol.text + +# Represents a token that was consumed during resynchronization +# rather than during a valid match operation. For example, +# we will create this kind of a node during single token insertion +# and deletion as well as during "consume until error recovery set" +# upon no viable alternative exceptions. + +class ErrorNodeImpl(TerminalNodeImpl,ErrorNode): + + def __init__(self, token:Token): + super().__init__(token) + + def accept(self, visitor:ParseTreeVisitor): + return visitor.visitErrorNode(self) + + +class ParseTreeWalker(object): + + DEFAULT = None + + def walk(self, listener:ParseTreeListener, t:ParseTree): + """ + Performs a walk on the given parse tree starting at the root and going down recursively + with depth-first search. On each node, {@link ParseTreeWalker#enterRule} is called before + recursively walking down into child nodes, then + {@link ParseTreeWalker#exitRule} is called after the recursive call to wind up. + @param listener The listener used by the walker to process grammar rules + @param t The parse tree to be walked on + """ + if isinstance(t, ErrorNode): + listener.visitErrorNode(t) + return + elif isinstance(t, TerminalNode): + listener.visitTerminal(t) + return + self.enterRule(listener, t) + for child in t.getChildren(): + self.walk(listener, child) + self.exitRule(listener, t) + + # + # The discovery of a rule node, involves sending two events: the generic + # {@link ParseTreeListener#enterEveryRule} and a + # {@link RuleContext}-specific event. First we trigger the generic and then + # the rule specific. We to them in reverse order upon finishing the node. + # + def enterRule(self, listener:ParseTreeListener, r:RuleNode): + """ + Enters a grammar rule by first triggering the generic event {@link ParseTreeListener#enterEveryRule} + then by triggering the event specific to the given parse tree node + @param listener The listener responding to the trigger events + @param r The grammar rule containing the rule context + """ + ctx = r.getRuleContext() + listener.enterEveryRule(ctx) + ctx.enterRule(listener) + + def exitRule(self, listener:ParseTreeListener, r:RuleNode): + """ + Exits a grammar rule by first triggering the event specific to the given parse tree node + then by triggering the generic event {@link ParseTreeListener#exitEveryRule} + @param listener The listener responding to the trigger events + @param r The grammar rule containing the rule context + """ + ctx = r.getRuleContext() + ctx.exitRule(listener) + listener.exitEveryRule(ctx) + +ParseTreeWalker.DEFAULT = ParseTreeWalker() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/Trees.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/Trees.py new file mode 100644 index 0000000000000000000000000000000000000000..686b8cb287b3058c2e0b33dfb1567320299f214e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/Trees.py @@ -0,0 +1,111 @@ +# +# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. +# Use of this file is governed by the BSD 3-clause license that +# can be found in the LICENSE.txt file in the project root. +# + + +# A set of utility routines useful for all kinds of ANTLR trees.# +from io import StringIO +from antlr4.Token import Token +from antlr4.Utils import escapeWhitespace +from antlr4.tree.Tree import RuleNode, ErrorNode, TerminalNode, Tree, ParseTree + +# need forward declaration +Parser = None + +class Trees(object): + + # Print out a whole tree in LISP form. {@link #getNodeText} is used on the + # node payloads to get the text for the nodes. Detect + # parse trees and extract data appropriately. + @classmethod + def toStringTree(cls, t:Tree, ruleNames:list=None, recog:Parser=None): + if recog is not None: + ruleNames = recog.ruleNames + s = escapeWhitespace(cls.getNodeText(t, ruleNames), False) + if t.getChildCount()==0: + return s + with StringIO() as buf: + buf.write("(") + buf.write(s) + buf.write(' ') + for i in range(0, t.getChildCount()): + if i > 0: + buf.write(' ') + buf.write(cls.toStringTree(t.getChild(i), ruleNames)) + buf.write(")") + return buf.getvalue() + + @classmethod + def getNodeText(cls, t:Tree, ruleNames:list=None, recog:Parser=None): + if recog is not None: + ruleNames = recog.ruleNames + if ruleNames is not None: + if isinstance(t, RuleNode): + if t.getAltNumber()!=0: # should use ATN.INVALID_ALT_NUMBER but won't compile + return ruleNames[t.getRuleIndex()]+":"+str(t.getAltNumber()) + return ruleNames[t.getRuleIndex()] + elif isinstance( t, ErrorNode): + return str(t) + elif isinstance(t, TerminalNode): + if t.symbol is not None: + return t.symbol.text + # no recog for rule names + payload = t.getPayload() + if isinstance(payload, Token ): + return payload.text + return str(t.getPayload()) + + + # Return ordered list of all children of this node + @classmethod + def getChildren(cls, t:Tree): + return [ t.getChild(i) for i in range(0, t.getChildCount()) ] + + # Return a list of all ancestors of this node. The first node of + # list is the root and the last is the parent of this node. + # + @classmethod + def getAncestors(cls, t:Tree): + ancestors = [] + t = t.getParent() + while t is not None: + ancestors.insert(0, t) # insert at start + t = t.getParent() + return ancestors + + @classmethod + def findAllTokenNodes(cls, t:ParseTree, ttype:int): + return cls.findAllNodes(t, ttype, True) + + @classmethod + def findAllRuleNodes(cls, t:ParseTree, ruleIndex:int): + return cls.findAllNodes(t, ruleIndex, False) + + @classmethod + def findAllNodes(cls, t:ParseTree, index:int, findTokens:bool): + nodes = [] + cls._findAllNodes(t, index, findTokens, nodes) + return nodes + + @classmethod + def _findAllNodes(cls, t:ParseTree, index:int, findTokens:bool, nodes:list): + from antlr4.ParserRuleContext import ParserRuleContext + # check this node (the root) first + if findTokens and isinstance(t, TerminalNode): + if t.symbol.type==index: + nodes.append(t) + elif not findTokens and isinstance(t, ParserRuleContext): + if t.ruleIndex == index: + nodes.append(t) + # check children + for i in range(0, t.getChildCount()): + cls._findAllNodes(t.getChild(i), index, findTokens, nodes) + + @classmethod + def descendants(cls, t:ParseTree): + nodes = [t] + for i in range(0, t.getChildCount()): + nodes.extend(cls.descendants(t.getChild(i))) + return nodes diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/tree/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/xpath/XPath.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/xpath/XPath.py new file mode 100644 index 0000000000000000000000000000000000000000..24029e7cf2bfa9798538211bc7599b49dbb70191 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/xpath/XPath.py @@ -0,0 +1,352 @@ +# +# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. +# Use of this file is governed by the BSD 3-clause license that +# can be found in the LICENSE.txt file in the project root. +# + +# +# Represent a subset of XPath XML path syntax for use in identifying nodes in +# parse trees. +# +#

+# Split path into words and separators {@code /} and {@code //} via ANTLR +# itself then walk path elements from left to right. At each separator-word +# pair, find set of nodes. Next stage uses those as work list.

+# +#

+# The basic interface is +# {@link XPath#findAll ParseTree.findAll}{@code (tree, pathString, parser)}. +# But that is just shorthand for:

+# +#
+# {@link XPath} p = new {@link XPath#XPath XPath}(parser, pathString);
+# return p.{@link #evaluate evaluate}(tree);
+# 
+# +#

+# See {@code org.antlr.v4.test.TestXPath} for descriptions. In short, this +# allows operators:

+# +#
+#
/
root
+#
//
anywhere
+#
!
invert; this must appear directly after root or anywhere +# operator
+#
+# +#

+# and path elements:

+# +#
+#
ID
token name
+#
'string'
any string literal token from the grammar
+#
expr
rule name
+#
*
wildcard matching any node
+#
+# +#

+# Whitespace is not allowed.

+# +from antlr4 import CommonTokenStream, DFA, PredictionContextCache, Lexer, LexerATNSimulator, ParserRuleContext, TerminalNode +from antlr4.InputStream import InputStream +from antlr4.Parser import Parser +from antlr4.RuleContext import RuleContext +from antlr4.Token import Token +from antlr4.atn.ATNDeserializer import ATNDeserializer +from antlr4.error.ErrorListener import ErrorListener +from antlr4.error.Errors import LexerNoViableAltException +from antlr4.tree.Tree import ParseTree +from antlr4.tree.Trees import Trees +from io import StringIO + + +def serializedATN(): + with StringIO() as buf: + buf.write("\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd\2\n") + buf.write("\64\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t") + buf.write("\7\4\b\t\b\4\t\t\t\3\2\3\2\3\2\3\3\3\3\3\4\3\4\3\5\3\5") + buf.write("\3\6\3\6\7\6\37\n\6\f\6\16\6\"\13\6\3\6\3\6\3\7\3\7\5") + buf.write("\7(\n\7\3\b\3\b\3\t\3\t\7\t.\n\t\f\t\16\t\61\13\t\3\t") + buf.write("\3\t\3/\2\n\3\5\5\6\7\7\t\b\13\t\r\2\17\2\21\n\3\2\4\7") + buf.write("\2\62;aa\u00b9\u00b9\u0302\u0371\u2041\u2042\17\2C\\c") + buf.write("|\u00c2\u00d8\u00da\u00f8\u00fa\u0301\u0372\u037f\u0381") + buf.write("\u2001\u200e\u200f\u2072\u2191\u2c02\u2ff1\u3003\ud801") + buf.write("\uf902\ufdd1\ufdf2\uffff\64\2\3\3\2\2\2\2\5\3\2\2\2\2") + buf.write("\7\3\2\2\2\2\t\3\2\2\2\2\13\3\2\2\2\2\21\3\2\2\2\3\23") + buf.write("\3\2\2\2\5\26\3\2\2\2\7\30\3\2\2\2\t\32\3\2\2\2\13\34") + buf.write("\3\2\2\2\r\'\3\2\2\2\17)\3\2\2\2\21+\3\2\2\2\23\24\7\61") + buf.write("\2\2\24\25\7\61\2\2\25\4\3\2\2\2\26\27\7\61\2\2\27\6\3") + buf.write("\2\2\2\30\31\7,\2\2\31\b\3\2\2\2\32\33\7#\2\2\33\n\3\2") + buf.write("\2\2\34 \5\17\b\2\35\37\5\r\7\2\36\35\3\2\2\2\37\"\3\2") + buf.write("\2\2 \36\3\2\2\2 !\3\2\2\2!#\3\2\2\2\" \3\2\2\2#$\b\6") + buf.write("\2\2$\f\3\2\2\2%(\5\17\b\2&(\t\2\2\2\'%\3\2\2\2\'&\3\2") + buf.write("\2\2(\16\3\2\2\2)*\t\3\2\2*\20\3\2\2\2+/\7)\2\2,.\13\2") + buf.write("\2\2-,\3\2\2\2.\61\3\2\2\2/\60\3\2\2\2/-\3\2\2\2\60\62") + buf.write("\3\2\2\2\61/\3\2\2\2\62\63\7)\2\2\63\22\3\2\2\2\6\2 \'") + buf.write("/\3\3\6\2") + return buf.getvalue() + + +class XPathLexer(Lexer): + + atn = ATNDeserializer().deserialize(serializedATN()) + + decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] + + + TOKEN_REF = 1 + RULE_REF = 2 + ANYWHERE = 3 + ROOT = 4 + WILDCARD = 5 + BANG = 6 + ID = 7 + STRING = 8 + + modeNames = [ "DEFAULT_MODE" ] + + literalNames = [ "", + "'//'", "'/'", "'*'", "'!'" ] + + symbolicNames = [ "", + "TOKEN_REF", "RULE_REF", "ANYWHERE", "ROOT", "WILDCARD", "BANG", + "ID", "STRING" ] + + ruleNames = [ "ANYWHERE", "ROOT", "WILDCARD", "BANG", "ID", "NameChar", + "NameStartChar", "STRING" ] + + grammarFileName = "XPathLexer.g4" + + def __init__(self, input=None): + super().__init__(input) + self.checkVersion("4.9.1") + self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache()) + self._actions = None + self._predicates = None + + + def action(self, localctx:RuleContext, ruleIndex:int, actionIndex:int): + if self._actions is None: + actions = dict() + actions[4] = self.ID_action + self._actions = actions + _action = self._actions.get(ruleIndex, None) + if _action is not None: + _action(localctx, actionIndex) + else: + raise Exception("No registered action for: %d" % ruleIndex) + + def ID_action(self, localctx:RuleContext , actionIndex:int): + if actionIndex == 0: + char = self.text[0] + if char.isupper(): + self.type = XPathLexer.TOKEN_REF + else: + self.type = XPathLexer.RULE_REF + +class XPath(object): + + WILDCARD = "*" # word not operator/separator + NOT = "!" # word for invert operator + + def __init__(self, parser:Parser, path:str): + self.parser = parser + self.path = path + self.elements = self.split(path) + + def split(self, path:str): + input = InputStream(path) + lexer = XPathLexer(input) + def recover(self, e): + raise e + lexer.recover = recover + lexer.removeErrorListeners() + lexer.addErrorListener(ErrorListener()) # XPathErrorListener does no more + tokenStream = CommonTokenStream(lexer) + try: + tokenStream.fill() + except LexerNoViableAltException as e: + pos = lexer.column + msg = "Invalid tokens or characters at index %d in path '%s'" % (pos, path) + raise Exception(msg, e) + + tokens = iter(tokenStream.tokens) + elements = list() + for el in tokens: + invert = False + anywhere = False + # Check for path separators, if none assume root + if el.type in [XPathLexer.ROOT, XPathLexer.ANYWHERE]: + anywhere = el.type == XPathLexer.ANYWHERE + next_el = next(tokens, None) + if not next_el: + raise Exception('Missing element after %s' % el.getText()) + else: + el = next_el + # Check for bangs + if el.type == XPathLexer.BANG: + invert = True + next_el = next(tokens, None) + if not next_el: + raise Exception('Missing element after %s' % el.getText()) + else: + el = next_el + # Add searched element + if el.type in [XPathLexer.TOKEN_REF, XPathLexer.RULE_REF, XPathLexer.WILDCARD, XPathLexer.STRING]: + element = self.getXPathElement(el, anywhere) + element.invert = invert + elements.append(element) + elif el.type==Token.EOF: + break + else: + raise Exception("Unknown path element %s" % lexer.symbolicNames[el.type]) + return elements + + # + # Convert word like {@code#} or {@code ID} or {@code expr} to a path + # element. {@code anywhere} is {@code true} if {@code //} precedes the + # word. + # + def getXPathElement(self, wordToken:Token, anywhere:bool): + if wordToken.type==Token.EOF: + raise Exception("Missing path element at end of path") + + word = wordToken.text + if wordToken.type==XPathLexer.WILDCARD : + return XPathWildcardAnywhereElement() if anywhere else XPathWildcardElement() + + elif wordToken.type in [XPathLexer.TOKEN_REF, XPathLexer.STRING]: + tsource = self.parser.getTokenStream().tokenSource + + ttype = Token.INVALID_TYPE + if wordToken.type == XPathLexer.TOKEN_REF: + if word in tsource.ruleNames: + ttype = tsource.ruleNames.index(word) + 1 + else: + if word in tsource.literalNames: + ttype = tsource.literalNames.index(word) + + if ttype == Token.INVALID_TYPE: + raise Exception("%s at index %d isn't a valid token name" % (word, wordToken.tokenIndex)) + return XPathTokenAnywhereElement(word, ttype) if anywhere else XPathTokenElement(word, ttype) + + else: + ruleIndex = self.parser.ruleNames.index(word) if word in self.parser.ruleNames else -1 + + if ruleIndex == -1: + raise Exception("%s at index %d isn't a valid rule name" % (word, wordToken.tokenIndex)) + return XPathRuleAnywhereElement(word, ruleIndex) if anywhere else XPathRuleElement(word, ruleIndex) + + + @staticmethod + def findAll(tree:ParseTree, xpath:str, parser:Parser): + p = XPath(parser, xpath) + return p.evaluate(tree) + + # + # Return a list of all nodes starting at {@code t} as root that satisfy the + # path. The root {@code /} is relative to the node passed to + # {@link #evaluate}. + # + def evaluate(self, t:ParseTree): + dummyRoot = ParserRuleContext() + dummyRoot.children = [t] # don't set t's parent. + + work = [dummyRoot] + for element in self.elements: + work_next = list() + for node in work: + if not isinstance(node, TerminalNode) and node.children: + # only try to match next element if it has children + # e.g., //func/*/stat might have a token node for which + # we can't go looking for stat nodes. + matching = element.evaluate(node) + + # See issue antlr#370 - Prevents XPath from returning the + # same node multiple times + matching = filter(lambda m: m not in work_next, matching) + + work_next.extend(matching) + work = work_next + + return work + + +class XPathElement(object): + + def __init__(self, nodeName:str): + self.nodeName = nodeName + self.invert = False + + def __str__(self): + return type(self).__name__ + "[" + ("!" if self.invert else "") + self.nodeName + "]" + + + +# +# Either {@code ID} at start of path or {@code ...//ID} in middle of path. +# +class XPathRuleAnywhereElement(XPathElement): + + def __init__(self, ruleName:str, ruleIndex:int): + super().__init__(ruleName) + self.ruleIndex = ruleIndex + + def evaluate(self, t:ParseTree): + # return all ParserRuleContext descendants of t that match ruleIndex (or do not match if inverted) + return filter(lambda c: isinstance(c, ParserRuleContext) and (self.invert ^ (c.getRuleIndex() == self.ruleIndex)), Trees.descendants(t)) + +class XPathRuleElement(XPathElement): + + def __init__(self, ruleName:str, ruleIndex:int): + super().__init__(ruleName) + self.ruleIndex = ruleIndex + + def evaluate(self, t:ParseTree): + # return all ParserRuleContext children of t that match ruleIndex (or do not match if inverted) + return filter(lambda c: isinstance(c, ParserRuleContext) and (self.invert ^ (c.getRuleIndex() == self.ruleIndex)), Trees.getChildren(t)) + +class XPathTokenAnywhereElement(XPathElement): + + def __init__(self, ruleName:str, tokenType:int): + super().__init__(ruleName) + self.tokenType = tokenType + + def evaluate(self, t:ParseTree): + # return all TerminalNode descendants of t that match tokenType (or do not match if inverted) + return filter(lambda c: isinstance(c, TerminalNode) and (self.invert ^ (c.symbol.type == self.tokenType)), Trees.descendants(t)) + +class XPathTokenElement(XPathElement): + + def __init__(self, ruleName:str, tokenType:int): + super().__init__(ruleName) + self.tokenType = tokenType + + def evaluate(self, t:ParseTree): + # return all TerminalNode children of t that match tokenType (or do not match if inverted) + return filter(lambda c: isinstance(c, TerminalNode) and (self.invert ^ (c.symbol.type == self.tokenType)), Trees.getChildren(t)) + + +class XPathWildcardAnywhereElement(XPathElement): + + def __init__(self): + super().__init__(XPath.WILDCARD) + + def evaluate(self, t:ParseTree): + if self.invert: + return list() # !* is weird but valid (empty) + else: + return Trees.descendants(t) + + +class XPathWildcardElement(XPathElement): + + def __init__(self): + super().__init__(XPath.WILDCARD) + + + def evaluate(self, t:ParseTree): + if self.invert: + return list() # !* is weird but valid (empty) + else: + return Trees.getChildren(t) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/xpath/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/xpath/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..216c000dc5ffc8e53cc9c596e420c1e67604d1aa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4/xpath/__init__.py @@ -0,0 +1 @@ +__author__ = 'ericvergnaud' diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4_python3_runtime-4.9.3.dist-info/INSTALLER b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4_python3_runtime-4.9.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4_python3_runtime-4.9.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4_python3_runtime-4.9.3.dist-info/METADATA b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4_python3_runtime-4.9.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..4729e215e6127997f4ecafeddb784ac0344edab3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4_python3_runtime-4.9.3.dist-info/METADATA @@ -0,0 +1,15 @@ +Metadata-Version: 2.4 +Name: antlr4-python3-runtime +Version: 4.9.3 +Summary: ANTLR 4.9.3 runtime for Python 3.7 +Home-page: http://www.antlr.org +Author: Eric Vergnaud, Terence Parr, Sam Harwell +Author-email: eric.vergnaud@wanadoo.fr +License: BSD +Requires-Dist: typing; python_version < "3.5" +Dynamic: author +Dynamic: author-email +Dynamic: home-page +Dynamic: license +Dynamic: requires-dist +Dynamic: summary diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4_python3_runtime-4.9.3.dist-info/RECORD b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4_python3_runtime-4.9.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..b6773c24a8f275d77de8753e118829ef5e110e3c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4_python3_runtime-4.9.3.dist-info/RECORD @@ -0,0 +1,118 @@ +../../../bin/pygrun,sha256=fyqneSOA38hfCV9dBVscsKTIt9XVKA4-Iy3FFEQsVVM,6182 +antlr4/BufferedTokenStream.py,sha256=_BwmzOH1TO6yL2yC_ZaUzkghq8wzc0UPHfI3UpnZUwM,10780 +antlr4/CommonTokenFactory.py,sha256=Tv16zg_pWD1Dv3IphsxFu8nwWdLeXYcqJ8CC5yHwjH8,2110 +antlr4/CommonTokenStream.py,sha256=NNJHXwRg2_Zn46ZhJyDxZtvZzsPWhb6JjXa7BjM45eg,2770 +antlr4/FileStream.py,sha256=-ZR_-jl_If9IIBYLINIwlQrlTSmu5k1VUKDc3ie7WR4,868 +antlr4/InputStream.py,sha256=sggjE2jEGvSgQmxFvqeeuT3aOVgcH5tS7mMybW8wKS4,2334 +antlr4/IntervalSet.py,sha256=Cd0WKhd_kYbiLYKkDNncgSM19GAuS7OaTOC4-5Yubs4,5965 +antlr4/LL1Analyzer.py,sha256=oJBvO7_S8cAlb_D4qWNxd2IlK0qP4ka-oeoDxx16CZ4,7752 +antlr4/Lexer.py,sha256=C72hqayfkympxb46AcSnhPD9kVZ0quWgboGxa6gcIcg,11542 +antlr4/ListTokenSource.py,sha256=IffLMo7YQnD_CjKryrrgNWSk0q5QSYd7puZyyUk7vOk,5356 +antlr4/Parser.py,sha256=F2Q25z0-__KHfa354KQhDu3ZOVzLFfag3s2ixJ4dl_o,22883 +antlr4/ParserInterpreter.py,sha256=-QU9kn4x3WCQ-LSA99R231HoicTqakiHZ5KM72l-hIo,7206 +antlr4/ParserRuleContext.py,sha256=wHAVdOxMAO5jkUqloTXVzn_xYnJhiHbvvuhZpth0ZF8,6762 +antlr4/PredictionContext.py,sha256=cb4KI6EGpS7sRzJ8UvPEkxphINZuWhyiZ95752g3prI,22977 +antlr4/Recognizer.py,sha256=vmKAtSjIgR9LQr5YzuK5OmPZWMJ3x69OuVZQ_FTzQHE,5383 +antlr4/RuleContext.py,sha256=GiviRv2k_al1IBgdJOEEoD0ohJaVd-_h5T_CPG_Bsmg,8099 +antlr4/StdinStream.py,sha256=MMSH4zN8T6i_nu-3_TlN-3E4nPM4b5KgK4GT6n_FUQA,303 +antlr4/Token.py,sha256=OtWCab4Ut52X_nLLAA-8x4Zl6xaF6TEN-0033uaoaEo,5206 +antlr4/TokenStreamRewriter.py,sha256=cuErQTrXwC_0kqVv3MsTWGZSm-E1Vy1yzA-3SOhKd_s,10324 +antlr4/Utils.py,sha256=Oyg8CJCRL1TrF_QSB_LLlVdWOB4loVcKOgFNT-icO7c,931 +antlr4/__init__.py,sha256=g8UGpflnlMWcAyLtihejzrgAP1Uo3b9GhwfI8QnZjtw,1125 +antlr4/__pycache__/BufferedTokenStream.cpython-310.pyc,, +antlr4/__pycache__/CommonTokenFactory.cpython-310.pyc,, +antlr4/__pycache__/CommonTokenStream.cpython-310.pyc,, +antlr4/__pycache__/FileStream.cpython-310.pyc,, +antlr4/__pycache__/InputStream.cpython-310.pyc,, +antlr4/__pycache__/IntervalSet.cpython-310.pyc,, +antlr4/__pycache__/LL1Analyzer.cpython-310.pyc,, +antlr4/__pycache__/Lexer.cpython-310.pyc,, +antlr4/__pycache__/ListTokenSource.cpython-310.pyc,, +antlr4/__pycache__/Parser.cpython-310.pyc,, +antlr4/__pycache__/ParserInterpreter.cpython-310.pyc,, +antlr4/__pycache__/ParserRuleContext.cpython-310.pyc,, +antlr4/__pycache__/PredictionContext.cpython-310.pyc,, +antlr4/__pycache__/Recognizer.cpython-310.pyc,, +antlr4/__pycache__/RuleContext.cpython-310.pyc,, +antlr4/__pycache__/StdinStream.cpython-310.pyc,, +antlr4/__pycache__/Token.cpython-310.pyc,, +antlr4/__pycache__/TokenStreamRewriter.cpython-310.pyc,, +antlr4/__pycache__/Utils.cpython-310.pyc,, +antlr4/__pycache__/__init__.cpython-310.pyc,, +antlr4/atn/ATN.py,sha256=LYE8kT-D8FpUd5fpOtyOLqvXLFkUSa83TVFowhCWAiY,5789 +antlr4/atn/ATNConfig.py,sha256=tNdIC6_GrxXllHBx3npAWyDh6KrohLZDV_XyPrydRMY,6565 +antlr4/atn/ATNConfigSet.py,sha256=qRzVsBeMqk2txjG3DrGptwF6Vb2hHC5w3umkSL0GNJw,8312 +antlr4/atn/ATNDeserializationOptions.py,sha256=lUV_bGW6mxj7t20esda5Yv-X9m-U_x1-0xaLifhXIPo,1010 +antlr4/atn/ATNDeserializer.py,sha256=aYLDDtQ-wyo3gId6A-wD1E3QmpfrPZlXxj4_IDm-mUY,22252 +antlr4/atn/ATNSimulator.py,sha256=mDc-G3GF3kSeqpfGDabUOLJ0WLVTqibxZlkvXQYmBRk,2298 +antlr4/atn/ATNState.py,sha256=NbndISWUwFDF_vuBfbTiZZ8GPHoQa6UXdqbD-yjJE7c,7663 +antlr4/atn/ATNType.py,sha256=xgv8AMVU7tc07U73_hRTm1AiZ7MvGhoaP5fTiOrrCGg,422 +antlr4/atn/LexerATNSimulator.py,sha256=kYXRwUvHptSRU8T_K9pSrGlCk9YypWeHlAcjgry1VVo,25465 +antlr4/atn/LexerAction.py,sha256=KUeJwKekBch0m1poSPskHIh-15dcKAG4lR7zlq98tzc,10014 +antlr4/atn/LexerActionExecutor.py,sha256=7rlg17THcwLsuTmh7NsLrTbRH4DTrm8qIdW9_235CEc,6420 +antlr4/atn/ParserATNSimulator.py,sha256=IKCzsDLcznROSVojU-daAygKr3svl0DmK5DhkUllASY,80365 +antlr4/atn/PredictionMode.py,sha256=i8B7MULA7v-qbXeCY_xp6sgi21kHM6kybqIrG6rSrro,22486 +antlr4/atn/SemanticContext.py,sha256=ds0TmM4qenb0LN-rl2Fp_N_xB959abN67I19EF6rs8o,10495 +antlr4/atn/Transition.py,sha256=ZAsEFpa5I_n-zxD6U-DauM5_33jFK65x3PWu6-NW0RA,8762 +antlr4/atn/__init__.py,sha256=gsnQdtTH8IUgCiVUpQfzhxx2pFRvksW76SjwIk3fYSk,28 +antlr4/atn/__pycache__/ATN.cpython-310.pyc,, +antlr4/atn/__pycache__/ATNConfig.cpython-310.pyc,, +antlr4/atn/__pycache__/ATNConfigSet.cpython-310.pyc,, +antlr4/atn/__pycache__/ATNDeserializationOptions.cpython-310.pyc,, +antlr4/atn/__pycache__/ATNDeserializer.cpython-310.pyc,, +antlr4/atn/__pycache__/ATNSimulator.cpython-310.pyc,, +antlr4/atn/__pycache__/ATNState.cpython-310.pyc,, +antlr4/atn/__pycache__/ATNType.cpython-310.pyc,, +antlr4/atn/__pycache__/LexerATNSimulator.cpython-310.pyc,, +antlr4/atn/__pycache__/LexerAction.cpython-310.pyc,, +antlr4/atn/__pycache__/LexerActionExecutor.cpython-310.pyc,, +antlr4/atn/__pycache__/ParserATNSimulator.cpython-310.pyc,, +antlr4/atn/__pycache__/PredictionMode.cpython-310.pyc,, +antlr4/atn/__pycache__/SemanticContext.cpython-310.pyc,, +antlr4/atn/__pycache__/Transition.cpython-310.pyc,, +antlr4/atn/__pycache__/__init__.cpython-310.pyc,, +antlr4/dfa/DFA.py,sha256=weIh0uaRfakP12mFvHo7U0tqO3GONV3-nHFkc2xk-ZE,5388 +antlr4/dfa/DFASerializer.py,sha256=1st_HO85yXLYy7gInTEnkztgA6am4CT-yReh-mazp9E,2518 +antlr4/dfa/DFAState.py,sha256=R7JwKf0GtAEs9J_MD_Y0WKcuzdt0BVX1sow-uv9yFYc,5583 +antlr4/dfa/__init__.py,sha256=gsnQdtTH8IUgCiVUpQfzhxx2pFRvksW76SjwIk3fYSk,28 +antlr4/dfa/__pycache__/DFA.cpython-310.pyc,, +antlr4/dfa/__pycache__/DFASerializer.cpython-310.pyc,, +antlr4/dfa/__pycache__/DFAState.cpython-310.pyc,, +antlr4/dfa/__pycache__/__init__.cpython-310.pyc,, +antlr4/error/DiagnosticErrorListener.py,sha256=EwS2D_Ox6CmvCa16NPJ9ud4QYPHmlPXt6-Wdn1h5Kg8,4430 +antlr4/error/ErrorListener.py,sha256=yP_MDguol4Cj0_pEPyNzeH3v4ZvUjW5iwDjhYTVAHbE,2722 +antlr4/error/ErrorStrategy.py,sha256=0mhzFL57ZVnjKkGrtadta93Zm3NXdF-HW10DVD07VXs,30391 +antlr4/error/Errors.py,sha256=hlKngclBfXdkDiAymhYsvh2OCXlvmHM2kTl_A1vgp-w,6759 +antlr4/error/__init__.py,sha256=gsnQdtTH8IUgCiVUpQfzhxx2pFRvksW76SjwIk3fYSk,28 +antlr4/error/__pycache__/DiagnosticErrorListener.cpython-310.pyc,, +antlr4/error/__pycache__/ErrorListener.cpython-310.pyc,, +antlr4/error/__pycache__/ErrorStrategy.cpython-310.pyc,, +antlr4/error/__pycache__/Errors.cpython-310.pyc,, +antlr4/error/__pycache__/__init__.cpython-310.pyc,, +antlr4/tree/Chunk.py,sha256=oCIZjolLq9xkxtVDROEDxfUGgndcEnsDW0eUmLM7Gpk,695 +antlr4/tree/ParseTreeMatch.py,sha256=Dc6GVWSUqoIAFXUaUZqUwCUlZfTcgUbGLGzNf6QxQvE,4485 +antlr4/tree/ParseTreePattern.py,sha256=ASBNaQORh3f7f8KnFeZJC2yWFFx4uQlxvC2Y55ifhY0,2825 +antlr4/tree/ParseTreePatternMatcher.py,sha256=HtE9yi1Urr2QPLGLJDBvr0lxv6bjuj9CHl-4clahSe8,16388 +antlr4/tree/RuleTagToken.py,sha256=n4zXcmrrfsGyl91pj5ZYcc_CeKMhPrvYkUdppgMBpbY,2022 +antlr4/tree/TokenTagToken.py,sha256=S3o3DJhfzL5kpClxsKyI-Il-xvuuZQiBAIsLCKFjRHo,1576 +antlr4/tree/Tree.py,sha256=ZI7U_5IxBLm_IrnfJOtb12BCPIWyzfeZtLnhHKVVZIw,5572 +antlr4/tree/Trees.py,sha256=JtQ7cYWmKwI9TIBP6y9XIgjlNS4mYjv3ARwOfwWc5Vg,3968 +antlr4/tree/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +antlr4/tree/__pycache__/Chunk.cpython-310.pyc,, +antlr4/tree/__pycache__/ParseTreeMatch.cpython-310.pyc,, +antlr4/tree/__pycache__/ParseTreePattern.cpython-310.pyc,, +antlr4/tree/__pycache__/ParseTreePatternMatcher.cpython-310.pyc,, +antlr4/tree/__pycache__/RuleTagToken.cpython-310.pyc,, +antlr4/tree/__pycache__/TokenTagToken.cpython-310.pyc,, +antlr4/tree/__pycache__/Tree.cpython-310.pyc,, +antlr4/tree/__pycache__/Trees.cpython-310.pyc,, +antlr4/tree/__pycache__/__init__.cpython-310.pyc,, +antlr4/xpath/XPath.py,sha256=O9s4-EDvLbAbYytP_bae9Z2khLl0iAtRzPAtVbuWUM4,13015 +antlr4/xpath/__init__.py,sha256=gsnQdtTH8IUgCiVUpQfzhxx2pFRvksW76SjwIk3fYSk,28 +antlr4/xpath/__pycache__/XPath.cpython-310.pyc,, +antlr4/xpath/__pycache__/__init__.cpython-310.pyc,, +antlr4_python3_runtime-4.9.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +antlr4_python3_runtime-4.9.3.dist-info/METADATA,sha256=vzJeUVUxg4Wi_MRoB0LacQu63xOj0cCXmpizSHmA8mE,403 +antlr4_python3_runtime-4.9.3.dist-info/RECORD,, +antlr4_python3_runtime-4.9.3.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92 +antlr4_python3_runtime-4.9.3.dist-info/top_level.txt,sha256=OsoZsh9bb30wgXb2zBUjdDwYg46MfV-RVZA6Pk8pcB0,7 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4_python3_runtime-4.9.3.dist-info/WHEEL b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4_python3_runtime-4.9.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..0885d055554a9bce53952482316a33cebf0845e4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4_python3_runtime-4.9.3.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.10.2) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4_python3_runtime-4.9.3.dist-info/top_level.txt b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4_python3_runtime-4.9.3.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..3dee19f3e13c2cbbb49b818e6ac67c63f77b865f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/antlr4_python3_runtime-4.9.3.dist-info/top_level.txt @@ -0,0 +1 @@ +antlr4 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio-4.12.1.dist-info/INSTALLER b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio-4.12.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio-4.12.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio-4.12.1.dist-info/METADATA b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio-4.12.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..dbeb1989ba35da34a15e015e0225304dcd140331 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio-4.12.1.dist-info/METADATA @@ -0,0 +1,96 @@ +Metadata-Version: 2.4 +Name: anyio +Version: 4.12.1 +Summary: High-level concurrency and networking framework on top of asyncio or Trio +Author-email: Alex Grönholm +License-Expression: MIT +Project-URL: Documentation, https://anyio.readthedocs.io/en/latest/ +Project-URL: Changelog, https://anyio.readthedocs.io/en/stable/versionhistory.html +Project-URL: Source code, https://github.com/agronholm/anyio +Project-URL: Issue tracker, https://github.com/agronholm/anyio/issues +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Framework :: AnyIO +Classifier: Typing :: Typed +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Requires-Python: >=3.9 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: exceptiongroup>=1.0.2; python_version < "3.11" +Requires-Dist: idna>=2.8 +Requires-Dist: typing_extensions>=4.5; python_version < "3.13" +Provides-Extra: trio +Requires-Dist: trio>=0.32.0; python_version >= "3.10" and extra == "trio" +Requires-Dist: trio>=0.31.0; python_version < "3.10" and extra == "trio" +Dynamic: license-file + +.. image:: https://github.com/agronholm/anyio/actions/workflows/test.yml/badge.svg + :target: https://github.com/agronholm/anyio/actions/workflows/test.yml + :alt: Build Status +.. image:: https://coveralls.io/repos/github/agronholm/anyio/badge.svg?branch=master + :target: https://coveralls.io/github/agronholm/anyio?branch=master + :alt: Code Coverage +.. image:: https://readthedocs.org/projects/anyio/badge/?version=latest + :target: https://anyio.readthedocs.io/en/latest/?badge=latest + :alt: Documentation +.. image:: https://badges.gitter.im/gitterHQ/gitter.svg + :target: https://gitter.im/python-trio/AnyIO + :alt: Gitter chat + +AnyIO is an asynchronous networking and concurrency library that works on top of either asyncio_ or +Trio_. It implements Trio-like `structured concurrency`_ (SC) on top of asyncio and works in harmony +with the native SC of Trio itself. + +Applications and libraries written against AnyIO's API will run unmodified on either asyncio_ or +Trio_. AnyIO can also be adopted into a library or application incrementally – bit by bit, no full +refactoring necessary. It will blend in with the native libraries of your chosen backend. + +To find out why you might want to use AnyIO's APIs instead of asyncio's, you can read about it +`here `_. + +Documentation +------------- + +View full documentation at: https://anyio.readthedocs.io/ + +Features +-------- + +AnyIO offers the following functionality: + +* Task groups (nurseries_ in trio terminology) +* High-level networking (TCP, UDP and UNIX sockets) + + * `Happy eyeballs`_ algorithm for TCP connections (more robust than that of asyncio on Python + 3.8) + * async/await style UDP sockets (unlike asyncio where you still have to use Transports and + Protocols) + +* A versatile API for byte streams and object streams +* Inter-task synchronization and communication (locks, conditions, events, semaphores, object + streams) +* Worker threads +* Subprocesses +* Subinterpreter support for code parallelization (on Python 3.13 and later) +* Asynchronous file I/O (using worker threads) +* Signal handling +* Asynchronous version of the functools_ module + +AnyIO also comes with its own pytest_ plugin which also supports asynchronous fixtures. +It even works with the popular Hypothesis_ library. + +.. _asyncio: https://docs.python.org/3/library/asyncio.html +.. _Trio: https://github.com/python-trio/trio +.. _structured concurrency: https://en.wikipedia.org/wiki/Structured_concurrency +.. _nurseries: https://trio.readthedocs.io/en/stable/reference-core.html#nurseries-and-spawning +.. _Happy eyeballs: https://en.wikipedia.org/wiki/Happy_Eyeballs +.. _pytest: https://docs.pytest.org/en/latest/ +.. _functools: https://docs.python.org/3/library/functools.html +.. _Hypothesis: https://hypothesis.works/ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio-4.12.1.dist-info/RECORD b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio-4.12.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..310e0e13c166a4088e978cf11228126aa021befc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio-4.12.1.dist-info/RECORD @@ -0,0 +1,92 @@ +anyio-4.12.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +anyio-4.12.1.dist-info/METADATA,sha256=DfiDab9Tmmcfy802lOLTMEHJQShkOSbopCwqCYbLuJk,4277 +anyio-4.12.1.dist-info/RECORD,, +anyio-4.12.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +anyio-4.12.1.dist-info/entry_points.txt,sha256=_d6Yu6uiaZmNe0CydowirE9Cmg7zUL2g08tQpoS3Qvc,39 +anyio-4.12.1.dist-info/licenses/LICENSE,sha256=U2GsncWPLvX9LpsJxoKXwX8ElQkJu8gCO9uC6s8iwrA,1081 +anyio-4.12.1.dist-info/top_level.txt,sha256=QglSMiWX8_5dpoVAEIHdEYzvqFMdSYWmCj6tYw2ITkQ,6 +anyio/__init__.py,sha256=7iDVqMUprUuKNY91FuoKqayAhR-OY136YDPI6P78HHk,6170 +anyio/__pycache__/__init__.cpython-310.pyc,, +anyio/__pycache__/from_thread.cpython-310.pyc,, +anyio/__pycache__/functools.cpython-310.pyc,, +anyio/__pycache__/lowlevel.cpython-310.pyc,, +anyio/__pycache__/pytest_plugin.cpython-310.pyc,, +anyio/__pycache__/to_interpreter.cpython-310.pyc,, +anyio/__pycache__/to_process.cpython-310.pyc,, +anyio/__pycache__/to_thread.cpython-310.pyc,, +anyio/_backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +anyio/_backends/__pycache__/__init__.cpython-310.pyc,, +anyio/_backends/__pycache__/_asyncio.cpython-310.pyc,, +anyio/_backends/__pycache__/_trio.cpython-310.pyc,, +anyio/_backends/_asyncio.py,sha256=xG6qv60mgGnL0mK82dxjH2b8hlkMlJ-x2BqIq3qv70Y,98863 +anyio/_backends/_trio.py,sha256=30Rctb7lm8g63ZHljVPVnj5aH-uK6oQvphjwUBoAzuI,41456 +anyio/_core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +anyio/_core/__pycache__/__init__.cpython-310.pyc,, +anyio/_core/__pycache__/_asyncio_selector_thread.cpython-310.pyc,, +anyio/_core/__pycache__/_contextmanagers.cpython-310.pyc,, +anyio/_core/__pycache__/_eventloop.cpython-310.pyc,, +anyio/_core/__pycache__/_exceptions.cpython-310.pyc,, +anyio/_core/__pycache__/_fileio.cpython-310.pyc,, +anyio/_core/__pycache__/_resources.cpython-310.pyc,, +anyio/_core/__pycache__/_signals.cpython-310.pyc,, +anyio/_core/__pycache__/_sockets.cpython-310.pyc,, +anyio/_core/__pycache__/_streams.cpython-310.pyc,, +anyio/_core/__pycache__/_subprocesses.cpython-310.pyc,, +anyio/_core/__pycache__/_synchronization.cpython-310.pyc,, +anyio/_core/__pycache__/_tasks.cpython-310.pyc,, +anyio/_core/__pycache__/_tempfile.cpython-310.pyc,, +anyio/_core/__pycache__/_testing.cpython-310.pyc,, +anyio/_core/__pycache__/_typedattr.cpython-310.pyc,, +anyio/_core/_asyncio_selector_thread.py,sha256=2PdxFM3cs02Kp6BSppbvmRT7q7asreTW5FgBxEsflBo,5626 +anyio/_core/_contextmanagers.py,sha256=YInBCabiEeS-UaP_Jdxa1CaFC71ETPW8HZTHIM8Rsc8,7215 +anyio/_core/_eventloop.py,sha256=c2EdcBX-xnKwxPcC4Pjn3_qG9I-x4IWFO2R9RqCGjM4,6448 +anyio/_core/_exceptions.py,sha256=Y3aq-Wxd7Q2HqwSg7nZPvRsHEuGazv_qeet6gqEBdPk,4407 +anyio/_core/_fileio.py,sha256=uc7t10Vb-If7GbdWM_zFf-ajUe6uek63fSt7IBLlZW0,25731 +anyio/_core/_resources.py,sha256=NbmU5O5UX3xEyACnkmYX28Fmwdl-f-ny0tHym26e0w0,435 +anyio/_core/_signals.py,sha256=mjTBB2hTKNPRlU0IhnijeQedpWOGERDiMjSlJQsFrug,1016 +anyio/_core/_sockets.py,sha256=RBXHcUqZt5gg_-OOfgHVv8uq2FSKk1uVUzTdpjBoI1o,34977 +anyio/_core/_streams.py,sha256=FczFwIgDpnkK0bODWJXMpsUJYdvAD04kaUaGzJU8DK0,1806 +anyio/_core/_subprocesses.py,sha256=EXm5igL7dj55iYkPlbYVAqtbqxJxjU-6OndSTIx9SRg,8047 +anyio/_core/_synchronization.py,sha256=MgVVqFzvt580tHC31LiOcq1G6aryut--xRG4Ff8KwxQ,20869 +anyio/_core/_tasks.py,sha256=pVB7K6AAulzUM8YgXAeqNZG44nSyZ1bYJjH8GznC00I,5435 +anyio/_core/_tempfile.py,sha256=lHb7CW4FyIlpkf5ADAf4VmLHCKwEHF9nxqNyBCFFUiA,19697 +anyio/_core/_testing.py,sha256=u7MPqGXwpTxqI7hclSdNA30z2GH1Nw258uwKvy_RfBg,2340 +anyio/_core/_typedattr.py,sha256=P4ozZikn3-DbpoYcvyghS_FOYAgbmUxeoU8-L_07pZM,2508 +anyio/abc/__init__.py,sha256=6mWhcl_pGXhrgZVHP_TCfMvIXIOp9mroEFM90fYCU_U,2869 +anyio/abc/__pycache__/__init__.cpython-310.pyc,, +anyio/abc/__pycache__/_eventloop.cpython-310.pyc,, +anyio/abc/__pycache__/_resources.cpython-310.pyc,, +anyio/abc/__pycache__/_sockets.cpython-310.pyc,, +anyio/abc/__pycache__/_streams.cpython-310.pyc,, +anyio/abc/__pycache__/_subprocesses.cpython-310.pyc,, +anyio/abc/__pycache__/_tasks.cpython-310.pyc,, +anyio/abc/__pycache__/_testing.cpython-310.pyc,, +anyio/abc/_eventloop.py,sha256=GlzgB3UJGgG6Kr7olpjOZ-o00PghecXuofVDQ_5611Q,10749 +anyio/abc/_resources.py,sha256=DrYvkNN1hH6Uvv5_5uKySvDsnknGVDe8FCKfko0VtN8,783 +anyio/abc/_sockets.py,sha256=ECTY0jLEF18gryANHR3vFzXzGdZ-xPwELq1QdgOb0Jo,13258 +anyio/abc/_streams.py,sha256=005GKSCXGprxnhucILboSqc2JFovECZk9m3p-qqxXVc,7640 +anyio/abc/_subprocesses.py,sha256=cumAPJTktOQtw63IqG0lDpyZqu_l1EElvQHMiwJgL08,2067 +anyio/abc/_tasks.py,sha256=KC7wrciE48AINOI-AhPutnFhe1ewfP7QnamFlDzqesQ,3721 +anyio/abc/_testing.py,sha256=tBJUzkSfOXJw23fe8qSJ03kJlShOYjjaEyFB6k6MYT8,1821 +anyio/from_thread.py,sha256=L-0w1HxJ6BSb-KuVi57k5Tkc3yzQrx3QK5tAxMPcY-0,19141 +anyio/functools.py,sha256=HWj7GBEmc0Z-mZg3uok7Z7ZJn0rEC_0Pzbt0nYUDaTQ,10973 +anyio/lowlevel.py,sha256=AyKLVK3LaWSoK39LkCKxE4_GDMLKZBNqTrLUgk63y80,5158 +anyio/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +anyio/pytest_plugin.py,sha256=3jAFQn0jv_pyoWE2GBBlHaj9sqXj4e8vob0_hgrsXE8,10244 +anyio/streams/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +anyio/streams/__pycache__/__init__.cpython-310.pyc,, +anyio/streams/__pycache__/buffered.cpython-310.pyc,, +anyio/streams/__pycache__/file.cpython-310.pyc,, +anyio/streams/__pycache__/memory.cpython-310.pyc,, +anyio/streams/__pycache__/stapled.cpython-310.pyc,, +anyio/streams/__pycache__/text.cpython-310.pyc,, +anyio/streams/__pycache__/tls.cpython-310.pyc,, +anyio/streams/buffered.py,sha256=2R3PeJhe4EXrdYqz44Y6-Eg9R6DrmlsYrP36Ir43-po,6263 +anyio/streams/file.py,sha256=4WZ7XGz5WNu39FQHvqbe__TQ0HDP9OOhgO1mk9iVpVU,4470 +anyio/streams/memory.py,sha256=F0zwzvFJKAhX_LRZGoKzzqDC2oMM-f-yyTBrEYEGOaU,10740 +anyio/streams/stapled.py,sha256=T8Xqwf8K6EgURPxbt1N4i7A8BAk-gScv-GRhjLXIf_o,4390 +anyio/streams/text.py,sha256=BcVAGJw1VRvtIqnv-o0Rb0pwH7p8vwlvl21xHq522ag,5765 +anyio/streams/tls.py,sha256=Jpxy0Mfbcp1BxHCwE-YjSSFaLnIBbnnwur-excYThs4,15368 +anyio/to_interpreter.py,sha256=_mLngrMy97TMR6VbW4Y6YzDUk9ZuPcQMPlkuyRh3C9k,7100 +anyio/to_process.py,sha256=J7gAA_YOuoHqnpDAf5fm1Qu6kOmTzdFbiDNvnV755vk,9798 +anyio/to_thread.py,sha256=menEgXYmUV7Fjg_9WqCV95P9MAtQS8BzPGGcWB_QnfQ,2687 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio-4.12.1.dist-info/WHEEL b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio-4.12.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio-4.12.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio-4.12.1.dist-info/entry_points.txt b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio-4.12.1.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..44dd9bdc3039122cc98014c1439ca254313fd014 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio-4.12.1.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[pytest11] +anyio = anyio.pytest_plugin diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio-4.12.1.dist-info/licenses/LICENSE b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio-4.12.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..104eebf5a3002fccdaceef3a4cb936173c1c2035 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio-4.12.1.dist-info/licenses/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2018 Alex Grönholm + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio-4.12.1.dist-info/top_level.txt b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio-4.12.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..c77c069ecc9b7f8b1f97dbcfec905725db0253a8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio-4.12.1.dist-info/top_level.txt @@ -0,0 +1 @@ +anyio diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d23c5a5a27878561b79551da9513cf600dce5005 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/__init__.py @@ -0,0 +1,111 @@ +from __future__ import annotations + +from ._core._contextmanagers import AsyncContextManagerMixin as AsyncContextManagerMixin +from ._core._contextmanagers import ContextManagerMixin as ContextManagerMixin +from ._core._eventloop import current_time as current_time +from ._core._eventloop import get_all_backends as get_all_backends +from ._core._eventloop import get_available_backends as get_available_backends +from ._core._eventloop import get_cancelled_exc_class as get_cancelled_exc_class +from ._core._eventloop import run as run +from ._core._eventloop import sleep as sleep +from ._core._eventloop import sleep_forever as sleep_forever +from ._core._eventloop import sleep_until as sleep_until +from ._core._exceptions import BrokenResourceError as BrokenResourceError +from ._core._exceptions import BrokenWorkerInterpreter as BrokenWorkerInterpreter +from ._core._exceptions import BrokenWorkerProcess as BrokenWorkerProcess +from ._core._exceptions import BusyResourceError as BusyResourceError +from ._core._exceptions import ClosedResourceError as ClosedResourceError +from ._core._exceptions import ConnectionFailed as ConnectionFailed +from ._core._exceptions import DelimiterNotFound as DelimiterNotFound +from ._core._exceptions import EndOfStream as EndOfStream +from ._core._exceptions import IncompleteRead as IncompleteRead +from ._core._exceptions import NoEventLoopError as NoEventLoopError +from ._core._exceptions import RunFinishedError as RunFinishedError +from ._core._exceptions import TypedAttributeLookupError as TypedAttributeLookupError +from ._core._exceptions import WouldBlock as WouldBlock +from ._core._fileio import AsyncFile as AsyncFile +from ._core._fileio import Path as Path +from ._core._fileio import open_file as open_file +from ._core._fileio import wrap_file as wrap_file +from ._core._resources import aclose_forcefully as aclose_forcefully +from ._core._signals import open_signal_receiver as open_signal_receiver +from ._core._sockets import TCPConnectable as TCPConnectable +from ._core._sockets import UNIXConnectable as UNIXConnectable +from ._core._sockets import as_connectable as as_connectable +from ._core._sockets import connect_tcp as connect_tcp +from ._core._sockets import connect_unix as connect_unix +from ._core._sockets import create_connected_udp_socket as create_connected_udp_socket +from ._core._sockets import ( + create_connected_unix_datagram_socket as create_connected_unix_datagram_socket, +) +from ._core._sockets import create_tcp_listener as create_tcp_listener +from ._core._sockets import create_udp_socket as create_udp_socket +from ._core._sockets import create_unix_datagram_socket as create_unix_datagram_socket +from ._core._sockets import create_unix_listener as create_unix_listener +from ._core._sockets import getaddrinfo as getaddrinfo +from ._core._sockets import getnameinfo as getnameinfo +from ._core._sockets import notify_closing as notify_closing +from ._core._sockets import wait_readable as wait_readable +from ._core._sockets import wait_socket_readable as wait_socket_readable +from ._core._sockets import wait_socket_writable as wait_socket_writable +from ._core._sockets import wait_writable as wait_writable +from ._core._streams import create_memory_object_stream as create_memory_object_stream +from ._core._subprocesses import open_process as open_process +from ._core._subprocesses import run_process as run_process +from ._core._synchronization import CapacityLimiter as CapacityLimiter +from ._core._synchronization import ( + CapacityLimiterStatistics as CapacityLimiterStatistics, +) +from ._core._synchronization import Condition as Condition +from ._core._synchronization import ConditionStatistics as ConditionStatistics +from ._core._synchronization import Event as Event +from ._core._synchronization import EventStatistics as EventStatistics +from ._core._synchronization import Lock as Lock +from ._core._synchronization import LockStatistics as LockStatistics +from ._core._synchronization import ResourceGuard as ResourceGuard +from ._core._synchronization import Semaphore as Semaphore +from ._core._synchronization import SemaphoreStatistics as SemaphoreStatistics +from ._core._tasks import TASK_STATUS_IGNORED as TASK_STATUS_IGNORED +from ._core._tasks import CancelScope as CancelScope +from ._core._tasks import create_task_group as create_task_group +from ._core._tasks import current_effective_deadline as current_effective_deadline +from ._core._tasks import fail_after as fail_after +from ._core._tasks import move_on_after as move_on_after +from ._core._tempfile import NamedTemporaryFile as NamedTemporaryFile +from ._core._tempfile import SpooledTemporaryFile as SpooledTemporaryFile +from ._core._tempfile import TemporaryDirectory as TemporaryDirectory +from ._core._tempfile import TemporaryFile as TemporaryFile +from ._core._tempfile import gettempdir as gettempdir +from ._core._tempfile import gettempdirb as gettempdirb +from ._core._tempfile import mkdtemp as mkdtemp +from ._core._tempfile import mkstemp as mkstemp +from ._core._testing import TaskInfo as TaskInfo +from ._core._testing import get_current_task as get_current_task +from ._core._testing import get_running_tasks as get_running_tasks +from ._core._testing import wait_all_tasks_blocked as wait_all_tasks_blocked +from ._core._typedattr import TypedAttributeProvider as TypedAttributeProvider +from ._core._typedattr import TypedAttributeSet as TypedAttributeSet +from ._core._typedattr import typed_attribute as typed_attribute + +# Re-export imports so they look like they live directly in this package +for __value in list(locals().values()): + if getattr(__value, "__module__", "").startswith("anyio."): + __value.__module__ = __name__ + + +del __value + + +def __getattr__(attr: str) -> type[BrokenWorkerInterpreter]: + """Support deprecated aliases.""" + if attr == "BrokenWorkerIntepreter": + import warnings + + warnings.warn( + "The 'BrokenWorkerIntepreter' alias is deprecated, use 'BrokenWorkerInterpreter' instead.", + DeprecationWarning, + stacklevel=2, + ) + return BrokenWorkerInterpreter + + raise AttributeError(f"module {__name__!r} has no attribute {attr!r}") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_backends/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_backends/_asyncio.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_backends/_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..8ff009e2699a3731e9b42e3318b87ef72f90900c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_backends/_asyncio.py @@ -0,0 +1,2980 @@ +from __future__ import annotations + +import array +import asyncio +import concurrent.futures +import contextvars +import math +import os +import socket +import sys +import threading +import weakref +from asyncio import ( + AbstractEventLoop, + CancelledError, + all_tasks, + create_task, + current_task, + get_running_loop, + sleep, +) +from asyncio.base_events import _run_until_complete_cb # type: ignore[attr-defined] +from collections import OrderedDict, deque +from collections.abc import ( + AsyncGenerator, + AsyncIterator, + Awaitable, + Callable, + Collection, + Coroutine, + Iterable, + Sequence, +) +from concurrent.futures import Future +from contextlib import AbstractContextManager, suppress +from contextvars import Context, copy_context +from dataclasses import dataclass, field +from functools import partial, wraps +from inspect import ( + CORO_RUNNING, + CORO_SUSPENDED, + getcoroutinestate, + iscoroutine, +) +from io import IOBase +from os import PathLike +from queue import Queue +from signal import Signals +from socket import AddressFamily, SocketKind +from threading import Thread +from types import CodeType, TracebackType +from typing import ( + IO, + TYPE_CHECKING, + Any, + Optional, + TypeVar, + cast, +) +from weakref import WeakKeyDictionary + +from .. import ( + CapacityLimiterStatistics, + EventStatistics, + LockStatistics, + TaskInfo, + abc, +) +from .._core._eventloop import ( + claim_worker_thread, + set_current_async_library, + threadlocals, +) +from .._core._exceptions import ( + BrokenResourceError, + BusyResourceError, + ClosedResourceError, + EndOfStream, + RunFinishedError, + WouldBlock, + iterate_exceptions, +) +from .._core._sockets import convert_ipv6_sockaddr +from .._core._streams import create_memory_object_stream +from .._core._synchronization import ( + CapacityLimiter as BaseCapacityLimiter, +) +from .._core._synchronization import Event as BaseEvent +from .._core._synchronization import Lock as BaseLock +from .._core._synchronization import ( + ResourceGuard, + SemaphoreStatistics, +) +from .._core._synchronization import Semaphore as BaseSemaphore +from .._core._tasks import CancelScope as BaseCancelScope +from ..abc import ( + AsyncBackend, + IPSockAddrType, + SocketListener, + UDPPacketType, + UNIXDatagramPacketType, +) +from ..abc._eventloop import StrOrBytesPath +from ..lowlevel import RunVar +from ..streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream + +if TYPE_CHECKING: + from _typeshed import FileDescriptorLike +else: + FileDescriptorLike = object + +if sys.version_info >= (3, 10): + from typing import ParamSpec +else: + from typing_extensions import ParamSpec + +if sys.version_info >= (3, 11): + from asyncio import Runner + from typing import TypeVarTuple, Unpack +else: + import contextvars + import enum + import signal + from asyncio import coroutines, events, exceptions, tasks + + from exceptiongroup import BaseExceptionGroup + from typing_extensions import TypeVarTuple, Unpack + + class _State(enum.Enum): + CREATED = "created" + INITIALIZED = "initialized" + CLOSED = "closed" + + class Runner: + # Copied from CPython 3.11 + def __init__( + self, + *, + debug: bool | None = None, + loop_factory: Callable[[], AbstractEventLoop] | None = None, + ): + self._state = _State.CREATED + self._debug = debug + self._loop_factory = loop_factory + self._loop: AbstractEventLoop | None = None + self._context = None + self._interrupt_count = 0 + self._set_event_loop = False + + def __enter__(self) -> Runner: + self._lazy_init() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.close() + + def close(self) -> None: + """Shutdown and close event loop.""" + loop = self._loop + if self._state is not _State.INITIALIZED or loop is None: + return + try: + _cancel_all_tasks(loop) + loop.run_until_complete(loop.shutdown_asyncgens()) + if hasattr(loop, "shutdown_default_executor"): + loop.run_until_complete(loop.shutdown_default_executor()) + else: + loop.run_until_complete(_shutdown_default_executor(loop)) + finally: + if self._set_event_loop: + events.set_event_loop(None) + loop.close() + self._loop = None + self._state = _State.CLOSED + + def get_loop(self) -> AbstractEventLoop: + """Return embedded event loop.""" + self._lazy_init() + return self._loop + + def run(self, coro: Coroutine[T_Retval], *, context=None) -> T_Retval: + """Run a coroutine inside the embedded event loop.""" + if not coroutines.iscoroutine(coro): + raise ValueError(f"a coroutine was expected, got {coro!r}") + + if events._get_running_loop() is not None: + # fail fast with short traceback + raise RuntimeError( + "Runner.run() cannot be called from a running event loop" + ) + + self._lazy_init() + + if context is None: + context = self._context + task = context.run(self._loop.create_task, coro) + + if ( + threading.current_thread() is threading.main_thread() + and signal.getsignal(signal.SIGINT) is signal.default_int_handler + ): + sigint_handler = partial(self._on_sigint, main_task=task) + try: + signal.signal(signal.SIGINT, sigint_handler) + except ValueError: + # `signal.signal` may throw if `threading.main_thread` does + # not support signals (e.g. embedded interpreter with signals + # not registered - see gh-91880) + sigint_handler = None + else: + sigint_handler = None + + self._interrupt_count = 0 + try: + return self._loop.run_until_complete(task) + except exceptions.CancelledError: + if self._interrupt_count > 0: + uncancel = getattr(task, "uncancel", None) + if uncancel is not None and uncancel() == 0: + raise KeyboardInterrupt # noqa: B904 + raise # CancelledError + finally: + if ( + sigint_handler is not None + and signal.getsignal(signal.SIGINT) is sigint_handler + ): + signal.signal(signal.SIGINT, signal.default_int_handler) + + def _lazy_init(self) -> None: + if self._state is _State.CLOSED: + raise RuntimeError("Runner is closed") + if self._state is _State.INITIALIZED: + return + if self._loop_factory is None: + self._loop = events.new_event_loop() + if not self._set_event_loop: + # Call set_event_loop only once to avoid calling + # attach_loop multiple times on child watchers + events.set_event_loop(self._loop) + self._set_event_loop = True + else: + self._loop = self._loop_factory() + if self._debug is not None: + self._loop.set_debug(self._debug) + self._context = contextvars.copy_context() + self._state = _State.INITIALIZED + + def _on_sigint(self, signum, frame, main_task: asyncio.Task) -> None: + self._interrupt_count += 1 + if self._interrupt_count == 1 and not main_task.done(): + main_task.cancel() + # wakeup loop if it is blocked by select() with long timeout + self._loop.call_soon_threadsafe(lambda: None) + return + raise KeyboardInterrupt() + + def _cancel_all_tasks(loop: AbstractEventLoop) -> None: + to_cancel = tasks.all_tasks(loop) + if not to_cancel: + return + + for task in to_cancel: + task.cancel() + + loop.run_until_complete(tasks.gather(*to_cancel, return_exceptions=True)) + + for task in to_cancel: + if task.cancelled(): + continue + if task.exception() is not None: + loop.call_exception_handler( + { + "message": "unhandled exception during asyncio.run() shutdown", + "exception": task.exception(), + "task": task, + } + ) + + async def _shutdown_default_executor(loop: AbstractEventLoop) -> None: + """Schedule the shutdown of the default executor.""" + + def _do_shutdown(future: asyncio.futures.Future) -> None: + try: + loop._default_executor.shutdown(wait=True) # type: ignore[attr-defined] + loop.call_soon_threadsafe(future.set_result, None) + except Exception as ex: + loop.call_soon_threadsafe(future.set_exception, ex) + + loop._executor_shutdown_called = True + if loop._default_executor is None: + return + future = loop.create_future() + thread = threading.Thread(target=_do_shutdown, args=(future,)) + thread.start() + try: + await future + finally: + thread.join() + + +T_Retval = TypeVar("T_Retval") +T_contra = TypeVar("T_contra", contravariant=True) +PosArgsT = TypeVarTuple("PosArgsT") +P = ParamSpec("P") + +_root_task: RunVar[asyncio.Task | None] = RunVar("_root_task") + + +def find_root_task() -> asyncio.Task: + root_task = _root_task.get(None) + if root_task is not None and not root_task.done(): + return root_task + + # Look for a task that has been started via run_until_complete() + for task in all_tasks(): + if task._callbacks and not task.done(): + callbacks = [cb for cb, context in task._callbacks] + for cb in callbacks: + if ( + cb is _run_until_complete_cb + or getattr(cb, "__module__", None) == "uvloop.loop" + ): + _root_task.set(task) + return task + + # Look up the topmost task in the AnyIO task tree, if possible + task = cast(asyncio.Task, current_task()) + state = _task_states.get(task) + if state: + cancel_scope = state.cancel_scope + while cancel_scope and cancel_scope._parent_scope is not None: + cancel_scope = cancel_scope._parent_scope + + if cancel_scope is not None: + return cast(asyncio.Task, cancel_scope._host_task) + + return task + + +def get_callable_name(func: Callable) -> str: + module = getattr(func, "__module__", None) + qualname = getattr(func, "__qualname__", None) + return ".".join([x for x in (module, qualname) if x]) + + +# +# Event loop +# + +_run_vars: WeakKeyDictionary[asyncio.AbstractEventLoop, Any] = WeakKeyDictionary() + + +def _task_started(task: asyncio.Task) -> bool: + """Return ``True`` if the task has been started and has not finished.""" + # The task coro should never be None here, as we never add finished tasks to the + # task list + coro = task.get_coro() + assert coro is not None + try: + return getcoroutinestate(coro) in (CORO_RUNNING, CORO_SUSPENDED) + except AttributeError: + # task coro is async_genenerator_asend https://bugs.python.org/issue37771 + raise Exception(f"Cannot determine if task {task} has started or not") from None + + +# +# Timeouts and cancellation +# + + +def is_anyio_cancellation(exc: CancelledError) -> bool: + # Sometimes third party frameworks catch a CancelledError and raise a new one, so as + # a workaround we have to look at the previous ones in __context__ too for a + # matching cancel message + while True: + if ( + exc.args + and isinstance(exc.args[0], str) + and exc.args[0].startswith("Cancelled via cancel scope ") + ): + return True + + if isinstance(exc.__context__, CancelledError): + exc = exc.__context__ + continue + + return False + + +class CancelScope(BaseCancelScope): + def __new__( + cls, *, deadline: float = math.inf, shield: bool = False + ) -> CancelScope: + return object.__new__(cls) + + def __init__(self, deadline: float = math.inf, shield: bool = False): + self._deadline = deadline + self._shield = shield + self._parent_scope: CancelScope | None = None + self._child_scopes: set[CancelScope] = set() + self._cancel_called = False + self._cancel_reason: str | None = None + self._cancelled_caught = False + self._active = False + self._timeout_handle: asyncio.TimerHandle | None = None + self._cancel_handle: asyncio.Handle | None = None + self._tasks: set[asyncio.Task] = set() + self._host_task: asyncio.Task | None = None + if sys.version_info >= (3, 11): + self._pending_uncancellations: int | None = 0 + else: + self._pending_uncancellations = None + + def __enter__(self) -> CancelScope: + if self._active: + raise RuntimeError( + "Each CancelScope may only be used for a single 'with' block" + ) + + self._host_task = host_task = cast(asyncio.Task, current_task()) + self._tasks.add(host_task) + try: + task_state = _task_states[host_task] + except KeyError: + task_state = TaskState(None, self) + _task_states[host_task] = task_state + else: + self._parent_scope = task_state.cancel_scope + task_state.cancel_scope = self + if self._parent_scope is not None: + # If using an eager task factory, the parent scope may not even contain + # the host task + self._parent_scope._child_scopes.add(self) + self._parent_scope._tasks.discard(host_task) + + self._timeout() + self._active = True + + # Start cancelling the host task if the scope was cancelled before entering + if self._cancel_called: + self._deliver_cancellation(self) + + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + del exc_tb + + if not self._active: + raise RuntimeError("This cancel scope is not active") + if current_task() is not self._host_task: + raise RuntimeError( + "Attempted to exit cancel scope in a different task than it was " + "entered in" + ) + + assert self._host_task is not None + host_task_state = _task_states.get(self._host_task) + if host_task_state is None or host_task_state.cancel_scope is not self: + raise RuntimeError( + "Attempted to exit a cancel scope that isn't the current tasks's " + "current cancel scope" + ) + + try: + self._active = False + if self._timeout_handle: + self._timeout_handle.cancel() + self._timeout_handle = None + + self._tasks.remove(self._host_task) + if self._parent_scope is not None: + self._parent_scope._child_scopes.remove(self) + self._parent_scope._tasks.add(self._host_task) + + host_task_state.cancel_scope = self._parent_scope + + # Restart the cancellation effort in the closest visible, cancelled parent + # scope if necessary + self._restart_cancellation_in_parent() + + # We only swallow the exception iff it was an AnyIO CancelledError, either + # directly as exc_val or inside an exception group and there are no cancelled + # parent cancel scopes visible to us here + if self._cancel_called and not self._parent_cancellation_is_visible_to_us: + # For each level-cancel() call made on the host task, call uncancel() + while self._pending_uncancellations: + self._host_task.uncancel() + self._pending_uncancellations -= 1 + + # Update cancelled_caught and check for exceptions we must not swallow + cannot_swallow_exc_val = False + if exc_val is not None: + for exc in iterate_exceptions(exc_val): + if isinstance(exc, CancelledError) and is_anyio_cancellation( + exc + ): + self._cancelled_caught = True + else: + cannot_swallow_exc_val = True + + return self._cancelled_caught and not cannot_swallow_exc_val + else: + if self._pending_uncancellations: + assert self._parent_scope is not None + assert self._parent_scope._pending_uncancellations is not None + self._parent_scope._pending_uncancellations += ( + self._pending_uncancellations + ) + self._pending_uncancellations = 0 + + return False + finally: + self._host_task = None + del exc_val + + @property + def _effectively_cancelled(self) -> bool: + cancel_scope: CancelScope | None = self + while cancel_scope is not None: + if cancel_scope._cancel_called: + return True + + if cancel_scope.shield: + return False + + cancel_scope = cancel_scope._parent_scope + + return False + + @property + def _parent_cancellation_is_visible_to_us(self) -> bool: + return ( + self._parent_scope is not None + and not self.shield + and self._parent_scope._effectively_cancelled + ) + + def _timeout(self) -> None: + if self._deadline != math.inf: + loop = get_running_loop() + if loop.time() >= self._deadline: + self.cancel("deadline exceeded") + else: + self._timeout_handle = loop.call_at(self._deadline, self._timeout) + + def _deliver_cancellation(self, origin: CancelScope) -> bool: + """ + Deliver cancellation to directly contained tasks and nested cancel scopes. + + Schedule another run at the end if we still have tasks eligible for + cancellation. + + :param origin: the cancel scope that originated the cancellation + :return: ``True`` if the delivery needs to be retried on the next cycle + + """ + should_retry = False + current = current_task() + for task in self._tasks: + should_retry = True + if task._must_cancel: # type: ignore[attr-defined] + continue + + # The task is eligible for cancellation if it has started + if task is not current and (task is self._host_task or _task_started(task)): + waiter = task._fut_waiter # type: ignore[attr-defined] + if not isinstance(waiter, asyncio.Future) or not waiter.done(): + task.cancel(origin._cancel_reason) + if ( + task is origin._host_task + and origin._pending_uncancellations is not None + ): + origin._pending_uncancellations += 1 + + # Deliver cancellation to child scopes that aren't shielded or running their own + # cancellation callbacks + for scope in self._child_scopes: + if not scope._shield and not scope.cancel_called: + should_retry = scope._deliver_cancellation(origin) or should_retry + + # Schedule another callback if there are still tasks left + if origin is self: + if should_retry: + self._cancel_handle = get_running_loop().call_soon( + self._deliver_cancellation, origin + ) + else: + self._cancel_handle = None + + return should_retry + + def _restart_cancellation_in_parent(self) -> None: + """ + Restart the cancellation effort in the closest directly cancelled parent scope. + + """ + scope = self._parent_scope + while scope is not None: + if scope._cancel_called: + if scope._cancel_handle is None: + scope._deliver_cancellation(scope) + + break + + # No point in looking beyond any shielded scope + if scope._shield: + break + + scope = scope._parent_scope + + def cancel(self, reason: str | None = None) -> None: + if not self._cancel_called: + if self._timeout_handle: + self._timeout_handle.cancel() + self._timeout_handle = None + + self._cancel_called = True + self._cancel_reason = f"Cancelled via cancel scope {id(self):x}" + if task := current_task(): + self._cancel_reason += f" by {task}" + + if reason: + self._cancel_reason += f"; reason: {reason}" + + if self._host_task is not None: + self._deliver_cancellation(self) + + @property + def deadline(self) -> float: + return self._deadline + + @deadline.setter + def deadline(self, value: float) -> None: + self._deadline = float(value) + if self._timeout_handle is not None: + self._timeout_handle.cancel() + self._timeout_handle = None + + if self._active and not self._cancel_called: + self._timeout() + + @property + def cancel_called(self) -> bool: + return self._cancel_called + + @property + def cancelled_caught(self) -> bool: + return self._cancelled_caught + + @property + def shield(self) -> bool: + return self._shield + + @shield.setter + def shield(self, value: bool) -> None: + if self._shield != value: + self._shield = value + if not value: + self._restart_cancellation_in_parent() + + +# +# Task states +# + + +class TaskState: + """ + Encapsulates auxiliary task information that cannot be added to the Task instance + itself because there are no guarantees about its implementation. + """ + + __slots__ = "parent_id", "cancel_scope", "__weakref__" + + def __init__(self, parent_id: int | None, cancel_scope: CancelScope | None): + self.parent_id = parent_id + self.cancel_scope = cancel_scope + + +_task_states: WeakKeyDictionary[asyncio.Task, TaskState] = WeakKeyDictionary() + + +# +# Task groups +# + + +class _AsyncioTaskStatus(abc.TaskStatus): + def __init__(self, future: asyncio.Future, parent_id: int): + self._future = future + self._parent_id = parent_id + + def started(self, value: T_contra | None = None) -> None: + try: + self._future.set_result(value) + except asyncio.InvalidStateError: + if not self._future.cancelled(): + raise RuntimeError( + "called 'started' twice on the same task status" + ) from None + + task = cast(asyncio.Task, current_task()) + _task_states[task].parent_id = self._parent_id + + +if sys.version_info >= (3, 12): + _eager_task_factory_code: CodeType | None = asyncio.eager_task_factory.__code__ +else: + _eager_task_factory_code = None + + +class TaskGroup(abc.TaskGroup): + def __init__(self) -> None: + self.cancel_scope: CancelScope = CancelScope() + self._active = False + self._exceptions: list[BaseException] = [] + self._tasks: set[asyncio.Task] = set() + self._on_completed_fut: asyncio.Future[None] | None = None + + async def __aenter__(self) -> TaskGroup: + self.cancel_scope.__enter__() + self._active = True + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + try: + if exc_val is not None: + self.cancel_scope.cancel() + if not isinstance(exc_val, CancelledError): + self._exceptions.append(exc_val) + + loop = get_running_loop() + try: + if self._tasks: + with CancelScope() as wait_scope: + while self._tasks: + self._on_completed_fut = loop.create_future() + + try: + await self._on_completed_fut + except CancelledError as exc: + # Shield the scope against further cancellation attempts, + # as they're not productive (#695) + wait_scope.shield = True + self.cancel_scope.cancel() + + # Set exc_val from the cancellation exception if it was + # previously unset. However, we should not replace a native + # cancellation exception with one raise by a cancel scope. + if exc_val is None or ( + isinstance(exc_val, CancelledError) + and not is_anyio_cancellation(exc) + ): + exc_val = exc + + self._on_completed_fut = None + else: + # If there are no child tasks to wait on, run at least one checkpoint + # anyway + await AsyncIOBackend.cancel_shielded_checkpoint() + + self._active = False + if self._exceptions: + # The exception that got us here should already have been + # added to self._exceptions so it's ok to break exception + # chaining and avoid adding a "During handling of above..." + # for each nesting level. + raise BaseExceptionGroup( + "unhandled errors in a TaskGroup", self._exceptions + ) from None + elif exc_val: + raise exc_val + except BaseException as exc: + if self.cancel_scope.__exit__(type(exc), exc, exc.__traceback__): + return True + + raise + + return self.cancel_scope.__exit__(exc_type, exc_val, exc_tb) + finally: + del exc_val, exc_tb, self._exceptions + + def _spawn( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[Any]], + args: tuple[Unpack[PosArgsT]], + name: object, + task_status_future: asyncio.Future | None = None, + ) -> asyncio.Task: + def task_done(_task: asyncio.Task) -> None: + if sys.version_info >= (3, 14) and self.cancel_scope._host_task is not None: + asyncio.future_discard_from_awaited_by( + _task, self.cancel_scope._host_task + ) + + task_state = _task_states[_task] + assert task_state.cancel_scope is not None + assert _task in task_state.cancel_scope._tasks + task_state.cancel_scope._tasks.remove(_task) + self._tasks.remove(task) + del _task_states[_task] + + if self._on_completed_fut is not None and not self._tasks: + try: + self._on_completed_fut.set_result(None) + except asyncio.InvalidStateError: + pass + + try: + exc = _task.exception() + except CancelledError as e: + while isinstance(e.__context__, CancelledError): + e = e.__context__ + + exc = e + + if exc is not None: + # The future can only be in the cancelled state if the host task was + # cancelled, so return immediately instead of adding one more + # CancelledError to the exceptions list + if task_status_future is not None and task_status_future.cancelled(): + return + + if task_status_future is None or task_status_future.done(): + if not isinstance(exc, CancelledError): + self._exceptions.append(exc) + + if not self.cancel_scope._effectively_cancelled: + self.cancel_scope.cancel() + else: + task_status_future.set_exception(exc) + elif task_status_future is not None and not task_status_future.done(): + task_status_future.set_exception( + RuntimeError("Child exited without calling task_status.started()") + ) + + if not self._active: + raise RuntimeError( + "This task group is not active; no new tasks can be started." + ) + + kwargs = {} + if task_status_future: + parent_id = id(current_task()) + kwargs["task_status"] = _AsyncioTaskStatus( + task_status_future, id(self.cancel_scope._host_task) + ) + else: + parent_id = id(self.cancel_scope._host_task) + + coro = func(*args, **kwargs) + if not iscoroutine(coro): + prefix = f"{func.__module__}." if hasattr(func, "__module__") else "" + raise TypeError( + f"Expected {prefix}{func.__qualname__}() to return a coroutine, but " + f"the return value ({coro!r}) is not a coroutine object" + ) + + name = get_callable_name(func) if name is None else str(name) + loop = asyncio.get_running_loop() + if ( + (factory := loop.get_task_factory()) + and getattr(factory, "__code__", None) is _eager_task_factory_code + and (closure := getattr(factory, "__closure__", None)) + ): + custom_task_constructor = closure[0].cell_contents + task = custom_task_constructor(coro, loop=loop, name=name) + else: + task = create_task(coro, name=name) + + # Make the spawned task inherit the task group's cancel scope + _task_states[task] = TaskState( + parent_id=parent_id, cancel_scope=self.cancel_scope + ) + self.cancel_scope._tasks.add(task) + self._tasks.add(task) + if sys.version_info >= (3, 14) and self.cancel_scope._host_task is not None: + asyncio.future_add_to_awaited_by(task, self.cancel_scope._host_task) + + task.add_done_callback(task_done) + return task + + def start_soon( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[Any]], + *args: Unpack[PosArgsT], + name: object = None, + ) -> None: + self._spawn(func, args, name) + + async def start( + self, func: Callable[..., Awaitable[Any]], *args: object, name: object = None + ) -> Any: + future: asyncio.Future = asyncio.Future() + task = self._spawn(func, args, name, future) + + # If the task raises an exception after sending a start value without a switch + # point between, the task group is cancelled and this method never proceeds to + # process the completed future. That's why we have to have a shielded cancel + # scope here. + try: + return await future + except CancelledError: + # Cancel the task and wait for it to exit before returning + task.cancel() + with CancelScope(shield=True), suppress(CancelledError): + await task + + raise + + +# +# Threads +# + +_Retval_Queue_Type = tuple[Optional[T_Retval], Optional[BaseException]] + + +class WorkerThread(Thread): + MAX_IDLE_TIME = 10 # seconds + + def __init__( + self, + root_task: asyncio.Task, + workers: set[WorkerThread], + idle_workers: deque[WorkerThread], + ): + super().__init__(name="AnyIO worker thread") + self.root_task = root_task + self.workers = workers + self.idle_workers = idle_workers + self.loop = root_task._loop + self.queue: Queue[ + tuple[Context, Callable, tuple, asyncio.Future, CancelScope] | None + ] = Queue(2) + self.idle_since = AsyncIOBackend.current_time() + self.stopping = False + + def _report_result( + self, future: asyncio.Future, result: Any, exc: BaseException | None + ) -> None: + self.idle_since = AsyncIOBackend.current_time() + if not self.stopping: + self.idle_workers.append(self) + + if not future.cancelled(): + if exc is not None: + if isinstance(exc, StopIteration): + new_exc = RuntimeError("coroutine raised StopIteration") + new_exc.__cause__ = exc + exc = new_exc + + future.set_exception(exc) + else: + future.set_result(result) + + def run(self) -> None: + with claim_worker_thread(AsyncIOBackend, self.loop): + while True: + item = self.queue.get() + if item is None: + # Shutdown command received + return + + context, func, args, future, cancel_scope = item + if not future.cancelled(): + result = None + exception: BaseException | None = None + threadlocals.current_cancel_scope = cancel_scope + try: + result = context.run(func, *args) + except BaseException as exc: + exception = exc + finally: + del threadlocals.current_cancel_scope + + if not self.loop.is_closed(): + self.loop.call_soon_threadsafe( + self._report_result, future, result, exception + ) + + del result, exception + + self.queue.task_done() + del item, context, func, args, future, cancel_scope + + def stop(self, f: asyncio.Task | None = None) -> None: + self.stopping = True + self.queue.put_nowait(None) + self.workers.discard(self) + try: + self.idle_workers.remove(self) + except ValueError: + pass + + +_threadpool_idle_workers: RunVar[deque[WorkerThread]] = RunVar( + "_threadpool_idle_workers" +) +_threadpool_workers: RunVar[set[WorkerThread]] = RunVar("_threadpool_workers") + + +# +# Subprocesses +# + + +@dataclass(eq=False) +class StreamReaderWrapper(abc.ByteReceiveStream): + _stream: asyncio.StreamReader + + async def receive(self, max_bytes: int = 65536) -> bytes: + data = await self._stream.read(max_bytes) + if data: + return data + else: + raise EndOfStream + + async def aclose(self) -> None: + self._stream.set_exception(ClosedResourceError()) + await AsyncIOBackend.checkpoint() + + +@dataclass(eq=False) +class StreamWriterWrapper(abc.ByteSendStream): + _stream: asyncio.StreamWriter + _closed: bool = field(init=False, default=False) + + async def send(self, item: bytes) -> None: + await AsyncIOBackend.checkpoint_if_cancelled() + stream_paused = self._stream._protocol._paused # type: ignore[attr-defined] + try: + self._stream.write(item) + await self._stream.drain() + except (ConnectionResetError, BrokenPipeError, RuntimeError) as exc: + # If closed by us and/or the peer: + # * on stdlib, drain() raises ConnectionResetError or BrokenPipeError + # * on uvloop and Winloop, write() eventually starts raising RuntimeError + if self._closed: + raise ClosedResourceError from exc + elif self._stream.is_closing(): + raise BrokenResourceError from exc + + raise + + if not stream_paused: + await AsyncIOBackend.cancel_shielded_checkpoint() + + async def aclose(self) -> None: + self._closed = True + self._stream.close() + await AsyncIOBackend.checkpoint() + + +@dataclass(eq=False) +class Process(abc.Process): + _process: asyncio.subprocess.Process + _stdin: StreamWriterWrapper | None + _stdout: StreamReaderWrapper | None + _stderr: StreamReaderWrapper | None + + async def aclose(self) -> None: + with CancelScope(shield=True) as scope: + if self._stdin: + await self._stdin.aclose() + if self._stdout: + await self._stdout.aclose() + if self._stderr: + await self._stderr.aclose() + + scope.shield = False + try: + await self.wait() + except BaseException: + scope.shield = True + self.kill() + await self.wait() + raise + + async def wait(self) -> int: + return await self._process.wait() + + def terminate(self) -> None: + self._process.terminate() + + def kill(self) -> None: + self._process.kill() + + def send_signal(self, signal: int) -> None: + self._process.send_signal(signal) + + @property + def pid(self) -> int: + return self._process.pid + + @property + def returncode(self) -> int | None: + return self._process.returncode + + @property + def stdin(self) -> abc.ByteSendStream | None: + return self._stdin + + @property + def stdout(self) -> abc.ByteReceiveStream | None: + return self._stdout + + @property + def stderr(self) -> abc.ByteReceiveStream | None: + return self._stderr + + +def _forcibly_shutdown_process_pool_on_exit( + workers: set[Process], _task: object +) -> None: + """ + Forcibly shuts down worker processes belonging to this event loop.""" + child_watcher: asyncio.AbstractChildWatcher | None = None # type: ignore[name-defined] + if sys.version_info < (3, 12): + try: + child_watcher = asyncio.get_event_loop_policy().get_child_watcher() + except NotImplementedError: + pass + + # Close as much as possible (w/o async/await) to avoid warnings + for process in workers.copy(): + if process.returncode is None: + continue + + process._stdin._stream._transport.close() # type: ignore[union-attr] + process._stdout._stream._transport.close() # type: ignore[union-attr] + process._stderr._stream._transport.close() # type: ignore[union-attr] + process.kill() + if child_watcher: + child_watcher.remove_child_handler(process.pid) + + +async def _shutdown_process_pool_on_exit(workers: set[abc.Process]) -> None: + """ + Shuts down worker processes belonging to this event loop. + + NOTE: this only works when the event loop was started using asyncio.run() or + anyio.run(). + + """ + process: abc.Process + try: + await sleep(math.inf) + except asyncio.CancelledError: + workers = workers.copy() + for process in workers: + if process.returncode is None: + process.kill() + + for process in workers: + await process.aclose() + + +# +# Sockets and networking +# + + +class StreamProtocol(asyncio.Protocol): + read_queue: deque[bytes] + read_event: asyncio.Event + write_event: asyncio.Event + exception: Exception | None = None + is_at_eof: bool = False + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + self.read_queue = deque() + self.read_event = asyncio.Event() + self.write_event = asyncio.Event() + self.write_event.set() + cast(asyncio.Transport, transport).set_write_buffer_limits(0) + + def connection_lost(self, exc: Exception | None) -> None: + if exc: + self.exception = BrokenResourceError() + self.exception.__cause__ = exc + + self.read_event.set() + self.write_event.set() + + def data_received(self, data: bytes) -> None: + # ProactorEventloop sometimes sends bytearray instead of bytes + self.read_queue.append(bytes(data)) + self.read_event.set() + + def eof_received(self) -> bool | None: + self.is_at_eof = True + self.read_event.set() + return True + + def pause_writing(self) -> None: + self.write_event = asyncio.Event() + + def resume_writing(self) -> None: + self.write_event.set() + + +class DatagramProtocol(asyncio.DatagramProtocol): + read_queue: deque[tuple[bytes, IPSockAddrType]] + read_event: asyncio.Event + write_event: asyncio.Event + exception: Exception | None = None + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + self.read_queue = deque(maxlen=100) # arbitrary value + self.read_event = asyncio.Event() + self.write_event = asyncio.Event() + self.write_event.set() + + def connection_lost(self, exc: Exception | None) -> None: + self.read_event.set() + self.write_event.set() + + def datagram_received(self, data: bytes, addr: IPSockAddrType) -> None: + addr = convert_ipv6_sockaddr(addr) + self.read_queue.append((data, addr)) + self.read_event.set() + + def error_received(self, exc: Exception) -> None: + self.exception = exc + + def pause_writing(self) -> None: + self.write_event.clear() + + def resume_writing(self) -> None: + self.write_event.set() + + +class SocketStream(abc.SocketStream): + def __init__(self, transport: asyncio.Transport, protocol: StreamProtocol): + self._transport = transport + self._protocol = protocol + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + self._closed = False + + @property + def _raw_socket(self) -> socket.socket: + return self._transport.get_extra_info("socket") + + async def receive(self, max_bytes: int = 65536) -> bytes: + with self._receive_guard: + if ( + not self._protocol.read_event.is_set() + and not self._transport.is_closing() + and not self._protocol.is_at_eof + ): + self._transport.resume_reading() + await self._protocol.read_event.wait() + self._transport.pause_reading() + else: + await AsyncIOBackend.checkpoint() + + try: + chunk = self._protocol.read_queue.popleft() + except IndexError: + if self._closed: + raise ClosedResourceError from None + elif self._protocol.exception: + raise self._protocol.exception from None + else: + raise EndOfStream from None + + if len(chunk) > max_bytes: + # Split the oversized chunk + chunk, leftover = chunk[:max_bytes], chunk[max_bytes:] + self._protocol.read_queue.appendleft(leftover) + + # If the read queue is empty, clear the flag so that the next call will + # block until data is available + if not self._protocol.read_queue: + self._protocol.read_event.clear() + + return chunk + + async def send(self, item: bytes) -> None: + with self._send_guard: + await AsyncIOBackend.checkpoint() + + if self._closed: + raise ClosedResourceError + elif self._protocol.exception is not None: + raise self._protocol.exception + + try: + self._transport.write(item) + except RuntimeError as exc: + if self._transport.is_closing(): + raise BrokenResourceError from exc + else: + raise + + await self._protocol.write_event.wait() + + async def send_eof(self) -> None: + try: + self._transport.write_eof() + except OSError: + pass + + async def aclose(self) -> None: + self._closed = True + if not self._transport.is_closing(): + try: + self._transport.write_eof() + except OSError: + pass + + self._transport.close() + await sleep(0) + self._transport.abort() + + +class _RawSocketMixin: + _receive_future: asyncio.Future | None = None + _send_future: asyncio.Future | None = None + _closing = False + + def __init__(self, raw_socket: socket.socket): + self.__raw_socket = raw_socket + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + + @property + def _raw_socket(self) -> socket.socket: + return self.__raw_socket + + def _wait_until_readable(self, loop: asyncio.AbstractEventLoop) -> asyncio.Future: + def callback(f: object) -> None: + del self._receive_future + loop.remove_reader(self.__raw_socket) + + f = self._receive_future = asyncio.Future() + loop.add_reader(self.__raw_socket, f.set_result, None) + f.add_done_callback(callback) + return f + + def _wait_until_writable(self, loop: asyncio.AbstractEventLoop) -> asyncio.Future: + def callback(f: object) -> None: + del self._send_future + loop.remove_writer(self.__raw_socket) + + f = self._send_future = asyncio.Future() + loop.add_writer(self.__raw_socket, f.set_result, None) + f.add_done_callback(callback) + return f + + async def aclose(self) -> None: + if not self._closing: + self._closing = True + if self.__raw_socket.fileno() != -1: + self.__raw_socket.close() + + if self._receive_future: + self._receive_future.set_result(None) + if self._send_future: + self._send_future.set_result(None) + + +class UNIXSocketStream(_RawSocketMixin, abc.UNIXSocketStream): + async def send_eof(self) -> None: + with self._send_guard: + self._raw_socket.shutdown(socket.SHUT_WR) + + async def receive(self, max_bytes: int = 65536) -> bytes: + loop = get_running_loop() + await AsyncIOBackend.checkpoint() + with self._receive_guard: + while True: + try: + data = self._raw_socket.recv(max_bytes) + except BlockingIOError: + await self._wait_until_readable(loop) + except OSError as exc: + if self._closing: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + else: + if not data: + raise EndOfStream + + return data + + async def send(self, item: bytes) -> None: + loop = get_running_loop() + await AsyncIOBackend.checkpoint() + with self._send_guard: + view = memoryview(item) + while view: + try: + bytes_sent = self._raw_socket.send(view) + except BlockingIOError: + await self._wait_until_writable(loop) + except OSError as exc: + if self._closing: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + else: + view = view[bytes_sent:] + + async def receive_fds(self, msglen: int, maxfds: int) -> tuple[bytes, list[int]]: + if not isinstance(msglen, int) or msglen < 0: + raise ValueError("msglen must be a non-negative integer") + if not isinstance(maxfds, int) or maxfds < 1: + raise ValueError("maxfds must be a positive integer") + + loop = get_running_loop() + fds = array.array("i") + await AsyncIOBackend.checkpoint() + with self._receive_guard: + while True: + try: + message, ancdata, flags, addr = self._raw_socket.recvmsg( + msglen, socket.CMSG_LEN(maxfds * fds.itemsize) + ) + except BlockingIOError: + await self._wait_until_readable(loop) + except OSError as exc: + if self._closing: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + else: + if not message and not ancdata: + raise EndOfStream + + break + + for cmsg_level, cmsg_type, cmsg_data in ancdata: + if cmsg_level != socket.SOL_SOCKET or cmsg_type != socket.SCM_RIGHTS: + raise RuntimeError( + f"Received unexpected ancillary data; message = {message!r}, " + f"cmsg_level = {cmsg_level}, cmsg_type = {cmsg_type}" + ) + + fds.frombytes(cmsg_data[: len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) + + return message, list(fds) + + async def send_fds(self, message: bytes, fds: Collection[int | IOBase]) -> None: + if not message: + raise ValueError("message must not be empty") + if not fds: + raise ValueError("fds must not be empty") + + loop = get_running_loop() + filenos: list[int] = [] + for fd in fds: + if isinstance(fd, int): + filenos.append(fd) + elif isinstance(fd, IOBase): + filenos.append(fd.fileno()) + + fdarray = array.array("i", filenos) + await AsyncIOBackend.checkpoint() + with self._send_guard: + while True: + try: + # The ignore can be removed after mypy picks up + # https://github.com/python/typeshed/pull/5545 + self._raw_socket.sendmsg( + [message], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, fdarray)] + ) + break + except BlockingIOError: + await self._wait_until_writable(loop) + except OSError as exc: + if self._closing: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + + +class TCPSocketListener(abc.SocketListener): + _accept_scope: CancelScope | None = None + _closed = False + + def __init__(self, raw_socket: socket.socket): + self.__raw_socket = raw_socket + self._loop = cast(asyncio.BaseEventLoop, get_running_loop()) + self._accept_guard = ResourceGuard("accepting connections from") + + @property + def _raw_socket(self) -> socket.socket: + return self.__raw_socket + + async def accept(self) -> abc.SocketStream: + if self._closed: + raise ClosedResourceError + + with self._accept_guard: + await AsyncIOBackend.checkpoint() + with CancelScope() as self._accept_scope: + try: + client_sock, _addr = await self._loop.sock_accept(self._raw_socket) + except asyncio.CancelledError: + # Workaround for https://bugs.python.org/issue41317 + try: + self._loop.remove_reader(self._raw_socket) + except (ValueError, NotImplementedError): + pass + + if self._closed: + raise ClosedResourceError from None + + raise + finally: + self._accept_scope = None + + client_sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + transport, protocol = await self._loop.connect_accepted_socket( + StreamProtocol, client_sock + ) + return SocketStream(transport, protocol) + + async def aclose(self) -> None: + if self._closed: + return + + self._closed = True + if self._accept_scope: + # Workaround for https://bugs.python.org/issue41317 + try: + self._loop.remove_reader(self._raw_socket) + except (ValueError, NotImplementedError): + pass + + self._accept_scope.cancel() + await sleep(0) + + self._raw_socket.close() + + +class UNIXSocketListener(abc.SocketListener): + def __init__(self, raw_socket: socket.socket): + self.__raw_socket = raw_socket + self._loop = get_running_loop() + self._accept_guard = ResourceGuard("accepting connections from") + self._closed = False + + async def accept(self) -> abc.SocketStream: + await AsyncIOBackend.checkpoint() + with self._accept_guard: + while True: + try: + client_sock, _ = self.__raw_socket.accept() + client_sock.setblocking(False) + return UNIXSocketStream(client_sock) + except BlockingIOError: + f: asyncio.Future = asyncio.Future() + self._loop.add_reader(self.__raw_socket, f.set_result, None) + f.add_done_callback( + lambda _: self._loop.remove_reader(self.__raw_socket) + ) + await f + except OSError as exc: + if self._closed: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + + async def aclose(self) -> None: + self._closed = True + self.__raw_socket.close() + + @property + def _raw_socket(self) -> socket.socket: + return self.__raw_socket + + +class UDPSocket(abc.UDPSocket): + def __init__( + self, transport: asyncio.DatagramTransport, protocol: DatagramProtocol + ): + self._transport = transport + self._protocol = protocol + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + self._closed = False + + @property + def _raw_socket(self) -> socket.socket: + return self._transport.get_extra_info("socket") + + async def aclose(self) -> None: + self._closed = True + if not self._transport.is_closing(): + self._transport.close() + + async def receive(self) -> tuple[bytes, IPSockAddrType]: + with self._receive_guard: + await AsyncIOBackend.checkpoint() + + # If the buffer is empty, ask for more data + if not self._protocol.read_queue and not self._transport.is_closing(): + self._protocol.read_event.clear() + await self._protocol.read_event.wait() + + try: + return self._protocol.read_queue.popleft() + except IndexError: + if self._closed: + raise ClosedResourceError from None + else: + raise BrokenResourceError from None + + async def send(self, item: UDPPacketType) -> None: + with self._send_guard: + await AsyncIOBackend.checkpoint() + await self._protocol.write_event.wait() + if self._closed: + raise ClosedResourceError + elif self._transport.is_closing(): + raise BrokenResourceError + else: + self._transport.sendto(*item) + + +class ConnectedUDPSocket(abc.ConnectedUDPSocket): + def __init__( + self, transport: asyncio.DatagramTransport, protocol: DatagramProtocol + ): + self._transport = transport + self._protocol = protocol + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + self._closed = False + + @property + def _raw_socket(self) -> socket.socket: + return self._transport.get_extra_info("socket") + + async def aclose(self) -> None: + self._closed = True + if not self._transport.is_closing(): + self._transport.close() + + async def receive(self) -> bytes: + with self._receive_guard: + await AsyncIOBackend.checkpoint() + + # If the buffer is empty, ask for more data + if not self._protocol.read_queue and not self._transport.is_closing(): + self._protocol.read_event.clear() + await self._protocol.read_event.wait() + + try: + packet = self._protocol.read_queue.popleft() + except IndexError: + if self._closed: + raise ClosedResourceError from None + else: + raise BrokenResourceError from None + + return packet[0] + + async def send(self, item: bytes) -> None: + with self._send_guard: + await AsyncIOBackend.checkpoint() + await self._protocol.write_event.wait() + if self._closed: + raise ClosedResourceError + elif self._transport.is_closing(): + raise BrokenResourceError + else: + self._transport.sendto(item) + + +class UNIXDatagramSocket(_RawSocketMixin, abc.UNIXDatagramSocket): + async def receive(self) -> UNIXDatagramPacketType: + loop = get_running_loop() + await AsyncIOBackend.checkpoint() + with self._receive_guard: + while True: + try: + data = self._raw_socket.recvfrom(65536) + except BlockingIOError: + await self._wait_until_readable(loop) + except OSError as exc: + if self._closing: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + else: + return data + + async def send(self, item: UNIXDatagramPacketType) -> None: + loop = get_running_loop() + await AsyncIOBackend.checkpoint() + with self._send_guard: + while True: + try: + self._raw_socket.sendto(*item) + except BlockingIOError: + await self._wait_until_writable(loop) + except OSError as exc: + if self._closing: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + else: + return + + +class ConnectedUNIXDatagramSocket(_RawSocketMixin, abc.ConnectedUNIXDatagramSocket): + async def receive(self) -> bytes: + loop = get_running_loop() + await AsyncIOBackend.checkpoint() + with self._receive_guard: + while True: + try: + data = self._raw_socket.recv(65536) + except BlockingIOError: + await self._wait_until_readable(loop) + except OSError as exc: + if self._closing: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + else: + return data + + async def send(self, item: bytes) -> None: + loop = get_running_loop() + await AsyncIOBackend.checkpoint() + with self._send_guard: + while True: + try: + self._raw_socket.send(item) + except BlockingIOError: + await self._wait_until_writable(loop) + except OSError as exc: + if self._closing: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + else: + return + + +_read_events: RunVar[dict[int, asyncio.Future[bool]]] = RunVar("read_events") +_write_events: RunVar[dict[int, asyncio.Future[bool]]] = RunVar("write_events") + + +# +# Synchronization +# + + +class Event(BaseEvent): + def __new__(cls) -> Event: + return object.__new__(cls) + + def __init__(self) -> None: + self._event = asyncio.Event() + + def set(self) -> None: + self._event.set() + + def is_set(self) -> bool: + return self._event.is_set() + + async def wait(self) -> None: + if self.is_set(): + await AsyncIOBackend.checkpoint() + else: + await self._event.wait() + + def statistics(self) -> EventStatistics: + return EventStatistics(len(self._event._waiters)) + + +class Lock(BaseLock): + def __new__(cls, *, fast_acquire: bool = False) -> Lock: + return object.__new__(cls) + + def __init__(self, *, fast_acquire: bool = False) -> None: + self._fast_acquire = fast_acquire + self._owner_task: asyncio.Task | None = None + self._waiters: deque[tuple[asyncio.Task, asyncio.Future]] = deque() + + async def acquire(self) -> None: + task = cast(asyncio.Task, current_task()) + if self._owner_task is None and not self._waiters: + await AsyncIOBackend.checkpoint_if_cancelled() + self._owner_task = task + + # Unless on the "fast path", yield control of the event loop so that other + # tasks can run too + if not self._fast_acquire: + try: + await AsyncIOBackend.cancel_shielded_checkpoint() + except CancelledError: + self.release() + raise + + return + + if self._owner_task == task: + raise RuntimeError("Attempted to acquire an already held Lock") + + fut: asyncio.Future[None] = asyncio.Future() + item = task, fut + self._waiters.append(item) + try: + await fut + except CancelledError: + self._waiters.remove(item) + if self._owner_task is task: + self.release() + + raise + + self._waiters.remove(item) + + def acquire_nowait(self) -> None: + task = cast(asyncio.Task, current_task()) + if self._owner_task is None and not self._waiters: + self._owner_task = task + return + + if self._owner_task is task: + raise RuntimeError("Attempted to acquire an already held Lock") + + raise WouldBlock + + def locked(self) -> bool: + return self._owner_task is not None + + def release(self) -> None: + if self._owner_task != current_task(): + raise RuntimeError("The current task is not holding this lock") + + for task, fut in self._waiters: + if not fut.cancelled(): + self._owner_task = task + fut.set_result(None) + return + + self._owner_task = None + + def statistics(self) -> LockStatistics: + task_info = AsyncIOTaskInfo(self._owner_task) if self._owner_task else None + return LockStatistics(self.locked(), task_info, len(self._waiters)) + + +class Semaphore(BaseSemaphore): + def __new__( + cls, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> Semaphore: + return object.__new__(cls) + + def __init__( + self, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ): + super().__init__(initial_value, max_value=max_value) + self._value = initial_value + self._max_value = max_value + self._fast_acquire = fast_acquire + self._waiters: deque[asyncio.Future[None]] = deque() + + async def acquire(self) -> None: + if self._value > 0 and not self._waiters: + await AsyncIOBackend.checkpoint_if_cancelled() + self._value -= 1 + + # Unless on the "fast path", yield control of the event loop so that other + # tasks can run too + if not self._fast_acquire: + try: + await AsyncIOBackend.cancel_shielded_checkpoint() + except CancelledError: + self.release() + raise + + return + + fut: asyncio.Future[None] = asyncio.Future() + self._waiters.append(fut) + try: + await fut + except CancelledError: + try: + self._waiters.remove(fut) + except ValueError: + self.release() + + raise + + def acquire_nowait(self) -> None: + if self._value == 0: + raise WouldBlock + + self._value -= 1 + + def release(self) -> None: + if self._max_value is not None and self._value == self._max_value: + raise ValueError("semaphore released too many times") + + for fut in self._waiters: + if not fut.cancelled(): + fut.set_result(None) + self._waiters.remove(fut) + return + + self._value += 1 + + @property + def value(self) -> int: + return self._value + + @property + def max_value(self) -> int | None: + return self._max_value + + def statistics(self) -> SemaphoreStatistics: + return SemaphoreStatistics(len(self._waiters)) + + +class CapacityLimiter(BaseCapacityLimiter): + _total_tokens: float = 0 + + def __new__(cls, total_tokens: float) -> CapacityLimiter: + return object.__new__(cls) + + def __init__(self, total_tokens: float): + self._borrowers: set[Any] = set() + self._wait_queue: OrderedDict[Any, asyncio.Event] = OrderedDict() + self.total_tokens = total_tokens + + async def __aenter__(self) -> None: + await self.acquire() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.release() + + @property + def total_tokens(self) -> float: + return self._total_tokens + + @total_tokens.setter + def total_tokens(self, value: float) -> None: + if not isinstance(value, int) and not math.isinf(value): + raise TypeError("total_tokens must be an int or math.inf") + + if value < 0: + raise ValueError("total_tokens must be >= 0") + + waiters_to_notify = max(value - self._total_tokens, 0) + self._total_tokens = value + + # Notify waiting tasks that they have acquired the limiter + while self._wait_queue and waiters_to_notify: + event = self._wait_queue.popitem(last=False)[1] + event.set() + waiters_to_notify -= 1 + + @property + def borrowed_tokens(self) -> int: + return len(self._borrowers) + + @property + def available_tokens(self) -> float: + return self._total_tokens - len(self._borrowers) + + def _notify_next_waiter(self) -> None: + """Notify the next task in line if this limiter has free capacity now.""" + if self._wait_queue and len(self._borrowers) < self._total_tokens: + event = self._wait_queue.popitem(last=False)[1] + event.set() + + def acquire_nowait(self) -> None: + self.acquire_on_behalf_of_nowait(current_task()) + + def acquire_on_behalf_of_nowait(self, borrower: object) -> None: + if borrower in self._borrowers: + raise RuntimeError( + "this borrower is already holding one of this CapacityLimiter's tokens" + ) + + if self._wait_queue or len(self._borrowers) >= self._total_tokens: + raise WouldBlock + + self._borrowers.add(borrower) + + async def acquire(self) -> None: + return await self.acquire_on_behalf_of(current_task()) + + async def acquire_on_behalf_of(self, borrower: object) -> None: + await AsyncIOBackend.checkpoint_if_cancelled() + try: + self.acquire_on_behalf_of_nowait(borrower) + except WouldBlock: + event = asyncio.Event() + self._wait_queue[borrower] = event + try: + await event.wait() + except BaseException: + self._wait_queue.pop(borrower, None) + if event.is_set(): + self._notify_next_waiter() + + raise + + self._borrowers.add(borrower) + else: + try: + await AsyncIOBackend.cancel_shielded_checkpoint() + except BaseException: + self.release() + raise + + def release(self) -> None: + self.release_on_behalf_of(current_task()) + + def release_on_behalf_of(self, borrower: object) -> None: + try: + self._borrowers.remove(borrower) + except KeyError: + raise RuntimeError( + "this borrower isn't holding any of this CapacityLimiter's tokens" + ) from None + + self._notify_next_waiter() + + def statistics(self) -> CapacityLimiterStatistics: + return CapacityLimiterStatistics( + self.borrowed_tokens, + self.total_tokens, + tuple(self._borrowers), + len(self._wait_queue), + ) + + +_default_thread_limiter: RunVar[CapacityLimiter] = RunVar("_default_thread_limiter") + + +# +# Operating system signals +# + + +class _SignalReceiver: + def __init__(self, signals: tuple[Signals, ...]): + self._signals = signals + self._loop = get_running_loop() + self._signal_queue: deque[Signals] = deque() + self._future: asyncio.Future = asyncio.Future() + self._handled_signals: set[Signals] = set() + + def _deliver(self, signum: Signals) -> None: + self._signal_queue.append(signum) + if not self._future.done(): + self._future.set_result(None) + + def __enter__(self) -> _SignalReceiver: + for sig in set(self._signals): + self._loop.add_signal_handler(sig, self._deliver, sig) + self._handled_signals.add(sig) + + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + for sig in self._handled_signals: + self._loop.remove_signal_handler(sig) + + def __aiter__(self) -> _SignalReceiver: + return self + + async def __anext__(self) -> Signals: + await AsyncIOBackend.checkpoint() + if not self._signal_queue: + self._future = asyncio.Future() + await self._future + + return self._signal_queue.popleft() + + +# +# Testing and debugging +# + + +class AsyncIOTaskInfo(TaskInfo): + def __init__(self, task: asyncio.Task): + task_state = _task_states.get(task) + if task_state is None: + parent_id = None + else: + parent_id = task_state.parent_id + + coro = task.get_coro() + assert coro is not None, "created TaskInfo from a completed Task" + super().__init__(id(task), parent_id, task.get_name(), coro) + self._task = weakref.ref(task) + + def has_pending_cancellation(self) -> bool: + if not (task := self._task()): + # If the task isn't around anymore, it won't have a pending cancellation + return False + + if task._must_cancel: # type: ignore[attr-defined] + return True + elif ( + isinstance(task._fut_waiter, asyncio.Future) # type: ignore[attr-defined] + and task._fut_waiter.cancelled() # type: ignore[attr-defined] + ): + return True + + if task_state := _task_states.get(task): + if cancel_scope := task_state.cancel_scope: + return cancel_scope._effectively_cancelled + + return False + + +class TestRunner(abc.TestRunner): + _send_stream: MemoryObjectSendStream[tuple[Awaitable[Any], asyncio.Future[Any]]] + + def __init__( + self, + *, + debug: bool | None = None, + use_uvloop: bool = False, + loop_factory: Callable[[], AbstractEventLoop] | None = None, + ) -> None: + if use_uvloop and loop_factory is None: + if sys.platform != "win32": + import uvloop + + loop_factory = uvloop.new_event_loop + else: + import winloop + + loop_factory = winloop.new_event_loop + + self._runner = Runner(debug=debug, loop_factory=loop_factory) + self._exceptions: list[BaseException] = [] + self._runner_task: asyncio.Task | None = None + + def __enter__(self) -> TestRunner: + self._runner.__enter__() + self.get_loop().set_exception_handler(self._exception_handler) + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self._runner.__exit__(exc_type, exc_val, exc_tb) + + def get_loop(self) -> AbstractEventLoop: + return self._runner.get_loop() + + def _exception_handler( + self, loop: asyncio.AbstractEventLoop, context: dict[str, Any] + ) -> None: + if isinstance(context.get("exception"), Exception): + self._exceptions.append(context["exception"]) + else: + loop.default_exception_handler(context) + + def _raise_async_exceptions(self) -> None: + # Re-raise any exceptions raised in asynchronous callbacks + if self._exceptions: + exceptions, self._exceptions = self._exceptions, [] + if len(exceptions) == 1: + raise exceptions[0] + elif exceptions: + raise BaseExceptionGroup( + "Multiple exceptions occurred in asynchronous callbacks", exceptions + ) + + async def _run_tests_and_fixtures( + self, + receive_stream: MemoryObjectReceiveStream[ + tuple[Awaitable[T_Retval], asyncio.Future[T_Retval]] + ], + ) -> None: + from _pytest.outcomes import OutcomeException + + with receive_stream, self._send_stream: + async for coro, future in receive_stream: + try: + retval = await coro + except CancelledError as exc: + if not future.cancelled(): + future.cancel(*exc.args) + + raise + except BaseException as exc: + if not future.cancelled(): + future.set_exception(exc) + + if not isinstance(exc, (Exception, OutcomeException)): + raise + else: + if not future.cancelled(): + future.set_result(retval) + + async def _call_in_runner_task( + self, + func: Callable[P, Awaitable[T_Retval]], + *args: P.args, + **kwargs: P.kwargs, + ) -> T_Retval: + if not self._runner_task: + self._send_stream, receive_stream = create_memory_object_stream[ + tuple[Awaitable[Any], asyncio.Future] + ](1) + self._runner_task = self.get_loop().create_task( + self._run_tests_and_fixtures(receive_stream) + ) + + coro = func(*args, **kwargs) + future: asyncio.Future[T_Retval] = self.get_loop().create_future() + self._send_stream.send_nowait((coro, future)) + return await future + + def run_asyncgen_fixture( + self, + fixture_func: Callable[..., AsyncGenerator[T_Retval, Any]], + kwargs: dict[str, Any], + ) -> Iterable[T_Retval]: + asyncgen = fixture_func(**kwargs) + fixturevalue: T_Retval = self.get_loop().run_until_complete( + self._call_in_runner_task(asyncgen.asend, None) + ) + self._raise_async_exceptions() + + yield fixturevalue + + try: + self.get_loop().run_until_complete( + self._call_in_runner_task(asyncgen.asend, None) + ) + except StopAsyncIteration: + self._raise_async_exceptions() + else: + self.get_loop().run_until_complete(asyncgen.aclose()) + raise RuntimeError("Async generator fixture did not stop") + + def run_fixture( + self, + fixture_func: Callable[..., Coroutine[Any, Any, T_Retval]], + kwargs: dict[str, Any], + ) -> T_Retval: + retval = self.get_loop().run_until_complete( + self._call_in_runner_task(fixture_func, **kwargs) + ) + self._raise_async_exceptions() + return retval + + def run_test( + self, test_func: Callable[..., Coroutine[Any, Any, Any]], kwargs: dict[str, Any] + ) -> None: + try: + self.get_loop().run_until_complete( + self._call_in_runner_task(test_func, **kwargs) + ) + except Exception as exc: + self._exceptions.append(exc) + + self._raise_async_exceptions() + + +class AsyncIOBackend(AsyncBackend): + @classmethod + def run( + cls, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + args: tuple[Unpack[PosArgsT]], + kwargs: dict[str, Any], + options: dict[str, Any], + ) -> T_Retval: + @wraps(func) + async def wrapper() -> T_Retval: + task = cast(asyncio.Task, current_task()) + task.set_name(get_callable_name(func)) + _task_states[task] = TaskState(None, None) + + try: + return await func(*args) + finally: + del _task_states[task] + + debug = options.get("debug", None) + loop_factory = options.get("loop_factory", None) + if loop_factory is None and options.get("use_uvloop", False): + if sys.platform != "win32": + import uvloop + + loop_factory = uvloop.new_event_loop + else: + import winloop + + loop_factory = winloop.new_event_loop + + with Runner(debug=debug, loop_factory=loop_factory) as runner: + return runner.run(wrapper()) + + @classmethod + def current_token(cls) -> object: + return get_running_loop() + + @classmethod + def current_time(cls) -> float: + return get_running_loop().time() + + @classmethod + def cancelled_exception_class(cls) -> type[BaseException]: + return CancelledError + + @classmethod + async def checkpoint(cls) -> None: + await sleep(0) + + @classmethod + async def checkpoint_if_cancelled(cls) -> None: + task = current_task() + if task is None: + return + + try: + cancel_scope = _task_states[task].cancel_scope + except KeyError: + return + + while cancel_scope: + if cancel_scope.cancel_called: + await sleep(0) + elif cancel_scope.shield: + break + else: + cancel_scope = cancel_scope._parent_scope + + @classmethod + async def cancel_shielded_checkpoint(cls) -> None: + with CancelScope(shield=True): + await sleep(0) + + @classmethod + async def sleep(cls, delay: float) -> None: + await sleep(delay) + + @classmethod + def create_cancel_scope( + cls, *, deadline: float = math.inf, shield: bool = False + ) -> CancelScope: + return CancelScope(deadline=deadline, shield=shield) + + @classmethod + def current_effective_deadline(cls) -> float: + if (task := current_task()) is None: + return math.inf + + try: + cancel_scope = _task_states[task].cancel_scope + except KeyError: + return math.inf + + deadline = math.inf + while cancel_scope: + deadline = min(deadline, cancel_scope.deadline) + if cancel_scope._cancel_called: + deadline = -math.inf + break + elif cancel_scope.shield: + break + else: + cancel_scope = cancel_scope._parent_scope + + return deadline + + @classmethod + def create_task_group(cls) -> abc.TaskGroup: + return TaskGroup() + + @classmethod + def create_event(cls) -> abc.Event: + return Event() + + @classmethod + def create_lock(cls, *, fast_acquire: bool) -> abc.Lock: + return Lock(fast_acquire=fast_acquire) + + @classmethod + def create_semaphore( + cls, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> abc.Semaphore: + return Semaphore(initial_value, max_value=max_value, fast_acquire=fast_acquire) + + @classmethod + def create_capacity_limiter(cls, total_tokens: float) -> abc.CapacityLimiter: + return CapacityLimiter(total_tokens) + + @classmethod + async def run_sync_in_worker_thread( # type: ignore[return] + cls, + func: Callable[[Unpack[PosArgsT]], T_Retval], + args: tuple[Unpack[PosArgsT]], + abandon_on_cancel: bool = False, + limiter: abc.CapacityLimiter | None = None, + ) -> T_Retval: + await cls.checkpoint() + + # If this is the first run in this event loop thread, set up the necessary + # variables + try: + idle_workers = _threadpool_idle_workers.get() + workers = _threadpool_workers.get() + except LookupError: + idle_workers = deque() + workers = set() + _threadpool_idle_workers.set(idle_workers) + _threadpool_workers.set(workers) + + async with limiter or cls.current_default_thread_limiter(): + with CancelScope(shield=not abandon_on_cancel) as scope: + future = asyncio.Future[T_Retval]() + root_task = find_root_task() + if not idle_workers: + worker = WorkerThread(root_task, workers, idle_workers) + worker.start() + workers.add(worker) + root_task.add_done_callback( + worker.stop, context=contextvars.Context() + ) + else: + worker = idle_workers.pop() + + # Prune any other workers that have been idle for MAX_IDLE_TIME + # seconds or longer + now = cls.current_time() + while idle_workers: + if ( + now - idle_workers[0].idle_since + < WorkerThread.MAX_IDLE_TIME + ): + break + + expired_worker = idle_workers.popleft() + expired_worker.root_task.remove_done_callback( + expired_worker.stop + ) + expired_worker.stop() + + context = copy_context() + context.run(set_current_async_library, None) + if abandon_on_cancel or scope._parent_scope is None: + worker_scope = scope + else: + worker_scope = scope._parent_scope + + worker.queue.put_nowait((context, func, args, future, worker_scope)) + return await future + + @classmethod + def check_cancelled(cls) -> None: + scope: CancelScope | None = threadlocals.current_cancel_scope + while scope is not None: + if scope.cancel_called: + raise CancelledError(f"Cancelled by cancel scope {id(scope):x}") + + if scope.shield: + return + + scope = scope._parent_scope + + @classmethod + def run_async_from_thread( + cls, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + args: tuple[Unpack[PosArgsT]], + token: object, + ) -> T_Retval: + async def task_wrapper() -> T_Retval: + __tracebackhide__ = True + if scope is not None: + task = cast(asyncio.Task, current_task()) + _task_states[task] = TaskState(None, scope) + scope._tasks.add(task) + try: + return await func(*args) + except CancelledError as exc: + raise concurrent.futures.CancelledError(str(exc)) from None + finally: + if scope is not None: + scope._tasks.discard(task) + + loop = cast( + "AbstractEventLoop", token or threadlocals.current_token.native_token + ) + if loop.is_closed(): + raise RunFinishedError + + context = copy_context() + context.run(set_current_async_library, "asyncio") + scope = getattr(threadlocals, "current_cancel_scope", None) + f: concurrent.futures.Future[T_Retval] = context.run( + asyncio.run_coroutine_threadsafe, task_wrapper(), loop=loop + ) + return f.result() + + @classmethod + def run_sync_from_thread( + cls, + func: Callable[[Unpack[PosArgsT]], T_Retval], + args: tuple[Unpack[PosArgsT]], + token: object, + ) -> T_Retval: + @wraps(func) + def wrapper() -> None: + try: + set_current_async_library("asyncio") + f.set_result(func(*args)) + except BaseException as exc: + f.set_exception(exc) + if not isinstance(exc, Exception): + raise + + loop = cast( + "AbstractEventLoop", token or threadlocals.current_token.native_token + ) + if loop.is_closed(): + raise RunFinishedError + + f: concurrent.futures.Future[T_Retval] = Future() + loop.call_soon_threadsafe(wrapper) + return f.result() + + @classmethod + async def open_process( + cls, + command: StrOrBytesPath | Sequence[StrOrBytesPath], + *, + stdin: int | IO[Any] | None, + stdout: int | IO[Any] | None, + stderr: int | IO[Any] | None, + **kwargs: Any, + ) -> Process: + await cls.checkpoint() + if isinstance(command, PathLike): + command = os.fspath(command) + + if isinstance(command, (str, bytes)): + process = await asyncio.create_subprocess_shell( + command, + stdin=stdin, + stdout=stdout, + stderr=stderr, + **kwargs, + ) + else: + process = await asyncio.create_subprocess_exec( + *command, + stdin=stdin, + stdout=stdout, + stderr=stderr, + **kwargs, + ) + + stdin_stream = StreamWriterWrapper(process.stdin) if process.stdin else None + stdout_stream = StreamReaderWrapper(process.stdout) if process.stdout else None + stderr_stream = StreamReaderWrapper(process.stderr) if process.stderr else None + return Process(process, stdin_stream, stdout_stream, stderr_stream) + + @classmethod + def setup_process_pool_exit_at_shutdown(cls, workers: set[abc.Process]) -> None: + create_task( + _shutdown_process_pool_on_exit(workers), + name="AnyIO process pool shutdown task", + ) + find_root_task().add_done_callback( + partial(_forcibly_shutdown_process_pool_on_exit, workers) # type:ignore[arg-type] + ) + + @classmethod + async def connect_tcp( + cls, host: str, port: int, local_address: IPSockAddrType | None = None + ) -> abc.SocketStream: + transport, protocol = cast( + tuple[asyncio.Transport, StreamProtocol], + await get_running_loop().create_connection( + StreamProtocol, host, port, local_addr=local_address + ), + ) + transport.pause_reading() + return SocketStream(transport, protocol) + + @classmethod + async def connect_unix(cls, path: str | bytes) -> abc.UNIXSocketStream: + await cls.checkpoint() + loop = get_running_loop() + raw_socket = socket.socket(socket.AF_UNIX) + raw_socket.setblocking(False) + while True: + try: + raw_socket.connect(path) + except BlockingIOError: + f: asyncio.Future = asyncio.Future() + loop.add_writer(raw_socket, f.set_result, None) + f.add_done_callback(lambda _: loop.remove_writer(raw_socket)) + await f + except BaseException: + raw_socket.close() + raise + else: + return UNIXSocketStream(raw_socket) + + @classmethod + def create_tcp_listener(cls, sock: socket.socket) -> SocketListener: + return TCPSocketListener(sock) + + @classmethod + def create_unix_listener(cls, sock: socket.socket) -> SocketListener: + return UNIXSocketListener(sock) + + @classmethod + async def create_udp_socket( + cls, + family: AddressFamily, + local_address: IPSockAddrType | None, + remote_address: IPSockAddrType | None, + reuse_port: bool, + ) -> UDPSocket | ConnectedUDPSocket: + transport, protocol = await get_running_loop().create_datagram_endpoint( + DatagramProtocol, + local_addr=local_address, + remote_addr=remote_address, + family=family, + reuse_port=reuse_port, + ) + if protocol.exception: + transport.close() + raise protocol.exception + + if not remote_address: + return UDPSocket(transport, protocol) + else: + return ConnectedUDPSocket(transport, protocol) + + @classmethod + async def create_unix_datagram_socket( # type: ignore[override] + cls, raw_socket: socket.socket, remote_path: str | bytes | None + ) -> abc.UNIXDatagramSocket | abc.ConnectedUNIXDatagramSocket: + await cls.checkpoint() + loop = get_running_loop() + + if remote_path: + while True: + try: + raw_socket.connect(remote_path) + except BlockingIOError: + f: asyncio.Future = asyncio.Future() + loop.add_writer(raw_socket, f.set_result, None) + f.add_done_callback(lambda _: loop.remove_writer(raw_socket)) + await f + except BaseException: + raw_socket.close() + raise + else: + return ConnectedUNIXDatagramSocket(raw_socket) + else: + return UNIXDatagramSocket(raw_socket) + + @classmethod + async def getaddrinfo( + cls, + host: bytes | str | None, + port: str | int | None, + *, + family: int | AddressFamily = 0, + type: int | SocketKind = 0, + proto: int = 0, + flags: int = 0, + ) -> Sequence[ + tuple[ + AddressFamily, + SocketKind, + int, + str, + tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes], + ] + ]: + return await get_running_loop().getaddrinfo( + host, port, family=family, type=type, proto=proto, flags=flags + ) + + @classmethod + async def getnameinfo( + cls, sockaddr: IPSockAddrType, flags: int = 0 + ) -> tuple[str, str]: + return await get_running_loop().getnameinfo(sockaddr, flags) + + @classmethod + async def wait_readable(cls, obj: FileDescriptorLike) -> None: + try: + read_events = _read_events.get() + except LookupError: + read_events = {} + _read_events.set(read_events) + + fd = obj if isinstance(obj, int) else obj.fileno() + if read_events.get(fd): + raise BusyResourceError("reading from") + + loop = get_running_loop() + fut: asyncio.Future[bool] = loop.create_future() + + def cb() -> None: + try: + del read_events[fd] + except KeyError: + pass + else: + remove_reader(fd) + + try: + fut.set_result(True) + except asyncio.InvalidStateError: + pass + + try: + loop.add_reader(fd, cb) + except NotImplementedError: + from anyio._core._asyncio_selector_thread import get_selector + + selector = get_selector() + selector.add_reader(fd, cb) + remove_reader = selector.remove_reader + else: + remove_reader = loop.remove_reader + + read_events[fd] = fut + try: + success = await fut + finally: + try: + del read_events[fd] + except KeyError: + pass + else: + remove_reader(fd) + + if not success: + raise ClosedResourceError + + @classmethod + async def wait_writable(cls, obj: FileDescriptorLike) -> None: + try: + write_events = _write_events.get() + except LookupError: + write_events = {} + _write_events.set(write_events) + + fd = obj if isinstance(obj, int) else obj.fileno() + if write_events.get(fd): + raise BusyResourceError("writing to") + + loop = get_running_loop() + fut: asyncio.Future[bool] = loop.create_future() + + def cb() -> None: + try: + del write_events[fd] + except KeyError: + pass + else: + remove_writer(fd) + + try: + fut.set_result(True) + except asyncio.InvalidStateError: + pass + + try: + loop.add_writer(fd, cb) + except NotImplementedError: + from anyio._core._asyncio_selector_thread import get_selector + + selector = get_selector() + selector.add_writer(fd, cb) + remove_writer = selector.remove_writer + else: + remove_writer = loop.remove_writer + + write_events[fd] = fut + try: + success = await fut + finally: + try: + del write_events[fd] + except KeyError: + pass + else: + remove_writer(fd) + + if not success: + raise ClosedResourceError + + @classmethod + def notify_closing(cls, obj: FileDescriptorLike) -> None: + fd = obj if isinstance(obj, int) else obj.fileno() + loop = get_running_loop() + + try: + write_events = _write_events.get() + except LookupError: + pass + else: + try: + fut = write_events.pop(fd) + except KeyError: + pass + else: + try: + fut.set_result(False) + except asyncio.InvalidStateError: + pass + + try: + loop.remove_writer(fd) + except NotImplementedError: + from anyio._core._asyncio_selector_thread import get_selector + + get_selector().remove_writer(fd) + + try: + read_events = _read_events.get() + except LookupError: + pass + else: + try: + fut = read_events.pop(fd) + except KeyError: + pass + else: + try: + fut.set_result(False) + except asyncio.InvalidStateError: + pass + + try: + loop.remove_reader(fd) + except NotImplementedError: + from anyio._core._asyncio_selector_thread import get_selector + + get_selector().remove_reader(fd) + + @classmethod + async def wrap_listener_socket(cls, sock: socket.socket) -> SocketListener: + return TCPSocketListener(sock) + + @classmethod + async def wrap_stream_socket(cls, sock: socket.socket) -> SocketStream: + transport, protocol = await get_running_loop().create_connection( + StreamProtocol, sock=sock + ) + return SocketStream(transport, protocol) + + @classmethod + async def wrap_unix_stream_socket(cls, sock: socket.socket) -> UNIXSocketStream: + return UNIXSocketStream(sock) + + @classmethod + async def wrap_udp_socket(cls, sock: socket.socket) -> UDPSocket: + transport, protocol = await get_running_loop().create_datagram_endpoint( + DatagramProtocol, sock=sock + ) + return UDPSocket(transport, protocol) + + @classmethod + async def wrap_connected_udp_socket(cls, sock: socket.socket) -> ConnectedUDPSocket: + transport, protocol = await get_running_loop().create_datagram_endpoint( + DatagramProtocol, sock=sock + ) + return ConnectedUDPSocket(transport, protocol) + + @classmethod + async def wrap_unix_datagram_socket(cls, sock: socket.socket) -> UNIXDatagramSocket: + return UNIXDatagramSocket(sock) + + @classmethod + async def wrap_connected_unix_datagram_socket( + cls, sock: socket.socket + ) -> ConnectedUNIXDatagramSocket: + return ConnectedUNIXDatagramSocket(sock) + + @classmethod + def current_default_thread_limiter(cls) -> CapacityLimiter: + try: + return _default_thread_limiter.get() + except LookupError: + limiter = CapacityLimiter(40) + _default_thread_limiter.set(limiter) + return limiter + + @classmethod + def open_signal_receiver( + cls, *signals: Signals + ) -> AbstractContextManager[AsyncIterator[Signals]]: + return _SignalReceiver(signals) + + @classmethod + def get_current_task(cls) -> TaskInfo: + return AsyncIOTaskInfo(current_task()) # type: ignore[arg-type] + + @classmethod + def get_running_tasks(cls) -> Sequence[TaskInfo]: + return [AsyncIOTaskInfo(task) for task in all_tasks() if not task.done()] + + @classmethod + async def wait_all_tasks_blocked(cls) -> None: + await cls.checkpoint() + this_task = current_task() + while True: + for task in all_tasks(): + if task is this_task: + continue + + waiter = task._fut_waiter # type: ignore[attr-defined] + if waiter is None or waiter.done(): + await sleep(0.1) + break + else: + return + + @classmethod + def create_test_runner(cls, options: dict[str, Any]) -> TestRunner: + return TestRunner(**options) + + +backend_class = AsyncIOBackend diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_backends/_trio.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_backends/_trio.py new file mode 100644 index 0000000000000000000000000000000000000000..f460a7f5e0072a8cec103dfb8f4887d15fa666d0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_backends/_trio.py @@ -0,0 +1,1346 @@ +from __future__ import annotations + +import array +import math +import os +import socket +import sys +import types +import weakref +from collections.abc import ( + AsyncGenerator, + AsyncIterator, + Awaitable, + Callable, + Collection, + Coroutine, + Iterable, + Sequence, +) +from contextlib import AbstractContextManager +from dataclasses import dataclass +from io import IOBase +from os import PathLike +from signal import Signals +from socket import AddressFamily, SocketKind +from types import TracebackType +from typing import ( + IO, + TYPE_CHECKING, + Any, + Generic, + NoReturn, + TypeVar, + cast, + overload, +) + +import trio.from_thread +import trio.lowlevel +from outcome import Error, Outcome, Value +from trio.lowlevel import ( + current_root_task, + current_task, + notify_closing, + wait_readable, + wait_writable, +) +from trio.socket import SocketType as TrioSocketType +from trio.to_thread import run_sync + +from .. import ( + CapacityLimiterStatistics, + EventStatistics, + LockStatistics, + RunFinishedError, + TaskInfo, + WouldBlock, + abc, +) +from .._core._eventloop import claim_worker_thread +from .._core._exceptions import ( + BrokenResourceError, + BusyResourceError, + ClosedResourceError, + EndOfStream, +) +from .._core._sockets import convert_ipv6_sockaddr +from .._core._streams import create_memory_object_stream +from .._core._synchronization import ( + CapacityLimiter as BaseCapacityLimiter, +) +from .._core._synchronization import Event as BaseEvent +from .._core._synchronization import Lock as BaseLock +from .._core._synchronization import ( + ResourceGuard, + SemaphoreStatistics, +) +from .._core._synchronization import Semaphore as BaseSemaphore +from .._core._tasks import CancelScope as BaseCancelScope +from ..abc import IPSockAddrType, UDPPacketType, UNIXDatagramPacketType +from ..abc._eventloop import AsyncBackend, StrOrBytesPath +from ..streams.memory import MemoryObjectSendStream + +if TYPE_CHECKING: + from _typeshed import FileDescriptorLike + +if sys.version_info >= (3, 10): + from typing import ParamSpec +else: + from typing_extensions import ParamSpec + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from exceptiongroup import BaseExceptionGroup + from typing_extensions import TypeVarTuple, Unpack + +T = TypeVar("T") +T_Retval = TypeVar("T_Retval") +T_SockAddr = TypeVar("T_SockAddr", str, IPSockAddrType) +PosArgsT = TypeVarTuple("PosArgsT") +P = ParamSpec("P") + + +# +# Event loop +# + +RunVar = trio.lowlevel.RunVar + + +# +# Timeouts and cancellation +# + + +class CancelScope(BaseCancelScope): + def __new__( + cls, original: trio.CancelScope | None = None, **kwargs: object + ) -> CancelScope: + return object.__new__(cls) + + def __init__(self, original: trio.CancelScope | None = None, **kwargs: Any) -> None: + self.__original = original or trio.CancelScope(**kwargs) + + def __enter__(self) -> CancelScope: + self.__original.__enter__() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + return self.__original.__exit__(exc_type, exc_val, exc_tb) + + def cancel(self, reason: str | None = None) -> None: + self.__original.cancel(reason) + + @property + def deadline(self) -> float: + return self.__original.deadline + + @deadline.setter + def deadline(self, value: float) -> None: + self.__original.deadline = value + + @property + def cancel_called(self) -> bool: + return self.__original.cancel_called + + @property + def cancelled_caught(self) -> bool: + return self.__original.cancelled_caught + + @property + def shield(self) -> bool: + return self.__original.shield + + @shield.setter + def shield(self, value: bool) -> None: + self.__original.shield = value + + +# +# Task groups +# + + +class TaskGroup(abc.TaskGroup): + def __init__(self) -> None: + self._active = False + self._nursery_manager = trio.open_nursery(strict_exception_groups=True) + self.cancel_scope = None # type: ignore[assignment] + + async def __aenter__(self) -> TaskGroup: + self._active = True + self._nursery = await self._nursery_manager.__aenter__() + self.cancel_scope = CancelScope(self._nursery.cancel_scope) + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + try: + # trio.Nursery.__exit__ returns bool; .open_nursery has wrong type + return await self._nursery_manager.__aexit__(exc_type, exc_val, exc_tb) # type: ignore[return-value] + except BaseExceptionGroup as exc: + if not exc.split(trio.Cancelled)[1]: + raise trio.Cancelled._create() from exc + + raise + finally: + del exc_val, exc_tb + self._active = False + + def start_soon( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[Any]], + *args: Unpack[PosArgsT], + name: object = None, + ) -> None: + if not self._active: + raise RuntimeError( + "This task group is not active; no new tasks can be started." + ) + + self._nursery.start_soon(func, *args, name=name) + + async def start( + self, func: Callable[..., Awaitable[Any]], *args: object, name: object = None + ) -> Any: + if not self._active: + raise RuntimeError( + "This task group is not active; no new tasks can be started." + ) + + return await self._nursery.start(func, *args, name=name) + + +# +# Subprocesses +# + + +@dataclass(eq=False) +class ReceiveStreamWrapper(abc.ByteReceiveStream): + _stream: trio.abc.ReceiveStream + + async def receive(self, max_bytes: int | None = None) -> bytes: + try: + data = await self._stream.receive_some(max_bytes) + except trio.ClosedResourceError as exc: + raise ClosedResourceError from exc.__cause__ + except trio.BrokenResourceError as exc: + raise BrokenResourceError from exc.__cause__ + + if data: + return bytes(data) + else: + raise EndOfStream + + async def aclose(self) -> None: + await self._stream.aclose() + + +@dataclass(eq=False) +class SendStreamWrapper(abc.ByteSendStream): + _stream: trio.abc.SendStream + + async def send(self, item: bytes) -> None: + try: + await self._stream.send_all(item) + except trio.ClosedResourceError as exc: + raise ClosedResourceError from exc.__cause__ + except trio.BrokenResourceError as exc: + raise BrokenResourceError from exc.__cause__ + + async def aclose(self) -> None: + await self._stream.aclose() + + +@dataclass(eq=False) +class Process(abc.Process): + _process: trio.Process + _stdin: abc.ByteSendStream | None + _stdout: abc.ByteReceiveStream | None + _stderr: abc.ByteReceiveStream | None + + async def aclose(self) -> None: + with CancelScope(shield=True): + if self._stdin: + await self._stdin.aclose() + if self._stdout: + await self._stdout.aclose() + if self._stderr: + await self._stderr.aclose() + + try: + await self.wait() + except BaseException: + self.kill() + with CancelScope(shield=True): + await self.wait() + raise + + async def wait(self) -> int: + return await self._process.wait() + + def terminate(self) -> None: + self._process.terminate() + + def kill(self) -> None: + self._process.kill() + + def send_signal(self, signal: Signals) -> None: + self._process.send_signal(signal) + + @property + def pid(self) -> int: + return self._process.pid + + @property + def returncode(self) -> int | None: + return self._process.returncode + + @property + def stdin(self) -> abc.ByteSendStream | None: + return self._stdin + + @property + def stdout(self) -> abc.ByteReceiveStream | None: + return self._stdout + + @property + def stderr(self) -> abc.ByteReceiveStream | None: + return self._stderr + + +class _ProcessPoolShutdownInstrument(trio.abc.Instrument): + def after_run(self) -> None: + super().after_run() + + +current_default_worker_process_limiter: trio.lowlevel.RunVar = RunVar( + "current_default_worker_process_limiter" +) + + +async def _shutdown_process_pool(workers: set[abc.Process]) -> None: + try: + await trio.sleep(math.inf) + except trio.Cancelled: + for process in workers: + if process.returncode is None: + process.kill() + + with CancelScope(shield=True): + for process in workers: + await process.aclose() + + +# +# Sockets and networking +# + + +class _TrioSocketMixin(Generic[T_SockAddr]): + def __init__(self, trio_socket: TrioSocketType) -> None: + self._trio_socket = trio_socket + self._closed = False + + def _check_closed(self) -> None: + if self._closed: + raise ClosedResourceError + if self._trio_socket.fileno() < 0: + raise BrokenResourceError + + @property + def _raw_socket(self) -> socket.socket: + return self._trio_socket._sock # type: ignore[attr-defined] + + async def aclose(self) -> None: + if self._trio_socket.fileno() >= 0: + self._closed = True + self._trio_socket.close() + + def _convert_socket_error(self, exc: BaseException) -> NoReturn: + if isinstance(exc, trio.ClosedResourceError): + raise ClosedResourceError from exc + elif self._trio_socket.fileno() < 0 and self._closed: + raise ClosedResourceError from None + elif isinstance(exc, OSError): + raise BrokenResourceError from exc + else: + raise exc + + +class SocketStream(_TrioSocketMixin, abc.SocketStream): + def __init__(self, trio_socket: TrioSocketType) -> None: + super().__init__(trio_socket) + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + + async def receive(self, max_bytes: int = 65536) -> bytes: + with self._receive_guard: + try: + data = await self._trio_socket.recv(max_bytes) + except BaseException as exc: + self._convert_socket_error(exc) + + if data: + return data + else: + raise EndOfStream + + async def send(self, item: bytes) -> None: + with self._send_guard: + view = memoryview(item) + while view: + try: + bytes_sent = await self._trio_socket.send(view) + except BaseException as exc: + self._convert_socket_error(exc) + + view = view[bytes_sent:] + + async def send_eof(self) -> None: + self._trio_socket.shutdown(socket.SHUT_WR) + + +class UNIXSocketStream(SocketStream, abc.UNIXSocketStream): + async def receive_fds(self, msglen: int, maxfds: int) -> tuple[bytes, list[int]]: + if not isinstance(msglen, int) or msglen < 0: + raise ValueError("msglen must be a non-negative integer") + if not isinstance(maxfds, int) or maxfds < 1: + raise ValueError("maxfds must be a positive integer") + + fds = array.array("i") + await trio.lowlevel.checkpoint() + with self._receive_guard: + while True: + try: + message, ancdata, flags, addr = await self._trio_socket.recvmsg( + msglen, socket.CMSG_LEN(maxfds * fds.itemsize) + ) + except BaseException as exc: + self._convert_socket_error(exc) + else: + if not message and not ancdata: + raise EndOfStream + + break + + for cmsg_level, cmsg_type, cmsg_data in ancdata: + if cmsg_level != socket.SOL_SOCKET or cmsg_type != socket.SCM_RIGHTS: + raise RuntimeError( + f"Received unexpected ancillary data; message = {message!r}, " + f"cmsg_level = {cmsg_level}, cmsg_type = {cmsg_type}" + ) + + fds.frombytes(cmsg_data[: len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) + + return message, list(fds) + + async def send_fds(self, message: bytes, fds: Collection[int | IOBase]) -> None: + if not message: + raise ValueError("message must not be empty") + if not fds: + raise ValueError("fds must not be empty") + + filenos: list[int] = [] + for fd in fds: + if isinstance(fd, int): + filenos.append(fd) + elif isinstance(fd, IOBase): + filenos.append(fd.fileno()) + + fdarray = array.array("i", filenos) + await trio.lowlevel.checkpoint() + with self._send_guard: + while True: + try: + await self._trio_socket.sendmsg( + [message], + [ + ( + socket.SOL_SOCKET, + socket.SCM_RIGHTS, + fdarray, + ) + ], + ) + break + except BaseException as exc: + self._convert_socket_error(exc) + + +class TCPSocketListener(_TrioSocketMixin, abc.SocketListener): + def __init__(self, raw_socket: socket.socket): + super().__init__(trio.socket.from_stdlib_socket(raw_socket)) + self._accept_guard = ResourceGuard("accepting connections from") + + async def accept(self) -> SocketStream: + with self._accept_guard: + try: + trio_socket, _addr = await self._trio_socket.accept() + except BaseException as exc: + self._convert_socket_error(exc) + + trio_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + return SocketStream(trio_socket) + + +class UNIXSocketListener(_TrioSocketMixin, abc.SocketListener): + def __init__(self, raw_socket: socket.socket): + super().__init__(trio.socket.from_stdlib_socket(raw_socket)) + self._accept_guard = ResourceGuard("accepting connections from") + + async def accept(self) -> UNIXSocketStream: + with self._accept_guard: + try: + trio_socket, _addr = await self._trio_socket.accept() + except BaseException as exc: + self._convert_socket_error(exc) + + return UNIXSocketStream(trio_socket) + + +class UDPSocket(_TrioSocketMixin[IPSockAddrType], abc.UDPSocket): + def __init__(self, trio_socket: TrioSocketType) -> None: + super().__init__(trio_socket) + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + + async def receive(self) -> tuple[bytes, IPSockAddrType]: + with self._receive_guard: + try: + data, addr = await self._trio_socket.recvfrom(65536) + return data, convert_ipv6_sockaddr(addr) + except BaseException as exc: + self._convert_socket_error(exc) + + async def send(self, item: UDPPacketType) -> None: + with self._send_guard: + try: + await self._trio_socket.sendto(*item) + except BaseException as exc: + self._convert_socket_error(exc) + + +class ConnectedUDPSocket(_TrioSocketMixin[IPSockAddrType], abc.ConnectedUDPSocket): + def __init__(self, trio_socket: TrioSocketType) -> None: + super().__init__(trio_socket) + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + + async def receive(self) -> bytes: + with self._receive_guard: + try: + return await self._trio_socket.recv(65536) + except BaseException as exc: + self._convert_socket_error(exc) + + async def send(self, item: bytes) -> None: + with self._send_guard: + try: + await self._trio_socket.send(item) + except BaseException as exc: + self._convert_socket_error(exc) + + +class UNIXDatagramSocket(_TrioSocketMixin[str], abc.UNIXDatagramSocket): + def __init__(self, trio_socket: TrioSocketType) -> None: + super().__init__(trio_socket) + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + + async def receive(self) -> UNIXDatagramPacketType: + with self._receive_guard: + try: + data, addr = await self._trio_socket.recvfrom(65536) + return data, addr + except BaseException as exc: + self._convert_socket_error(exc) + + async def send(self, item: UNIXDatagramPacketType) -> None: + with self._send_guard: + try: + await self._trio_socket.sendto(*item) + except BaseException as exc: + self._convert_socket_error(exc) + + +class ConnectedUNIXDatagramSocket( + _TrioSocketMixin[str], abc.ConnectedUNIXDatagramSocket +): + def __init__(self, trio_socket: TrioSocketType) -> None: + super().__init__(trio_socket) + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + + async def receive(self) -> bytes: + with self._receive_guard: + try: + return await self._trio_socket.recv(65536) + except BaseException as exc: + self._convert_socket_error(exc) + + async def send(self, item: bytes) -> None: + with self._send_guard: + try: + await self._trio_socket.send(item) + except BaseException as exc: + self._convert_socket_error(exc) + + +# +# Synchronization +# + + +class Event(BaseEvent): + def __new__(cls) -> Event: + return object.__new__(cls) + + def __init__(self) -> None: + self.__original = trio.Event() + + def is_set(self) -> bool: + return self.__original.is_set() + + async def wait(self) -> None: + return await self.__original.wait() + + def statistics(self) -> EventStatistics: + orig_statistics = self.__original.statistics() + return EventStatistics(tasks_waiting=orig_statistics.tasks_waiting) + + def set(self) -> None: + self.__original.set() + + +class Lock(BaseLock): + def __new__(cls, *, fast_acquire: bool = False) -> Lock: + return object.__new__(cls) + + def __init__(self, *, fast_acquire: bool = False) -> None: + self._fast_acquire = fast_acquire + self.__original = trio.Lock() + + @staticmethod + def _convert_runtime_error_msg(exc: RuntimeError) -> None: + if exc.args == ("attempt to re-acquire an already held Lock",): + exc.args = ("Attempted to acquire an already held Lock",) + + async def acquire(self) -> None: + if not self._fast_acquire: + try: + await self.__original.acquire() + except RuntimeError as exc: + self._convert_runtime_error_msg(exc) + raise + + return + + # This is the "fast path" where we don't let other tasks run + await trio.lowlevel.checkpoint_if_cancelled() + try: + self.__original.acquire_nowait() + except trio.WouldBlock: + await self.__original._lot.park() + except RuntimeError as exc: + self._convert_runtime_error_msg(exc) + raise + + def acquire_nowait(self) -> None: + try: + self.__original.acquire_nowait() + except trio.WouldBlock: + raise WouldBlock from None + except RuntimeError as exc: + self._convert_runtime_error_msg(exc) + raise + + def locked(self) -> bool: + return self.__original.locked() + + def release(self) -> None: + self.__original.release() + + def statistics(self) -> LockStatistics: + orig_statistics = self.__original.statistics() + owner = TrioTaskInfo(orig_statistics.owner) if orig_statistics.owner else None + return LockStatistics( + orig_statistics.locked, owner, orig_statistics.tasks_waiting + ) + + +class Semaphore(BaseSemaphore): + def __new__( + cls, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> Semaphore: + return object.__new__(cls) + + def __init__( + self, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> None: + super().__init__(initial_value, max_value=max_value, fast_acquire=fast_acquire) + self.__original = trio.Semaphore(initial_value, max_value=max_value) + + async def acquire(self) -> None: + if not self._fast_acquire: + await self.__original.acquire() + return + + # This is the "fast path" where we don't let other tasks run + await trio.lowlevel.checkpoint_if_cancelled() + try: + self.__original.acquire_nowait() + except trio.WouldBlock: + await self.__original._lot.park() + + def acquire_nowait(self) -> None: + try: + self.__original.acquire_nowait() + except trio.WouldBlock: + raise WouldBlock from None + + @property + def max_value(self) -> int | None: + return self.__original.max_value + + @property + def value(self) -> int: + return self.__original.value + + def release(self) -> None: + self.__original.release() + + def statistics(self) -> SemaphoreStatistics: + orig_statistics = self.__original.statistics() + return SemaphoreStatistics(orig_statistics.tasks_waiting) + + +class CapacityLimiter(BaseCapacityLimiter): + def __new__( + cls, + total_tokens: float | None = None, + *, + original: trio.CapacityLimiter | None = None, + ) -> CapacityLimiter: + return object.__new__(cls) + + def __init__( + self, + total_tokens: float | None = None, + *, + original: trio.CapacityLimiter | None = None, + ) -> None: + if original is not None: + self.__original = original + else: + assert total_tokens is not None + self.__original = trio.CapacityLimiter(total_tokens) + + async def __aenter__(self) -> None: + return await self.__original.__aenter__() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + await self.__original.__aexit__(exc_type, exc_val, exc_tb) + + @property + def total_tokens(self) -> float: + return self.__original.total_tokens + + @total_tokens.setter + def total_tokens(self, value: float) -> None: + self.__original.total_tokens = value + + @property + def borrowed_tokens(self) -> int: + return self.__original.borrowed_tokens + + @property + def available_tokens(self) -> float: + return self.__original.available_tokens + + def acquire_nowait(self) -> None: + self.__original.acquire_nowait() + + def acquire_on_behalf_of_nowait(self, borrower: object) -> None: + self.__original.acquire_on_behalf_of_nowait(borrower) + + async def acquire(self) -> None: + await self.__original.acquire() + + async def acquire_on_behalf_of(self, borrower: object) -> None: + await self.__original.acquire_on_behalf_of(borrower) + + def release(self) -> None: + return self.__original.release() + + def release_on_behalf_of(self, borrower: object) -> None: + return self.__original.release_on_behalf_of(borrower) + + def statistics(self) -> CapacityLimiterStatistics: + orig = self.__original.statistics() + return CapacityLimiterStatistics( + borrowed_tokens=orig.borrowed_tokens, + total_tokens=orig.total_tokens, + borrowers=tuple(orig.borrowers), + tasks_waiting=orig.tasks_waiting, + ) + + +_capacity_limiter_wrapper: trio.lowlevel.RunVar = RunVar("_capacity_limiter_wrapper") + + +# +# Signal handling +# + + +class _SignalReceiver: + _iterator: AsyncIterator[int] + + def __init__(self, signals: tuple[Signals, ...]): + self._signals = signals + + def __enter__(self) -> _SignalReceiver: + self._cm = trio.open_signal_receiver(*self._signals) + self._iterator = self._cm.__enter__() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool | None: + return self._cm.__exit__(exc_type, exc_val, exc_tb) + + def __aiter__(self) -> _SignalReceiver: + return self + + async def __anext__(self) -> Signals: + signum = await self._iterator.__anext__() + return Signals(signum) + + +# +# Testing and debugging +# + + +class TestRunner(abc.TestRunner): + def __init__(self, **options: Any) -> None: + from queue import Queue + + self._call_queue: Queue[Callable[[], object]] = Queue() + self._send_stream: MemoryObjectSendStream | None = None + self._options = options + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: types.TracebackType | None, + ) -> None: + if self._send_stream: + self._send_stream.close() + while self._send_stream is not None: + self._call_queue.get()() + + async def _run_tests_and_fixtures(self) -> None: + self._send_stream, receive_stream = create_memory_object_stream(1) + with receive_stream: + async for coro, outcome_holder in receive_stream: + try: + retval = await coro + except BaseException as exc: + outcome_holder.append(Error(exc)) + else: + outcome_holder.append(Value(retval)) + + def _main_task_finished(self, outcome: object) -> None: + self._send_stream = None + + def _call_in_runner_task( + self, + func: Callable[P, Awaitable[T_Retval]], + *args: P.args, + **kwargs: P.kwargs, + ) -> T_Retval: + if self._send_stream is None: + trio.lowlevel.start_guest_run( + self._run_tests_and_fixtures, + run_sync_soon_threadsafe=self._call_queue.put, + done_callback=self._main_task_finished, + **self._options, + ) + while self._send_stream is None: + self._call_queue.get()() + + outcome_holder: list[Outcome] = [] + self._send_stream.send_nowait((func(*args, **kwargs), outcome_holder)) + while not outcome_holder: + self._call_queue.get()() + + return outcome_holder[0].unwrap() + + def run_asyncgen_fixture( + self, + fixture_func: Callable[..., AsyncGenerator[T_Retval, Any]], + kwargs: dict[str, Any], + ) -> Iterable[T_Retval]: + asyncgen = fixture_func(**kwargs) + fixturevalue: T_Retval = self._call_in_runner_task(asyncgen.asend, None) + + yield fixturevalue + + try: + self._call_in_runner_task(asyncgen.asend, None) + except StopAsyncIteration: + pass + else: + self._call_in_runner_task(asyncgen.aclose) + raise RuntimeError("Async generator fixture did not stop") + + def run_fixture( + self, + fixture_func: Callable[..., Coroutine[Any, Any, T_Retval]], + kwargs: dict[str, Any], + ) -> T_Retval: + return self._call_in_runner_task(fixture_func, **kwargs) + + def run_test( + self, test_func: Callable[..., Coroutine[Any, Any, Any]], kwargs: dict[str, Any] + ) -> None: + self._call_in_runner_task(test_func, **kwargs) + + +class TrioTaskInfo(TaskInfo): + def __init__(self, task: trio.lowlevel.Task): + parent_id = None + if task.parent_nursery and task.parent_nursery.parent_task: + parent_id = id(task.parent_nursery.parent_task) + + super().__init__(id(task), parent_id, task.name, task.coro) + self._task = weakref.proxy(task) + + def has_pending_cancellation(self) -> bool: + try: + return self._task._cancel_status.effectively_cancelled + except ReferenceError: + # If the task is no longer around, it surely doesn't have a cancellation + # pending + return False + + +class TrioBackend(AsyncBackend): + @classmethod + def run( + cls, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + args: tuple[Unpack[PosArgsT]], + kwargs: dict[str, Any], + options: dict[str, Any], + ) -> T_Retval: + return trio.run(func, *args) + + @classmethod + def current_token(cls) -> object: + return trio.lowlevel.current_trio_token() + + @classmethod + def current_time(cls) -> float: + return trio.current_time() + + @classmethod + def cancelled_exception_class(cls) -> type[BaseException]: + return trio.Cancelled + + @classmethod + async def checkpoint(cls) -> None: + await trio.lowlevel.checkpoint() + + @classmethod + async def checkpoint_if_cancelled(cls) -> None: + await trio.lowlevel.checkpoint_if_cancelled() + + @classmethod + async def cancel_shielded_checkpoint(cls) -> None: + await trio.lowlevel.cancel_shielded_checkpoint() + + @classmethod + async def sleep(cls, delay: float) -> None: + await trio.sleep(delay) + + @classmethod + def create_cancel_scope( + cls, *, deadline: float = math.inf, shield: bool = False + ) -> abc.CancelScope: + return CancelScope(deadline=deadline, shield=shield) + + @classmethod + def current_effective_deadline(cls) -> float: + return trio.current_effective_deadline() + + @classmethod + def create_task_group(cls) -> abc.TaskGroup: + return TaskGroup() + + @classmethod + def create_event(cls) -> abc.Event: + return Event() + + @classmethod + def create_lock(cls, *, fast_acquire: bool) -> Lock: + return Lock(fast_acquire=fast_acquire) + + @classmethod + def create_semaphore( + cls, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> abc.Semaphore: + return Semaphore(initial_value, max_value=max_value, fast_acquire=fast_acquire) + + @classmethod + def create_capacity_limiter(cls, total_tokens: float) -> CapacityLimiter: + return CapacityLimiter(total_tokens) + + @classmethod + async def run_sync_in_worker_thread( + cls, + func: Callable[[Unpack[PosArgsT]], T_Retval], + args: tuple[Unpack[PosArgsT]], + abandon_on_cancel: bool = False, + limiter: abc.CapacityLimiter | None = None, + ) -> T_Retval: + def wrapper() -> T_Retval: + with claim_worker_thread(TrioBackend, token): + return func(*args) + + token = TrioBackend.current_token() + return await run_sync( + wrapper, + abandon_on_cancel=abandon_on_cancel, + limiter=cast(trio.CapacityLimiter, limiter), + ) + + @classmethod + def check_cancelled(cls) -> None: + trio.from_thread.check_cancelled() + + @classmethod + def run_async_from_thread( + cls, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + args: tuple[Unpack[PosArgsT]], + token: object, + ) -> T_Retval: + trio_token = cast("trio.lowlevel.TrioToken | None", token) + try: + return trio.from_thread.run(func, *args, trio_token=trio_token) + except trio.RunFinishedError: + raise RunFinishedError from None + + @classmethod + def run_sync_from_thread( + cls, + func: Callable[[Unpack[PosArgsT]], T_Retval], + args: tuple[Unpack[PosArgsT]], + token: object, + ) -> T_Retval: + trio_token = cast("trio.lowlevel.TrioToken | None", token) + try: + return trio.from_thread.run_sync(func, *args, trio_token=trio_token) + except trio.RunFinishedError: + raise RunFinishedError from None + + @classmethod + async def open_process( + cls, + command: StrOrBytesPath | Sequence[StrOrBytesPath], + *, + stdin: int | IO[Any] | None, + stdout: int | IO[Any] | None, + stderr: int | IO[Any] | None, + **kwargs: Any, + ) -> Process: + def convert_item(item: StrOrBytesPath) -> str: + str_or_bytes = os.fspath(item) + if isinstance(str_or_bytes, str): + return str_or_bytes + else: + return os.fsdecode(str_or_bytes) + + if isinstance(command, (str, bytes, PathLike)): + process = await trio.lowlevel.open_process( + convert_item(command), + stdin=stdin, + stdout=stdout, + stderr=stderr, + shell=True, + **kwargs, + ) + else: + process = await trio.lowlevel.open_process( + [convert_item(item) for item in command], + stdin=stdin, + stdout=stdout, + stderr=stderr, + shell=False, + **kwargs, + ) + + stdin_stream = SendStreamWrapper(process.stdin) if process.stdin else None + stdout_stream = ReceiveStreamWrapper(process.stdout) if process.stdout else None + stderr_stream = ReceiveStreamWrapper(process.stderr) if process.stderr else None + return Process(process, stdin_stream, stdout_stream, stderr_stream) + + @classmethod + def setup_process_pool_exit_at_shutdown(cls, workers: set[abc.Process]) -> None: + trio.lowlevel.spawn_system_task(_shutdown_process_pool, workers) + + @classmethod + async def connect_tcp( + cls, host: str, port: int, local_address: IPSockAddrType | None = None + ) -> SocketStream: + family = socket.AF_INET6 if ":" in host else socket.AF_INET + trio_socket = trio.socket.socket(family) + trio_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + if local_address: + await trio_socket.bind(local_address) + + try: + await trio_socket.connect((host, port)) + except BaseException: + trio_socket.close() + raise + + return SocketStream(trio_socket) + + @classmethod + async def connect_unix(cls, path: str | bytes) -> abc.UNIXSocketStream: + trio_socket = trio.socket.socket(socket.AF_UNIX) + try: + await trio_socket.connect(path) + except BaseException: + trio_socket.close() + raise + + return UNIXSocketStream(trio_socket) + + @classmethod + def create_tcp_listener(cls, sock: socket.socket) -> abc.SocketListener: + return TCPSocketListener(sock) + + @classmethod + def create_unix_listener(cls, sock: socket.socket) -> abc.SocketListener: + return UNIXSocketListener(sock) + + @classmethod + async def create_udp_socket( + cls, + family: socket.AddressFamily, + local_address: IPSockAddrType | None, + remote_address: IPSockAddrType | None, + reuse_port: bool, + ) -> UDPSocket | ConnectedUDPSocket: + trio_socket = trio.socket.socket(family=family, type=socket.SOCK_DGRAM) + + if reuse_port: + trio_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + + if local_address: + await trio_socket.bind(local_address) + + if remote_address: + await trio_socket.connect(remote_address) + return ConnectedUDPSocket(trio_socket) + else: + return UDPSocket(trio_socket) + + @classmethod + @overload + async def create_unix_datagram_socket( + cls, raw_socket: socket.socket, remote_path: None + ) -> abc.UNIXDatagramSocket: ... + + @classmethod + @overload + async def create_unix_datagram_socket( + cls, raw_socket: socket.socket, remote_path: str | bytes + ) -> abc.ConnectedUNIXDatagramSocket: ... + + @classmethod + async def create_unix_datagram_socket( + cls, raw_socket: socket.socket, remote_path: str | bytes | None + ) -> abc.UNIXDatagramSocket | abc.ConnectedUNIXDatagramSocket: + trio_socket = trio.socket.from_stdlib_socket(raw_socket) + + if remote_path: + await trio_socket.connect(remote_path) + return ConnectedUNIXDatagramSocket(trio_socket) + else: + return UNIXDatagramSocket(trio_socket) + + @classmethod + async def getaddrinfo( + cls, + host: bytes | str | None, + port: str | int | None, + *, + family: int | AddressFamily = 0, + type: int | SocketKind = 0, + proto: int = 0, + flags: int = 0, + ) -> Sequence[ + tuple[ + AddressFamily, + SocketKind, + int, + str, + tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes], + ] + ]: + return await trio.socket.getaddrinfo(host, port, family, type, proto, flags) + + @classmethod + async def getnameinfo( + cls, sockaddr: IPSockAddrType, flags: int = 0 + ) -> tuple[str, str]: + return await trio.socket.getnameinfo(sockaddr, flags) + + @classmethod + async def wait_readable(cls, obj: FileDescriptorLike) -> None: + try: + await wait_readable(obj) + except trio.ClosedResourceError as exc: + raise ClosedResourceError().with_traceback(exc.__traceback__) from None + except trio.BusyResourceError: + raise BusyResourceError("reading from") from None + + @classmethod + async def wait_writable(cls, obj: FileDescriptorLike) -> None: + try: + await wait_writable(obj) + except trio.ClosedResourceError as exc: + raise ClosedResourceError().with_traceback(exc.__traceback__) from None + except trio.BusyResourceError: + raise BusyResourceError("writing to") from None + + @classmethod + def notify_closing(cls, obj: FileDescriptorLike) -> None: + notify_closing(obj) + + @classmethod + async def wrap_listener_socket(cls, sock: socket.socket) -> abc.SocketListener: + return TCPSocketListener(sock) + + @classmethod + async def wrap_stream_socket(cls, sock: socket.socket) -> SocketStream: + trio_sock = trio.socket.from_stdlib_socket(sock) + return SocketStream(trio_sock) + + @classmethod + async def wrap_unix_stream_socket(cls, sock: socket.socket) -> UNIXSocketStream: + trio_sock = trio.socket.from_stdlib_socket(sock) + return UNIXSocketStream(trio_sock) + + @classmethod + async def wrap_udp_socket(cls, sock: socket.socket) -> UDPSocket: + trio_sock = trio.socket.from_stdlib_socket(sock) + return UDPSocket(trio_sock) + + @classmethod + async def wrap_connected_udp_socket(cls, sock: socket.socket) -> ConnectedUDPSocket: + trio_sock = trio.socket.from_stdlib_socket(sock) + return ConnectedUDPSocket(trio_sock) + + @classmethod + async def wrap_unix_datagram_socket(cls, sock: socket.socket) -> UNIXDatagramSocket: + trio_sock = trio.socket.from_stdlib_socket(sock) + return UNIXDatagramSocket(trio_sock) + + @classmethod + async def wrap_connected_unix_datagram_socket( + cls, sock: socket.socket + ) -> ConnectedUNIXDatagramSocket: + trio_sock = trio.socket.from_stdlib_socket(sock) + return ConnectedUNIXDatagramSocket(trio_sock) + + @classmethod + def current_default_thread_limiter(cls) -> CapacityLimiter: + try: + return _capacity_limiter_wrapper.get() + except LookupError: + limiter = CapacityLimiter( + original=trio.to_thread.current_default_thread_limiter() + ) + _capacity_limiter_wrapper.set(limiter) + return limiter + + @classmethod + def open_signal_receiver( + cls, *signals: Signals + ) -> AbstractContextManager[AsyncIterator[Signals]]: + return _SignalReceiver(signals) + + @classmethod + def get_current_task(cls) -> TaskInfo: + task = current_task() + return TrioTaskInfo(task) + + @classmethod + def get_running_tasks(cls) -> Sequence[TaskInfo]: + root_task = current_root_task() + assert root_task + task_infos = [TrioTaskInfo(root_task)] + nurseries = root_task.child_nurseries + while nurseries: + new_nurseries: list[trio.Nursery] = [] + for nursery in nurseries: + for task in nursery.child_tasks: + task_infos.append(TrioTaskInfo(task)) + new_nurseries.extend(task.child_nurseries) + + nurseries = new_nurseries + + return task_infos + + @classmethod + async def wait_all_tasks_blocked(cls) -> None: + from trio.testing import wait_all_tasks_blocked + + await wait_all_tasks_blocked() + + @classmethod + def create_test_runner(cls, options: dict[str, Any]) -> TestRunner: + return TestRunner(**options) + + +backend_class = TrioBackend diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_asyncio_selector_thread.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_asyncio_selector_thread.py new file mode 100644 index 0000000000000000000000000000000000000000..9f35bae568e33e6a9e1219761c83cc8350fa0532 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_asyncio_selector_thread.py @@ -0,0 +1,167 @@ +from __future__ import annotations + +import asyncio +import socket +import threading +from collections.abc import Callable +from selectors import EVENT_READ, EVENT_WRITE, DefaultSelector +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from _typeshed import FileDescriptorLike + +_selector_lock = threading.Lock() +_selector: Selector | None = None + + +class Selector: + def __init__(self) -> None: + self._thread = threading.Thread(target=self.run, name="AnyIO socket selector") + self._selector = DefaultSelector() + self._send, self._receive = socket.socketpair() + self._send.setblocking(False) + self._receive.setblocking(False) + # This somewhat reduces the amount of memory wasted queueing up data + # for wakeups. With these settings, maximum number of 1-byte sends + # before getting BlockingIOError: + # Linux 4.8: 6 + # macOS (darwin 15.5): 1 + # Windows 10: 525347 + # Windows you're weird. (And on Windows setting SNDBUF to 0 makes send + # blocking, even on non-blocking sockets, so don't do that.) + self._receive.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1) + self._send.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1) + # On Windows this is a TCP socket so this might matter. On other + # platforms this fails b/c AF_UNIX sockets aren't actually TCP. + try: + self._send.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + except OSError: + pass + + self._selector.register(self._receive, EVENT_READ) + self._closed = False + + def start(self) -> None: + self._thread.start() + threading._register_atexit(self._stop) # type: ignore[attr-defined] + + def _stop(self) -> None: + global _selector + self._closed = True + self._notify_self() + self._send.close() + self._thread.join() + self._selector.unregister(self._receive) + self._receive.close() + self._selector.close() + _selector = None + assert not self._selector.get_map(), ( + "selector still has registered file descriptors after shutdown" + ) + + def _notify_self(self) -> None: + try: + self._send.send(b"\x00") + except BlockingIOError: + pass + + def add_reader(self, fd: FileDescriptorLike, callback: Callable[[], Any]) -> None: + loop = asyncio.get_running_loop() + try: + key = self._selector.get_key(fd) + except KeyError: + self._selector.register(fd, EVENT_READ, {EVENT_READ: (loop, callback)}) + else: + if EVENT_READ in key.data: + raise ValueError( + "this file descriptor is already registered for reading" + ) + + key.data[EVENT_READ] = loop, callback + self._selector.modify(fd, key.events | EVENT_READ, key.data) + + self._notify_self() + + def add_writer(self, fd: FileDescriptorLike, callback: Callable[[], Any]) -> None: + loop = asyncio.get_running_loop() + try: + key = self._selector.get_key(fd) + except KeyError: + self._selector.register(fd, EVENT_WRITE, {EVENT_WRITE: (loop, callback)}) + else: + if EVENT_WRITE in key.data: + raise ValueError( + "this file descriptor is already registered for writing" + ) + + key.data[EVENT_WRITE] = loop, callback + self._selector.modify(fd, key.events | EVENT_WRITE, key.data) + + self._notify_self() + + def remove_reader(self, fd: FileDescriptorLike) -> bool: + try: + key = self._selector.get_key(fd) + except KeyError: + return False + + if new_events := key.events ^ EVENT_READ: + del key.data[EVENT_READ] + self._selector.modify(fd, new_events, key.data) + else: + self._selector.unregister(fd) + + return True + + def remove_writer(self, fd: FileDescriptorLike) -> bool: + try: + key = self._selector.get_key(fd) + except KeyError: + return False + + if new_events := key.events ^ EVENT_WRITE: + del key.data[EVENT_WRITE] + self._selector.modify(fd, new_events, key.data) + else: + self._selector.unregister(fd) + + return True + + def run(self) -> None: + while not self._closed: + for key, events in self._selector.select(): + if key.fileobj is self._receive: + try: + while self._receive.recv(4096): + pass + except BlockingIOError: + pass + + continue + + if events & EVENT_READ: + loop, callback = key.data[EVENT_READ] + self.remove_reader(key.fd) + try: + loop.call_soon_threadsafe(callback) + except RuntimeError: + pass # the loop was already closed + + if events & EVENT_WRITE: + loop, callback = key.data[EVENT_WRITE] + self.remove_writer(key.fd) + try: + loop.call_soon_threadsafe(callback) + except RuntimeError: + pass # the loop was already closed + + +def get_selector() -> Selector: + global _selector + + with _selector_lock: + if _selector is None: + _selector = Selector() + _selector.start() + + return _selector diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_contextmanagers.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_contextmanagers.py new file mode 100644 index 0000000000000000000000000000000000000000..302f32b0c78a7071605b195c55054cfdb0b55f37 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_contextmanagers.py @@ -0,0 +1,200 @@ +from __future__ import annotations + +from abc import abstractmethod +from contextlib import AbstractAsyncContextManager, AbstractContextManager +from inspect import isasyncgen, iscoroutine, isgenerator +from types import TracebackType +from typing import Protocol, TypeVar, cast, final + +_T_co = TypeVar("_T_co", covariant=True) +_ExitT_co = TypeVar("_ExitT_co", covariant=True, bound="bool | None") + + +class _SupportsCtxMgr(Protocol[_T_co, _ExitT_co]): + def __contextmanager__(self) -> AbstractContextManager[_T_co, _ExitT_co]: ... + + +class _SupportsAsyncCtxMgr(Protocol[_T_co, _ExitT_co]): + def __asynccontextmanager__( + self, + ) -> AbstractAsyncContextManager[_T_co, _ExitT_co]: ... + + +class ContextManagerMixin: + """ + Mixin class providing context manager functionality via a generator-based + implementation. + + This class allows you to implement a context manager via :meth:`__contextmanager__` + which should return a generator. The mechanics are meant to mirror those of + :func:`@contextmanager `. + + .. note:: Classes using this mix-in are not reentrant as context managers, meaning + that once you enter it, you can't re-enter before first exiting it. + + .. seealso:: :doc:`contextmanagers` + """ + + __cm: AbstractContextManager[object, bool | None] | None = None + + @final + def __enter__(self: _SupportsCtxMgr[_T_co, bool | None]) -> _T_co: + # Needed for mypy to assume self still has the __cm member + assert isinstance(self, ContextManagerMixin) + if self.__cm is not None: + raise RuntimeError( + f"this {self.__class__.__qualname__} has already been entered" + ) + + cm = self.__contextmanager__() + if not isinstance(cm, AbstractContextManager): + if isgenerator(cm): + raise TypeError( + "__contextmanager__() returned a generator object instead of " + "a context manager. Did you forget to add the @contextmanager " + "decorator?" + ) + + raise TypeError( + f"__contextmanager__() did not return a context manager object, " + f"but {cm.__class__!r}" + ) + + if cm is self: + raise TypeError( + f"{self.__class__.__qualname__}.__contextmanager__() returned " + f"self. Did you forget to add the @contextmanager decorator and a " + f"'yield' statement?" + ) + + value = cm.__enter__() + self.__cm = cm + return value + + @final + def __exit__( + self: _SupportsCtxMgr[object, _ExitT_co], + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> _ExitT_co: + # Needed for mypy to assume self still has the __cm member + assert isinstance(self, ContextManagerMixin) + if self.__cm is None: + raise RuntimeError( + f"this {self.__class__.__qualname__} has not been entered yet" + ) + + # Prevent circular references + cm = self.__cm + del self.__cm + + return cast(_ExitT_co, cm.__exit__(exc_type, exc_val, exc_tb)) + + @abstractmethod + def __contextmanager__(self) -> AbstractContextManager[object, bool | None]: + """ + Implement your context manager logic here. + + This method **must** be decorated with + :func:`@contextmanager `. + + .. note:: Remember that the ``yield`` will raise any exception raised in the + enclosed context block, so use a ``finally:`` block to clean up resources! + + :return: a context manager object + """ + + +class AsyncContextManagerMixin: + """ + Mixin class providing async context manager functionality via a generator-based + implementation. + + This class allows you to implement a context manager via + :meth:`__asynccontextmanager__`. The mechanics are meant to mirror those of + :func:`@asynccontextmanager `. + + .. note:: Classes using this mix-in are not reentrant as context managers, meaning + that once you enter it, you can't re-enter before first exiting it. + + .. seealso:: :doc:`contextmanagers` + """ + + __cm: AbstractAsyncContextManager[object, bool | None] | None = None + + @final + async def __aenter__(self: _SupportsAsyncCtxMgr[_T_co, bool | None]) -> _T_co: + # Needed for mypy to assume self still has the __cm member + assert isinstance(self, AsyncContextManagerMixin) + if self.__cm is not None: + raise RuntimeError( + f"this {self.__class__.__qualname__} has already been entered" + ) + + cm = self.__asynccontextmanager__() + if not isinstance(cm, AbstractAsyncContextManager): + if isasyncgen(cm): + raise TypeError( + "__asynccontextmanager__() returned an async generator instead of " + "an async context manager. Did you forget to add the " + "@asynccontextmanager decorator?" + ) + elif iscoroutine(cm): + cm.close() + raise TypeError( + "__asynccontextmanager__() returned a coroutine object instead of " + "an async context manager. Did you forget to add the " + "@asynccontextmanager decorator and a 'yield' statement?" + ) + + raise TypeError( + f"__asynccontextmanager__() did not return an async context manager, " + f"but {cm.__class__!r}" + ) + + if cm is self: + raise TypeError( + f"{self.__class__.__qualname__}.__asynccontextmanager__() returned " + f"self. Did you forget to add the @asynccontextmanager decorator and a " + f"'yield' statement?" + ) + + value = await cm.__aenter__() + self.__cm = cm + return value + + @final + async def __aexit__( + self: _SupportsAsyncCtxMgr[object, _ExitT_co], + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> _ExitT_co: + assert isinstance(self, AsyncContextManagerMixin) + if self.__cm is None: + raise RuntimeError( + f"this {self.__class__.__qualname__} has not been entered yet" + ) + + # Prevent circular references + cm = self.__cm + del self.__cm + + return cast(_ExitT_co, await cm.__aexit__(exc_type, exc_val, exc_tb)) + + @abstractmethod + def __asynccontextmanager__( + self, + ) -> AbstractAsyncContextManager[object, bool | None]: + """ + Implement your async context manager logic here. + + This method **must** be decorated with + :func:`@asynccontextmanager `. + + .. note:: Remember that the ``yield`` will raise any exception raised in the + enclosed context block, so use a ``finally:`` block to clean up resources! + + :return: an async context manager object + """ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_eventloop.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_eventloop.py new file mode 100644 index 0000000000000000000000000000000000000000..59a69ccdf02c2989fb522bcc9af5a23f64e1f3e7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_eventloop.py @@ -0,0 +1,234 @@ +from __future__ import annotations + +import math +import sys +import threading +from collections.abc import Awaitable, Callable, Generator +from contextlib import contextmanager +from contextvars import Token +from importlib import import_module +from typing import TYPE_CHECKING, Any, TypeVar + +from ._exceptions import NoEventLoopError + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +sniffio: Any +try: + import sniffio +except ModuleNotFoundError: + sniffio = None + +if TYPE_CHECKING: + from ..abc import AsyncBackend + +# This must be updated when new backends are introduced +BACKENDS = "asyncio", "trio" + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") + +threadlocals = threading.local() +loaded_backends: dict[str, type[AsyncBackend]] = {} + + +def run( + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + *args: Unpack[PosArgsT], + backend: str = "asyncio", + backend_options: dict[str, Any] | None = None, +) -> T_Retval: + """ + Run the given coroutine function in an asynchronous event loop. + + The current thread must not be already running an event loop. + + :param func: a coroutine function + :param args: positional arguments to ``func`` + :param backend: name of the asynchronous event loop implementation – currently + either ``asyncio`` or ``trio`` + :param backend_options: keyword arguments to call the backend ``run()`` + implementation with (documented :ref:`here `) + :return: the return value of the coroutine function + :raises RuntimeError: if an asynchronous event loop is already running in this + thread + :raises LookupError: if the named backend is not found + + """ + if asynclib_name := current_async_library(): + raise RuntimeError(f"Already running {asynclib_name} in this thread") + + try: + async_backend = get_async_backend(backend) + except ImportError as exc: + raise LookupError(f"No such backend: {backend}") from exc + + token = None + if asynclib_name is None: + # Since we're in control of the event loop, we can cache the name of the async + # library + token = set_current_async_library(backend) + + try: + backend_options = backend_options or {} + return async_backend.run(func, args, {}, backend_options) + finally: + reset_current_async_library(token) + + +async def sleep(delay: float) -> None: + """ + Pause the current task for the specified duration. + + :param delay: the duration, in seconds + + """ + return await get_async_backend().sleep(delay) + + +async def sleep_forever() -> None: + """ + Pause the current task until it's cancelled. + + This is a shortcut for ``sleep(math.inf)``. + + .. versionadded:: 3.1 + + """ + await sleep(math.inf) + + +async def sleep_until(deadline: float) -> None: + """ + Pause the current task until the given time. + + :param deadline: the absolute time to wake up at (according to the internal + monotonic clock of the event loop) + + .. versionadded:: 3.1 + + """ + now = current_time() + await sleep(max(deadline - now, 0)) + + +def current_time() -> float: + """ + Return the current value of the event loop's internal clock. + + :return: the clock value (seconds) + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + return get_async_backend().current_time() + + +def get_all_backends() -> tuple[str, ...]: + """Return a tuple of the names of all built-in backends.""" + return BACKENDS + + +def get_available_backends() -> tuple[str, ...]: + """ + Test for the availability of built-in backends. + + :return a tuple of the built-in backend names that were successfully imported + + .. versionadded:: 4.12 + + """ + available_backends: list[str] = [] + for backend_name in get_all_backends(): + try: + get_async_backend(backend_name) + except ImportError: + continue + + available_backends.append(backend_name) + + return tuple(available_backends) + + +def get_cancelled_exc_class() -> type[BaseException]: + """ + Return the current async library's cancellation exception class. + + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + return get_async_backend().cancelled_exception_class() + + +# +# Private API +# + + +@contextmanager +def claim_worker_thread( + backend_class: type[AsyncBackend], token: object +) -> Generator[Any, None, None]: + from ..lowlevel import EventLoopToken + + threadlocals.current_token = EventLoopToken(backend_class, token) + try: + yield + finally: + del threadlocals.current_token + + +def get_async_backend(asynclib_name: str | None = None) -> type[AsyncBackend]: + if asynclib_name is None: + asynclib_name = current_async_library() + if not asynclib_name: + raise NoEventLoopError( + f"Not currently running on any asynchronous event loop. " + f"Available async backends: {', '.join(get_all_backends())}" + ) + + # We use our own dict instead of sys.modules to get the already imported back-end + # class because the appropriate modules in sys.modules could potentially be only + # partially initialized + try: + return loaded_backends[asynclib_name] + except KeyError: + module = import_module(f"anyio._backends._{asynclib_name}") + loaded_backends[asynclib_name] = module.backend_class + return module.backend_class + + +def current_async_library() -> str | None: + if sniffio is None: + # If sniffio is not installed, we assume we're either running asyncio or nothing + import asyncio + + try: + asyncio.get_running_loop() + return "asyncio" + except RuntimeError: + pass + else: + try: + return sniffio.current_async_library() + except sniffio.AsyncLibraryNotFoundError: + pass + + return None + + +def set_current_async_library(asynclib_name: str | None) -> Token | None: + # no-op if sniffio is not installed + if sniffio is None: + return None + + return sniffio.current_async_library_cvar.set(asynclib_name) + + +def reset_current_async_library(token: Token | None) -> None: + if token is not None: + sniffio.current_async_library_cvar.reset(token) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_exceptions.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..3776bedcd339913d609e41e2e396f3f2fd16ae9d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_exceptions.py @@ -0,0 +1,156 @@ +from __future__ import annotations + +import sys +from collections.abc import Generator +from textwrap import dedent +from typing import Any + +if sys.version_info < (3, 11): + from exceptiongroup import BaseExceptionGroup + + +class BrokenResourceError(Exception): + """ + Raised when trying to use a resource that has been rendered unusable due to external + causes (e.g. a send stream whose peer has disconnected). + """ + + +class BrokenWorkerProcess(Exception): + """ + Raised by :meth:`~anyio.to_process.run_sync` if the worker process terminates abruptly or + otherwise misbehaves. + """ + + +class BrokenWorkerInterpreter(Exception): + """ + Raised by :meth:`~anyio.to_interpreter.run_sync` if an unexpected exception is + raised in the subinterpreter. + """ + + def __init__(self, excinfo: Any): + # This was adapted from concurrent.futures.interpreter.ExecutionFailed + msg = excinfo.formatted + if not msg: + if excinfo.type and excinfo.msg: + msg = f"{excinfo.type.__name__}: {excinfo.msg}" + else: + msg = excinfo.type.__name__ or excinfo.msg + + super().__init__(msg) + self.excinfo = excinfo + + def __str__(self) -> str: + try: + formatted = self.excinfo.errdisplay + except Exception: + return super().__str__() + else: + return dedent( + f""" + {super().__str__()} + + Uncaught in the interpreter: + + {formatted} + """.strip() + ) + + +class BusyResourceError(Exception): + """ + Raised when two tasks are trying to read from or write to the same resource + concurrently. + """ + + def __init__(self, action: str): + super().__init__(f"Another task is already {action} this resource") + + +class ClosedResourceError(Exception): + """Raised when trying to use a resource that has been closed.""" + + +class ConnectionFailed(OSError): + """ + Raised when a connection attempt fails. + + .. note:: This class inherits from :exc:`OSError` for backwards compatibility. + """ + + +def iterate_exceptions( + exception: BaseException, +) -> Generator[BaseException, None, None]: + if isinstance(exception, BaseExceptionGroup): + for exc in exception.exceptions: + yield from iterate_exceptions(exc) + else: + yield exception + + +class DelimiterNotFound(Exception): + """ + Raised during + :meth:`~anyio.streams.buffered.BufferedByteReceiveStream.receive_until` if the + maximum number of bytes has been read without the delimiter being found. + """ + + def __init__(self, max_bytes: int) -> None: + super().__init__( + f"The delimiter was not found among the first {max_bytes} bytes" + ) + + +class EndOfStream(Exception): + """ + Raised when trying to read from a stream that has been closed from the other end. + """ + + +class IncompleteRead(Exception): + """ + Raised during + :meth:`~anyio.streams.buffered.BufferedByteReceiveStream.receive_exactly` or + :meth:`~anyio.streams.buffered.BufferedByteReceiveStream.receive_until` if the + connection is closed before the requested amount of bytes has been read. + """ + + def __init__(self) -> None: + super().__init__( + "The stream was closed before the read operation could be completed" + ) + + +class TypedAttributeLookupError(LookupError): + """ + Raised by :meth:`~anyio.TypedAttributeProvider.extra` when the given typed attribute + is not found and no default value has been given. + """ + + +class WouldBlock(Exception): + """Raised by ``X_nowait`` functions if ``X()`` would block.""" + + +class NoEventLoopError(RuntimeError): + """ + Raised by several functions that require an event loop to be running in the current + thread when there is no running event loop. + + This is also raised by :func:`.from_thread.run` and :func:`.from_thread.run_sync` + if not calling from an AnyIO worker thread, and no ``token`` was passed. + """ + + +class RunFinishedError(RuntimeError): + """ + Raised by :func:`.from_thread.run` and :func:`.from_thread.run_sync` if the event + loop associated with the explicitly passed token has already finished. + """ + + def __init__(self) -> None: + super().__init__( + "The event loop associated with the given token has already finished" + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_fileio.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_fileio.py new file mode 100644 index 0000000000000000000000000000000000000000..061f0d7e100b04a338249ae592ead886fa54335e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_fileio.py @@ -0,0 +1,797 @@ +from __future__ import annotations + +import os +import pathlib +import sys +from collections.abc import ( + AsyncIterator, + Callable, + Iterable, + Iterator, + Sequence, +) +from dataclasses import dataclass +from functools import partial +from os import PathLike +from typing import ( + IO, + TYPE_CHECKING, + Any, + AnyStr, + ClassVar, + Final, + Generic, + overload, +) + +from .. import to_thread +from ..abc import AsyncResource + +if TYPE_CHECKING: + from types import ModuleType + + from _typeshed import OpenBinaryMode, OpenTextMode, ReadableBuffer, WriteableBuffer +else: + ReadableBuffer = OpenBinaryMode = OpenTextMode = WriteableBuffer = object + + +class AsyncFile(AsyncResource, Generic[AnyStr]): + """ + An asynchronous file object. + + This class wraps a standard file object and provides async friendly versions of the + following blocking methods (where available on the original file object): + + * read + * read1 + * readline + * readlines + * readinto + * readinto1 + * write + * writelines + * truncate + * seek + * tell + * flush + + All other methods are directly passed through. + + This class supports the asynchronous context manager protocol which closes the + underlying file at the end of the context block. + + This class also supports asynchronous iteration:: + + async with await open_file(...) as f: + async for line in f: + print(line) + """ + + def __init__(self, fp: IO[AnyStr]) -> None: + self._fp: Any = fp + + def __getattr__(self, name: str) -> object: + return getattr(self._fp, name) + + @property + def wrapped(self) -> IO[AnyStr]: + """The wrapped file object.""" + return self._fp + + async def __aiter__(self) -> AsyncIterator[AnyStr]: + while True: + line = await self.readline() + if line: + yield line + else: + break + + async def aclose(self) -> None: + return await to_thread.run_sync(self._fp.close) + + async def read(self, size: int = -1) -> AnyStr: + return await to_thread.run_sync(self._fp.read, size) + + async def read1(self: AsyncFile[bytes], size: int = -1) -> bytes: + return await to_thread.run_sync(self._fp.read1, size) + + async def readline(self) -> AnyStr: + return await to_thread.run_sync(self._fp.readline) + + async def readlines(self) -> list[AnyStr]: + return await to_thread.run_sync(self._fp.readlines) + + async def readinto(self: AsyncFile[bytes], b: WriteableBuffer) -> int: + return await to_thread.run_sync(self._fp.readinto, b) + + async def readinto1(self: AsyncFile[bytes], b: WriteableBuffer) -> int: + return await to_thread.run_sync(self._fp.readinto1, b) + + @overload + async def write(self: AsyncFile[bytes], b: ReadableBuffer) -> int: ... + + @overload + async def write(self: AsyncFile[str], b: str) -> int: ... + + async def write(self, b: ReadableBuffer | str) -> int: + return await to_thread.run_sync(self._fp.write, b) + + @overload + async def writelines( + self: AsyncFile[bytes], lines: Iterable[ReadableBuffer] + ) -> None: ... + + @overload + async def writelines(self: AsyncFile[str], lines: Iterable[str]) -> None: ... + + async def writelines(self, lines: Iterable[ReadableBuffer] | Iterable[str]) -> None: + return await to_thread.run_sync(self._fp.writelines, lines) + + async def truncate(self, size: int | None = None) -> int: + return await to_thread.run_sync(self._fp.truncate, size) + + async def seek(self, offset: int, whence: int | None = os.SEEK_SET) -> int: + return await to_thread.run_sync(self._fp.seek, offset, whence) + + async def tell(self) -> int: + return await to_thread.run_sync(self._fp.tell) + + async def flush(self) -> None: + return await to_thread.run_sync(self._fp.flush) + + +@overload +async def open_file( + file: str | PathLike[str] | int, + mode: OpenBinaryMode, + buffering: int = ..., + encoding: str | None = ..., + errors: str | None = ..., + newline: str | None = ..., + closefd: bool = ..., + opener: Callable[[str, int], int] | None = ..., +) -> AsyncFile[bytes]: ... + + +@overload +async def open_file( + file: str | PathLike[str] | int, + mode: OpenTextMode = ..., + buffering: int = ..., + encoding: str | None = ..., + errors: str | None = ..., + newline: str | None = ..., + closefd: bool = ..., + opener: Callable[[str, int], int] | None = ..., +) -> AsyncFile[str]: ... + + +async def open_file( + file: str | PathLike[str] | int, + mode: str = "r", + buffering: int = -1, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + closefd: bool = True, + opener: Callable[[str, int], int] | None = None, +) -> AsyncFile[Any]: + """ + Open a file asynchronously. + + The arguments are exactly the same as for the builtin :func:`open`. + + :return: an asynchronous file object + + """ + fp = await to_thread.run_sync( + open, file, mode, buffering, encoding, errors, newline, closefd, opener + ) + return AsyncFile(fp) + + +def wrap_file(file: IO[AnyStr]) -> AsyncFile[AnyStr]: + """ + Wrap an existing file as an asynchronous file. + + :param file: an existing file-like object + :return: an asynchronous file object + + """ + return AsyncFile(file) + + +@dataclass(eq=False) +class _PathIterator(AsyncIterator["Path"]): + iterator: Iterator[PathLike[str]] + + async def __anext__(self) -> Path: + nextval = await to_thread.run_sync( + next, self.iterator, None, abandon_on_cancel=True + ) + if nextval is None: + raise StopAsyncIteration from None + + return Path(nextval) + + +class Path: + """ + An asynchronous version of :class:`pathlib.Path`. + + This class cannot be substituted for :class:`pathlib.Path` or + :class:`pathlib.PurePath`, but it is compatible with the :class:`os.PathLike` + interface. + + It implements the Python 3.10 version of :class:`pathlib.Path` interface, except for + the deprecated :meth:`~pathlib.Path.link_to` method. + + Some methods may be unavailable or have limited functionality, based on the Python + version: + + * :meth:`~pathlib.Path.copy` (available on Python 3.14 or later) + * :meth:`~pathlib.Path.copy_into` (available on Python 3.14 or later) + * :meth:`~pathlib.Path.from_uri` (available on Python 3.13 or later) + * :meth:`~pathlib.PurePath.full_match` (available on Python 3.13 or later) + * :attr:`~pathlib.Path.info` (available on Python 3.14 or later) + * :meth:`~pathlib.Path.is_junction` (available on Python 3.12 or later) + * :meth:`~pathlib.PurePath.match` (the ``case_sensitive`` parameter is only + available on Python 3.13 or later) + * :meth:`~pathlib.Path.move` (available on Python 3.14 or later) + * :meth:`~pathlib.Path.move_into` (available on Python 3.14 or later) + * :meth:`~pathlib.PurePath.relative_to` (the ``walk_up`` parameter is only available + on Python 3.12 or later) + * :meth:`~pathlib.Path.walk` (available on Python 3.12 or later) + + Any methods that do disk I/O need to be awaited on. These methods are: + + * :meth:`~pathlib.Path.absolute` + * :meth:`~pathlib.Path.chmod` + * :meth:`~pathlib.Path.cwd` + * :meth:`~pathlib.Path.exists` + * :meth:`~pathlib.Path.expanduser` + * :meth:`~pathlib.Path.group` + * :meth:`~pathlib.Path.hardlink_to` + * :meth:`~pathlib.Path.home` + * :meth:`~pathlib.Path.is_block_device` + * :meth:`~pathlib.Path.is_char_device` + * :meth:`~pathlib.Path.is_dir` + * :meth:`~pathlib.Path.is_fifo` + * :meth:`~pathlib.Path.is_file` + * :meth:`~pathlib.Path.is_junction` + * :meth:`~pathlib.Path.is_mount` + * :meth:`~pathlib.Path.is_socket` + * :meth:`~pathlib.Path.is_symlink` + * :meth:`~pathlib.Path.lchmod` + * :meth:`~pathlib.Path.lstat` + * :meth:`~pathlib.Path.mkdir` + * :meth:`~pathlib.Path.open` + * :meth:`~pathlib.Path.owner` + * :meth:`~pathlib.Path.read_bytes` + * :meth:`~pathlib.Path.read_text` + * :meth:`~pathlib.Path.readlink` + * :meth:`~pathlib.Path.rename` + * :meth:`~pathlib.Path.replace` + * :meth:`~pathlib.Path.resolve` + * :meth:`~pathlib.Path.rmdir` + * :meth:`~pathlib.Path.samefile` + * :meth:`~pathlib.Path.stat` + * :meth:`~pathlib.Path.symlink_to` + * :meth:`~pathlib.Path.touch` + * :meth:`~pathlib.Path.unlink` + * :meth:`~pathlib.Path.walk` + * :meth:`~pathlib.Path.write_bytes` + * :meth:`~pathlib.Path.write_text` + + Additionally, the following methods return an async iterator yielding + :class:`~.Path` objects: + + * :meth:`~pathlib.Path.glob` + * :meth:`~pathlib.Path.iterdir` + * :meth:`~pathlib.Path.rglob` + """ + + __slots__ = "_path", "__weakref__" + + __weakref__: Any + + def __init__(self, *args: str | PathLike[str]) -> None: + self._path: Final[pathlib.Path] = pathlib.Path(*args) + + def __fspath__(self) -> str: + return self._path.__fspath__() + + def __str__(self) -> str: + return self._path.__str__() + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.as_posix()!r})" + + def __bytes__(self) -> bytes: + return self._path.__bytes__() + + def __hash__(self) -> int: + return self._path.__hash__() + + def __eq__(self, other: object) -> bool: + target = other._path if isinstance(other, Path) else other + return self._path.__eq__(target) + + def __lt__(self, other: pathlib.PurePath | Path) -> bool: + target = other._path if isinstance(other, Path) else other + return self._path.__lt__(target) + + def __le__(self, other: pathlib.PurePath | Path) -> bool: + target = other._path if isinstance(other, Path) else other + return self._path.__le__(target) + + def __gt__(self, other: pathlib.PurePath | Path) -> bool: + target = other._path if isinstance(other, Path) else other + return self._path.__gt__(target) + + def __ge__(self, other: pathlib.PurePath | Path) -> bool: + target = other._path if isinstance(other, Path) else other + return self._path.__ge__(target) + + def __truediv__(self, other: str | PathLike[str]) -> Path: + return Path(self._path / other) + + def __rtruediv__(self, other: str | PathLike[str]) -> Path: + return Path(other) / self + + @property + def parts(self) -> tuple[str, ...]: + return self._path.parts + + @property + def drive(self) -> str: + return self._path.drive + + @property + def root(self) -> str: + return self._path.root + + @property + def anchor(self) -> str: + return self._path.anchor + + @property + def parents(self) -> Sequence[Path]: + return tuple(Path(p) for p in self._path.parents) + + @property + def parent(self) -> Path: + return Path(self._path.parent) + + @property + def name(self) -> str: + return self._path.name + + @property + def suffix(self) -> str: + return self._path.suffix + + @property + def suffixes(self) -> list[str]: + return self._path.suffixes + + @property + def stem(self) -> str: + return self._path.stem + + async def absolute(self) -> Path: + path = await to_thread.run_sync(self._path.absolute) + return Path(path) + + def as_posix(self) -> str: + return self._path.as_posix() + + def as_uri(self) -> str: + return self._path.as_uri() + + if sys.version_info >= (3, 13): + parser: ClassVar[ModuleType] = pathlib.Path.parser + + @classmethod + def from_uri(cls, uri: str) -> Path: + return Path(pathlib.Path.from_uri(uri)) + + def full_match( + self, path_pattern: str, *, case_sensitive: bool | None = None + ) -> bool: + return self._path.full_match(path_pattern, case_sensitive=case_sensitive) + + def match( + self, path_pattern: str, *, case_sensitive: bool | None = None + ) -> bool: + return self._path.match(path_pattern, case_sensitive=case_sensitive) + else: + + def match(self, path_pattern: str) -> bool: + return self._path.match(path_pattern) + + if sys.version_info >= (3, 14): + + @property + def info(self) -> Any: # TODO: add return type annotation when Typeshed gets it + return self._path.info + + async def copy( + self, + target: str | os.PathLike[str], + *, + follow_symlinks: bool = True, + preserve_metadata: bool = False, + ) -> Path: + func = partial( + self._path.copy, + follow_symlinks=follow_symlinks, + preserve_metadata=preserve_metadata, + ) + return Path(await to_thread.run_sync(func, pathlib.Path(target))) + + async def copy_into( + self, + target_dir: str | os.PathLike[str], + *, + follow_symlinks: bool = True, + preserve_metadata: bool = False, + ) -> Path: + func = partial( + self._path.copy_into, + follow_symlinks=follow_symlinks, + preserve_metadata=preserve_metadata, + ) + return Path(await to_thread.run_sync(func, pathlib.Path(target_dir))) + + async def move(self, target: str | os.PathLike[str]) -> Path: + # Upstream does not handle anyio.Path properly as a PathLike + target = pathlib.Path(target) + return Path(await to_thread.run_sync(self._path.move, target)) + + async def move_into( + self, + target_dir: str | os.PathLike[str], + ) -> Path: + return Path(await to_thread.run_sync(self._path.move_into, target_dir)) + + def is_relative_to(self, other: str | PathLike[str]) -> bool: + try: + self.relative_to(other) + return True + except ValueError: + return False + + async def chmod(self, mode: int, *, follow_symlinks: bool = True) -> None: + func = partial(os.chmod, follow_symlinks=follow_symlinks) + return await to_thread.run_sync(func, self._path, mode) + + @classmethod + async def cwd(cls) -> Path: + path = await to_thread.run_sync(pathlib.Path.cwd) + return cls(path) + + async def exists(self) -> bool: + return await to_thread.run_sync(self._path.exists, abandon_on_cancel=True) + + async def expanduser(self) -> Path: + return Path( + await to_thread.run_sync(self._path.expanduser, abandon_on_cancel=True) + ) + + if sys.version_info < (3, 12): + # Python 3.11 and earlier + def glob(self, pattern: str) -> AsyncIterator[Path]: + gen = self._path.glob(pattern) + return _PathIterator(gen) + elif (3, 12) <= sys.version_info < (3, 13): + # changed in Python 3.12: + # - The case_sensitive parameter was added. + def glob( + self, + pattern: str, + *, + case_sensitive: bool | None = None, + ) -> AsyncIterator[Path]: + gen = self._path.glob(pattern, case_sensitive=case_sensitive) + return _PathIterator(gen) + elif sys.version_info >= (3, 13): + # Changed in Python 3.13: + # - The recurse_symlinks parameter was added. + # - The pattern parameter accepts a path-like object. + def glob( # type: ignore[misc] # mypy doesn't allow for differing signatures in a conditional block + self, + pattern: str | PathLike[str], + *, + case_sensitive: bool | None = None, + recurse_symlinks: bool = False, + ) -> AsyncIterator[Path]: + gen = self._path.glob( + pattern, # type: ignore[arg-type] + case_sensitive=case_sensitive, + recurse_symlinks=recurse_symlinks, + ) + return _PathIterator(gen) + + async def group(self) -> str: + return await to_thread.run_sync(self._path.group, abandon_on_cancel=True) + + async def hardlink_to( + self, target: str | bytes | PathLike[str] | PathLike[bytes] + ) -> None: + if isinstance(target, Path): + target = target._path + + await to_thread.run_sync(os.link, target, self) + + @classmethod + async def home(cls) -> Path: + home_path = await to_thread.run_sync(pathlib.Path.home) + return cls(home_path) + + def is_absolute(self) -> bool: + return self._path.is_absolute() + + async def is_block_device(self) -> bool: + return await to_thread.run_sync( + self._path.is_block_device, abandon_on_cancel=True + ) + + async def is_char_device(self) -> bool: + return await to_thread.run_sync( + self._path.is_char_device, abandon_on_cancel=True + ) + + async def is_dir(self) -> bool: + return await to_thread.run_sync(self._path.is_dir, abandon_on_cancel=True) + + async def is_fifo(self) -> bool: + return await to_thread.run_sync(self._path.is_fifo, abandon_on_cancel=True) + + async def is_file(self) -> bool: + return await to_thread.run_sync(self._path.is_file, abandon_on_cancel=True) + + if sys.version_info >= (3, 12): + + async def is_junction(self) -> bool: + return await to_thread.run_sync(self._path.is_junction) + + async def is_mount(self) -> bool: + return await to_thread.run_sync( + os.path.ismount, self._path, abandon_on_cancel=True + ) + + def is_reserved(self) -> bool: + return self._path.is_reserved() + + async def is_socket(self) -> bool: + return await to_thread.run_sync(self._path.is_socket, abandon_on_cancel=True) + + async def is_symlink(self) -> bool: + return await to_thread.run_sync(self._path.is_symlink, abandon_on_cancel=True) + + async def iterdir(self) -> AsyncIterator[Path]: + gen = ( + self._path.iterdir() + if sys.version_info < (3, 13) + else await to_thread.run_sync(self._path.iterdir, abandon_on_cancel=True) + ) + async for path in _PathIterator(gen): + yield path + + def joinpath(self, *args: str | PathLike[str]) -> Path: + return Path(self._path.joinpath(*args)) + + async def lchmod(self, mode: int) -> None: + await to_thread.run_sync(self._path.lchmod, mode) + + async def lstat(self) -> os.stat_result: + return await to_thread.run_sync(self._path.lstat, abandon_on_cancel=True) + + async def mkdir( + self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False + ) -> None: + await to_thread.run_sync(self._path.mkdir, mode, parents, exist_ok) + + @overload + async def open( + self, + mode: OpenBinaryMode, + buffering: int = ..., + encoding: str | None = ..., + errors: str | None = ..., + newline: str | None = ..., + ) -> AsyncFile[bytes]: ... + + @overload + async def open( + self, + mode: OpenTextMode = ..., + buffering: int = ..., + encoding: str | None = ..., + errors: str | None = ..., + newline: str | None = ..., + ) -> AsyncFile[str]: ... + + async def open( + self, + mode: str = "r", + buffering: int = -1, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> AsyncFile[Any]: + fp = await to_thread.run_sync( + self._path.open, mode, buffering, encoding, errors, newline + ) + return AsyncFile(fp) + + async def owner(self) -> str: + return await to_thread.run_sync(self._path.owner, abandon_on_cancel=True) + + async def read_bytes(self) -> bytes: + return await to_thread.run_sync(self._path.read_bytes) + + async def read_text( + self, encoding: str | None = None, errors: str | None = None + ) -> str: + return await to_thread.run_sync(self._path.read_text, encoding, errors) + + if sys.version_info >= (3, 12): + + def relative_to( + self, *other: str | PathLike[str], walk_up: bool = False + ) -> Path: + # relative_to() should work with any PathLike but it doesn't + others = [pathlib.Path(other) for other in other] + return Path(self._path.relative_to(*others, walk_up=walk_up)) + + else: + + def relative_to(self, *other: str | PathLike[str]) -> Path: + return Path(self._path.relative_to(*other)) + + async def readlink(self) -> Path: + target = await to_thread.run_sync(os.readlink, self._path) + return Path(target) + + async def rename(self, target: str | pathlib.PurePath | Path) -> Path: + if isinstance(target, Path): + target = target._path + + await to_thread.run_sync(self._path.rename, target) + return Path(target) + + async def replace(self, target: str | pathlib.PurePath | Path) -> Path: + if isinstance(target, Path): + target = target._path + + await to_thread.run_sync(self._path.replace, target) + return Path(target) + + async def resolve(self, strict: bool = False) -> Path: + func = partial(self._path.resolve, strict=strict) + return Path(await to_thread.run_sync(func, abandon_on_cancel=True)) + + if sys.version_info < (3, 12): + # Pre Python 3.12 + def rglob(self, pattern: str) -> AsyncIterator[Path]: + gen = self._path.rglob(pattern) + return _PathIterator(gen) + elif (3, 12) <= sys.version_info < (3, 13): + # Changed in Python 3.12: + # - The case_sensitive parameter was added. + def rglob( + self, pattern: str, *, case_sensitive: bool | None = None + ) -> AsyncIterator[Path]: + gen = self._path.rglob(pattern, case_sensitive=case_sensitive) + return _PathIterator(gen) + elif sys.version_info >= (3, 13): + # Changed in Python 3.13: + # - The recurse_symlinks parameter was added. + # - The pattern parameter accepts a path-like object. + def rglob( # type: ignore[misc] # mypy doesn't allow for differing signatures in a conditional block + self, + pattern: str | PathLike[str], + *, + case_sensitive: bool | None = None, + recurse_symlinks: bool = False, + ) -> AsyncIterator[Path]: + gen = self._path.rglob( + pattern, # type: ignore[arg-type] + case_sensitive=case_sensitive, + recurse_symlinks=recurse_symlinks, + ) + return _PathIterator(gen) + + async def rmdir(self) -> None: + await to_thread.run_sync(self._path.rmdir) + + async def samefile(self, other_path: str | PathLike[str]) -> bool: + if isinstance(other_path, Path): + other_path = other_path._path + + return await to_thread.run_sync( + self._path.samefile, other_path, abandon_on_cancel=True + ) + + async def stat(self, *, follow_symlinks: bool = True) -> os.stat_result: + func = partial(os.stat, follow_symlinks=follow_symlinks) + return await to_thread.run_sync(func, self._path, abandon_on_cancel=True) + + async def symlink_to( + self, + target: str | bytes | PathLike[str] | PathLike[bytes], + target_is_directory: bool = False, + ) -> None: + if isinstance(target, Path): + target = target._path + + await to_thread.run_sync(self._path.symlink_to, target, target_is_directory) + + async def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None: + await to_thread.run_sync(self._path.touch, mode, exist_ok) + + async def unlink(self, missing_ok: bool = False) -> None: + try: + await to_thread.run_sync(self._path.unlink) + except FileNotFoundError: + if not missing_ok: + raise + + if sys.version_info >= (3, 12): + + async def walk( + self, + top_down: bool = True, + on_error: Callable[[OSError], object] | None = None, + follow_symlinks: bool = False, + ) -> AsyncIterator[tuple[Path, list[str], list[str]]]: + def get_next_value() -> tuple[pathlib.Path, list[str], list[str]] | None: + try: + return next(gen) + except StopIteration: + return None + + gen = self._path.walk(top_down, on_error, follow_symlinks) + while True: + value = await to_thread.run_sync(get_next_value) + if value is None: + return + + root, dirs, paths = value + yield Path(root), dirs, paths + + def with_name(self, name: str) -> Path: + return Path(self._path.with_name(name)) + + def with_stem(self, stem: str) -> Path: + return Path(self._path.with_name(stem + self._path.suffix)) + + def with_suffix(self, suffix: str) -> Path: + return Path(self._path.with_suffix(suffix)) + + def with_segments(self, *pathsegments: str | PathLike[str]) -> Path: + return Path(*pathsegments) + + async def write_bytes(self, data: bytes) -> int: + return await to_thread.run_sync(self._path.write_bytes, data) + + async def write_text( + self, + data: str, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> int: + # Path.write_text() does not support the "newline" parameter before Python 3.10 + def sync_write_text() -> int: + with self._path.open( + "w", encoding=encoding, errors=errors, newline=newline + ) as fp: + return fp.write(data) + + return await to_thread.run_sync(sync_write_text) + + +PathLike.register(Path) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_resources.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..b9a5344aef2962670f9b305a02cd0b11f2087d2f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_resources.py @@ -0,0 +1,18 @@ +from __future__ import annotations + +from ..abc import AsyncResource +from ._tasks import CancelScope + + +async def aclose_forcefully(resource: AsyncResource) -> None: + """ + Close an asynchronous resource in a cancelled scope. + + Doing this closes the resource without waiting on anything. + + :param resource: the resource to close + + """ + with CancelScope() as scope: + scope.cancel() + await resource.aclose() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_signals.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_signals.py new file mode 100644 index 0000000000000000000000000000000000000000..e24c79e10d4b76775679f7dd0dbe3f5860150451 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_signals.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +from collections.abc import AsyncIterator +from contextlib import AbstractContextManager +from signal import Signals + +from ._eventloop import get_async_backend + + +def open_signal_receiver( + *signals: Signals, +) -> AbstractContextManager[AsyncIterator[Signals]]: + """ + Start receiving operating system signals. + + :param signals: signals to receive (e.g. ``signal.SIGINT``) + :return: an asynchronous context manager for an asynchronous iterator which yields + signal numbers + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + .. warning:: Windows does not support signals natively so it is best to avoid + relying on this in cross-platform applications. + + .. warning:: On asyncio, this permanently replaces any previous signal handler for + the given signals, as set via :meth:`~asyncio.loop.add_signal_handler`. + + """ + return get_async_backend().open_signal_receiver(*signals) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_sockets.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_sockets.py new file mode 100644 index 0000000000000000000000000000000000000000..6c99b3a1c1c7a5beee07aa5cf053149f8b5b9e2f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_sockets.py @@ -0,0 +1,1003 @@ +from __future__ import annotations + +import errno +import os +import socket +import ssl +import stat +import sys +from collections.abc import Awaitable +from dataclasses import dataclass +from ipaddress import IPv4Address, IPv6Address, ip_address +from os import PathLike, chmod +from socket import AddressFamily, SocketKind +from typing import TYPE_CHECKING, Any, Literal, cast, overload + +from .. import ConnectionFailed, to_thread +from ..abc import ( + ByteStreamConnectable, + ConnectedUDPSocket, + ConnectedUNIXDatagramSocket, + IPAddressType, + IPSockAddrType, + SocketListener, + SocketStream, + UDPSocket, + UNIXDatagramSocket, + UNIXSocketStream, +) +from ..streams.stapled import MultiListener +from ..streams.tls import TLSConnectable, TLSStream +from ._eventloop import get_async_backend +from ._resources import aclose_forcefully +from ._synchronization import Event +from ._tasks import create_task_group, move_on_after + +if TYPE_CHECKING: + from _typeshed import FileDescriptorLike +else: + FileDescriptorLike = object + +if sys.version_info < (3, 11): + from exceptiongroup import ExceptionGroup + +if sys.version_info >= (3, 12): + from typing import override +else: + from typing_extensions import override + +if sys.version_info < (3, 13): + from typing_extensions import deprecated +else: + from warnings import deprecated + +IPPROTO_IPV6 = getattr(socket, "IPPROTO_IPV6", 41) # https://bugs.python.org/issue29515 + +AnyIPAddressFamily = Literal[ + AddressFamily.AF_UNSPEC, AddressFamily.AF_INET, AddressFamily.AF_INET6 +] +IPAddressFamily = Literal[AddressFamily.AF_INET, AddressFamily.AF_INET6] + + +# tls_hostname given +@overload +async def connect_tcp( + remote_host: IPAddressType, + remote_port: int, + *, + local_host: IPAddressType | None = ..., + ssl_context: ssl.SSLContext | None = ..., + tls_standard_compatible: bool = ..., + tls_hostname: str, + happy_eyeballs_delay: float = ..., +) -> TLSStream: ... + + +# ssl_context given +@overload +async def connect_tcp( + remote_host: IPAddressType, + remote_port: int, + *, + local_host: IPAddressType | None = ..., + ssl_context: ssl.SSLContext, + tls_standard_compatible: bool = ..., + tls_hostname: str | None = ..., + happy_eyeballs_delay: float = ..., +) -> TLSStream: ... + + +# tls=True +@overload +async def connect_tcp( + remote_host: IPAddressType, + remote_port: int, + *, + local_host: IPAddressType | None = ..., + tls: Literal[True], + ssl_context: ssl.SSLContext | None = ..., + tls_standard_compatible: bool = ..., + tls_hostname: str | None = ..., + happy_eyeballs_delay: float = ..., +) -> TLSStream: ... + + +# tls=False +@overload +async def connect_tcp( + remote_host: IPAddressType, + remote_port: int, + *, + local_host: IPAddressType | None = ..., + tls: Literal[False], + ssl_context: ssl.SSLContext | None = ..., + tls_standard_compatible: bool = ..., + tls_hostname: str | None = ..., + happy_eyeballs_delay: float = ..., +) -> SocketStream: ... + + +# No TLS arguments +@overload +async def connect_tcp( + remote_host: IPAddressType, + remote_port: int, + *, + local_host: IPAddressType | None = ..., + happy_eyeballs_delay: float = ..., +) -> SocketStream: ... + + +async def connect_tcp( + remote_host: IPAddressType, + remote_port: int, + *, + local_host: IPAddressType | None = None, + tls: bool = False, + ssl_context: ssl.SSLContext | None = None, + tls_standard_compatible: bool = True, + tls_hostname: str | None = None, + happy_eyeballs_delay: float = 0.25, +) -> SocketStream | TLSStream: + """ + Connect to a host using the TCP protocol. + + This function implements the stateless version of the Happy Eyeballs algorithm (RFC + 6555). If ``remote_host`` is a host name that resolves to multiple IP addresses, + each one is tried until one connection attempt succeeds. If the first attempt does + not connected within 250 milliseconds, a second attempt is started using the next + address in the list, and so on. On IPv6 enabled systems, an IPv6 address (if + available) is tried first. + + When the connection has been established, a TLS handshake will be done if either + ``ssl_context`` or ``tls_hostname`` is not ``None``, or if ``tls`` is ``True``. + + :param remote_host: the IP address or host name to connect to + :param remote_port: port on the target host to connect to + :param local_host: the interface address or name to bind the socket to before + connecting + :param tls: ``True`` to do a TLS handshake with the connected stream and return a + :class:`~anyio.streams.tls.TLSStream` instead + :param ssl_context: the SSL context object to use (if omitted, a default context is + created) + :param tls_standard_compatible: If ``True``, performs the TLS shutdown handshake + before closing the stream and requires that the server does this as well. + Otherwise, :exc:`~ssl.SSLEOFError` may be raised during reads from the stream. + Some protocols, such as HTTP, require this option to be ``False``. + See :meth:`~ssl.SSLContext.wrap_socket` for details. + :param tls_hostname: host name to check the server certificate against (defaults to + the value of ``remote_host``) + :param happy_eyeballs_delay: delay (in seconds) before starting the next connection + attempt + :return: a socket stream object if no TLS handshake was done, otherwise a TLS stream + :raises ConnectionFailed: if the connection fails + + """ + # Placed here due to https://github.com/python/mypy/issues/7057 + connected_stream: SocketStream | None = None + + async def try_connect(remote_host: str, event: Event) -> None: + nonlocal connected_stream + try: + stream = await asynclib.connect_tcp(remote_host, remote_port, local_address) + except OSError as exc: + oserrors.append(exc) + return + else: + if connected_stream is None: + connected_stream = stream + tg.cancel_scope.cancel() + else: + await stream.aclose() + finally: + event.set() + + asynclib = get_async_backend() + local_address: IPSockAddrType | None = None + family = socket.AF_UNSPEC + if local_host: + gai_res = await getaddrinfo(str(local_host), None) + family, *_, local_address = gai_res[0] + + target_host = str(remote_host) + try: + addr_obj = ip_address(remote_host) + except ValueError: + addr_obj = None + + if addr_obj is not None: + if isinstance(addr_obj, IPv6Address): + target_addrs = [(socket.AF_INET6, addr_obj.compressed)] + else: + target_addrs = [(socket.AF_INET, addr_obj.compressed)] + else: + # getaddrinfo() will raise an exception if name resolution fails + gai_res = await getaddrinfo( + target_host, remote_port, family=family, type=socket.SOCK_STREAM + ) + + # Organize the list so that the first address is an IPv6 address (if available) + # and the second one is an IPv4 addresses. The rest can be in whatever order. + v6_found = v4_found = False + target_addrs = [] + for af, *_, sa in gai_res: + if af == socket.AF_INET6 and not v6_found: + v6_found = True + target_addrs.insert(0, (af, sa[0])) + elif af == socket.AF_INET and not v4_found and v6_found: + v4_found = True + target_addrs.insert(1, (af, sa[0])) + else: + target_addrs.append((af, sa[0])) + + oserrors: list[OSError] = [] + try: + async with create_task_group() as tg: + for _af, addr in target_addrs: + event = Event() + tg.start_soon(try_connect, addr, event) + with move_on_after(happy_eyeballs_delay): + await event.wait() + + if connected_stream is None: + cause = ( + oserrors[0] + if len(oserrors) == 1 + else ExceptionGroup("multiple connection attempts failed", oserrors) + ) + raise OSError("All connection attempts failed") from cause + finally: + oserrors.clear() + + if tls or tls_hostname or ssl_context: + try: + return await TLSStream.wrap( + connected_stream, + server_side=False, + hostname=tls_hostname or str(remote_host), + ssl_context=ssl_context, + standard_compatible=tls_standard_compatible, + ) + except BaseException: + await aclose_forcefully(connected_stream) + raise + + return connected_stream + + +async def connect_unix(path: str | bytes | PathLike[Any]) -> UNIXSocketStream: + """ + Connect to the given UNIX socket. + + Not available on Windows. + + :param path: path to the socket + :return: a socket stream object + :raises ConnectionFailed: if the connection fails + + """ + path = os.fspath(path) + return await get_async_backend().connect_unix(path) + + +async def create_tcp_listener( + *, + local_host: IPAddressType | None = None, + local_port: int = 0, + family: AnyIPAddressFamily = socket.AddressFamily.AF_UNSPEC, + backlog: int = 65536, + reuse_port: bool = False, +) -> MultiListener[SocketStream]: + """ + Create a TCP socket listener. + + :param local_port: port number to listen on + :param local_host: IP address of the interface to listen on. If omitted, listen on + all IPv4 and IPv6 interfaces. To listen on all interfaces on a specific address + family, use ``0.0.0.0`` for IPv4 or ``::`` for IPv6. + :param family: address family (used if ``local_host`` was omitted) + :param backlog: maximum number of queued incoming connections (up to a maximum of + 2**16, or 65536) + :param reuse_port: ``True`` to allow multiple sockets to bind to the same + address/port (not supported on Windows) + :return: a multi-listener object containing one or more socket listeners + :raises OSError: if there's an error creating a socket, or binding to one or more + interfaces failed + + """ + asynclib = get_async_backend() + backlog = min(backlog, 65536) + local_host = str(local_host) if local_host is not None else None + + def setup_raw_socket( + fam: AddressFamily, + bind_addr: tuple[str, int] | tuple[str, int, int, int], + *, + v6only: bool = True, + ) -> socket.socket: + sock = socket.socket(fam) + try: + sock.setblocking(False) + + if fam == AddressFamily.AF_INET6: + sock.setsockopt(IPPROTO_IPV6, socket.IPV6_V6ONLY, v6only) + + # For Windows, enable exclusive address use. For others, enable address + # reuse. + if sys.platform == "win32": + sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) + else: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + + if reuse_port: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + + # Workaround for #554 + if fam == socket.AF_INET6 and "%" in bind_addr[0]: + addr, scope_id = bind_addr[0].split("%", 1) + bind_addr = (addr, bind_addr[1], 0, int(scope_id)) + + sock.bind(bind_addr) + sock.listen(backlog) + except BaseException: + sock.close() + raise + + return sock + + # We passing type=0 on non-Windows platforms as a workaround for a uvloop bug + # where we don't get the correct scope ID for IPv6 link-local addresses when passing + # type=socket.SOCK_STREAM to getaddrinfo(): + # https://github.com/MagicStack/uvloop/issues/539 + gai_res = await getaddrinfo( + local_host, + local_port, + family=family, + type=socket.SOCK_STREAM if sys.platform == "win32" else 0, + flags=socket.AI_PASSIVE | socket.AI_ADDRCONFIG, + ) + + # The set comprehension is here to work around a glibc bug: + # https://sourceware.org/bugzilla/show_bug.cgi?id=14969 + sockaddrs = sorted({res for res in gai_res if res[1] == SocketKind.SOCK_STREAM}) + + # Special case for dual-stack binding on the "any" interface + if ( + local_host is None + and family == AddressFamily.AF_UNSPEC + and socket.has_dualstack_ipv6() + and any(fam == AddressFamily.AF_INET6 for fam, *_ in gai_res) + ): + raw_socket = setup_raw_socket( + AddressFamily.AF_INET6, ("::", local_port), v6only=False + ) + listener = asynclib.create_tcp_listener(raw_socket) + return MultiListener([listener]) + + errors: list[OSError] = [] + try: + for _ in range(len(sockaddrs)): + listeners: list[SocketListener] = [] + bound_ephemeral_port = local_port + try: + for fam, *_, sockaddr in sockaddrs: + sockaddr = sockaddr[0], bound_ephemeral_port, *sockaddr[2:] + raw_socket = setup_raw_socket(fam, sockaddr) + + # Store the assigned port if an ephemeral port was requested, so + # we'll bind to the same port on all interfaces + if local_port == 0 and len(gai_res) > 1: + bound_ephemeral_port = raw_socket.getsockname()[1] + + listeners.append(asynclib.create_tcp_listener(raw_socket)) + except BaseException as exc: + for listener in listeners: + await listener.aclose() + + # If an ephemeral port was requested but binding the assigned port + # failed for another interface, rotate the address list and try again + if ( + isinstance(exc, OSError) + and exc.errno == errno.EADDRINUSE + and local_port == 0 + and bound_ephemeral_port + ): + errors.append(exc) + sockaddrs.append(sockaddrs.pop(0)) + continue + + raise + + return MultiListener(listeners) + + raise OSError( + f"Could not create {len(sockaddrs)} listeners with a consistent port" + ) from ExceptionGroup("Several bind attempts failed", errors) + finally: + del errors # Prevent reference cycles + + +async def create_unix_listener( + path: str | bytes | PathLike[Any], + *, + mode: int | None = None, + backlog: int = 65536, +) -> SocketListener: + """ + Create a UNIX socket listener. + + Not available on Windows. + + :param path: path of the socket + :param mode: permissions to set on the socket + :param backlog: maximum number of queued incoming connections (up to a maximum of + 2**16, or 65536) + :return: a listener object + + .. versionchanged:: 3.0 + If a socket already exists on the file system in the given path, it will be + removed first. + + """ + backlog = min(backlog, 65536) + raw_socket = await setup_unix_local_socket(path, mode, socket.SOCK_STREAM) + try: + raw_socket.listen(backlog) + return get_async_backend().create_unix_listener(raw_socket) + except BaseException: + raw_socket.close() + raise + + +async def create_udp_socket( + family: AnyIPAddressFamily = AddressFamily.AF_UNSPEC, + *, + local_host: IPAddressType | None = None, + local_port: int = 0, + reuse_port: bool = False, +) -> UDPSocket: + """ + Create a UDP socket. + + If ``port`` has been given, the socket will be bound to this port on the local + machine, making this socket suitable for providing UDP based services. + + :param family: address family (``AF_INET`` or ``AF_INET6``) – automatically + determined from ``local_host`` if omitted + :param local_host: IP address or host name of the local interface to bind to + :param local_port: local port to bind to + :param reuse_port: ``True`` to allow multiple sockets to bind to the same + address/port (not supported on Windows) + :return: a UDP socket + + """ + if family is AddressFamily.AF_UNSPEC and not local_host: + raise ValueError('Either "family" or "local_host" must be given') + + if local_host: + gai_res = await getaddrinfo( + str(local_host), + local_port, + family=family, + type=socket.SOCK_DGRAM, + flags=socket.AI_PASSIVE | socket.AI_ADDRCONFIG, + ) + family = cast(AnyIPAddressFamily, gai_res[0][0]) + local_address = gai_res[0][-1] + elif family is AddressFamily.AF_INET6: + local_address = ("::", 0) + else: + local_address = ("0.0.0.0", 0) + + sock = await get_async_backend().create_udp_socket( + family, local_address, None, reuse_port + ) + return cast(UDPSocket, sock) + + +async def create_connected_udp_socket( + remote_host: IPAddressType, + remote_port: int, + *, + family: AnyIPAddressFamily = AddressFamily.AF_UNSPEC, + local_host: IPAddressType | None = None, + local_port: int = 0, + reuse_port: bool = False, +) -> ConnectedUDPSocket: + """ + Create a connected UDP socket. + + Connected UDP sockets can only communicate with the specified remote host/port, an + any packets sent from other sources are dropped. + + :param remote_host: remote host to set as the default target + :param remote_port: port on the remote host to set as the default target + :param family: address family (``AF_INET`` or ``AF_INET6``) – automatically + determined from ``local_host`` or ``remote_host`` if omitted + :param local_host: IP address or host name of the local interface to bind to + :param local_port: local port to bind to + :param reuse_port: ``True`` to allow multiple sockets to bind to the same + address/port (not supported on Windows) + :return: a connected UDP socket + + """ + local_address = None + if local_host: + gai_res = await getaddrinfo( + str(local_host), + local_port, + family=family, + type=socket.SOCK_DGRAM, + flags=socket.AI_PASSIVE | socket.AI_ADDRCONFIG, + ) + family = cast(AnyIPAddressFamily, gai_res[0][0]) + local_address = gai_res[0][-1] + + gai_res = await getaddrinfo( + str(remote_host), remote_port, family=family, type=socket.SOCK_DGRAM + ) + family = cast(AnyIPAddressFamily, gai_res[0][0]) + remote_address = gai_res[0][-1] + + sock = await get_async_backend().create_udp_socket( + family, local_address, remote_address, reuse_port + ) + return cast(ConnectedUDPSocket, sock) + + +async def create_unix_datagram_socket( + *, + local_path: None | str | bytes | PathLike[Any] = None, + local_mode: int | None = None, +) -> UNIXDatagramSocket: + """ + Create a UNIX datagram socket. + + Not available on Windows. + + If ``local_path`` has been given, the socket will be bound to this path, making this + socket suitable for receiving datagrams from other processes. Other processes can + send datagrams to this socket only if ``local_path`` is set. + + If a socket already exists on the file system in the ``local_path``, it will be + removed first. + + :param local_path: the path on which to bind to + :param local_mode: permissions to set on the local socket + :return: a UNIX datagram socket + + """ + raw_socket = await setup_unix_local_socket( + local_path, local_mode, socket.SOCK_DGRAM + ) + return await get_async_backend().create_unix_datagram_socket(raw_socket, None) + + +async def create_connected_unix_datagram_socket( + remote_path: str | bytes | PathLike[Any], + *, + local_path: None | str | bytes | PathLike[Any] = None, + local_mode: int | None = None, +) -> ConnectedUNIXDatagramSocket: + """ + Create a connected UNIX datagram socket. + + Connected datagram sockets can only communicate with the specified remote path. + + If ``local_path`` has been given, the socket will be bound to this path, making + this socket suitable for receiving datagrams from other processes. Other processes + can send datagrams to this socket only if ``local_path`` is set. + + If a socket already exists on the file system in the ``local_path``, it will be + removed first. + + :param remote_path: the path to set as the default target + :param local_path: the path on which to bind to + :param local_mode: permissions to set on the local socket + :return: a connected UNIX datagram socket + + """ + remote_path = os.fspath(remote_path) + raw_socket = await setup_unix_local_socket( + local_path, local_mode, socket.SOCK_DGRAM + ) + return await get_async_backend().create_unix_datagram_socket( + raw_socket, remote_path + ) + + +async def getaddrinfo( + host: bytes | str | None, + port: str | int | None, + *, + family: int | AddressFamily = 0, + type: int | SocketKind = 0, + proto: int = 0, + flags: int = 0, +) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int]]]: + """ + Look up a numeric IP address given a host name. + + Internationalized domain names are translated according to the (non-transitional) + IDNA 2008 standard. + + .. note:: 4-tuple IPv6 socket addresses are automatically converted to 2-tuples of + (host, port), unlike what :func:`socket.getaddrinfo` does. + + :param host: host name + :param port: port number + :param family: socket family (`'AF_INET``, ...) + :param type: socket type (``SOCK_STREAM``, ...) + :param proto: protocol number + :param flags: flags to pass to upstream ``getaddrinfo()`` + :return: list of tuples containing (family, type, proto, canonname, sockaddr) + + .. seealso:: :func:`socket.getaddrinfo` + + """ + # Handle unicode hostnames + if isinstance(host, str): + try: + encoded_host: bytes | None = host.encode("ascii") + except UnicodeEncodeError: + import idna + + encoded_host = idna.encode(host, uts46=True) + else: + encoded_host = host + + gai_res = await get_async_backend().getaddrinfo( + encoded_host, port, family=family, type=type, proto=proto, flags=flags + ) + return [ + (family, type, proto, canonname, convert_ipv6_sockaddr(sockaddr)) + for family, type, proto, canonname, sockaddr in gai_res + # filter out IPv6 results when IPv6 is disabled + if not isinstance(sockaddr[0], int) + ] + + +def getnameinfo(sockaddr: IPSockAddrType, flags: int = 0) -> Awaitable[tuple[str, str]]: + """ + Look up the host name of an IP address. + + :param sockaddr: socket address (e.g. (ipaddress, port) for IPv4) + :param flags: flags to pass to upstream ``getnameinfo()`` + :return: a tuple of (host name, service name) + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + .. seealso:: :func:`socket.getnameinfo` + + """ + return get_async_backend().getnameinfo(sockaddr, flags) + + +@deprecated("This function is deprecated; use `wait_readable` instead") +def wait_socket_readable(sock: socket.socket) -> Awaitable[None]: + """ + .. deprecated:: 4.7.0 + Use :func:`wait_readable` instead. + + Wait until the given socket has data to be read. + + .. warning:: Only use this on raw sockets that have not been wrapped by any higher + level constructs like socket streams! + + :param sock: a socket object + :raises ~anyio.ClosedResourceError: if the socket was closed while waiting for the + socket to become readable + :raises ~anyio.BusyResourceError: if another task is already waiting for the socket + to become readable + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + return get_async_backend().wait_readable(sock.fileno()) + + +@deprecated("This function is deprecated; use `wait_writable` instead") +def wait_socket_writable(sock: socket.socket) -> Awaitable[None]: + """ + .. deprecated:: 4.7.0 + Use :func:`wait_writable` instead. + + Wait until the given socket can be written to. + + This does **NOT** work on Windows when using the asyncio backend with a proactor + event loop (default on py3.8+). + + .. warning:: Only use this on raw sockets that have not been wrapped by any higher + level constructs like socket streams! + + :param sock: a socket object + :raises ~anyio.ClosedResourceError: if the socket was closed while waiting for the + socket to become writable + :raises ~anyio.BusyResourceError: if another task is already waiting for the socket + to become writable + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + return get_async_backend().wait_writable(sock.fileno()) + + +def wait_readable(obj: FileDescriptorLike) -> Awaitable[None]: + """ + Wait until the given object has data to be read. + + On Unix systems, ``obj`` must either be an integer file descriptor, or else an + object with a ``.fileno()`` method which returns an integer file descriptor. Any + kind of file descriptor can be passed, though the exact semantics will depend on + your kernel. For example, this probably won't do anything useful for on-disk files. + + On Windows systems, ``obj`` must either be an integer ``SOCKET`` handle, or else an + object with a ``.fileno()`` method which returns an integer ``SOCKET`` handle. File + descriptors aren't supported, and neither are handles that refer to anything besides + a ``SOCKET``. + + On backends where this functionality is not natively provided (asyncio + ``ProactorEventLoop`` on Windows), it is provided using a separate selector thread + which is set to shut down when the interpreter shuts down. + + .. warning:: Don't use this on raw sockets that have been wrapped by any higher + level constructs like socket streams! + + :param obj: an object with a ``.fileno()`` method or an integer handle + :raises ~anyio.ClosedResourceError: if the object was closed while waiting for the + object to become readable + :raises ~anyio.BusyResourceError: if another task is already waiting for the object + to become readable + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + return get_async_backend().wait_readable(obj) + + +def wait_writable(obj: FileDescriptorLike) -> Awaitable[None]: + """ + Wait until the given object can be written to. + + :param obj: an object with a ``.fileno()`` method or an integer handle + :raises ~anyio.ClosedResourceError: if the object was closed while waiting for the + object to become writable + :raises ~anyio.BusyResourceError: if another task is already waiting for the object + to become writable + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + .. seealso:: See the documentation of :func:`wait_readable` for the definition of + ``obj`` and notes on backend compatibility. + + .. warning:: Don't use this on raw sockets that have been wrapped by any higher + level constructs like socket streams! + + """ + return get_async_backend().wait_writable(obj) + + +def notify_closing(obj: FileDescriptorLike) -> None: + """ + Call this before closing a file descriptor (on Unix) or socket (on + Windows). This will cause any `wait_readable` or `wait_writable` + calls on the given object to immediately wake up and raise + `~anyio.ClosedResourceError`. + + This doesn't actually close the object – you still have to do that + yourself afterwards. Also, you want to be careful to make sure no + new tasks start waiting on the object in between when you call this + and when it's actually closed. So to close something properly, you + usually want to do these steps in order: + + 1. Explicitly mark the object as closed, so that any new attempts + to use it will abort before they start. + 2. Call `notify_closing` to wake up any already-existing users. + 3. Actually close the object. + + It's also possible to do them in a different order if that's more + convenient, *but only if* you make sure not to have any checkpoints in + between the steps. This way they all happen in a single atomic + step, so other tasks won't be able to tell what order they happened + in anyway. + + :param obj: an object with a ``.fileno()`` method or an integer handle + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + get_async_backend().notify_closing(obj) + + +# +# Private API +# + + +def convert_ipv6_sockaddr( + sockaddr: tuple[str, int, int, int] | tuple[str, int], +) -> tuple[str, int]: + """ + Convert a 4-tuple IPv6 socket address to a 2-tuple (address, port) format. + + If the scope ID is nonzero, it is added to the address, separated with ``%``. + Otherwise the flow id and scope id are simply cut off from the tuple. + Any other kinds of socket addresses are returned as-is. + + :param sockaddr: the result of :meth:`~socket.socket.getsockname` + :return: the converted socket address + + """ + # This is more complicated than it should be because of MyPy + if isinstance(sockaddr, tuple) and len(sockaddr) == 4: + host, port, flowinfo, scope_id = sockaddr + if scope_id: + # PyPy (as of v7.3.11) leaves the interface name in the result, so + # we discard it and only get the scope ID from the end + # (https://foss.heptapod.net/pypy/pypy/-/issues/3938) + host = host.split("%")[0] + + # Add scope_id to the address + return f"{host}%{scope_id}", port + else: + return host, port + else: + return sockaddr + + +async def setup_unix_local_socket( + path: None | str | bytes | PathLike[Any], + mode: int | None, + socktype: int, +) -> socket.socket: + """ + Create a UNIX local socket object, deleting the socket at the given path if it + exists. + + Not available on Windows. + + :param path: path of the socket + :param mode: permissions to set on the socket + :param socktype: socket.SOCK_STREAM or socket.SOCK_DGRAM + + """ + path_str: str | None + if path is not None: + path_str = os.fsdecode(path) + + # Linux abstract namespace sockets aren't backed by a concrete file so skip stat call + if not path_str.startswith("\0"): + # Copied from pathlib... + try: + stat_result = os.stat(path) + except OSError as e: + if e.errno not in ( + errno.ENOENT, + errno.ENOTDIR, + errno.EBADF, + errno.ELOOP, + ): + raise + else: + if stat.S_ISSOCK(stat_result.st_mode): + os.unlink(path) + else: + path_str = None + + raw_socket = socket.socket(socket.AF_UNIX, socktype) + raw_socket.setblocking(False) + + if path_str is not None: + try: + await to_thread.run_sync(raw_socket.bind, path_str, abandon_on_cancel=True) + if mode is not None: + await to_thread.run_sync(chmod, path_str, mode, abandon_on_cancel=True) + except BaseException: + raw_socket.close() + raise + + return raw_socket + + +@dataclass +class TCPConnectable(ByteStreamConnectable): + """ + Connects to a TCP server at the given host and port. + + :param host: host name or IP address of the server + :param port: TCP port number of the server + """ + + host: str | IPv4Address | IPv6Address + port: int + + def __post_init__(self) -> None: + if self.port < 1 or self.port > 65535: + raise ValueError("TCP port number out of range") + + @override + async def connect(self) -> SocketStream: + try: + return await connect_tcp(self.host, self.port) + except OSError as exc: + raise ConnectionFailed( + f"error connecting to {self.host}:{self.port}: {exc}" + ) from exc + + +@dataclass +class UNIXConnectable(ByteStreamConnectable): + """ + Connects to a UNIX domain socket at the given path. + + :param path: the file system path of the socket + """ + + path: str | bytes | PathLike[str] | PathLike[bytes] + + @override + async def connect(self) -> UNIXSocketStream: + try: + return await connect_unix(self.path) + except OSError as exc: + raise ConnectionFailed(f"error connecting to {self.path!r}: {exc}") from exc + + +def as_connectable( + remote: ByteStreamConnectable + | tuple[str | IPv4Address | IPv6Address, int] + | str + | bytes + | PathLike[str], + /, + *, + tls: bool = False, + ssl_context: ssl.SSLContext | None = None, + tls_hostname: str | None = None, + tls_standard_compatible: bool = True, +) -> ByteStreamConnectable: + """ + Return a byte stream connectable from the given object. + + If a bytestream connectable is given, it is returned unchanged. + If a tuple of (host, port) is given, a TCP connectable is returned. + If a string or bytes path is given, a UNIX connectable is returned. + + If ``tls=True``, the connectable will be wrapped in a + :class:`~.streams.tls.TLSConnectable`. + + :param remote: a connectable, a tuple of (host, port) or a path to a UNIX socket + :param tls: if ``True``, wrap the plaintext connectable in a + :class:`~.streams.tls.TLSConnectable`, using the provided TLS settings) + :param ssl_context: if ``tls=True``, the SSLContext object to use (if not provided, + a secure default will be created) + :param tls_hostname: if ``tls=True``, host name of the server to use for checking + the server certificate (defaults to the host portion of the address for TCP + connectables) + :param tls_standard_compatible: if ``False`` and ``tls=True``, makes the TLS stream + skip the closing handshake when closing the connection, so it won't raise an + exception if the server does the same + + """ + connectable: TCPConnectable | UNIXConnectable | TLSConnectable + if isinstance(remote, ByteStreamConnectable): + return remote + elif isinstance(remote, tuple) and len(remote) == 2: + connectable = TCPConnectable(*remote) + elif isinstance(remote, (str, bytes, PathLike)): + connectable = UNIXConnectable(remote) + else: + raise TypeError(f"cannot convert {remote!r} to a connectable") + + if tls: + if not tls_hostname and isinstance(connectable, TCPConnectable): + tls_hostname = str(connectable.host) + + connectable = TLSConnectable( + connectable, + ssl_context=ssl_context, + hostname=tls_hostname, + standard_compatible=tls_standard_compatible, + ) + + return connectable diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_streams.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_streams.py new file mode 100644 index 0000000000000000000000000000000000000000..2b9c7df200f9520357503c754bcdea1c047bdda3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_streams.py @@ -0,0 +1,52 @@ +from __future__ import annotations + +import math +from typing import TypeVar +from warnings import warn + +from ..streams.memory import ( + MemoryObjectReceiveStream, + MemoryObjectSendStream, + _MemoryObjectStreamState, +) + +T_Item = TypeVar("T_Item") + + +class create_memory_object_stream( + tuple[MemoryObjectSendStream[T_Item], MemoryObjectReceiveStream[T_Item]], +): + """ + Create a memory object stream. + + The stream's item type can be annotated like + :func:`create_memory_object_stream[T_Item]`. + + :param max_buffer_size: number of items held in the buffer until ``send()`` starts + blocking + :param item_type: old way of marking the streams with the right generic type for + static typing (does nothing on AnyIO 4) + + .. deprecated:: 4.0 + Use ``create_memory_object_stream[YourItemType](...)`` instead. + :return: a tuple of (send stream, receive stream) + + """ + + def __new__( # type: ignore[misc] + cls, max_buffer_size: float = 0, item_type: object = None + ) -> tuple[MemoryObjectSendStream[T_Item], MemoryObjectReceiveStream[T_Item]]: + if max_buffer_size != math.inf and not isinstance(max_buffer_size, int): + raise ValueError("max_buffer_size must be either an integer or math.inf") + if max_buffer_size < 0: + raise ValueError("max_buffer_size cannot be negative") + if item_type is not None: + warn( + "The item_type argument has been deprecated in AnyIO 4.0. " + "Use create_memory_object_stream[YourItemType](...) instead.", + DeprecationWarning, + stacklevel=2, + ) + + state = _MemoryObjectStreamState[T_Item](max_buffer_size) + return (MemoryObjectSendStream(state), MemoryObjectReceiveStream(state)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_subprocesses.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_subprocesses.py new file mode 100644 index 0000000000000000000000000000000000000000..36d9b306c992b83a8033c0ee66daa141d23d010c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_subprocesses.py @@ -0,0 +1,202 @@ +from __future__ import annotations + +import sys +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from io import BytesIO +from os import PathLike +from subprocess import PIPE, CalledProcessError, CompletedProcess +from typing import IO, Any, Union, cast + +from ..abc import Process +from ._eventloop import get_async_backend +from ._tasks import create_task_group + +if sys.version_info >= (3, 10): + from typing import TypeAlias +else: + from typing_extensions import TypeAlias + +StrOrBytesPath: TypeAlias = Union[str, bytes, "PathLike[str]", "PathLike[bytes]"] + + +async def run_process( + command: StrOrBytesPath | Sequence[StrOrBytesPath], + *, + input: bytes | None = None, + stdin: int | IO[Any] | None = None, + stdout: int | IO[Any] | None = PIPE, + stderr: int | IO[Any] | None = PIPE, + check: bool = True, + cwd: StrOrBytesPath | None = None, + env: Mapping[str, str] | None = None, + startupinfo: Any = None, + creationflags: int = 0, + start_new_session: bool = False, + pass_fds: Sequence[int] = (), + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, +) -> CompletedProcess[bytes]: + """ + Run an external command in a subprocess and wait until it completes. + + .. seealso:: :func:`subprocess.run` + + :param command: either a string to pass to the shell, or an iterable of strings + containing the executable name or path and its arguments + :param input: bytes passed to the standard input of the subprocess + :param stdin: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, + a file-like object, or `None`; ``input`` overrides this + :param stdout: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, + a file-like object, or `None` + :param stderr: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, + :data:`subprocess.STDOUT`, a file-like object, or `None` + :param check: if ``True``, raise :exc:`~subprocess.CalledProcessError` if the + process terminates with a return code other than 0 + :param cwd: If not ``None``, change the working directory to this before running the + command + :param env: if not ``None``, this mapping replaces the inherited environment + variables from the parent process + :param startupinfo: an instance of :class:`subprocess.STARTUPINFO` that can be used + to specify process startup parameters (Windows only) + :param creationflags: flags that can be used to control the creation of the + subprocess (see :class:`subprocess.Popen` for the specifics) + :param start_new_session: if ``true`` the setsid() system call will be made in the + child process prior to the execution of the subprocess. (POSIX only) + :param pass_fds: sequence of file descriptors to keep open between the parent and + child processes. (POSIX only) + :param user: effective user to run the process as (Python >= 3.9, POSIX only) + :param group: effective group to run the process as (Python >= 3.9, POSIX only) + :param extra_groups: supplementary groups to set in the subprocess (Python >= 3.9, + POSIX only) + :param umask: if not negative, this umask is applied in the child process before + running the given command (Python >= 3.9, POSIX only) + :return: an object representing the completed process + :raises ~subprocess.CalledProcessError: if ``check`` is ``True`` and the process + exits with a nonzero return code + + """ + + async def drain_stream(stream: AsyncIterable[bytes], index: int) -> None: + buffer = BytesIO() + async for chunk in stream: + buffer.write(chunk) + + stream_contents[index] = buffer.getvalue() + + if stdin is not None and input is not None: + raise ValueError("only one of stdin and input is allowed") + + async with await open_process( + command, + stdin=PIPE if input else stdin, + stdout=stdout, + stderr=stderr, + cwd=cwd, + env=env, + startupinfo=startupinfo, + creationflags=creationflags, + start_new_session=start_new_session, + pass_fds=pass_fds, + user=user, + group=group, + extra_groups=extra_groups, + umask=umask, + ) as process: + stream_contents: list[bytes | None] = [None, None] + async with create_task_group() as tg: + if process.stdout: + tg.start_soon(drain_stream, process.stdout, 0) + + if process.stderr: + tg.start_soon(drain_stream, process.stderr, 1) + + if process.stdin and input: + await process.stdin.send(input) + await process.stdin.aclose() + + await process.wait() + + output, errors = stream_contents + if check and process.returncode != 0: + raise CalledProcessError(cast(int, process.returncode), command, output, errors) + + return CompletedProcess(command, cast(int, process.returncode), output, errors) + + +async def open_process( + command: StrOrBytesPath | Sequence[StrOrBytesPath], + *, + stdin: int | IO[Any] | None = PIPE, + stdout: int | IO[Any] | None = PIPE, + stderr: int | IO[Any] | None = PIPE, + cwd: StrOrBytesPath | None = None, + env: Mapping[str, str] | None = None, + startupinfo: Any = None, + creationflags: int = 0, + start_new_session: bool = False, + pass_fds: Sequence[int] = (), + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, +) -> Process: + """ + Start an external command in a subprocess. + + .. seealso:: :class:`subprocess.Popen` + + :param command: either a string to pass to the shell, or an iterable of strings + containing the executable name or path and its arguments + :param stdin: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, a + file-like object, or ``None`` + :param stdout: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, + a file-like object, or ``None`` + :param stderr: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, + :data:`subprocess.STDOUT`, a file-like object, or ``None`` + :param cwd: If not ``None``, the working directory is changed before executing + :param env: If env is not ``None``, it must be a mapping that defines the + environment variables for the new process + :param creationflags: flags that can be used to control the creation of the + subprocess (see :class:`subprocess.Popen` for the specifics) + :param startupinfo: an instance of :class:`subprocess.STARTUPINFO` that can be used + to specify process startup parameters (Windows only) + :param start_new_session: if ``true`` the setsid() system call will be made in the + child process prior to the execution of the subprocess. (POSIX only) + :param pass_fds: sequence of file descriptors to keep open between the parent and + child processes. (POSIX only) + :param user: effective user to run the process as (POSIX only) + :param group: effective group to run the process as (POSIX only) + :param extra_groups: supplementary groups to set in the subprocess (POSIX only) + :param umask: if not negative, this umask is applied in the child process before + running the given command (POSIX only) + :return: an asynchronous process object + + """ + kwargs: dict[str, Any] = {} + if user is not None: + kwargs["user"] = user + + if group is not None: + kwargs["group"] = group + + if extra_groups is not None: + kwargs["extra_groups"] = group + + if umask >= 0: + kwargs["umask"] = umask + + return await get_async_backend().open_process( + command, + stdin=stdin, + stdout=stdout, + stderr=stderr, + cwd=cwd, + env=env, + startupinfo=startupinfo, + creationflags=creationflags, + start_new_session=start_new_session, + pass_fds=pass_fds, + **kwargs, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_synchronization.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_synchronization.py new file mode 100644 index 0000000000000000000000000000000000000000..c0ef27a686f22f77d5ec3f404005e2805fa46a64 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_synchronization.py @@ -0,0 +1,753 @@ +from __future__ import annotations + +import math +from collections import deque +from collections.abc import Callable +from dataclasses import dataclass +from types import TracebackType +from typing import TypeVar + +from ..lowlevel import checkpoint_if_cancelled +from ._eventloop import get_async_backend +from ._exceptions import BusyResourceError, NoEventLoopError +from ._tasks import CancelScope +from ._testing import TaskInfo, get_current_task + +T = TypeVar("T") + + +@dataclass(frozen=True) +class EventStatistics: + """ + :ivar int tasks_waiting: number of tasks waiting on :meth:`~.Event.wait` + """ + + tasks_waiting: int + + +@dataclass(frozen=True) +class CapacityLimiterStatistics: + """ + :ivar int borrowed_tokens: number of tokens currently borrowed by tasks + :ivar float total_tokens: total number of available tokens + :ivar tuple borrowers: tasks or other objects currently holding tokens borrowed from + this limiter + :ivar int tasks_waiting: number of tasks waiting on + :meth:`~.CapacityLimiter.acquire` or + :meth:`~.CapacityLimiter.acquire_on_behalf_of` + """ + + borrowed_tokens: int + total_tokens: float + borrowers: tuple[object, ...] + tasks_waiting: int + + +@dataclass(frozen=True) +class LockStatistics: + """ + :ivar bool locked: flag indicating if this lock is locked or not + :ivar ~anyio.TaskInfo owner: task currently holding the lock (or ``None`` if the + lock is not held by any task) + :ivar int tasks_waiting: number of tasks waiting on :meth:`~.Lock.acquire` + """ + + locked: bool + owner: TaskInfo | None + tasks_waiting: int + + +@dataclass(frozen=True) +class ConditionStatistics: + """ + :ivar int tasks_waiting: number of tasks blocked on :meth:`~.Condition.wait` + :ivar ~anyio.LockStatistics lock_statistics: statistics of the underlying + :class:`~.Lock` + """ + + tasks_waiting: int + lock_statistics: LockStatistics + + +@dataclass(frozen=True) +class SemaphoreStatistics: + """ + :ivar int tasks_waiting: number of tasks waiting on :meth:`~.Semaphore.acquire` + + """ + + tasks_waiting: int + + +class Event: + def __new__(cls) -> Event: + try: + return get_async_backend().create_event() + except NoEventLoopError: + return EventAdapter() + + def set(self) -> None: + """Set the flag, notifying all listeners.""" + raise NotImplementedError + + def is_set(self) -> bool: + """Return ``True`` if the flag is set, ``False`` if not.""" + raise NotImplementedError + + async def wait(self) -> None: + """ + Wait until the flag has been set. + + If the flag has already been set when this method is called, it returns + immediately. + + """ + raise NotImplementedError + + def statistics(self) -> EventStatistics: + """Return statistics about the current state of this event.""" + raise NotImplementedError + + +class EventAdapter(Event): + _internal_event: Event | None = None + _is_set: bool = False + + def __new__(cls) -> EventAdapter: + return object.__new__(cls) + + @property + def _event(self) -> Event: + if self._internal_event is None: + self._internal_event = get_async_backend().create_event() + if self._is_set: + self._internal_event.set() + + return self._internal_event + + def set(self) -> None: + if self._internal_event is None: + self._is_set = True + else: + self._event.set() + + def is_set(self) -> bool: + if self._internal_event is None: + return self._is_set + + return self._internal_event.is_set() + + async def wait(self) -> None: + await self._event.wait() + + def statistics(self) -> EventStatistics: + if self._internal_event is None: + return EventStatistics(tasks_waiting=0) + + return self._internal_event.statistics() + + +class Lock: + def __new__(cls, *, fast_acquire: bool = False) -> Lock: + try: + return get_async_backend().create_lock(fast_acquire=fast_acquire) + except NoEventLoopError: + return LockAdapter(fast_acquire=fast_acquire) + + async def __aenter__(self) -> None: + await self.acquire() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.release() + + async def acquire(self) -> None: + """Acquire the lock.""" + raise NotImplementedError + + def acquire_nowait(self) -> None: + """ + Acquire the lock, without blocking. + + :raises ~anyio.WouldBlock: if the operation would block + + """ + raise NotImplementedError + + def release(self) -> None: + """Release the lock.""" + raise NotImplementedError + + def locked(self) -> bool: + """Return True if the lock is currently held.""" + raise NotImplementedError + + def statistics(self) -> LockStatistics: + """ + Return statistics about the current state of this lock. + + .. versionadded:: 3.0 + """ + raise NotImplementedError + + +class LockAdapter(Lock): + _internal_lock: Lock | None = None + + def __new__(cls, *, fast_acquire: bool = False) -> LockAdapter: + return object.__new__(cls) + + def __init__(self, *, fast_acquire: bool = False): + self._fast_acquire = fast_acquire + + @property + def _lock(self) -> Lock: + if self._internal_lock is None: + self._internal_lock = get_async_backend().create_lock( + fast_acquire=self._fast_acquire + ) + + return self._internal_lock + + async def __aenter__(self) -> None: + await self._lock.acquire() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self._internal_lock is not None: + self._internal_lock.release() + + async def acquire(self) -> None: + """Acquire the lock.""" + await self._lock.acquire() + + def acquire_nowait(self) -> None: + """ + Acquire the lock, without blocking. + + :raises ~anyio.WouldBlock: if the operation would block + + """ + self._lock.acquire_nowait() + + def release(self) -> None: + """Release the lock.""" + self._lock.release() + + def locked(self) -> bool: + """Return True if the lock is currently held.""" + return self._lock.locked() + + def statistics(self) -> LockStatistics: + """ + Return statistics about the current state of this lock. + + .. versionadded:: 3.0 + + """ + if self._internal_lock is None: + return LockStatistics(False, None, 0) + + return self._internal_lock.statistics() + + +class Condition: + _owner_task: TaskInfo | None = None + + def __init__(self, lock: Lock | None = None): + self._lock = lock or Lock() + self._waiters: deque[Event] = deque() + + async def __aenter__(self) -> None: + await self.acquire() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.release() + + def _check_acquired(self) -> None: + if self._owner_task != get_current_task(): + raise RuntimeError("The current task is not holding the underlying lock") + + async def acquire(self) -> None: + """Acquire the underlying lock.""" + await self._lock.acquire() + self._owner_task = get_current_task() + + def acquire_nowait(self) -> None: + """ + Acquire the underlying lock, without blocking. + + :raises ~anyio.WouldBlock: if the operation would block + + """ + self._lock.acquire_nowait() + self._owner_task = get_current_task() + + def release(self) -> None: + """Release the underlying lock.""" + self._lock.release() + + def locked(self) -> bool: + """Return True if the lock is set.""" + return self._lock.locked() + + def notify(self, n: int = 1) -> None: + """Notify exactly n listeners.""" + self._check_acquired() + for _ in range(n): + try: + event = self._waiters.popleft() + except IndexError: + break + + event.set() + + def notify_all(self) -> None: + """Notify all the listeners.""" + self._check_acquired() + for event in self._waiters: + event.set() + + self._waiters.clear() + + async def wait(self) -> None: + """Wait for a notification.""" + await checkpoint_if_cancelled() + self._check_acquired() + event = Event() + self._waiters.append(event) + self.release() + try: + await event.wait() + except BaseException: + if not event.is_set(): + self._waiters.remove(event) + + raise + finally: + with CancelScope(shield=True): + await self.acquire() + + async def wait_for(self, predicate: Callable[[], T]) -> T: + """ + Wait until a predicate becomes true. + + :param predicate: a callable that returns a truthy value when the condition is + met + :return: the result of the predicate + + .. versionadded:: 4.11.0 + + """ + while not (result := predicate()): + await self.wait() + + return result + + def statistics(self) -> ConditionStatistics: + """ + Return statistics about the current state of this condition. + + .. versionadded:: 3.0 + """ + return ConditionStatistics(len(self._waiters), self._lock.statistics()) + + +class Semaphore: + def __new__( + cls, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> Semaphore: + try: + return get_async_backend().create_semaphore( + initial_value, max_value=max_value, fast_acquire=fast_acquire + ) + except NoEventLoopError: + return SemaphoreAdapter(initial_value, max_value=max_value) + + def __init__( + self, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ): + if not isinstance(initial_value, int): + raise TypeError("initial_value must be an integer") + if initial_value < 0: + raise ValueError("initial_value must be >= 0") + if max_value is not None: + if not isinstance(max_value, int): + raise TypeError("max_value must be an integer or None") + if max_value < initial_value: + raise ValueError( + "max_value must be equal to or higher than initial_value" + ) + + self._fast_acquire = fast_acquire + + async def __aenter__(self) -> Semaphore: + await self.acquire() + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.release() + + async def acquire(self) -> None: + """Decrement the semaphore value, blocking if necessary.""" + raise NotImplementedError + + def acquire_nowait(self) -> None: + """ + Acquire the underlying lock, without blocking. + + :raises ~anyio.WouldBlock: if the operation would block + + """ + raise NotImplementedError + + def release(self) -> None: + """Increment the semaphore value.""" + raise NotImplementedError + + @property + def value(self) -> int: + """The current value of the semaphore.""" + raise NotImplementedError + + @property + def max_value(self) -> int | None: + """The maximum value of the semaphore.""" + raise NotImplementedError + + def statistics(self) -> SemaphoreStatistics: + """ + Return statistics about the current state of this semaphore. + + .. versionadded:: 3.0 + """ + raise NotImplementedError + + +class SemaphoreAdapter(Semaphore): + _internal_semaphore: Semaphore | None = None + + def __new__( + cls, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> SemaphoreAdapter: + return object.__new__(cls) + + def __init__( + self, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> None: + super().__init__(initial_value, max_value=max_value, fast_acquire=fast_acquire) + self._initial_value = initial_value + self._max_value = max_value + + @property + def _semaphore(self) -> Semaphore: + if self._internal_semaphore is None: + self._internal_semaphore = get_async_backend().create_semaphore( + self._initial_value, max_value=self._max_value + ) + + return self._internal_semaphore + + async def acquire(self) -> None: + await self._semaphore.acquire() + + def acquire_nowait(self) -> None: + self._semaphore.acquire_nowait() + + def release(self) -> None: + self._semaphore.release() + + @property + def value(self) -> int: + if self._internal_semaphore is None: + return self._initial_value + + return self._semaphore.value + + @property + def max_value(self) -> int | None: + return self._max_value + + def statistics(self) -> SemaphoreStatistics: + if self._internal_semaphore is None: + return SemaphoreStatistics(tasks_waiting=0) + + return self._semaphore.statistics() + + +class CapacityLimiter: + def __new__(cls, total_tokens: float) -> CapacityLimiter: + try: + return get_async_backend().create_capacity_limiter(total_tokens) + except NoEventLoopError: + return CapacityLimiterAdapter(total_tokens) + + async def __aenter__(self) -> None: + raise NotImplementedError + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + raise NotImplementedError + + @property + def total_tokens(self) -> float: + """ + The total number of tokens available for borrowing. + + This is a read-write property. If the total number of tokens is increased, the + proportionate number of tasks waiting on this limiter will be granted their + tokens. + + .. versionchanged:: 3.0 + The property is now writable. + .. versionchanged:: 4.12 + The value can now be set to 0. + + """ + raise NotImplementedError + + @total_tokens.setter + def total_tokens(self, value: float) -> None: + raise NotImplementedError + + @property + def borrowed_tokens(self) -> int: + """The number of tokens that have currently been borrowed.""" + raise NotImplementedError + + @property + def available_tokens(self) -> float: + """The number of tokens currently available to be borrowed""" + raise NotImplementedError + + def acquire_nowait(self) -> None: + """ + Acquire a token for the current task without waiting for one to become + available. + + :raises ~anyio.WouldBlock: if there are no tokens available for borrowing + + """ + raise NotImplementedError + + def acquire_on_behalf_of_nowait(self, borrower: object) -> None: + """ + Acquire a token without waiting for one to become available. + + :param borrower: the entity borrowing a token + :raises ~anyio.WouldBlock: if there are no tokens available for borrowing + + """ + raise NotImplementedError + + async def acquire(self) -> None: + """ + Acquire a token for the current task, waiting if necessary for one to become + available. + + """ + raise NotImplementedError + + async def acquire_on_behalf_of(self, borrower: object) -> None: + """ + Acquire a token, waiting if necessary for one to become available. + + :param borrower: the entity borrowing a token + + """ + raise NotImplementedError + + def release(self) -> None: + """ + Release the token held by the current task. + + :raises RuntimeError: if the current task has not borrowed a token from this + limiter. + + """ + raise NotImplementedError + + def release_on_behalf_of(self, borrower: object) -> None: + """ + Release the token held by the given borrower. + + :raises RuntimeError: if the borrower has not borrowed a token from this + limiter. + + """ + raise NotImplementedError + + def statistics(self) -> CapacityLimiterStatistics: + """ + Return statistics about the current state of this limiter. + + .. versionadded:: 3.0 + + """ + raise NotImplementedError + + +class CapacityLimiterAdapter(CapacityLimiter): + _internal_limiter: CapacityLimiter | None = None + + def __new__(cls, total_tokens: float) -> CapacityLimiterAdapter: + return object.__new__(cls) + + def __init__(self, total_tokens: float) -> None: + self.total_tokens = total_tokens + + @property + def _limiter(self) -> CapacityLimiter: + if self._internal_limiter is None: + self._internal_limiter = get_async_backend().create_capacity_limiter( + self._total_tokens + ) + + return self._internal_limiter + + async def __aenter__(self) -> None: + await self._limiter.__aenter__() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + return await self._limiter.__aexit__(exc_type, exc_val, exc_tb) + + @property + def total_tokens(self) -> float: + if self._internal_limiter is None: + return self._total_tokens + + return self._internal_limiter.total_tokens + + @total_tokens.setter + def total_tokens(self, value: float) -> None: + if not isinstance(value, int) and value is not math.inf: + raise TypeError("total_tokens must be an int or math.inf") + elif value < 1: + raise ValueError("total_tokens must be >= 1") + + if self._internal_limiter is None: + self._total_tokens = value + return + + self._limiter.total_tokens = value + + @property + def borrowed_tokens(self) -> int: + if self._internal_limiter is None: + return 0 + + return self._internal_limiter.borrowed_tokens + + @property + def available_tokens(self) -> float: + if self._internal_limiter is None: + return self._total_tokens + + return self._internal_limiter.available_tokens + + def acquire_nowait(self) -> None: + self._limiter.acquire_nowait() + + def acquire_on_behalf_of_nowait(self, borrower: object) -> None: + self._limiter.acquire_on_behalf_of_nowait(borrower) + + async def acquire(self) -> None: + await self._limiter.acquire() + + async def acquire_on_behalf_of(self, borrower: object) -> None: + await self._limiter.acquire_on_behalf_of(borrower) + + def release(self) -> None: + self._limiter.release() + + def release_on_behalf_of(self, borrower: object) -> None: + self._limiter.release_on_behalf_of(borrower) + + def statistics(self) -> CapacityLimiterStatistics: + if self._internal_limiter is None: + return CapacityLimiterStatistics( + borrowed_tokens=0, + total_tokens=self.total_tokens, + borrowers=(), + tasks_waiting=0, + ) + + return self._internal_limiter.statistics() + + +class ResourceGuard: + """ + A context manager for ensuring that a resource is only used by a single task at a + time. + + Entering this context manager while the previous has not exited it yet will trigger + :exc:`BusyResourceError`. + + :param action: the action to guard against (visible in the :exc:`BusyResourceError` + when triggered, e.g. "Another task is already {action} this resource") + + .. versionadded:: 4.1 + """ + + __slots__ = "action", "_guarded" + + def __init__(self, action: str = "using"): + self.action: str = action + self._guarded = False + + def __enter__(self) -> None: + if self._guarded: + raise BusyResourceError(self.action) + + self._guarded = True + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self._guarded = False diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_tasks.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..0688bfe960cf9747373c93e482a64d1369befa11 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_tasks.py @@ -0,0 +1,173 @@ +from __future__ import annotations + +import math +from collections.abc import Generator +from contextlib import contextmanager +from types import TracebackType + +from ..abc._tasks import TaskGroup, TaskStatus +from ._eventloop import get_async_backend + + +class _IgnoredTaskStatus(TaskStatus[object]): + def started(self, value: object = None) -> None: + pass + + +TASK_STATUS_IGNORED = _IgnoredTaskStatus() + + +class CancelScope: + """ + Wraps a unit of work that can be made separately cancellable. + + :param deadline: The time (clock value) when this scope is cancelled automatically + :param shield: ``True`` to shield the cancel scope from external cancellation + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + """ + + def __new__( + cls, *, deadline: float = math.inf, shield: bool = False + ) -> CancelScope: + return get_async_backend().create_cancel_scope(shield=shield, deadline=deadline) + + def cancel(self, reason: str | None = None) -> None: + """ + Cancel this scope immediately. + + :param reason: a message describing the reason for the cancellation + + """ + raise NotImplementedError + + @property + def deadline(self) -> float: + """ + The time (clock value) when this scope is cancelled automatically. + + Will be ``float('inf')`` if no timeout has been set. + + """ + raise NotImplementedError + + @deadline.setter + def deadline(self, value: float) -> None: + raise NotImplementedError + + @property + def cancel_called(self) -> bool: + """``True`` if :meth:`cancel` has been called.""" + raise NotImplementedError + + @property + def cancelled_caught(self) -> bool: + """ + ``True`` if this scope suppressed a cancellation exception it itself raised. + + This is typically used to check if any work was interrupted, or to see if the + scope was cancelled due to its deadline being reached. The value will, however, + only be ``True`` if the cancellation was triggered by the scope itself (and not + an outer scope). + + """ + raise NotImplementedError + + @property + def shield(self) -> bool: + """ + ``True`` if this scope is shielded from external cancellation. + + While a scope is shielded, it will not receive cancellations from outside. + + """ + raise NotImplementedError + + @shield.setter + def shield(self, value: bool) -> None: + raise NotImplementedError + + def __enter__(self) -> CancelScope: + raise NotImplementedError + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + raise NotImplementedError + + +@contextmanager +def fail_after( + delay: float | None, shield: bool = False +) -> Generator[CancelScope, None, None]: + """ + Create a context manager which raises a :class:`TimeoutError` if does not finish in + time. + + :param delay: maximum allowed time (in seconds) before raising the exception, or + ``None`` to disable the timeout + :param shield: ``True`` to shield the cancel scope from external cancellation + :return: a context manager that yields a cancel scope + :rtype: :class:`~typing.ContextManager`\\[:class:`~anyio.CancelScope`\\] + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + current_time = get_async_backend().current_time + deadline = (current_time() + delay) if delay is not None else math.inf + with get_async_backend().create_cancel_scope( + deadline=deadline, shield=shield + ) as cancel_scope: + yield cancel_scope + + if cancel_scope.cancelled_caught and current_time() >= cancel_scope.deadline: + raise TimeoutError + + +def move_on_after(delay: float | None, shield: bool = False) -> CancelScope: + """ + Create a cancel scope with a deadline that expires after the given delay. + + :param delay: maximum allowed time (in seconds) before exiting the context block, or + ``None`` to disable the timeout + :param shield: ``True`` to shield the cancel scope from external cancellation + :return: a cancel scope + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + deadline = ( + (get_async_backend().current_time() + delay) if delay is not None else math.inf + ) + return get_async_backend().create_cancel_scope(deadline=deadline, shield=shield) + + +def current_effective_deadline() -> float: + """ + Return the nearest deadline among all the cancel scopes effective for the current + task. + + :return: a clock value from the event loop's internal clock (or ``float('inf')`` if + there is no deadline in effect, or ``float('-inf')`` if the current scope has + been cancelled) + :rtype: float + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + return get_async_backend().current_effective_deadline() + + +def create_task_group() -> TaskGroup: + """ + Create a task group. + + :return: a task group + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + return get_async_backend().create_task_group() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_tempfile.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_tempfile.py new file mode 100644 index 0000000000000000000000000000000000000000..fbb6b14a9a8eae9dcaa66eb68ac36d2084617877 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_tempfile.py @@ -0,0 +1,616 @@ +from __future__ import annotations + +import os +import sys +import tempfile +from collections.abc import Iterable +from io import BytesIO, TextIOWrapper +from types import TracebackType +from typing import ( + TYPE_CHECKING, + Any, + AnyStr, + Generic, + overload, +) + +from .. import to_thread +from .._core._fileio import AsyncFile +from ..lowlevel import checkpoint_if_cancelled + +if TYPE_CHECKING: + from _typeshed import OpenBinaryMode, OpenTextMode, ReadableBuffer, WriteableBuffer + + +class TemporaryFile(Generic[AnyStr]): + """ + An asynchronous temporary file that is automatically created and cleaned up. + + This class provides an asynchronous context manager interface to a temporary file. + The file is created using Python's standard `tempfile.TemporaryFile` function in a + background thread, and is wrapped as an asynchronous file using `AsyncFile`. + + :param mode: The mode in which the file is opened. Defaults to "w+b". + :param buffering: The buffering policy (-1 means the default buffering). + :param encoding: The encoding used to decode or encode the file. Only applicable in + text mode. + :param newline: Controls how universal newlines mode works (only applicable in text + mode). + :param suffix: The suffix for the temporary file name. + :param prefix: The prefix for the temporary file name. + :param dir: The directory in which the temporary file is created. + :param errors: The error handling scheme used for encoding/decoding errors. + """ + + _async_file: AsyncFile[AnyStr] + + @overload + def __init__( + self: TemporaryFile[bytes], + mode: OpenBinaryMode = ..., + buffering: int = ..., + encoding: str | None = ..., + newline: str | None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: str | None = ..., + *, + errors: str | None = ..., + ): ... + @overload + def __init__( + self: TemporaryFile[str], + mode: OpenTextMode, + buffering: int = ..., + encoding: str | None = ..., + newline: str | None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: str | None = ..., + *, + errors: str | None = ..., + ): ... + + def __init__( + self, + mode: OpenTextMode | OpenBinaryMode = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + *, + errors: str | None = None, + ) -> None: + self.mode = mode + self.buffering = buffering + self.encoding = encoding + self.newline = newline + self.suffix: str | None = suffix + self.prefix: str | None = prefix + self.dir: str | None = dir + self.errors = errors + + async def __aenter__(self) -> AsyncFile[AnyStr]: + fp = await to_thread.run_sync( + lambda: tempfile.TemporaryFile( + self.mode, + self.buffering, + self.encoding, + self.newline, + self.suffix, + self.prefix, + self.dir, + errors=self.errors, + ) + ) + self._async_file = AsyncFile(fp) + return self._async_file + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + await self._async_file.aclose() + + +class NamedTemporaryFile(Generic[AnyStr]): + """ + An asynchronous named temporary file that is automatically created and cleaned up. + + This class provides an asynchronous context manager for a temporary file with a + visible name in the file system. It uses Python's standard + :func:`~tempfile.NamedTemporaryFile` function and wraps the file object with + :class:`AsyncFile` for asynchronous operations. + + :param mode: The mode in which the file is opened. Defaults to "w+b". + :param buffering: The buffering policy (-1 means the default buffering). + :param encoding: The encoding used to decode or encode the file. Only applicable in + text mode. + :param newline: Controls how universal newlines mode works (only applicable in text + mode). + :param suffix: The suffix for the temporary file name. + :param prefix: The prefix for the temporary file name. + :param dir: The directory in which the temporary file is created. + :param delete: Whether to delete the file when it is closed. + :param errors: The error handling scheme used for encoding/decoding errors. + :param delete_on_close: (Python 3.12+) Whether to delete the file on close. + """ + + _async_file: AsyncFile[AnyStr] + + @overload + def __init__( + self: NamedTemporaryFile[bytes], + mode: OpenBinaryMode = ..., + buffering: int = ..., + encoding: str | None = ..., + newline: str | None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: str | None = ..., + delete: bool = ..., + *, + errors: str | None = ..., + delete_on_close: bool = ..., + ): ... + @overload + def __init__( + self: NamedTemporaryFile[str], + mode: OpenTextMode, + buffering: int = ..., + encoding: str | None = ..., + newline: str | None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: str | None = ..., + delete: bool = ..., + *, + errors: str | None = ..., + delete_on_close: bool = ..., + ): ... + + def __init__( + self, + mode: OpenBinaryMode | OpenTextMode = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + delete: bool = True, + *, + errors: str | None = None, + delete_on_close: bool = True, + ) -> None: + self._params: dict[str, Any] = { + "mode": mode, + "buffering": buffering, + "encoding": encoding, + "newline": newline, + "suffix": suffix, + "prefix": prefix, + "dir": dir, + "delete": delete, + "errors": errors, + } + if sys.version_info >= (3, 12): + self._params["delete_on_close"] = delete_on_close + + async def __aenter__(self) -> AsyncFile[AnyStr]: + fp = await to_thread.run_sync( + lambda: tempfile.NamedTemporaryFile(**self._params) + ) + self._async_file = AsyncFile(fp) + return self._async_file + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + await self._async_file.aclose() + + +class SpooledTemporaryFile(AsyncFile[AnyStr]): + """ + An asynchronous spooled temporary file that starts in memory and is spooled to disk. + + This class provides an asynchronous interface to a spooled temporary file, much like + Python's standard :class:`~tempfile.SpooledTemporaryFile`. It supports asynchronous + write operations and provides a method to force a rollover to disk. + + :param max_size: Maximum size in bytes before the file is rolled over to disk. + :param mode: The mode in which the file is opened. Defaults to "w+b". + :param buffering: The buffering policy (-1 means the default buffering). + :param encoding: The encoding used to decode or encode the file (text mode only). + :param newline: Controls how universal newlines mode works (text mode only). + :param suffix: The suffix for the temporary file name. + :param prefix: The prefix for the temporary file name. + :param dir: The directory in which the temporary file is created. + :param errors: The error handling scheme used for encoding/decoding errors. + """ + + _rolled: bool = False + + @overload + def __init__( + self: SpooledTemporaryFile[bytes], + max_size: int = ..., + mode: OpenBinaryMode = ..., + buffering: int = ..., + encoding: str | None = ..., + newline: str | None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: str | None = ..., + *, + errors: str | None = ..., + ): ... + @overload + def __init__( + self: SpooledTemporaryFile[str], + max_size: int = ..., + mode: OpenTextMode = ..., + buffering: int = ..., + encoding: str | None = ..., + newline: str | None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: str | None = ..., + *, + errors: str | None = ..., + ): ... + + def __init__( + self, + max_size: int = 0, + mode: OpenBinaryMode | OpenTextMode = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + *, + errors: str | None = None, + ) -> None: + self._tempfile_params: dict[str, Any] = { + "mode": mode, + "buffering": buffering, + "encoding": encoding, + "newline": newline, + "suffix": suffix, + "prefix": prefix, + "dir": dir, + "errors": errors, + } + self._max_size = max_size + if "b" in mode: + super().__init__(BytesIO()) # type: ignore[arg-type] + else: + super().__init__( + TextIOWrapper( # type: ignore[arg-type] + BytesIO(), + encoding=encoding, + errors=errors, + newline=newline, + write_through=True, + ) + ) + + async def aclose(self) -> None: + if not self._rolled: + self._fp.close() + return + + await super().aclose() + + async def _check(self) -> None: + if self._rolled or self._fp.tell() <= self._max_size: + return + + await self.rollover() + + async def rollover(self) -> None: + if self._rolled: + return + + self._rolled = True + buffer = self._fp + buffer.seek(0) + self._fp = await to_thread.run_sync( + lambda: tempfile.TemporaryFile(**self._tempfile_params) + ) + await self.write(buffer.read()) + buffer.close() + + @property + def closed(self) -> bool: + return self._fp.closed + + async def read(self, size: int = -1) -> AnyStr: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.read(size) + + return await super().read(size) # type: ignore[return-value] + + async def read1(self: SpooledTemporaryFile[bytes], size: int = -1) -> bytes: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.read1(size) + + return await super().read1(size) + + async def readline(self) -> AnyStr: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.readline() + + return await super().readline() # type: ignore[return-value] + + async def readlines(self) -> list[AnyStr]: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.readlines() + + return await super().readlines() # type: ignore[return-value] + + async def readinto(self: SpooledTemporaryFile[bytes], b: WriteableBuffer) -> int: + if not self._rolled: + await checkpoint_if_cancelled() + self._fp.readinto(b) + + return await super().readinto(b) + + async def readinto1(self: SpooledTemporaryFile[bytes], b: WriteableBuffer) -> int: + if not self._rolled: + await checkpoint_if_cancelled() + self._fp.readinto(b) + + return await super().readinto1(b) + + async def seek(self, offset: int, whence: int | None = os.SEEK_SET) -> int: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.seek(offset, whence) + + return await super().seek(offset, whence) + + async def tell(self) -> int: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.tell() + + return await super().tell() + + async def truncate(self, size: int | None = None) -> int: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.truncate(size) + + return await super().truncate(size) + + @overload + async def write(self: SpooledTemporaryFile[bytes], b: ReadableBuffer) -> int: ... + @overload + async def write(self: SpooledTemporaryFile[str], b: str) -> int: ... + + async def write(self, b: ReadableBuffer | str) -> int: + """ + Asynchronously write data to the spooled temporary file. + + If the file has not yet been rolled over, the data is written synchronously, + and a rollover is triggered if the size exceeds the maximum size. + + :param s: The data to write. + :return: The number of bytes written. + :raises RuntimeError: If the underlying file is not initialized. + + """ + if not self._rolled: + await checkpoint_if_cancelled() + result = self._fp.write(b) + await self._check() + return result + + return await super().write(b) # type: ignore[misc] + + @overload + async def writelines( + self: SpooledTemporaryFile[bytes], lines: Iterable[ReadableBuffer] + ) -> None: ... + @overload + async def writelines( + self: SpooledTemporaryFile[str], lines: Iterable[str] + ) -> None: ... + + async def writelines(self, lines: Iterable[str] | Iterable[ReadableBuffer]) -> None: + """ + Asynchronously write a list of lines to the spooled temporary file. + + If the file has not yet been rolled over, the lines are written synchronously, + and a rollover is triggered if the size exceeds the maximum size. + + :param lines: An iterable of lines to write. + :raises RuntimeError: If the underlying file is not initialized. + + """ + if not self._rolled: + await checkpoint_if_cancelled() + result = self._fp.writelines(lines) + await self._check() + return result + + return await super().writelines(lines) # type: ignore[misc] + + +class TemporaryDirectory(Generic[AnyStr]): + """ + An asynchronous temporary directory that is created and cleaned up automatically. + + This class provides an asynchronous context manager for creating a temporary + directory. It wraps Python's standard :class:`~tempfile.TemporaryDirectory` to + perform directory creation and cleanup operations in a background thread. + + :param suffix: Suffix to be added to the temporary directory name. + :param prefix: Prefix to be added to the temporary directory name. + :param dir: The parent directory where the temporary directory is created. + :param ignore_cleanup_errors: Whether to ignore errors during cleanup + (Python 3.10+). + :param delete: Whether to delete the directory upon closing (Python 3.12+). + """ + + def __init__( + self, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: AnyStr | None = None, + *, + ignore_cleanup_errors: bool = False, + delete: bool = True, + ) -> None: + self.suffix: AnyStr | None = suffix + self.prefix: AnyStr | None = prefix + self.dir: AnyStr | None = dir + self.ignore_cleanup_errors = ignore_cleanup_errors + self.delete = delete + + self._tempdir: tempfile.TemporaryDirectory | None = None + + async def __aenter__(self) -> str: + params: dict[str, Any] = { + "suffix": self.suffix, + "prefix": self.prefix, + "dir": self.dir, + } + if sys.version_info >= (3, 10): + params["ignore_cleanup_errors"] = self.ignore_cleanup_errors + + if sys.version_info >= (3, 12): + params["delete"] = self.delete + + self._tempdir = await to_thread.run_sync( + lambda: tempfile.TemporaryDirectory(**params) + ) + return await to_thread.run_sync(self._tempdir.__enter__) + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + if self._tempdir is not None: + await to_thread.run_sync( + self._tempdir.__exit__, exc_type, exc_value, traceback + ) + + async def cleanup(self) -> None: + if self._tempdir is not None: + await to_thread.run_sync(self._tempdir.cleanup) + + +@overload +async def mkstemp( + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + text: bool = False, +) -> tuple[int, str]: ... + + +@overload +async def mkstemp( + suffix: bytes | None = None, + prefix: bytes | None = None, + dir: bytes | None = None, + text: bool = False, +) -> tuple[int, bytes]: ... + + +async def mkstemp( + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: AnyStr | None = None, + text: bool = False, +) -> tuple[int, str | bytes]: + """ + Asynchronously create a temporary file and return an OS-level handle and the file + name. + + This function wraps `tempfile.mkstemp` and executes it in a background thread. + + :param suffix: Suffix to be added to the file name. + :param prefix: Prefix to be added to the file name. + :param dir: Directory in which the temporary file is created. + :param text: Whether the file is opened in text mode. + :return: A tuple containing the file descriptor and the file name. + + """ + return await to_thread.run_sync(tempfile.mkstemp, suffix, prefix, dir, text) + + +@overload +async def mkdtemp( + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, +) -> str: ... + + +@overload +async def mkdtemp( + suffix: bytes | None = None, + prefix: bytes | None = None, + dir: bytes | None = None, +) -> bytes: ... + + +async def mkdtemp( + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: AnyStr | None = None, +) -> str | bytes: + """ + Asynchronously create a temporary directory and return its path. + + This function wraps `tempfile.mkdtemp` and executes it in a background thread. + + :param suffix: Suffix to be added to the directory name. + :param prefix: Prefix to be added to the directory name. + :param dir: Parent directory where the temporary directory is created. + :return: The path of the created temporary directory. + + """ + return await to_thread.run_sync(tempfile.mkdtemp, suffix, prefix, dir) + + +async def gettempdir() -> str: + """ + Asynchronously return the name of the directory used for temporary files. + + This function wraps `tempfile.gettempdir` and executes it in a background thread. + + :return: The path of the temporary directory as a string. + + """ + return await to_thread.run_sync(tempfile.gettempdir) + + +async def gettempdirb() -> bytes: + """ + Asynchronously return the name of the directory used for temporary files in bytes. + + This function wraps `tempfile.gettempdirb` and executes it in a background thread. + + :return: The path of the temporary directory as bytes. + + """ + return await to_thread.run_sync(tempfile.gettempdirb) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_testing.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..369e65c068a426e99b7e8571209e80ce35b71f47 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_testing.py @@ -0,0 +1,82 @@ +from __future__ import annotations + +from collections.abc import Awaitable, Generator +from typing import Any, cast + +from ._eventloop import get_async_backend + + +class TaskInfo: + """ + Represents an asynchronous task. + + :ivar int id: the unique identifier of the task + :ivar parent_id: the identifier of the parent task, if any + :vartype parent_id: Optional[int] + :ivar str name: the description of the task (if any) + :ivar ~collections.abc.Coroutine coro: the coroutine object of the task + """ + + __slots__ = "_name", "id", "parent_id", "name", "coro" + + def __init__( + self, + id: int, + parent_id: int | None, + name: str | None, + coro: Generator[Any, Any, Any] | Awaitable[Any], + ): + func = get_current_task + self._name = f"{func.__module__}.{func.__qualname__}" + self.id: int = id + self.parent_id: int | None = parent_id + self.name: str | None = name + self.coro: Generator[Any, Any, Any] | Awaitable[Any] = coro + + def __eq__(self, other: object) -> bool: + if isinstance(other, TaskInfo): + return self.id == other.id + + return NotImplemented + + def __hash__(self) -> int: + return hash(self.id) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(id={self.id!r}, name={self.name!r})" + + def has_pending_cancellation(self) -> bool: + """ + Return ``True`` if the task has a cancellation pending, ``False`` otherwise. + + """ + return False + + +def get_current_task() -> TaskInfo: + """ + Return the current task. + + :return: a representation of the current task + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + return get_async_backend().get_current_task() + + +def get_running_tasks() -> list[TaskInfo]: + """ + Return a list of running tasks in the current event loop. + + :return: a list of task info objects + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + return cast("list[TaskInfo]", get_async_backend().get_running_tasks()) + + +async def wait_all_tasks_blocked() -> None: + """Wait until all other tasks are waiting for something.""" + await get_async_backend().wait_all_tasks_blocked() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_typedattr.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_typedattr.py new file mode 100644 index 0000000000000000000000000000000000000000..f358a448cb12739fd4eda4f4859d3a24ddd1de63 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/_core/_typedattr.py @@ -0,0 +1,81 @@ +from __future__ import annotations + +from collections.abc import Callable, Mapping +from typing import Any, TypeVar, final, overload + +from ._exceptions import TypedAttributeLookupError + +T_Attr = TypeVar("T_Attr") +T_Default = TypeVar("T_Default") +undefined = object() + + +def typed_attribute() -> Any: + """Return a unique object, used to mark typed attributes.""" + return object() + + +class TypedAttributeSet: + """ + Superclass for typed attribute collections. + + Checks that every public attribute of every subclass has a type annotation. + """ + + def __init_subclass__(cls) -> None: + annotations: dict[str, Any] = getattr(cls, "__annotations__", {}) + for attrname in dir(cls): + if not attrname.startswith("_") and attrname not in annotations: + raise TypeError( + f"Attribute {attrname!r} is missing its type annotation" + ) + + super().__init_subclass__() + + +class TypedAttributeProvider: + """Base class for classes that wish to provide typed extra attributes.""" + + @property + def extra_attributes(self) -> Mapping[T_Attr, Callable[[], T_Attr]]: + """ + A mapping of the extra attributes to callables that return the corresponding + values. + + If the provider wraps another provider, the attributes from that wrapper should + also be included in the returned mapping (but the wrapper may override the + callables from the wrapped instance). + + """ + return {} + + @overload + def extra(self, attribute: T_Attr) -> T_Attr: ... + + @overload + def extra(self, attribute: T_Attr, default: T_Default) -> T_Attr | T_Default: ... + + @final + def extra(self, attribute: Any, default: object = undefined) -> object: + """ + extra(attribute, default=undefined) + + Return the value of the given typed extra attribute. + + :param attribute: the attribute (member of a :class:`~TypedAttributeSet`) to + look for + :param default: the value that should be returned if no value is found for the + attribute + :raises ~anyio.TypedAttributeLookupError: if the search failed and no default + value was given + + """ + try: + getter = self.extra_attributes[attribute] + except KeyError: + if default is undefined: + raise TypedAttributeLookupError("Attribute not found") from None + else: + return default + + return getter() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/abc/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/abc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d560ce3f1fa45a7ee4a3bc8958aa59702caa9d0c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/abc/__init__.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +from ._eventloop import AsyncBackend as AsyncBackend +from ._resources import AsyncResource as AsyncResource +from ._sockets import ConnectedUDPSocket as ConnectedUDPSocket +from ._sockets import ConnectedUNIXDatagramSocket as ConnectedUNIXDatagramSocket +from ._sockets import IPAddressType as IPAddressType +from ._sockets import IPSockAddrType as IPSockAddrType +from ._sockets import SocketAttribute as SocketAttribute +from ._sockets import SocketListener as SocketListener +from ._sockets import SocketStream as SocketStream +from ._sockets import UDPPacketType as UDPPacketType +from ._sockets import UDPSocket as UDPSocket +from ._sockets import UNIXDatagramPacketType as UNIXDatagramPacketType +from ._sockets import UNIXDatagramSocket as UNIXDatagramSocket +from ._sockets import UNIXSocketStream as UNIXSocketStream +from ._streams import AnyByteReceiveStream as AnyByteReceiveStream +from ._streams import AnyByteSendStream as AnyByteSendStream +from ._streams import AnyByteStream as AnyByteStream +from ._streams import AnyByteStreamConnectable as AnyByteStreamConnectable +from ._streams import AnyUnreliableByteReceiveStream as AnyUnreliableByteReceiveStream +from ._streams import AnyUnreliableByteSendStream as AnyUnreliableByteSendStream +from ._streams import AnyUnreliableByteStream as AnyUnreliableByteStream +from ._streams import ByteReceiveStream as ByteReceiveStream +from ._streams import ByteSendStream as ByteSendStream +from ._streams import ByteStream as ByteStream +from ._streams import ByteStreamConnectable as ByteStreamConnectable +from ._streams import Listener as Listener +from ._streams import ObjectReceiveStream as ObjectReceiveStream +from ._streams import ObjectSendStream as ObjectSendStream +from ._streams import ObjectStream as ObjectStream +from ._streams import ObjectStreamConnectable as ObjectStreamConnectable +from ._streams import UnreliableObjectReceiveStream as UnreliableObjectReceiveStream +from ._streams import UnreliableObjectSendStream as UnreliableObjectSendStream +from ._streams import UnreliableObjectStream as UnreliableObjectStream +from ._subprocesses import Process as Process +from ._tasks import TaskGroup as TaskGroup +from ._tasks import TaskStatus as TaskStatus +from ._testing import TestRunner as TestRunner + +# Re-exported here, for backwards compatibility +# isort: off +from .._core._synchronization import ( + CapacityLimiter as CapacityLimiter, + Condition as Condition, + Event as Event, + Lock as Lock, + Semaphore as Semaphore, +) +from .._core._tasks import CancelScope as CancelScope +from ..from_thread import BlockingPortal as BlockingPortal + +# Re-export imports so they look like they live directly in this package +for __value in list(locals().values()): + if getattr(__value, "__module__", "").startswith("anyio.abc."): + __value.__module__ = __name__ + +del __value diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/abc/_eventloop.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/abc/_eventloop.py new file mode 100644 index 0000000000000000000000000000000000000000..b1bd085596d634939d9894c4725e5cb01726fcb3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/abc/_eventloop.py @@ -0,0 +1,414 @@ +from __future__ import annotations + +import math +import sys +from abc import ABCMeta, abstractmethod +from collections.abc import AsyncIterator, Awaitable, Callable, Sequence +from contextlib import AbstractContextManager +from os import PathLike +from signal import Signals +from socket import AddressFamily, SocketKind, socket +from typing import ( + IO, + TYPE_CHECKING, + Any, + TypeVar, + Union, + overload, +) + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +if sys.version_info >= (3, 10): + from typing import TypeAlias +else: + from typing_extensions import TypeAlias + +if TYPE_CHECKING: + from _typeshed import FileDescriptorLike + + from .._core._synchronization import CapacityLimiter, Event, Lock, Semaphore + from .._core._tasks import CancelScope + from .._core._testing import TaskInfo + from ._sockets import ( + ConnectedUDPSocket, + ConnectedUNIXDatagramSocket, + IPSockAddrType, + SocketListener, + SocketStream, + UDPSocket, + UNIXDatagramSocket, + UNIXSocketStream, + ) + from ._subprocesses import Process + from ._tasks import TaskGroup + from ._testing import TestRunner + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") +StrOrBytesPath: TypeAlias = Union[str, bytes, "PathLike[str]", "PathLike[bytes]"] + + +class AsyncBackend(metaclass=ABCMeta): + @classmethod + @abstractmethod + def run( + cls, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + args: tuple[Unpack[PosArgsT]], + kwargs: dict[str, Any], + options: dict[str, Any], + ) -> T_Retval: + """ + Run the given coroutine function in an asynchronous event loop. + + The current thread must not be already running an event loop. + + :param func: a coroutine function + :param args: positional arguments to ``func`` + :param kwargs: positional arguments to ``func`` + :param options: keyword arguments to call the backend ``run()`` implementation + with + :return: the return value of the coroutine function + """ + + @classmethod + @abstractmethod + def current_token(cls) -> object: + """ + Return an object that allows other threads to run code inside the event loop. + + :return: a token object, specific to the event loop running in the current + thread + """ + + @classmethod + @abstractmethod + def current_time(cls) -> float: + """ + Return the current value of the event loop's internal clock. + + :return: the clock value (seconds) + """ + + @classmethod + @abstractmethod + def cancelled_exception_class(cls) -> type[BaseException]: + """Return the exception class that is raised in a task if it's cancelled.""" + + @classmethod + @abstractmethod + async def checkpoint(cls) -> None: + """ + Check if the task has been cancelled, and allow rescheduling of other tasks. + + This is effectively the same as running :meth:`checkpoint_if_cancelled` and then + :meth:`cancel_shielded_checkpoint`. + """ + + @classmethod + async def checkpoint_if_cancelled(cls) -> None: + """ + Check if the current task group has been cancelled. + + This will check if the task has been cancelled, but will not allow other tasks + to be scheduled if not. + + """ + if cls.current_effective_deadline() == -math.inf: + await cls.checkpoint() + + @classmethod + async def cancel_shielded_checkpoint(cls) -> None: + """ + Allow the rescheduling of other tasks. + + This will give other tasks the opportunity to run, but without checking if the + current task group has been cancelled, unlike with :meth:`checkpoint`. + + """ + with cls.create_cancel_scope(shield=True): + await cls.sleep(0) + + @classmethod + @abstractmethod + async def sleep(cls, delay: float) -> None: + """ + Pause the current task for the specified duration. + + :param delay: the duration, in seconds + """ + + @classmethod + @abstractmethod + def create_cancel_scope( + cls, *, deadline: float = math.inf, shield: bool = False + ) -> CancelScope: + pass + + @classmethod + @abstractmethod + def current_effective_deadline(cls) -> float: + """ + Return the nearest deadline among all the cancel scopes effective for the + current task. + + :return: + - a clock value from the event loop's internal clock + - ``inf`` if there is no deadline in effect + - ``-inf`` if the current scope has been cancelled + :rtype: float + """ + + @classmethod + @abstractmethod + def create_task_group(cls) -> TaskGroup: + pass + + @classmethod + @abstractmethod + def create_event(cls) -> Event: + pass + + @classmethod + @abstractmethod + def create_lock(cls, *, fast_acquire: bool) -> Lock: + pass + + @classmethod + @abstractmethod + def create_semaphore( + cls, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> Semaphore: + pass + + @classmethod + @abstractmethod + def create_capacity_limiter(cls, total_tokens: float) -> CapacityLimiter: + pass + + @classmethod + @abstractmethod + async def run_sync_in_worker_thread( + cls, + func: Callable[[Unpack[PosArgsT]], T_Retval], + args: tuple[Unpack[PosArgsT]], + abandon_on_cancel: bool = False, + limiter: CapacityLimiter | None = None, + ) -> T_Retval: + pass + + @classmethod + @abstractmethod + def check_cancelled(cls) -> None: + pass + + @classmethod + @abstractmethod + def run_async_from_thread( + cls, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + args: tuple[Unpack[PosArgsT]], + token: object, + ) -> T_Retval: + pass + + @classmethod + @abstractmethod + def run_sync_from_thread( + cls, + func: Callable[[Unpack[PosArgsT]], T_Retval], + args: tuple[Unpack[PosArgsT]], + token: object, + ) -> T_Retval: + pass + + @classmethod + @abstractmethod + async def open_process( + cls, + command: StrOrBytesPath | Sequence[StrOrBytesPath], + *, + stdin: int | IO[Any] | None, + stdout: int | IO[Any] | None, + stderr: int | IO[Any] | None, + **kwargs: Any, + ) -> Process: + pass + + @classmethod + @abstractmethod + def setup_process_pool_exit_at_shutdown(cls, workers: set[Process]) -> None: + pass + + @classmethod + @abstractmethod + async def connect_tcp( + cls, host: str, port: int, local_address: IPSockAddrType | None = None + ) -> SocketStream: + pass + + @classmethod + @abstractmethod + async def connect_unix(cls, path: str | bytes) -> UNIXSocketStream: + pass + + @classmethod + @abstractmethod + def create_tcp_listener(cls, sock: socket) -> SocketListener: + pass + + @classmethod + @abstractmethod + def create_unix_listener(cls, sock: socket) -> SocketListener: + pass + + @classmethod + @abstractmethod + async def create_udp_socket( + cls, + family: AddressFamily, + local_address: IPSockAddrType | None, + remote_address: IPSockAddrType | None, + reuse_port: bool, + ) -> UDPSocket | ConnectedUDPSocket: + pass + + @classmethod + @overload + async def create_unix_datagram_socket( + cls, raw_socket: socket, remote_path: None + ) -> UNIXDatagramSocket: ... + + @classmethod + @overload + async def create_unix_datagram_socket( + cls, raw_socket: socket, remote_path: str | bytes + ) -> ConnectedUNIXDatagramSocket: ... + + @classmethod + @abstractmethod + async def create_unix_datagram_socket( + cls, raw_socket: socket, remote_path: str | bytes | None + ) -> UNIXDatagramSocket | ConnectedUNIXDatagramSocket: + pass + + @classmethod + @abstractmethod + async def getaddrinfo( + cls, + host: bytes | str | None, + port: str | int | None, + *, + family: int | AddressFamily = 0, + type: int | SocketKind = 0, + proto: int = 0, + flags: int = 0, + ) -> Sequence[ + tuple[ + AddressFamily, + SocketKind, + int, + str, + tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes], + ] + ]: + pass + + @classmethod + @abstractmethod + async def getnameinfo( + cls, sockaddr: IPSockAddrType, flags: int = 0 + ) -> tuple[str, str]: + pass + + @classmethod + @abstractmethod + async def wait_readable(cls, obj: FileDescriptorLike) -> None: + pass + + @classmethod + @abstractmethod + async def wait_writable(cls, obj: FileDescriptorLike) -> None: + pass + + @classmethod + @abstractmethod + def notify_closing(cls, obj: FileDescriptorLike) -> None: + pass + + @classmethod + @abstractmethod + async def wrap_listener_socket(cls, sock: socket) -> SocketListener: + pass + + @classmethod + @abstractmethod + async def wrap_stream_socket(cls, sock: socket) -> SocketStream: + pass + + @classmethod + @abstractmethod + async def wrap_unix_stream_socket(cls, sock: socket) -> UNIXSocketStream: + pass + + @classmethod + @abstractmethod + async def wrap_udp_socket(cls, sock: socket) -> UDPSocket: + pass + + @classmethod + @abstractmethod + async def wrap_connected_udp_socket(cls, sock: socket) -> ConnectedUDPSocket: + pass + + @classmethod + @abstractmethod + async def wrap_unix_datagram_socket(cls, sock: socket) -> UNIXDatagramSocket: + pass + + @classmethod + @abstractmethod + async def wrap_connected_unix_datagram_socket( + cls, sock: socket + ) -> ConnectedUNIXDatagramSocket: + pass + + @classmethod + @abstractmethod + def current_default_thread_limiter(cls) -> CapacityLimiter: + pass + + @classmethod + @abstractmethod + def open_signal_receiver( + cls, *signals: Signals + ) -> AbstractContextManager[AsyncIterator[Signals]]: + pass + + @classmethod + @abstractmethod + def get_current_task(cls) -> TaskInfo: + pass + + @classmethod + @abstractmethod + def get_running_tasks(cls) -> Sequence[TaskInfo]: + pass + + @classmethod + @abstractmethod + async def wait_all_tasks_blocked(cls) -> None: + pass + + @classmethod + @abstractmethod + def create_test_runner(cls, options: dict[str, Any]) -> TestRunner: + pass diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/abc/_resources.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/abc/_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..10df115a7b9f975493476da763cc1e26dbd822e5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/abc/_resources.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from abc import ABCMeta, abstractmethod +from types import TracebackType +from typing import TypeVar + +T = TypeVar("T") + + +class AsyncResource(metaclass=ABCMeta): + """ + Abstract base class for all closeable asynchronous resources. + + Works as an asynchronous context manager which returns the instance itself on enter, + and calls :meth:`aclose` on exit. + """ + + __slots__ = () + + async def __aenter__(self: T) -> T: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + await self.aclose() + + @abstractmethod + async def aclose(self) -> None: + """Close the resource.""" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/abc/_sockets.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/abc/_sockets.py new file mode 100644 index 0000000000000000000000000000000000000000..3ff60d4d9dfc3c15d416c9fc4a6b3b7f79a9fdb1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/abc/_sockets.py @@ -0,0 +1,405 @@ +from __future__ import annotations + +import errno +import socket +import sys +from abc import abstractmethod +from collections.abc import Callable, Collection, Mapping +from contextlib import AsyncExitStack +from io import IOBase +from ipaddress import IPv4Address, IPv6Address +from socket import AddressFamily +from typing import Any, TypeVar, Union + +from .._core._eventloop import get_async_backend +from .._core._typedattr import ( + TypedAttributeProvider, + TypedAttributeSet, + typed_attribute, +) +from ._streams import ByteStream, Listener, UnreliableObjectStream +from ._tasks import TaskGroup + +if sys.version_info >= (3, 10): + from typing import TypeAlias +else: + from typing_extensions import TypeAlias + +IPAddressType: TypeAlias = Union[str, IPv4Address, IPv6Address] +IPSockAddrType: TypeAlias = tuple[str, int] +SockAddrType: TypeAlias = Union[IPSockAddrType, str] +UDPPacketType: TypeAlias = tuple[bytes, IPSockAddrType] +UNIXDatagramPacketType: TypeAlias = tuple[bytes, str] +T_Retval = TypeVar("T_Retval") + + +def _validate_socket( + sock_or_fd: socket.socket | int, + sock_type: socket.SocketKind, + addr_family: socket.AddressFamily = socket.AF_UNSPEC, + *, + require_connected: bool = False, + require_bound: bool = False, +) -> socket.socket: + if isinstance(sock_or_fd, int): + try: + sock = socket.socket(fileno=sock_or_fd) + except OSError as exc: + if exc.errno == errno.ENOTSOCK: + raise ValueError( + "the file descriptor does not refer to a socket" + ) from exc + elif require_connected: + raise ValueError("the socket must be connected") from exc + elif require_bound: + raise ValueError("the socket must be bound to a local address") from exc + else: + raise + elif isinstance(sock_or_fd, socket.socket): + sock = sock_or_fd + else: + raise TypeError( + f"expected an int or socket, got {type(sock_or_fd).__qualname__} instead" + ) + + try: + if require_connected: + try: + sock.getpeername() + except OSError as exc: + raise ValueError("the socket must be connected") from exc + + if require_bound: + try: + if sock.family in (socket.AF_INET, socket.AF_INET6): + bound_addr = sock.getsockname()[1] + else: + bound_addr = sock.getsockname() + except OSError: + bound_addr = None + + if not bound_addr: + raise ValueError("the socket must be bound to a local address") + + if addr_family != socket.AF_UNSPEC and sock.family != addr_family: + raise ValueError( + f"address family mismatch: expected {addr_family.name}, got " + f"{sock.family.name}" + ) + + if sock.type != sock_type: + raise ValueError( + f"socket type mismatch: expected {sock_type.name}, got {sock.type.name}" + ) + except BaseException: + # Avoid ResourceWarning from the locally constructed socket object + if isinstance(sock_or_fd, int): + sock.detach() + + raise + + sock.setblocking(False) + return sock + + +class SocketAttribute(TypedAttributeSet): + """ + .. attribute:: family + :type: socket.AddressFamily + + the address family of the underlying socket + + .. attribute:: local_address + :type: tuple[str, int] | str + + the local address the underlying socket is connected to + + .. attribute:: local_port + :type: int + + for IP based sockets, the local port the underlying socket is bound to + + .. attribute:: raw_socket + :type: socket.socket + + the underlying stdlib socket object + + .. attribute:: remote_address + :type: tuple[str, int] | str + + the remote address the underlying socket is connected to + + .. attribute:: remote_port + :type: int + + for IP based sockets, the remote port the underlying socket is connected to + """ + + family: AddressFamily = typed_attribute() + local_address: SockAddrType = typed_attribute() + local_port: int = typed_attribute() + raw_socket: socket.socket = typed_attribute() + remote_address: SockAddrType = typed_attribute() + remote_port: int = typed_attribute() + + +class _SocketProvider(TypedAttributeProvider): + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + from .._core._sockets import convert_ipv6_sockaddr as convert + + attributes: dict[Any, Callable[[], Any]] = { + SocketAttribute.family: lambda: self._raw_socket.family, + SocketAttribute.local_address: lambda: convert( + self._raw_socket.getsockname() + ), + SocketAttribute.raw_socket: lambda: self._raw_socket, + } + try: + peername: tuple[str, int] | None = convert(self._raw_socket.getpeername()) + except OSError: + peername = None + + # Provide the remote address for connected sockets + if peername is not None: + attributes[SocketAttribute.remote_address] = lambda: peername + + # Provide local and remote ports for IP based sockets + if self._raw_socket.family in (AddressFamily.AF_INET, AddressFamily.AF_INET6): + attributes[SocketAttribute.local_port] = ( + lambda: self._raw_socket.getsockname()[1] + ) + if peername is not None: + remote_port = peername[1] + attributes[SocketAttribute.remote_port] = lambda: remote_port + + return attributes + + @property + @abstractmethod + def _raw_socket(self) -> socket.socket: + pass + + +class SocketStream(ByteStream, _SocketProvider): + """ + Transports bytes over a socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket(cls, sock_or_fd: socket.socket | int) -> SocketStream: + """ + Wrap an existing socket object or file descriptor as a socket stream. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must already be connected. + + :param sock_or_fd: a socket object or file descriptor + :return: a socket stream + + """ + sock = _validate_socket(sock_or_fd, socket.SOCK_STREAM, require_connected=True) + return await get_async_backend().wrap_stream_socket(sock) + + +class UNIXSocketStream(SocketStream): + @classmethod + async def from_socket(cls, sock_or_fd: socket.socket | int) -> UNIXSocketStream: + """ + Wrap an existing socket object or file descriptor as a UNIX socket stream. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must already be connected. + + :param sock_or_fd: a socket object or file descriptor + :return: a UNIX socket stream + + """ + sock = _validate_socket( + sock_or_fd, socket.SOCK_STREAM, socket.AF_UNIX, require_connected=True + ) + return await get_async_backend().wrap_unix_stream_socket(sock) + + @abstractmethod + async def send_fds(self, message: bytes, fds: Collection[int | IOBase]) -> None: + """ + Send file descriptors along with a message to the peer. + + :param message: a non-empty bytestring + :param fds: a collection of files (either numeric file descriptors or open file + or socket objects) + """ + + @abstractmethod + async def receive_fds(self, msglen: int, maxfds: int) -> tuple[bytes, list[int]]: + """ + Receive file descriptors along with a message from the peer. + + :param msglen: length of the message to expect from the peer + :param maxfds: maximum number of file descriptors to expect from the peer + :return: a tuple of (message, file descriptors) + """ + + +class SocketListener(Listener[SocketStream], _SocketProvider): + """ + Listens to incoming socket connections. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket( + cls, + sock_or_fd: socket.socket | int, + ) -> SocketListener: + """ + Wrap an existing socket object or file descriptor as a socket listener. + + The newly created listener takes ownership of the socket being passed in. + + :param sock_or_fd: a socket object or file descriptor + :return: a socket listener + + """ + sock = _validate_socket(sock_or_fd, socket.SOCK_STREAM, require_bound=True) + return await get_async_backend().wrap_listener_socket(sock) + + @abstractmethod + async def accept(self) -> SocketStream: + """Accept an incoming connection.""" + + async def serve( + self, + handler: Callable[[SocketStream], Any], + task_group: TaskGroup | None = None, + ) -> None: + from .. import create_task_group + + async with AsyncExitStack() as stack: + if task_group is None: + task_group = await stack.enter_async_context(create_task_group()) + + while True: + stream = await self.accept() + task_group.start_soon(handler, stream) + + +class UDPSocket(UnreliableObjectStream[UDPPacketType], _SocketProvider): + """ + Represents an unconnected UDP socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket(cls, sock_or_fd: socket.socket | int) -> UDPSocket: + """ + Wrap an existing socket object or file descriptor as a UDP socket. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must be bound to a local address. + + :param sock_or_fd: a socket object or file descriptor + :return: a UDP socket + + """ + sock = _validate_socket(sock_or_fd, socket.SOCK_DGRAM, require_bound=True) + return await get_async_backend().wrap_udp_socket(sock) + + async def sendto(self, data: bytes, host: str, port: int) -> None: + """ + Alias for :meth:`~.UnreliableObjectSendStream.send` ((data, (host, port))). + + """ + return await self.send((data, (host, port))) + + +class ConnectedUDPSocket(UnreliableObjectStream[bytes], _SocketProvider): + """ + Represents an connected UDP socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket(cls, sock_or_fd: socket.socket | int) -> ConnectedUDPSocket: + """ + Wrap an existing socket object or file descriptor as a connected UDP socket. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must already be connected. + + :param sock_or_fd: a socket object or file descriptor + :return: a connected UDP socket + + """ + sock = _validate_socket( + sock_or_fd, + socket.SOCK_DGRAM, + require_connected=True, + ) + return await get_async_backend().wrap_connected_udp_socket(sock) + + +class UNIXDatagramSocket( + UnreliableObjectStream[UNIXDatagramPacketType], _SocketProvider +): + """ + Represents an unconnected Unix datagram socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket( + cls, + sock_or_fd: socket.socket | int, + ) -> UNIXDatagramSocket: + """ + Wrap an existing socket object or file descriptor as a UNIX datagram + socket. + + The newly created socket wrapper takes ownership of the socket being passed in. + + :param sock_or_fd: a socket object or file descriptor + :return: a UNIX datagram socket + + """ + sock = _validate_socket(sock_or_fd, socket.SOCK_DGRAM, socket.AF_UNIX) + return await get_async_backend().wrap_unix_datagram_socket(sock) + + async def sendto(self, data: bytes, path: str) -> None: + """Alias for :meth:`~.UnreliableObjectSendStream.send` ((data, path)).""" + return await self.send((data, path)) + + +class ConnectedUNIXDatagramSocket(UnreliableObjectStream[bytes], _SocketProvider): + """ + Represents a connected Unix datagram socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket( + cls, + sock_or_fd: socket.socket | int, + ) -> ConnectedUNIXDatagramSocket: + """ + Wrap an existing socket object or file descriptor as a connected UNIX datagram + socket. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must already be connected. + + :param sock_or_fd: a socket object or file descriptor + :return: a connected UNIX datagram socket + + """ + sock = _validate_socket( + sock_or_fd, socket.SOCK_DGRAM, socket.AF_UNIX, require_connected=True + ) + return await get_async_backend().wrap_connected_unix_datagram_socket(sock) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/abc/_streams.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/abc/_streams.py new file mode 100644 index 0000000000000000000000000000000000000000..369df3f36cda74aa0d0893cd98bd4b29d3786faa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/abc/_streams.py @@ -0,0 +1,239 @@ +from __future__ import annotations + +import sys +from abc import ABCMeta, abstractmethod +from collections.abc import Callable +from typing import Any, Generic, TypeVar, Union + +from .._core._exceptions import EndOfStream +from .._core._typedattr import TypedAttributeProvider +from ._resources import AsyncResource +from ._tasks import TaskGroup + +if sys.version_info >= (3, 10): + from typing import TypeAlias +else: + from typing_extensions import TypeAlias + +T_Item = TypeVar("T_Item") +T_co = TypeVar("T_co", covariant=True) +T_contra = TypeVar("T_contra", contravariant=True) + + +class UnreliableObjectReceiveStream( + Generic[T_co], AsyncResource, TypedAttributeProvider +): + """ + An interface for receiving objects. + + This interface makes no guarantees that the received messages arrive in the order in + which they were sent, or that no messages are missed. + + Asynchronously iterating over objects of this type will yield objects matching the + given type parameter. + """ + + def __aiter__(self) -> UnreliableObjectReceiveStream[T_co]: + return self + + async def __anext__(self) -> T_co: + try: + return await self.receive() + except EndOfStream: + raise StopAsyncIteration from None + + @abstractmethod + async def receive(self) -> T_co: + """ + Receive the next item. + + :raises ~anyio.ClosedResourceError: if the receive stream has been explicitly + closed + :raises ~anyio.EndOfStream: if this stream has been closed from the other end + :raises ~anyio.BrokenResourceError: if this stream has been rendered unusable + due to external causes + """ + + +class UnreliableObjectSendStream( + Generic[T_contra], AsyncResource, TypedAttributeProvider +): + """ + An interface for sending objects. + + This interface makes no guarantees that the messages sent will reach the + recipient(s) in the same order in which they were sent, or at all. + """ + + @abstractmethod + async def send(self, item: T_contra) -> None: + """ + Send an item to the peer(s). + + :param item: the item to send + :raises ~anyio.ClosedResourceError: if the send stream has been explicitly + closed + :raises ~anyio.BrokenResourceError: if this stream has been rendered unusable + due to external causes + """ + + +class UnreliableObjectStream( + UnreliableObjectReceiveStream[T_Item], UnreliableObjectSendStream[T_Item] +): + """ + A bidirectional message stream which does not guarantee the order or reliability of + message delivery. + """ + + +class ObjectReceiveStream(UnreliableObjectReceiveStream[T_co]): + """ + A receive message stream which guarantees that messages are received in the same + order in which they were sent, and that no messages are missed. + """ + + +class ObjectSendStream(UnreliableObjectSendStream[T_contra]): + """ + A send message stream which guarantees that messages are delivered in the same order + in which they were sent, without missing any messages in the middle. + """ + + +class ObjectStream( + ObjectReceiveStream[T_Item], + ObjectSendStream[T_Item], + UnreliableObjectStream[T_Item], +): + """ + A bidirectional message stream which guarantees the order and reliability of message + delivery. + """ + + @abstractmethod + async def send_eof(self) -> None: + """ + Send an end-of-file indication to the peer. + + You should not try to send any further data to this stream after calling this + method. This method is idempotent (does nothing on successive calls). + """ + + +class ByteReceiveStream(AsyncResource, TypedAttributeProvider): + """ + An interface for receiving bytes from a single peer. + + Iterating this byte stream will yield a byte string of arbitrary length, but no more + than 65536 bytes. + """ + + def __aiter__(self) -> ByteReceiveStream: + return self + + async def __anext__(self) -> bytes: + try: + return await self.receive() + except EndOfStream: + raise StopAsyncIteration from None + + @abstractmethod + async def receive(self, max_bytes: int = 65536) -> bytes: + """ + Receive at most ``max_bytes`` bytes from the peer. + + .. note:: Implementers of this interface should not return an empty + :class:`bytes` object, and users should ignore them. + + :param max_bytes: maximum number of bytes to receive + :return: the received bytes + :raises ~anyio.EndOfStream: if this stream has been closed from the other end + """ + + +class ByteSendStream(AsyncResource, TypedAttributeProvider): + """An interface for sending bytes to a single peer.""" + + @abstractmethod + async def send(self, item: bytes) -> None: + """ + Send the given bytes to the peer. + + :param item: the bytes to send + """ + + +class ByteStream(ByteReceiveStream, ByteSendStream): + """A bidirectional byte stream.""" + + @abstractmethod + async def send_eof(self) -> None: + """ + Send an end-of-file indication to the peer. + + You should not try to send any further data to this stream after calling this + method. This method is idempotent (does nothing on successive calls). + """ + + +#: Type alias for all unreliable bytes-oriented receive streams. +AnyUnreliableByteReceiveStream: TypeAlias = Union[ + UnreliableObjectReceiveStream[bytes], ByteReceiveStream +] +#: Type alias for all unreliable bytes-oriented send streams. +AnyUnreliableByteSendStream: TypeAlias = Union[ + UnreliableObjectSendStream[bytes], ByteSendStream +] +#: Type alias for all unreliable bytes-oriented streams. +AnyUnreliableByteStream: TypeAlias = Union[UnreliableObjectStream[bytes], ByteStream] +#: Type alias for all bytes-oriented receive streams. +AnyByteReceiveStream: TypeAlias = Union[ObjectReceiveStream[bytes], ByteReceiveStream] +#: Type alias for all bytes-oriented send streams. +AnyByteSendStream: TypeAlias = Union[ObjectSendStream[bytes], ByteSendStream] +#: Type alias for all bytes-oriented streams. +AnyByteStream: TypeAlias = Union[ObjectStream[bytes], ByteStream] + + +class Listener(Generic[T_co], AsyncResource, TypedAttributeProvider): + """An interface for objects that let you accept incoming connections.""" + + @abstractmethod + async def serve( + self, handler: Callable[[T_co], Any], task_group: TaskGroup | None = None + ) -> None: + """ + Accept incoming connections as they come in and start tasks to handle them. + + :param handler: a callable that will be used to handle each accepted connection + :param task_group: the task group that will be used to start tasks for handling + each accepted connection (if omitted, an ad-hoc task group will be created) + """ + + +class ObjectStreamConnectable(Generic[T_co], metaclass=ABCMeta): + @abstractmethod + async def connect(self) -> ObjectStream[T_co]: + """ + Connect to the remote endpoint. + + :return: an object stream connected to the remote end + :raises ConnectionFailed: if the connection fails + """ + + +class ByteStreamConnectable(metaclass=ABCMeta): + @abstractmethod + async def connect(self) -> ByteStream: + """ + Connect to the remote endpoint. + + :return: a bytestream connected to the remote end + :raises ConnectionFailed: if the connection fails + """ + + +#: Type alias for all connectables returning bytestreams or bytes-oriented object streams +AnyByteStreamConnectable: TypeAlias = Union[ + ObjectStreamConnectable[bytes], ByteStreamConnectable +] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/abc/_subprocesses.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/abc/_subprocesses.py new file mode 100644 index 0000000000000000000000000000000000000000..ce0564ceac8aac425675b5c8f7f7205d08061fd3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/abc/_subprocesses.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +from abc import abstractmethod +from signal import Signals + +from ._resources import AsyncResource +from ._streams import ByteReceiveStream, ByteSendStream + + +class Process(AsyncResource): + """An asynchronous version of :class:`subprocess.Popen`.""" + + @abstractmethod + async def wait(self) -> int: + """ + Wait until the process exits. + + :return: the exit code of the process + """ + + @abstractmethod + def terminate(self) -> None: + """ + Terminates the process, gracefully if possible. + + On Windows, this calls ``TerminateProcess()``. + On POSIX systems, this sends ``SIGTERM`` to the process. + + .. seealso:: :meth:`subprocess.Popen.terminate` + """ + + @abstractmethod + def kill(self) -> None: + """ + Kills the process. + + On Windows, this calls ``TerminateProcess()``. + On POSIX systems, this sends ``SIGKILL`` to the process. + + .. seealso:: :meth:`subprocess.Popen.kill` + """ + + @abstractmethod + def send_signal(self, signal: Signals) -> None: + """ + Send a signal to the subprocess. + + .. seealso:: :meth:`subprocess.Popen.send_signal` + + :param signal: the signal number (e.g. :data:`signal.SIGHUP`) + """ + + @property + @abstractmethod + def pid(self) -> int: + """The process ID of the process.""" + + @property + @abstractmethod + def returncode(self) -> int | None: + """ + The return code of the process. If the process has not yet terminated, this will + be ``None``. + """ + + @property + @abstractmethod + def stdin(self) -> ByteSendStream | None: + """The stream for the standard input of the process.""" + + @property + @abstractmethod + def stdout(self) -> ByteReceiveStream | None: + """The stream for the standard output of the process.""" + + @property + @abstractmethod + def stderr(self) -> ByteReceiveStream | None: + """The stream for the standard error output of the process.""" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/abc/_tasks.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/abc/_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..516b3ec3b38a4b140f5d607dd28da989f057b832 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/abc/_tasks.py @@ -0,0 +1,117 @@ +from __future__ import annotations + +import sys +from abc import ABCMeta, abstractmethod +from collections.abc import Awaitable, Callable +from types import TracebackType +from typing import TYPE_CHECKING, Any, Protocol, overload + +if sys.version_info >= (3, 13): + from typing import TypeVar +else: + from typing_extensions import TypeVar + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +if TYPE_CHECKING: + from .._core._tasks import CancelScope + +T_Retval = TypeVar("T_Retval") +T_contra = TypeVar("T_contra", contravariant=True, default=None) +PosArgsT = TypeVarTuple("PosArgsT") + + +class TaskStatus(Protocol[T_contra]): + @overload + def started(self: TaskStatus[None]) -> None: ... + + @overload + def started(self, value: T_contra) -> None: ... + + def started(self, value: T_contra | None = None) -> None: + """ + Signal that the task has started. + + :param value: object passed back to the starter of the task + """ + + +class TaskGroup(metaclass=ABCMeta): + """ + Groups several asynchronous tasks together. + + :ivar cancel_scope: the cancel scope inherited by all child tasks + :vartype cancel_scope: CancelScope + + .. note:: On asyncio, support for eager task factories is considered to be + **experimental**. In particular, they don't follow the usual semantics of new + tasks being scheduled on the next iteration of the event loop, and may thus + cause unexpected behavior in code that wasn't written with such semantics in + mind. + """ + + cancel_scope: CancelScope + + @abstractmethod + def start_soon( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[Any]], + *args: Unpack[PosArgsT], + name: object = None, + ) -> None: + """ + Start a new task in this task group. + + :param func: a coroutine function + :param args: positional arguments to call the function with + :param name: name of the task, for the purposes of introspection and debugging + + .. versionadded:: 3.0 + """ + + @abstractmethod + async def start( + self, + func: Callable[..., Awaitable[Any]], + *args: object, + name: object = None, + ) -> Any: + """ + Start a new task and wait until it signals for readiness. + + The target callable must accept a keyword argument ``task_status`` (of type + :class:`TaskStatus`). Awaiting on this method will return whatever was passed to + ``task_status.started()`` (``None`` by default). + + .. note:: The :class:`TaskStatus` class is generic, and the type argument should + indicate the type of the value that will be passed to + ``task_status.started()``. + + :param func: a coroutine function that accepts the ``task_status`` keyword + argument + :param args: positional arguments to call the function with + :param name: an optional name for the task, for introspection and debugging + :return: the value passed to ``task_status.started()`` + :raises RuntimeError: if the task finishes without calling + ``task_status.started()`` + + .. seealso:: :ref:`start_initialize` + + .. versionadded:: 3.0 + """ + + @abstractmethod + async def __aenter__(self) -> TaskGroup: + """Enter the task group context and allow starting new tasks.""" + + @abstractmethod + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + """Exit the task group context waiting for all tasks to finish.""" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/abc/_testing.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/abc/_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..7c50ed76dc4d8df41262973a0122295523e2a935 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/abc/_testing.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +import types +from abc import ABCMeta, abstractmethod +from collections.abc import AsyncGenerator, Callable, Coroutine, Iterable +from typing import Any, TypeVar + +_T = TypeVar("_T") + + +class TestRunner(metaclass=ABCMeta): + """ + Encapsulates a running event loop. Every call made through this object will use the + same event loop. + """ + + def __enter__(self) -> TestRunner: + return self + + @abstractmethod + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: types.TracebackType | None, + ) -> bool | None: ... + + @abstractmethod + def run_asyncgen_fixture( + self, + fixture_func: Callable[..., AsyncGenerator[_T, Any]], + kwargs: dict[str, Any], + ) -> Iterable[_T]: + """ + Run an async generator fixture. + + :param fixture_func: the fixture function + :param kwargs: keyword arguments to call the fixture function with + :return: an iterator yielding the value yielded from the async generator + """ + + @abstractmethod + def run_fixture( + self, + fixture_func: Callable[..., Coroutine[Any, Any, _T]], + kwargs: dict[str, Any], + ) -> _T: + """ + Run an async fixture. + + :param fixture_func: the fixture function + :param kwargs: keyword arguments to call the fixture function with + :return: the return value of the fixture function + """ + + @abstractmethod + def run_test( + self, test_func: Callable[..., Coroutine[Any, Any, Any]], kwargs: dict[str, Any] + ) -> None: + """ + Run an async test function. + + :param test_func: the test function + :param kwargs: keyword arguments to call the test function with + """ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/from_thread.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/from_thread.py new file mode 100644 index 0000000000000000000000000000000000000000..837de5e96715b6ba324d156e9f4a2432a7ccf27d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/from_thread.py @@ -0,0 +1,578 @@ +from __future__ import annotations + +__all__ = ( + "BlockingPortal", + "BlockingPortalProvider", + "check_cancelled", + "run", + "run_sync", + "start_blocking_portal", +) + +import sys +from collections.abc import Awaitable, Callable, Generator +from concurrent.futures import Future +from contextlib import ( + AbstractAsyncContextManager, + AbstractContextManager, + contextmanager, +) +from dataclasses import dataclass, field +from functools import partial +from inspect import isawaitable +from threading import Lock, Thread, current_thread, get_ident +from types import TracebackType +from typing import ( + Any, + Generic, + TypeVar, + cast, + overload, +) + +from ._core._eventloop import ( + get_cancelled_exc_class, + threadlocals, +) +from ._core._eventloop import run as run_eventloop +from ._core._exceptions import NoEventLoopError +from ._core._synchronization import Event +from ._core._tasks import CancelScope, create_task_group +from .abc._tasks import TaskStatus +from .lowlevel import EventLoopToken, current_token + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +T_Retval = TypeVar("T_Retval") +T_co = TypeVar("T_co", covariant=True) +PosArgsT = TypeVarTuple("PosArgsT") + + +def _token_or_error(token: EventLoopToken | None) -> EventLoopToken: + if token is not None: + return token + + try: + return threadlocals.current_token + except AttributeError: + raise NoEventLoopError( + "Not running inside an AnyIO worker thread, and no event loop token was " + "provided" + ) from None + + +def run( + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + *args: Unpack[PosArgsT], + token: EventLoopToken | None = None, +) -> T_Retval: + """ + Call a coroutine function from a worker thread. + + :param func: a coroutine function + :param args: positional arguments for the callable + :param token: an event loop token to use to get back to the event loop thread + (required if calling this function from outside an AnyIO worker thread) + :return: the return value of the coroutine function + :raises MissingTokenError: if no token was provided and called from outside an + AnyIO worker thread + :raises RunFinishedError: if the event loop tied to ``token`` is no longer running + + .. versionchanged:: 4.11.0 + Added the ``token`` parameter. + + """ + explicit_token = token is not None + token = _token_or_error(token) + return token.backend_class.run_async_from_thread( + func, args, token=token.native_token if explicit_token else None + ) + + +def run_sync( + func: Callable[[Unpack[PosArgsT]], T_Retval], + *args: Unpack[PosArgsT], + token: EventLoopToken | None = None, +) -> T_Retval: + """ + Call a function in the event loop thread from a worker thread. + + :param func: a callable + :param args: positional arguments for the callable + :param token: an event loop token to use to get back to the event loop thread + (required if calling this function from outside an AnyIO worker thread) + :return: the return value of the callable + :raises MissingTokenError: if no token was provided and called from outside an + AnyIO worker thread + :raises RunFinishedError: if the event loop tied to ``token`` is no longer running + + .. versionchanged:: 4.11.0 + Added the ``token`` parameter. + + """ + explicit_token = token is not None + token = _token_or_error(token) + return token.backend_class.run_sync_from_thread( + func, args, token=token.native_token if explicit_token else None + ) + + +class _BlockingAsyncContextManager(Generic[T_co], AbstractContextManager): + _enter_future: Future[T_co] + _exit_future: Future[bool | None] + _exit_event: Event + _exit_exc_info: tuple[ + type[BaseException] | None, BaseException | None, TracebackType | None + ] = (None, None, None) + + def __init__( + self, async_cm: AbstractAsyncContextManager[T_co], portal: BlockingPortal + ): + self._async_cm = async_cm + self._portal = portal + + async def run_async_cm(self) -> bool | None: + try: + self._exit_event = Event() + value = await self._async_cm.__aenter__() + except BaseException as exc: + self._enter_future.set_exception(exc) + raise + else: + self._enter_future.set_result(value) + + try: + # Wait for the sync context manager to exit. + # This next statement can raise `get_cancelled_exc_class()` if + # something went wrong in a task group in this async context + # manager. + await self._exit_event.wait() + finally: + # In case of cancellation, it could be that we end up here before + # `_BlockingAsyncContextManager.__exit__` is called, and an + # `_exit_exc_info` has been set. + result = await self._async_cm.__aexit__(*self._exit_exc_info) + + return result + + def __enter__(self) -> T_co: + self._enter_future = Future() + self._exit_future = self._portal.start_task_soon(self.run_async_cm) + return self._enter_future.result() + + def __exit__( + self, + __exc_type: type[BaseException] | None, + __exc_value: BaseException | None, + __traceback: TracebackType | None, + ) -> bool | None: + self._exit_exc_info = __exc_type, __exc_value, __traceback + self._portal.call(self._exit_event.set) + return self._exit_future.result() + + +class _BlockingPortalTaskStatus(TaskStatus): + def __init__(self, future: Future): + self._future = future + + def started(self, value: object = None) -> None: + self._future.set_result(value) + + +class BlockingPortal: + """ + An object that lets external threads run code in an asynchronous event loop. + + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + """ + + def __init__(self) -> None: + self._token = current_token() + self._event_loop_thread_id: int | None = get_ident() + self._stop_event = Event() + self._task_group = create_task_group() + + async def __aenter__(self) -> BlockingPortal: + await self._task_group.__aenter__() + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + await self.stop() + return await self._task_group.__aexit__(exc_type, exc_val, exc_tb) + + def _check_running(self) -> None: + if self._event_loop_thread_id is None: + raise RuntimeError("This portal is not running") + if self._event_loop_thread_id == get_ident(): + raise RuntimeError( + "This method cannot be called from the event loop thread" + ) + + async def sleep_until_stopped(self) -> None: + """Sleep until :meth:`stop` is called.""" + await self._stop_event.wait() + + async def stop(self, cancel_remaining: bool = False) -> None: + """ + Signal the portal to shut down. + + This marks the portal as no longer accepting new calls and exits from + :meth:`sleep_until_stopped`. + + :param cancel_remaining: ``True`` to cancel all the remaining tasks, ``False`` + to let them finish before returning + + """ + self._event_loop_thread_id = None + self._stop_event.set() + if cancel_remaining: + self._task_group.cancel_scope.cancel("the blocking portal is shutting down") + + async def _call_func( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval], + args: tuple[Unpack[PosArgsT]], + kwargs: dict[str, Any], + future: Future[T_Retval], + ) -> None: + def callback(f: Future[T_Retval]) -> None: + if f.cancelled(): + if self._event_loop_thread_id == get_ident(): + scope.cancel("the future was cancelled") + elif self._event_loop_thread_id is not None: + self.call(scope.cancel, "the future was cancelled") + + try: + retval_or_awaitable = func(*args, **kwargs) + if isawaitable(retval_or_awaitable): + with CancelScope() as scope: + future.add_done_callback(callback) + retval = await retval_or_awaitable + else: + retval = retval_or_awaitable + except get_cancelled_exc_class(): + future.cancel() + future.set_running_or_notify_cancel() + except BaseException as exc: + if not future.cancelled(): + future.set_exception(exc) + + # Let base exceptions fall through + if not isinstance(exc, Exception): + raise + else: + if not future.cancelled(): + future.set_result(retval) + finally: + scope = None # type: ignore[assignment] + + def _spawn_task_from_thread( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval], + args: tuple[Unpack[PosArgsT]], + kwargs: dict[str, Any], + name: object, + future: Future[T_Retval], + ) -> None: + """ + Spawn a new task using the given callable. + + :param func: a callable + :param args: positional arguments to be passed to the callable + :param kwargs: keyword arguments to be passed to the callable + :param name: name of the task (will be coerced to a string if not ``None``) + :param future: a future that will resolve to the return value of the callable, + or the exception raised during its execution + + """ + run_sync( + partial(self._task_group.start_soon, name=name), + self._call_func, + func, + args, + kwargs, + future, + token=self._token, + ) + + @overload + def call( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + *args: Unpack[PosArgsT], + ) -> T_Retval: ... + + @overload + def call( + self, func: Callable[[Unpack[PosArgsT]], T_Retval], *args: Unpack[PosArgsT] + ) -> T_Retval: ... + + def call( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval], + *args: Unpack[PosArgsT], + ) -> T_Retval: + """ + Call the given function in the event loop thread. + + If the callable returns a coroutine object, it is awaited on. + + :param func: any callable + :raises RuntimeError: if the portal is not running or if this method is called + from within the event loop thread + + """ + return cast(T_Retval, self.start_task_soon(func, *args).result()) + + @overload + def start_task_soon( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + *args: Unpack[PosArgsT], + name: object = None, + ) -> Future[T_Retval]: ... + + @overload + def start_task_soon( + self, + func: Callable[[Unpack[PosArgsT]], T_Retval], + *args: Unpack[PosArgsT], + name: object = None, + ) -> Future[T_Retval]: ... + + def start_task_soon( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval], + *args: Unpack[PosArgsT], + name: object = None, + ) -> Future[T_Retval]: + """ + Start a task in the portal's task group. + + The task will be run inside a cancel scope which can be cancelled by cancelling + the returned future. + + :param func: the target function + :param args: positional arguments passed to ``func`` + :param name: name of the task (will be coerced to a string if not ``None``) + :return: a future that resolves with the return value of the callable if the + task completes successfully, or with the exception raised in the task + :raises RuntimeError: if the portal is not running or if this method is called + from within the event loop thread + :rtype: concurrent.futures.Future[T_Retval] + + .. versionadded:: 3.0 + + """ + self._check_running() + f: Future[T_Retval] = Future() + self._spawn_task_from_thread(func, args, {}, name, f) + return f + + def start_task( + self, + func: Callable[..., Awaitable[T_Retval]], + *args: object, + name: object = None, + ) -> tuple[Future[T_Retval], Any]: + """ + Start a task in the portal's task group and wait until it signals for readiness. + + This method works the same way as :meth:`.abc.TaskGroup.start`. + + :param func: the target function + :param args: positional arguments passed to ``func`` + :param name: name of the task (will be coerced to a string if not ``None``) + :return: a tuple of (future, task_status_value) where the ``task_status_value`` + is the value passed to ``task_status.started()`` from within the target + function + :rtype: tuple[concurrent.futures.Future[T_Retval], Any] + + .. versionadded:: 3.0 + + """ + + def task_done(future: Future[T_Retval]) -> None: + if not task_status_future.done(): + if future.cancelled(): + task_status_future.cancel() + elif future.exception(): + task_status_future.set_exception(future.exception()) + else: + exc = RuntimeError( + "Task exited without calling task_status.started()" + ) + task_status_future.set_exception(exc) + + self._check_running() + task_status_future: Future = Future() + task_status = _BlockingPortalTaskStatus(task_status_future) + f: Future = Future() + f.add_done_callback(task_done) + self._spawn_task_from_thread(func, args, {"task_status": task_status}, name, f) + return f, task_status_future.result() + + def wrap_async_context_manager( + self, cm: AbstractAsyncContextManager[T_co] + ) -> AbstractContextManager[T_co]: + """ + Wrap an async context manager as a synchronous context manager via this portal. + + Spawns a task that will call both ``__aenter__()`` and ``__aexit__()``, stopping + in the middle until the synchronous context manager exits. + + :param cm: an asynchronous context manager + :return: a synchronous context manager + + .. versionadded:: 2.1 + + """ + return _BlockingAsyncContextManager(cm, self) + + +@dataclass +class BlockingPortalProvider: + """ + A manager for a blocking portal. Used as a context manager. The first thread to + enter this context manager causes a blocking portal to be started with the specific + parameters, and the last thread to exit causes the portal to be shut down. Thus, + there will be exactly one blocking portal running in this context as long as at + least one thread has entered this context manager. + + The parameters are the same as for :func:`~anyio.run`. + + :param backend: name of the backend + :param backend_options: backend options + + .. versionadded:: 4.4 + """ + + backend: str = "asyncio" + backend_options: dict[str, Any] | None = None + _lock: Lock = field(init=False, default_factory=Lock) + _leases: int = field(init=False, default=0) + _portal: BlockingPortal = field(init=False) + _portal_cm: AbstractContextManager[BlockingPortal] | None = field( + init=False, default=None + ) + + def __enter__(self) -> BlockingPortal: + with self._lock: + if self._portal_cm is None: + self._portal_cm = start_blocking_portal( + self.backend, self.backend_options + ) + self._portal = self._portal_cm.__enter__() + + self._leases += 1 + return self._portal + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + portal_cm: AbstractContextManager[BlockingPortal] | None = None + with self._lock: + assert self._portal_cm + assert self._leases > 0 + self._leases -= 1 + if not self._leases: + portal_cm = self._portal_cm + self._portal_cm = None + del self._portal + + if portal_cm: + portal_cm.__exit__(None, None, None) + + +@contextmanager +def start_blocking_portal( + backend: str = "asyncio", + backend_options: dict[str, Any] | None = None, + *, + name: str | None = None, +) -> Generator[BlockingPortal, Any, None]: + """ + Start a new event loop in a new thread and run a blocking portal in its main task. + + The parameters are the same as for :func:`~anyio.run`. + + :param backend: name of the backend + :param backend_options: backend options + :param name: name of the thread + :return: a context manager that yields a blocking portal + + .. versionchanged:: 3.0 + Usage as a context manager is now required. + + """ + + async def run_portal() -> None: + async with BlockingPortal() as portal_: + if name is None: + current_thread().name = f"{backend}-portal-{id(portal_):x}" + + future.set_result(portal_) + await portal_.sleep_until_stopped() + + def run_blocking_portal() -> None: + if future.set_running_or_notify_cancel(): + try: + run_eventloop( + run_portal, backend=backend, backend_options=backend_options + ) + except BaseException as exc: + if not future.done(): + future.set_exception(exc) + + future: Future[BlockingPortal] = Future() + thread = Thread(target=run_blocking_portal, daemon=True, name=name) + thread.start() + try: + cancel_remaining_tasks = False + portal = future.result() + try: + yield portal + except BaseException: + cancel_remaining_tasks = True + raise + finally: + try: + portal.call(portal.stop, cancel_remaining_tasks) + except RuntimeError: + pass + finally: + thread.join() + + +def check_cancelled() -> None: + """ + Check if the cancel scope of the host task's running the current worker thread has + been cancelled. + + If the host task's current cancel scope has indeed been cancelled, the + backend-specific cancellation exception will be raised. + + :raises RuntimeError: if the current thread was not spawned by + :func:`.to_thread.run_sync` + + """ + try: + token: EventLoopToken = threadlocals.current_token + except AttributeError: + raise NoEventLoopError( + "This function can only be called inside an AnyIO worker thread" + ) from None + + token.backend_class.check_cancelled() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/functools.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/functools.py new file mode 100644 index 0000000000000000000000000000000000000000..b80afe6c81e5138c9ba439cd1b7d633eac154b21 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/functools.py @@ -0,0 +1,375 @@ +from __future__ import annotations + +__all__ = ( + "AsyncCacheInfo", + "AsyncCacheParameters", + "AsyncLRUCacheWrapper", + "cache", + "lru_cache", + "reduce", +) + +import functools +import sys +from collections import OrderedDict +from collections.abc import ( + AsyncIterable, + Awaitable, + Callable, + Coroutine, + Hashable, + Iterable, +) +from functools import update_wrapper +from inspect import iscoroutinefunction +from typing import ( + Any, + Generic, + NamedTuple, + TypedDict, + TypeVar, + cast, + final, + overload, +) +from weakref import WeakKeyDictionary + +from ._core._synchronization import Lock +from .lowlevel import RunVar, checkpoint + +if sys.version_info >= (3, 11): + from typing import ParamSpec +else: + from typing_extensions import ParamSpec + +T = TypeVar("T") +S = TypeVar("S") +P = ParamSpec("P") +lru_cache_items: RunVar[ + WeakKeyDictionary[ + AsyncLRUCacheWrapper[Any, Any], + OrderedDict[Hashable, tuple[_InitialMissingType, Lock] | tuple[Any, None]], + ] +] = RunVar("lru_cache_items") + + +class _InitialMissingType: + pass + + +initial_missing: _InitialMissingType = _InitialMissingType() + + +class AsyncCacheInfo(NamedTuple): + hits: int + misses: int + maxsize: int | None + currsize: int + + +class AsyncCacheParameters(TypedDict): + maxsize: int | None + typed: bool + always_checkpoint: bool + + +class _LRUMethodWrapper(Generic[T]): + def __init__(self, wrapper: AsyncLRUCacheWrapper[..., T], instance: object): + self.__wrapper = wrapper + self.__instance = instance + + def cache_info(self) -> AsyncCacheInfo: + return self.__wrapper.cache_info() + + def cache_parameters(self) -> AsyncCacheParameters: + return self.__wrapper.cache_parameters() + + def cache_clear(self) -> None: + self.__wrapper.cache_clear() + + async def __call__(self, *args: Any, **kwargs: Any) -> T: + if self.__instance is None: + return await self.__wrapper(*args, **kwargs) + + return await self.__wrapper(self.__instance, *args, **kwargs) + + +@final +class AsyncLRUCacheWrapper(Generic[P, T]): + def __init__( + self, + func: Callable[P, Awaitable[T]], + maxsize: int | None, + typed: bool, + always_checkpoint: bool, + ): + self.__wrapped__ = func + self._hits: int = 0 + self._misses: int = 0 + self._maxsize = max(maxsize, 0) if maxsize is not None else None + self._currsize: int = 0 + self._typed = typed + self._always_checkpoint = always_checkpoint + update_wrapper(self, func) + + def cache_info(self) -> AsyncCacheInfo: + return AsyncCacheInfo(self._hits, self._misses, self._maxsize, self._currsize) + + def cache_parameters(self) -> AsyncCacheParameters: + return { + "maxsize": self._maxsize, + "typed": self._typed, + "always_checkpoint": self._always_checkpoint, + } + + def cache_clear(self) -> None: + if cache := lru_cache_items.get(None): + cache.pop(self, None) + self._hits = self._misses = self._currsize = 0 + + async def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T: + # Easy case first: if maxsize == 0, no caching is done + if self._maxsize == 0: + value = await self.__wrapped__(*args, **kwargs) + self._misses += 1 + return value + + # The key is constructed as a flat tuple to avoid memory overhead + key: tuple[Any, ...] = args + if kwargs: + # initial_missing is used as a separator + key += (initial_missing,) + sum(kwargs.items(), ()) + + if self._typed: + key += tuple(type(arg) for arg in args) + if kwargs: + key += (initial_missing,) + tuple(type(val) for val in kwargs.values()) + + try: + cache = lru_cache_items.get() + except LookupError: + cache = WeakKeyDictionary() + lru_cache_items.set(cache) + + try: + cache_entry = cache[self] + except KeyError: + cache_entry = cache[self] = OrderedDict() + + cached_value: T | _InitialMissingType + try: + cached_value, lock = cache_entry[key] + except KeyError: + # We're the first task to call this function + cached_value, lock = ( + initial_missing, + Lock(fast_acquire=not self._always_checkpoint), + ) + cache_entry[key] = cached_value, lock + + if lock is None: + # The value was already cached + self._hits += 1 + cache_entry.move_to_end(key) + if self._always_checkpoint: + await checkpoint() + + return cast(T, cached_value) + + async with lock: + # Check if another task filled the cache while we acquired the lock + if (cached_value := cache_entry[key][0]) is initial_missing: + self._misses += 1 + if self._maxsize is not None and self._currsize >= self._maxsize: + cache_entry.popitem(last=False) + else: + self._currsize += 1 + + value = await self.__wrapped__(*args, **kwargs) + cache_entry[key] = value, None + else: + # Another task filled the cache while we were waiting for the lock + self._hits += 1 + cache_entry.move_to_end(key) + value = cast(T, cached_value) + + return value + + def __get__( + self, instance: object, owner: type | None = None + ) -> _LRUMethodWrapper[T]: + wrapper = _LRUMethodWrapper(self, instance) + update_wrapper(wrapper, self.__wrapped__) + return wrapper + + +class _LRUCacheWrapper(Generic[T]): + def __init__(self, maxsize: int | None, typed: bool, always_checkpoint: bool): + self._maxsize = maxsize + self._typed = typed + self._always_checkpoint = always_checkpoint + + @overload + def __call__( # type: ignore[overload-overlap] + self, func: Callable[P, Coroutine[Any, Any, T]], / + ) -> AsyncLRUCacheWrapper[P, T]: ... + + @overload + def __call__( + self, func: Callable[..., T], / + ) -> functools._lru_cache_wrapper[T]: ... + + def __call__( + self, f: Callable[P, Coroutine[Any, Any, T]] | Callable[..., T], / + ) -> AsyncLRUCacheWrapper[P, T] | functools._lru_cache_wrapper[T]: + if iscoroutinefunction(f): + return AsyncLRUCacheWrapper( + f, self._maxsize, self._typed, self._always_checkpoint + ) + + return functools.lru_cache(maxsize=self._maxsize, typed=self._typed)(f) # type: ignore[arg-type] + + +@overload +def cache( # type: ignore[overload-overlap] + func: Callable[P, Coroutine[Any, Any, T]], / +) -> AsyncLRUCacheWrapper[P, T]: ... + + +@overload +def cache(func: Callable[..., T], /) -> functools._lru_cache_wrapper[T]: ... + + +def cache( + func: Callable[..., T] | Callable[P, Coroutine[Any, Any, T]], / +) -> AsyncLRUCacheWrapper[P, T] | functools._lru_cache_wrapper[T]: + """ + A convenient shortcut for :func:`lru_cache` with ``maxsize=None``. + + This is the asynchronous equivalent to :func:`functools.cache`. + + """ + return lru_cache(maxsize=None)(func) + + +@overload +def lru_cache( + *, maxsize: int | None = ..., typed: bool = ..., always_checkpoint: bool = ... +) -> _LRUCacheWrapper[Any]: ... + + +@overload +def lru_cache( # type: ignore[overload-overlap] + func: Callable[P, Coroutine[Any, Any, T]], / +) -> AsyncLRUCacheWrapper[P, T]: ... + + +@overload +def lru_cache(func: Callable[..., T], /) -> functools._lru_cache_wrapper[T]: ... + + +def lru_cache( + func: Callable[P, Coroutine[Any, Any, T]] | Callable[..., T] | None = None, + /, + *, + maxsize: int | None = 128, + typed: bool = False, + always_checkpoint: bool = False, +) -> ( + AsyncLRUCacheWrapper[P, T] | functools._lru_cache_wrapper[T] | _LRUCacheWrapper[Any] +): + """ + An asynchronous version of :func:`functools.lru_cache`. + + If a synchronous function is passed, the standard library + :func:`functools.lru_cache` is applied instead. + + :param always_checkpoint: if ``True``, every call to the cached function will be + guaranteed to yield control to the event loop at least once + + .. note:: Caches and locks are managed on a per-event loop basis. + + """ + if func is None: + return _LRUCacheWrapper[Any](maxsize, typed, always_checkpoint) + + if not callable(func): + raise TypeError("the first argument must be callable") + + return _LRUCacheWrapper[T](maxsize, typed, always_checkpoint)(func) + + +@overload +async def reduce( + function: Callable[[T, S], Awaitable[T]], + iterable: Iterable[S] | AsyncIterable[S], + /, + initial: T, +) -> T: ... + + +@overload +async def reduce( + function: Callable[[T, T], Awaitable[T]], + iterable: Iterable[T] | AsyncIterable[T], + /, +) -> T: ... + + +async def reduce( # type: ignore[misc] + function: Callable[[T, T], Awaitable[T]] | Callable[[T, S], Awaitable[T]], + iterable: Iterable[T] | Iterable[S] | AsyncIterable[T] | AsyncIterable[S], + /, + initial: T | _InitialMissingType = initial_missing, +) -> T: + """ + Asynchronous version of :func:`functools.reduce`. + + :param function: a coroutine function that takes two arguments: the accumulated + value and the next element from the iterable + :param iterable: an iterable or async iterable + :param initial: the initial value (if missing, the first element of the iterable is + used as the initial value) + + """ + element: Any + function_called = False + if isinstance(iterable, AsyncIterable): + async_it = iterable.__aiter__() + if initial is initial_missing: + try: + value = cast(T, await async_it.__anext__()) + except StopAsyncIteration: + raise TypeError( + "reduce() of empty sequence with no initial value" + ) from None + else: + value = cast(T, initial) + + async for element in async_it: + value = await function(value, element) + function_called = True + elif isinstance(iterable, Iterable): + it = iter(iterable) + if initial is initial_missing: + try: + value = cast(T, next(it)) + except StopIteration: + raise TypeError( + "reduce() of empty sequence with no initial value" + ) from None + else: + value = cast(T, initial) + + for element in it: + value = await function(value, element) + function_called = True + else: + raise TypeError("reduce() argument 2 must be an iterable or async iterable") + + # Make sure there is at least one checkpoint, even if an empty iterable and an + # initial value were given + if not function_called: + await checkpoint() + + return value diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/lowlevel.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/lowlevel.py new file mode 100644 index 0000000000000000000000000000000000000000..ffbb75a7079aa4b1a13318641c1e1299e7bc1827 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/lowlevel.py @@ -0,0 +1,196 @@ +from __future__ import annotations + +__all__ = ( + "EventLoopToken", + "RunvarToken", + "RunVar", + "checkpoint", + "checkpoint_if_cancelled", + "cancel_shielded_checkpoint", + "current_token", +) + +import enum +from dataclasses import dataclass +from types import TracebackType +from typing import Any, Generic, Literal, TypeVar, final, overload +from weakref import WeakKeyDictionary + +from ._core._eventloop import get_async_backend +from .abc import AsyncBackend + +T = TypeVar("T") +D = TypeVar("D") + + +async def checkpoint() -> None: + """ + Check for cancellation and allow the scheduler to switch to another task. + + Equivalent to (but more efficient than):: + + await checkpoint_if_cancelled() + await cancel_shielded_checkpoint() + + .. versionadded:: 3.0 + + """ + await get_async_backend().checkpoint() + + +async def checkpoint_if_cancelled() -> None: + """ + Enter a checkpoint if the enclosing cancel scope has been cancelled. + + This does not allow the scheduler to switch to a different task. + + .. versionadded:: 3.0 + + """ + await get_async_backend().checkpoint_if_cancelled() + + +async def cancel_shielded_checkpoint() -> None: + """ + Allow the scheduler to switch to another task but without checking for cancellation. + + Equivalent to (but potentially more efficient than):: + + with CancelScope(shield=True): + await checkpoint() + + .. versionadded:: 3.0 + + """ + await get_async_backend().cancel_shielded_checkpoint() + + +@final +@dataclass(frozen=True, repr=False) +class EventLoopToken: + """ + An opaque object that holds a reference to an event loop. + + .. versionadded:: 4.11.0 + """ + + backend_class: type[AsyncBackend] + native_token: object + + +def current_token() -> EventLoopToken: + """ + Return a token object that can be used to call code in the current event loop from + another thread. + + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + .. versionadded:: 4.11.0 + + """ + backend_class = get_async_backend() + raw_token = backend_class.current_token() + return EventLoopToken(backend_class, raw_token) + + +_run_vars: WeakKeyDictionary[object, dict[RunVar[Any], Any]] = WeakKeyDictionary() + + +class _NoValueSet(enum.Enum): + NO_VALUE_SET = enum.auto() + + +class RunvarToken(Generic[T]): + __slots__ = "_var", "_value", "_redeemed" + + def __init__(self, var: RunVar[T], value: T | Literal[_NoValueSet.NO_VALUE_SET]): + self._var = var + self._value: T | Literal[_NoValueSet.NO_VALUE_SET] = value + self._redeemed = False + + def __enter__(self) -> RunvarToken[T]: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self._var.reset(self) + + +class RunVar(Generic[T]): + """ + Like a :class:`~contextvars.ContextVar`, except scoped to the running event loop. + + Can be used as a context manager, Just like :class:`~contextvars.ContextVar`, that + will reset the variable to its previous value when the context block is exited. + """ + + __slots__ = "_name", "_default" + + NO_VALUE_SET: Literal[_NoValueSet.NO_VALUE_SET] = _NoValueSet.NO_VALUE_SET + + def __init__( + self, name: str, default: T | Literal[_NoValueSet.NO_VALUE_SET] = NO_VALUE_SET + ): + self._name = name + self._default = default + + @property + def _current_vars(self) -> dict[RunVar[T], T]: + native_token = current_token().native_token + try: + return _run_vars[native_token] + except KeyError: + run_vars = _run_vars[native_token] = {} + return run_vars + + @overload + def get(self, default: D) -> T | D: ... + + @overload + def get(self) -> T: ... + + def get( + self, default: D | Literal[_NoValueSet.NO_VALUE_SET] = NO_VALUE_SET + ) -> T | D: + try: + return self._current_vars[self] + except KeyError: + if default is not RunVar.NO_VALUE_SET: + return default + elif self._default is not RunVar.NO_VALUE_SET: + return self._default + + raise LookupError( + f'Run variable "{self._name}" has no value and no default set' + ) + + def set(self, value: T) -> RunvarToken[T]: + current_vars = self._current_vars + token = RunvarToken(self, current_vars.get(self, RunVar.NO_VALUE_SET)) + current_vars[self] = value + return token + + def reset(self, token: RunvarToken[T]) -> None: + if token._var is not self: + raise ValueError("This token does not belong to this RunVar") + + if token._redeemed: + raise ValueError("This token has already been used") + + if token._value is _NoValueSet.NO_VALUE_SET: + try: + del self._current_vars[self] + except KeyError: + pass + else: + self._current_vars[self] = token._value + + token._redeemed = True + + def __repr__(self) -> str: + return f"" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/py.typed b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/pytest_plugin.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/pytest_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..4222816ab72f6dc96e16e43e06ae6a8b4059b3cd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/pytest_plugin.py @@ -0,0 +1,302 @@ +from __future__ import annotations + +import socket +import sys +from collections.abc import Callable, Generator, Iterator +from contextlib import ExitStack, contextmanager +from inspect import isasyncgenfunction, iscoroutinefunction, ismethod +from typing import Any, cast + +import pytest +from _pytest.fixtures import SubRequest +from _pytest.outcomes import Exit + +from . import get_available_backends +from ._core._eventloop import ( + current_async_library, + get_async_backend, + reset_current_async_library, + set_current_async_library, +) +from ._core._exceptions import iterate_exceptions +from .abc import TestRunner + +if sys.version_info < (3, 11): + from exceptiongroup import ExceptionGroup + +_current_runner: TestRunner | None = None +_runner_stack: ExitStack | None = None +_runner_leases = 0 + + +def extract_backend_and_options(backend: object) -> tuple[str, dict[str, Any]]: + if isinstance(backend, str): + return backend, {} + elif isinstance(backend, tuple) and len(backend) == 2: + if isinstance(backend[0], str) and isinstance(backend[1], dict): + return cast(tuple[str, dict[str, Any]], backend) + + raise TypeError("anyio_backend must be either a string or tuple of (string, dict)") + + +@contextmanager +def get_runner( + backend_name: str, backend_options: dict[str, Any] +) -> Iterator[TestRunner]: + global _current_runner, _runner_leases, _runner_stack + if _current_runner is None: + asynclib = get_async_backend(backend_name) + _runner_stack = ExitStack() + if current_async_library() is None: + # Since we're in control of the event loop, we can cache the name of the + # async library + token = set_current_async_library(backend_name) + _runner_stack.callback(reset_current_async_library, token) + + backend_options = backend_options or {} + _current_runner = _runner_stack.enter_context( + asynclib.create_test_runner(backend_options) + ) + + _runner_leases += 1 + try: + yield _current_runner + finally: + _runner_leases -= 1 + if not _runner_leases: + assert _runner_stack is not None + _runner_stack.close() + _runner_stack = _current_runner = None + + +def pytest_addoption(parser: pytest.Parser) -> None: + parser.addini( + "anyio_mode", + default="strict", + help='AnyIO plugin mode (either "strict" or "auto")', + ) + + +def pytest_configure(config: pytest.Config) -> None: + config.addinivalue_line( + "markers", + "anyio: mark the (coroutine function) test to be run asynchronously via anyio.", + ) + if ( + config.getini("anyio_mode") == "auto" + and config.pluginmanager.has_plugin("asyncio") + and config.getini("asyncio_mode") == "auto" + ): + config.issue_config_time_warning( + pytest.PytestConfigWarning( + "AnyIO auto mode has been enabled together with pytest-asyncio auto " + "mode. This may cause unexpected behavior." + ), + 1, + ) + + +@pytest.hookimpl(hookwrapper=True) +def pytest_fixture_setup(fixturedef: Any, request: Any) -> Generator[Any]: + def wrapper(anyio_backend: Any, request: SubRequest, **kwargs: Any) -> Any: + # Rebind any fixture methods to the request instance + if ( + request.instance + and ismethod(func) + and type(func.__self__) is type(request.instance) + ): + local_func = func.__func__.__get__(request.instance) + else: + local_func = func + + backend_name, backend_options = extract_backend_and_options(anyio_backend) + if has_backend_arg: + kwargs["anyio_backend"] = anyio_backend + + if has_request_arg: + kwargs["request"] = request + + with get_runner(backend_name, backend_options) as runner: + if isasyncgenfunction(local_func): + yield from runner.run_asyncgen_fixture(local_func, kwargs) + else: + yield runner.run_fixture(local_func, kwargs) + + # Only apply this to coroutine functions and async generator functions in requests + # that involve the anyio_backend fixture + func = fixturedef.func + if isasyncgenfunction(func) or iscoroutinefunction(func): + if "anyio_backend" in request.fixturenames: + fixturedef.func = wrapper + original_argname = fixturedef.argnames + + if not (has_backend_arg := "anyio_backend" in fixturedef.argnames): + fixturedef.argnames += ("anyio_backend",) + + if not (has_request_arg := "request" in fixturedef.argnames): + fixturedef.argnames += ("request",) + + try: + return (yield) + finally: + fixturedef.func = func + fixturedef.argnames = original_argname + + return (yield) + + +@pytest.hookimpl(tryfirst=True) +def pytest_pycollect_makeitem( + collector: pytest.Module | pytest.Class, name: str, obj: object +) -> None: + if collector.istestfunction(obj, name): + inner_func = obj.hypothesis.inner_test if hasattr(obj, "hypothesis") else obj + if iscoroutinefunction(inner_func): + anyio_auto_mode = collector.config.getini("anyio_mode") == "auto" + marker = collector.get_closest_marker("anyio") + own_markers = getattr(obj, "pytestmark", ()) + if ( + anyio_auto_mode + or marker + or any(marker.name == "anyio" for marker in own_markers) + ): + pytest.mark.usefixtures("anyio_backend")(obj) + + +@pytest.hookimpl(tryfirst=True) +def pytest_pyfunc_call(pyfuncitem: Any) -> bool | None: + def run_with_hypothesis(**kwargs: Any) -> None: + with get_runner(backend_name, backend_options) as runner: + runner.run_test(original_func, kwargs) + + backend = pyfuncitem.funcargs.get("anyio_backend") + if backend: + backend_name, backend_options = extract_backend_and_options(backend) + + if hasattr(pyfuncitem.obj, "hypothesis"): + # Wrap the inner test function unless it's already wrapped + original_func = pyfuncitem.obj.hypothesis.inner_test + if original_func.__qualname__ != run_with_hypothesis.__qualname__: + if iscoroutinefunction(original_func): + pyfuncitem.obj.hypothesis.inner_test = run_with_hypothesis + + return None + + if iscoroutinefunction(pyfuncitem.obj): + funcargs = pyfuncitem.funcargs + testargs = {arg: funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames} + with get_runner(backend_name, backend_options) as runner: + try: + runner.run_test(pyfuncitem.obj, testargs) + except ExceptionGroup as excgrp: + for exc in iterate_exceptions(excgrp): + if isinstance(exc, (Exit, KeyboardInterrupt, SystemExit)): + raise exc from excgrp + + raise + + return True + + return None + + +@pytest.fixture(scope="module", params=get_available_backends()) +def anyio_backend(request: Any) -> Any: + return request.param + + +@pytest.fixture +def anyio_backend_name(anyio_backend: Any) -> str: + if isinstance(anyio_backend, str): + return anyio_backend + else: + return anyio_backend[0] + + +@pytest.fixture +def anyio_backend_options(anyio_backend: Any) -> dict[str, Any]: + if isinstance(anyio_backend, str): + return {} + else: + return anyio_backend[1] + + +class FreePortFactory: + """ + Manages port generation based on specified socket kind, ensuring no duplicate + ports are generated. + + This class provides functionality for generating available free ports on the + system. It is initialized with a specific socket kind and can generate ports + for given address families while avoiding reuse of previously generated ports. + + Users should not instantiate this class directly, but use the + ``free_tcp_port_factory`` and ``free_udp_port_factory`` fixtures instead. For simple + uses cases, ``free_tcp_port`` and ``free_udp_port`` can be used instead. + """ + + def __init__(self, kind: socket.SocketKind) -> None: + self._kind = kind + self._generated = set[int]() + + @property + def kind(self) -> socket.SocketKind: + """ + The type of socket connection (e.g., :data:`~socket.SOCK_STREAM` or + :data:`~socket.SOCK_DGRAM`) used to bind for checking port availability + + """ + return self._kind + + def __call__(self, family: socket.AddressFamily | None = None) -> int: + """ + Return an unbound port for the given address family. + + :param family: if omitted, both IPv4 and IPv6 addresses will be tried + :return: a port number + + """ + if family is not None: + families = [family] + else: + families = [socket.AF_INET] + if socket.has_ipv6: + families.append(socket.AF_INET6) + + while True: + port = 0 + with ExitStack() as stack: + for family in families: + sock = stack.enter_context(socket.socket(family, self._kind)) + addr = "::1" if family == socket.AF_INET6 else "127.0.0.1" + try: + sock.bind((addr, port)) + except OSError: + break + + if not port: + port = sock.getsockname()[1] + else: + if port not in self._generated: + self._generated.add(port) + return port + + +@pytest.fixture(scope="session") +def free_tcp_port_factory() -> FreePortFactory: + return FreePortFactory(socket.SOCK_STREAM) + + +@pytest.fixture(scope="session") +def free_udp_port_factory() -> FreePortFactory: + return FreePortFactory(socket.SOCK_DGRAM) + + +@pytest.fixture +def free_tcp_port(free_tcp_port_factory: Callable[[], int]) -> int: + return free_tcp_port_factory() + + +@pytest.fixture +def free_udp_port(free_udp_port_factory: Callable[[], int]) -> int: + return free_udp_port_factory() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/streams/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/streams/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/streams/buffered.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/streams/buffered.py new file mode 100644 index 0000000000000000000000000000000000000000..57c7cd749bfb94bbe7a992aa9a05af268a841d3d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/streams/buffered.py @@ -0,0 +1,188 @@ +from __future__ import annotations + +__all__ = ( + "BufferedByteReceiveStream", + "BufferedByteStream", + "BufferedConnectable", +) + +import sys +from collections.abc import Callable, Iterable, Mapping +from dataclasses import dataclass, field +from typing import Any, SupportsIndex + +from .. import ClosedResourceError, DelimiterNotFound, EndOfStream, IncompleteRead +from ..abc import ( + AnyByteReceiveStream, + AnyByteStream, + AnyByteStreamConnectable, + ByteReceiveStream, + ByteStream, + ByteStreamConnectable, +) + +if sys.version_info >= (3, 12): + from typing import override +else: + from typing_extensions import override + + +@dataclass(eq=False) +class BufferedByteReceiveStream(ByteReceiveStream): + """ + Wraps any bytes-based receive stream and uses a buffer to provide sophisticated + receiving capabilities in the form of a byte stream. + """ + + receive_stream: AnyByteReceiveStream + _buffer: bytearray = field(init=False, default_factory=bytearray) + _closed: bool = field(init=False, default=False) + + async def aclose(self) -> None: + await self.receive_stream.aclose() + self._closed = True + + @property + def buffer(self) -> bytes: + """The bytes currently in the buffer.""" + return bytes(self._buffer) + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return self.receive_stream.extra_attributes + + def feed_data(self, data: Iterable[SupportsIndex], /) -> None: + """ + Append data directly into the buffer. + + Any data in the buffer will be consumed by receive operations before receiving + anything from the wrapped stream. + + :param data: the data to append to the buffer (can be bytes or anything else + that supports ``__index__()``) + + """ + self._buffer.extend(data) + + async def receive(self, max_bytes: int = 65536) -> bytes: + if self._closed: + raise ClosedResourceError + + if self._buffer: + chunk = bytes(self._buffer[:max_bytes]) + del self._buffer[:max_bytes] + return chunk + elif isinstance(self.receive_stream, ByteReceiveStream): + return await self.receive_stream.receive(max_bytes) + else: + # With a bytes-oriented object stream, we need to handle any surplus bytes + # we get from the receive() call + chunk = await self.receive_stream.receive() + if len(chunk) > max_bytes: + # Save the surplus bytes in the buffer + self._buffer.extend(chunk[max_bytes:]) + return chunk[:max_bytes] + else: + return chunk + + async def receive_exactly(self, nbytes: int) -> bytes: + """ + Read exactly the given amount of bytes from the stream. + + :param nbytes: the number of bytes to read + :return: the bytes read + :raises ~anyio.IncompleteRead: if the stream was closed before the requested + amount of bytes could be read from the stream + + """ + while True: + remaining = nbytes - len(self._buffer) + if remaining <= 0: + retval = self._buffer[:nbytes] + del self._buffer[:nbytes] + return bytes(retval) + + try: + if isinstance(self.receive_stream, ByteReceiveStream): + chunk = await self.receive_stream.receive(remaining) + else: + chunk = await self.receive_stream.receive() + except EndOfStream as exc: + raise IncompleteRead from exc + + self._buffer.extend(chunk) + + async def receive_until(self, delimiter: bytes, max_bytes: int) -> bytes: + """ + Read from the stream until the delimiter is found or max_bytes have been read. + + :param delimiter: the marker to look for in the stream + :param max_bytes: maximum number of bytes that will be read before raising + :exc:`~anyio.DelimiterNotFound` + :return: the bytes read (not including the delimiter) + :raises ~anyio.IncompleteRead: if the stream was closed before the delimiter + was found + :raises ~anyio.DelimiterNotFound: if the delimiter is not found within the + bytes read up to the maximum allowed + + """ + delimiter_size = len(delimiter) + offset = 0 + while True: + # Check if the delimiter can be found in the current buffer + index = self._buffer.find(delimiter, offset) + if index >= 0: + found = self._buffer[:index] + del self._buffer[: index + len(delimiter) :] + return bytes(found) + + # Check if the buffer is already at or over the limit + if len(self._buffer) >= max_bytes: + raise DelimiterNotFound(max_bytes) + + # Read more data into the buffer from the socket + try: + data = await self.receive_stream.receive() + except EndOfStream as exc: + raise IncompleteRead from exc + + # Move the offset forward and add the new data to the buffer + offset = max(len(self._buffer) - delimiter_size + 1, 0) + self._buffer.extend(data) + + +class BufferedByteStream(BufferedByteReceiveStream, ByteStream): + """ + A full-duplex variant of :class:`BufferedByteReceiveStream`. All writes are passed + through to the wrapped stream as-is. + """ + + def __init__(self, stream: AnyByteStream): + """ + :param stream: the stream to be wrapped + + """ + super().__init__(stream) + self._stream = stream + + @override + async def send_eof(self) -> None: + await self._stream.send_eof() + + @override + async def send(self, item: bytes) -> None: + await self._stream.send(item) + + +class BufferedConnectable(ByteStreamConnectable): + def __init__(self, connectable: AnyByteStreamConnectable): + """ + :param connectable: the connectable to wrap + + """ + self.connectable = connectable + + @override + async def connect(self) -> BufferedByteStream: + stream = await self.connectable.connect() + return BufferedByteStream(stream) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/streams/file.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/streams/file.py new file mode 100644 index 0000000000000000000000000000000000000000..82d2da8965ab4281ef0b554f7b8cae857a21bde5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/streams/file.py @@ -0,0 +1,154 @@ +from __future__ import annotations + +__all__ = ( + "FileReadStream", + "FileStreamAttribute", + "FileWriteStream", +) + +from collections.abc import Callable, Mapping +from io import SEEK_SET, UnsupportedOperation +from os import PathLike +from pathlib import Path +from typing import Any, BinaryIO, cast + +from .. import ( + BrokenResourceError, + ClosedResourceError, + EndOfStream, + TypedAttributeSet, + to_thread, + typed_attribute, +) +from ..abc import ByteReceiveStream, ByteSendStream + + +class FileStreamAttribute(TypedAttributeSet): + #: the open file descriptor + file: BinaryIO = typed_attribute() + #: the path of the file on the file system, if available (file must be a real file) + path: Path = typed_attribute() + #: the file number, if available (file must be a real file or a TTY) + fileno: int = typed_attribute() + + +class _BaseFileStream: + def __init__(self, file: BinaryIO): + self._file = file + + async def aclose(self) -> None: + await to_thread.run_sync(self._file.close) + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + attributes: dict[Any, Callable[[], Any]] = { + FileStreamAttribute.file: lambda: self._file, + } + + if hasattr(self._file, "name"): + attributes[FileStreamAttribute.path] = lambda: Path(self._file.name) + + try: + self._file.fileno() + except UnsupportedOperation: + pass + else: + attributes[FileStreamAttribute.fileno] = lambda: self._file.fileno() + + return attributes + + +class FileReadStream(_BaseFileStream, ByteReceiveStream): + """ + A byte stream that reads from a file in the file system. + + :param file: a file that has been opened for reading in binary mode + + .. versionadded:: 3.0 + """ + + @classmethod + async def from_path(cls, path: str | PathLike[str]) -> FileReadStream: + """ + Create a file read stream by opening the given file. + + :param path: path of the file to read from + + """ + file = await to_thread.run_sync(Path(path).open, "rb") + return cls(cast(BinaryIO, file)) + + async def receive(self, max_bytes: int = 65536) -> bytes: + try: + data = await to_thread.run_sync(self._file.read, max_bytes) + except ValueError: + raise ClosedResourceError from None + except OSError as exc: + raise BrokenResourceError from exc + + if data: + return data + else: + raise EndOfStream + + async def seek(self, position: int, whence: int = SEEK_SET) -> int: + """ + Seek the file to the given position. + + .. seealso:: :meth:`io.IOBase.seek` + + .. note:: Not all file descriptors are seekable. + + :param position: position to seek the file to + :param whence: controls how ``position`` is interpreted + :return: the new absolute position + :raises OSError: if the file is not seekable + + """ + return await to_thread.run_sync(self._file.seek, position, whence) + + async def tell(self) -> int: + """ + Return the current stream position. + + .. note:: Not all file descriptors are seekable. + + :return: the current absolute position + :raises OSError: if the file is not seekable + + """ + return await to_thread.run_sync(self._file.tell) + + +class FileWriteStream(_BaseFileStream, ByteSendStream): + """ + A byte stream that writes to a file in the file system. + + :param file: a file that has been opened for writing in binary mode + + .. versionadded:: 3.0 + """ + + @classmethod + async def from_path( + cls, path: str | PathLike[str], append: bool = False + ) -> FileWriteStream: + """ + Create a file write stream by opening the given file for writing. + + :param path: path of the file to write to + :param append: if ``True``, open the file for appending; if ``False``, any + existing file at the given path will be truncated + + """ + mode = "ab" if append else "wb" + file = await to_thread.run_sync(Path(path).open, mode) + return cls(cast(BinaryIO, file)) + + async def send(self, item: bytes) -> None: + try: + await to_thread.run_sync(self._file.write, item) + except ValueError: + raise ClosedResourceError from None + except OSError as exc: + raise BrokenResourceError from exc diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/streams/memory.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/streams/memory.py new file mode 100644 index 0000000000000000000000000000000000000000..a3fa0c3d9783f34fb5225938f6ce5d1d31b9b85c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/streams/memory.py @@ -0,0 +1,325 @@ +from __future__ import annotations + +__all__ = ( + "MemoryObjectReceiveStream", + "MemoryObjectSendStream", + "MemoryObjectStreamStatistics", +) + +import warnings +from collections import OrderedDict, deque +from dataclasses import dataclass, field +from types import TracebackType +from typing import Generic, NamedTuple, TypeVar + +from .. import ( + BrokenResourceError, + ClosedResourceError, + EndOfStream, + WouldBlock, +) +from .._core._testing import TaskInfo, get_current_task +from ..abc import Event, ObjectReceiveStream, ObjectSendStream +from ..lowlevel import checkpoint + +T_Item = TypeVar("T_Item") +T_co = TypeVar("T_co", covariant=True) +T_contra = TypeVar("T_contra", contravariant=True) + + +class MemoryObjectStreamStatistics(NamedTuple): + current_buffer_used: int #: number of items stored in the buffer + #: maximum number of items that can be stored on this stream (or :data:`math.inf`) + max_buffer_size: float + open_send_streams: int #: number of unclosed clones of the send stream + open_receive_streams: int #: number of unclosed clones of the receive stream + #: number of tasks blocked on :meth:`MemoryObjectSendStream.send` + tasks_waiting_send: int + #: number of tasks blocked on :meth:`MemoryObjectReceiveStream.receive` + tasks_waiting_receive: int + + +@dataclass(eq=False) +class _MemoryObjectItemReceiver(Generic[T_Item]): + task_info: TaskInfo = field(init=False, default_factory=get_current_task) + item: T_Item = field(init=False) + + def __repr__(self) -> str: + # When item is not defined, we get following error with default __repr__: + # AttributeError: 'MemoryObjectItemReceiver' object has no attribute 'item' + item = getattr(self, "item", None) + return f"{self.__class__.__name__}(task_info={self.task_info}, item={item!r})" + + +@dataclass(eq=False) +class _MemoryObjectStreamState(Generic[T_Item]): + max_buffer_size: float = field() + buffer: deque[T_Item] = field(init=False, default_factory=deque) + open_send_channels: int = field(init=False, default=0) + open_receive_channels: int = field(init=False, default=0) + waiting_receivers: OrderedDict[Event, _MemoryObjectItemReceiver[T_Item]] = field( + init=False, default_factory=OrderedDict + ) + waiting_senders: OrderedDict[Event, T_Item] = field( + init=False, default_factory=OrderedDict + ) + + def statistics(self) -> MemoryObjectStreamStatistics: + return MemoryObjectStreamStatistics( + len(self.buffer), + self.max_buffer_size, + self.open_send_channels, + self.open_receive_channels, + len(self.waiting_senders), + len(self.waiting_receivers), + ) + + +@dataclass(eq=False) +class MemoryObjectReceiveStream(Generic[T_co], ObjectReceiveStream[T_co]): + _state: _MemoryObjectStreamState[T_co] + _closed: bool = field(init=False, default=False) + + def __post_init__(self) -> None: + self._state.open_receive_channels += 1 + + def receive_nowait(self) -> T_co: + """ + Receive the next item if it can be done without waiting. + + :return: the received item + :raises ~anyio.ClosedResourceError: if this send stream has been closed + :raises ~anyio.EndOfStream: if the buffer is empty and this stream has been + closed from the sending end + :raises ~anyio.WouldBlock: if there are no items in the buffer and no tasks + waiting to send + + """ + if self._closed: + raise ClosedResourceError + + if self._state.waiting_senders: + # Get the item from the next sender + send_event, item = self._state.waiting_senders.popitem(last=False) + self._state.buffer.append(item) + send_event.set() + + if self._state.buffer: + return self._state.buffer.popleft() + elif not self._state.open_send_channels: + raise EndOfStream + + raise WouldBlock + + async def receive(self) -> T_co: + await checkpoint() + try: + return self.receive_nowait() + except WouldBlock: + # Add ourselves in the queue + receive_event = Event() + receiver = _MemoryObjectItemReceiver[T_co]() + self._state.waiting_receivers[receive_event] = receiver + + try: + await receive_event.wait() + finally: + self._state.waiting_receivers.pop(receive_event, None) + + try: + return receiver.item + except AttributeError: + raise EndOfStream from None + + def clone(self) -> MemoryObjectReceiveStream[T_co]: + """ + Create a clone of this receive stream. + + Each clone can be closed separately. Only when all clones have been closed will + the receiving end of the memory stream be considered closed by the sending ends. + + :return: the cloned stream + + """ + if self._closed: + raise ClosedResourceError + + return MemoryObjectReceiveStream(_state=self._state) + + def close(self) -> None: + """ + Close the stream. + + This works the exact same way as :meth:`aclose`, but is provided as a special + case for the benefit of synchronous callbacks. + + """ + if not self._closed: + self._closed = True + self._state.open_receive_channels -= 1 + if self._state.open_receive_channels == 0: + send_events = list(self._state.waiting_senders.keys()) + for event in send_events: + event.set() + + async def aclose(self) -> None: + self.close() + + def statistics(self) -> MemoryObjectStreamStatistics: + """ + Return statistics about the current state of this stream. + + .. versionadded:: 3.0 + """ + return self._state.statistics() + + def __enter__(self) -> MemoryObjectReceiveStream[T_co]: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.close() + + def __del__(self) -> None: + if not self._closed: + warnings.warn( + f"Unclosed <{self.__class__.__name__} at {id(self):x}>", + ResourceWarning, + stacklevel=1, + source=self, + ) + + +@dataclass(eq=False) +class MemoryObjectSendStream(Generic[T_contra], ObjectSendStream[T_contra]): + _state: _MemoryObjectStreamState[T_contra] + _closed: bool = field(init=False, default=False) + + def __post_init__(self) -> None: + self._state.open_send_channels += 1 + + def send_nowait(self, item: T_contra) -> None: + """ + Send an item immediately if it can be done without waiting. + + :param item: the item to send + :raises ~anyio.ClosedResourceError: if this send stream has been closed + :raises ~anyio.BrokenResourceError: if the stream has been closed from the + receiving end + :raises ~anyio.WouldBlock: if the buffer is full and there are no tasks waiting + to receive + + """ + if self._closed: + raise ClosedResourceError + if not self._state.open_receive_channels: + raise BrokenResourceError + + while self._state.waiting_receivers: + receive_event, receiver = self._state.waiting_receivers.popitem(last=False) + if not receiver.task_info.has_pending_cancellation(): + receiver.item = item + receive_event.set() + return + + if len(self._state.buffer) < self._state.max_buffer_size: + self._state.buffer.append(item) + else: + raise WouldBlock + + async def send(self, item: T_contra) -> None: + """ + Send an item to the stream. + + If the buffer is full, this method blocks until there is again room in the + buffer or the item can be sent directly to a receiver. + + :param item: the item to send + :raises ~anyio.ClosedResourceError: if this send stream has been closed + :raises ~anyio.BrokenResourceError: if the stream has been closed from the + receiving end + + """ + await checkpoint() + try: + self.send_nowait(item) + except WouldBlock: + # Wait until there's someone on the receiving end + send_event = Event() + self._state.waiting_senders[send_event] = item + try: + await send_event.wait() + except BaseException: + self._state.waiting_senders.pop(send_event, None) + raise + + if send_event in self._state.waiting_senders: + del self._state.waiting_senders[send_event] + raise BrokenResourceError from None + + def clone(self) -> MemoryObjectSendStream[T_contra]: + """ + Create a clone of this send stream. + + Each clone can be closed separately. Only when all clones have been closed will + the sending end of the memory stream be considered closed by the receiving ends. + + :return: the cloned stream + + """ + if self._closed: + raise ClosedResourceError + + return MemoryObjectSendStream(_state=self._state) + + def close(self) -> None: + """ + Close the stream. + + This works the exact same way as :meth:`aclose`, but is provided as a special + case for the benefit of synchronous callbacks. + + """ + if not self._closed: + self._closed = True + self._state.open_send_channels -= 1 + if self._state.open_send_channels == 0: + receive_events = list(self._state.waiting_receivers.keys()) + self._state.waiting_receivers.clear() + for event in receive_events: + event.set() + + async def aclose(self) -> None: + self.close() + + def statistics(self) -> MemoryObjectStreamStatistics: + """ + Return statistics about the current state of this stream. + + .. versionadded:: 3.0 + """ + return self._state.statistics() + + def __enter__(self) -> MemoryObjectSendStream[T_contra]: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.close() + + def __del__(self) -> None: + if not self._closed: + warnings.warn( + f"Unclosed <{self.__class__.__name__} at {id(self):x}>", + ResourceWarning, + stacklevel=1, + source=self, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/streams/stapled.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/streams/stapled.py new file mode 100644 index 0000000000000000000000000000000000000000..9248b68abfbff90ddd64646fbe9cabb9f0ebe869 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/streams/stapled.py @@ -0,0 +1,147 @@ +from __future__ import annotations + +__all__ = ( + "MultiListener", + "StapledByteStream", + "StapledObjectStream", +) + +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass +from typing import Any, Generic, TypeVar + +from ..abc import ( + ByteReceiveStream, + ByteSendStream, + ByteStream, + Listener, + ObjectReceiveStream, + ObjectSendStream, + ObjectStream, + TaskGroup, +) + +T_Item = TypeVar("T_Item") +T_Stream = TypeVar("T_Stream") + + +@dataclass(eq=False) +class StapledByteStream(ByteStream): + """ + Combines two byte streams into a single, bidirectional byte stream. + + Extra attributes will be provided from both streams, with the receive stream + providing the values in case of a conflict. + + :param ByteSendStream send_stream: the sending byte stream + :param ByteReceiveStream receive_stream: the receiving byte stream + """ + + send_stream: ByteSendStream + receive_stream: ByteReceiveStream + + async def receive(self, max_bytes: int = 65536) -> bytes: + return await self.receive_stream.receive(max_bytes) + + async def send(self, item: bytes) -> None: + await self.send_stream.send(item) + + async def send_eof(self) -> None: + await self.send_stream.aclose() + + async def aclose(self) -> None: + await self.send_stream.aclose() + await self.receive_stream.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + **self.send_stream.extra_attributes, + **self.receive_stream.extra_attributes, + } + + +@dataclass(eq=False) +class StapledObjectStream(Generic[T_Item], ObjectStream[T_Item]): + """ + Combines two object streams into a single, bidirectional object stream. + + Extra attributes will be provided from both streams, with the receive stream + providing the values in case of a conflict. + + :param ObjectSendStream send_stream: the sending object stream + :param ObjectReceiveStream receive_stream: the receiving object stream + """ + + send_stream: ObjectSendStream[T_Item] + receive_stream: ObjectReceiveStream[T_Item] + + async def receive(self) -> T_Item: + return await self.receive_stream.receive() + + async def send(self, item: T_Item) -> None: + await self.send_stream.send(item) + + async def send_eof(self) -> None: + await self.send_stream.aclose() + + async def aclose(self) -> None: + await self.send_stream.aclose() + await self.receive_stream.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + **self.send_stream.extra_attributes, + **self.receive_stream.extra_attributes, + } + + +@dataclass(eq=False) +class MultiListener(Generic[T_Stream], Listener[T_Stream]): + """ + Combines multiple listeners into one, serving connections from all of them at once. + + Any MultiListeners in the given collection of listeners will have their listeners + moved into this one. + + Extra attributes are provided from each listener, with each successive listener + overriding any conflicting attributes from the previous one. + + :param listeners: listeners to serve + :type listeners: Sequence[Listener[T_Stream]] + """ + + listeners: Sequence[Listener[T_Stream]] + + def __post_init__(self) -> None: + listeners: list[Listener[T_Stream]] = [] + for listener in self.listeners: + if isinstance(listener, MultiListener): + listeners.extend(listener.listeners) + del listener.listeners[:] # type: ignore[attr-defined] + else: + listeners.append(listener) + + self.listeners = listeners + + async def serve( + self, handler: Callable[[T_Stream], Any], task_group: TaskGroup | None = None + ) -> None: + from .. import create_task_group + + async with create_task_group() as tg: + for listener in self.listeners: + tg.start_soon(listener.serve, handler, task_group) + + async def aclose(self) -> None: + for listener in self.listeners: + await listener.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + attributes: dict = {} + for listener in self.listeners: + attributes.update(listener.extra_attributes) + + return attributes diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/streams/text.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/streams/text.py new file mode 100644 index 0000000000000000000000000000000000000000..296cd250459f3848bb333301fff1ac32973f219a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/streams/text.py @@ -0,0 +1,176 @@ +from __future__ import annotations + +__all__ = ( + "TextConnectable", + "TextReceiveStream", + "TextSendStream", + "TextStream", +) + +import codecs +import sys +from collections.abc import Callable, Mapping +from dataclasses import InitVar, dataclass, field +from typing import Any + +from ..abc import ( + AnyByteReceiveStream, + AnyByteSendStream, + AnyByteStream, + AnyByteStreamConnectable, + ObjectReceiveStream, + ObjectSendStream, + ObjectStream, + ObjectStreamConnectable, +) + +if sys.version_info >= (3, 12): + from typing import override +else: + from typing_extensions import override + + +@dataclass(eq=False) +class TextReceiveStream(ObjectReceiveStream[str]): + """ + Stream wrapper that decodes bytes to strings using the given encoding. + + Decoding is done using :class:`~codecs.IncrementalDecoder` which returns any + completely received unicode characters as soon as they come in. + + :param transport_stream: any bytes-based receive stream + :param encoding: character encoding to use for decoding bytes to strings (defaults + to ``utf-8``) + :param errors: handling scheme for decoding errors (defaults to ``strict``; see the + `codecs module documentation`_ for a comprehensive list of options) + + .. _codecs module documentation: + https://docs.python.org/3/library/codecs.html#codec-objects + """ + + transport_stream: AnyByteReceiveStream + encoding: InitVar[str] = "utf-8" + errors: InitVar[str] = "strict" + _decoder: codecs.IncrementalDecoder = field(init=False) + + def __post_init__(self, encoding: str, errors: str) -> None: + decoder_class = codecs.getincrementaldecoder(encoding) + self._decoder = decoder_class(errors=errors) + + async def receive(self) -> str: + while True: + chunk = await self.transport_stream.receive() + decoded = self._decoder.decode(chunk) + if decoded: + return decoded + + async def aclose(self) -> None: + await self.transport_stream.aclose() + self._decoder.reset() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return self.transport_stream.extra_attributes + + +@dataclass(eq=False) +class TextSendStream(ObjectSendStream[str]): + """ + Sends strings to the wrapped stream as bytes using the given encoding. + + :param AnyByteSendStream transport_stream: any bytes-based send stream + :param str encoding: character encoding to use for encoding strings to bytes + (defaults to ``utf-8``) + :param str errors: handling scheme for encoding errors (defaults to ``strict``; see + the `codecs module documentation`_ for a comprehensive list of options) + + .. _codecs module documentation: + https://docs.python.org/3/library/codecs.html#codec-objects + """ + + transport_stream: AnyByteSendStream + encoding: InitVar[str] = "utf-8" + errors: str = "strict" + _encoder: Callable[..., tuple[bytes, int]] = field(init=False) + + def __post_init__(self, encoding: str) -> None: + self._encoder = codecs.getencoder(encoding) + + async def send(self, item: str) -> None: + encoded = self._encoder(item, self.errors)[0] + await self.transport_stream.send(encoded) + + async def aclose(self) -> None: + await self.transport_stream.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return self.transport_stream.extra_attributes + + +@dataclass(eq=False) +class TextStream(ObjectStream[str]): + """ + A bidirectional stream that decodes bytes to strings on receive and encodes strings + to bytes on send. + + Extra attributes will be provided from both streams, with the receive stream + providing the values in case of a conflict. + + :param AnyByteStream transport_stream: any bytes-based stream + :param str encoding: character encoding to use for encoding/decoding strings to/from + bytes (defaults to ``utf-8``) + :param str errors: handling scheme for encoding errors (defaults to ``strict``; see + the `codecs module documentation`_ for a comprehensive list of options) + + .. _codecs module documentation: + https://docs.python.org/3/library/codecs.html#codec-objects + """ + + transport_stream: AnyByteStream + encoding: InitVar[str] = "utf-8" + errors: InitVar[str] = "strict" + _receive_stream: TextReceiveStream = field(init=False) + _send_stream: TextSendStream = field(init=False) + + def __post_init__(self, encoding: str, errors: str) -> None: + self._receive_stream = TextReceiveStream( + self.transport_stream, encoding=encoding, errors=errors + ) + self._send_stream = TextSendStream( + self.transport_stream, encoding=encoding, errors=errors + ) + + async def receive(self) -> str: + return await self._receive_stream.receive() + + async def send(self, item: str) -> None: + await self._send_stream.send(item) + + async def send_eof(self) -> None: + await self.transport_stream.send_eof() + + async def aclose(self) -> None: + await self._send_stream.aclose() + await self._receive_stream.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + **self._send_stream.extra_attributes, + **self._receive_stream.extra_attributes, + } + + +class TextConnectable(ObjectStreamConnectable[str]): + def __init__(self, connectable: AnyByteStreamConnectable): + """ + :param connectable: the bytestream endpoint to wrap + + """ + self.connectable = connectable + + @override + async def connect(self) -> TextStream: + stream = await self.connectable.connect() + return TextStream(stream) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/streams/tls.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/streams/tls.py new file mode 100644 index 0000000000000000000000000000000000000000..b507488c57a3f90c64ea80733910dc9311e5a3e3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/streams/tls.py @@ -0,0 +1,424 @@ +from __future__ import annotations + +__all__ = ( + "TLSAttribute", + "TLSConnectable", + "TLSListener", + "TLSStream", +) + +import logging +import re +import ssl +import sys +from collections.abc import Callable, Mapping +from dataclasses import dataclass +from functools import wraps +from ssl import SSLContext +from typing import Any, TypeVar + +from .. import ( + BrokenResourceError, + EndOfStream, + aclose_forcefully, + get_cancelled_exc_class, + to_thread, +) +from .._core._typedattr import TypedAttributeSet, typed_attribute +from ..abc import ( + AnyByteStream, + AnyByteStreamConnectable, + ByteStream, + ByteStreamConnectable, + Listener, + TaskGroup, +) + +if sys.version_info >= (3, 10): + from typing import TypeAlias +else: + from typing_extensions import TypeAlias + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +if sys.version_info >= (3, 12): + from typing import override +else: + from typing_extensions import override + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") +_PCTRTT: TypeAlias = tuple[tuple[str, str], ...] +_PCTRTTT: TypeAlias = tuple[_PCTRTT, ...] + + +class TLSAttribute(TypedAttributeSet): + """Contains Transport Layer Security related attributes.""" + + #: the selected ALPN protocol + alpn_protocol: str | None = typed_attribute() + #: the channel binding for type ``tls-unique`` + channel_binding_tls_unique: bytes = typed_attribute() + #: the selected cipher + cipher: tuple[str, str, int] = typed_attribute() + #: the peer certificate in dictionary form (see :meth:`ssl.SSLSocket.getpeercert` + # for more information) + peer_certificate: None | (dict[str, str | _PCTRTTT | _PCTRTT]) = typed_attribute() + #: the peer certificate in binary form + peer_certificate_binary: bytes | None = typed_attribute() + #: ``True`` if this is the server side of the connection + server_side: bool = typed_attribute() + #: ciphers shared by the client during the TLS handshake (``None`` if this is the + #: client side) + shared_ciphers: list[tuple[str, str, int]] | None = typed_attribute() + #: the :class:`~ssl.SSLObject` used for encryption + ssl_object: ssl.SSLObject = typed_attribute() + #: ``True`` if this stream does (and expects) a closing TLS handshake when the + #: stream is being closed + standard_compatible: bool = typed_attribute() + #: the TLS protocol version (e.g. ``TLSv1.2``) + tls_version: str = typed_attribute() + + +@dataclass(eq=False) +class TLSStream(ByteStream): + """ + A stream wrapper that encrypts all sent data and decrypts received data. + + This class has no public initializer; use :meth:`wrap` instead. + All extra attributes from :class:`~TLSAttribute` are supported. + + :var AnyByteStream transport_stream: the wrapped stream + + """ + + transport_stream: AnyByteStream + standard_compatible: bool + _ssl_object: ssl.SSLObject + _read_bio: ssl.MemoryBIO + _write_bio: ssl.MemoryBIO + + @classmethod + async def wrap( + cls, + transport_stream: AnyByteStream, + *, + server_side: bool | None = None, + hostname: str | None = None, + ssl_context: ssl.SSLContext | None = None, + standard_compatible: bool = True, + ) -> TLSStream: + """ + Wrap an existing stream with Transport Layer Security. + + This performs a TLS handshake with the peer. + + :param transport_stream: a bytes-transporting stream to wrap + :param server_side: ``True`` if this is the server side of the connection, + ``False`` if this is the client side (if omitted, will be set to ``False`` + if ``hostname`` has been provided, ``False`` otherwise). Used only to create + a default context when an explicit context has not been provided. + :param hostname: host name of the peer (if host name checking is desired) + :param ssl_context: the SSLContext object to use (if not provided, a secure + default will be created) + :param standard_compatible: if ``False``, skip the closing handshake when + closing the connection, and don't raise an exception if the peer does the + same + :raises ~ssl.SSLError: if the TLS handshake fails + + """ + if server_side is None: + server_side = not hostname + + if not ssl_context: + purpose = ( + ssl.Purpose.CLIENT_AUTH if server_side else ssl.Purpose.SERVER_AUTH + ) + ssl_context = ssl.create_default_context(purpose) + + # Re-enable detection of unexpected EOFs if it was disabled by Python + if hasattr(ssl, "OP_IGNORE_UNEXPECTED_EOF"): + ssl_context.options &= ~ssl.OP_IGNORE_UNEXPECTED_EOF + + bio_in = ssl.MemoryBIO() + bio_out = ssl.MemoryBIO() + + # External SSLContext implementations may do blocking I/O in wrap_bio(), + # but the standard library implementation won't + if type(ssl_context) is ssl.SSLContext: + ssl_object = ssl_context.wrap_bio( + bio_in, bio_out, server_side=server_side, server_hostname=hostname + ) + else: + ssl_object = await to_thread.run_sync( + ssl_context.wrap_bio, + bio_in, + bio_out, + server_side, + hostname, + None, + ) + + wrapper = cls( + transport_stream=transport_stream, + standard_compatible=standard_compatible, + _ssl_object=ssl_object, + _read_bio=bio_in, + _write_bio=bio_out, + ) + await wrapper._call_sslobject_method(ssl_object.do_handshake) + return wrapper + + async def _call_sslobject_method( + self, func: Callable[[Unpack[PosArgsT]], T_Retval], *args: Unpack[PosArgsT] + ) -> T_Retval: + while True: + try: + result = func(*args) + except ssl.SSLWantReadError: + try: + # Flush any pending writes first + if self._write_bio.pending: + await self.transport_stream.send(self._write_bio.read()) + + data = await self.transport_stream.receive() + except EndOfStream: + self._read_bio.write_eof() + except OSError as exc: + self._read_bio.write_eof() + self._write_bio.write_eof() + raise BrokenResourceError from exc + else: + self._read_bio.write(data) + except ssl.SSLWantWriteError: + await self.transport_stream.send(self._write_bio.read()) + except ssl.SSLSyscallError as exc: + self._read_bio.write_eof() + self._write_bio.write_eof() + raise BrokenResourceError from exc + except ssl.SSLError as exc: + self._read_bio.write_eof() + self._write_bio.write_eof() + if isinstance(exc, ssl.SSLEOFError) or ( + exc.strerror and "UNEXPECTED_EOF_WHILE_READING" in exc.strerror + ): + if self.standard_compatible: + raise BrokenResourceError from exc + else: + raise EndOfStream from None + + raise + else: + # Flush any pending writes first + if self._write_bio.pending: + await self.transport_stream.send(self._write_bio.read()) + + return result + + async def unwrap(self) -> tuple[AnyByteStream, bytes]: + """ + Does the TLS closing handshake. + + :return: a tuple of (wrapped byte stream, bytes left in the read buffer) + + """ + await self._call_sslobject_method(self._ssl_object.unwrap) + self._read_bio.write_eof() + self._write_bio.write_eof() + return self.transport_stream, self._read_bio.read() + + async def aclose(self) -> None: + if self.standard_compatible: + try: + await self.unwrap() + except BaseException: + await aclose_forcefully(self.transport_stream) + raise + + await self.transport_stream.aclose() + + async def receive(self, max_bytes: int = 65536) -> bytes: + data = await self._call_sslobject_method(self._ssl_object.read, max_bytes) + if not data: + raise EndOfStream + + return data + + async def send(self, item: bytes) -> None: + await self._call_sslobject_method(self._ssl_object.write, item) + + async def send_eof(self) -> None: + tls_version = self.extra(TLSAttribute.tls_version) + match = re.match(r"TLSv(\d+)(?:\.(\d+))?", tls_version) + if match: + major, minor = int(match.group(1)), int(match.group(2) or 0) + if (major, minor) < (1, 3): + raise NotImplementedError( + f"send_eof() requires at least TLSv1.3; current " + f"session uses {tls_version}" + ) + + raise NotImplementedError( + "send_eof() has not yet been implemented for TLS streams" + ) + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + **self.transport_stream.extra_attributes, + TLSAttribute.alpn_protocol: self._ssl_object.selected_alpn_protocol, + TLSAttribute.channel_binding_tls_unique: ( + self._ssl_object.get_channel_binding + ), + TLSAttribute.cipher: self._ssl_object.cipher, + TLSAttribute.peer_certificate: lambda: self._ssl_object.getpeercert(False), + TLSAttribute.peer_certificate_binary: lambda: self._ssl_object.getpeercert( + True + ), + TLSAttribute.server_side: lambda: self._ssl_object.server_side, + TLSAttribute.shared_ciphers: lambda: self._ssl_object.shared_ciphers() + if self._ssl_object.server_side + else None, + TLSAttribute.standard_compatible: lambda: self.standard_compatible, + TLSAttribute.ssl_object: lambda: self._ssl_object, + TLSAttribute.tls_version: self._ssl_object.version, + } + + +@dataclass(eq=False) +class TLSListener(Listener[TLSStream]): + """ + A convenience listener that wraps another listener and auto-negotiates a TLS session + on every accepted connection. + + If the TLS handshake times out or raises an exception, + :meth:`handle_handshake_error` is called to do whatever post-mortem processing is + deemed necessary. + + Supports only the :attr:`~TLSAttribute.standard_compatible` extra attribute. + + :param Listener listener: the listener to wrap + :param ssl_context: the SSL context object + :param standard_compatible: a flag passed through to :meth:`TLSStream.wrap` + :param handshake_timeout: time limit for the TLS handshake + (passed to :func:`~anyio.fail_after`) + """ + + listener: Listener[Any] + ssl_context: ssl.SSLContext + standard_compatible: bool = True + handshake_timeout: float = 30 + + @staticmethod + async def handle_handshake_error(exc: BaseException, stream: AnyByteStream) -> None: + """ + Handle an exception raised during the TLS handshake. + + This method does 3 things: + + #. Forcefully closes the original stream + #. Logs the exception (unless it was a cancellation exception) using the + ``anyio.streams.tls`` logger + #. Reraises the exception if it was a base exception or a cancellation exception + + :param exc: the exception + :param stream: the original stream + + """ + await aclose_forcefully(stream) + + # Log all except cancellation exceptions + if not isinstance(exc, get_cancelled_exc_class()): + # CPython (as of 3.11.5) returns incorrect `sys.exc_info()` here when using + # any asyncio implementation, so we explicitly pass the exception to log + # (https://github.com/python/cpython/issues/108668). Trio does not have this + # issue because it works around the CPython bug. + logging.getLogger(__name__).exception( + "Error during TLS handshake", exc_info=exc + ) + + # Only reraise base exceptions and cancellation exceptions + if not isinstance(exc, Exception) or isinstance(exc, get_cancelled_exc_class()): + raise + + async def serve( + self, + handler: Callable[[TLSStream], Any], + task_group: TaskGroup | None = None, + ) -> None: + @wraps(handler) + async def handler_wrapper(stream: AnyByteStream) -> None: + from .. import fail_after + + try: + with fail_after(self.handshake_timeout): + wrapped_stream = await TLSStream.wrap( + stream, + ssl_context=self.ssl_context, + standard_compatible=self.standard_compatible, + ) + except BaseException as exc: + await self.handle_handshake_error(exc, stream) + else: + await handler(wrapped_stream) + + await self.listener.serve(handler_wrapper, task_group) + + async def aclose(self) -> None: + await self.listener.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + TLSAttribute.standard_compatible: lambda: self.standard_compatible, + } + + +class TLSConnectable(ByteStreamConnectable): + """ + Wraps another connectable and does TLS negotiation after a successful connection. + + :param connectable: the connectable to wrap + :param hostname: host name of the server (if host name checking is desired) + :param ssl_context: the SSLContext object to use (if not provided, a secure default + will be created) + :param standard_compatible: if ``False``, skip the closing handshake when closing + the connection, and don't raise an exception if the server does the same + """ + + def __init__( + self, + connectable: AnyByteStreamConnectable, + *, + hostname: str | None = None, + ssl_context: ssl.SSLContext | None = None, + standard_compatible: bool = True, + ) -> None: + self.connectable = connectable + self.ssl_context: SSLContext = ssl_context or ssl.create_default_context( + ssl.Purpose.SERVER_AUTH + ) + if not isinstance(self.ssl_context, ssl.SSLContext): + raise TypeError( + "ssl_context must be an instance of ssl.SSLContext, not " + f"{type(self.ssl_context).__name__}" + ) + self.hostname = hostname + self.standard_compatible = standard_compatible + + @override + async def connect(self) -> TLSStream: + stream = await self.connectable.connect() + try: + return await TLSStream.wrap( + stream, + hostname=self.hostname, + ssl_context=self.ssl_context, + standard_compatible=self.standard_compatible, + ) + except BaseException: + await aclose_forcefully(stream) + raise diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/to_interpreter.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/to_interpreter.py new file mode 100644 index 0000000000000000000000000000000000000000..694dbe77bc8581032ee72316afe4e0590311ba00 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/to_interpreter.py @@ -0,0 +1,246 @@ +from __future__ import annotations + +__all__ = ( + "run_sync", + "current_default_interpreter_limiter", +) + +import atexit +import os +import sys +from collections import deque +from collections.abc import Callable +from typing import Any, Final, TypeVar + +from . import current_time, to_thread +from ._core._exceptions import BrokenWorkerInterpreter +from ._core._synchronization import CapacityLimiter +from .lowlevel import RunVar + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +if sys.version_info >= (3, 14): + from concurrent.interpreters import ExecutionFailed, create + + def _interp_call( + func: Callable[..., Any], args: tuple[Any, ...] + ) -> tuple[Any, bool]: + try: + retval = func(*args) + except BaseException as exc: + return exc, True + else: + return retval, False + + class _Worker: + last_used: float = 0 + + def __init__(self) -> None: + self._interpreter = create() + + def destroy(self) -> None: + self._interpreter.close() + + def call( + self, + func: Callable[..., T_Retval], + args: tuple[Any, ...], + ) -> T_Retval: + try: + res, is_exception = self._interpreter.call(_interp_call, func, args) + except ExecutionFailed as exc: + raise BrokenWorkerInterpreter(exc.excinfo) from exc + + if is_exception: + raise res + + return res +elif sys.version_info >= (3, 13): + import _interpqueues + import _interpreters + + UNBOUND: Final = 2 # I have no clue how this works, but it was used in the stdlib + FMT_UNPICKLED: Final = 0 + FMT_PICKLED: Final = 1 + QUEUE_PICKLE_ARGS: Final = (FMT_PICKLED, UNBOUND) + QUEUE_UNPICKLE_ARGS: Final = (FMT_UNPICKLED, UNBOUND) + + _run_func = compile( + """ +import _interpqueues +from _interpreters import NotShareableError +from pickle import loads, dumps, HIGHEST_PROTOCOL + +QUEUE_PICKLE_ARGS = (1, 2) +QUEUE_UNPICKLE_ARGS = (0, 2) + +item = _interpqueues.get(queue_id)[0] +try: + func, args = loads(item) + retval = func(*args) +except BaseException as exc: + is_exception = True + retval = exc +else: + is_exception = False + +try: + _interpqueues.put(queue_id, (retval, is_exception), *QUEUE_UNPICKLE_ARGS) +except NotShareableError: + retval = dumps(retval, HIGHEST_PROTOCOL) + _interpqueues.put(queue_id, (retval, is_exception), *QUEUE_PICKLE_ARGS) + """, + "", + "exec", + ) + + class _Worker: + last_used: float = 0 + + def __init__(self) -> None: + self._interpreter_id = _interpreters.create() + self._queue_id = _interpqueues.create(1, *QUEUE_UNPICKLE_ARGS) + _interpreters.set___main___attrs( + self._interpreter_id, {"queue_id": self._queue_id} + ) + + def destroy(self) -> None: + _interpqueues.destroy(self._queue_id) + _interpreters.destroy(self._interpreter_id) + + def call( + self, + func: Callable[..., T_Retval], + args: tuple[Any, ...], + ) -> T_Retval: + import pickle + + item = pickle.dumps((func, args), pickle.HIGHEST_PROTOCOL) + _interpqueues.put(self._queue_id, item, *QUEUE_PICKLE_ARGS) + exc_info = _interpreters.exec(self._interpreter_id, _run_func) + if exc_info: + raise BrokenWorkerInterpreter(exc_info) + + res = _interpqueues.get(self._queue_id) + (res, is_exception), fmt = res[:2] + if fmt == FMT_PICKLED: + res = pickle.loads(res) + + if is_exception: + raise res + + return res +else: + + class _Worker: + last_used: float = 0 + + def __init__(self) -> None: + raise RuntimeError("subinterpreters require at least Python 3.13") + + def call( + self, + func: Callable[..., T_Retval], + args: tuple[Any, ...], + ) -> T_Retval: + raise NotImplementedError + + def destroy(self) -> None: + pass + + +DEFAULT_CPU_COUNT: Final = 8 # this is just an arbitrarily selected value +MAX_WORKER_IDLE_TIME = ( + 30 # seconds a subinterpreter can be idle before becoming eligible for pruning +) + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") + +_idle_workers = RunVar[deque[_Worker]]("_available_workers") +_default_interpreter_limiter = RunVar[CapacityLimiter]("_default_interpreter_limiter") + + +def _stop_workers(workers: deque[_Worker]) -> None: + for worker in workers: + worker.destroy() + + workers.clear() + + +async def run_sync( + func: Callable[[Unpack[PosArgsT]], T_Retval], + *args: Unpack[PosArgsT], + limiter: CapacityLimiter | None = None, +) -> T_Retval: + """ + Call the given function with the given arguments in a subinterpreter. + + .. warning:: On Python 3.13, the :mod:`concurrent.interpreters` module was not yet + available, so the code path for that Python version relies on an undocumented, + private API. As such, it is recommended to not rely on this function for anything + mission-critical on Python 3.13. + + :param func: a callable + :param args: the positional arguments for the callable + :param limiter: capacity limiter to use to limit the total number of subinterpreters + running (if omitted, the default limiter is used) + :return: the result of the call + :raises BrokenWorkerInterpreter: if there's an internal error in a subinterpreter + + """ + if limiter is None: + limiter = current_default_interpreter_limiter() + + try: + idle_workers = _idle_workers.get() + except LookupError: + idle_workers = deque() + _idle_workers.set(idle_workers) + atexit.register(_stop_workers, idle_workers) + + async with limiter: + try: + worker = idle_workers.pop() + except IndexError: + worker = _Worker() + + try: + return await to_thread.run_sync( + worker.call, + func, + args, + limiter=limiter, + ) + finally: + # Prune workers that have been idle for too long + now = current_time() + while idle_workers: + if now - idle_workers[0].last_used <= MAX_WORKER_IDLE_TIME: + break + + await to_thread.run_sync(idle_workers.popleft().destroy, limiter=limiter) + + worker.last_used = current_time() + idle_workers.append(worker) + + +def current_default_interpreter_limiter() -> CapacityLimiter: + """ + Return the capacity limiter used by default to limit the number of concurrently + running subinterpreters. + + Defaults to the number of CPU cores. + + :return: a capacity limiter object + + """ + try: + return _default_interpreter_limiter.get() + except LookupError: + limiter = CapacityLimiter(os.cpu_count() or DEFAULT_CPU_COUNT) + _default_interpreter_limiter.set(limiter) + return limiter diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/to_process.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/to_process.py new file mode 100644 index 0000000000000000000000000000000000000000..b289234ecfaafc1651dfa76e924291e5a5e9521e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/to_process.py @@ -0,0 +1,266 @@ +from __future__ import annotations + +__all__ = ( + "current_default_process_limiter", + "process_worker", + "run_sync", +) + +import os +import pickle +import subprocess +import sys +from collections import deque +from collections.abc import Callable +from importlib.util import module_from_spec, spec_from_file_location +from typing import TypeVar, cast + +from ._core._eventloop import current_time, get_async_backend, get_cancelled_exc_class +from ._core._exceptions import BrokenWorkerProcess +from ._core._subprocesses import open_process +from ._core._synchronization import CapacityLimiter +from ._core._tasks import CancelScope, fail_after +from .abc import ByteReceiveStream, ByteSendStream, Process +from .lowlevel import RunVar, checkpoint_if_cancelled +from .streams.buffered import BufferedByteReceiveStream + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +WORKER_MAX_IDLE_TIME = 300 # 5 minutes + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") + +_process_pool_workers: RunVar[set[Process]] = RunVar("_process_pool_workers") +_process_pool_idle_workers: RunVar[deque[tuple[Process, float]]] = RunVar( + "_process_pool_idle_workers" +) +_default_process_limiter: RunVar[CapacityLimiter] = RunVar("_default_process_limiter") + + +async def run_sync( # type: ignore[return] + func: Callable[[Unpack[PosArgsT]], T_Retval], + *args: Unpack[PosArgsT], + cancellable: bool = False, + limiter: CapacityLimiter | None = None, +) -> T_Retval: + """ + Call the given function with the given arguments in a worker process. + + If the ``cancellable`` option is enabled and the task waiting for its completion is + cancelled, the worker process running it will be abruptly terminated using SIGKILL + (or ``terminateProcess()`` on Windows). + + :param func: a callable + :param args: positional arguments for the callable + :param cancellable: ``True`` to allow cancellation of the operation while it's + running + :param limiter: capacity limiter to use to limit the total amount of processes + running (if omitted, the default limiter is used) + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + :return: an awaitable that yields the return value of the function. + + """ + + async def send_raw_command(pickled_cmd: bytes) -> object: + try: + await stdin.send(pickled_cmd) + response = await buffered.receive_until(b"\n", 50) + status, length = response.split(b" ") + if status not in (b"RETURN", b"EXCEPTION"): + raise RuntimeError( + f"Worker process returned unexpected response: {response!r}" + ) + + pickled_response = await buffered.receive_exactly(int(length)) + except BaseException as exc: + workers.discard(process) + try: + process.kill() + with CancelScope(shield=True): + await process.aclose() + except ProcessLookupError: + pass + + if isinstance(exc, get_cancelled_exc_class()): + raise + else: + raise BrokenWorkerProcess from exc + + retval = pickle.loads(pickled_response) + if status == b"EXCEPTION": + assert isinstance(retval, BaseException) + raise retval + else: + return retval + + # First pickle the request before trying to reserve a worker process + await checkpoint_if_cancelled() + request = pickle.dumps(("run", func, args), protocol=pickle.HIGHEST_PROTOCOL) + + # If this is the first run in this event loop thread, set up the necessary variables + try: + workers = _process_pool_workers.get() + idle_workers = _process_pool_idle_workers.get() + except LookupError: + workers = set() + idle_workers = deque() + _process_pool_workers.set(workers) + _process_pool_idle_workers.set(idle_workers) + get_async_backend().setup_process_pool_exit_at_shutdown(workers) + + async with limiter or current_default_process_limiter(): + # Pop processes from the pool (starting from the most recently used) until we + # find one that hasn't exited yet + process: Process + while idle_workers: + process, idle_since = idle_workers.pop() + if process.returncode is None: + stdin = cast(ByteSendStream, process.stdin) + buffered = BufferedByteReceiveStream( + cast(ByteReceiveStream, process.stdout) + ) + + # Prune any other workers that have been idle for WORKER_MAX_IDLE_TIME + # seconds or longer + now = current_time() + killed_processes: list[Process] = [] + while idle_workers: + if now - idle_workers[0][1] < WORKER_MAX_IDLE_TIME: + break + + process_to_kill, idle_since = idle_workers.popleft() + process_to_kill.kill() + workers.remove(process_to_kill) + killed_processes.append(process_to_kill) + + with CancelScope(shield=True): + for killed_process in killed_processes: + await killed_process.aclose() + + break + + workers.remove(process) + else: + command = [sys.executable, "-u", "-m", __name__] + process = await open_process( + command, stdin=subprocess.PIPE, stdout=subprocess.PIPE + ) + try: + stdin = cast(ByteSendStream, process.stdin) + buffered = BufferedByteReceiveStream( + cast(ByteReceiveStream, process.stdout) + ) + with fail_after(20): + message = await buffered.receive(6) + + if message != b"READY\n": + raise BrokenWorkerProcess( + f"Worker process returned unexpected response: {message!r}" + ) + + main_module_path = getattr(sys.modules["__main__"], "__file__", None) + pickled = pickle.dumps( + ("init", sys.path, main_module_path), + protocol=pickle.HIGHEST_PROTOCOL, + ) + await send_raw_command(pickled) + except (BrokenWorkerProcess, get_cancelled_exc_class()): + raise + except BaseException as exc: + process.kill() + raise BrokenWorkerProcess( + "Error during worker process initialization" + ) from exc + + workers.add(process) + + with CancelScope(shield=not cancellable): + try: + return cast(T_Retval, await send_raw_command(request)) + finally: + if process in workers: + idle_workers.append((process, current_time())) + + +def current_default_process_limiter() -> CapacityLimiter: + """ + Return the capacity limiter that is used by default to limit the number of worker + processes. + + :return: a capacity limiter object + + """ + try: + return _default_process_limiter.get() + except LookupError: + limiter = CapacityLimiter(os.cpu_count() or 2) + _default_process_limiter.set(limiter) + return limiter + + +def process_worker() -> None: + # Redirect standard streams to os.devnull so that user code won't interfere with the + # parent-worker communication + stdin = sys.stdin + stdout = sys.stdout + sys.stdin = open(os.devnull) + sys.stdout = open(os.devnull, "w") + + stdout.buffer.write(b"READY\n") + while True: + retval = exception = None + try: + command, *args = pickle.load(stdin.buffer) + except EOFError: + return + except BaseException as exc: + exception = exc + else: + if command == "run": + func, args = args + try: + retval = func(*args) + except BaseException as exc: + exception = exc + elif command == "init": + main_module_path: str | None + sys.path, main_module_path = args + del sys.modules["__main__"] + if main_module_path and os.path.isfile(main_module_path): + # Load the parent's main module but as __mp_main__ instead of + # __main__ (like multiprocessing does) to avoid infinite recursion + try: + spec = spec_from_file_location("__mp_main__", main_module_path) + if spec and spec.loader: + main = module_from_spec(spec) + spec.loader.exec_module(main) + sys.modules["__main__"] = main + except BaseException as exc: + exception = exc + try: + if exception is not None: + status = b"EXCEPTION" + pickled = pickle.dumps(exception, pickle.HIGHEST_PROTOCOL) + else: + status = b"RETURN" + pickled = pickle.dumps(retval, pickle.HIGHEST_PROTOCOL) + except BaseException as exc: + exception = exc + status = b"EXCEPTION" + pickled = pickle.dumps(exc, pickle.HIGHEST_PROTOCOL) + + stdout.buffer.write(b"%s %d\n" % (status, len(pickled))) + stdout.buffer.write(pickled) + + # Respect SIGTERM + if isinstance(exception, SystemExit): + raise exception + + +if __name__ == "__main__": + process_worker() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/to_thread.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/to_thread.py new file mode 100644 index 0000000000000000000000000000000000000000..4be5b7190ad9142a1aeb684bff0bd40245f71fb6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anyio/to_thread.py @@ -0,0 +1,78 @@ +from __future__ import annotations + +__all__ = ( + "run_sync", + "current_default_thread_limiter", +) + +import sys +from collections.abc import Callable +from typing import TypeVar +from warnings import warn + +from ._core._eventloop import get_async_backend +from .abc import CapacityLimiter + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") + + +async def run_sync( + func: Callable[[Unpack[PosArgsT]], T_Retval], + *args: Unpack[PosArgsT], + abandon_on_cancel: bool = False, + cancellable: bool | None = None, + limiter: CapacityLimiter | None = None, +) -> T_Retval: + """ + Call the given function with the given arguments in a worker thread. + + If the ``cancellable`` option is enabled and the task waiting for its completion is + cancelled, the thread will still run its course but its return value (or any raised + exception) will be ignored. + + :param func: a callable + :param args: positional arguments for the callable + :param abandon_on_cancel: ``True`` to abandon the thread (leaving it to run + unchecked on own) if the host task is cancelled, ``False`` to ignore + cancellations in the host task until the operation has completed in the worker + thread + :param cancellable: deprecated alias of ``abandon_on_cancel``; will override + ``abandon_on_cancel`` if both parameters are passed + :param limiter: capacity limiter to use to limit the total amount of threads running + (if omitted, the default limiter is used) + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + :return: an awaitable that yields the return value of the function. + + """ + if cancellable is not None: + abandon_on_cancel = cancellable + warn( + "The `cancellable=` keyword argument to `anyio.to_thread.run_sync` is " + "deprecated since AnyIO 4.1.0; use `abandon_on_cancel=` instead", + DeprecationWarning, + stacklevel=2, + ) + + return await get_async_backend().run_sync_in_worker_thread( + func, args, abandon_on_cancel=abandon_on_cancel, limiter=limiter + ) + + +def current_default_thread_limiter() -> CapacityLimiter: + """ + Return the capacity limiter that is used by default to limit the number of + concurrent threads. + + :return: a capacity limiter object + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + return get_async_backend().current_default_thread_limiter() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore-0.2.dist-info/INSTALLER b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore-0.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore-0.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore-0.2.dist-info/METADATA b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore-0.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..57ef0301e4d663932dccf0b5b8d663d6f0a1234c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore-0.2.dist-info/METADATA @@ -0,0 +1,71 @@ +Metadata-Version: 2.4 +Name: anykeystore +Version: 0.2 +Summary: A key-value store supporting multiple backends. +Home-page: +Author: Michael Merickel +Author-email: oss@m.merickel.org +License: MIT +Classifier: Development Status :: 3 - Alpha +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 2.6 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3.2 +Classifier: Topic :: Database +Classifier: License :: OSI Approved :: MIT License +License-File: LICENSE.txt +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: summary + +=========== +anykeystore +=========== + +A generic interface wrapping multiple different backends to provide a +consistent key-value storage API. This library is intended to be used by other +libraries that require some form of generic storage. + +Usage +===== + +:: + + from anykeystore import create_store + + store = create_store('sqla', url='postgres+psycopg2://bob@localhost/mydb') + + settings = { + 'mystore.store': 'sqla', + 'mystore.url': 'mysql://bob@localhost/mydb', + } + store = create_store_from_settings(settings, prefix='mystore.') + +Supported Backends +================== + +- memory + +- sqlalchemy + + requires: sqlalchemy + +- mongodb + + requires: pymongo + +- redis + + requires: redis-py + +- memcached + + requires: python-memcached, or python3-memcached + + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore-0.2.dist-info/RECORD b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore-0.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..33e226f2146e31a50cde03e3373e914976bd5725 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore-0.2.dist-info/RECORD @@ -0,0 +1,53 @@ +anykeystore-0.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +anykeystore-0.2.dist-info/METADATA,sha256=OtkwhabRM4mWxFb-CWe1FOGW23O47uW_kGVRzWocb28,1508 +anykeystore-0.2.dist-info/RECORD,, +anykeystore-0.2.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92 +anykeystore-0.2.dist-info/licenses/LICENSE.txt,sha256=xDLpEEJOuu2lkvVMhPUyNoPYGWsDOa4vIsau76vG9s8,1060 +anykeystore-0.2.dist-info/top_level.txt,sha256=3NtVqFD9V2SuM6jmjxV9StYdCbv7cirpcHgNTy-fgi0,12 +anykeystore/__init__.py,sha256=glE4kxBxUvMLtTFv9mtf9O7QydlwL_X1Zp_n85iCLcY,84 +anykeystore/__pycache__/__init__.cpython-310.pyc,, +anykeystore/__pycache__/compat.cpython-310.pyc,, +anykeystore/__pycache__/exceptions.cpython-310.pyc,, +anykeystore/__pycache__/interfaces.cpython-310.pyc,, +anykeystore/__pycache__/store.cpython-310.pyc,, +anykeystore/__pycache__/utils.cpython-310.pyc,, +anykeystore/backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +anykeystore/backends/__pycache__/__init__.cpython-310.pyc,, +anykeystore/backends/__pycache__/memcached.cpython-310.pyc,, +anykeystore/backends/__pycache__/memory.cpython-310.pyc,, +anykeystore/backends/__pycache__/mongodb.cpython-310.pyc,, +anykeystore/backends/__pycache__/redis.cpython-310.pyc,, +anykeystore/backends/__pycache__/sqla.cpython-310.pyc,, +anykeystore/backends/memcached.py,sha256=a-cPMyE1eIEKfkznLSjYRWTIghW-YLs9jJuX8ts7aHs,1775 +anykeystore/backends/memory.py,sha256=IthTIs0-OuXWojH1t9qElTIlSOKOFnBJYCIlRMI5rgg,1435 +anykeystore/backends/mongodb.py,sha256=C9hFEh6jLIP08sT836nmS4T6FMPGDfPyUkF04YWhpR8,2408 +anykeystore/backends/redis.py,sha256=sSHgYm1GXn-g4MyfwYndPaLC0RdrD2VmWuvBvvRV0eQ,1937 +anykeystore/backends/sqla.py,sha256=VbJxEHpxRDWbgQHV401mH-NXjiUAW8qz4HPJX6glvUU,4025 +anykeystore/compat.py,sha256=kfeCel5zmJxLzdwdzuqNp-hhYudphJxNZGVYf4nyG6w,589 +anykeystore/exceptions.py,sha256=bteT5dxs3i9QGARiKIqDAIQ4BzIPx5kyygGsrkrbwws,192 +anykeystore/interfaces.py,sha256=YgE6CR4dpYF3MYKiAZcy06TOhoW8mgskDiTlyPyGx7Y,1605 +anykeystore/store.py,sha256=EaPBKqkEKTI3bPGan9MwLIvY_B2JMROUOcv5xAhoyFQ,1445 +anykeystore/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +anykeystore/tests/__pycache__/__init__.cpython-310.pyc,, +anykeystore/tests/__pycache__/test_store.cpython-310.pyc,, +anykeystore/tests/__pycache__/test_utils.cpython-310.pyc,, +anykeystore/tests/integration/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +anykeystore/tests/integration/__pycache__/__init__.cpython-310.pyc,, +anykeystore/tests/integration/__pycache__/tests.cpython-310.pyc,, +anykeystore/tests/integration/testing.ini,sha256=Z5DgI0I1QtITn-0V887HVn4ZyKAG8rnz9GyvHRShTrk,407 +anykeystore/tests/integration/tests.py,sha256=305Cg5cZjBIm9DDbUml67paZ3A0wtFaaJ0_GNArhk18,2035 +anykeystore/tests/test_backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +anykeystore/tests/test_backends/__pycache__/__init__.cpython-310.pyc,, +anykeystore/tests/test_backends/__pycache__/test_memcached.cpython-310.pyc,, +anykeystore/tests/test_backends/__pycache__/test_memory.cpython-310.pyc,, +anykeystore/tests/test_backends/__pycache__/test_mongodb.cpython-310.pyc,, +anykeystore/tests/test_backends/__pycache__/test_redis.cpython-310.pyc,, +anykeystore/tests/test_backends/__pycache__/test_sqla.cpython-310.pyc,, +anykeystore/tests/test_backends/test_memcached.py,sha256=HirK_l58798rRTQ_2rjWcm69zuQQcS1tQqbC1dFbyIM,2689 +anykeystore/tests/test_backends/test_memory.py,sha256=8oV_7wi632pUC4dEKUvGd1oW_aJ2KUAxSEY8FWBiuy4,899 +anykeystore/tests/test_backends/test_mongodb.py,sha256=tBG3x4LmUcaErShwasPIDgOceIRdGEE3yMICSPmfM94,5657 +anykeystore/tests/test_backends/test_redis.py,sha256=1Q8raMN3SkOcmcDQwQDuu9pGA9nsfCMyuJy__-9WkSI,3042 +anykeystore/tests/test_backends/test_sqla.py,sha256=XV8trTEKeC2Hr9jvC4g3CoTbbE-LEyKml8O3gGHui6k,2866 +anykeystore/tests/test_store.py,sha256=rfwVhXPOUPyyFAtoRW_3TztlisabwqUna7bxUZX-R04,1132 +anykeystore/tests/test_utils.py,sha256=unMFG1NcomOoze5a5T6Dj3956l5VlkLmBpg-Nb4cPbs,957 +anykeystore/utils.py,sha256=dU2d1zypkxd6NLYfCN6zNSSJj0rDbDA-Sjin9-RkWmY,368 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore-0.2.dist-info/WHEEL b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore-0.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..0885d055554a9bce53952482316a33cebf0845e4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore-0.2.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.10.2) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore-0.2.dist-info/licenses/LICENSE.txt b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore-0.2.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..078ffe7aa74053f314184ad20c0af47565c12ec1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore-0.2.dist-info/licenses/LICENSE.txt @@ -0,0 +1,19 @@ +Copyright (c) 2012 Michael Merickel + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore-0.2.dist-info/top_level.txt b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore-0.2.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..3101cc100459d661fbd6c8ebb943c8350bcc3ccc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore-0.2.dist-info/top_level.txt @@ -0,0 +1 @@ +anykeystore diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..013ff12e7317a5ae3d6c84b8d94c1d6a4b23c33b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/__init__.py @@ -0,0 +1,4 @@ +from anykeystore.store import ( + create_store, + create_store_from_settings, +) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/backends/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/backends/memcached.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/backends/memcached.py new file mode 100644 index 0000000000000000000000000000000000000000..8fd0a52d53b865ed1734d0f1588182ccbd92ff6e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/backends/memcached.py @@ -0,0 +1,60 @@ +import logging + +from anykeystore.compat import basestring +from anykeystore.interfaces import KeyValueStore +from anykeystore.utils import coerce_timedelta, splitlines + + +log = logging.getLogger(__name__) + +class MemcachedStore(KeyValueStore): + def __init__(self, + servers=('localhost:11211',), + key_prefix='anykeystore.', + backend_api=None): + if isinstance(servers, basestring): + servers = splitlines(servers) + self.servers = servers + self.key_prefix = key_prefix + self.backend_api = backend_api + + @classmethod + def backend_api(cls): + try: + import memcache + except ImportError: # pragma: no cover + # fall back for Google App Engine -- hasnt been tested though + from google.appengine.api import memcache + return memcache + + def _get_conn(self): + """The Memcached connection, cached for this call""" + return self.backend_api.Client(self.servers) + + def _make_key(self, key): + return '%s%s' % (self.key_prefix, key) + + def retrieve(self, key): + data = self._get_conn().get(self._make_key(key)) + if data: + return data + raise KeyError + + def store(self, key, value, expires=None): + key = self._make_key(key) + log.debug('Servers %s storing %s=%s' % (self.servers, key, value)) + + expiration = None + if expires is not None: + expiration = coerce_timedelta(expires).seconds + self._get_conn().set(key, value, expiration or 0) + + def delete(self, key): + key = self._make_key(key) + log.debug('Deleting %s', key) + self._get_conn().delete(key) + + def purge_expired(self): + pass + +backend = MemcachedStore diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/backends/memory.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/backends/memory.py new file mode 100644 index 0000000000000000000000000000000000000000..4343bae0c081296a410dd2f59a05962fa2d6caa2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/backends/memory.py @@ -0,0 +1,47 @@ +from datetime import datetime + +from anykeystore.compat import iteritems_ +from anykeystore.interfaces import KeyValueStore +from anykeystore.utils import coerce_timedelta + +class MemoryStore(KeyValueStore): + """ In-memory storage. Not persistent.""" + def __init__(self, backend_api=dict): + self.backend_api = backend_api + self._store = self.backend_api() + + @classmethod + def backend_api(cls): + return dict + + def retrieve(self, key): + data = self._store.get(key) + if data: + value, expires = data + if expires is None or datetime.utcnow() < expires: + return value + raise KeyError + + def store(self, key, value, expires=None): + expiration = None + if expires is not None: + expiration = datetime.utcnow() + coerce_timedelta(expires) + self._store[key] = (value, expiration) + + def delete(self, key): + if key in self._store: + del self._store[key] + + def purge_expired(self): + now = datetime.utcnow() + to_delete = [] + + # Record the keys to delete, there may be a lot, so we use iteritems + # which doesn't let us change it while iterating + for key, value in iteritems_(self._store): + if value[1] is not None and now > value[1]: + to_delete.append(key) + for key in to_delete: + del self._store[key] + +backend = MemoryStore diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/backends/mongodb.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/backends/mongodb.py new file mode 100644 index 0000000000000000000000000000000000000000..5ad8f9fafbb746389372e2c6d71d1ab7d396a6b4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/backends/mongodb.py @@ -0,0 +1,82 @@ +from datetime import datetime + +from anykeystore.compat import pickle +from anykeystore.interfaces import KeyValueStore +from anykeystore.utils import coerce_timedelta + + +class MongoDBStore(KeyValueStore): + """ Simple storage via MongoDB. + + :param db: The name of the database. + :param collection: Optional (default="anykeystore"). + The document collection within the database. + :param host: MongoDB server host. + :param port: MongoDB server port. + """ + + def __init__(self, + db, + collection='anykeystore', + host='localhost', + port=27017, + backend_api=None): + self.host = host + self.port = int(port) + self.db = db + self.collection = collection + self.backend_api = backend_api + + @classmethod + def backend_api(cls): + import pymongo + import pymongo.binary + return pymongo + + def _get_conn(self): + db_conn = self.backend_api.Connection( + self.host, self.port, slave_okay=False) + conn = db_conn[self.db] + if not self.collection in conn.collection_names(): + conn.create_collection(self.collection) + return conn + + def retrieve(self, key): + c = self._get_conn() + data = c[self.collection].find_one({'key': key}) + if data: + expires = data['expires'] + if expires is None or datetime.utcnow() < expires: + return pickle.loads(data['value']) + raise KeyError + + def store(self, key, value, expires=None): + expiration = None + if expires is not None: + expiration = datetime.utcnow() + coerce_timedelta(expires) + c = self._get_conn() + api = self.backend_api + c[self.collection].update( + {'key': key}, + { + '$set': { + 'value': api.binary.Binary(pickle.dumps(value)), + 'expires': expiration, + }, + }, + upsert=True, + safe=True, + ) + + def delete(self, key): + c = self._get_conn() + c[self.collection].remove({'key': key}, safe=True) + + def purge_expired(self): + c = self._get_conn() + c[self.collection].remove( + {'expires': {'$lte': datetime.utcnow()}}, + safe=True, + ) + +backend = MongoDBStore diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/backends/redis.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/backends/redis.py new file mode 100644 index 0000000000000000000000000000000000000000..5fbc0db6e543a3cc1c169d1abc6437ecb8309937 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/backends/redis.py @@ -0,0 +1,63 @@ +from __future__ import absolute_import + +from anykeystore.compat import pickle +from anykeystore.interfaces import KeyValueStore +from anykeystore.utils import coerce_timedelta + + +class RedisStore(KeyValueStore): + """ Simple storage via Redis. + + :param db: The name of the redis database. + :param host: Redis server host. + :param port: Redis server port. + :param key_prefix: Key prefix to avoid colliding with other parts of + the redis key/value store. + :param backend_api: Specific redis implementation to use. + """ + + def __init__(self, db=0, host='localhost', port=6379, + key_prefix='anykeystore.', backend_api=None): + self.host = host + self.port = int(port) + self.db = int(db) + self.key_prefix = key_prefix or '' + self.backend_api = backend_api + + @classmethod + def backend_api(cls): + return __import__('redis') + + def _make_key(self, key): + return '%s%s' % (self.key_prefix, key) + + _pool = None + def _get_conn(self): + """The Redis connection, cached for this call""" + api = self.backend_api + if self._pool is None: + self._pool = api.ConnectionPool( + host=self.host, port=self.port, db=self.db) + return api.Redis(connection_pool=self._pool) + + def retrieve(self, key): + data = self._get_conn().get(self._make_key(key)) + if data: + return pickle.loads(data) + raise KeyError + + def store(self, key, value, expires=None): + key = self._make_key(key) + c = self._get_conn() + c.set(key, pickle.dumps(value, protocol=pickle.HIGHEST_PROTOCOL)) + if expires is not None: + expires = coerce_timedelta(expires) + c.expire(key, expires.seconds) + + def delete(self, key): + self._get_conn().delete(self._make_key(key)) + + def purge_expired(self): + pass + +backend = RedisStore diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/backends/sqla.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/backends/sqla.py new file mode 100644 index 0000000000000000000000000000000000000000..1a56c316d65c2ffc6da41c751eeabfa17ec2c02a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/backends/sqla.py @@ -0,0 +1,122 @@ +from datetime import datetime + +from anykeystore.interfaces import KeyValueStore +from anykeystore.utils import coerce_timedelta + + +class SQLStore(KeyValueStore): + """ Simple storage via SQLAlchemy. + + The store will automatically create a table object if one is not + supplied. The automatically generated table is shown below. If a + table is supplied directly, it must support the required columns + `key`, `value`, and `expires`. + + .. code-block:: python + + table = Table(table_name, metadata, + Column('key', String(200), primary_key=True, nullable=False), + Column('value', Text(), nullable=False), + Column('expires', DateTime()), + ) + + :param engine: A SQLAlchemy engine. + :param table: Optional. The SQLAlchemy Table instance to be used for + storage. If this isn't supplied, a table is generated + automatically. + :type table: sqlalchemy.Table + :param table_name: Optional. The name of the table. + :param metadata: Optional. The SQLAlchemy MetaData instance to hook the + generated table into. + :type metadata: sqlalchemy.MetaData + :param backend_api: Should be SQLAlchemy. + """ + def __init__(self, url, **kw): + self.url = url + self.table = kw.pop('table', None) + self.backend_api = api = kw.pop('backend_api') + if not self.table: + table_name = kw.pop('table_name', 'key_storage') + meta = kw.pop('metadata', api.MetaData()) + self.table = self._make_table(table_name, meta) + kw['url'] = url + self.engine = api.engine_from_config(kw, prefix='') + + @classmethod + def backend_api(cls): + import sqlalchemy + import sqlalchemy.exc + return sqlalchemy + + def _make_table(self, name, meta): + api = self.backend_api + table = api.Table(name, meta, + api.Column( + 'key', api.String(256), primary_key=True, nullable=False), + api.Column('value', api.PickleType(), nullable=False), + api.Column('expires', api.DateTime()), + ) + return table + + def _create_table(self): + self.table.create(checkfirst=True, bind=self.engine) + self._created = True + + _created = False + def _get_conn(self): + if not self._created: + self._create_table() + return self.engine.connect() + + def retrieve(self, key): + c = self._get_conn() + api = self.backend_api + try: + data = c.execute(api.select( + [self.table.c.value, self.table.c.expires], + self.table.c.key == key)).fetchone() + if data: + value, expires = data + if expires is None or datetime.utcnow() < expires: + return value + finally: + c.close() + raise KeyError + + def _insert_or_replace(self, c, key, value, expires): + try: + c.execute( + self.table.insert(), key=key, value=value, expires=expires) + except self.backend_api.exc.IntegrityError: + c.execute( + self.table.update(), key=key, value=value, expires=expires) + + def store(self, key, value, expires=None): + expiration = None + if expires is not None: + expiration = datetime.utcnow() + coerce_timedelta(expires) + c = self._get_conn() + try: + self._insert_or_replace(c, key, value, expiration) + finally: + c.close() + + def delete(self, key): + c = self._get_conn() + api = self.backend_api + try: + c.execute(api.delete(self.table, self.table.c.key == key)) + finally: + c.close() + + def purge_expired(self): + c = self._get_conn() + api = self.backend_api + try: + c.execute( + api.delete( + self.table, self.table.c.expires < datetime.utcnow())) + finally: + c.close() + +backend = SQLStore diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/compat.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..0c49f79177e7e2d31b2bf5a8d71bc2e01f01302a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/compat.py @@ -0,0 +1,29 @@ +import sys + +# True if we are running on Python 3. +PY3 = sys.version_info[0] == 3 + +try: + import cPickle as pickle +except ImportError: # pragma: no cover + import pickle + +if PY3: # pragma: no cover + def iteritems_(d): + return d.items() + def itervalues_(d): + return d.values() + def iterkeys_(d): + return d.keys() +else: + def iteritems_(d): + return d.iteritems() + def itervalues_(d): + return d.itervalues() + def iterkeys_(d): + return d.iterkeys() + +if PY3: #pragma: no cover + basestring = str +else: + basestring = basestring diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/exceptions.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..24de2c9e6d85fbe8160108394a4a1ea7eba07ede --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/exceptions.py @@ -0,0 +1,6 @@ +class ConfigurationError(Exception): + """ Raised when configuration fails on a backend.""" + + def __init__(self, message, exc=None): + self.message = message + self.exc = exc diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/interfaces.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/interfaces.py new file mode 100644 index 0000000000000000000000000000000000000000..098965b806e549970f14b63a0e2b231d3c37b0f7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/interfaces.py @@ -0,0 +1,41 @@ +class KeyValueStore(object): + """ Backend interface for storing and retrieving data.""" + + def retrieve(self, key): + """ This method retrieves the data for a key from the storage. + + :param key: The key to retrieve. Keys are always ascii-safe strings. + """ + raise NotImplementedError # pragma: no cover + + def store(self, key, value, expires=None): + """ This method stores value in the storage. + + For backend's that don't automatically expire data, some record should + be kept with the key's data marking when it should have expired so that + :meth:`~velruse.store.interface.purge_expired` can properly purge + old data. + + :param key: The key to store the value under. + :param value: The data to store. + :param expires: Optional expiration time in seconds or a + :meth:`datetime.timedelta` object before the stored + data should be removed. + """ + raise NotImplementedError # pragma: no cover + + def delete(self, key): + """ This method deletes data from the storage. + + :param key: The key of the data to be removed. + """ + raise NotImplementedError # pragma: no cover + + def purge_expired(self): + """ This method purges all expired data from the storage. + + All expired data should be purged from the backend when this method + is called. Backends that automatically expire old data must still + implement this method, but can do nothing. + """ + raise NotImplementedError # pragma: no cover diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/store.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/store.py new file mode 100644 index 0000000000000000000000000000000000000000..0bc72c8bc1d2a3023415af2c40c937a8506dc927 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/store.py @@ -0,0 +1,47 @@ +import sys + +from anykeystore.exceptions import ConfigurationError + +def _load_backend(name): + try: + module_name = 'anykeystore.backends.%s' % name + __import__(module_name) + module = sys.modules[module_name] + if hasattr(module, 'backend'): + backend = module.backend + else: + module = _load_entry_point(name) + if module is None: + raise ConfigurationError( + 'Could not determine backend for "%s"' % name) + return backend + except ImportError: + module = _load_entry_point(name) + if module is not None: + return module + raise ConfigurationError( + 'Could not determine backend for "%s"' % name) + +def _load_entry_point(name): + try: + import pkg_resources + except ImportError: + return None + + for res in pkg_resources.iter_entry_points('anykeystore.backends'): + if res.name == name: + return res.load() + +def create_store(name, **kwargs): + backend_cls = _load_backend(name) + backend_api = backend_cls.backend_api() + kwargs.setdefault('backend_api', backend_api) + return backend_cls(**kwargs) + +def create_store_from_settings(settings, prefix='', **kwargs): + plen = len(prefix) + for k, v in settings.items(): + if k.startswith(prefix): + kwargs[k[plen:]] = v + name = kwargs.pop('store') + return create_store(name, **kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/integration/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/integration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/integration/testing.ini b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/integration/testing.ini new file mode 100644 index 0000000000000000000000000000000000000000..0c20f62561f4fcc7620511d8224e4af66a95fcb3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/integration/testing.ini @@ -0,0 +1,23 @@ +[testconfig] + +memory.store = memory + +sqla.store = sqla +sqla.url = sqlite:// + +memcached.store = memcached +memcached.key_prefix = anykeytest. +memcached.servers = + localhost:11211 + +mongodb.store = mongodb +mongodb.db = test +mongodb.collection = anykeytest +mongodb.host = localhost +mongodb.port = 27017 + +redis.store = redis +redis.db = 0 +redis.key_prefix = anykeytest. +redis.host = localhost +redis.port = 6379 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/integration/tests.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/integration/tests.py new file mode 100644 index 0000000000000000000000000000000000000000..b2a84123944a806ec86eb3ef3fe7ac7fef944b08 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/integration/tests.py @@ -0,0 +1,78 @@ +import os +import time +import unittest2 as unittest +from ConfigParser import ConfigParser + + +config = {} + +def setUpModule(): + inipath = os.environ.get('TEST_INI', 'testing.ini') + if os.path.isfile(inipath): + parser = ConfigParser() + parser.read(inipath) + + config.update(parser.items('testconfig')) + + else: + raise unittest.SkipTest( + 'could not find testing.ini required to run integration tests') + +class BackendTests(object): + expires = -1 + wait = 0 + + def _makeOne(self): + from anykeystore import create_store_from_settings + try: + store = create_store_from_settings(config, prefix=self.key + '.') + except ImportError as e: + raise unittest.SkipTest(str(e)) + return store + + def test_it(self): + store = self._makeOne() + store.store('foo', 'bar') + value = store.retrieve('foo') + self.assertEqual(value, 'bar') + + def test_delete(self): + store = self._makeOne() + store.store('foo', 'bar') + store.delete('foo') + self.assertRaises(KeyError, store.retrieve, 'foo') + + def test_retrieve_expired(self): + store = self._makeOne() + store.store('foo', 'bar', expires=self.expires) + time.sleep(self.wait) + self.assertRaises(KeyError, store.retrieve, 'foo') + + def test_purge(self): + store = self._makeOne() + store.store('foo', 'bar', expires=self.expires) + time.sleep(self.wait) + store.purge_expired() + self.assertRaises(KeyError, store.retrieve, 'foo') + +class TestMemory(unittest.TestCase, BackendTests): + key = 'memory' + +class TestSQLA(unittest.TestCase, BackendTests): + key = 'sqla' + +class TestMemcached(unittest.TestCase, BackendTests): + key = 'memcached' + expires = 1 + wait = 2 + +class TestMongoDB(unittest.TestCase, BackendTests): + key = 'mongodb' + +class TestRedis(unittest.TestCase, BackendTests): + key = 'redis' + expires = 1 + wait = 2 + +if __name__ == '__main__': + unittest.main() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/test_backends/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/test_backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/test_backends/test_memcached.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/test_backends/test_memcached.py new file mode 100644 index 0000000000000000000000000000000000000000..5243dbaaae922617dc4dd058e65ea51fdbaaef50 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/test_backends/test_memcached.py @@ -0,0 +1,85 @@ +import unittest2 as unittest +from mock import MagicMock + +class TestMemcachedStore(unittest.TestCase): + + def _makeOne(self, + servers='myhost:8080', + key_prefix='key.', + backend_api=None): + from anykeystore.backends.memcached import MemcachedStore + store = MemcachedStore( + servers=servers, key_prefix=key_prefix, backend_api=backend_api) + return store + + def _makeClient(self): + client = MagicMock(spec=['get', 'set', 'delete']) + return client + + def test_init_with_server_string(self): + store = self._makeOne(servers='myhost:8080\n yourhost:6790') + self.assertEqual(store.servers, ['myhost:8080', 'yourhost:6790']) + + def test_init_with_server_list(self): + store = self._makeOne(servers=['myhost:8080', 'yourhost:6790']) + self.assertEqual(store.servers, ['myhost:8080', 'yourhost:6790']) + + def test__get_conn(self): + api = MagicMock(spec=['Client']) + api.Client.return_value = 'myconn' + + store = self._makeOne(backend_api=api) + conn = store._get_conn() + + self.assertEqual(conn, 'myconn') + api.Client.assert_called_with(['myhost:8080']) + + def test_store(self): + store = self._makeOne() + client = self._makeClient() + store._get_conn = MagicMock(return_value=client) + + store.store('foo', 'bar') + + client.set.assert_called_with('key.foo', 'bar', 0) + + def test_store_with_expires(self): + store = self._makeOne() + client = self._makeClient() + store._get_conn = MagicMock(return_value=client) + + store.store('foo', 'bar', expires=5) + + client.set.assert_called_with('key.foo', 'bar', 5) + + def test_delete(self): + store = self._makeOne() + client = self._makeClient() + store._get_conn = MagicMock(return_value=client) + + store.delete('foo') + + client.delete.assert_called_with('key.foo') + + def test_retrieve(self): + store = self._makeOne() + client = self._makeClient() + client.get.return_value = 'bar' + store._get_conn = MagicMock(return_value=client) + + result = store.retrieve('foo') + + self.assertEqual(result, 'bar') + client.get.assert_called_with('key.foo') + + def test_retrieve_expired(self): + store = self._makeOne() + client = self._makeClient() + client.get.return_value = None + store._get_conn = MagicMock(return_value=client) + self.assertRaises(KeyError, store.retrieve, 'foo') + client.get.assert_called_with('key.foo') + + def test_purge(self): + store = self._makeOne() + store.purge_expired() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/test_backends/test_memory.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/test_backends/test_memory.py new file mode 100644 index 0000000000000000000000000000000000000000..6cc87094ac351066c8371da44abe875dab4af7c5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/test_backends/test_memory.py @@ -0,0 +1,30 @@ +import unittest2 as unittest + +class TestMemoryStore(unittest.TestCase): + + def _makeOne(self): + from anykeystore.backends.memory import MemoryStore + return MemoryStore() + + def test_it(self): + store = self._makeOne() + store.store('foo', 'bar') + value = store.retrieve('foo') + self.assertEqual(value, 'bar') + + def test_it_delete(self): + store = self._makeOne() + store.store('foo', 'bar') + store.delete('foo') + self.assertRaises(KeyError, store.retrieve, 'foo') + + def test_it_old(self): + store = self._makeOne() + store.store('foo', 'bar', expires=-1) + self.assertRaises(KeyError, store.retrieve, 'foo') + + def test_it_purge(self): + store = self._makeOne() + store.store('foo', 'bar', expires=-1) + store.purge_expired() + self.assertRaises(KeyError, store.retrieve, 'foo') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/test_backends/test_mongodb.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/test_backends/test_mongodb.py new file mode 100644 index 0000000000000000000000000000000000000000..e7d91dc58354c2cb1da353cff7de3de6a58903a3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/test_backends/test_mongodb.py @@ -0,0 +1,152 @@ +from datetime import datetime, timedelta + +import unittest2 as unittest +from mock import MagicMock, patch + +class TestMongoStore(unittest.TestCase): + + def _makeOne(self, + db='testdb', + collection='keystore', + host='localhost', + port=8080, + backend_api=None): + from anykeystore.backends.mongodb import MongoDBStore + store = MongoDBStore(db=db, collection=collection, host=host, + port=port, backend_api=backend_api) + return store + + def _makeConnection(self): + conn = MagicMock(spec=[ + 'create_collection', 'collection_names', '__getitem__']) + return conn + + def test__get_conn(self): + conn = self._makeConnection() + conn.collection_names.return_value = ['keystore'] + + db_conn = MagicMock() + db_conn.__getitem__.return_value = conn + + api = MagicMock(spec=['Connection', 'binary']) + api.Connection.return_value = db_conn + + store = self._makeOne(backend_api=api) + result = store._get_conn() + + self.assertEqual(result, conn) + api.Connection.assert_called_with('localhost', 8080, slave_okay=False) + self.assertFalse(conn.create_collection.called) + + def test__get_conn_and_create_collection(self): + conn = self._makeConnection() + conn.collection_names.return_value = [] + + db_conn = MagicMock() + db_conn.__getitem__.return_value = conn + + api = MagicMock(spec=['Connection', 'binary']) + api.Connection.return_value = db_conn + + store = self._makeOne(backend_api=api) + result = store._get_conn() + + self.assertEqual(result, conn) + api.Connection.assert_called_with('localhost', 8080, slave_okay=False) + self.assertTrue(conn.create_collection.called) + + def test_store(self): + api = MagicMock(spec=['Connection', 'binary']) + store = self._makeOne(backend_api=api) + collection = MagicMock(spec=['update', 'remove', 'find_one']) + conn = self._makeConnection() + conn.__getitem__.return_value = collection + store._get_conn = MagicMock(return_value=conn) + + store.store('foo', 'bar') + + conn.__getitem__.assert_called_with('keystore') + args = collection.update.call_args[0] + self.assertEqual(args[0], {'key': 'foo'}) + self.assertEqual(args[1]['$set']['expires'], None) + + def test_store_with_expires(self): + api = MagicMock(spec=['Connection', 'binary']) + store = self._makeOne(backend_api=api) + collection = MagicMock(spec=['update', 'remove', 'find_one']) + conn = self._makeConnection() + conn.__getitem__.return_value = collection + store._get_conn = MagicMock(return_value=conn) + + now = datetime.utcnow() + with patch('anykeystore.backends.mongodb.datetime') as dt: + dt.utcnow.return_value = now + store.store('foo', 'bar', expires=5) + + conn.__getitem__.assert_called_with('keystore') + args = collection.update.call_args[0] + self.assertEqual(args[0], {'key': 'foo'}) + self.assertEqual(args[1]['$set']['expires'], + now + timedelta(seconds=5)) + + def test_delete(self): + store = self._makeOne() + collection = MagicMock(spec=['update', 'remove', 'find_one']) + conn = self._makeConnection() + conn.__getitem__.return_value = collection + store._get_conn = MagicMock(return_value=conn) + + store.delete('foo') + + conn.__getitem__.assert_called_with('keystore') + args = collection.remove.call_args[0] + self.assertEqual(args[0], {'key': 'foo'}) + + def test_retrieve(self): + store = self._makeOne() + collection = MagicMock(spec=['update', 'remove', 'find_one']) + conn = self._makeConnection() + conn.__getitem__.return_value = collection + store._get_conn = MagicMock(return_value=conn) + collection.find_one.return_value = {'expires': None, 'value': 'bar'} + + with patch('anykeystore.backends.mongodb.pickle') as pickle: + pickle.loads = lambda value: value + result = store.retrieve('foo') + + self.assertEqual(result, 'bar') + conn.__getitem__.assert_called_with('keystore') + args = collection.find_one.call_args[0] + self.assertEqual(args[0], {'key': 'foo'}) + + def test_retrieve_expired(self): + store = self._makeOne() + collection = MagicMock(spec=['update', 'remove', 'find_one']) + conn = self._makeConnection() + conn.__getitem__.return_value = collection + store._get_conn = MagicMock(return_value=conn) + + old = datetime.utcnow() - timedelta(seconds=1) + collection.find_one.return_value = {'expires': old, 'value': 'bar'} + + self.assertRaises(KeyError, store.retrieve, 'foo') + + conn.__getitem__.assert_called_with('keystore') + args = collection.find_one.call_args[0] + self.assertEqual(args[0], {'key': 'foo'}) + + def test_purge(self): + store = self._makeOne() + collection = MagicMock(spec=['update', 'remove', 'find_one']) + conn = self._makeConnection() + conn.__getitem__.return_value = collection + store._get_conn = MagicMock(return_value=conn) + + now = datetime.utcnow() + with patch('anykeystore.backends.mongodb.datetime') as dt: + dt.utcnow.return_value = now + store.purge_expired() + + conn.__getitem__.assert_called_with('keystore') + args = collection.remove.call_args[0] + self.assertEqual(args[0], {'expires': {'$lte': now}}) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/test_backends/test_redis.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/test_backends/test_redis.py new file mode 100644 index 0000000000000000000000000000000000000000..ae3e4700b7642701962a3489edbfaefe8623a687 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/test_backends/test_redis.py @@ -0,0 +1,94 @@ +import unittest2 as unittest +from mock import MagicMock, patch + +class TestRedisStore(unittest.TestCase): + + def _makeOne(self, + db=0, + key_prefix='key.', + host='localhost', + port=6379, + backend_api=None): + from anykeystore.backends.redis import RedisStore + store = RedisStore(db=db, key_prefix=key_prefix, host=host, port=port, + backend_api=backend_api) + return store + + def _makeConnection(self): + conn = MagicMock(spec=['get', 'set', 'delete', 'expire']) + return conn + + def test__get_conn(self): + api = MagicMock(spec=['Redis', 'ConnectionPool']) + api.ConnectionPool.return_value = 'foo' + api.Redis.return_value = 'myconn' + + store = self._makeOne(backend_api=api) + conn = store._get_conn() + self.assertEqual(conn, 'myconn') + + conn = store._get_conn() + self.assertEqual(conn, 'myconn') + + api.Redis.assert_called_with(connection_pool='foo') + self.assertEqual(api.ConnectionPool.call_count, 1) + + def test_store(self): + store = self._makeOne() + conn = self._makeConnection() + store._get_conn = MagicMock(return_value=conn) + + with patch('anykeystore.backends.redis.pickle') as pickle: + pickle.dumps = lambda value, protocol: value + store.store('foo', 'bar') + + conn.set.assert_called_with('key.foo', 'bar') + self.assertFalse(conn.expire.called) + + def test_store_with_expires(self): + store = self._makeOne() + conn = self._makeConnection() + store._get_conn = MagicMock(return_value=conn) + + with patch('anykeystore.backends.redis.pickle') as pickle: + pickle.dumps = lambda value, protocol: value + store.store('foo', 'bar', expires=5) + + conn.set.assert_called_with('key.foo', 'bar') + conn.expire.assert_called_with('key.foo', 5) + + def test_delete(self): + store = self._makeOne() + conn = self._makeConnection() + store._get_conn = MagicMock(return_value=conn) + + store.delete('foo') + + conn.delete.assert_called_with('key.foo') + + def test_retrieve(self): + store = self._makeOne() + conn = self._makeConnection() + conn.get.return_value = 'bar' + store._get_conn = MagicMock(return_value=conn) + + with patch('anykeystore.backends.redis.pickle') as pickle: + pickle.loads = lambda value: value + result = store.retrieve('foo') + + self.assertEqual(result, 'bar') + conn.get.assert_called_with('key.foo') + + def test_retrieve_expired(self): + store = self._makeOne() + conn = self._makeConnection() + conn.get.return_value = None + store._get_conn = MagicMock(return_value=conn) + + self.assertRaises(KeyError, store.retrieve, 'foo') + + conn.get.assert_called_with('key.foo') + + def test_purge(self): + store = self._makeOne() + store.purge_expired() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/test_backends/test_sqla.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/test_backends/test_sqla.py new file mode 100644 index 0000000000000000000000000000000000000000..2184a1918e9ca033922ef7a169df5624deb5e8f5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/test_backends/test_sqla.py @@ -0,0 +1,76 @@ +import unittest2 as unittest +from mock import MagicMock, patch + +class TestSQLStore(unittest.TestCase): + + def _getTargetClass(self): + from anykeystore.backends.sqla import SQLStore + return SQLStore + + def _makeApi(self): + api = MagicMock(spec=[ + 'engine_from_config', 'MetaData', + 'select', 'insert', 'delete']) + return api + + def test_init_with_table(self): + cls = self._getTargetClass() + api = self._makeApi() + result = cls('myurl', table='foo', backend_api=api) + self.assertEqual(result.table, 'foo') + + def test_init_with_table_name(self): + cls = self._getTargetClass() + api = self._makeApi() + api.MetaData.return_value = 'a_meta' + with patch.object(cls, '_make_table') as _make_table: + _make_table.return_value = 'some_table' + result = cls( + 'myurl', table_name='foo', backend_api=api) + self.assertEqual(result.table, 'some_table') + _make_table.assert_called_with('foo', 'a_meta') + + def test_init_with_table_name_and_metadata(self): + cls = self._getTargetClass() + api = self._makeApi() + api.MetaData.return_value = 'a_meta' + with patch.object(cls, '_make_table') as _make_table: + _make_table.return_value = 'some_table' + result = cls( + 'myurl', table_name='foo', metadata='b_meta', backend_api=api) + self.assertEqual(result.table, 'some_table') + _make_table.assert_called_with('foo', 'b_meta') + + def test__get_conn(self): + cls = self._getTargetClass() + api = self._makeApi() + engine = MagicMock() + engine.connect.return_value = 'myconn' + api.engine_from_config.return_value = engine + table = MagicMock() + store = cls('myurl', table=table, backend_api=api) + result = store._get_conn() + self.assertEqual(result, 'myconn') + self.assertTrue(store._created) + self.assertEqual(table.create.call_count, 1) + self.assertEqual(engine.connect.call_count, 1) + + result = store._get_conn() + self.assertEqual(result, 'myconn') + self.assertEqual(table.create.call_count, 1) + self.assertEqual(engine.connect.call_count, 2) + + def test_retrieve(self): + cls = self._getTargetClass() + api = self._makeApi() + table = MagicMock() + store = cls('myurl', table=table, backend_api=api) + with patch.object(store, '_get_conn') as get_conn: + get_conn.return_value = conn = MagicMock() + + conn.execute.return_value.fetchone.return_value = ('bar', None) + result = store.retrieve('foo') + self.assertEqual(result, 'bar') + + conn.execute.return_value.fetchone.return_value = None + self.assertRaises(KeyError, store.retrieve, 'foo') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/test_store.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/test_store.py new file mode 100644 index 0000000000000000000000000000000000000000..f22ce4e356932c5cb15adc421600bbf4769b561b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/test_store.py @@ -0,0 +1,30 @@ +import unittest + +class TestStore(unittest.TestCase): + + def test_create_store(self): + from anykeystore import create_store + store = create_store('memory') + + from anykeystore.backends.memory import MemoryStore + self.assertTrue(isinstance(store, MemoryStore)) + + def test_create_store_from_settings(self): + from anykeystore import create_store_from_settings + store = create_store_from_settings({'store': 'memory'}) + + from anykeystore.backends.memory import MemoryStore + self.assertTrue(isinstance(store, MemoryStore)) + + def test_create_store_from_settings_with_prefix(self): + from anykeystore import create_store_from_settings + store = create_store_from_settings( + {'any.store': 'memory'}, prefix='any.') + + from anykeystore.backends.memory import MemoryStore + self.assertTrue(isinstance(store, MemoryStore)) + + def test_create_nonexistent_store(self): + from anykeystore import create_store + from anykeystore.exceptions import ConfigurationError + self.assertRaises(ConfigurationError, create_store, '_dumbdb') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/test_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9dad5ff767b7c35589ad74cd469a3873636395d1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/tests/test_utils.py @@ -0,0 +1,29 @@ +import unittest +from datetime import timedelta + +class TestCoerceTimedelta(unittest.TestCase): + def _callFUT(self, value): + from anykeystore.utils import coerce_timedelta + return coerce_timedelta(value) + + def test_coerce_with_int(self): + result = self._callFUT(20) + self.assertEqual(result, timedelta(seconds=20)) + + def test_coerce_with_timedelta(self): + dt = timedelta(seconds=1) + result = self._callFUT(dt) + self.assertEqual(result, dt) + +class TestSplitlines(unittest.TestCase): + def _callFUT(self, value): + from anykeystore.utils import splitlines + return splitlines(value) + + def test_it_single_line(self): + result = self._callFUT('localhost:11211') + self.assertEqual(result, ['localhost:11211']) + + def test_it_multiple_lines(self): + result = self._callFUT(' localhost:11211 \n\tfoo:80') + self.assertEqual(result, ['localhost:11211', 'foo:80']) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..09ea0ab7124addb9d54fe4480bf8dee5a807af67 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/anykeystore/utils.py @@ -0,0 +1,11 @@ +from datetime import timedelta + +def coerce_timedelta(value): + if isinstance(value, timedelta): + return value + if isinstance(value, int) or isinstance(value, float): + return timedelta(seconds=value) + +def splitlines(s): + return list(filter(None, [c.strip() for x in s.splitlines() + for c in x.split(', ')])) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d8232ef8b5f66a3dbd7fe027757780ea89966700 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/__init__.py @@ -0,0 +1,30 @@ +from .api import create_dataloader +from .chord import Chord +from .dataloader import ArpeggioBaseDataloader, ArpeggioIterableDataloader, ArpeggioMapStyleDataloader, DataloaderArgs +from .dataset import ( + ArpeggioBaseDataset, + ArpeggioIterableDataset, + ArpeggioMapStyleDataset, + ArpeggioMultiSourceIterableDataset, +) +from .tuners import TRANSFORM_REGISTRY, TransformBase, load_transform, register_transform +from .version import __version__ + + +__all__ = [ + "__version__", + "TRANSFORM_REGISTRY", + "Chord", + "TransformBase", + "ArpeggioBaseDataset", + "ArpeggioMapStyleDataset", + "ArpeggioIterableDataset", + "DataloaderArgs", + "ArpeggioBaseDataloader", + "ArpeggioIterableDataloader", + "ArpeggioMapStyleDataloader", + "ArpeggioMultiSourceIterableDataset", + "load_transform", + "register_transform", + "create_dataloader", +] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/api.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/api.py new file mode 100644 index 0000000000000000000000000000000000000000..88030d1e6568ae00fe1df66e48bf5675207eb026 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/api.py @@ -0,0 +1,303 @@ +from __future__ import annotations + +import json +import warnings +from typing import Optional, Union, overload + +import torch.distributed as dist + +from arpeggio.dataloader import ( + ArpeggioBaseDataloader, + ArpeggioIterableDataloader, + ArpeggioMapStyleDataloader, + DataloaderArgs, +) +from arpeggio.dataset import ArpeggioTinyIterableDataset, ArpeggioIterableDataset, ArpeggioMapStyleDataset, ArpeggioMultiSourceIterableDataset +from arpeggio.meta import DataSourceMeta, read_dataset_meta_paths +from arpeggio.sampler import BatchSampler, ContinuousBatchSampler +from arpeggio.tuners import load_transform +from arpeggio.tuners.base import TransformBase +from arpeggio.utils.io_utils import glob_files, read_file + + +Filepaths = list[str] +RankToFilepaths = list[list[str]] + + +# Create dataloader with filepaths +@overload +def create_dataloader( + *, + filepaths: Union[list[str], str], + args: Optional[DataloaderArgs] = None, + model_path: Optional[str] = None, + model_type: Optional[str] = None, + transform: Optional[TransformBase] = None, + dp_group: Optional[dist.ProcessGroup] = None, + dataset_meta_paths: Union[list[str], str, None] = None, +) -> ArpeggioBaseDataloader: ... + + +# Create dataloader with patterns +@overload +def create_dataloader( + *, + patterns: Union[list[str], str], + args: Optional[DataloaderArgs] = None, + model_path: Optional[str] = None, + model_type: Optional[str] = None, + transform: Optional[TransformBase] = None, + dp_group: Optional[dist.ProcessGroup] = None, + dataset_meta_paths: Union[list[str], str, None] = None, +) -> ArpeggioBaseDataloader: ... + + +# Create dataloader with rank_to_filepaths +@overload +def create_dataloader( + *, + rank_to_filepaths: RankToFilepaths, + args: Optional[DataloaderArgs] = None, + model_path: Optional[str] = None, + model_type: Optional[str] = None, + transform: Optional[TransformBase] = None, + dp_group: Optional[dist.ProcessGroup] = None, +) -> ArpeggioBaseDataloader: ... + + +# Create dataloader with data_source_metas +@overload +def create_dataloader( + *, + data_source_metas: Union[list[DataSourceMeta], list[str], DataSourceMeta, str, None] = None, + args: Optional[DataloaderArgs] = None, + model_path: Optional[str] = None, + model_type: Optional[str] = None, + transform: Optional[TransformBase] = None, + dp_group: Optional[dist.ProcessGroup] = None, +) -> ArpeggioBaseDataloader: ... + + +def create_dataloader( + *, + args: Optional[DataloaderArgs] = None, + model_path: Optional[str] = None, + model_type: Optional[str] = None, + transform: Optional[TransformBase] = None, + dp_group: Optional[dist.ProcessGroup] = None, + filepaths: Union[list[str], str, None] = None, + patterns: Union[list[str], str, None] = None, + rank_to_filepaths: Optional[RankToFilepaths] = None, + data_source_metas: Union[list[DataSourceMeta], list[str], DataSourceMeta, str, None] = None, + dataset_meta_paths: Union[list[str], str, None] = None, + **kwargs, +) -> ArpeggioBaseDataloader: + if len(kwargs) > 0: + warnings.warn(f"create_dataloader unused kwargs: {list(kwargs.keys())}", UserWarning) + + # Initialize args if None + if args is None: + args = DataloaderArgs() + + dp_rank, dp_size = 0, 1 + if dp_group is not None: + dp_rank, dp_size = dp_group.rank(), dp_group.size() + total_workers = args.num_workers * dp_size + + # Resolve data source + _ensure_only_one_given( + filepaths=filepaths, + patterns=patterns, + rank_to_filepaths=rank_to_filepaths, + data_source_metas=data_source_metas, + ) + + if filepaths is not None: + if isinstance(filepaths, str): + filepaths = [filepaths] + assert len(filepaths) > 0 + + elif patterns is not None: + filepaths = _patterns_to_filepaths(patterns) + assert len(filepaths) > 0 + + elif rank_to_filepaths is not None: + if len(rank_to_filepaths) != total_workers: + raise ValueError( + "rank_to_filepaths should be of size dp_size * num_workers = " + f"{dp_size} * {args.num_workers} = {total_workers}" + ) + + else: + assert data_source_metas is not None + if isinstance(data_source_metas, (str, dict)): + data_source_metas = [data_source_metas] + assert len(data_source_metas) > 0 + if isinstance(data_source_metas[0], str): + # Data sources are located in files, have to read them + data_source_metas = [_read_json_from_file(filepath) for filepath in data_source_metas] + if not args.iterable: + warnings.warn( + "multi-source dataset only supports iterable, iterable mode automatically used", + UserWarning, + ) + args.iterable = True + + # Rsolve transform + transform = _resolve_transform( + model_path=model_path, + model_type=model_type, + transform=transform, + ) + + # Handle map-style + if not args.iterable: + assert filepaths is not None, "filepaths / patterns necessary for map style dataset" + + if args.allow_skip_files: + warnings.warn("allow_skip_files not implemented for map-style datasets") + if args.max_seq_len is not None: + warnings.warn("max_seq_len not implemented for map-style datasets") + if args.max_micro_steps is not None: + warnings.warn("max_micro_steps not implemented for map-style datasets") + + dataset = ArpeggioMapStyleDataset( + filepaths=filepaths, + transform=transform, + pad_to_multiple_of=args.pad_to_multiple_of, + dp_rank=dp_rank, + dp_size=dp_size, + ) + + if args.is_continuous_batch: + if dataset_meta_paths is None: + raise ValueError("dataset_meta_paths is required for map-style continous batching") + + # Extract seq lens from dataset meta + filepath_to_meta = read_dataset_meta_paths(dataset_meta_paths) + seq_lens = [] + for filepath in dataset.filepaths: + meta = filepath_to_meta[filepath] + seq_lens.extend(meta["seq_len"]) + + # Make batch sampler + batch_sampler = ContinuousBatchSampler( + seq_lens=seq_lens, + max_tokens_per_batch=args.max_tokens_per_batch, + max_samples_per_batch=args.max_samples_per_batch, + shuffle=args.shuffle, + seed=args.seed, + num_epoch=args.num_epoch, + generate_infinitely=args.generate_infinitely, + dp_group=dp_group, + ) + + else: + # Make batch sampler + batch_sampler = BatchSampler( + dataset_size=len(dataset), + batch_size=args.micro_batch_size, + shuffle=args.shuffle, + seed=args.seed, + num_epoch=args.num_epoch, + generate_infinitely=args.generate_infinitely, + dp_group=dp_group, + max_tokens_per_batch=args.max_tokens_per_batch, + max_samples_per_batch=args.max_samples_per_batch, + ) + + return ArpeggioMapStyleDataloader( + dataset=dataset, + args=args, + dp_group=dp_group, + batch_sampler=batch_sampler, + ) + + iterable_dataset_kwargs = { + "transform": transform, + "max_seq_len": args.max_seq_len, + "micro_batch_size": args.micro_batch_size, + "is_continuous_batch": args.is_continuous_batch, + "max_tokens_per_batch": args.max_tokens_per_batch, + "max_samples_per_batch": args.max_samples_per_batch, + "pad_to_multiple_of": args.pad_to_multiple_of, + "shuffle": args.shuffle, + "num_epoch": args.num_epoch, + "max_micro_steps": args.max_micro_steps, + "generate_infinitely": args.generate_infinitely, + "allow_skip_files": args.allow_skip_files, + "seed": args.seed, + "dp_rank": dp_rank, + "dp_size": dp_size, + } + + if data_source_metas is not None: + dataset = ArpeggioMultiSourceIterableDataset( + data_source_metas=data_source_metas, + num_workers=args.num_workers, + est_continuous_batch_efficiency=args.est_continuous_batch_efficiency, + **iterable_dataset_kwargs, + ) + elif args.tiny_iterable: + assert filepaths is not None, "filepaths / patterns necessary for tiny iterable dataset" + dataset = ArpeggioTinyIterableDataset( + filepaths=filepaths, + **iterable_dataset_kwargs, + ) + + else: + dataset = ArpeggioIterableDataset( + filepaths=filepaths, + rank_to_filepaths=rank_to_filepaths, + **iterable_dataset_kwargs, + ) + + return ArpeggioIterableDataloader( + dataset=dataset, + args=args, + dp_group=dp_group, + ) + + +def _ensure_only_one_given(**kwargs) -> bool: + names = tuple(kwargs.keys()) + seen = 0 + for arg in kwargs.values(): + if arg is None: + continue + if seen > 0: + raise ValueError(f"One of {names} must be provided and only one") + seen += 1 + if seen == 0: + raise ValueError(f"One of {names} must be provided and only one") + + +def _resolve_transform( + model_path: Optional[str] = None, + model_type: Optional[str] = None, + transform: Optional[TransformBase] = None, + **extra_kwargs, +) -> TransformBase: + if transform is not None: + if model_path is not None: + raise ValueError("Either model_path or transform must be provided but not both.") + return transform + + if model_path is None: + raise ValueError("If transform isn't provided, model_path must be used.") + return load_transform(model_path=model_path, model_type=model_type, **extra_kwargs) + + +def _patterns_to_filepaths(patterns: Union[list[str], str]): + if isinstance(patterns, str): + patterns = [patterns] + + filepaths = [] + for pattern in patterns: + filepaths.extend(glob_files(pattern)) + filepaths = sorted(filepaths) + return filepaths + + +def _read_json_from_file(filepath: str) -> object: + return json.loads(read_file(filepath)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/batcher.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/batcher.py new file mode 100644 index 0000000000000000000000000000000000000000..343c1401d2c06982362386106a11642ebd8a5808 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/batcher.py @@ -0,0 +1,144 @@ +from __future__ import annotations + +from abc import ABC, abstractmethod +from dataclasses import dataclass +from typing import Optional + +import torch +from torch.utils.data import Dataset, IterableDataset, get_worker_info +from transformers.feature_extraction_utils import BatchFeature + +from arpeggio.chord import Chord + + +class BaseBatcher(ABC): + def identity_collate(self, batch: list): + return batch[0] + + @abstractmethod + def collate(self, batch: list, pad_to_multiple_of: Optional[int] = None) -> Chord: ... + + +@dataclass +class RegularBatcher(BaseBatcher): + pad_token_id: int = 0 + pad_to_multiple_of: int = 1 + + def collate(self, batch: list[Chord], pad_to_multiple_of: Optional[int] = None) -> Chord: + # Skip trivial case + if len(batch) == 1: + return batch[0] + + if pad_to_multiple_of is None: + pad_to_multiple_of = self.pad_to_multiple_of + + # Calculate batch dimensions + batch_size = sum(chord["input_ids"].shape[0] for chord in batch) + assert batch_size >= 1, "collate for batch_size=0 not implemented" + + batch_seq_len = max(chord["input_ids"].shape[-1] for chord in batch) + if batch_seq_len % pad_to_multiple_of > 0: + batch_seq_len = (batch_seq_len // pad_to_multiple_of + 1) * pad_to_multiple_of + + # Create placeholder for storing output + placeholder: dict = { + "input_ids": torch.zeros(batch_size, batch_seq_len, dtype=torch.long) + self.pad_token_id, + "attention_mask": torch.zeros(batch_size, batch_seq_len, dtype=torch.long), + } + + use_mrope = any(chord["position_ids"].ndim == 3 for chord in batch) + if use_mrope: + placeholder["position_ids"] = torch.ones(3, batch_size, batch_seq_len, dtype=torch.long) + else: + placeholder["position_ids"] = torch.ones(batch_size, batch_seq_len, dtype=torch.long) + + has_labels = any(chord.get("labels") is not None for chord in batch) + if has_labels: + placeholder["labels"] = torch.zeros(batch_size, batch_seq_len, dtype=torch.long) - 100 + + extra_info_list = [] + pixel_values_list = [] + image_grid_thw_list = [] + pixel_values_videos_list = [] + video_grid_thw_list = [] + all_keys: set[str] = set() + + offset = 0 + for item in batch: + # For ease of development if mrope, then assert all mrope + if use_mrope: + assert item["position_ids"].ndim == 3 + + mini_batch_size, seq_len = item["input_ids"].shape + next_offset = offset + mini_batch_size + placeholder["input_ids"][offset:next_offset, :seq_len] = item["input_ids"] + placeholder["position_ids"][..., offset:next_offset, :seq_len] = item["position_ids"] + placeholder["attention_mask"][offset:next_offset, :seq_len] = item["attention_mask"] + if has_labels: + placeholder["labels"][offset:next_offset, :seq_len] = item["labels"] + + extra_info_list.extend(item["extra_info"]) + + pixel_val = item.get("pixel_values") + if pixel_val is not None: + pixel_values_list.append(pixel_val) + img_grid = item.get("image_grid_thw") + if img_grid is not None: + image_grid_thw_list.append(img_grid) + pixel_vid = item.get("pixel_values_videos") + if pixel_vid is not None: + pixel_values_videos_list.append(pixel_vid) + vid_grid = item.get("video_grid_thw") + if vid_grid is not None: + video_grid_thw_list.append(vid_grid) + + all_keys.update(item.keys()) + offset = next_offset + + placeholder["extra_info"] = extra_info_list + + if len(pixel_values_list) > 0: + placeholder["pixel_values"] = torch.cat(pixel_values_list, dim=0) # type: ignore[arg-type] + placeholder["image_grid_thw"] = torch.cat(image_grid_thw_list, dim=0) # type: ignore[arg-type] + if len(pixel_values_videos_list) > 0: + placeholder["pixel_values_videos"] = torch.cat(pixel_values_videos_list, dim=0) # type: ignore[arg-type] + placeholder["video_grid_thw"] = torch.cat(video_grid_thw_list, dim=0) # type: ignore[arg-type] + + for key in all_keys: + if key in placeholder: + # We've already added them into placeholder + continue + + placeholder[key] = [] + for chord in batch: + n_samples = len(chord["extra_info"]) + if key in chord: + values = chord.get(key) # type: ignore[literal-required] + else: + values = [None] * n_samples + if values is not None: + placeholder[key].extend(values) + + return BatchFeature(placeholder) # type: ignore[return-value] + + +class ContinuousBatcher(RegularBatcher): + def collate(self, batch: list[Chord], pad_to_multiple_of: Optional[int] = None) -> Chord: + assert len(batch) > 0, "collate_continuous for batch_size=0 not implemented" + + placeholder: Chord = super().collate(batch) + use_mrope = placeholder["position_ids"].ndim == 3 + has_labels = "labels" in placeholder + + mask = placeholder["attention_mask"] > 0 + placeholder["input_ids"] = placeholder["input_ids"][mask][None] + placeholder["attention_mask"] = placeholder["attention_mask"][mask][None] + if use_mrope: + placeholder["position_ids"] = placeholder["position_ids"][:, mask][:, None] + else: + placeholder["position_ids"] = placeholder["position_ids"][mask][None] + + if has_labels: + placeholder["labels"] = placeholder["labels"][mask][None] + + return BatchFeature(placeholder) # type: ignore[return-value] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/chord.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/chord.py new file mode 100644 index 0000000000000000000000000000000000000000..8161f5d11fd530992f5edc42d367b472067dd5c0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/chord.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +from typing import Optional, TypedDict, Union + +import torch + + +class ChordExtraInfo(TypedDict, total=False): + worker_rank: int + worker_world_size: int + + file_idx: int + row_idx: int + file_name: str + dataset_idx: int + + seq_len: int + + +class Chord(TypedDict): + """Chords are processed items ready for model input. + + This class is designed to be compatible with text LLMs and also Qwen2.5-VL. + """ + + extra_info: list[ChordExtraInfo] + + input_ids: Union[torch.LongTensor, torch.Tensor] + position_ids: torch.LongTensor + attention_mask: torch.LongTensor + + # For SFT training + labels: Optional[torch.LongTensor] + + # For multimodal models + pixel_values: Optional[torch.FloatTensor] + image_grid_thw: Optional[torch.LongTensor] + pixel_values_videos: Optional[torch.FloatTensor] + video_grid_thw: Optional[torch.LongTensor] + + +def make_dummy_chord( + batch_size: int = 1, + seq_len: int = 1, + use_mrope: bool = False, + has_labels: bool = False, +) -> Chord: + input_ids = torch.ones(batch_size, seq_len, dtype=torch.long) + + position_ids = torch.ones_like(input_ids) + position_ids[..., 0].fill_(0) + + if use_mrope: + position_ids = position_ids.unsqueeze(0).repeat(3, 1, 1) + extra_info = { + "worker_rank": -1, # We should honestly use real values + "worker_world_size": -1, + "file_idx": -1, + "row_idx": -1, + "file_name": "dummy", + "dataset_idx": -1, + "seq_len": seq_len, + } + + dummy = { + "input_ids": input_ids, + "position_ids": position_ids, + "attention_mask": torch.ones_like(input_ids), + "extra_info": [extra_info], + } + if has_labels: + dummy["labels"] = torch.empty_like(dummy["input_ids"]).fill_(-100) + + return dummy diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/cli/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/cli/extract_meta.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/cli/extract_meta.py new file mode 100644 index 0000000000000000000000000000000000000000..09d17aee01b5e314e5ce96fc863ebbbcbbf6a7c0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/cli/extract_meta.py @@ -0,0 +1,280 @@ +from __future__ import annotations + +import argparse +import json +import logging +import os +import shutil +import sys +import traceback +import warnings +from multiprocessing.pool import AsyncResult +from tempfile import TemporaryDirectory +from typing import Optional, TypeVar + +import fsspec +import torch +import torch.multiprocessing as mp +from torch.utils.data import DataLoader, Dataset +from tqdm import tqdm + +from arpeggio.meta import ChordMeta, FileMeta +from arpeggio.tuners import load_transform +from arpeggio.tuners.base import TransformBase +from arpeggio.utils.io_utils import abspath, glob_files, read_rows_from_dataset_file +from arpeggio.version import __version__ as arpeggio_version + + +DEFAULT_TUNER_CLS = "llm" +T = TypeVar("T") + + +class MetaDataset(Dataset[ChordMeta]): + def __init__( + self, + items: list[dict], + transform: TransformBase, + ): + self.transform = transform + self.items = items + + def __len__(self) -> int: + return len(self.items) + + def __getitem__(self, index: int) -> ChordMeta: + return self.transform.get_meta(self.items[index]) + + +def setup_worker(): + torch.set_num_threads(1) + + try: + from qwen_vl_utils.vision_process import logger as qwen_vl_logger + + qwen_vl_logger.setLevel(logging.ERROR) + except ImportError: + pass + + +def identity(x: list[T]) -> T: + return x[0] + + +def extract_file_meta( + filepath: str, + model_path: str, + model_type: Optional[str] = None, + dataloader_workers: int = 0, + extra_module_path: Optional[str] = None, + extra_transform_kwargs: Optional[dict] = None, +) -> FileMeta: + setup_worker() + + # Load extra module and transform function + if extra_module_path is not None: + tmpdir = TemporaryDirectory() + sys.path.append(tmpdir.name) + tmp_module_path = f"{tmpdir.name}/abbie_extra_module.py" + shutil.copy(extra_module_path, tmp_module_path) + __import__("abbie_extra_module") + if extra_transform_kwargs is None: + extra_transform_kwargs = {} + + transform = load_transform(model_path, model_type=model_type, **extra_transform_kwargs) + + try: + items = read_rows_from_dataset_file(filepath) + except Exception as e: + # In the event that file reading fails, just return an empty FileMeta + err_trace = traceback.format_exc() + warnings.warn(f"Failed to read {filepath} due to {e}: {err_trace}") + if extra_module_path is not None: + tmpdir.cleanup() + return { + "filepath": abspath(filepath), + "num_items": 0, + "seq_len": [], + "num_image_patches": [], + "num_video_patches": [], + "arpeggio_version": arpeggio_version, + "transform_cls": transform.__class__.__name__, + "transform_model_path": model_path, + "transform_model_type": model_type, + } + + dataset = MetaDataset( + items=items, + transform=transform, + ) + dataloader = DataLoader( + dataset=dataset, + batch_size=1, + collate_fn=identity, + num_workers=dataloader_workers, + ) + + seq_lens = [] + num_image_patches_list = [] + num_video_patches_list = [] + for meta in dataloader: + seq_len = meta["seq_len"] + num_image_patches = meta["num_image_patches"] + num_video_patches = meta["num_video_patches"] + + seq_lens.append(seq_len) + num_image_patches_list.append(num_image_patches) + num_video_patches_list.append(num_video_patches) + + if extra_module_path is not None: + tmpdir.cleanup() + + return { + "filepath": abspath(filepath), + "num_items": len(seq_lens), + "seq_len": seq_lens, + "num_image_patches": num_image_patches_list, + "num_video_patches": num_video_patches_list, + "arpeggio_version": arpeggio_version, + "transform_cls": transform.__class__.__name__, + "transform_model_path": model_path, + "transform_model_type": model_type, + } + + +def batch_extract_file_meta( + filepaths: list[str], + model_path: str, + model_type: Optional[str] = None, + extra_module_path: Optional[str] = None, + extra_transform_kwargs: Optional[dict] = None, +) -> list[FileMeta]: + all_meta = [] + + with mp.Pool(mp.cpu_count(), maxtasksperchild=1) as pool: + futures: list[AsyncResult] = [] + for filepath in filepaths: + future = pool.apply_async( + extract_file_meta, + kwds={ + "filepath": filepath, + "model_path": model_path, + "model_type": model_type, + "extra_module_path": extra_module_path, + "extra_transform_kwargs": extra_transform_kwargs, + }, + ) + futures.append(future) + + for future in tqdm(futures, desc="Collecting metadata"): + meta = future.get() + all_meta.append(meta) + + return all_meta + + +def batch_extract_file_meta_ray( + filepaths: list[str], + model_path: str, + model_type: Optional[str] = None, + dataloader_workers: int = 0, + extra_module_path: Optional[str] = None, + extra_transform_kwargs: Optional[dict] = None, +) -> list[FileMeta]: + import ray + + extract_file_meta_ray = ray.remote(max_calls=1)(extract_file_meta) + + futures = [] + for filepath in filepaths: + future = extract_file_meta_ray.remote( + filepath=filepath, + model_path=model_path, + model_type=model_type, + dataloader_workers=dataloader_workers, + extra_module_path=extra_module_path, + extra_transform_kwargs=extra_transform_kwargs, + ) + + futures.append(future) + + all_meta = [] + + with tqdm(total=len(futures), desc="Collecting metadata") as pbar: + while futures: + ready, futures = ray.wait(futures, num_returns=1) + meta = ray.get(ready[0]) + pbar.update(1) + + all_meta.append(meta) + + return all_meta + + +def main(): + parser = argparse.ArgumentParser( + description="Script to extract file metadata", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + parser.add_argument("patterns", nargs="+") + parser.add_argument("-o", "--output_path", default="dataset_meta.jsonl", help="Output save path") + parser.add_argument("-m", "--model_path", required=True) + parser.add_argument("--model_type", default=None) + parser.add_argument( + "--dataloader_workers", + type=int, + default=0, + help="Number of dataloader workers per ray worker", + ) + parser.add_argument("--extra_transform_kwargs", default=None, type=eval, help="Extra kwargs for transform") + parser.add_argument("--extra_module_path", help="Extra module path to import (typically some custom transform)") + parser.add_argument("--use_ray", action="store_true", help="Use ray to do multiprocessing") + parser.add_argument("--ray_address", default=None, help="Ray cluster address") + args = parser.parse_args() + print(args) + + if args.extra_transform_kwargs is not None: + if not isinstance(args.extra_transform_kwargs, dict): + raise ValueError( + f"Expecting extra_transform_kwargs to be dict. Instead received {args.extra_transform_kwargs}" + ) + + print("Searching for files") + filepaths = [] + for pattern in args.patterns: + filepaths.extend(glob_files(pattern)) + print(f"Found {len(filepaths)} files") + + if args.use_ray: + import ray + + if not ray.is_initialized(): + ray.init(address=args.ray_address) + + file_metas = batch_extract_file_meta_ray( + filepaths=filepaths, + model_path=args.model_path, + model_type=args.model_type, + dataloader_workers=args.dataloader_workers, + extra_module_path=args.extra_module_path, + ) + + else: + assert args.dataloader_workers == 0, "to use dataloader workers, please use ray" + mp.set_start_method("spawn") + + file_metas = batch_extract_file_meta( + filepaths=filepaths, + model_path=args.model_path, + model_type=args.model_type, + extra_module_path=args.extra_module_path, + extra_transform_kwargs=args.extra_transform_kwargs, + ) + + os.makedirs(os.path.dirname(args.output_path), exist_ok=True) + with fsspec.open(args.output_path, "w") as f: + for meta in file_metas: + f.write(json.dumps(meta)) + + +if __name__ == "__main__": + main() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/cli/extract_source_meta.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/cli/extract_source_meta.py new file mode 100644 index 0000000000000000000000000000000000000000..0fa277450838865423a65016c3c33818537de35b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/cli/extract_source_meta.py @@ -0,0 +1,204 @@ +from __future__ import annotations + +import argparse +import json +import os +from typing import Optional + +import fsspec +import torch.multiprocessing as mp + +from arpeggio.meta import DataSourceMeta +from arpeggio.utils.io_utils import glob_files +from arpeggio.version import __version__ as arpeggio_version + +from .extract_meta import extract_file_meta + + +def extract_source_meta( + filepaths: list[str], + model_path: str, + model_type: Optional[str] = None, + max_files_to_sample: int = 3, + dataset_name: str = "unknown", + dataloader_workers: int = 0, + extra_module_path: Optional[str] = None, + extra_transform_kwargs: Optional[dict] = None, +) -> DataSourceMeta: + assert len(filepaths) > 0, "did not receive any files" + + filepaths_to_sample = filepaths[:max_files_to_sample] + total_sampled_files = len(filepaths_to_sample) + + sampled_num_samples = 0 + sampled_num_tokens = 0 + for filepath in filepaths_to_sample: + file_meta = extract_file_meta( + filepath=filepath, + model_path=model_path, + model_type=model_type, + dataloader_workers=dataloader_workers, + extra_module_path=extra_module_path, + extra_transform_kwargs=extra_transform_kwargs, + ) + + seq_lens = file_meta["seq_len"] + seq_lens = [seq_len for seq_len in seq_lens if seq_len > 0] + + sampled_num_samples += len(seq_lens) + sampled_num_tokens += sum(seq_lens) + + avg_num_samples = sampled_num_samples / total_sampled_files + avg_num_tokens = sampled_num_tokens / total_sampled_files + + return { + "name": dataset_name, + "avg_seq_len": sampled_num_tokens / sampled_num_samples, + "avg_samples_per_file": avg_num_samples, + "avg_tokens_per_file": avg_num_tokens, + "transform_cls": file_meta["transform_cls"], + "transform_model_path": model_path, + "transform_model_type": model_type, + "arpeggio_version": arpeggio_version, + "filepaths": filepaths, + } + + +def extract_source_meta_ray( + filepaths: list[str], + model_path: str, + model_type: Optional[str] = None, + max_files_to_sample: int = 3, + dataset_name: str = "unknown", + dataloader_workers: int = 0, + extra_module_path: Optional[str] = None, + extra_transform_kwargs: Optional[dict] = None, +) -> DataSourceMeta: + import ray + + assert len(filepaths) > 0, "did not receive any files" + + filepaths_to_sample = filepaths[:max_files_to_sample] + total_sampled_files = len(filepaths_to_sample) + + extract_file_meta_ray = ray.remote(extract_file_meta, max_calls=1) + + futures = [] + for filepath in filepaths_to_sample: + future = extract_file_meta_ray.remote( + filepath=filepath, + model_path=model_path, + model_type=model_type, + dataloader_workers=dataloader_workers, + extra_module_path=extra_module_path, + extra_transform_kwargs=extra_transform_kwargs, + ) + futures.append(future) + + sampled_num_samples = 0 + sampled_num_tokens = 0 + while futures: + ready, futures = ray.wait(futures, num_returns=1) + file_meta = ray.get(ready[0]) + + seq_lens = file_meta["seq_len"] + seq_lens = [seq_len for seq_len in seq_lens if seq_len > 0] + + sampled_num_samples += len(seq_lens) + sampled_num_tokens += sum(seq_lens) + + avg_num_samples = sampled_num_samples / total_sampled_files + avg_num_tokens = sampled_num_tokens / total_sampled_files + + return { + "name": dataset_name, + "avg_seq_len": sampled_num_tokens / sampled_num_samples, + "avg_samples_per_file": avg_num_samples, + "avg_tokens_per_file": avg_num_tokens, + "transform_cls": file_meta["transform_cls"], + "transform_model_path": model_path, + "transform_model_type": model_type, + "arpeggio_version": arpeggio_version, + "filepaths": filepaths, + } + + +def main(): + parser = argparse.ArgumentParser( + description="Script to extract source metadata by sampling files", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + parser.add_argument("pattern", help="File pattern to match dataset files") + parser.add_argument("-o", "--output_path", default="source_meta.json", help="Output save path") + parser.add_argument("-m", "--model_path", required=True, help="Path to model for preprocessing") + parser.add_argument("--model_type", default=None, help="Model type override") + parser.add_argument( + "--max_files_to_sample", + type=int, + default=3, + help="Number of files to sample for estimating averages", + ) + parser.add_argument("--dataset_name", default="unknown", help="Name of the dataset") + parser.add_argument( + "--dataloader_workers", + type=int, + default=0, + help="Number of dataloader workers per ray worker", + ) + parser.add_argument("--extra_transform_kwargs", default=None, type=eval, help="Extra kwargs for transform") + parser.add_argument("--extra_module_path", help="Extra module path to import (typically some custom transform)") + parser.add_argument("--use_ray", action="store_true", help="Use ray to do multiprocessing") + parser.add_argument("--ray-address", default=None, help="Ray cluster address") + args = parser.parse_args() + print(args) + + if args.extra_transform_kwargs is not None: + if not isinstance(args.extra_transform_kwargs, dict): + raise ValueError( + f"Expecting extra_transform_kwargs to be dict. Instead received {args.extra_transform_kwargs}" + ) + + print("Searching for files") + filepaths = glob_files(args.pattern) + print(f"Found {len(filepaths)} files") + + if args.use_ray: + import ray + + if not ray.is_initialized(): + ray.init(address=args.ray_address) + + source_meta = extract_source_meta_ray( + filepaths=filepaths, + model_path=args.model_path, + model_type=args.model_type, + max_files_to_sample=args.max_files_to_sample, + dataset_name=args.dataset_name, + dataloader_workers=args.dataloader_workers, + extra_module_path=args.extra_module_path, + extra_transform_kwargs=args.extra_transform_kwargs, + ) + + else: + mp.set_start_method("spawn") + + source_meta = extract_source_meta( + filepaths=filepaths, + model_path=args.model_path, + model_type=args.model_type, + max_files_to_sample=args.max_files_to_sample, + dataset_name=args.dataset_name, + dataloader_workers=args.dataloader_workers, + extra_module_path=args.extra_module_path, + extra_transform_kwargs=args.extra_transform_kwargs, + ) + + os.makedirs(os.path.dirname(args.output_path) or ".", exist_ok=True) + with fsspec.open(args.output_path, "w") as f: + json.dump(source_meta, f, indent=2) + + print(f"Source metadata saved to {args.output_path}") + + +if __name__ == "__main__": + main() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/dataloader.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/dataloader.py new file mode 100644 index 0000000000000000000000000000000000000000..0aef1f981328918dac6e90387f89d4901b23ef73 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/dataloader.py @@ -0,0 +1,243 @@ +from __future__ import annotations + +import json +import logging +import os +import warnings +from collections.abc import Iterator +from dataclasses import dataclass +from functools import partial +from typing import Optional, Union + +import torch.distributed as dist +from torch.utils.data import Sampler +from torchdata.stateful_dataloader import StatefulDataLoader + +from arpeggio.chord import Chord +from arpeggio.dataset import ( + ArpeggioBaseDataset, + ArpeggioIterableDataset, + ArpeggioMapStyleDataset, + ArpeggioMultiSourceIterableDataset, + ArpeggioTinyIterableDataset, +) +from arpeggio.tuners.base import TransformBase + + +__all__ = [ + "ArpeggioBaseDataloader", + "ArpeggioMapStyleDataloader", + "ArpeggioIterableDataloader", +] + + +# Default TOKENIZERS_PARALLELISM=false is safer +os.environ["TOKENIZERS_PARALLELISM"] = os.getenv("TOKENIZERS_PARALLELISM", "false") + +logger = logging.getLogger(__name__) + + +def _init_worker_logging(worker_rank: int, dp_rank: int = 0, level: int = logging.WARNING): + root_logger = logging.getLogger() + + # Save existing file handlers before clearing + existing_file_handlers = [h for h in root_logger.handlers if isinstance(h, logging.FileHandler)] + + # Clear all handlers and reconfigure + for handler in root_logger.handlers[:]: + root_logger.removeHandler(handler) + + formatter = logging.Formatter( + f"[Rank {dp_rank} - Worker {worker_rank}] %(asctime)s - %(name)s - %(levelname)s - %(message)s" + ) + + # Re-add file handlers with new formatter + for file_handler in existing_file_handlers: + file_handler.setFormatter(formatter) + root_logger.addHandler(file_handler) + + # Add console handler + console_handler = logging.StreamHandler() + console_handler.setFormatter(formatter) + root_logger.addHandler(console_handler) + + root_logger.setLevel(level) + + +@dataclass +class DataloaderArgs: + num_epoch: int = 1 + iterable: bool = False + tiny_iterable: bool = False + max_micro_steps: Optional[int] = None + generate_infinitely: bool = False + chunks_per_step: int = 1 + max_seq_len: Optional[int] = None + prefetch_factor: Optional[int] = None + + # Regular batching + micro_batch_size: int = 1 + + # Continuous batching + is_continuous_batch: bool = False + max_tokens_per_batch: int = 2048 + max_samples_per_batch: int = 32 + + pad_to_multiple_of: int = 1 + + num_workers: int = 0 + shuffle: bool = False + seed: int = 137 + allow_skip_files: bool = False + est_continuous_batch_efficiency: float = 0.9 + + # deprecated + max_micro_steps_per_epoch: Optional[int] = None + + def __post_init__(self): + if self.max_micro_steps_per_epoch is not None: + warnings.warn( + "max_micro_steps_per_epoch has been deprecated, please use max_micro_steps instead", DeprecationWarning + ) + self.max_micro_steps = self.max_micro_steps_per_epoch // self.num_epoch + + +class ArpeggioBaseDataloader: + _inner_loader: StatefulDataLoader + + def __init__( + self, + dataset: ArpeggioBaseDataset, + args: DataloaderArgs, + dp_group: Optional[dist.ProcessGroup] = None, + ): + self.dataset = dataset + self.args = args + self.dp_group = dp_group + + self.worker_init_fn = None + if args.num_workers > 0: + self.worker_init_fn = partial( + _init_worker_logging, + dp_rank=self.dp_rank, + ) + + @property + def dp_rank(self) -> int: + if self.dp_group is None: + return 0 + return self.dp_group.rank() + + @property + def dp_size(self) -> int: + if self.dp_group is None: + return 1 + return self.dp_group.size() + + @property + def global_num_workers(self) -> int: + if self.args.num_workers == 0: + return self.dp_size + return self.dp_size * self.args.num_workers + + @property + def transform(self) -> TransformBase: + return self.dataset.transform + + def __len__(self) -> Optional[int]: + if self.args.generate_infinitely: + return None + return len(self._inner_loader) // self.args.chunks_per_step + + def __iter__(self) -> Iterator[Chord]: + chunk = [] + for note in self._inner_loader: + chunk.append(note) + if len(chunk) >= self.args.chunks_per_step: + yield self.transform.collate(chunk) + chunk = [] + + def state_dict(self) -> dict: + r: dict = { + f"loader_{self.dp_rank}": self._inner_loader.state_dict(), + } + return r + + def load_state_dict(self, state_dict: dict): + key = f"loader_{self.dp_rank}" + assert key in state_dict, f"{key} not found in state_dict, dp_size may diff from checkpoitns" + self._inner_loader.load_state_dict(state_dict[key]) + + def _gather_state_dict(self): + if self.dp_group is None: + return self.state_dict() + + backend_name = self.dp_group._get_backend_name() + if backend_name == "undefined": + return self.state_dict() + + all_states = [{}] * self.dp_size + dist.all_gather_object(all_states, self.state_dict(), self.dp_group) + return {k: v for s in all_states for k, v in s.items()} + + def dump_checkpoint(self, checkpoint_dir: str): + sd = self._gather_state_dict() + + if self.dp_rank != 0: + return + + os.makedirs(checkpoint_dir, exist_ok=True) + + fp = os.path.join(checkpoint_dir, "dataloader_state.json") + with open(fp, "w") as f: + json.dump(sd, f) + size = os.path.getsize(fp) + logging.info(f"dump_checkpoint finished, checkpoint_file: {fp}, file size: {size}") + + def resume_from_checkpoint(self, checkpoint_dir: str): + fp = os.path.join(checkpoint_dir, "dataloader_state.json") + sd = json.load(open(fp)) + self.load_state_dict(sd) + return sd + + +class ArpeggioIterableDataloader(ArpeggioBaseDataloader): + def __init__( + self, + dataset: Union[ArpeggioIterableDataset, ArpeggioTinyIterableDataset, ArpeggioMultiSourceIterableDataset], + args: DataloaderArgs, + dp_group: Optional[dist.ProcessGroup] = None, + ): + super().__init__(dataset=dataset, args=args, dp_group=dp_group) + + self._inner_loader = StatefulDataLoader( + dataset=self.dataset, + num_workers=self.args.num_workers, + collate_fn=self.transform.collate, + worker_init_fn=self.worker_init_fn, + prefetch_factor=None if self.args.num_workers == 0 else self.args.prefetch_factor, + ) + + +class ArpeggioMapStyleDataloader(ArpeggioBaseDataloader): + def __init__( + self, + dataset: ArpeggioMapStyleDataset, + args: DataloaderArgs, + batch_sampler: Optional[Sampler] = None, + dp_group: Optional[dist.ProcessGroup] = None, + ): + super().__init__(dataset=dataset, args=args, dp_group=dp_group) + + self._inner_loader = StatefulDataLoader( + dataset=self.dataset, + num_workers=self.args.num_workers, + batch_sampler=batch_sampler, + collate_fn=partial( + self.transform.collate, + continuous_batch=self.args.is_continuous_batch, + pad_to_multiple_of=self.args.pad_to_multiple_of, + ), + worker_init_fn=self.worker_init_fn, + prefetch_factor=None if self.args.num_workers == 0 else self.args.prefetch_factor, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/dataset/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/dataset/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0fbb1e1fd32931076a9473b2706644337b2b6351 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/dataset/__init__.py @@ -0,0 +1,5 @@ +from .base import ArpeggioBaseDataset +from .iterable import ArpeggioIterableDataset +from .map_style import ArpeggioMapStyleDataset +from .multi_source_iterable import ArpeggioMultiSourceIterableDataset +from .tiny_iterable import ArpeggioTinyIterableDataset diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/dataset/base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/dataset/base.py new file mode 100644 index 0000000000000000000000000000000000000000..8bc8b41967a63225d2a5f5dae9fc30edd851882e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/dataset/base.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +from torch.utils.data import IterableDataset, get_worker_info + +from arpeggio.chord import Chord +from arpeggio.tuners import TransformBase +from arpeggio.utils.io_utils import abspath + + +class ArpeggioBaseDataset: + """Base class with universal utils like processing data into model inputs. + + This base class has the following features + - Find all dataset files + - Load model config and processor + - Process conversation into model inputs + """ + + def __init__( + self, + filepaths: list[str], + transform: TransformBase, + pad_to_multiple_of: int = 1, + dp_rank: int = 0, + dp_size: int = 1, + ): + filepaths = [abspath(filepath) for filepath in filepaths] + + self.filepaths = filepaths + self.transform = transform + self.pad_to_multiple_of = pad_to_multiple_of + self.dp_rank = dp_rank + self.dp_size = dp_size + + @property + def is_iterable(self) -> bool: + return isinstance(self, IterableDataset) + + @property + def worker_rank(self) -> int: + worker_info = get_worker_info() + if worker_info is None: + return self.dp_rank + return worker_info.num_workers * self.dp_rank + worker_info.id + + @property + def worker_world_size(self) -> int: + worker_info = get_worker_info() + if worker_info is None: + return self.dp_size + return worker_info.num_workers * self.dp_size + + def process_item(self, item: dict) -> Chord: + sample = self.transform.preprocess(item) + if self.pad_to_multiple_of > 1: + # Pad the indiviaul items for zig-zag ring attention + sample = self.transform.collate([sample], pad_to_multiple_of=self.pad_to_multiple_of) + sample["attention_mask"].fill_(1) + return sample + + def state_dict(self) -> dict: ... + + def load_state_dict(self, state_dict: dict): ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/dataset/iterable.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/dataset/iterable.py new file mode 100644 index 0000000000000000000000000000000000000000..9e43b1b8b072437aed10ac86689502220c2ef302 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/dataset/iterable.py @@ -0,0 +1,325 @@ +from __future__ import annotations + +import logging +import os +import random +import traceback +import warnings +from typing import Iterator, Optional, TypeVar + +from torch.utils.data import IterableDataset + +from arpeggio.chord import Chord +from arpeggio.tuners import TransformBase +from arpeggio.utils.io_utils import BufferedIterator, read_rows_from_dataset_file + +from .base import ArpeggioBaseDataset +from .utils import shuffle_samples_for_file_content + + +# DISABLE_EPOCH_SHUFFLE is for aligning with previous dualpipe baselines +DISABLE_EPOCH_SHUFFLE = os.getenv("DISABLE_EPOCH_SHUFFLE", "0") == "1" + + +T = TypeVar("T") + +Filepaths = list[str] +RankToFilepaths = list[Filepaths] + + +class ArpeggioIterableDataset(ArpeggioBaseDataset, IterableDataset[Chord]): + """In multi-worker dataloaders, dataset instance is copied to each worker and unserialized by pickle. + So, any Initialization per worker should be done in __iter__ or __next__ methods. + """ + + def __init__( + self, + transform: TransformBase, + filepaths: Optional[Filepaths] = None, + rank_to_filepaths: Optional[RankToFilepaths] = None, + max_seq_len: Optional[int] = None, + micro_batch_size: int = 1, + is_continuous_batch: bool = False, + max_tokens_per_batch: int = 2048, + max_samples_per_batch: int = 32, + pad_to_multiple_of: int = 1, + shuffle: bool = False, + num_epoch: int = 1, + max_micro_steps: Optional[int] = None, + generate_infinitely: bool = False, + allow_skip_files: bool = False, + seed: int = 137, + dp_rank: int = 0, + dp_size: int = 1, + ): + if filepaths is not None: + assert rank_to_filepaths is None, "Can't use both filepaths and rank_to_filepaths" + self._rank_to_filepaths = None + + elif rank_to_filepaths is not None: + assert filepaths is None, "Can't use both filepaths and rank_to_filepaths" + + all_filepaths = [] + for filepaths in rank_to_filepaths: + all_filepaths.extend(filepaths) + filepaths = all_filepaths + self._rank_to_filepaths = rank_to_filepaths + + else: + raise ValueError("Either filepaths or rank_to_filepaths must be provided") + + super().__init__( + filepaths=filepaths, + transform=transform, + pad_to_multiple_of=pad_to_multiple_of, + dp_rank=dp_rank, + dp_size=dp_size, + ) + assert num_epoch >= 1 + + if max_seq_len is None and is_continuous_batch: + max_seq_len = max_tokens_per_batch + self.max_seq_len = max_seq_len + + self.sample_count_skipped_all = 0 + + self.micro_batch_size = micro_batch_size + self.is_continuous_batch = is_continuous_batch + self.max_tokens_per_batch = max_tokens_per_batch + self.max_samples_per_batch = max_samples_per_batch + self.pad_to_multiple_of = pad_to_multiple_of + + self.shuffle = shuffle + self.num_epoch = num_epoch + self.max_micro_steps = max_micro_steps + self.generate_infinitely = generate_infinitely + self.allow_skip_files = allow_skip_files + self.seed = seed + + # stateful fields + self._epoch_num: int = 0 + self._current_file_idx: int = 0 + self._current_row_idx: int = 0 + self._current_step_num: int = 0 + + def state_dict(self) -> dict: + return { + "epoch_num": self._epoch_num, + "current_file_idx": self._current_file_idx, + "current_row_idx": self._current_row_idx, + "current_step_num": self._current_step_num, + } + + def load_state_dict(self, state_dict: dict): + self._epoch_num = state_dict["epoch_num"] + self._current_file_idx = state_dict["current_file_idx"] + self._current_row_idx = state_dict["current_row_idx"] + self._current_step_num = state_dict["current_step_num"] + + def _get_worker_files_for_epoch(self, epoch_num: int = 0): + if self._rank_to_filepaths is not None: + if len(self._rank_to_filepaths) != self.worker_world_size: + raise RuntimeError( + "Mis-aligned worker count and rank_to_filepaths. " + f"Has {self.worker_world_size} workers but " + f"rank_to_filepaths has only {len(self._rank_to_filepaths)} ranks." + ) + filepaths = list(self._rank_to_filepaths[self.worker_rank]) + return filepaths + + # determine files for local worker + local_file_paths = list(self.filepaths) + if self.shuffle: + rng = random.Random(self.seed) + rng.shuffle(local_file_paths) + + local_file_paths = local_file_paths[self.worker_rank :: self.worker_world_size] + + # Warn if this shard is receiving way more or less files + expected_files_per_shard = len(self.filepaths) / self.worker_world_size + ratio = len(local_file_paths) / expected_files_per_shard + if ratio > 1.2 or ratio < 0.8: + warnings.warn( + f"[DataImbalanceWarning] rank={self.dp_rank} worker={self.worker_rank} " + f"receives {ratio:.2f}x the average number of files", + UserWarning, + ) + + # Shuffle if necessary + local_file_paths = list(local_file_paths) + if self.shuffle and not DISABLE_EPOCH_SHUFFLE: + random.Random(self.seed + self.worker_rank + epoch_num).shuffle(local_file_paths) + + return local_file_paths + + def _iter_files_for_epoch( + self, + epoch_num: int = 0, + start_file_idx: int = 0, + start_row_idx: int = 0, + ) -> Iterator[tuple[list[dict], str, int, int]]: + file_idx = start_file_idx + row_idx = start_row_idx + + filepaths = self._get_worker_files_for_epoch(epoch_num) + filepaths = filepaths[file_idx:] + logging.debug(f"{filepaths[:3] = }") + + for file_idx, filepath in enumerate(filepaths, start=file_idx): + try: + rows = read_rows_from_dataset_file(filepath) + + except Exception as e: + if not self.allow_skip_files: + raise e + + err_trace = traceback.format_exc() + warnings.warn(f"Failed to read {filepath} due to {e}: {err_trace}") + + else: + rows = shuffle_samples_for_file_content( + samples=rows, + seed=self.seed, + worker_rank=self.worker_rank, + epoch_num=epoch_num, + file_idx=file_idx, + filepath=filepath, + ) + + rows = rows[row_idx:] + yield rows, filepath, file_idx, row_idx + + row_idx = 0 + + def _iter_samples_for_epoch( + self, + epoch_num: int = 0, + start_file_idx: int = 0, + start_row_idx: int = 0, + ) -> Iterator[tuple[Chord, str, int, int]]: + file_iter = self._iter_files_for_epoch( + epoch_num=epoch_num, + start_file_idx=start_file_idx, + start_row_idx=start_row_idx, + ) + for rows, filepath, file_idx, row_idx in BufferedIterator(file_iter): + for row_idx, row in enumerate(rows, start=row_idx): + chord = self.process_item(row) + + extra_info = {} + if "extra_info" in chord: + extra_info = chord["extra_info"][0] + + # It's useful to store these information, not just for debugging + # our dataloader but also for DS to determine data source + extra_info["worker_rank"] = self.worker_rank + extra_info["worker_world_size"] = self.worker_world_size + extra_info["file_idx"] = file_idx + extra_info["row_idx"] = row_idx + extra_info["file_name"] = filepath + extra_info["seq_len"] = chord["input_ids"].shape[-1] + + chord["extra_info"] = [extra_info] + + yield chord, filepath, file_idx, row_idx + + def _iter_batches_for_epoch( + self, + epoch_num: int = 0, + start_file_idx: int = 0, + start_row_idx: int = 0, + ) -> Iterator[tuple[Chord, int, int]]: + current_batch = [] + current_tokens = 0 + + for sample, filepath, file_idx, row_idx in self._iter_samples_for_epoch( + epoch_num=epoch_num, + start_file_idx=start_file_idx, + start_row_idx=start_row_idx, + ): + seq_len = sample["input_ids"].shape[-1] + + # Skip empty sequences (e.g., from failed preprocessing with allow_skip=True) + if seq_len == 0: + self.sample_count_skipped_all += 1 + warnings.warn( + f"Found empty sample (seq_len=0) from {filepath}, will be skipped, " + f"{self.sample_count_skipped_all} samples have been skipped", + UserWarning, + ) + continue + + if self.max_seq_len and seq_len > self.max_seq_len: + self.sample_count_skipped_all += 1 + warnings.warn(f"Found sample with length {seq_len} from {filepath}, will be skipped, {self.sample_count_skipped_all} samples have been skipped", UserWarning) + continue + + # Now decide if would_exceed or not + if self.is_continuous_batch: + would_exceed_token = current_tokens + seq_len > self.max_tokens_per_batch + would_exceed_sample = len(current_batch) >= self.max_samples_per_batch + would_exceed = would_exceed_token or would_exceed_sample + + else: + would_exceed = len(current_batch) >= self.micro_batch_size + + if would_exceed: + batch = self.transform.collate( + batch=current_batch, + continuous_batch=self.is_continuous_batch, + pad_to_multiple_of=self.pad_to_multiple_of, + ) + yield batch, file_idx, row_idx + + current_batch = [] + current_tokens = 0 + + current_batch.append(sample) + current_tokens += seq_len + + if len(current_batch) > 0: + if not self.is_continuous_batch and len(current_batch) < self.micro_batch_size: + return # drop last small batch + + batch = self.transform.collate( + batch=current_batch, + continuous_batch=self.is_continuous_batch, + pad_to_multiple_of=self.pad_to_multiple_of, + ) + yield batch, file_idx, row_idx + + def __len__(self) -> int: + if self.max_micro_steps is None: + raise ValueError("max_micro_steps is None") + return self.max_micro_steps + + def __iter__(self) -> Iterator[Chord]: + current_epoch_num = self._epoch_num + + while True: + if current_epoch_num >= self.num_epoch and not self.generate_infinitely: + break + + batch_iter = self._iter_batches_for_epoch( + epoch_num=self._epoch_num, + start_file_idx=self._current_file_idx, + start_row_idx=self._current_row_idx, + ) + for step_num, (batch, file_idx, row_idx) in enumerate( + batch_iter, + start=self._current_step_num, + ): + self._current_file_idx = file_idx + self._current_row_idx = row_idx + self._current_step_num = step_num + yield batch + + if self.max_micro_steps is not None: + if step_num + 1 >= self.max_micro_steps: + break + + current_epoch_num += 1 + + self._epoch_num = current_epoch_num + self._current_file_idx = 0 + self._current_row_idx = 0 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/dataset/map_style.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/dataset/map_style.py new file mode 100644 index 0000000000000000000000000000000000000000..8fe236218847dd8d7eabed509b0ec8fc5b250368 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/dataset/map_style.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +from torch.utils.data import Dataset + +from arpeggio.chord import Chord +from arpeggio.tuners import TransformBase +from arpeggio.utils.io_utils import read_rows_from_dataset_file + +from .base import ArpeggioBaseDataset + + +class ArpeggioMapStyleDataset(ArpeggioBaseDataset, Dataset[Chord]): + def __init__( + self, + filepaths: list[str], + transform: TransformBase, + pad_to_multiple_of: int = 1, + dp_rank: int = 0, + dp_size: int = 1, + ): + super().__init__( + filepaths=filepaths, + transform=transform, + pad_to_multiple_of=pad_to_multiple_of, + dp_rank=dp_rank, + dp_size=dp_size, + ) + self._load_data() + + def _load_data(self): + # Optionally we can speed this up by reading on first rank then broadcasting + # But mapstyle dataset is designed for small use cases so not necessary. + items = [] + for filepath in self.filepaths: + rows = read_rows_from_dataset_file(filepath) + items.extend(rows) + self.items = items + + def __len__(self) -> int: + return len(self.items) + + def __getitem__(self, index: int) -> Chord: + chord = self.process_item(self.items[index]) + + extra_info = {} + if "extra_info" in chord: + extra_info = chord["extra_info"][0] + + extra_info = chord["extra_info"][0] + extra_info["worker_rank"] = self.worker_rank + extra_info["dataset_idx"] = index + extra_info["seq_len"] = chord["input_ids"].shape[-1] + + chord["extra_info"] = [extra_info] + + return chord diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/dataset/multi_source_iterable.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/dataset/multi_source_iterable.py new file mode 100644 index 0000000000000000000000000000000000000000..b2258ecacc0f7e50b9f8593df246d6f91b11a095 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/dataset/multi_source_iterable.py @@ -0,0 +1,462 @@ +import math +import random +import traceback +import warnings +from dataclasses import dataclass +from typing import Iterator, List, Optional, Tuple + +from torch.utils.data import IterableDataset, get_worker_info + +from arpeggio.chord import Chord, make_dummy_chord +from arpeggio.meta import DataSourceMeta +from arpeggio.tuners import TransformBase +from arpeggio.utils.io_utils import BufferedIterator, read_rows_from_dataset_file + +from .base import ArpeggioBaseDataset +from .utils import shuffle_samples_for_file_content + + +@dataclass +class DataSourceShard: + meta: DataSourceMeta + filepaths: List[str] + est_samples: int + est_tokens: float + + +class ArpeggioMultiSourceIterableDataset(ArpeggioBaseDataset, IterableDataset[Chord]): + def __init__( + self, + data_source_metas: List[DataSourceMeta], + num_workers: int, + transform: TransformBase, + micro_batch_size: int = 1, + max_seq_len: Optional[int] = None, + is_continuous_batch: bool = False, + max_tokens_per_batch: int = 2048, + max_samples_per_batch: int = 32, + pad_to_multiple_of: int = 1, + shuffle: bool = False, + num_epoch: int = 1, + max_micro_steps: Optional[int] = None, + generate_infinitely: bool = False, + allow_skip_files: bool = False, + est_continuous_batch_efficiency: float = 0.9, + seed: int = 137, + dp_rank: int = 0, + dp_size: int = 1, + ): + filepaths = [] + for meta in data_source_metas: + filepaths.extend(meta["filepaths"]) + + super().__init__( + filepaths=filepaths, + transform=transform, + pad_to_multiple_of=pad_to_multiple_of, + dp_rank=dp_rank, + dp_size=dp_size, + ) + + if max_seq_len is None and is_continuous_batch: + max_seq_len = max_tokens_per_batch + + self.data_source_metas = data_source_metas + + self.micro_batch_size = micro_batch_size + self.max_seq_len = max_seq_len + self.is_continuous_batch = is_continuous_batch + self.max_tokens_per_batch = max_tokens_per_batch + self.max_samples_per_batch = max_samples_per_batch + + self.shuffle = shuffle + self.num_epoch = num_epoch + self.max_micro_steps = max_micro_steps + self.generate_infinitely = generate_infinitely + self.allow_skip_files = allow_skip_files + self.seed = seed + self.est_continuous_batch_efficiency = est_continuous_batch_efficiency + + # We keep this only for validation later + self._num_workers = max(num_workers, 1) + + # Distribute filepaths evenly across workers & calculate number of steps + self._plan_dataloading() + + # Setup stateful fields for checkpoint / resume + self._setup_stateful_fields() + + @property + def source_names(self) -> List[str]: + return [meta["name"] for meta in self.data_source_metas] + + def _plan_dataloading(self): + """Does 2 things + 1. Distribute filepaths evenly across workers + 2. Estimate the number of steps for each epoch + + This function is also deterministic based on the seed. + """ + + rng = random.Random(self.seed) + total_num_workers = self._num_workers * self.dp_size + + # Later on we will allocate files to workers one at a time + # we use a simple round robin strategy. + def make_round_robin_scheduler(): + while True: + worker_idxs = list(range(total_num_workers)) + rng.shuffle(worker_idxs) + yield from worker_idxs + + # Build rank_to_shards + scheduler = make_round_robin_scheduler() + self.rank_to_shards: List[List[DataSourceShard]] = [[] for _ in range(total_num_workers)] + + for meta in self.data_source_metas: + # Split filepaths evenly across workers + filepaths = list(meta["filepaths"]) + rng.shuffle(filepaths) + rank_to_filepaths = [[] for _ in range(total_num_workers)] + for filepath in filepaths: + worker_idx = next(scheduler) + rank_to_filepaths[worker_idx].append(filepath) + + # Merge with rank_to_shards & accumulate aux info + for worker_idx, filepaths in enumerate(rank_to_filepaths): + est_samples = int(meta["avg_samples_per_file"] * len(filepaths)) + est_tokens = meta["avg_tokens_per_file"] * len(filepaths) + self.rank_to_shards[worker_idx].append( + DataSourceShard( + meta=meta, + filepaths=filepaths, + est_samples=est_samples, + est_tokens=est_tokens, + ) + ) + + # Estimate the total number of steps (if not generating infinitely) + rank_to_est_steps = [] + for worker_idx, shards in enumerate(self.rank_to_shards): + if self.is_continuous_batch: + num_tokens_per_epoch = sum(shard.est_tokens for shard in shards) + est_tokens_per_batch = self.max_tokens_per_batch * self.est_continuous_batch_efficiency + est_steps_per_epoch = num_tokens_per_epoch / est_tokens_per_batch + + else: + num_samples_per_epoch = sum(shard.est_samples for shard in shards) + est_steps_per_epoch = num_samples_per_epoch / self.micro_batch_size + + assert est_steps_per_epoch > 0, f"Estimated that worker={worker_idx} won't receive any data" + rank_to_est_steps.append(est_steps_per_epoch * self.num_epoch) + + # We already don't + min_est_steps_per_worker = min(rank_to_est_steps) + max_est_steps_per_worker = max(rank_to_est_steps) + ratio = min_est_steps_per_worker / max_est_steps_per_worker + if ratio < 0.9: + warnings.warn( + f"Estimated that the some ranks will receive only {ratio}% the tokens of other ranks", + UserWarning, + ) + self._est_steps_per_worker = math.ceil(max_est_steps_per_worker) + + if self.max_micro_steps is not None: + self._steps_per_worker = math.ceil(self.max_micro_steps / self._num_workers) + else: + self._steps_per_worker = self._est_steps_per_worker + + def _setup_stateful_fields(self): + self._epoch_num = 0 + self._step_num = 0 + # Using a list doesn't seem to work, use a dict instead + self._source_to_file_idx = dict.fromkeys(range(len(self.data_source_metas)), 0) + self._source_to_row_idx = dict.fromkeys(range(len(self.data_source_metas)), 0) + + def state_dict(self) -> dict: + return { + "epoch_num": self._epoch_num, + "step_num": self._step_num, + "source_to_file_idx": self._source_to_file_idx, + "source_to_row_idx": self._source_to_row_idx, + } + + def load_state_dict(self, state_dict: dict): + self._epoch_num = state_dict["epoch_num"] + self._step_num = state_dict["step_num"] + self._source_to_file_idx = {int(k): v for k, v in state_dict["source_to_file_idx"].items()} + self._source_to_row_idx = {int(k): v for k, v in state_dict["source_to_row_idx"].items()} + + def _iter_files( + self, + filepaths: List[str], + epoch_num: int, + start_file_idx: int = 0, + start_row_idx: int = 0, + ) -> Iterator[Tuple[List[dict], str, int, int]]: + # Load samples from files + file_idx, row_idx = start_file_idx, start_row_idx + for file_idx, filepath in enumerate(filepaths[file_idx:], start=file_idx): + try: + rows = read_rows_from_dataset_file(filepath) + + except Exception as e: + if not self.allow_skip_files: + raise e + + err_trace = traceback.format_exc() + warnings.warn(f"Failed to fread {filepath} due to {e}: {err_trace}") + + else: + rows = shuffle_samples_for_file_content( + samples=rows, + seed=self.seed, + worker_rank=self.worker_rank, + epoch_num=epoch_num, + file_idx=file_idx, + filepath=filepath, + ) + + rows = rows[row_idx:] + yield rows, filepath, file_idx, row_idx + + row_idx = 0 + + def _iter_samples_from_single_shard( + self, + shard: DataSourceShard, + epoch_num: int, + start_file_idx: int = 0, + start_row_idx: int = 0, + ) -> Iterator[Tuple[Chord, str, str, int, int]]: + # Shuffle files for epoch + filepaths = list(shard.filepaths) + rng = random.Random(self.seed + self.worker_rank + epoch_num) + rng.shuffle(filepaths) + + # Build file iterator and buffer it + files_iter = self._iter_files( + filepaths=filepaths, + epoch_num=epoch_num, + start_file_idx=start_file_idx, + start_row_idx=start_row_idx, + ) + files_iter = BufferedIterator(files_iter) + source_name = shard.meta["name"] + + # Process each item, add metadata, and yield + for rows, filepath, file_idx, row_idx in files_iter: + for row_idx, row in enumerate(rows, start=row_idx): + chord = self.process_item(row) + + extra_info = {} + if "extra_info" in chord: + extra_info = chord["extra_info"][0] + + # It's useful to store these information, not just for debugging + # but also for to determine data source + extra_info["worker_rank"] = self.worker_rank + extra_info["worker_world_size"] = self.worker_world_size + extra_info["file_idx"] = file_idx + extra_info["row_idx"] = row_idx + extra_info["file_name"] = filepath + extra_info["source_name"] = source_name + extra_info["seq_len"] = chord["input_ids"].shape[-1] + + chord["extra_info"] = [extra_info] + + yield chord, filepath, file_idx, row_idx + + def _iter_samples( + self, + epoch_num: int, + source_to_start_file_idx: List[int], + source_to_start_row_idx: List[int], + ) -> Iterator[Tuple[Chord, int, str, int, int]]: + shards = self.rank_to_shards[self.worker_rank] + + # Initialize iterators for every data source + shard_iters = [] + for source_idx, shard in enumerate(shards): + shard_iter = self._iter_samples_from_single_shard( + shard=shard, + epoch_num=epoch_num, + start_file_idx=source_to_start_file_idx[source_idx], + start_row_idx=source_to_start_row_idx[source_idx], + ) + shard_iters.append(shard_iter) + + # Pre-determine the order to load samples from sources + loading_order = _get_loading_order( + shards=shards, + worker_rank=self.worker_rank, + epoch_num=epoch_num, + ) + + for source_idx in loading_order: + shard_iter = shard_iters[source_idx] + + try: + chord, filepath, file_idx, row_idx = next(shard_iter) + except StopIteration: + # Skip if end of iteration reached + # Perhaps there could be an option to control if we end the epoch + continue + + yield chord, source_idx, filepath, file_idx, row_idx + + def _iter_batches( + self, + epoch_num: int, + source_to_start_file_idx: List[int], + source_to_start_row_idx: List[int], + ) -> Iterator[Tuple[Chord, dict[int, Tuple[int, int]]]]: + current_batch = [] + current_tokens = 0 + source_to_offsets = {} + + for chord, source_idx, filepath, file_idx, row_idx in self._iter_samples( + epoch_num=epoch_num, + source_to_start_file_idx=source_to_start_file_idx, + source_to_start_row_idx=source_to_start_row_idx, + ): + seq_len = chord["input_ids"].shape[-1] + + # Skip empty sequences (e.g., from failed preprocessing with allow_skip=True) + if seq_len == 0: + warnings.warn( + f"Found empty sample (seq_len=0) from {filepath}, will be skipped.", + UserWarning, + ) + continue + + # Skip invalid sample + if self.max_seq_len and seq_len > self.max_seq_len: + warnings.warn( + f"Found sample with length {seq_len} from {filepath}. Sample will be skipped.", + UserWarning, + ) + continue + + # Check if would exceed current batch + if self.is_continuous_batch: + would_exceed_token = current_tokens + seq_len > self.max_tokens_per_batch + would_exceed_sample = len(current_batch) >= self.max_samples_per_batch + would_exceed = would_exceed_token or would_exceed_sample + + else: + would_exceed = len(current_batch) >= self.micro_batch_size + + if would_exceed: + batch = self.transform.collate( + batch=current_batch, + continuous_batch=self.is_continuous_batch, + pad_to_multiple_of=self.pad_to_multiple_of, + ) + yield batch, source_to_offsets + + current_batch = [] + current_tokens = 0 + source_to_offsets = {} + + current_batch.append(chord) + current_tokens += seq_len + source_to_offsets[source_idx] = (file_idx, row_idx) + + if len(current_batch) > 0: + if not self.is_continuous_batch: + # Still have to pad this sample up to micro_batch_size + for _ in range(self.micro_batch_size - len(current_batch)): + current_batch.append( + make_dummy_chord( + batch_size=1, + seq_len=self.pad_to_multiple_of, + use_mrope=self.transform.should_use_mrope, + has_labels=True, + ) + ) + + batch = self.transform.collate( + batch=current_batch, + continuous_batch=self.is_continuous_batch, + pad_to_multiple_of=self.pad_to_multiple_of, + ) + yield batch, source_to_offsets + + def __len__(self) -> int: + return self._steps_per_worker * self._num_workers + + def __iter__(self) -> Iterator[Chord]: + worker_info = get_worker_info() + if worker_info is None: + assert self._num_workers == 1, "Number of workers mis-aligned" + else: + assert self._num_workers == worker_info.num_workers, "Number of workers mis-aligned" + + if not self.generate_infinitely: + if self._step_num >= self._steps_per_worker: + warnings.warn("dataset has been fully consumed, it cannot generate any new data", UserWarning) + return # StopIteration + + # Note: Currently we spill over to the next epoch + # An alternative approach is to start generating dummy data to + # fill in the gaps + + num_dummy_steps = 0 + while True: + batch_iter = self._iter_batches( + epoch_num=self._epoch_num, + source_to_start_file_idx=dict(self._source_to_file_idx), + source_to_start_row_idx=dict(self._source_to_row_idx), + ) + for batch, source_to_offsets in batch_iter: + self._step_num += 1 + for source_idx, (file_offset, row_offset) in source_to_offsets.items(): + self._source_to_file_idx[source_idx] = file_offset + self._source_to_row_idx[source_idx] = row_offset + 1 + yield batch + + # Check if should stop + if not self.generate_infinitely: + if self._step_num >= self._steps_per_worker: + break + + # Check if should stop (Needed 2 breaks as there are 2 loops) + if not self.generate_infinitely: + if self._step_num >= self._steps_per_worker: + break + + self._epoch_num += 1 + self._source_to_file_idx = dict.fromkeys(range(len(self.data_source_metas)), 0) + self._source_to_row_idx = dict.fromkeys(range(len(self.data_source_metas)), 0) + + if not self.generate_infinitely: + # Number of epoch has reached + if self._epoch_num >= self.num_epoch: + num_dummy_steps = max(self._steps_per_worker - self._step_num, 0) + break + + dummy_batch_size = 1 if self.is_continuous_batch else self.micro_batch_size + for _ in range(num_dummy_steps): + yield make_dummy_chord( + batch_size=dummy_batch_size, + seq_len=self.pad_to_multiple_of, + use_mrope=self.transform.should_use_mrope, + has_labels=True, + ) + + +def _get_loading_order( + shards: List[DataSourceShard], + worker_rank: int, + epoch_num: int, + seed: int = 137, +) -> List[int]: + order = [] + for i, shard in enumerate(shards): + order.extend([i] * shard.est_samples) + + rng = random.Random(seed + worker_rank + epoch_num) + rng.shuffle(order) + + return order diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/dataset/tiny_iterable.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/dataset/tiny_iterable.py new file mode 100644 index 0000000000000000000000000000000000000000..f3846f92648c593f132c8ba1b3e55d4a8d7a1991 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/dataset/tiny_iterable.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +import random +from typing import Iterator, Optional + +from arpeggio.chord import Chord +from arpeggio.tuners import TransformBase +from arpeggio.utils.io_utils import read_rows_from_dataset_file + +from .iterable import ArpeggioIterableDataset + + +class ArpeggioTinyIterableDataset(ArpeggioIterableDataset): + """Dataset for small files where all content is loaded into memory first. + + Unlike ArpeggioIterableDataset which distributes files across workers, + this dataset reads all files, combines samples into one list, then + distributes samples by index across dp ranks. + + Useful when you have few large files but want even distribution of samples. + """ + + def __init__( + self, + filepaths: list[str], + **kwargs, + ): + super().__init__(filepaths=filepaths, **kwargs) + self._all_samples: Optional[list[dict]] = None + + def _load_all_samples(self) -> list[dict]: + if self._all_samples is not None: + return self._all_samples + + all_rows = [] + for filepath in self.filepaths: + rows = read_rows_from_dataset_file(filepath) + for row in rows: + row["__source_file__"] = filepath + all_rows.extend(rows) + + self._all_samples = all_rows + return all_rows + + def _iter_samples_for_epoch( + self, + epoch_num: int = 0, + start_file_idx: int = 0, + start_row_idx: int = 0, + ) -> Iterator[tuple[Chord, str, int, int]]: + all_samples = self._load_all_samples() + + if self.shuffle: + samples = list(all_samples) + rng = random.Random(self.seed + self.worker_rank + epoch_num) + rng.shuffle(samples) + else: + samples = all_samples + + samples = samples[self.worker_rank :: self.worker_world_size] + samples = samples[start_row_idx:] + + for row_idx, row in enumerate(samples, start=start_row_idx): + chord = self.process_item(row) + + extra_info = {} + if "extra_info" in chord: + extra_info = chord["extra_info"][0] + + extra_info["worker_rank"] = self.worker_rank + extra_info["worker_world_size"] = self.worker_world_size + extra_info["file_idx"] = 0 + extra_info["row_idx"] = row_idx + extra_info["file_name"] = row.get("__source_file__", "") + extra_info["seq_len"] = chord["input_ids"].shape[-1] + + chord["extra_info"] = [extra_info] + + yield chord, row.get("__source_file__", ""), 0, row_idx diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/dataset/utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/dataset/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..15b1962afa81fb4fdea97fe8fd75b810caffae7a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/dataset/utils.py @@ -0,0 +1,32 @@ +import hashlib +import random +from typing import Optional, TypeVar + + +T = TypeVar("T") + + +def hash_string_to_uint16(text: str) -> int: + hash_digest = hashlib.sha256(text.encode()).hexdigest() + int_hash = int(hash_digest, 16) + uint16_hash = int_hash % (1 << 16) + return uint16_hash + + +def shuffle_samples_for_file_content( + samples: list[T], + seed: int = 137, + worker_rank: int = 0, + epoch_num: int = 0, + file_idx: int = 0, + filepath: Optional[str] = None, +) -> list[T]: + shuffle_seed = seed + worker_rank + epoch_num + file_idx + if filepath is not None: + shuffle_seed += hash_string_to_uint16(filepath) + rng = random.Random(shuffle_seed) + + samples = list(samples) + rng.shuffle(samples) + + return samples diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/meta.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/meta.py new file mode 100644 index 0000000000000000000000000000000000000000..65ca592b52167a9e0240a2875dc73de18379e726 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/meta.py @@ -0,0 +1,77 @@ +from __future__ import annotations + +from typing import Optional, TypedDict + +from arpeggio.utils.io_utils import iter_rows_from_dataset_file + + +class ChordMeta(TypedDict): + seq_len: int + num_image_patches: Optional[int] + num_video_patches: Optional[int] + + +class FileMeta(TypedDict): + arpeggio_version: str + + transform_cls: str + transform_model_path: str + transform_model_type: str + + filepath: str + seq_len: list[int] + num_image_patches: list[int] + num_video_patches: list[int] + + +class DataSourceMeta(TypedDict): + name: str + filepaths: list[str] + + # Estimated dataset stats + avg_seq_len: float + avg_samples_per_file: float + avg_tokens_per_file: float + + # Metadata to tell us about preprocessing + transform_cls: str + transform_model_path: str + transform_model_type: str + arpeggio_version: str + + +def read_dataset_meta_paths(dataset_meta_paths: list[str]) -> dict[str, FileMeta]: + filepath_to_meta = {} + for dataset_meta_path in dataset_meta_paths: + for file_meta in iter_rows_from_dataset_file(dataset_meta_path): + filepath_to_meta[file_meta["filepath"]] = file_meta + return filepath_to_meta + + +# @dataclass +# class DatasetMetaManager: +# dataset_meta_paths: list[str] + +# def __post_init__(self): +# if isinstance(self.dataset_meta_paths, str): +# self.dataset_meta_paths = [self.dataset_meta_paths] + +# def iter_file_meta(self) -> Iterator[FileMeta]: +# for dataset_meta_path in self.dataset_meta_paths: +# # Just assume that it's all file meta +# yield from iter_rows_from_dataset_file(dataset_meta_path) + +# def list_file_token_counts(self) -> Iterator[Tuple[str, int]]: +# for file_meta in self.iter_file_meta(): +# yield file_meta["filepath"], sum(file_meta["seq_len"]) + +# def get_file_meta_dict(self, filepaths: list[str]) -> dict[str, FileMeta]: +# filepaths = set(filepaths) +# file_meta_dict = {} +# for meta in self.iter_file_meta(): +# if meta["filepath"] not in filepaths: +# continue +# file_meta_dict[meta["filepath"]] = meta +# for filepath in filepaths: +# assert filepath in file_meta_dict, f"Unable to find meta of {filepath}" +# return file_meta_dict diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/sampler.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..c4cee2edbcc0708130deff14713e47522c6458ff --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/sampler.py @@ -0,0 +1,198 @@ +from __future__ import annotations + +import os +import random +import warnings +from collections.abc import Iterator +from typing import Optional + +import torch.distributed as dist +from torch.utils.data import Sampler + +from arpeggio.utils.distributed import DistributedPlugin + + +DISABLE_EPOCH_SHUFFLE = os.getenv("DISABLE_EPOCH_SHUFFLE", "0") == "1" + + +class BatchSampler(Sampler[list[int]], DistributedPlugin): + def __init__( + self, + dataset_size: int, + batch_size: int = 1, + shuffle: bool = False, + seed: int = 137, + num_epoch: int = 1, + generate_infinitely: bool = False, + resume_micro_step_nb: int = 0, + dp_group: Optional[dist.ProcessGroup] = None, + ): + DistributedPlugin.__init__(self, dp_group) + self.dataset_size = dataset_size + + self.batch_size = batch_size + self.shuffle = shuffle + self.seed = seed + self.num_epoch = num_epoch + self.generate_infinitely = generate_infinitely + + self.resume_micro_step_nb = resume_micro_step_nb + + @property + def num_batches_per_rank(self): + # Assume drop last (default just makes sense) + global_batch_size = self.dp_size * self.batch_size + return self.dataset_size // global_batch_size + + def __len__(self) -> int: + if self.generate_infinitely: + raise TypeError("generating infinitely") + return self.num_batches_per_rank + + def __iter__(self) -> Iterator[list[int]]: + samples_per_epoch = self.num_batches_per_rank * self.batch_size + + epoch_nb = 0 + micro_step_nb = 0 + + while True: + if epoch_nb >= self.num_epoch and not self.generate_infinitely: + break + + idxs = list(range(self.dataset_size)) + if self.shuffle: + rng = random.Random(self.seed + epoch_nb) + rng.shuffle(idxs) + + local_idxs = idxs[self.dp_rank :: self.dp_size] + local_idxs = local_idxs[:samples_per_epoch] + + for offset in range(0, len(local_idxs), self.batch_size): + if micro_step_nb >= self.resume_micro_step_nb: + yield local_idxs[offset : offset + self.batch_size] + micro_step_nb += 1 + epoch_nb += 1 + + +class ContinuousBatchSampler(Sampler[list[int]], DistributedPlugin): + def __init__( + self, + seq_lens: list[int], + max_tokens_per_batch: int = 2048, + max_samples_per_batch: int = 32, + shuffle: bool = False, + seed: int = 137, + num_epoch: int = 1, + generate_infinitely: bool = False, + dp_group: Optional[dist.ProcessGroup] = None, + resume_micro_step_nb: int = 0, + ): + DistributedPlugin.__init__(self, dp_group) + + self.max_tokens_per_batch = max_tokens_per_batch + self.max_samples_per_batch = max_samples_per_batch + self.shuffle = shuffle + self.seed = seed + self.num_epoch = num_epoch + self.generate_infinitely = generate_infinitely + + self.resume_micro_step_nb = resume_micro_step_nb + + self.sample_infos = self._seq_lens_to_sample_infos(seq_lens) + self.batches = self._create_batches() + + def _seq_lens_to_sample_infos(self, seq_lens: list[int]) -> list[dict]: + filtered_count = 0 + sample_infos = [] + for idx, seq_len in enumerate(seq_lens): + if seq_len >= self.max_tokens_per_batch: + filtered_count += 1 + continue + + sample_infos.append({"idx": idx, "seq_len": seq_len}) + + if filtered_count > 0: + warnings.warn( + f"ContinuousBatchSampler: Filtered out {filtered_count} samples " + f"with token count > {self.max_tokens_per_batch}", + UserWarning, + ) + + return sample_infos + + def _create_batches(self) -> list[list[int]]: + if self.shuffle: + rng = random.Random(self.seed) + + batches = [] + + for _ in range(self.num_epoch): + batches_current_epoch = [] + current_batch: list[int] = [] + current_tokens = 0 + + # Shuffle sample order for every epoch + sample_infos = list(self.sample_infos) + if self.shuffle: + rng.shuffle(sample_infos) + + for sample_info in sample_infos: + # Kinda blindly trust this + seq_len = sample_info["seq_len"] + + # Check if will exceed limits + would_exceed_token = current_tokens + seq_len > self.max_tokens_per_batch + would_exceed_sample = len(current_batch) >= self.max_samples_per_batch + + if would_exceed_token or would_exceed_sample: + if len(current_batch) > 0: + batches_current_epoch.append(current_batch) + current_batch = [] + current_tokens = 0 + + # Add sample to current batch + current_batch.append(sample_info["idx"]) + current_tokens += seq_len + + # Handle remaining samples + if len(current_batch) > 0: + batches_current_epoch.append(current_batch) + + if self.shuffle: + rng.shuffle(batches_current_epoch) + + batches.extend(batches_current_epoch) + + return batches + + @property + def num_batches_per_rank(self): + # Assume drop last (default just makes sense) + return len(self.batches) // self.dp_size + + def __len__(self) -> int: + if self.generate_infinitely: + raise TypeError("generating infinitely") + return self.num_batches_per_rank + + def __iter__(self) -> Iterator[list[int]]: + epoch_nb = 0 + micro_step_nb = 0 + + while True: + if epoch_nb >= self.num_epoch and not self.generate_infinitely: + break + + batches = list(self.batches) + if self.shuffle and not DISABLE_EPOCH_SHUFFLE: + rng = random.Random(self.seed + epoch_nb) + rng.shuffle(batches) + + local_batches = batches[self.dp_rank :: self.dp_size] + local_batches = local_batches[: self.num_batches_per_rank] + + for batch in local_batches: + if micro_step_nb >= self.resume_micro_step_nb: + yield batch + micro_step_nb += 1 + epoch_nb += 1 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/tuners/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/tuners/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..895b1ce3d343a4fb87fe2a7d230c937939e04c29 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/tuners/__init__.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +from typing import Dict, Optional, Type + +from transformers import AutoConfig + +from .base import TransformBase +from .llm_tuner import LLMTransform + + +TRANSFORM_REGISTRY: Dict[str, Type[TransformBase]] = {} + + +def register_transform(name: str, cls: Type[TransformBase]): + TRANSFORM_REGISTRY[name] = cls + + +def load_transform( + model_path: str, + model_type: Optional[str] = None, + **extra_kwargs, +) -> TransformBase: + if model_type is None: + config = AutoConfig.from_pretrained(model_path) + model_type = config.model_type + + if model_type not in TRANSFORM_REGISTRY: + print(f"Could not find {model_type} in TRANSFORM_REGISTRY, defaulting to default for LLMs") + model_type = "llm" + + transform_cls = TRANSFORM_REGISTRY[model_type] + print(f"transform {model_type} init with {extra_kwargs = }") + return transform_cls.from_pretrained(model_path, **extra_kwargs) + + +register_transform("llm", LLMTransform) + + +try: + from .qwen2_5_vl_tuner import Qwen2_5_VL_Transform + + register_transform("qwen2_5_vl", Qwen2_5_VL_Transform) + register_transform("qwen2_5_vl_text", Qwen2_5_VL_Transform) +except ImportError: + pass + +try: + from .qwen3_vl_tuner import Qwen3VLTransform + + register_transform("qwen3_vl", Qwen3VLTransform) + register_transform("qwen3_vl_text", Qwen3VLTransform) + register_transform("qwen3_vl_moe", Qwen3VLTransform) + register_transform("qwen3_vl_moe_text", Qwen3VLTransform) + + register_transform("qwen3_5", Qwen3VLTransform) + register_transform("qwen3_5_moe", Qwen3VLTransform) +except ImportError: + pass diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/tuners/base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/tuners/base.py new file mode 100644 index 0000000000000000000000000000000000000000..10a7b48e7e4a8c7b3634e01841a9fea0d7103874 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/tuners/base.py @@ -0,0 +1,45 @@ +from abc import ABC, abstractmethod +from typing import List, Optional + +import torch +from transformers.feature_extraction_utils import BatchFeature + +from arpeggio.chord import Chord +from arpeggio.meta import ChordMeta + +from arpeggio.tuners.collator import CollatorBase + + +class TransformBase(ABC, CollatorBase): + @abstractmethod + def preprocess(self, item: dict) -> Chord: + # item -> Sample -> Chord + ... + + def get_meta(self, item: dict) -> ChordMeta: + chord = self.preprocess(item) + + seq_len = chord["input_ids"].size(-1) + pixel_values = chord.get("pixel_values", None) + pixel_values_videos = chord.get("pixel_values_videos", None) + num_image_patches = 0 if pixel_values is None else pixel_values.size(0) + num_video_patches = 0 if pixel_values_videos is None else pixel_values_videos.size(0) + + return { + "seq_len": seq_len, + "num_image_patches": num_image_patches, + "num_video_patches": num_video_patches, + } + + @property + def should_use_mrope(self) -> bool: + return False + + @classmethod + @abstractmethod + def from_pretrained(cls, pretrained_path: str, **kwargs) -> "TransformBase": ... + + @abstractmethod + def save_pretrained(self, pretrained_path: str): ... + + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/tuners/collator.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/tuners/collator.py new file mode 100644 index 0000000000000000000000000000000000000000..7cee09bdccec9f07cdf9aa48f9faa8212c6d6bdf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/tuners/collator.py @@ -0,0 +1,153 @@ +from abc import ABC, abstractmethod +from typing import List, Optional + +import torch +from transformers.feature_extraction_utils import BatchFeature + +from arpeggio.chord import Chord +from arpeggio.meta import ChordMeta + + +class CollatorBase: + + def collate( + self, + batch: list[Chord], + continuous_batch: bool = False, + pad_to_multiple_of: int = 1, + pad_token_id: Optional[int] = None, + ) -> Chord: + + # Default collate assumes LLM, this should work for most models + # Okay this is like a direct copy rom batcher.py but I made some small + # modifications so cont batching and pad can both work together. + # This difference is small but important. + + if pad_token_id is None: + pad_token_id = getattr(self, "pad_token_id", 0) + + # Calculate batch dimensions + batch_size = sum(chord["input_ids"].shape[0] for chord in batch) + assert batch_size >= 1, "collate for batch_size=0 not implemented" + batch_seq_len = max(chord["input_ids"].shape[-1] for chord in batch) + batch_seq_len = self.round_up_to_multiple(batch_seq_len, pad_to_multiple_of) + + if batch_size == 1 and batch[0]["input_ids"].shape[-1] == batch_seq_len: + # No need for batching + return batch[0] + + # Create placeholder for storing output + placeholder: dict = { + "input_ids": torch.zeros(batch_size, batch_seq_len, dtype=torch.long) + pad_token_id, + "attention_mask": torch.zeros(batch_size, batch_seq_len, dtype=torch.long), + } + + use_mrope = any(chord["position_ids"].ndim == 3 for chord in batch) + if use_mrope: + placeholder["position_ids"] = torch.ones(3, batch_size, batch_seq_len, dtype=torch.long) + else: + placeholder["position_ids"] = torch.ones(batch_size, batch_seq_len, dtype=torch.long) + + has_labels = any(chord.get("labels") is not None for chord in batch) + if has_labels: + placeholder["labels"] = torch.zeros(batch_size, batch_seq_len, dtype=torch.long) - 100 + + seq_lens = [] + extra_info_list = [] + pixel_values_list = [] + image_grid_thw_list = [] + pixel_values_videos_list = [] + video_grid_thw_list = [] + all_keys: set[str] = set() + + offset = 0 + for item in batch: + # For ease of development if mrope, then assert all mrope + if use_mrope: + assert item["position_ids"].ndim == 3 + + mini_batch_size, seq_len = item["input_ids"].shape + padded_seq_len = self.round_up_to_multiple(seq_len, pad_to_multiple_of) + + # Fill the placeholder tensors + next_offset = offset + mini_batch_size + placeholder["input_ids"][offset:next_offset, :seq_len] = item["input_ids"] + placeholder["position_ids"][..., offset:next_offset, :seq_len] = item["position_ids"] + placeholder["attention_mask"][offset:next_offset, :seq_len] = item["attention_mask"] + if has_labels: + placeholder["labels"][offset:next_offset, :seq_len] = item["labels"] + + # We have to mark the end of the sequence to support sequence parallel + if padded_seq_len < batch_seq_len: + placeholder["position_ids"][..., offset:next_offset, padded_seq_len] = 0 + + seq_lens.append(padded_seq_len) + extra_info_list.extend(item["extra_info"]) + + pixel_val = item.get("pixel_values") + if pixel_val is not None: + pixel_values_list.append(pixel_val) + img_grid = item.get("image_grid_thw") + if img_grid is not None: + image_grid_thw_list.append(img_grid) + pixel_vid = item.get("pixel_values_videos") + if pixel_vid is not None: + pixel_values_videos_list.append(pixel_vid) + vid_grid = item.get("video_grid_thw") + if vid_grid is not None: + video_grid_thw_list.append(vid_grid) + + all_keys.update(item.keys()) + offset = next_offset + + placeholder["extra_info"] = extra_info_list + + if len(pixel_values_list) > 0: + placeholder["pixel_values"] = torch.cat(pixel_values_list, dim=0) # type: ignore[arg-type] + placeholder["image_grid_thw"] = torch.cat(image_grid_thw_list, dim=0) # type: ignore[arg-type] + if len(pixel_values_videos_list) > 0: + placeholder["pixel_values_videos"] = torch.cat(pixel_values_videos_list, dim=0) # type: ignore[arg-type] + placeholder["video_grid_thw"] = torch.cat(video_grid_thw_list, dim=0) # type: ignore[arg-type] + + for key in all_keys: + if key in placeholder: + # We've already added them into placeholder + continue + + placeholder[key] = [] + for chord in batch: + n_samples = len(chord["extra_info"]) + if key in chord: + values = chord.get(key) # type: ignore[literal-required] + else: + values = [None] * n_samples + if values is not None: + placeholder[key].extend(values) + + if continuous_batch: + placeholder["input_ids"] = self._continuous_batch_flatten(placeholder["input_ids"], seq_lens) + placeholder["position_ids"] = self._continuous_batch_flatten(placeholder["position_ids"], seq_lens) + placeholder["attention_mask"] = self._continuous_batch_flatten(placeholder["attention_mask"], seq_lens) + if has_labels: + placeholder["labels"] = self._continuous_batch_flatten(placeholder["labels"], seq_lens) + + return BatchFeature(placeholder) # type: ignore[return-value] + + + def _continuous_batch_flatten(self, tensor: torch.Tensor, seq_lens: List[int]): + batch_size = tensor.shape[-2] + assert batch_size == len(seq_lens), "batch size don't agree" + segments = [] + for i, seq_len in enumerate(seq_lens): + segments.append(tensor[..., i, :seq_len]) + return torch.cat(segments, dim=-1).unsqueeze(-2) + + + def cdiv(self, a: int, b: int) -> int: + if b == 0: + raise ZeroDivisionError("Division by zero") + return -(-a // b) + + + def round_up_to_multiple(self, a: int, b: int) -> int: + return self.cdiv(a, b) * b diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/tuners/llm_tuner.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/tuners/llm_tuner.py new file mode 100644 index 0000000000000000000000000000000000000000..b06cf42deb76249fc9d904234f346c42bed3592f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/tuners/llm_tuner.py @@ -0,0 +1,249 @@ +from __future__ import annotations + +import logging +import os +import traceback +from functools import cached_property +from typing import Callable, List, Optional, Union, Any, Dict, Tuple + +from dataclasses import dataclass, field + +import torch +from transformers import AutoProcessor +from transformers.processing_utils import ProcessorMixin +from transformers.tokenization_utils_base import PreTrainedTokenizerBase + +from arpeggio.chord import Chord +from arpeggio.utils.conversation_utils import chatml_input_ids_to_labels, build_chatml_training_inputs + +from .base import TransformBase + + +# TODO: Deprecate prompt_key, call it conversation_key +DEFAULT_PROMPT_KEY = os.getenv("DEFAULT_PROMPT_KEY", "prompt") +DEFAULT_DOCUMENT_KEY = os.getenv("DEFAULT_DOCUMENT_KEY", "document") + + +class LLMTransform(TransformBase): + def __init__( + self, + processor: Union[ProcessorMixin, PreTrainedTokenizerBase], + conversation_format: str = "chatml", + conversation_key: str = DEFAULT_PROMPT_KEY, + document_key: str = DEFAULT_DOCUMENT_KEY, + add_raw: bool = False, + allow_skip: bool = False, + structured_tokenization: bool = False, + max_sample_len: Optional[int] = None, + omit_thinking: bool = False, + **unused_kwargs, + ): + self.processor = processor + self.conversation_format = conversation_format + self.conversation_key = conversation_key + self.document_key = document_key + self.add_raw = add_raw + self.allow_skip = allow_skip + self.structured_tokenization = structured_tokenization + self.max_sample_len = max_sample_len + self.omit_thinking = omit_thinking + + @property + def tokenizer(self) -> PreTrainedTokenizerBase: + if isinstance(self.processor, PreTrainedTokenizerBase): + return self.processor + return self.processor.tokenizer + + @property + def pad_token_id(self) -> int: + return self.tokenizer.pad_token_id + + @property + def eos_token_id(self) -> int: + return self.tokenizer.eos_token_id + + @cached_property + def _assistant_token_id(self) -> int: + return self.tokenizer.encode("assistant", add_special_tokens=False)[0] + + @cached_property + def _bos_token_id(self) -> int: + return self.tokenizer.encode("<|im_start|>", add_special_tokens=False)[0] + + """ + def process_conversation_input_ids_to_labels(self, input_ids: List[int]) -> List[int]: + if self.conversation_format == "chatml": + return chatml_input_ids_to_labels( + input_ids=input_ids, + assistant_token_id=self._assistant_token_id, + bos_token_id=self._bos_token_id, + eos_token_id=self.eos_token_id, + ) + + raise NotImplementedError(f"{self.conversation_format=} not supported") + + def process_document_input_ids_to_labels(self, input_ids: List[int]) -> List[int]: + labels = list(input_ids) + + if self.conversation_format == "chatml": + # 2nd token can also be ignored based on the way we preprocess + labels[1] = -100 + + labels[0] = -100 + return labels + + def _make_model_inputs( + self, + text: str, + input_ids_to_labels_fn: Optional[Callable] = None, + extra_info: Optional[dict] = None, + **kwargs, + ): + if input_ids_to_labels_fn is None: + input_ids_to_labels_fn = self.process_conversation_input_ids_to_labels + + model_inputs = self.processor(text=[text]) + input_ids = model_inputs["input_ids"][0] + labels = input_ids_to_labels_fn(input_ids) + model_inputs["labels"] = [labels] + model_inputs = model_inputs.convert_to_tensors("pt") + + # A bit out of place but seq_len will be used later + seq_len = model_inputs["input_ids"].shape[-1] + + # Add position_ids + model_inputs["position_ids"] = torch.arange(seq_len, dtype=torch.long)[None] + + # Fill stuff into extra_info + if extra_info is None: + extra_info = {} + extra_info["seq_len"] = seq_len + model_inputs["extra_info"] = [extra_info] + + return model_inputs + + """ + + def extract_text(self, item: dict) -> str: + if self.conversation_key in item: + conversation = item.get(self.conversation_key) + text = self.processor.apply_chat_template(conversation, tokenize=False) + assert isinstance(text, str), f"Unable to process conversation into text, got type {type(text)}" + return text + + elif self.document_key in item: + document = item.get(self.document_key) + if isinstance(document, str): + document = [{"type": "text", "text": document}] + assert isinstance(document, list), f"Unable to process document of type {type(document)}" + + text = "".join([ele["text"] for ele in document]) + text = f"<|im_start|>{text}<|im_end|>" + + return text + else: + raise RuntimeError(f"sample contained no usable fields {list(item.keys())}") + + def compose_labels(self, item: dict, input_ids: List[int]) -> List[int]: + if self.conversation_key in item: + return chatml_input_ids_to_labels( + input_ids=input_ids, + assistant_token_id=self._assistant_token_id, + bos_token_id=self._bos_token_id, + eos_token_id=self.eos_token_id, + ) + + elif self.document_key in item: + labels = list(input_ids) + + if self.conversation_format == "chatml": + # 2nd token can also be ignored based on the way we preprocess + labels[1] = -100 + + labels[0] = -100 + return labels + + else: + raise RuntimeError(f"sample contained no usable fields {list(item.keys())}") + + def structuredly_tokenize(self, item: dict, input_ids: List[int]) -> Tuple[List[int], List[int]]: + return build_chatml_training_inputs( + input_ids, + self.tokenizer, + max_sample_len=self.max_sample_len, + omit_thinking=self.omit_thinking, + ) + + def preprocess(self, item: dict) -> Chord: + try: + raw_content = item.get(self.conversation_key) or item.get(self.document_key) + + text = self.extract_text(item) + + model_inputs = self.processor(text=[text]) + + input_ids: List[int] = model_inputs["input_ids"][0] + + if self.structured_tokenization: + input_ids, labels = self.structuredly_tokenize(item, input_ids) + model_inputs["input_ids"] = [input_ids] + model_inputs["attention_mask"] = [[1] * len(input_ids)] + else: + labels = self.compose_labels(item, input_ids) + + model_inputs["labels"] = [labels] + + model_inputs = model_inputs.convert_to_tensors("pt") + + # A bit out of place but seq_len will be used later + seq_len = model_inputs["input_ids"].shape[-1] + + # Add position_ids + model_inputs["position_ids"] = torch.arange(seq_len, dtype=torch.long)[None] + + # Fill stuff into extra_info + extra_info = item.pop("extra_info", {}) + if self.add_raw: + extra_info["raw_prompt"] = raw_content + extra_info["text"] = text + + extra_info["seq_len"] = seq_len + model_inputs["extra_info"] = [extra_info] + + return model_inputs + + except Exception as e: + if not self.allow_skip: + raise e + + err_trace = traceback.format_exc() + logging.warning(f"Skipped sample due to {e}: {err_trace}") + + if self.should_use_mrope: + position_ids = torch.zeros(3, 1, 0, dtype=torch.long) + else: + position_ids = torch.zeros(1, 0, dtype=torch.long) + + return { + "input_ids": torch.zeros(1, 0, dtype=torch.long), + "position_ids": position_ids, + "attention_mask": torch.zeros(1, 0, dtype=torch.long), + "labels": torch.zeros(1, 0, dtype=torch.long), + "extra_info": [{}], + } + + @classmethod + def from_pretrained( + cls, + pretrained_path: str, + conversation_format: str = "chatml", + **kwargs, + ): + return cls( + processor=AutoProcessor.from_pretrained(pretrained_path), + conversation_format=conversation_format, + **kwargs, + ) + + def save_pretrained(self, pretrained_path: str): + self.processor.save_pretrained(pretrained_path) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/tuners/qwen2_5_vl_tuner.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/tuners/qwen2_5_vl_tuner.py new file mode 100644 index 0000000000000000000000000000000000000000..c3e16b1466c9c4c2b8a9d38ed78428f82dd24c03 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/tuners/qwen2_5_vl_tuner.py @@ -0,0 +1,381 @@ +from __future__ import annotations + +import logging +import traceback +from functools import cached_property +from typing import Callable, List, Optional, Set, Union + +import torch +from PIL import Image +from qwen_vl_utils import fetch_image, fetch_video, process_vision_info +from transformers import ( + AutoConfig, + AutoProcessor, + Qwen2_5_VLConfig, + Qwen2_5_VLProcessor, + Qwen2VLConfig, + Qwen2VLProcessor, +) + +from arpeggio.chord import Chord +from arpeggio.utils.conversation_utils import ( + chatml_input_ids_to_labels, + handle_message_extra_fields, + sharegpt_to_hf_format, +) +from arpeggio.utils.qwen_vl_utils import get_mrope_index + +from .llm_tuner import DEFAULT_PROMPT_KEY, DEFAULT_DOCUMENT_KEY, LLMTransform + + +ELE_RESIZE_KEYS = [ + "min_pixels", + "max_pixels", + "min_frames", + "max_frames", + "nframes", + "fps", +] + + +class Qwen2_5_VL_Transform(LLMTransform): + def __init__( + self, + processor: Union[Qwen2VLProcessor, Qwen2_5_VLProcessor], + model_config: Union[Qwen2VLConfig, Qwen2_5_VLConfig], + conversation_key: str = DEFAULT_PROMPT_KEY, + document_key: str = DEFAULT_DOCUMENT_KEY, + add_raw: bool = False, + allow_skip: bool = False, + structured_tokenization: bool = False, + image_min_pixels: Optional[int] = None, + image_max_pixels: Optional[int] = None, + video_min_pixels: Optional[int] = None, + video_max_pixels: Optional[int] = None, + video_min_frames: Optional[int] = None, + video_max_frames: Optional[int] = None, + video_fps: Optional[float] = None, + video_nframes: Optional[int] = None, + override_ele_resize_args: bool = False, + **unused_kwargs, + ): + legacy_prompt_key = unused_kwargs.pop("prompt_key", None) + if legacy_prompt_key is not None: + conversation_key = legacy_prompt_key + + super().__init__( + processor=processor, + conversation_format="chatml", + conversation_key=conversation_key, + document_key=document_key, + add_raw=add_raw, + allow_skip=allow_skip, + structured_tokenization=structured_tokenization, + ) + + self.model_config = model_config + self.override_ele_resize_args = override_ele_resize_args + + if video_nframes is not None: + assert video_min_frames is None + assert video_max_frames is None + assert video_fps is None + + self._image_ele_kwargs = { + "min_pixels": image_min_pixels, + "max_pixels": image_max_pixels, + } + self._video_ele_kwargs = { + "min_pixels": video_min_pixels, + "max_pixels": video_max_pixels, + "min_frames": video_min_frames, + "max_frames": video_max_frames, + "fps": video_fps, + "nframes": video_nframes, + } + + self._image_ele_kwargs = {k: v for k, v in self._image_ele_kwargs.items() if v is not None} + self._video_ele_kwargs = {k: v for k, v in self._video_ele_kwargs.items() if v is not None} + + @property + def should_use_mrope(self) -> bool: + return True + + @cached_property + def _patch_size(self) -> int: + return self.model_config.vision_config.patch_size + + @cached_property + def _skip_token_ids(self) -> Set[int]: + return { + self.pad_token_id, + # self.model_config.vision_start_token_id, + # self.model_config.vision_end_token_id, + # self.model_config.image_token_id, + # self.model_config.video_token_id, + self.model_config.vision_start_token_id, + self.model_config.vision_end_token_id, + self.model_config.image_token_id, + self.model_config.video_token_id, + } + + def process_document_input_ids_to_labels(self, input_ids: List[int]) -> List[int]: + # Skip all visual tokens + labels = [-100 if token_id in self._skip_token_ids else token_id for token_id in input_ids] + labels[1] = -100 + labels[0] = -100 + return labels + + def _patch_visual_element(self, ele: dict): + ele_type = ele["type"] + if ele_type in ("image", "image_url"): + if self.override_ele_resize_args: + for key in ELE_RESIZE_KEYS: + ele.pop(key, None) + ele.update(self._image_ele_kwargs) + + if ele_type in ("video"): + if self.override_ele_resize_args: + for key in ELE_RESIZE_KEYS: + ele.pop(key, None) + ele.update(self._video_ele_kwargs) + + def _patch_visual_elements_in_prompt(self, prompt: dict): + for message in prompt: + contents = message["content"] + if not isinstance(contents, list): + continue + + for part in contents: + if not isinstance(part, dict): + continue + self._patch_visual_element(part) + + def _make_model_inputs( + self, + text: str, + images: Optional[List[Image.Image]] = None, + videos: Optional[List[torch.Tensor]] = None, + input_ids_to_labels_fn: Optional[Callable] = None, + extra_info: Optional[dict] = None, + **kwargs, + ): + model_inputs = self.processor( + text=[text], + images=images, + videos=videos, + **kwargs, + ) + + # Form labels + if input_ids_to_labels_fn is None: + input_ids_to_labels_fn = lambda ids: chatml_input_ids_to_labels( + input_ids=ids, + assistant_token_id=self._assistant_token_id, + bos_token_id=self._bos_token_id, + eos_token_id=self.eos_token_id, + ) + + input_ids = model_inputs["input_ids"][0] + if self.structured_tokenization: + input_ids, labels = self.structuredly_tokenize({}, input_ids) + model_inputs["input_ids"] = [input_ids] + model_inputs["attention_mask"] = [[1] * len(input_ids)] + else: + labels = input_ids_to_labels_fn(input_ids) + model_inputs["labels"] = [labels] + model_inputs = model_inputs.convert_to_tensors("pt") + + # A bit out of place but seq_len will be used later + seq_len = model_inputs["input_ids"].shape[-1] + + # Add position_ids + if self.should_use_mrope: + model_inputs["position_ids"] = get_mrope_index( + config=self.model_config, + input_ids=model_inputs["input_ids"][0], + image_grid_thw=model_inputs.get("image_grid_thw"), + video_grid_thw=model_inputs.get("video_grid_thw"), + second_per_grid_ts=model_inputs.get("second_per_grid_ts"), + )[:, None] # [3, 1, seq_len] + + else: + model_inputs["position_ids"] = torch.arange(seq_len, dtype=torch.long)[None] + + # hardcoded but second_per_grid_ts is only useful for calculating mrope + model_inputs.pop("second_per_grid_ts", None) + + # Fill stuff into extra_info + if extra_info is None: + extra_info = {} + extra_info["seq_len"] = seq_len + model_inputs["extra_info"] = [extra_info] + + return model_inputs + + def preprocess_conversation(self, item: dict) -> Chord: + item = dict(item) # Make shallow copy + + prompt = item.pop(self.conversation_key) + + images = videos = None + video_kwargs = {} + + # First determine if we are dealing with ShareGPT or HF/OpenAI format + if "images" in item or "videos" in item: + prompt = sharegpt_to_hf_format(prompt) + raw_images = item.pop("images", None) + raw_videos = item.pop("videos", None) + + if raw_images: + images = [] + for raw in raw_images: + self._patch_visual_element(raw) + image = fetch_image(raw, image_patch_size=self._patch_size) + images.append(image) + + if raw_videos: + videos = [] + fps_list = [] + for raw in raw_videos: + self._patch_visual_element(raw) + video, fps = fetch_video(raw, return_video_sample_fps=True) + videos.append(video) + fps_list.append(fps) + video_kwargs["fps"] = fps_list + + else: + # HF/OpenAI format can be handled with qwen-vl-utils + prompt = handle_message_extra_fields(prompt) + self._patch_visual_elements_in_prompt(prompt) + images, videos, video_kwargs = process_vision_info( + prompt, + return_video_kwargs=True, + ) + + # Apply chat template & process with model processor + text = self.processor.apply_chat_template(prompt, tokenize=False) + + extra_info = item.pop("extra_info", {}) + if self.add_raw: + extra_info["raw_prompt"] = prompt + extra_info["text"] = text + + video_kwargs = {k: v for k, v in video_kwargs.items() if v} + return self._make_model_inputs( + text=text, + images=images, + videos=videos, + extra_info=extra_info, + do_resize=False, + **video_kwargs, + ) + + def preprocess_document(self, item: dict) -> Chord: + item = dict(item) + + document = item.pop(self.document_key) + if isinstance(document, str): + document = [{"type": "text", "text": document}] + if not isinstance(document, list): + raise ValueError(f"Unable to process document of type {type(document)}") + + images = videos = None + video_kwargs = {} + + # First determine if we are dealing with ShareGPT or HF/OpenAI format + if "images" in item or "videos" in item: + raw_images = item.pop("images", None) + raw_videos = item.pop("videos", None) + + if raw_images: + images = [] + for raw in raw_images: + self._patch_visual_element(raw) + image = fetch_image(raw, image_patch_size=self._patch_size) + images.append(image) + + if raw_videos: + videos = [] + fps_list = [] + for raw in raw_videos: + self._patch_visual_element(raw) + video, fps = fetch_video(raw, return_video_sample_fps=True) + videos.append(video) + fps_list.append(fps) + video_kwargs["fps"] = fps_list + + else: + # HF/OpenAI format can be handled with qwen-vl-utils + fake_prompt = [{"role": "user", "content": document}] + fake_prompt = handle_message_extra_fields(fake_prompt) + self._patch_visual_elements_in_prompt(fake_prompt) + images, videos, video_kwargs = process_vision_info( + fake_prompt, + image_patch_size=self._patch_size, + return_video_kwargs=True, + ) + + # Built text data + text_segments = [] + for part in document: + if part["type"] == "text": + text_segments.append(part["text"]) + elif part["type"] == "image": + text_segments.append("<|vision_start|><|image_pad|><|vision_end|>") + elif part["type"] == "video": + text_segments.append("<|vision_start|><|video_pad|><|vision_end|>") + text = "".join(text_segments) + text = "<|im_start|>" + text + "<|im_end|>" + + extra_info = item.pop("extra_info", {}) + if self.add_raw: + extra_info["raw_prompt"] = document + extra_info["text"] = text + + video_kwargs = {k: v for k, v in video_kwargs.items() if v} + return self._make_model_inputs( + text=text, + images=images, + videos=videos, + extra_info=extra_info, + do_resize=False, + **video_kwargs, + ) + + def preprocess(self, item: dict) -> Chord: + try: + if self.conversation_key in item: + return self.preprocess_conversation(item) + if self.document_key in item: + return self.preprocess_document(item) + raise RuntimeError(f"sample contained no usable fields {list(item.keys())}") + except Exception as e: + if not self.allow_skip: + raise e + + err_trace = traceback.format_exc() + logging.warning(f"Skipped sample due to {e}: {err_trace}") + + position_ids = ( + torch.zeros(3, 1, 0, dtype=torch.long) + if self.should_use_mrope + else torch.zeros(1, 0, dtype=torch.long) + ) + return { + "input_ids": torch.zeros(1, 0, dtype=torch.long), + "position_ids": position_ids, + "attention_mask": torch.zeros(1, 0, dtype=torch.long), + "labels": torch.zeros(1, 0, dtype=torch.long), + "extra_info": [{}], + } + + @classmethod + def from_pretrained(cls, pretrained_path, **kwargs): + processor = AutoProcessor.from_pretrained(pretrained_path) + config = AutoConfig.from_pretrained(pretrained_path) + return cls(processor=processor, model_config=config, **kwargs) + + def save_pretrained(self, pretrained_path: str): + self.processor.save_pretrained(pretrained_path) + self.model_config.save_pretrained(pretrained_path) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/tuners/qwen3_vl_tuner.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/tuners/qwen3_vl_tuner.py new file mode 100644 index 0000000000000000000000000000000000000000..3266d4579a57f4056da105efb37c1c6918faf489 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/tuners/qwen3_vl_tuner.py @@ -0,0 +1,397 @@ +from __future__ import annotations + +import logging +import traceback +from functools import cached_property +from importlib.metadata import version +from typing import Callable, List, Optional, Set, Union + +import torch +from packaging.version import Version +from PIL import Image +from qwen_vl_utils import fetch_image, fetch_video, process_vision_info +from transformers import AutoConfig, AutoProcessor, Qwen3VLConfig, Qwen3VLMoeConfig, Qwen3VLProcessor + +from arpeggio.chord import Chord +from arpeggio.utils.conversation_utils import ( + build_chatml_training_inputs, + handle_message_extra_fields, + sharegpt_to_hf_format, +) +from arpeggio.utils.qwen_vl_utils import get_mrope_index_qwen3_vl + +from .llm_tuner import DEFAULT_PROMPT_KEY, DEFAULT_DOCUMENT_KEY, LLMTransform + + +ELE_RESIZE_KEYS = [ + "min_pixels", + "max_pixels", + "min_frames", + "max_frames", + "nframes", + "fps", +] +QWEN_VL_UTILS_GTE_0_0_14 = Version(version("qwen-vl-utils")) >= Version("0.0.14") +assert QWEN_VL_UTILS_GTE_0_0_14, "Qwen3-VL requires qwen-vl-utils>=0.0.14" + + +class Qwen3VLTransform(LLMTransform): + def __init__( + self, + processor: Qwen3VLProcessor, + model_config: Union[Qwen3VLConfig, Qwen3VLMoeConfig], + conversation_key: str = DEFAULT_PROMPT_KEY, + document_key: str = DEFAULT_DOCUMENT_KEY, + add_raw: bool = False, + allow_skip: bool = False, + image_min_pixels: Optional[int] = None, + image_max_pixels: Optional[int] = None, + video_min_pixels: Optional[int] = None, + video_max_pixels: Optional[int] = None, + video_min_frames: Optional[int] = None, + video_max_frames: Optional[int] = None, + video_fps: Optional[float] = None, + video_nframes: Optional[int] = None, + override_ele_resize_args: bool = False, + **unused_kwargs, + ): + legacy_prompt_key = unused_kwargs.pop("prompt_key", None) + if legacy_prompt_key is not None: + conversation_key = legacy_prompt_key + + super().__init__( + processor=processor, + conversation_format="chatml", + conversation_key=conversation_key, + document_key=document_key, + add_raw=add_raw, + allow_skip=allow_skip, + ) + + self.model_config = model_config + self.override_ele_resize_args = override_ele_resize_args + + if video_nframes is not None: + assert video_min_frames is None + assert video_max_frames is None + assert video_fps is None + + self._image_ele_kwargs = { + "min_pixels": image_min_pixels, + "max_pixels": image_max_pixels, + } + self._video_ele_kwargs = { + "min_pixels": video_min_pixels, + "max_pixels": video_max_pixels, + "min_frames": video_min_frames, + "max_frames": video_max_frames, + "fps": video_fps, + "nframes": video_nframes, + } + + self._image_ele_kwargs = {k: v for k, v in self._image_ele_kwargs.items() if v is not None} + self._video_ele_kwargs = {k: v for k, v in self._video_ele_kwargs.items() if v is not None} + + @property + def should_use_mrope(self) -> bool: + return True + + @cached_property + def _patch_size(self) -> int: + return self.model_config.vision_config.patch_size + + @cached_property + def _skip_token_ids(self) -> Set[int]: + return { + self.pad_token_id, + self.model_config.vision_start_token_id, + self.model_config.vision_end_token_id, + self.model_config.image_token_id, + self.model_config.video_token_id, + } + + def process_document_input_ids_to_labels(self, input_ids: List[int]) -> List[int]: + # Skip all visual tokens + labels = [-100 if token_id in self._skip_token_ids else token_id for token_id in input_ids] + labels[1] = -100 + labels[0] = -100 + return labels + + def _patch_visual_element(self, ele: dict): + ele_type = ele["type"] + if ele_type in ("image", "image_url"): + if self.override_ele_resize_args: + for key in ELE_RESIZE_KEYS: + ele.pop(key, None) + ele.update(self._image_ele_kwargs) + + if ele_type in ("video"): + if self.override_ele_resize_args: + for key in ELE_RESIZE_KEYS: + ele.pop(key, None) + ele.update(self._video_ele_kwargs) + + def _patch_visual_elements_in_prompt(self, prompt: dict): + for message in prompt: + contents = message["content"] + if not isinstance(contents, list): + continue + + for part in contents: + if not isinstance(part, dict): + continue + self._patch_visual_element(part) + + def _make_model_inputs( + self, + text: str, + images: Optional[List[Image.Image]] = None, + videos: Optional[List[torch.Tensor]] = None, + video_metadatas: Optional[List[dict]] = None, + input_ids_to_labels_fn: Optional[Callable] = None, + extra_info: Optional[dict] = None, + **kwargs, + ): + # Make model inputs makes it easier for people to extend + # Qwen3-VL processor for new tasks and types of datasets such as those + # in pretraining. + # All the data extraction will be done in _preprocess + # while make_model_inputs transforms the extracted visual and text data + # and turns them into input_ids and stuff for model inputs. + + model_inputs = self.processor( + text=text, + images=images, + videos=videos, + video_metadata=video_metadatas, + **kwargs, + ) + + input_ids = model_inputs["input_ids"][0] + if input_ids_to_labels_fn is None: + # To ensure that tokenization respects ChatML text boundaries we + # re-encode the input_ids + input_ids, labels = build_chatml_training_inputs( + input_ids=input_ids, + tokenizer=self.tokenizer, + ) + model_inputs["input_ids"] = [input_ids] + model_inputs["attention_mask"] = [[1] * len(input_ids)] + else: + # document pretraining path keeps its own label logic + labels = input_ids_to_labels_fn(input_ids) + + model_inputs["labels"] = [labels] + model_inputs = model_inputs.convert_to_tensors("pt") + + # A bit out of place but seq_len will be used later + seq_len = len(input_ids) + + model_inputs["position_ids"] = get_mrope_index_qwen3_vl( + config=self.model_config, + input_ids=model_inputs["input_ids"][0], + image_grid_thw=model_inputs.get("image_grid_thw"), + video_grid_thw=model_inputs.get("video_grid_thw"), + )[:, None] # [3, 1, seq_len] + + # Fill stuff into extra_info + if extra_info is None: + extra_info = {} + extra_info["seq_len"] = seq_len + model_inputs["extra_info"] = [extra_info] + + return model_inputs + + def preprocess_conversation(self, item: dict) -> Chord: + item = dict(item) # Make shallow copy + + prompt = item.pop(self.conversation_key) + + images = videos = None + video_kwargs = {"do_sample_frames": False} + + # First determine if we are dealing with ShareGPT or HF/OpenAI format + if "images" in item or "videos" in item: + prompt = sharegpt_to_hf_format(prompt) + raw_images = item.pop("images", None) + raw_videos = item.pop("videos", None) + + if raw_images: + images = [] + for raw in raw_images: + self._patch_visual_element(raw) + image = fetch_image(raw, image_patch_size=self._patch_size) + images.append(image) + + if raw_videos: + videos = [] + fps_list = [] + for raw in raw_videos: + self._patch_visual_element(raw) + video, fps = fetch_video( + raw, + image_patch_size=self._patch_size, + return_video_sample_fps=True, + return_video_metadata=True, + ) + videos.append(video) + fps_list.append(fps) + video_kwargs["fps"] = fps_list + + else: + # HF/OpenAI format can be handled with qwen-vl-utils + prompt = handle_message_extra_fields(prompt) + self._patch_visual_elements_in_prompt(prompt) + images, videos, video_kwargs = process_vision_info( + prompt, + image_patch_size=self._patch_size, + return_video_kwargs=True, + return_video_metadata=True, + ) + + # Follow qwen-vl-utils usage from https://github.com/QwenLM/Qwen3-VL + if videos: + videos, video_metadatas = zip(*videos) + videos, video_metadatas = list(videos), list(video_metadatas) + else: + videos = video_metadatas = None + + text = self.processor.apply_chat_template(prompt, tokenize=False) + + extra_info = item.pop("extra_info", {}) + if self.add_raw: + extra_info["raw_prompt"] = prompt + extra_info["text"] = text + + return self._make_model_inputs( + text=text, + images=images, + videos=videos, + video_metadatas=video_metadatas, + extra_info=extra_info, + do_resize=False, + **video_kwargs, + ) + + def preprocess_document(self, item: dict) -> Chord: + item = dict(item) + + document = item.pop(self.document_key) + if isinstance(document, str): + document = [{"type": "text", "text": document}] + if not isinstance(document, list): + raise ValueError(f"Unable to process document of type {type(document)}") + + images = videos = None + video_kwargs = {"do_sample_frames": False} + + # First extract images or videos + if "images" in item or "videos" in item: + raw_images = item.pop("images", None) + raw_videos = item.pop("videos", None) + + if raw_images: + images = [] + for raw in raw_images: + self._patch_visual_element(raw) + image = fetch_image(raw, image_patch_size=self._patch_size) + images.append(image) + + if raw_videos: + videos = [] + fps_list = [] + for raw in raw_videos: + self._patch_visual_element(raw) + video, fps = fetch_video( + raw, + image_patch_size=self._patch_size, + return_video_sample_fps=True, + return_video_metadata=True, + ) + videos.append(video) + fps_list.append(fps) + video_kwargs["fps"] = fps_list + + else: + # Assume images / videos are in document, handle this like HF/OpenAI prompt + fake_prompt = [{"role": "user", "content": document}] + fake_prompt = handle_message_extra_fields(fake_prompt) + self._patch_visual_elements_in_prompt(fake_prompt) + images, videos, video_kwargs = process_vision_info( + fake_prompt, + image_patch_size=self._patch_size, + return_video_kwargs=True, + return_video_metadata=True, + ) + + # Follow qwen-vl-utils usage from https://github.com/QwenLM/Qwen3-VL + if videos: + videos, video_metadatas = zip(*videos) + videos, video_metadatas = list(videos), list(video_metadatas) + else: + videos = video_metadatas = None + + # Built text data + text_segments = [] + for part in document: + if part["type"] == "text": + text_segments.append(part["text"]) + elif part["type"] == "image": + text_segments.append("<|vision_start|><|image_pad|><|vision_end|>") + elif part["type"] == "video": + text_segments.append("<|vision_start|><|video_pad|><|vision_end|>") + text = "".join(text_segments) + text = "<|im_start|>" + text + "<|im_end|>" + + extra_info = item.pop("extra_info", {}) + if self.add_raw: + extra_info["raw_prompt"] = document + extra_info["text"] = text + + return self._make_model_inputs( + text=text, + images=images, + videos=videos, + video_metadatas=video_metadatas, + input_ids_to_labels_fn=self.process_document_input_ids_to_labels, + extra_info=extra_info, + do_resize=False, + **video_kwargs, + ) + + def preprocess(self, item: dict) -> Chord: + try: + if self.conversation_key in item: + return self.preprocess_conversation(item) + if self.document_key in item: + return self.preprocess_document(item) + raise RuntimeError(f"sample contained no usable fields {list(item.keys())}") + except Exception as e: + if not self.allow_skip: + raise e + + err_trace = traceback.format_exc() + logging.warning(f"Skipped sample due to {e}: {err_trace}") + + position_ids = ( + torch.zeros(3, 1, 0, dtype=torch.long) + if self.should_use_mrope + else torch.zeros(1, 0, dtype=torch.long) + ) + return { + "input_ids": torch.zeros(1, 0, dtype=torch.long), + "position_ids": position_ids, + "attention_mask": torch.zeros(1, 0, dtype=torch.long), + "labels": torch.zeros(1, 0, dtype=torch.long), + "extra_info": [{}], + } + + @classmethod + def from_pretrained(cls, pretrained_path, **kwargs): + processor = AutoProcessor.from_pretrained(pretrained_path) + config = AutoConfig.from_pretrained(pretrained_path) + return cls(processor=processor, model_config=config, **kwargs) + + def save_pretrained(self, pretrained_path: str): + self.processor.save_pretrained(pretrained_path) + self.model_config.save_pretrained(pretrained_path) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/utils/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/utils/cache_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/utils/cache_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..292eea8fd5a7d8b54aae6828af96a36f08e6a684 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/utils/cache_utils.py @@ -0,0 +1,76 @@ +import hashlib +import json +import os +from typing import TypeVar + + +DEFAULT_CACHE_DIR = os.path.expanduser("~/.cache/arpeggio") +T = TypeVar("T") + + +def cache_to_disk(fn: T) -> T: + """Disk-based caching decorator for expensive function calls. + + Caches function results to disk using MD5-hashed kwargs as the cache key. + Results are stored as JSON files in {cache_dir}/{subfolder}/{hash}.json. + + Args: + subfolder: Subdirectory name within cache_dir for organizing cache files + cache_dir: Root cache directory (default: ~/.cache/arpeggio) + + Returns: + Decorator function that wraps the target function with caching logic + + Caveats and Limitations: + 1. **Keyword-only arguments**: Wrapped functions MUST use keyword arguments only. + Positional arguments will raise ValueError. + + 2. **JSON serialization**: Both function arguments and return values must be + JSON-serializable. Complex objects (numpy arrays, custom classes, etc.) + will fail. + + 3. **No cache invalidation**: Cache files persist until manually deleted. + No TTL or automatic cleanup mechanism. + + 4. **Hash collisions**: Different functions sharing the same subfolder and + kwargs will collide (same cache file). Use unique subfolders per function. + + 5. **Performance**: sha256 hashing and JSON I/O add overhead. Best for expensive + computations where I/O cost is negligible compared to computation time. + + Example: + >>> @cache_to_disk + ... def expensive_computation(param1=None, param2=None): + ... # ... expensive work ... + ... return result + ... + >>> # First call computes and caches + >>> result = expensive_computation(param1="a", param2=42) + >>> # Second call returns cached result instantly + >>> result = expensive_computation(param1="a", param2=42) + """ + + fn_name = f"{fn.__module__}.{fn.__qualname__}" + fn_cache_dir = os.path.join(DEFAULT_CACHE_DIR, fn_name) + + def cached_fn(*args, **kwargs): + # I hate to handle edge case... just don't + if len(args) > 0: + raise ValueError("cache_to_disk wrapped functions cannot use positional arguments") + + canonical = json.dumps(kwargs, sort_keys=True) + hash_value = hashlib.sha256(canonical.encode()).hexdigest() + + cache_path = os.path.join(fn_cache_dir, hash_value) + + if os.path.exists(cache_path): + with open(cache_path, "r") as f: + return json.load(f)["out"] + + out = fn(*args, **kwargs) + os.makedirs(fn_cache_dir, exist_ok=True) + with open(cache_path, "w") as f: + json.dump({"name": str(fn), "kwargs": kwargs, "out": out}, f) + return out + + return cached_fn diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/utils/conversation_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/utils/conversation_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..94a576965b81fb40dd7c533f1013a8f2e43553a6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/arpeggio/utils/conversation_utils.py @@ -0,0 +1,213 @@ +import re +from copy import deepcopy +from typing import List, Optional, Tuple + + +VISUAL_PATTERN = re.compile(r"(|