schrodinger.application.desmond.antlr3.streams module

ANTLR3 runtime package

class schrodinger.application.desmond.antlr3.streams.IntStream

Bases: object

@brief Base interface for streams of integer values.

A simple stream of integers used when all I care about is the char or token type sequence (such as interpretation).

consume()
LA(i)

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.

mark()

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 input indexes. Same for tree node streams.

index()

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.

rewind(marker=None)

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 unroll them like a stack. Assume the state the stream was in when this marker was created.

If marker is None: Rewind to the input position of the last marker. Used currently only after a cyclic DFA and just before starting a sem/syn predicate to get the input position back to the start of the decision. Do not “pop” the marker off the state. mark(i) and rewind(i) should balance still. It is like invoking rewind(last marker) but it should not “pop” the marker off. It’s like seek(last marker’s input position).

release(marker=None)

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 argument. So if you’re nested 5 levels of mark(), and then release(2) you have to release resources for depths 2..5.

seek(index)

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 its argument is strictly an input cursor (index).

For char streams, seeking forward must update the stream state such as line number. For seeking backwards, you will be presumably backtracking using the mark/rewind mechanism that restores state and so this method does not need to update state when seeking backwards.

Currently, this method is only used for efficient backtracking using memoization, but in the future it may be used for incremental parsing.

The index is 0..n-1. A seek to position i means that LA(1) will return the ith symbol. So, seeking to 0 means LA(1) will return the first element in the stream.

size()

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.

getSourceName()

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.

class schrodinger.application.desmond.antlr3.streams.CharStream

Bases: schrodinger.application.desmond.antlr3.streams.IntStream

@brief A source of characters for an ANTLR lexer.

This is an abstract class that must be implemented by a subclass.

EOF = -1
substring(start, stop)

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.

LT(i)

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.

getLine()

ANTLR tracks the line information automatically

setLine(line)

Because this stream can rewind, we need to be able to reset the line

getCharPositionInLine()

The index of the character relative to the beginning of the line 0..n-1

setCharPositionInLine(pos)
class schrodinger.application.desmond.antlr3.streams.TokenStream

Bases: schrodinger.application.desmond.antlr3.streams.IntStream

@brief A stream of tokens accessing tokens from a TokenSource

This is an abstract class that must be implemented by a subclass.

LT(k)

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.

get(i)

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 use this method, removing the dependency.

getTokenSource()

Where is this stream pulling tokens from? This is not the name, but the object that provides Token objects.

toString(start=None, stop=None)

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 for two token objects themselves to indicate the start/end location. Most often this will just delegate to the other toString(int,int). This is also parallel with the TreeNodeStream.toString(Object,Object).

class schrodinger.application.desmond.antlr3.streams.ANTLRStringStream(data)

Bases: schrodinger.application.desmond.antlr3.streams.CharStream

@brief CharStream that pull data from a unicode string.

A pretty quick CharStream that pulls all data from an array directly. Every method call counts in the lexer.

__init__(data)
: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.

reset()

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.

consume()
LA(i)

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.

LT(i)

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.

index()

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).

size()

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.

mark()

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 input indexes. Same for tree node streams.

rewind(marker=None)

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 unroll them like a stack. Assume the state the stream was in when this marker was created.

If marker is None: Rewind to the input position of the last marker. Used currently only after a cyclic DFA and just before starting a sem/syn predicate to get the input position back to the start of the decision. Do not “pop” the marker off the state. mark(i) and rewind(i) should balance still. It is like invoking rewind(last marker) but it should not “pop” the marker off. It’s like seek(last marker’s input position).

release(marker=None)

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 argument. So if you’re nested 5 levels of mark(), and then release(2) you have to release resources for depths 2..5.

seek(index)

consume() ahead until p==index; can’t just set p=index as we must update line and charPositionInLine.

substring(start, stop)

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.

getLine()

Using setter/getter methods is deprecated. Use o.line instead.

getCharPositionInLine()

Using setter/getter methods is deprecated. Use o.charPositionInLine instead.

setLine(line)

Using setter/getter methods is deprecated. Use o.line instead.

setCharPositionInLine(pos)

Using setter/getter methods is deprecated. Use o.charPositionInLine instead.

getSourceName()

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.

class schrodinger.application.desmond.antlr3.streams.ANTLRFileStream(fileName, encoding=None)

Bases: schrodinger.application.desmond.antlr3.streams.ANTLRStringStream

@brief CharStream that opens a file to read the data.

This is a char buffer stream that is loaded from a file all at once when you construct the object.

__init__(fileName, encoding=None)
: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.

getSourceName()

Deprecated, access o.fileName directly.

class schrodinger.application.desmond.antlr3.streams.ANTLRInputStream(file, encoding=None)

Bases: schrodinger.application.desmond.antlr3.streams.ANTLRStringStream

@brief CharStream that reads data from a file-like object.

This is a char buffer stream that is loaded from a file like object all at once when you construct the object.

All input is consumed from the file, but it is not closed.

__init__(file, encoding=None)
: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.

schrodinger.application.desmond.antlr3.streams.StringStream

alias of schrodinger.application.desmond.antlr3.streams.ANTLRStringStream

schrodinger.application.desmond.antlr3.streams.FileStream

alias of schrodinger.application.desmond.antlr3.streams.ANTLRFileStream

schrodinger.application.desmond.antlr3.streams.InputStream

alias of schrodinger.application.desmond.antlr3.streams.ANTLRInputStream

class schrodinger.application.desmond.antlr3.streams.CommonTokenStream(tokenSource=None, channel=0)

Bases: schrodinger.application.desmond.antlr3.streams.TokenStream

@brief The most common stream of tokens

The most common stream of tokens is one where every token is buffered up and tokens are prefiltered for a certain channel (the parser will only see these tokens and cannot change the filter channel number during the parse).

__init__(tokenSource=None, channel=0)
: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…

setTokenSource(tokenSource)

Reset this token stream by setting its token source.

reset()
fillBuffer()

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.

consume()

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.

skipOffTokenChannels(i)

Given a starting index, return the index of the first on-channel token.

skipOffTokenChannelsReverse(i)
setTokenTypeChannel(ttype, channel)

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.

discardTokenType(ttype)
getTokens(start=None, stop=None, types=None)

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.

LT(k)

Get the ith token from the current position 1..n where k=1 is the first symbol of lookahead.

LB(k)

Look backwards k tokens on-channel tokens

get(i)

Return absolute token i; ignore which channel the tokens are on; that is, count all tokens not just on-channel tokens.

LA(i)

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.

mark()

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 input indexes. Same for tree node streams.

release(marker=None)

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 argument. So if you’re nested 5 levels of mark(), and then release(2) you have to release resources for depths 2..5.

size()

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.

index()

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.

rewind(marker=None)

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 unroll them like a stack. Assume the state the stream was in when this marker was created.

If marker is None: Rewind to the input position of the last marker. Used currently only after a cyclic DFA and just before starting a sem/syn predicate to get the input position back to the start of the decision. Do not “pop” the marker off the state. mark(i) and rewind(i) should balance still. It is like invoking rewind(last marker) but it should not “pop” the marker off. It’s like seek(last marker’s input position).

seek(index)

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 its argument is strictly an input cursor (index).

For char streams, seeking forward must update the stream state such as line number. For seeking backwards, you will be presumably backtracking using the mark/rewind mechanism that restores state and so this method does not need to update state when seeking backwards.

Currently, this method is only used for efficient backtracking using memoization, but in the future it may be used for incremental parsing.

The index is 0..n-1. A seek to position i means that LA(1) will return the ith symbol. So, seeking to 0 means LA(1) will return the first element in the stream.

getTokenSource()

Where is this stream pulling tokens from? This is not the name, but the object that provides Token objects.

getSourceName()

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.

toString(start=None, stop=None)

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 for two token objects themselves to indicate the start/end location. Most often this will just delegate to the other toString(int,int). This is also parallel with the TreeNodeStream.toString(Object,Object).

class schrodinger.application.desmond.antlr3.streams.RewriteOperation(stream, index, text)

Bases: object

@brief Internal helper class.

__init__(stream, index, text)
execute(buf)

Execute the rewrite operation by possibly adding to the buffer. Return the index of the next token to operate on.

toString()
class schrodinger.application.desmond.antlr3.streams.InsertBeforeOp(stream, index, text)

Bases: schrodinger.application.desmond.antlr3.streams.RewriteOperation

@brief Internal helper class.

execute(buf)

Execute the rewrite operation by possibly adding to the buffer. Return the index of the next token to operate on.

class schrodinger.application.desmond.antlr3.streams.ReplaceOp(stream, first, last, text)

Bases: schrodinger.application.desmond.antlr3.streams.RewriteOperation

@brief Internal helper class.

I’m going to try replacing range from x..y with (y-x)+1 ReplaceOp instructions.

__init__(stream, first, last, text)
execute(buf)

Execute the rewrite operation by possibly adding to the buffer. Return the index of the next token to operate on.

toString()
class schrodinger.application.desmond.antlr3.streams.DeleteOp(stream, first, last)

Bases: schrodinger.application.desmond.antlr3.streams.ReplaceOp

@brief Internal helper class.

__init__(stream, first, last)
toString()
class schrodinger.application.desmond.antlr3.streams.TokenRewriteStream(tokenSource=None, channel=0)

Bases: schrodinger.application.desmond.antlr3.streams.CommonTokenStream

@brief CommonTokenStream that can be modified.

Useful for dumping out the input stream after doing some augmentation or other manipulations.

You can insert stuff, replace, and delete chunks. Note that the operations are done lazily–only if you convert the buffer to a String. This is very efficient because you are not moving data around all the time. As the buffer of tokens is converted to strings, the toString() method(s) check to see if there is an operation at the current index. If so, the operation is done and then normal String rendering continues on the buffer. This is like having multiple Turing machine instruction streams (programs) operating on a single input tape. :)

Since the operations are done lazily at toString-time, operations do not screw up the token index values. That is, an insert operation at token index i does not change the index values for tokens i+1..n-1.

Because operations never actually alter the buffer, you may always get the original token stream back without undoing anything. Since the instructions are queued up, you can easily simulate transactions and roll back any changes if there is an error just by removing instructions. For example,

CharStream input = new ANTLRFileStream(“input”); TLexer lex = new TLexer(input); TokenRewriteStream tokens = new TokenRewriteStream(lex); T parser = new T(tokens); parser.startRule();

Then in the rules, you can execute

Token t,u; … input.insertAfter(t, “text to put after t”);} input.insertAfter(u, “text after u”);} System.out.println(tokens.toString());

Actually, you have to cast the ‘input’ to a TokenRewriteStream. :(

You can also have multiple “instruction streams” and get multiple rewrites from a single pass over the input. Just name the instruction streams and use that name again when printing the buffer. This could be useful for generating a C file and also its header file–all from the same buffer:

tokens.insertAfter(“pass1”, t, “text to put after t”);} tokens.insertAfter(“pass2”, u, “text after u”);} System.out.println(tokens.toString(“pass1”)); System.out.println(tokens.toString(“pass2”));

If you don’t use named rewrite streams, a “default” stream is used as the first example shows.

DEFAULT_PROGRAM_NAME = 'default'
MIN_TOKEN_INDEX = 0
__init__(tokenSource=None, channel=0)
: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…

rollback(*args)

Rollback the instruction stream for a program so that the indicated instruction (via instructionIndex) is no longer in the stream. UNTESTED!

deleteProgram(programName='default')

Reset the program so that no instructions exist

insertAfter(*args)
insertBefore(*args)
replace(*args)
delete(*args)
getLastRewriteTokenIndex(programName='default')
setLastRewriteTokenIndex(programName, i)
getProgram(name)
initializeProgram(name)
toOriginalString(start=None, end=None)
toString(*args)

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 for two token objects themselves to indicate the start/end location. Most often this will just delegate to the other toString(int,int). This is also parallel with the TreeNodeStream.toString(Object,Object).

reduceToSingleOperationPerIndex(rewrites)

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.x-y.v | i-j in x-y delete first R R.i-j.u R.i-j.v delete first R R.i-j.u R.x-y.v | x-y in i-j ERROR R.i-j.u R.x-y.v | boundaries overlap ERROR

I.i.u R.x-y.v | i in x-y delete I I.i.u R.x-y.v | i not in x-y leave alone, nonoverlapping R.x-y.v I.i.u | i in x-y ERROR R.x-y.v I.x.u R.x-y.uv (combine, delete I) R.x-y.v I.i.u | i not in x-y leave alone, nonoverlapping

I.i.u = insert u before op @ index i R.x-y.u = replace x-y indexed tokens with u

First we need to examine replaces. For any replace op:

  1. wipe out any insertions before op within that range.

  2. Drop any replace op before that is contained completely within that range.

  3. Throw exception upon boundary overlap with any previous replace.

Then we can deal with inserts:

  1. for any inserts to same index, combine even if not adjacent.

  2. for any prior replace with same left boundary, combine this insert with replace and delete this replace.

  3. throw exception if index in same range as previous replace

Don’t actually delete; make op null in list. Easier to walk list. Later we can throw as we add to index -> op map.

Note that I.2 R.2-2 will wipe out I.2 even though, technically, the inserted stuff would be before the replace range. But, if you add tokens in front of a method body ‘{’ and then delete the method body, I think the stuff before the ‘{’ you added should disappear too.

Return a map from token index to operation.

catOpText(a, b)
getKindOfOps(rewrites, kind, before=None)
toDebugString(start=None, end=None)