desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Get a token at an absolute index i; 0..n-1. This is really only needed for profiling and debugging and token stream rewriting. If you don\'t want to buffer up tokens, then this method makes no sense for you. Naturally you can\'t use the rewrite stream feature. I believe DebugTokenStream can easily be altered to not ...
def get(self, i):
raise NotImplementedError
'Where is this stream pulling tokens from? This is not the name, but the object that provides Token objects.'
def getTokenSource(self):
raise NotImplementedError
'Return the text of all tokens from start to stop, inclusive. If the stream does not buffer all the tokens then it can just return "" or null; Users should not access $ruleLabel.text in an action of course in that case. Because the user is not required to use a token with an index stored in it, we must provide a means...
def toString(self, start=None, stop=None):
raise NotImplementedError
'@param data This should be a unicode string holding the data you want to parse. If you pass in a byte string, the Lexer will choke on non-ascii data.'
def __init__(self, data):
CharStream.__init__(self) self.strdata = unicode(data) self.data = [ord(c) for c in self.strdata] self.n = len(data) self.p = 0 self.line = 1 self.charPositionInLine = 0 self._markers = [] self.lastMarker = None self.markDepth = 0 self.name = None
'Reset the stream so that it\'s in the same state it was when the object was created *except* the data array is not touched.'
def reset(self):
self.p = 0 self.line = 1 self.charPositionInLine = 0 self._markers = []
'Return the current input symbol index 0..n where n indicates the last symbol has been read. The index is the index of char to be returned from LA(1).'
def index(self):
return self.p
'consume() ahead until p==index; can\'t just set p=index as we must update line and charPositionInLine.'
def seek(self, index):
if (index <= self.p): self.p = index return while (self.p < index): self.consume()
'Using setter/getter methods is deprecated. Use o.line instead.'
def getLine(self):
return self.line
'Using setter/getter methods is deprecated. Use o.charPositionInLine instead.'
def getCharPositionInLine(self):
return self.charPositionInLine
'Using setter/getter methods is deprecated. Use o.line instead.'
def setLine(self, line):
self.line = line
'Using setter/getter methods is deprecated. Use o.charPositionInLine instead.'
def setCharPositionInLine(self, pos):
self.charPositionInLine = pos
'@param fileName The path to the file to be opened. The file will be opened with mode \'rb\'. @param encoding If you set the optional encoding argument, then the data will be decoded on the fly.'
def __init__(self, fileName, encoding=None):
self.fileName = fileName fp = codecs.open(fileName, 'rb', encoding) try: data = fp.read() finally: fp.close() ANTLRStringStream.__init__(self, data)
'Deprecated, access o.fileName directly.'
def getSourceName(self):
return self.fileName
'@param file A file-like object holding your input. Only the read() method must be implemented. @param encoding If you set the optional encoding argument, then the data will be decoded on the fly.'
def __init__(self, file, encoding=None):
if (encoding is not None): reader = codecs.lookup(encoding)[2] file = reader(file) data = file.read() ANTLRStringStream.__init__(self, data)
'@param tokenSource A TokenSource instance (usually a Lexer) to pull the tokens from. @param channel Skip tokens on any channel but this one; this is how we skip whitespace...'
def __init__(self, tokenSource=None, channel=DEFAULT_CHANNEL):
TokenStream.__init__(self) self.tokenSource = tokenSource self.tokens = [] self.channelOverrideMap = {} self.discardSet = set() self.channel = channel self.discardOffChannelTokens = False self.p = (-1) self.lastMarker = None
'Reset this token stream by setting its token source.'
def setTokenSource(self, tokenSource):
self.tokenSource = tokenSource self.tokens = [] self.p = (-1) self.channel = DEFAULT_CHANNEL
'Load all tokens from the token source and put in tokens. This is done upon first LT request because you might want to set some token type / channel overrides before filling buffer.'
def fillBuffer(self):
index = 0 t = self.tokenSource.nextToken() while ((t is not None) and (t.type != EOF)): discard = False if ((self.discardSet is not None) and (t.type in self.discardSet)): discard = True elif (self.discardOffChannelTokens and (t.channel != self.channel)): disc...
'Move the input pointer to the next incoming token. The stream must become active with LT(1) available. consume() simply moves the input pointer so that LT(1) points at the next input symbol. Consume at least one token. Walk past any token not on the channel the parser is listening to.'
def consume(self):
if (self.p < len(self.tokens)): self.p += 1 self.p = self.skipOffTokenChannels(self.p)
'Given a starting index, return the index of the first on-channel token.'
def skipOffTokenChannels(self, i):
try: while (self.tokens[i].channel != self.channel): i += 1 except IndexError: pass return i
'A simple filter mechanism whereby you can tell this token stream to force all tokens of type ttype to be on channel. For example, when interpreting, we cannot exec actions so we need to tell the stream to force all WS and NEWLINE to be a different, ignored channel.'
def setTokenTypeChannel(self, ttype, channel):
self.channelOverrideMap[ttype] = channel
'Given a start and stop index, return a list of all tokens in the token type set. Return None if no tokens were found. This method looks at both on and off channel tokens.'
def getTokens(self, start=None, stop=None, types=None):
if (self.p == (-1)): self.fillBuffer() if ((stop is None) or (stop >= len(self.tokens))): stop = (len(self.tokens) - 1) if ((start is None) or (stop < 0)): start = 0 if (start > stop): return None if isinstance(types, (int, long)): types = set([types]) fil...
'Get the ith token from the current position 1..n where k=1 is the first symbol of lookahead.'
def LT(self, k):
if (self.p == (-1)): self.fillBuffer() if (k == 0): return None if (k < 0): return self.LB((- k)) i = self.p n = 1 while (n < k): i = self.skipOffTokenChannels((i + 1)) n += 1 try: return self.tokens[i] except IndexError: return EOF...
'Look backwards k tokens on-channel tokens'
def LB(self, k):
if (self.p == (-1)): self.fillBuffer() if (k == 0): return None if ((self.p - k) < 0): return None i = self.p n = 1 while (n <= k): i = self.skipOffTokenChannelsReverse((i - 1)) n += 1 if (i < 0): return None return self.tokens[i]
'Return absolute token i; ignore which channel the tokens are on; that is, count all tokens not just on-channel tokens.'
def get(self, i):
return self.tokens[i]
'Execute the rewrite operation by possibly adding to the buffer. Return the index of the next token to operate on.'
def execute(self, buf):
return self.index
'Rollback the instruction stream for a program so that the indicated instruction (via instructionIndex) is no longer in the stream. UNTESTED!'
def rollback(self, *args):
if (len(args) == 2): programName = args[0] instructionIndex = args[1] elif (len(args) == 1): programName = self.DEFAULT_PROGRAM_NAME instructionIndex = args[0] else: raise TypeError('Invalid arguments') p = self.programs.get(programName, None) if (p is not ...
'Reset the program so that no instructions exist'
def deleteProgram(self, programName=DEFAULT_PROGRAM_NAME):
self.rollback(programName, self.MIN_TOKEN_INDEX)
'We need to combine operations and report invalid operations (like overlapping replaces that are not completed nested). Inserts to same index need to be combined etc... Here are the cases: I.i.u I.j.v leave alone, nonoverlapping I.i.u I.i.v combine: Iivu R.i-j.u R....
def reduceToSingleOperationPerIndex(self, rewrites):
for (i, rop) in enumerate(rewrites): if (rop is None): continue if (not isinstance(rop, ReplaceOp)): continue for (j, iop) in self.getKindOfOps(rewrites, InsertBeforeOp, i): if ((iop.index >= rop.index) and (iop.index <= rop.lastIndex)): re...
'@brief Get the text of the token. Using setter/getter methods is deprecated. Use o.text instead.'
def getText(self):
raise NotImplementedError
'@brief Set the text of the token. Using setter/getter methods is deprecated. Use o.text instead.'
def setText(self, text):
raise NotImplementedError
'@brief Get the type of the token. Using setter/getter methods is deprecated. Use o.type instead.'
def getType(self):
raise NotImplementedError
'@brief Get the type of the token. Using setter/getter methods is deprecated. Use o.type instead.'
def setType(self, ttype):
raise NotImplementedError
'@brief Get the line number on which this token was matched Lines are numbered 1..n Using setter/getter methods is deprecated. Use o.line instead.'
def getLine(self):
raise NotImplementedError
'@brief Set the line number on which this token was matched Using setter/getter methods is deprecated. Use o.line instead.'
def setLine(self, line):
raise NotImplementedError
'@brief Get the column of the tokens first character, Columns are numbered 0..n-1 Using setter/getter methods is deprecated. Use o.charPositionInLine instead.'
def getCharPositionInLine(self):
raise NotImplementedError
'@brief Set the column of the tokens first character, Using setter/getter methods is deprecated. Use o.charPositionInLine instead.'
def setCharPositionInLine(self, pos):
raise NotImplementedError
'@brief Get the channel of the token Using setter/getter methods is deprecated. Use o.channel instead.'
def getChannel(self):
raise NotImplementedError
'@brief Set the channel of the token Using setter/getter methods is deprecated. Use o.channel instead.'
def setChannel(self, channel):
raise NotImplementedError
'@brief Get the index in the input stream. An index from 0..n-1 of the token object in the input stream. This must be valid in order to use the ANTLRWorks debugger. Using setter/getter methods is deprecated. Use o.index instead.'
def getTokenIndex(self):
raise NotImplementedError
'@brief Set the index in the input stream. Using setter/getter methods is deprecated. Use o.index instead.'
def setTokenIndex(self, index):
raise NotImplementedError
'@brief From what character stream was this token created. You don\'t have to implement but it\'s nice to know where a Token comes from if you have include files etc... on the input.'
def getInputStream(self):
raise NotImplementedError
'@brief From what character stream was this token created. You don\'t have to implement but it\'s nice to know where a Token comes from if you have include files etc... on the input.'
def setInputStream(self, input):
raise NotImplementedError
'Override the text for this token. getText() will return this text rather than pulling from the buffer. Note that this does not mean that start/stop indexes are not valid. It means that that input was converted to a new string in the token object.'
def setText(self, text):
self._text = text
'reset the parser\'s state; subclasses must rewinds the input stream'
def reset(self):
if (self._state is None): return self._state.following = [] self._state.errorRecovery = False self._state.lastErrorIndex = (-1) self._state.syntaxErrors = 0 self._state.backtracking = 0 if (self._state.ruleMemo is not None): self._state.ruleMemo = {}
'Match current input symbol against ttype. Attempt single token insertion or deletion error recovery. If that fails, throw MismatchedTokenException. To turn off single token insertion or deletion error recovery, override mismatchRecover() and have it call plain mismatch(), which does not recover. Then any error in a...
def match(self, input, ttype, follow):
matchedSymbol = self.getCurrentInputSymbol(input) if (self.input.LA(1) == ttype): self.input.consume() self._state.errorRecovery = False return matchedSymbol if (self._state.backtracking > 0): raise BacktrackingFailed matchedSymbol = self.recoverFromMismatchedToken(input,...
'Match the wildcard: in a symbol'
def matchAny(self, input):
self._state.errorRecovery = False self.input.consume()
'Factor out what to do upon token mismatch so tree parsers can behave differently. Override and call mismatchRecover(input, ttype, follow) to get single token insertion and deletion. Use this to turn of single token insertion and deletion. Override mismatchRecover to call this instead.'
def mismatch(self, input, ttype, follow):
if self.mismatchIsUnwantedToken(input, ttype): raise UnwantedTokenException(ttype, input) elif self.mismatchIsMissingToken(input, follow): raise MissingTokenException(ttype, input, None) raise MismatchedTokenException(ttype, input)
'Report a recognition problem. This method sets errorRecovery to indicate the parser is recovering not parsing. Once in recovery mode, no errors are generated. To get out of recovery mode, the parser must successfully match a token (after a resync). So it will go: 1. error occurs 2. enter recovery mode, report error ...
def reportError(self, e):
if self._state.errorRecovery: return self._state.syntaxErrors += 1 self._state.errorRecovery = True self.displayRecognitionError(self.tokenNames, e)
'What error message should be generated for the various exception types? Not very object-oriented code, but I like having all error message generation within one method rather than spread among all of the exception classes. This also makes it much easier for the exception handling because the exception classes do not h...
def getErrorMessage(self, e, tokenNames):
if isinstance(e, UnwantedTokenException): tokenName = '<unknown>' if (e.expecting == EOF): tokenName = 'EOF' else: tokenName = self.tokenNames[e.expecting] msg = ('extraneous input %s expecting %s' % (self.getTokenErrorDisplay(e.getUnexpectedToken(...
'Get number of recognition errors (lexer, parser, tree parser). Each recognizer tracks its own number. So parser and lexer each have separate count. Does not count the spurious errors found between an error and next valid token match See also reportError()'
def getNumberOfSyntaxErrors(self):
return self._state.syntaxErrors
'What is the error header, normally line/character position information?'
def getErrorHeader(self, e):
return ('line %d:%d' % (e.line, e.charPositionInLine))
'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...
def getTokenErrorDisplay(self, t):
s = t.text if (s is None): if (t.type == EOF): s = '<EOF>' else: s = (('<' + t.type) + '>') return repr(s)
'Override this method to change where error messages go'
def emitErrorMessage(self, msg):
sys.stderr.write((msg + '\n'))
'Recover from an error found on the input stream. This is for NoViableAlt and mismatched symbol exceptions. If you enable single token insertion and deletion, this will usually not handle mismatched symbol exceptions but there could be a mismatched token that the match() routine could not recover from.'
def recover(self, input, re):
if (self._state.lastErrorIndex == input.index()): input.consume() self._state.lastErrorIndex = input.index() followSet = self.computeErrorRecoverySet() self.beginResync() self.consumeUntil(input, followSet) self.endResync()
'A hook to listen in on the token consumption during error recovery. The DebugParser subclasses this to fire events to the listenter.'
def beginResync(self):
pass
'A hook to listen in on the token consumption during error recovery. The DebugParser subclasses this to fire events to the listenter.'
def endResync(self):
pass
'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. This local follow set only includes tokens from within the rule; ...
def computeErrorRecoverySet(self):
return self.combineFollows(False)
'Compute the context-sensitive FOLLOW set for current rule. This is set of token types that can follow a specific rule reference given a specific call chain. You get the set of viable tokens that can possibly come next (lookahead depth 1) given the current call chain. Contrast this with the definition of plain FOLLOW...
def computeContextSensitiveRuleFOLLOW(self):
return self.combineFollows(True)
'Attempt to recover from a single missing or extra token. EXTRA TOKEN LA(1) is not what we are looking for. If LA(2) has the right token, however, then assume LA(1) is some extra spurious token. Delete it and LA(2) as if we were doing a normal match(), which advances the input. MISSING TOKEN If current token is consi...
def recoverFromMismatchedToken(self, input, ttype, follow):
e = None if self.mismatchIsUnwantedToken(input, ttype): e = UnwantedTokenException(ttype, input) self.beginResync() input.consume() self.endResync() self.reportError(e) matchedSymbol = self.getCurrentInputSymbol(input) input.consume() return matche...
'Not currently used'
def recoverFromMismatchedSet(self, input, e, follow):
if self.mismatchIsMissingToken(input, follow): self.reportError(e) return self.getMissingSymbol(input, e, INVALID_TOKEN_TYPE, follow) raise e
'Match needs to return the current input symbol, which gets put into the label for the associated token ref; e.g., x=ID. Token and tree parsers need to return different objects. Rather than test for input stream type or change the IntStream interface, I use a simple method to ask the recognizer to tell me what the cur...
def getCurrentInputSymbol(self, input):
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 ...
def getMissingSymbol(self, input, e, expectedTokenType, follow):
return None
'Consume tokens until one matches the given token or token set tokenTypes can be a single token type or a set of token types'
def consumeUntil(self, input, tokenTypes):
if (not isinstance(tokenTypes, (set, frozenset))): tokenTypes = frozenset([tokenTypes]) ttype = input.LA(1) while ((ttype != EOF) and (ttype not in tokenTypes)): input.consume() ttype = input.LA(1)
'Return List<String> of the rules in your parser instance leading up to a call to this method. You could override if you want more details such as the file/line info of where in the parser java code a rule is invoked. This is very useful for error messages and for context-sensitive error recovery. You must be careful,...
def getRuleInvocationStack(self):
return self._getRuleInvocationStack(self.__module__)
'A more general version of getRuleInvocationStack where you can pass in, for example, a RecognitionException to get it\'s rule stack trace. This routine is shared with all recognizers, hence, static. TODO: move to a utility class or something; weird having lexer call this'
def _getRuleInvocationStack(cls, module):
rules = [] for frame in reversed(inspect.stack()): code = frame[0].f_code codeMod = inspect.getmodule(code) if (codeMod is None): continue if (codeMod.__name__ != module): continue if (code.co_name in ('nextToken', '<module>')): continu...
'For debugging and other purposes, might want the grammar name. Have ANTLR generate an implementation for this method.'
def getGrammarFileName(self):
return self.grammarFileName
'A convenience method for use most often with template rewrites. Convert a List<Token> to List<String>'
def toStrings(self, tokens):
if (tokens is None): return None return [token.text for token in tokens]
'Given a rule number and a start token index number, return MEMO_RULE_UNKNOWN if the rule has not parsed input starting from start index. If this rule has parsed input starting from the start index before, then return where the rule stopped parsing. It returns the index of the last token matched by the rule.'
def getRuleMemoization(self, ruleIndex, ruleStartIndex):
if (ruleIndex not in self._state.ruleMemo): self._state.ruleMemo[ruleIndex] = {} return self._state.ruleMemo[ruleIndex].get(ruleStartIndex, self.MEMO_RULE_UNKNOWN)
'Has this rule already parsed input at the current index in the input stream? Return the stop token index or MEMO_RULE_UNKNOWN. If we attempted but failed to parse properly before, return MEMO_RULE_FAILED. This method has a side-effect: if we have seen this input for this rule and successfully parsed before, then seek...
def alreadyParsedRule(self, input, ruleIndex):
stopIndex = self.getRuleMemoization(ruleIndex, input.index()) if (stopIndex == self.MEMO_RULE_UNKNOWN): return False if (stopIndex == self.MEMO_RULE_FAILED): raise BacktrackingFailed else: input.seek((stopIndex + 1)) return True
'Record whether or not this rule parsed the input at this position successfully.'
def memoize(self, input, ruleIndex, ruleStartIndex, success):
if success: stopTokenIndex = (input.index() - 1) else: stopTokenIndex = self.MEMO_RULE_FAILED if (ruleIndex in self._state.ruleMemo): self._state.ruleMemo[ruleIndex][ruleStartIndex] = stopTokenIndex
'Return a Token object from your input stream (usually a CharStream). Do not fail/return upon lexing error; keep chewing on the characters until you get a good one; errors are not passed through to the parser.'
def nextToken(self):
raise NotImplementedError
'The TokenSource is an interator. The iteration will not include the final EOF token, see also the note for the next() method.'
def __iter__(self):
return self
'Return next token or raise StopIteration. Note that this will raise StopIteration when hitting the EOF token, so EOF will not be part of the iteration.'
def next(self):
token = self.nextToken() if ((token is None) or (token.type == EOF)): raise StopIteration return token
'Return a token from this source; i.e., match a token on the char stream.'
def nextToken(self):
while 1: self._state.token = None self._state.channel = DEFAULT_CHANNEL self._state.tokenStartCharIndex = self.input.index() self._state.tokenStartCharPositionInLine = self.input.charPositionInLine self._state.tokenStartLine = self.input.line self._state.text = None ...
'Instruct the lexer to skip creating a token for current lexer rule and look for another token. nextToken() knows to keep looking when a lexer rule finishes with token set to SKIP_TOKEN. Recall that if token==null at end of any token rule, it creates one for you and emits it.'
def skip(self):
self._state.token = SKIP_TOKEN
'This is the lexer entry point that sets instance var \'token\''
def mTokens(self):
raise NotImplementedError
'Set the char stream and reset the lexer'
def setCharStream(self, input):
self.input = None self.reset() self.input = input
'The standard method called to automatically emit a token at the outermost lexical rule. The token object should point into the char buffer start..stop. If there is a text override in \'text\', use that to set the token\'s text. Override this method to emit custom Token objects. If you are building trees, then you s...
def emit(self, token=None):
if (token is None): token = CommonToken(input=self.input, type=self._state.type, channel=self._state.channel, start=self._state.tokenStartCharIndex, stop=(self.getCharIndex() - 1)) token.line = self._state.tokenStartLine token.text = self._state.text token.charPositionInLine = self._...
'What is the index of the current character of lookahead?'
def getCharIndex(self):
return self.input.index()
'Return the text matched so far for the current token or any text override.'
def getText(self):
if (self._state.text is not None): return self._state.text return self.input.substring(self._state.tokenStartCharIndex, (self.getCharIndex() - 1))
'Set the complete text of this token; it wipes any previous changes to the text.'
def setText(self, text):
self._state.text = text
'Lexers can normally match any char in it\'s vocabulary after matching a token, so do the easy thing and just kill a character and hope it all works out. You can instead use the rule invocation stack to do sophisticated error recovery if you are in a fragment rule.'
def recover(self, re):
self.input.consume()
'Set the token stream and reset the parser'
def setTokenStream(self, input):
self.input = None self.reset() self.input = input
'Return the start token or tree.'
def getStart(self):
return None
'Return the stop token or tree.'
def getStop(self):
return None
'Has a value potentially if output=AST.'
def getTree(self):
return None
'Has a value potentially if output=template.'
def getTemplate(self):
return None
'From the input stream, predict what alternative will succeed using this DFA (representing the covering regular approximation to the underlying CFL). Return an alternative number 1..n. Throw an exception upon error.'
def predict(self, input):
mark = input.mark() s = 0 try: for _ in xrange(50000): specialState = self.special[s] if (specialState >= 0): s = self.specialStateTransition(specialState, input) if (s == (-1)): self.noViableAlt(s, input) ...
'A hook for debugging interface'
def error(self, nvae):
pass
'@brief Unpack the runlength encoded table data. Terence implemented packed table initializers, because Java has a size restriction on .class files and the lookup tables can grow pretty large. The generated JavaLexer.java of the Java.g example would be about 15MB with uncompressed array initializers. Python does not ha...
def unpack(cls, string):
ret = [] for i in range((len(string) / 2)): (n, v) = (ord(string[(i * 2)]), ord(string[((i * 2) + 1)])) if (v == 65535): v = (-1) ret += ([v] * n) return ret
'Constructor. Creates an unlimited range.'
def __init__(self):
self.__start = self.__end = None self.__start_inclusive = self.__end_inclusive = False
'Filter the range by \'rel_op limit\'. Args: rel_op: relational operator from datastore_pb.Query_Filter. limit: the value to limit the range by.'
def Update(self, rel_op, limit):
if (rel_op == datastore_pb.Query_Filter.LESS_THAN): if ((self.__end is None) or (limit <= self.__end)): self.__end = limit self.__end_inclusive = False elif ((rel_op == datastore_pb.Query_Filter.LESS_THAN_OR_EQUAL) or (rel_op == datastore_pb.Query_Filter.EQUAL)): if ((sel...
'Check if the range contains a specific value. Args: value: the value to check. Returns: True iff value is contained in this range.'
def Contains(self, value):
if (self.__start is not None): if (self.__start_inclusive and (value < self.__start)): return False if ((not self.__start_inclusive) and (value <= self.__start)): return False if (self.__end is not None): if (self.__end_inclusive and (value > self.__end)): ...
'Transforms the range extremes with a function. The function mapper must preserve order, i.e. x rel_op y iff mapper(x) rel_op y Args: mapper: function to apply to the range extremes.'
def Remap(self, mapper):
self.__start = (self.__start and mapper(self.__start)) self.__end = (self.__end and mapper(self.__end))
'Evaluate a function on the range extremes. Args: mapper: function to apply to the range extremes. Returns: (x, y) where x = None if the range has no start, mapper(start, start_inclusive, False) otherwise y = None if the range has no end, mapper(end, end_inclusive, True) otherwise'
def MapExtremes(self, mapper):
return ((self.__start and mapper(self.__start, self.__start_inclusive, False)), (self.__end and mapper(self.__end, self.__end_inclusive, True)))
'Constructor. Args: query: the query request proto. dsquery: a datastore_query.Query over query. orders: the orders of query as returned by _GuessOrders. index_list: the list of indexes used by the query.'
def __init__(self, query, dsquery, orders, index_list):
self.keys_only = query.keys_only() self.property_names = set(query.property_name_list()) self.group_by = set(query.group_by_property_name_list()) self.app = query.app() self.cursor = self._AcquireCursorID() self.__order_compare_entities = dsquery._order.cmp_for_filter(dsquery._filter_predicate) ...
'Acquires the next cursor id in a thread safe manner.'
@classmethod def _AcquireCursorID(cls):
cls._next_cursor_lock.acquire() try: cursor_id = cls._next_cursor cls._next_cursor += 1 finally: cls._next_cursor_lock.release() return cursor_id
'True if entity is before cursor according to the current order. Args: entity: a entity_pb.EntityProto entity. cursor: a compiled cursor as returned by _DecodeCompiledCursor.'
def _IsBeforeCursor(self, entity, cursor):
comparison_entity = entity_pb.EntityProto() for prop in entity.property_list(): if (prop.name() in self.__cursor_properties): comparison_entity.add_property().MergeFrom(prop) if cursor[0].has_key(): comparison_entity.mutable_key().MergeFrom(entity.key()) x = self.__order_comp...
'Converts a compiled_cursor into a cursor_entity. Args: compiled_cursor: The datastore_pb.CompiledCursor to decode. Returns: (cursor_entity, inclusive): a entity_pb.EntityProto and if it should be included in the result set.'
def _DecodeCompiledCursor(self, compiled_cursor):
assert (len(compiled_cursor.position_list()) == 1) position = compiled_cursor.position(0) remaining_properties = set(self.__cursor_properties) cursor_entity = entity_pb.EntityProto() if position.has_key(): cursor_entity.mutable_key().CopyFrom(position.key()) remaining_properties.remo...
'Converts the current state of the cursor into a compiled_cursor. Args: last_result: the last result returned by this query. compiled_cursor: an empty datstore_pb.CompiledCursor.'
def _EncodeCompiledCursor(self, last_result, compiled_cursor):
if (last_result is not None): position = compiled_cursor.add_position() if ('__key__' in self.__cursor_properties): position.mutable_key().MergeFrom(last_result.key()) for prop in last_result.property_list(): if (prop.name() in self.__cursor_properties): ...