org.antlr.v4.tool.templates.codegen.Python2.Python2.stg Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of virtdata-lib-realer Show documentation
Show all versions of virtdata-lib-realer Show documentation
With inspiration from other libraries
/*
* [The "BSD license"]
* Copyright (c) 2012-2016 Terence Parr
* Copyright (c) 2012-2016 Sam Harwell
* Copyright (c) 2014 Eric Vergnaud
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** ANTLR tool checks output templates are compatible with tool code generation.
* For now, a simple string match used on x.y of x.y.z scheme.
* Must match Tool.VERSION during load to templates.
*
* REQUIRED.
*/
pythonTypeInitMap ::= [
"bool":"False",
"int":"0",
"float":"0.0",
"str":"",
default:"None" // anything other than a primitive type is an object
]
// args must be ,
ParserFile(file, parser, namedActions, contextSuperClass) ::= <<
# encoding: utf-8
from __future__ import print_function
from antlr4 import *
from io import StringIO
import sys
>>
ListenerFile(file, header, namedActions) ::= <<
from antlr4 import *
# This class defines a complete listener for a parse tree produced by .
class Listener(ParseTreeListener):
#.
def enter(self, ctx):
pass
# Exit a parse tree produced by #.
def exit(self, ctx):
pass
}; separator="\n">
>>
VisitorFile(file, header, namedActions) ::= <<
from antlr4 import *
# This class defines a complete generic visitor for a parse tree produced by .
class Visitor(ParseTreeVisitor):
#.
def visit(self, ctx):
return self.visitChildren(ctx)
}; separator="\n">
>>
fileHeader(grammarFileName, ANTLRVersion) ::= <<
# Generated from by ANTLR
>>
Parser(parser, funcs, atn, sempredFuncs, superClass) ::= <<
>>
Parser_(parser, funcs, atn, sempredFuncs, ctor, superClass) ::= <<
from . import
class ( Parser ):
grammarFileName = ""
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
sharedContextCache = PredictionContextCache()
literalNames = [ }; null="u\"\\"", separator=", ", wrap, anchor> ]
symbolicNames = [ }; null="u\"\\"", separator=", ", wrap, anchor> ]
= }; separator="\n", wrap, anchor>
ruleNames = [ "}; separator=", ", wrap, anchor> ]
EOF = .EOF
=}; separator="\n", wrap, anchor>
def sempred(self, localctx, ruleIndex, predIndex):
if self._predicates == None:
self._predicates = dict()
] = self._sempred}; separator="\n ">
pred = self._predicates.get(ruleIndex, None)
if pred is None:
raise Exception("No predicate with index:" + str(ruleIndex))
else:
return pred(localctx, predIndex)
>>
dumpActions(recog, argFuncs, actionFuncs, sempredFuncs) ::= <<
def action(self, localctx, ruleIndex, actionIndex):
if self._actions is None:
actions = dict()
] = self._action }; separator="\n">
self._actions = actions
action = self._actions.get(ruleIndex, None)
if action is not None:
action(localctx, actionIndex)
else:
raise Exception("No registered action for:" + str(ruleIndex))
def sempred(self, localctx, ruleIndex, predIndex):
if self._predicates is None:
preds = dict()
] = self._sempred}; separator="\n">
self._predicates = preds
pred = self._predicates.get(ruleIndex, None)
if pred is not None:
return pred(localctx, predIndex)
else:
raise Exception("No registered predicate for:" + str(ruleIndex))
>>
parser_ctor(p) ::= <<
def __init__(self, input, output=sys.stdout):
super(, self).__init__(input, output=output)
self.checkVersion("")
self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache)
self._predicates = None
>>
/* This generates a private method since the actionIndex is generated, making an
* overriding implementation impossible to maintain.
*/
RuleActionFunction(r, actions) ::= <<
def _action(self, localctx , actionIndex):
if actionIndex == :
elif actionIndex == :
}; separator="\n">
>>
/* This generates a private method since the predIndex is generated, making an
* overriding implementation impossible to maintain.
*/
RuleSempredFunction(r, actions) ::= <<
def _sempred(self, localctx, predIndex):
if predIndex == :
return
elif predIndex == :
return
}; separator="\n">
>>
RuleFunction(currentRule,args,code,locals,ruleCtx,altLabelCtxs,namedActions,finallyAction,postamble,exceptions) ::= <<
}; separator="\n">
def (self}>):
localctx = .(self, self._ctx, self.state}>)
self.enterRule(localctx, , self.RULE_)
try:
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
>>
LeftRecursiveRuleFunction(currentRule,args,code,locals,ruleCtx,altLabelCtxs,
namedActions,finallyAction,postamble) ::=
<<
}; separator="\n">
def (self, _p=0, }>):
_parentctx = self._ctx
_parentState = self.state
localctx = .(self, self._ctx, _parentState}>)
_prevctx = localctx
_startState =
self.enterRecursionRule(localctx, , self.RULE_, _p)
try:
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
>>
CodeBlockForOuterMostAlt(currentOuterMostAltCodeBlock, locals, preamble, ops) ::= <<
localctx = .Context(self, localctx)
self.enterOuterAlt(localctx, )
>>
CodeBlockForAlt(currentAltCodeBlock, locals, preamble, ops) ::= <<
>>
LL1AltBlock(choice, preamble, alts, error) ::= <<
self.state =
self._errHandler.sync(self)
= _input.LT(1)
token = self._input.LA(1)
pass}; separator="\nel">
else:
>>
LL1OptionalBlock(choice, alts, error) ::= <<
self.state =
self._errHandler.sync(self)
token = self._input.LA(1)
pass}; separator="\nel">
else:
pass
>>
LL1OptionalBlockSingleAlt(choice, expr, alts, preamble, error, followExpr) ::= <<
self.state =
self._errHandler.sync(self)
if :
) ) !>
>>
LL1StarBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= <<
self.state =
self._errHandler.sync(self)
while :
self.state =
self._errHandler.sync(self)
>>
LL1PlusBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= <<
self.state =
self._errHandler.sync(self)
while True:
self.state =
self._errHandler.sync(self)
if not ():
break
>>
// LL(*) stuff
AltBlock(choice, preamble, alts, error) ::= <<
self.state =
self._errHandler.sync(self)
= _input.LT(1)
la_ = self._interp.adaptivePredict(self._input,,self._ctx)
:
pass
}; separator="\nel">
>>
OptionalBlock(choice, alts, error) ::= <<
self.state =
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,,self._ctx)
+1:
}; separator="\nel">
>>
StarBlock(choice, alts, sync, iteration) ::= <<
self.state =
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,,self._ctx)
while _alt!= and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1+1:
self.state =
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,,self._ctx)
>>
PlusBlock(choice, alts, error) ::= <<
self.state =
self._errHandler.sync(self)
_alt = 1+1
while _alt!= and _alt!=ATN.INVALID_ALT_NUMBER:
+1:
}; separator="\nel">
else:
self.state =
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,,self._ctx)
>>
Sync(s) ::= "sync()"
ThrowNoViableAlt(t) ::= "raise NoViableAltException(self)"
TestSetInline(s) ::= <<
}; separator=" or ">
>>
// Java language spec 15.19 - shift operators mask operands rather than overflow to 0... need range test
testShiftInRange(shiftAmount) ::= <<
(() & ~0x3f) == 0
>>
// produces smaller bytecode only when bits.ttypes contains more than two items
bitsetBitfieldComparison(s, bits) ::= <%
(})> and ((1 \<\< ) & ()}; separator=" | ">)) != 0)
%>
isZero ::= [
"0":true,
default:false
]
offsetShiftVar(shiftAmount, offset) ::= <%
( - )
%>
offsetShiftType(shiftAmount, offset) ::= <%
(. - ).
%>
// produces more efficient bytecode when bits.ttypes contains at most two items
bitsetInlineComparison(s, bits) ::= <%
==.}; separator=" or ">
%>
cases(ttypes) ::= <<
if token in [.}; separator=", ">]:
>>
InvokeRule(r, argExprsChunks) ::= <<
self.state =
= }>self.(,)
>>
MatchToken(m) ::= <<
self.state =
= }>self.match(.)
>>
MatchSet(m, expr, capture) ::= ""
MatchNotSet(m, expr, capture) ::= ""
CommonSetStuff(m, expr, capture, invert) ::= <<
self.state =
= }>self._input.LT(1)
if \<= 0 or if not()