desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'BaseTree doesn\'t track parent pointers.'
| def setParent(self, t):
| pass
|
'Print out a whole tree not just a node'
| def toStringTree(self):
| if (len(self.children) == 0):
return self.toString()
buf = []
if (not self.isNil()):
buf.append('(')
buf.append(self.toString())
buf.append(' ')
for (i, child) in enumerate(self.children):
if (i > 0):
buf.append(' ')
buf.append(child.toSt... |
'Override to say how a node (not a tree) should look as text'
| def toString(self):
| raise NotImplementedError
|
'create tree node that holds the start and stop tokens associated
with an error.
If you specify your own kind of tree nodes, you will likely have to
override this method. CommonTree returns Token.INVALID_TOKEN_TYPE
if no token payload but you might have to set token type for diff
node type.'
| def errorNode(self, input, start, stop, exc):
| return CommonErrorNode(input, start, stop, exc)
|
'This is generic in the sense that it will work with any kind of
tree (not just Tree interface). It invokes the adaptor routines
not the tree node routines to do the construction.'
| def dupTree(self, t, parent=None):
| if (t is None):
return None
newTree = self.dupNode(t)
self.setChildIndex(newTree, self.getChildIndex(t))
self.setParent(newTree, parent)
for i in range(self.getChildCount(t)):
child = self.getChild(t, i)
newSubTree = self.dupTree(child, t)
self.addChild(newTree, newSu... |
'Add a child to the tree t. If child is a flat tree (a list), make all
in list children of t. Warning: if t has no children, but child does
and child isNil then you can decide it is ok to move children to t via
t.children = child.children; i.e., without copying the array. Just
make sure that this is consistent with ... | def addChild(self, tree, child):
| if ((tree is not None) and (child is not None)):
tree.addChild(child)
|
'If oldRoot is a nil root, just copy or move the children to newRoot.
If not a nil root, make oldRoot a child of newRoot.
old=^(nil a b c), new=r yields ^(r a b c)
old=^(a b c), new=r yields ^(r ^(a b c))
If newRoot is a nil-rooted single child tree, use the single
child as the new root node.
old=^(nil a b c), new=^(ni... | def becomeRoot(self, newRoot, oldRoot):
| if isinstance(newRoot, Token):
newRoot = self.create(newRoot)
if (oldRoot is None):
return newRoot
if (not isinstance(newRoot, CommonTree)):
newRoot = self.createWithPayload(newRoot)
if newRoot.isNil():
nc = newRoot.getChildCount()
if (nc == 1):
newRoo... |
'Transform ^(nil x) to x and nil to null'
| def rulePostProcessing(self, root):
| if ((root is not None) and root.isNil()):
if (root.getChildCount() == 0):
root = None
elif (root.getChildCount() == 1):
root = root.getChild(0)
root.setParent(None)
root.setChildIndex((-1))
return root
|
'Tell me how to create a token for use with imaginary token nodes.
For example, there is probably no input symbol associated with imaginary
token DECL, but you need to create it as a payload or whatever for
the DECL node as in ^(DECL type ID).
If you care what the token payload objects\' type is, you should
override th... | def createToken(self, fromToken=None, tokenType=None, text=None):
| raise NotImplementedError
|
'Duplicate a node. This is part of the factory;
override if you want another kind of node to be built.
I could use reflection to prevent having to override this
but reflection is slow.'
| def dupNode(self, treeNode):
| if (treeNode is None):
return None
return treeNode.dupNode()
|
'Tell me how to create a token for use with imaginary token nodes.
For example, there is probably no input symbol associated with imaginary
token DECL, but you need to create it as a payload or whatever for
the DECL node as in ^(DECL type ID).
If you care what the token payload objects\' type is, you should
override th... | def createToken(self, fromToken=None, tokenType=None, text=None):
| if (fromToken is not None):
return CommonToken(oldToken=fromToken)
return CommonToken(type=tokenType, text=text)
|
'Track start/stop token for subtree root created for a rule.
Only works with Tree nodes. For rules that match nothing,
seems like this will yield start=i and stop=i-1 in a nil node.
Might be useful info so I\'ll not force to be i..i.'
| def setTokenBoundaries(self, t, startToken, stopToken):
| if (t is None):
return
start = 0
stop = 0
if (startToken is not None):
start = startToken.index
if (stopToken is not None):
stop = stopToken.index
t.setTokenStartIndex(start)
t.setTokenStopIndex(stop)
|
'What is the Token associated with this node? If
you are not using CommonTree, then you must
override this in your own adaptor.'
| def getToken(self, t):
| if isinstance(t, CommonTree):
return t.getToken()
return None
|
'Get a tree node at an absolute index i; 0..n-1.
If you don\'t want to buffer up nodes, then this method makes no
sense for you.'
| def get(self, i):
| raise NotImplementedError
|
'Get tree node at current input pointer + i ahead where i=1 is next node.
i<0 indicates nodes in the past. So LT(-1) is previous node, but
implementations are not required to provide results for k < -1.
LT(0) is undefined. For i>=n, return null.
Return null for LT(0) and any index that results in an absolute address
... | def LT(self, k):
| raise NotImplementedError
|
'Where is this stream pulling nodes from? This is not the name, but
the object that provides node objects.'
| def getTreeSource(self):
| raise NotImplementedError
|
'If the tree associated with this stream was created from a TokenStream,
you can specify it here. Used to do rule $text attribute in tree
parser. Optional unless you use tree parser rule text attribute
or output=template and rewrite=true options.'
| def getTokenStream(self):
| raise NotImplementedError
|
'What adaptor can tell me how to interpret/navigate nodes and
trees. E.g., get text of a node.'
| def getTreeAdaptor(self):
| raise NotImplementedError
|
'As we flatten the tree, we use UP, DOWN nodes to represent
the tree structure. When debugging we need unique nodes
so we have to instantiate new ones. When doing normal tree
parsing, it\'s slow and a waste of memory to create unique
navigation nodes. Default should be false;'
| def setUniqueNavigationNodes(self, uniqueNavigationNodes):
| raise NotImplementedError
|
'Return the text of all nodes from start to stop, inclusive.
If the stream does not buffer all the nodes then it can still
walk recursively from start until stop. You can always return
null or "" too, but users should not access $ruleLabel.text in
an action of course in that case.'
| def toString(self, start, stop):
| raise NotImplementedError
|
'Replace from start to stop child index of parent with t, which might
be a list. Number of children may be different
after this call. The stream is notified because it is walking the
tree and might need to know you are monkeying with the underlying
tree. Also, it might be able to modify the node stream to avoid
rest... | def replaceChildren(self, parent, startChildIndex, stopChildIndex, t):
| raise NotImplementedError
|
'Walk tree with depth-first-search and fill nodes buffer.
Don\'t do DOWN, UP nodes if its a list (t is isNil).'
| def fillBuffer(self):
| self._fillBuffer(self.root)
self.p = 0
|
'What is the stream index for node? 0..n-1
Return -1 if node not found.'
| def getNodeIndex(self, node):
| if (self.p == (-1)):
self.fillBuffer()
for (i, t) in enumerate(self.nodes):
if (t == node):
return i
return (-1)
|
'As we flatten the tree, we use UP, DOWN nodes to represent
the tree structure. When debugging we need unique nodes
so instantiate new ones when uniqueNavigationNodes is true.'
| def addNavigationNode(self, ttype):
| navNode = None
if (ttype == DOWN):
if self.hasUniqueNavigationNodes():
navNode = self.adaptor.createFromType(DOWN, 'DOWN')
else:
navNode = self.down
elif self.hasUniqueNavigationNodes():
navNode = self.adaptor.createFromType(UP, 'UP')
else:
navNode... |
'Look backwards k nodes'
| def LB(self, k):
| if (k == 0):
return None
if ((self.p - k) < 0):
return None
return self.nodes[(self.p - k)]
|
'Make stream jump to a new location, saving old location.
Switch back with pop().'
| def push(self, index):
| self.calls.append(self.p)
self.seek(index)
|
'Seek back to previous index saved during last push() call.
Return top of stack (return index).'
| def pop(self):
| ret = self.calls.pop((-1))
self.seek(ret)
return ret
|
'Used for testing, just return the token type stream'
| def __str__(self):
| if (self.p == (-1)):
self.fillBuffer()
return ' '.join([str(self.adaptor.getType(node)) for node in self.nodes])
|
'Set the input stream'
| def setTreeNodeStream(self, input):
| self.input = input
|
'Match \'.\' in tree parser has special meaning. Skip node or
entire tree if node has children. If children, scan until
corresponding UP node.'
| def matchAny(self, ignore):
| self._state.errorRecovery = False
look = self.input.LT(1)
if (self.input.getTreeAdaptor().getChildCount(look) == 0):
self.input.consume()
return
level = 0
tokenType = self.input.getTreeAdaptor().getType(look)
while ((tokenType != EOF) and (not ((tokenType == UP) and (level == 0))... |
'We have DOWN/UP nodes in the stream that have no line info; override.
plus we want to alter the exception type. Don\'t try to recover
from tree parser errors inline...'
| def mismatch(self, input, ttype, follow):
| raise MismatchedTreeNodeException(ttype, input)
|
'Prefix error message with the grammar name because message is
always intended for the programmer because the parser built
the input tree not the user.'
| def getErrorHeader(self, e):
| return (self.getGrammarFileName() + (': node from %sline %s:%s' % (['', 'after '][e.approximateLineInfo], e.line, e.charPositionInLine)))
|
'Tree parsers parse nodes they usually have a token object as
payload. Set the exception token and do the default behavior.'
| def getErrorMessage(self, e, tokenNames):
| if isinstance(self, TreeParser):
adaptor = e.input.getTreeAdaptor()
e.token = adaptor.getToken(e.node)
if (e.token is not None):
e.token = CommonToken(type=adaptor.getType(e.node), text=adaptor.getText(e.node))
return BaseRecognizer.getErrorMessage(self, e, tokenNames)
|
'Reset the condition of this stream so that it appears we have
not consumed any of its elements. Elements themselves are untouched.
Once we reset the stream, any future use will need duplicates. Set
the dirty bit.'
| def reset(self):
| self.cursor = 0
self.dirty = True
|
'Return the next element in the stream. If out of elements, throw
an exception unless size()==1. If size is 1, then return elements[0].
Return a duplicate node/subtree if stream is out of elements and
size==1. If we\'ve already used the element, dup (dirty bit set).'
| def nextTree(self):
| if (self.dirty or ((self.cursor >= len(self)) and (len(self) == 1))):
el = self._next()
return self.dup(el)
el = self._next()
return el
|
'do the work of getting the next element, making sure that it\'s
a tree node or subtree. Deal with the optimization of single-
element list versus list of size > 1. Throw an exception
if the stream is empty or we\'re out of elements and size>1.
protected so you can override in a subclass if necessary.'
| def _next(self):
| if (len(self) == 0):
raise RewriteEmptyStreamException(self.elementDescription)
if (self.cursor >= len(self)):
if (len(self) == 1):
return self.toTree(self.singleElement)
raise RewriteCardinalityException(self.elementDescription)
if (self.singleElement is not None):
... |
'When constructing trees, sometimes we need to dup a token or AST
subtree. Dup\'ing a token means just creating another AST node
around it. For trees, you must call the adaptor.dupTree() unless
the element is for a tree root; then it must be a node dup.'
| def dup(self, el):
| raise NotImplementedError
|
'Ensure stream emits trees; tokens must be converted to AST nodes.
AST nodes can be passed through unmolested.'
| def toTree(self, el):
| return el
|
'Deprecated. Directly access elementDescription attribute'
| def getDescription(self):
| return self.elementDescription
|
'Treat next element as a single node even if it\'s a subtree.
This is used instead of next() when the result has to be a
tree root node. Also prevents us from duplicating recently-added
children; e.g., ^(type ID)+ adds ID to type and then 2nd iteration
must dup the type node, but ID has been added.
Referencing a rule ... | def nextNode(self):
| if (self.dirty or ((self.cursor >= len(self)) and (len(self) == 1))):
el = self._next()
return self.adaptor.dupNode(el)
el = self._next()
return el
|
'Using the map of token names to token types, return the type.'
| def getTokenType(self, tokenName):
| try:
return self.tokenNameToTypeMap[tokenName]
except KeyError:
return INVALID_TOKEN_TYPE
|
'Create a tree or node from the indicated tree pattern that closely
follows ANTLR tree grammar tree element syntax:
(root child1 ... child2).
You can also just pass in a node: ID
Any node can have a text argument: ID[foo]
(notice there are no quotes around foo--it\'s clear it\'s a string).
nil is a special name meaning... | def create(self, pattern):
| tokenizer = TreePatternLexer(pattern)
parser = TreePatternParser(tokenizer, self, self.adaptor)
return parser.pattern()
|
'Walk the entire tree and make a node name to nodes mapping.
For now, use recursion but later nonrecursive version may be
more efficient. Returns a dict int -> list where the list is
of your AST node type. The int is the token type of the node.'
| def index(self, tree):
| m = {}
self._index(tree, m)
return m
|
'Do the work for index'
| def _index(self, t, m):
| if (t is None):
return
ttype = self.adaptor.getType(t)
elements = m.get(ttype)
if (elements is None):
m[ttype] = elements = []
elements.append(t)
for i in range(self.adaptor.getChildCount(t)):
child = self.adaptor.getChild(t, i)
self._index(child, m)
|
'Return a list of matching token.
what may either be an integer specifzing the token type to find or
a string with a pattern that must be matched.'
| def find(self, tree, what):
| if isinstance(what, (int, long)):
return self._findTokenType(tree, what)
elif isinstance(what, basestring):
return self._findPattern(tree, what)
else:
raise TypeError("'what' must be string or integer")
|
'Return a List of tree nodes with token type ttype'
| def _findTokenType(self, t, ttype):
| nodes = []
def visitor(tree, parent, childIndex, labels):
nodes.append(tree)
self.visit(t, ttype, visitor)
return nodes
|
'Return a List of subtrees matching pattern.'
| def _findPattern(self, t, pattern):
| subtrees = []
tokenizer = TreePatternLexer(pattern)
parser = TreePatternParser(tokenizer, self, TreePatternTreeAdaptor())
tpattern = parser.pattern()
if ((tpattern is None) or tpattern.isNil() or isinstance(tpattern, WildcardTreePattern)):
return None
rootTokenType = tpattern.getType()
... |
'Visit every node in tree matching what, invoking the visitor.
If what is a string, it is parsed as a pattern and only matching
subtrees will be visited.
The implementation uses the root node of the pattern in combination
with visit(t, ttype, visitor) so nil-rooted patterns are not allowed.
Patterns with wildcard roots... | def visit(self, tree, what, visitor):
| if isinstance(what, (int, long)):
self._visitType(tree, None, 0, what, visitor)
elif isinstance(what, basestring):
self._visitPattern(tree, what, visitor)
else:
raise TypeError("'what' must be string or integer")
|
'Do the recursive work for visit'
| def _visitType(self, t, parent, childIndex, ttype, visitor):
| if (t is None):
return
if (self.adaptor.getType(t) == ttype):
visitor(t, parent, childIndex, None)
for i in range(self.adaptor.getChildCount(t)):
child = self.adaptor.getChild(t, i)
self._visitType(child, t, i, ttype, visitor)
|
'For all subtrees that match the pattern, execute the visit action.'
| def _visitPattern(self, tree, pattern, visitor):
| tokenizer = TreePatternLexer(pattern)
parser = TreePatternParser(tokenizer, self, TreePatternTreeAdaptor())
tpattern = parser.pattern()
if ((tpattern is None) or tpattern.isNil() or isinstance(tpattern, WildcardTreePattern)):
return
rootTokenType = tpattern.getType()
def rootvisitor(tree... |
'Given a pattern like (ASSIGN %lhs:ID %rhs:.) with optional labels
on the various nodes and \'.\' (dot) as the node/subtree wildcard,
return true if the pattern matches and fill the labels Map with
the labels pointing at the appropriate nodes. Return false if
the pattern is malformed or the tree does not match.
If a n... | def parse(self, t, pattern, labels=None):
| tokenizer = TreePatternLexer(pattern)
parser = TreePatternParser(tokenizer, self, TreePatternTreeAdaptor())
tpattern = parser.pattern()
return self._parse(t, tpattern, labels)
|
'Do the work for parse. Check to see if the t2 pattern fits the
structure and token types in t1. Check text if the pattern has
text arguments on nodes. Fill labels map with pointers to nodes
in tree matched against nodes in pattern with labels.'
| def _parse(self, t1, t2, labels):
| if ((t1 is None) or (t2 is None)):
return False
if (not isinstance(t2, WildcardTreePattern)):
if (self.adaptor.getType(t1) != t2.getType()):
return False
if (t2.hasTextArg and (self.adaptor.getText(t1) != t2.getText())):
return False
if ((t2.label is not None)... |
'Compare t1 and t2; return true if token types/text, structure match
exactly.
The trees are examined in their entirety so that (A B) does not match
(A B C) nor (A (B C)).'
| def equals(self, t1, t2, adaptor=None):
| if (adaptor is None):
adaptor = self.adaptor
return self._equals(t1, t2, adaptor)
|
'Get int at current input pointer + i ahead where i=1 is next int.
Negative indexes are allowed. LA(-1) is previous token (token
just matched). LA(-i) where i is before first token should
yield -1, invalid char / EOF.'
| def LA(self, i):
| raise NotImplementedError
|
'Tell the stream to start buffering if it hasn\'t already. Return
current input position, index(), or some other marker so that
when passed to rewind() you get back to the same spot.
rewind(mark()) should not affect the input cursor. The Lexer
track line/col info as well as input index so its markers are
not pure inp... | def mark(self):
| raise NotImplementedError
|
'Return the current input symbol index 0..n where n indicates the
last symbol has been read. The index is the symbol about to be
read not the most recently read symbol.'
| def index(self):
| raise NotImplementedError
|
'Reset the stream so that next call to index would return marker.
The marker will usually be index() but it doesn\'t have to be. It\'s
just a marker to indicate what state the stream was in. This is
essentially calling release() and seek(). If there are markers
created after this marker argument, this routine must u... | def rewind(self, marker=None):
| raise NotImplementedError
|
'You may want to commit to a backtrack but don\'t want to force the
stream to keep bookkeeping objects around for a marker that is
no longer necessary. This will have the same behavior as
rewind() except it releases resources without the backward seek.
This must throw away resources for all markers back to the marker
... | def release(self, marker=None):
| raise NotImplementedError
|
'Set the input cursor to the position indicated by index. This is
normally used to seek ahead in the input stream. No buffering is
required to do this unless you know your stream will use seek to
move backwards such as when backtracking.
This is different from rewind in its multi-directional
requirement and in that i... | def seek(self, index):
| raise NotImplementedError
|
'Only makes sense for streams that buffer everything up probably, but
might be useful to display the entire stream or for testing. This
value includes a single EOF.'
| def size(self):
| raise NotImplementedError
|
'Where are you getting symbols from? Normally, implementations will
pass the buck all the way to the lexer who can ask its input stream
for the file name or whatever.'
| def getSourceName(self):
| raise NotImplementedError
|
'For infinite streams, you don\'t need this; primarily I\'m providing
a useful interface for action code. Just make sure actions don\'t
use this on streams that don\'t support it.'
| def substring(self, start, stop):
| raise NotImplementedError
|
'Get the ith character of lookahead. This is the same usually as
LA(i). This will be used for labels in the generated
lexer code. I\'d prefer to return a char here type-wise, but it\'s
probably better to be 32-bit clean and be consistent with LA.'
| def LT(self, i):
| raise NotImplementedError
|
'ANTLR tracks the line information automatically'
| def getLine(self):
| raise NotImplementedError
|
'Because this stream can rewind, we need to be able to reset the line'
| def setLine(self, line):
| raise NotImplementedError
|
'The index of the character relative to the beginning of the line 0..n-1'
| def getCharPositionInLine(self):
| raise NotImplementedError
|
'Get Token at current input pointer + i ahead where i=1 is next Token.
i<0 indicates tokens in the past. So -1 is previous token and -2 is
two tokens ago. LT(0) is undefined. For i>=n, return Token.EOFToken.
Return null for LT(0) and any index that results in an absolute address
that is negative.'
| def LT(self, k):
| raise NotImplementedError
|
'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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.