From d667b90bc9d30dee7940014c52740b4c5d73d0b9 Mon Sep 17 00:00:00 2001 From: Iman Hosseini Date: Sun, 28 Jul 2019 02:25:42 +0430 Subject: [PATCH 01/33] Fixed TextIO compatibility with 3.6+ Fixing this issue: https://github.com/antlr/antlr4/issues/2611 (and probably https://github.com/antlr/antlr4/issues/2193) TextIO has moved since Python 3.6 so it should be imported considering the change for new versions. --- .../org/antlr/v4/tool/templates/codegen/Python3/Python3.stg | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tool/resources/org/antlr/v4/tool/templates/codegen/Python3/Python3.stg b/tool/resources/org/antlr/v4/tool/templates/codegen/Python3/Python3.stg index ecd6af0f5..701a09a28 100644 --- a/tool/resources/org/antlr/v4/tool/templates/codegen/Python3/Python3.stg +++ b/tool/resources/org/antlr/v4/tool/templates/codegen/Python3/Python3.stg @@ -51,8 +51,11 @@ ParserFile(file, parser, namedActions, contextSuperClass) ::= << # encoding: utf-8 from antlr4 import * from io import StringIO -from typing.io import TextIO import sys +if sys.version_info[1] > 5: + from typing import TextIO +else: + from typing.io import TextIO From 32470dbab48dbe70e035e61cebee54f4df611b33 Mon Sep 17 00:00:00 2001 From: Eric Vergnaud Date: Sat, 24 Aug 2019 01:44:36 +0800 Subject: [PATCH 02/33] align on other runtimes --- runtime/JavaScript/src/antlr4/dfa/DFAState.js | 6 ------ 1 file changed, 6 deletions(-) diff --git a/runtime/JavaScript/src/antlr4/dfa/DFAState.js b/runtime/JavaScript/src/antlr4/dfa/DFAState.js index e597a54c3..b80df0365 100644 --- a/runtime/JavaScript/src/antlr4/dfa/DFAState.js +++ b/runtime/JavaScript/src/antlr4/dfa/DFAState.js @@ -139,12 +139,6 @@ DFAState.prototype.toString = function() { DFAState.prototype.hashCode = function() { var hash = new Hash(); hash.update(this.configs); - if(this.isAcceptState) { - if (this.predicates !== null) - hash.update(this.predicates); - else - hash.update(this.prediction); - } return hash.finish(); }; From badee1ffe11673f72d091b55275a324e9920c80c Mon Sep 17 00:00:00 2001 From: Eric Vergnaud Date: Sat, 24 Aug 2019 01:44:53 +0800 Subject: [PATCH 03/33] fix minor issue in deserializer --- runtime/JavaScript/src/antlr4/atn/ATNDeserializer.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/JavaScript/src/antlr4/atn/ATNDeserializer.js b/runtime/JavaScript/src/antlr4/atn/ATNDeserializer.js index 3d71d4242..295c07924 100644 --- a/runtime/JavaScript/src/antlr4/atn/ATNDeserializer.js +++ b/runtime/JavaScript/src/antlr4/atn/ATNDeserializer.js @@ -138,7 +138,7 @@ ATNDeserializer.prototype.deserialize = function(data) { ATNDeserializer.prototype.reset = function(data) { var adjust = function(c) { var v = c.charCodeAt(0); - return v>1 ? v-2 : v + 65533; + return v>1 ? v-2 : v + 65534; }; var temp = data.split("").map(adjust); // don't adjust the first value since that's the version number From 165dfa2b705d173ed833acaf5413295990c0d721 Mon Sep 17 00:00:00 2001 From: Eric Vergnaud Date: Sat, 24 Aug 2019 01:45:31 +0800 Subject: [PATCH 04/33] use same hash code whether readOnly or not --- runtime/JavaScript/src/antlr4/atn/ATNConfigSet.js | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/runtime/JavaScript/src/antlr4/atn/ATNConfigSet.js b/runtime/JavaScript/src/antlr4/atn/ATNConfigSet.js index 31b249d47..5a45f797e 100644 --- a/runtime/JavaScript/src/antlr4/atn/ATNConfigSet.js +++ b/runtime/JavaScript/src/antlr4/atn/ATNConfigSet.js @@ -175,7 +175,7 @@ ATNConfigSet.prototype.equals = function(other) { ATNConfigSet.prototype.hashCode = function() { var hash = new Hash(); - this.updateHashCode(hash); + hash.update(this.configs); return hash.finish(); }; @@ -183,13 +183,11 @@ ATNConfigSet.prototype.hashCode = function() { ATNConfigSet.prototype.updateHashCode = function(hash) { if (this.readOnly) { if (this.cachedHashCode === -1) { - var hash = new Hash(); - hash.update(this.configs); - this.cachedHashCode = hash.finish(); + this.cachedHashCode = this.hashCode(); } hash.update(this.cachedHashCode); } else { - hash.update(this.configs); + hash.update(this.hashCode()); } }; From 3e258c5d9d3ed66bd52303ec5f18933f1b76769a Mon Sep 17 00:00:00 2001 From: Eric Vergnaud Date: Sat, 24 Aug 2019 01:46:11 +0800 Subject: [PATCH 05/33] avoid hashCode == 0 --- runtime/JavaScript/src/antlr4/PredictionContext.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/runtime/JavaScript/src/antlr4/PredictionContext.js b/runtime/JavaScript/src/antlr4/PredictionContext.js index e69cdea37..8b2e2ece0 100644 --- a/runtime/JavaScript/src/antlr4/PredictionContext.js +++ b/runtime/JavaScript/src/antlr4/PredictionContext.js @@ -111,11 +111,13 @@ Object.defineProperty(PredictionContextCache.prototype, "length", { function SingletonPredictionContext(parent, returnState) { var hashCode = 0; + var hash = new Hash(); if(parent !== null) { - var hash = new Hash(); hash.update(parent, returnState); - hashCode = hash.finish(); + } else { + hash.update(1); } + hashCode = hash.finish(); PredictionContext.call(this, hashCode); this.parentCtx = parent; this.returnState = returnState; From 56eb0a3fab8f40741d25ca426d10e4899318292b Mon Sep 17 00:00:00 2001 From: Eric Vergnaud Date: Sat, 24 Aug 2019 01:47:12 +0800 Subject: [PATCH 06/33] fix 2 erroneous calls, thanks @akaJes --- runtime/JavaScript/src/antlr4/Utils.js | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/runtime/JavaScript/src/antlr4/Utils.js b/runtime/JavaScript/src/antlr4/Utils.js index 2cb939a66..9dad93c18 100644 --- a/runtime/JavaScript/src/antlr4/Utils.js +++ b/runtime/JavaScript/src/antlr4/Utils.js @@ -339,7 +339,7 @@ Hash.prototype.update = function () { if (value == null) continue; if(Array.isArray(value)) - this.update.apply(value); + this.update.apply(this, value); else { var k = 0; switch (typeof(value)) { @@ -354,7 +354,10 @@ Hash.prototype.update = function () { k = value.hashCode(); break; default: - value.updateHashCode(this); + if(value.updateHashCode) + value.updateHashCode(this); + else + console.log("No updateHashCode for " + value.toString()) continue; } k = k * 0xCC9E2D51; @@ -367,7 +370,7 @@ Hash.prototype.update = function () { this.hash = hash; } } -} +}; Hash.prototype.finish = function () { var hash = this.hash ^ (this.count * 4); @@ -377,11 +380,11 @@ Hash.prototype.finish = function () { hash = hash * 0xC2B2AE35; hash = hash ^ (hash >>> 16); return hash; -} +}; function hashStuff() { var hash = new Hash(); - hash.update.apply(arguments); + hash.update.apply(hash, arguments); return hash.finish(); } From 0de9612e5dc78874b5a6aa8183714a48d52fa70b Mon Sep 17 00:00:00 2001 From: Eric Vergnaud Date: Sat, 24 Aug 2019 02:10:12 +0800 Subject: [PATCH 07/33] adding original contributor --- contributors.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/contributors.txt b/contributors.txt index d40bacd5f..8fd2d2fb8 100644 --- a/contributors.txt +++ b/contributors.txt @@ -221,3 +221,4 @@ YYYY/MM/DD, github id, Full name, email 2019/07/11, olowo726, Olof Wolgast, olof@baah.se 2019/07/16, abhijithneilabraham, Abhijith Neil Abraham, abhijithneilabrahampk@gmail.com 2019/07/26, Braavos96, Eric Hettiaratchi, erichettiaratchi@gmail.com +2019/08/23, akaJes, Oleksandr Mamchyts, akaJes@gmail.com \ No newline at end of file From ff1283affb4df5d5192aa53aee395643b874a57a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Henrique?= Date: Tue, 3 Sep 2019 19:21:42 -0300 Subject: [PATCH 08/33] General XPath fixes for the Python3 runtime --- contributors.txt | 1 + runtime/Python3/src/antlr4/xpath/XPath.py | 117 +++++++++++----------- 2 files changed, 62 insertions(+), 56 deletions(-) diff --git a/contributors.txt b/contributors.txt index d40bacd5f..55687a831 100644 --- a/contributors.txt +++ b/contributors.txt @@ -221,3 +221,4 @@ YYYY/MM/DD, github id, Full name, email 2019/07/11, olowo726, Olof Wolgast, olof@baah.se 2019/07/16, abhijithneilabraham, Abhijith Neil Abraham, abhijithneilabrahampk@gmail.com 2019/07/26, Braavos96, Eric Hettiaratchi, erichettiaratchi@gmail.com +2019/09/03, João Henrique, johnnyonflame@hotmail.com diff --git a/runtime/Python3/src/antlr4/xpath/XPath.py b/runtime/Python3/src/antlr4/xpath/XPath.py index c49e3ba94..dcffad518 100644 --- a/runtime/Python3/src/antlr4/xpath/XPath.py +++ b/runtime/Python3/src/antlr4/xpath/XPath.py @@ -47,7 +47,7 @@ #

# Whitespace is not allowed.

# -from antlr4 import CommonTokenStream, DFA, PredictionContextCache, Lexer, LexerATNSimulator +from antlr4 import CommonTokenStream, DFA, PredictionContextCache, Lexer, LexerATNSimulator, ParserRuleContext, TerminalNode from antlr4.InputStream import InputStream from antlr4.Parser import Parser from antlr4.RuleContext import RuleContext @@ -134,7 +134,7 @@ class XPathLexer(Lexer): if _action is not None: _action(localctx, actionIndex) else: - raise Exception("No registered action for:" + str(ruleIndex)) + raise Exception("No registered action for: %d" % ruleIndex) def ID_action(self, localctx:RuleContext , actionIndex:int): if actionIndex == 0: @@ -166,40 +166,40 @@ class XPath(object): try: tokenStream.fill() except LexerNoViableAltException as e: - pos = lexer.getColumn() - msg = "Invalid tokens or characters at index " + str(pos) + " in path '" + path + "'" + pos = lexer.column + msg = "Invalid tokens or characters at index %d in path '%s'" % (pos, path) raise Exception(msg, e) - tokens = tokenStream.getTokens() + tokens = iter(tokenStream.tokens) elements = list() - n = len(tokens) - i=0 - while i < n : - el = tokens[i] - next = None + for el in tokens: + invert = False + anywhere = False + # Check for path separators, if none assume root if el.type in [XPathLexer.ROOT, XPathLexer.ANYWHERE]: - anywhere = el.type == XPathLexer.ANYWHERE - i += 1 - next = tokens[i] - invert = next.type==XPathLexer.BANG - if invert: - i += 1 - next = tokens[i] - pathElement = self.getXPathElement(next, anywhere) - pathElement.invert = invert - elements.append(pathElement) - i += 1 - - elif el.type in [XPathLexer.TOKEN_REF, XPathLexer.RULE_REF, XPathLexer.WILDCARD] : - elements.append( self.getXPathElement(el, False) ) - i += 1 - - elif el.type==Token.EOF : - break - + anywhere = el.type == XPathLexer.ANYWHERE + next_el = next(tokens, None) + if not next_el: + raise Exception('Missing element after %s' % el.getText()) + else: + el = next_el + # Check for bangs + if el.type == XPathLexer.BANG: + invert = True + next_el = next(tokens, None) + if not next_el: + raise Exception('Missing element after %s' % el.getText()) + else: + el = next_el + # Add searched element + if el.type in [XPathLexer.TOKEN_REF, XPathLexer.RULE_REF, XPathLexer.WILDCARD]: + element = self.getXPathElement(el, anywhere) + element.invert = invert + elements.append(element) + elif el.type==Token.EOF: + break else: - raise Exception("Unknown path element " + str(el)) - + raise Exception("Unknown path element %s" % lexer.symbolicNames[el.type]) return elements # @@ -210,24 +210,32 @@ class XPath(object): def getXPathElement(self, wordToken:Token, anywhere:bool): if wordToken.type==Token.EOF: raise Exception("Missing path element at end of path") + word = wordToken.text - ttype = self.parser.getTokenType(word) - ruleIndex = self.parser.getRuleIndex(word) - if wordToken.type==XPathLexer.WILDCARD : - return XPathWildcardAnywhereElement() if anywhere else XPathWildcardElement() elif wordToken.type in [XPathLexer.TOKEN_REF, XPathLexer.STRING]: + tsource = self.parser.getTokenStream().tokenSource - if ttype==Token.INVALID_TYPE: - raise Exception( word + " at index " + str(wordToken.startIndex) + " isn't a valid token name") + ttype = litType = None + if wordToken.type == XPathLexer.TOKEN_REF: + ttype = (tsource.ruleNames.index(word) + 1) if word in tsource.ruleNames else None + else: + litType = tsource.literalNames.index(word) if word in tsource.literalNames else None + + # Decide which one is it + ttype = ttype or litType + + if not ttype: + raise Exception("%s at index %d isn't a valid token name" % (word, wordToken.tokenIndex)) return XPathTokenAnywhereElement(word, ttype) if anywhere else XPathTokenElement(word, ttype) else: + ruleIndex = self.parser.ruleNames.index(word) if word in self.parser.ruleNames else None - if ruleIndex==-1: - raise Exception( word + " at index " + str(wordToken.getStartIndex()) + " isn't a valid rule name") + if not ruleIndex: + raise Exception("%s at index %d isn't a valid rule name" % (word, wordToken.tokenIndex)) return XPathRuleAnywhereElement(word, ruleIndex) if anywhere else XPathRuleElement(word, ruleIndex) @@ -246,18 +254,16 @@ class XPath(object): dummyRoot.children = [t] # don't set t's parent. work = [dummyRoot] - - for i in range(0, len(self.elements)): - next = set() + for element in self.elements: + work_next = list() for node in work: - if len( node.children) > 0 : + if not isinstance(node, TerminalNode) and node.children: # only try to match next element if it has children # e.g., //func/*/stat might have a token node for which # we can't go looking for stat nodes. - matching = self.elements[i].evaluate(node) - next |= matching - i += 1 - work = next + matching = element.evaluate(node) + work_next.extend(matching) + work = work_next return work @@ -283,8 +289,8 @@ class XPathRuleAnywhereElement(XPathElement): self.ruleIndex = ruleIndex def evaluate(self, t:ParseTree): - return Trees.findAllRuleNodes(t, self.ruleIndex) - + # return all ParserRuleContext descendants of t that match ruleIndex (or do not match if inverted) + return filter(lambda c: isinstance(c, ParserRuleContext) and (self.invert ^ (c.getRuleIndex() == self.ruleIndex)), Trees.descendants(t)) class XPathRuleElement(XPathElement): @@ -293,9 +299,8 @@ class XPathRuleElement(XPathElement): self.ruleIndex = ruleIndex def evaluate(self, t:ParseTree): - # return all children of t that match nodeName - return [c for c in Trees.getChildren(t) if isinstance(c, ParserRuleContext) and (c.ruleIndex == self.ruleIndex) == (not self.invert)] - + # return all ParserRuleContext children of t that match ruleIndex (or do not match if inverted) + return filter(lambda c: isinstance(c, ParserRuleContext) and (self.invert ^ (c.getRuleIndex() == self.ruleIndex)), Trees.getChildren(t)) class XPathTokenAnywhereElement(XPathElement): @@ -304,8 +309,8 @@ class XPathTokenAnywhereElement(XPathElement): self.tokenType = tokenType def evaluate(self, t:ParseTree): - return Trees.findAllTokenNodes(t, self.tokenType) - + # return all TerminalNode descendants of t that match tokenType (or do not match if inverted) + return filter(lambda c: isinstance(c, TerminalNode) and (self.invert ^ (c.symbol.type == self.tokenType)), Trees.descendants(t)) class XPathTokenElement(XPathElement): @@ -314,8 +319,8 @@ class XPathTokenElement(XPathElement): self.tokenType = tokenType def evaluate(self, t:ParseTree): - # return all children of t that match nodeName - return [c for c in Trees.getChildren(t) if isinstance(c, TerminalNode) and (c.symbol.type == self.tokenType) == (not self.invert)] + # return all TerminalNode children of t that match tokenType (or do not match if inverted) + return filter(lambda c: isinstance(c, TerminalNode) and (self.invert ^ (c.symbol.type == self.tokenType)), Trees.getChildren(t)) class XPathWildcardAnywhereElement(XPathElement): From 4c2f091e8c9f8e1d40686d7e84453027cc55fff1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Henrique?= Date: Wed, 4 Sep 2019 14:34:19 -0300 Subject: [PATCH 09/33] Style touch-ups on Python3 XPath implementation --- runtime/Python3/src/antlr4/xpath/XPath.py | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/runtime/Python3/src/antlr4/xpath/XPath.py b/runtime/Python3/src/antlr4/xpath/XPath.py index dcffad518..4e8670ff1 100644 --- a/runtime/Python3/src/antlr4/xpath/XPath.py +++ b/runtime/Python3/src/antlr4/xpath/XPath.py @@ -218,23 +218,22 @@ class XPath(object): elif wordToken.type in [XPathLexer.TOKEN_REF, XPathLexer.STRING]: tsource = self.parser.getTokenStream().tokenSource - ttype = litType = None + ttype = -1 if wordToken.type == XPathLexer.TOKEN_REF: - ttype = (tsource.ruleNames.index(word) + 1) if word in tsource.ruleNames else None + if word in tsource.ruleNames: + ttype = tsource.ruleNames.index(word) + 1 else: - litType = tsource.literalNames.index(word) if word in tsource.literalNames else None + if word in tsource.literalNames: + ttype = tsource.literalNames.index(word) - # Decide which one is it - ttype = ttype or litType - - if not ttype: + if ttype == -1: raise Exception("%s at index %d isn't a valid token name" % (word, wordToken.tokenIndex)) return XPathTokenAnywhereElement(word, ttype) if anywhere else XPathTokenElement(word, ttype) else: - ruleIndex = self.parser.ruleNames.index(word) if word in self.parser.ruleNames else None + ruleIndex = self.parser.ruleNames.index(word) if word in self.parser.ruleNames else -1 - if not ruleIndex: + if ruleIndex == -1: raise Exception("%s at index %d isn't a valid rule name" % (word, wordToken.tokenIndex)) return XPathRuleAnywhereElement(word, ruleIndex) if anywhere else XPathRuleElement(word, ruleIndex) From ae2a689a68408b2f76e7c1c7c3f51731fc293ffa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Henrique?= Date: Wed, 4 Sep 2019 15:33:24 -0300 Subject: [PATCH 10/33] Fixed missing XPathLexer.STRING case --- runtime/Python3/src/antlr4/xpath/XPath.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/Python3/src/antlr4/xpath/XPath.py b/runtime/Python3/src/antlr4/xpath/XPath.py index 4e8670ff1..07fcd0b54 100644 --- a/runtime/Python3/src/antlr4/xpath/XPath.py +++ b/runtime/Python3/src/antlr4/xpath/XPath.py @@ -192,7 +192,7 @@ class XPath(object): else: el = next_el # Add searched element - if el.type in [XPathLexer.TOKEN_REF, XPathLexer.RULE_REF, XPathLexer.WILDCARD]: + if el.type in [XPathLexer.TOKEN_REF, XPathLexer.RULE_REF, XPathLexer.WILDCARD, XPathLexer.STRING]: element = self.getXPathElement(el, anywhere) element.invert = invert elements.append(element) From f15a9f76287ea3083488672b17535ea63470f2ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Henrique?= Date: Wed, 4 Sep 2019 15:53:02 -0300 Subject: [PATCH 11/33] Prevent XPath from returning the same node multiple times in Python3 --- runtime/Python3/src/antlr4/xpath/XPath.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/runtime/Python3/src/antlr4/xpath/XPath.py b/runtime/Python3/src/antlr4/xpath/XPath.py index 07fcd0b54..4d3a4f56f 100644 --- a/runtime/Python3/src/antlr4/xpath/XPath.py +++ b/runtime/Python3/src/antlr4/xpath/XPath.py @@ -261,6 +261,11 @@ class XPath(object): # e.g., //func/*/stat might have a token node for which # we can't go looking for stat nodes. matching = element.evaluate(node) + + # See issue antlr#370 - Prevents XPath from returning the + # same node multiple times + matching = filter(lambda m: m not in work_next, matching) + work_next.extend(matching) work = work_next From 8da2ce3044cf9411b83e04812d0bd76da0b2680c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Henrique?= Date: Wed, 4 Sep 2019 15:59:12 -0300 Subject: [PATCH 12/33] Added XPath test on Python3 target --- runtime/Python3/test/expr/Expr.g4 | 31 ++ runtime/Python3/test/expr/ExprLexer.py | 94 ++++ runtime/Python3/test/expr/ExprParser.py | 658 ++++++++++++++++++++++++ runtime/Python3/test/run.py | 1 + runtime/Python3/test/xpathtest.py | 89 ++++ 5 files changed, 873 insertions(+) create mode 100644 runtime/Python3/test/expr/Expr.g4 create mode 100644 runtime/Python3/test/expr/ExprLexer.py create mode 100644 runtime/Python3/test/expr/ExprParser.py create mode 100644 runtime/Python3/test/xpathtest.py diff --git a/runtime/Python3/test/expr/Expr.g4 b/runtime/Python3/test/expr/Expr.g4 new file mode 100644 index 000000000..662079641 --- /dev/null +++ b/runtime/Python3/test/expr/Expr.g4 @@ -0,0 +1,31 @@ +// Taken from "tool-testsuite/test/org/antlr/v4/test/tool/TestXPath.java" +// Builds ExprLexer.py and ExprParser.py + +grammar Expr; +prog: func+ ; +func: 'def' ID '(' arg (',' arg)* ')' body ; +body: '{' stat+ '}' ; +arg : ID ; +stat: expr ';' # printExpr + | ID '=' expr ';' # assign + | 'return' expr ';' # ret + | ';' # blank + ; +expr: expr ('*'|'/') expr # MulDiv + | expr ('+'|'-') expr # AddSub + | primary # prim + ; +primary + : INT # int + | ID # id + | '(' expr ')' # parens + ; +MUL : '*' ; // assigns token name to '*' used above in grammar +DIV : '/' ; +ADD : '+' ; +SUB : '-' ; +RETURN : 'return' ; +ID : [a-zA-Z]+ ; // match identifiers +INT : [0-9]+ ; // match integers +NEWLINE:'\r'? '\n' -> skip; // return newlines to parser (is end-statement signal) +WS : [ \t]+ -> skip ; // toss out whitespace \ No newline at end of file diff --git a/runtime/Python3/test/expr/ExprLexer.py b/runtime/Python3/test/expr/ExprLexer.py new file mode 100644 index 000000000..e338b0b9e --- /dev/null +++ b/runtime/Python3/test/expr/ExprLexer.py @@ -0,0 +1,94 @@ +# Generated from expr/Expr.g4 by ANTLR 4.7.2 +from antlr4 import * +from io import StringIO +from typing.io import TextIO +import sys + + +def serializedATN(): + with StringIO() as buf: + buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\23") + buf.write("^\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7") + buf.write("\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r\4\16") + buf.write("\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22\3\2\3\2") + buf.write("\3\2\3\2\3\3\3\3\3\4\3\4\3\5\3\5\3\6\3\6\3\7\3\7\3\b\3") + buf.write("\b\3\t\3\t\3\n\3\n\3\13\3\13\3\f\3\f\3\r\3\r\3\16\3\16") + buf.write("\3\16\3\16\3\16\3\16\3\16\3\17\6\17H\n\17\r\17\16\17I") + buf.write("\3\20\6\20M\n\20\r\20\16\20N\3\21\5\21R\n\21\3\21\3\21") + buf.write("\3\21\3\21\3\22\6\22Y\n\22\r\22\16\22Z\3\22\3\22\2\2\23") + buf.write("\3\3\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31") + buf.write("\16\33\17\35\20\37\21!\22#\23\3\2\5\4\2C\\c|\3\2\62;\4") + buf.write("\2\13\13\"\"\2a\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3\2\2\2\2") + buf.write("\t\3\2\2\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21") + buf.write("\3\2\2\2\2\23\3\2\2\2\2\25\3\2\2\2\2\27\3\2\2\2\2\31\3") + buf.write("\2\2\2\2\33\3\2\2\2\2\35\3\2\2\2\2\37\3\2\2\2\2!\3\2\2") + buf.write("\2\2#\3\2\2\2\3%\3\2\2\2\5)\3\2\2\2\7+\3\2\2\2\t-\3\2") + buf.write("\2\2\13/\3\2\2\2\r\61\3\2\2\2\17\63\3\2\2\2\21\65\3\2") + buf.write("\2\2\23\67\3\2\2\2\259\3\2\2\2\27;\3\2\2\2\31=\3\2\2\2") + buf.write("\33?\3\2\2\2\35G\3\2\2\2\37L\3\2\2\2!Q\3\2\2\2#X\3\2\2") + buf.write("\2%&\7f\2\2&\'\7g\2\2\'(\7h\2\2(\4\3\2\2\2)*\7*\2\2*\6") + buf.write("\3\2\2\2+,\7.\2\2,\b\3\2\2\2-.\7+\2\2.\n\3\2\2\2/\60\7") + buf.write("}\2\2\60\f\3\2\2\2\61\62\7\177\2\2\62\16\3\2\2\2\63\64") + buf.write("\7=\2\2\64\20\3\2\2\2\65\66\7?\2\2\66\22\3\2\2\2\678\7") + buf.write(",\2\28\24\3\2\2\29:\7\61\2\2:\26\3\2\2\2;<\7-\2\2<\30") + buf.write("\3\2\2\2=>\7/\2\2>\32\3\2\2\2?@\7t\2\2@A\7g\2\2AB\7v\2") + buf.write("\2BC\7w\2\2CD\7t\2\2DE\7p\2\2E\34\3\2\2\2FH\t\2\2\2GF") + buf.write("\3\2\2\2HI\3\2\2\2IG\3\2\2\2IJ\3\2\2\2J\36\3\2\2\2KM\t") + buf.write("\3\2\2LK\3\2\2\2MN\3\2\2\2NL\3\2\2\2NO\3\2\2\2O \3\2\2") + buf.write("\2PR\7\17\2\2QP\3\2\2\2QR\3\2\2\2RS\3\2\2\2ST\7\f\2\2") + buf.write("TU\3\2\2\2UV\b\21\2\2V\"\3\2\2\2WY\t\4\2\2XW\3\2\2\2Y") + buf.write("Z\3\2\2\2ZX\3\2\2\2Z[\3\2\2\2[\\\3\2\2\2\\]\b\22\2\2]") + buf.write("$\3\2\2\2\7\2INQZ\3\b\2\2") + return buf.getvalue() + + +class ExprLexer(Lexer): + + atn = ATNDeserializer().deserialize(serializedATN()) + + decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] + + T__0 = 1 + T__1 = 2 + T__2 = 3 + T__3 = 4 + T__4 = 5 + T__5 = 6 + T__6 = 7 + T__7 = 8 + MUL = 9 + DIV = 10 + ADD = 11 + SUB = 12 + RETURN = 13 + ID = 14 + INT = 15 + NEWLINE = 16 + WS = 17 + + channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ] + + modeNames = [ "DEFAULT_MODE" ] + + literalNames = [ "", + "'def'", "'('", "','", "')'", "'{'", "'}'", "';'", "'='", "'*'", + "'/'", "'+'", "'-'", "'return'" ] + + symbolicNames = [ "", + "MUL", "DIV", "ADD", "SUB", "RETURN", "ID", "INT", "NEWLINE", + "WS" ] + + ruleNames = [ "T__0", "T__1", "T__2", "T__3", "T__4", "T__5", "T__6", + "T__7", "MUL", "DIV", "ADD", "SUB", "RETURN", "ID", "INT", + "NEWLINE", "WS" ] + + grammarFileName = "Expr.g4" + + def __init__(self, input=None, output:TextIO = sys.stdout): + super().__init__(input, output) + self.checkVersion("4.7.2") + self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache()) + self._actions = None + self._predicates = None + + diff --git a/runtime/Python3/test/expr/ExprParser.py b/runtime/Python3/test/expr/ExprParser.py new file mode 100644 index 000000000..598c778d1 --- /dev/null +++ b/runtime/Python3/test/expr/ExprParser.py @@ -0,0 +1,658 @@ +# Generated from expr/Expr.g4 by ANTLR 4.7.2 +# encoding: utf-8 +from antlr4 import * +from io import StringIO +from typing.io import TextIO +import sys + +def serializedATN(): + with StringIO() as buf: + buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3\23") + buf.write("S\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b") + buf.write("\t\b\3\2\6\2\22\n\2\r\2\16\2\23\3\3\3\3\3\3\3\3\3\3\3") + buf.write("\3\7\3\34\n\3\f\3\16\3\37\13\3\3\3\3\3\3\3\3\4\3\4\6\4") + buf.write("&\n\4\r\4\16\4\'\3\4\3\4\3\5\3\5\3\6\3\6\3\6\3\6\3\6\3") + buf.write("\6\3\6\3\6\3\6\3\6\3\6\3\6\3\6\5\6;\n\6\3\7\3\7\3\7\3") + buf.write("\7\3\7\3\7\3\7\3\7\3\7\7\7F\n\7\f\7\16\7I\13\7\3\b\3\b") + buf.write("\3\b\3\b\3\b\3\b\5\bQ\n\b\3\b\2\3\f\t\2\4\6\b\n\f\16\2") + buf.write("\4\3\2\13\f\3\2\r\16\2U\2\21\3\2\2\2\4\25\3\2\2\2\6#\3") + buf.write("\2\2\2\b+\3\2\2\2\n:\3\2\2\2\f<\3\2\2\2\16P\3\2\2\2\20") + buf.write("\22\5\4\3\2\21\20\3\2\2\2\22\23\3\2\2\2\23\21\3\2\2\2") + buf.write("\23\24\3\2\2\2\24\3\3\2\2\2\25\26\7\3\2\2\26\27\7\20\2") + buf.write("\2\27\30\7\4\2\2\30\35\5\b\5\2\31\32\7\5\2\2\32\34\5\b") + buf.write("\5\2\33\31\3\2\2\2\34\37\3\2\2\2\35\33\3\2\2\2\35\36\3") + buf.write("\2\2\2\36 \3\2\2\2\37\35\3\2\2\2 !\7\6\2\2!\"\5\6\4\2") + buf.write("\"\5\3\2\2\2#%\7\7\2\2$&\5\n\6\2%$\3\2\2\2&\'\3\2\2\2") + buf.write("\'%\3\2\2\2\'(\3\2\2\2()\3\2\2\2)*\7\b\2\2*\7\3\2\2\2") + buf.write("+,\7\20\2\2,\t\3\2\2\2-.\5\f\7\2./\7\t\2\2/;\3\2\2\2\60") + buf.write("\61\7\20\2\2\61\62\7\n\2\2\62\63\5\f\7\2\63\64\7\t\2\2") + buf.write("\64;\3\2\2\2\65\66\7\17\2\2\66\67\5\f\7\2\678\7\t\2\2") + buf.write("8;\3\2\2\29;\7\t\2\2:-\3\2\2\2:\60\3\2\2\2:\65\3\2\2\2") + buf.write(":9\3\2\2\2;\13\3\2\2\2<=\b\7\1\2=>\5\16\b\2>G\3\2\2\2") + buf.write("?@\f\5\2\2@A\t\2\2\2AF\5\f\7\6BC\f\4\2\2CD\t\3\2\2DF\5") + buf.write("\f\7\5E?\3\2\2\2EB\3\2\2\2FI\3\2\2\2GE\3\2\2\2GH\3\2\2") + buf.write("\2H\r\3\2\2\2IG\3\2\2\2JQ\7\21\2\2KQ\7\20\2\2LM\7\4\2") + buf.write("\2MN\5\f\7\2NO\7\6\2\2OQ\3\2\2\2PJ\3\2\2\2PK\3\2\2\2P") + buf.write("L\3\2\2\2Q\17\3\2\2\2\t\23\35\':EGP") + return buf.getvalue() + + +class ExprParser ( Parser ): + + grammarFileName = "Expr.g4" + + atn = ATNDeserializer().deserialize(serializedATN()) + + decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] + + sharedContextCache = PredictionContextCache() + + literalNames = [ "", "'def'", "'('", "','", "')'", "'{'", "'}'", + "';'", "'='", "'*'", "'/'", "'+'", "'-'", "'return'" ] + + symbolicNames = [ "", "", "", "", + "", "", "", "", + "", "MUL", "DIV", "ADD", "SUB", "RETURN", + "ID", "INT", "NEWLINE", "WS" ] + + RULE_prog = 0 + RULE_func = 1 + RULE_body = 2 + RULE_arg = 3 + RULE_stat = 4 + RULE_expr = 5 + RULE_primary = 6 + + ruleNames = [ "prog", "func", "body", "arg", "stat", "expr", "primary" ] + + EOF = Token.EOF + T__0=1 + T__1=2 + T__2=3 + T__3=4 + T__4=5 + T__5=6 + T__6=7 + T__7=8 + MUL=9 + DIV=10 + ADD=11 + SUB=12 + RETURN=13 + ID=14 + INT=15 + NEWLINE=16 + WS=17 + + def __init__(self, input:TokenStream, output:TextIO = sys.stdout): + super().__init__(input, output) + self.checkVersion("4.7.2") + self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache) + self._predicates = None + + + + class ProgContext(ParserRuleContext): + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def func(self, i:int=None): + if i is None: + return self.getTypedRuleContexts(ExprParser.FuncContext) + else: + return self.getTypedRuleContext(ExprParser.FuncContext,i) + + + def getRuleIndex(self): + return ExprParser.RULE_prog + + + + + def prog(self): + + localctx = ExprParser.ProgContext(self, self._ctx, self.state) + self.enterRule(localctx, 0, self.RULE_prog) + self._la = 0 # Token type + try: + self.enterOuterAlt(localctx, 1) + self.state = 15 + self._errHandler.sync(self) + _la = self._input.LA(1) + while True: + self.state = 14 + self.func() + self.state = 17 + self._errHandler.sync(self) + _la = self._input.LA(1) + if not (_la==ExprParser.T__0): + break + + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + class FuncContext(ParserRuleContext): + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def ID(self): + return self.getToken(ExprParser.ID, 0) + + def arg(self, i:int=None): + if i is None: + return self.getTypedRuleContexts(ExprParser.ArgContext) + else: + return self.getTypedRuleContext(ExprParser.ArgContext,i) + + + def body(self): + return self.getTypedRuleContext(ExprParser.BodyContext,0) + + + def getRuleIndex(self): + return ExprParser.RULE_func + + + + + def func(self): + + localctx = ExprParser.FuncContext(self, self._ctx, self.state) + self.enterRule(localctx, 2, self.RULE_func) + self._la = 0 # Token type + try: + self.enterOuterAlt(localctx, 1) + self.state = 19 + self.match(ExprParser.T__0) + self.state = 20 + self.match(ExprParser.ID) + self.state = 21 + self.match(ExprParser.T__1) + self.state = 22 + self.arg() + self.state = 27 + self._errHandler.sync(self) + _la = self._input.LA(1) + while _la==ExprParser.T__2: + self.state = 23 + self.match(ExprParser.T__2) + self.state = 24 + self.arg() + self.state = 29 + self._errHandler.sync(self) + _la = self._input.LA(1) + + self.state = 30 + self.match(ExprParser.T__3) + self.state = 31 + self.body() + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + class BodyContext(ParserRuleContext): + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def stat(self, i:int=None): + if i is None: + return self.getTypedRuleContexts(ExprParser.StatContext) + else: + return self.getTypedRuleContext(ExprParser.StatContext,i) + + + def getRuleIndex(self): + return ExprParser.RULE_body + + + + + def body(self): + + localctx = ExprParser.BodyContext(self, self._ctx, self.state) + self.enterRule(localctx, 4, self.RULE_body) + self._la = 0 # Token type + try: + self.enterOuterAlt(localctx, 1) + self.state = 33 + self.match(ExprParser.T__4) + self.state = 35 + self._errHandler.sync(self) + _la = self._input.LA(1) + while True: + self.state = 34 + self.stat() + self.state = 37 + self._errHandler.sync(self) + _la = self._input.LA(1) + if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << ExprParser.T__1) | (1 << ExprParser.T__6) | (1 << ExprParser.RETURN) | (1 << ExprParser.ID) | (1 << ExprParser.INT))) != 0)): + break + + self.state = 39 + self.match(ExprParser.T__5) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + class ArgContext(ParserRuleContext): + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + def ID(self): + return self.getToken(ExprParser.ID, 0) + + def getRuleIndex(self): + return ExprParser.RULE_arg + + + + + def arg(self): + + localctx = ExprParser.ArgContext(self, self._ctx, self.state) + self.enterRule(localctx, 6, self.RULE_arg) + try: + self.enterOuterAlt(localctx, 1) + self.state = 41 + self.match(ExprParser.ID) + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + class StatContext(ParserRuleContext): + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + + def getRuleIndex(self): + return ExprParser.RULE_stat + + + def copyFrom(self, ctx:ParserRuleContext): + super().copyFrom(ctx) + + + + class RetContext(StatContext): + + def __init__(self, parser, ctx:ParserRuleContext): # actually a ExprParser.StatContext + super().__init__(parser) + self.copyFrom(ctx) + + def RETURN(self): + return self.getToken(ExprParser.RETURN, 0) + def expr(self): + return self.getTypedRuleContext(ExprParser.ExprContext,0) + + + + class BlankContext(StatContext): + + def __init__(self, parser, ctx:ParserRuleContext): # actually a ExprParser.StatContext + super().__init__(parser) + self.copyFrom(ctx) + + + + class PrintExprContext(StatContext): + + def __init__(self, parser, ctx:ParserRuleContext): # actually a ExprParser.StatContext + super().__init__(parser) + self.copyFrom(ctx) + + def expr(self): + return self.getTypedRuleContext(ExprParser.ExprContext,0) + + + + class AssignContext(StatContext): + + def __init__(self, parser, ctx:ParserRuleContext): # actually a ExprParser.StatContext + super().__init__(parser) + self.copyFrom(ctx) + + def ID(self): + return self.getToken(ExprParser.ID, 0) + def expr(self): + return self.getTypedRuleContext(ExprParser.ExprContext,0) + + + + + def stat(self): + + localctx = ExprParser.StatContext(self, self._ctx, self.state) + self.enterRule(localctx, 8, self.RULE_stat) + try: + self.state = 56 + self._errHandler.sync(self) + la_ = self._interp.adaptivePredict(self._input,3,self._ctx) + if la_ == 1: + localctx = ExprParser.PrintExprContext(self, localctx) + self.enterOuterAlt(localctx, 1) + self.state = 43 + self.expr(0) + self.state = 44 + self.match(ExprParser.T__6) + pass + + elif la_ == 2: + localctx = ExprParser.AssignContext(self, localctx) + self.enterOuterAlt(localctx, 2) + self.state = 46 + self.match(ExprParser.ID) + self.state = 47 + self.match(ExprParser.T__7) + self.state = 48 + self.expr(0) + self.state = 49 + self.match(ExprParser.T__6) + pass + + elif la_ == 3: + localctx = ExprParser.RetContext(self, localctx) + self.enterOuterAlt(localctx, 3) + self.state = 51 + self.match(ExprParser.RETURN) + self.state = 52 + self.expr(0) + self.state = 53 + self.match(ExprParser.T__6) + pass + + elif la_ == 4: + localctx = ExprParser.BlankContext(self, localctx) + self.enterOuterAlt(localctx, 4) + self.state = 55 + self.match(ExprParser.T__6) + pass + + + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + class ExprContext(ParserRuleContext): + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + + def getRuleIndex(self): + return ExprParser.RULE_expr + + + def copyFrom(self, ctx:ParserRuleContext): + super().copyFrom(ctx) + + + class PrimContext(ExprContext): + + def __init__(self, parser, ctx:ParserRuleContext): # actually a ExprParser.ExprContext + super().__init__(parser) + self.copyFrom(ctx) + + def primary(self): + return self.getTypedRuleContext(ExprParser.PrimaryContext,0) + + + + class MulDivContext(ExprContext): + + def __init__(self, parser, ctx:ParserRuleContext): # actually a ExprParser.ExprContext + super().__init__(parser) + self.copyFrom(ctx) + + def expr(self, i:int=None): + if i is None: + return self.getTypedRuleContexts(ExprParser.ExprContext) + else: + return self.getTypedRuleContext(ExprParser.ExprContext,i) + + def MUL(self): + return self.getToken(ExprParser.MUL, 0) + def DIV(self): + return self.getToken(ExprParser.DIV, 0) + + + class AddSubContext(ExprContext): + + def __init__(self, parser, ctx:ParserRuleContext): # actually a ExprParser.ExprContext + super().__init__(parser) + self.copyFrom(ctx) + + def expr(self, i:int=None): + if i is None: + return self.getTypedRuleContexts(ExprParser.ExprContext) + else: + return self.getTypedRuleContext(ExprParser.ExprContext,i) + + def ADD(self): + return self.getToken(ExprParser.ADD, 0) + def SUB(self): + return self.getToken(ExprParser.SUB, 0) + + + + def expr(self, _p:int=0): + _parentctx = self._ctx + _parentState = self.state + localctx = ExprParser.ExprContext(self, self._ctx, _parentState) + _prevctx = localctx + _startState = 10 + self.enterRecursionRule(localctx, 10, self.RULE_expr, _p) + self._la = 0 # Token type + try: + self.enterOuterAlt(localctx, 1) + localctx = ExprParser.PrimContext(self, localctx) + self._ctx = localctx + _prevctx = localctx + + self.state = 59 + self.primary() + self._ctx.stop = self._input.LT(-1) + self.state = 69 + self._errHandler.sync(self) + _alt = self._interp.adaptivePredict(self._input,5,self._ctx) + while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: + if _alt==1: + if self._parseListeners is not None: + self.triggerExitRuleEvent() + _prevctx = localctx + self.state = 67 + self._errHandler.sync(self) + la_ = self._interp.adaptivePredict(self._input,4,self._ctx) + if la_ == 1: + localctx = ExprParser.MulDivContext(self, ExprParser.ExprContext(self, _parentctx, _parentState)) + self.pushNewRecursionContext(localctx, _startState, self.RULE_expr) + self.state = 61 + if not self.precpred(self._ctx, 3): + from antlr4.error.Errors import FailedPredicateException + raise FailedPredicateException(self, "self.precpred(self._ctx, 3)") + self.state = 62 + _la = self._input.LA(1) + if not(_la==ExprParser.MUL or _la==ExprParser.DIV): + self._errHandler.recoverInline(self) + else: + self._errHandler.reportMatch(self) + self.consume() + self.state = 63 + self.expr(4) + pass + + elif la_ == 2: + localctx = ExprParser.AddSubContext(self, ExprParser.ExprContext(self, _parentctx, _parentState)) + self.pushNewRecursionContext(localctx, _startState, self.RULE_expr) + self.state = 64 + if not self.precpred(self._ctx, 2): + from antlr4.error.Errors import FailedPredicateException + raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") + self.state = 65 + _la = self._input.LA(1) + if not(_la==ExprParser.ADD or _la==ExprParser.SUB): + self._errHandler.recoverInline(self) + else: + self._errHandler.reportMatch(self) + self.consume() + self.state = 66 + self.expr(3) + pass + + + self.state = 71 + self._errHandler.sync(self) + _alt = self._interp.adaptivePredict(self._input,5,self._ctx) + + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.unrollRecursionContexts(_parentctx) + return localctx + + class PrimaryContext(ParserRuleContext): + + def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): + super().__init__(parent, invokingState) + self.parser = parser + + + def getRuleIndex(self): + return ExprParser.RULE_primary + + + def copyFrom(self, ctx:ParserRuleContext): + super().copyFrom(ctx) + + + + class ParensContext(PrimaryContext): + + def __init__(self, parser, ctx:ParserRuleContext): # actually a ExprParser.PrimaryContext + super().__init__(parser) + self.copyFrom(ctx) + + def expr(self): + return self.getTypedRuleContext(ExprParser.ExprContext,0) + + + + class IdContext(PrimaryContext): + + def __init__(self, parser, ctx:ParserRuleContext): # actually a ExprParser.PrimaryContext + super().__init__(parser) + self.copyFrom(ctx) + + def ID(self): + return self.getToken(ExprParser.ID, 0) + + + class IntContext(PrimaryContext): + + def __init__(self, parser, ctx:ParserRuleContext): # actually a ExprParser.PrimaryContext + super().__init__(parser) + self.copyFrom(ctx) + + def INT(self): + return self.getToken(ExprParser.INT, 0) + + + + def primary(self): + + localctx = ExprParser.PrimaryContext(self, self._ctx, self.state) + self.enterRule(localctx, 12, self.RULE_primary) + try: + self.state = 78 + self._errHandler.sync(self) + token = self._input.LA(1) + if token in [ExprParser.INT]: + localctx = ExprParser.IntContext(self, localctx) + self.enterOuterAlt(localctx, 1) + self.state = 72 + self.match(ExprParser.INT) + pass + elif token in [ExprParser.ID]: + localctx = ExprParser.IdContext(self, localctx) + self.enterOuterAlt(localctx, 2) + self.state = 73 + self.match(ExprParser.ID) + pass + elif token in [ExprParser.T__1]: + localctx = ExprParser.ParensContext(self, localctx) + self.enterOuterAlt(localctx, 3) + self.state = 74 + self.match(ExprParser.T__1) + self.state = 75 + self.expr(0) + self.state = 76 + self.match(ExprParser.T__3) + pass + else: + raise NoViableAltException(self) + + except RecognitionException as re: + localctx.exception = re + self._errHandler.reportError(self, re) + self._errHandler.recover(self, re) + finally: + self.exitRule() + return localctx + + + + def sempred(self, localctx:RuleContext, ruleIndex:int, predIndex:int): + if self._predicates == None: + self._predicates = dict() + self._predicates[5] = self.expr_sempred + pred = self._predicates.get(ruleIndex, None) + if pred is None: + raise Exception("No predicate with index:" + str(ruleIndex)) + else: + return pred(localctx, predIndex) + + def expr_sempred(self, localctx:ExprContext, predIndex:int): + if predIndex == 0: + return self.precpred(self._ctx, 3) + + + if predIndex == 1: + return self.precpred(self._ctx, 2) + + + + + diff --git a/runtime/Python3/test/run.py b/runtime/Python3/test/run.py index c9ae18877..5aad7896c 100644 --- a/runtime/Python3/test/run.py +++ b/runtime/Python3/test/run.py @@ -3,5 +3,6 @@ import os src_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'src') sys.path.insert(0,src_path) from TestTokenStreamRewriter import TestTokenStreamRewriter +from xpathtest import XPathTest import unittest unittest.main() \ No newline at end of file diff --git a/runtime/Python3/test/xpathtest.py b/runtime/Python3/test/xpathtest.py new file mode 100644 index 000000000..278bffe5b --- /dev/null +++ b/runtime/Python3/test/xpathtest.py @@ -0,0 +1,89 @@ +import antlr4 +from antlr4 import InputStream, CommonTokenStream, TerminalNode +from antlr4.xpath.XPath import XPath +import unittest +from expr.ExprParser import ExprParser +from expr.ExprLexer import ExprLexer + +def tokenToString(token, ruleNames): + if isinstance(token, TerminalNode): + return str(token) + else: + return ruleNames[token.getRuleIndex()] + +class XPathTest(unittest.TestCase): + def setUp(self): + self.input_stream = InputStream( + "def f(x,y) { x = 3+4; y; ; }\n" + "def g(x) { return 1+2*x; }\n" + ) + + # Create the Token Stream + self.lexer = ExprLexer(self.input_stream) + self.stream = CommonTokenStream(self.lexer) + self.stream.fill() + + # Create the parser and expression parse tree + self.parser = ExprParser(self.stream) + self.tree = self.parser.prog() + + def testValidPaths(self): + valid_paths = [ + "/prog/func", # all funcs under prog at root + "/prog/*", # all children of prog at root + "/*/func", # all func kids of any root node + "prog", # prog must be root node + "/prog", # prog must be root node + "/*", # any root + "*", # any root + "//ID", # any ID in tree + "//expr/primary/ID", # any ID child of a primary under any expr + "//body//ID", # any ID under a body + "//'return'", # any 'return' literal in tree, matched by literal name + "//RETURN", # any 'return' literal in tree, matched by symbolic name + "//primary/*", # all kids of any primary + "//func/*/stat", # all stat nodes grandkids of any func node + "/prog/func/'def'", # all def literal kids of func kid of prog + "//stat/';'", # all ';' under any stat node + "//expr/primary/!ID",# anything but ID under primary under any expr node + "//expr/!primary", # anything but primary under any expr node + "//!*", # nothing anywhere + "/!*", # nothing at root + "//expr//ID" # any ID under any expression (tests antlr/antlr4#370) + ] + + expected_results = [ + "[func, func]", + "[func, func]", + "[func, func]", + "[prog]", + "[prog]", + "[prog]", + "[prog]", + "[f, x, y, x, y, g, x, x]", + "[y, x]", + "[x, y, x]", + "[return]", + "[return]", + "[3, 4, y, 1, 2, x]", + "[stat, stat, stat, stat]", + "[def, def]", + "[;, ;, ;, ;]", + "[3, 4, 1, 2]", + "[expr, expr, expr, expr, expr, expr]", + "[]", + "[]", + "[y, x]", + ] + + for path, expected in zip(valid_paths, expected_results): + # Build test string + res = XPath.findAll(self.tree, path, self.parser) + res_str = ", ".join([tokenToString(token, self.parser.ruleNames) for token in res]) + res_str = "[%s]" % res_str + + # Test against expected output + self.assertEqual(res_str, expected, "Failed test %s" % path) + +if __name__ == '__main__': + unittest.main() \ No newline at end of file From b0eb1825fb943ffee8d92af6ef09d1b858ad1b00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Henrique?= Date: Wed, 4 Sep 2019 16:43:12 -0300 Subject: [PATCH 13/33] Spaces/Tabs mishap --- runtime/Python3/test/xpathtest.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/Python3/test/xpathtest.py b/runtime/Python3/test/xpathtest.py index 278bffe5b..03b6101a9 100644 --- a/runtime/Python3/test/xpathtest.py +++ b/runtime/Python3/test/xpathtest.py @@ -15,7 +15,7 @@ class XPathTest(unittest.TestCase): def setUp(self): self.input_stream = InputStream( "def f(x,y) { x = 3+4; y; ; }\n" - "def g(x) { return 1+2*x; }\n" + "def g(x) { return 1+2*x; }\n" ) # Create the Token Stream From ae282133430c326e4523f075f19a61c549e8d9a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Henrique?= Date: Thu, 5 Sep 2019 14:29:25 -0300 Subject: [PATCH 14/33] Python3 XPath: Use Token.INVALID_TYPE instead of -1 on getXPathElement --- runtime/Python3/src/antlr4/xpath/XPath.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/runtime/Python3/src/antlr4/xpath/XPath.py b/runtime/Python3/src/antlr4/xpath/XPath.py index 4d3a4f56f..58b05c466 100644 --- a/runtime/Python3/src/antlr4/xpath/XPath.py +++ b/runtime/Python3/src/antlr4/xpath/XPath.py @@ -218,7 +218,7 @@ class XPath(object): elif wordToken.type in [XPathLexer.TOKEN_REF, XPathLexer.STRING]: tsource = self.parser.getTokenStream().tokenSource - ttype = -1 + ttype = Token.INVALID_TYPE if wordToken.type == XPathLexer.TOKEN_REF: if word in tsource.ruleNames: ttype = tsource.ruleNames.index(word) + 1 @@ -226,7 +226,7 @@ class XPath(object): if word in tsource.literalNames: ttype = tsource.literalNames.index(word) - if ttype == -1: + if ttype == Token.INVALID_TYPE: raise Exception("%s at index %d isn't a valid token name" % (word, wordToken.tokenIndex)) return XPathTokenAnywhereElement(word, ttype) if anywhere else XPathTokenElement(word, ttype) From 3c1231738e7dd00330fd79f8ef1159e1e116f8d0 Mon Sep 17 00:00:00 2001 From: Iman Hosseini Date: Tue, 10 Sep 2019 02:29:13 -0400 Subject: [PATCH 15/33] Update contributors.txt --- contributors.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/contributors.txt b/contributors.txt index d40bacd5f..c3a388f5b 100644 --- a/contributors.txt +++ b/contributors.txt @@ -221,3 +221,4 @@ YYYY/MM/DD, github id, Full name, email 2019/07/11, olowo726, Olof Wolgast, olof@baah.se 2019/07/16, abhijithneilabraham, Abhijith Neil Abraham, abhijithneilabrahampk@gmail.com 2019/07/26, Braavos96, Eric Hettiaratchi, erichettiaratchi@gmail.com +2019/09/10, ImanHosseini, Iman Hosseini, hosseini.iman@yahoo.com From e2b1ae7c79b4c04f1f9edd2a36523faf34e56515 Mon Sep 17 00:00:00 2001 From: neko1235 Date: Tue, 10 Sep 2019 16:01:16 -0700 Subject: [PATCH 16/33] Fix data race in LexerATNSimulator There is a potential memory consistency problem. --- .../Java/src/org/antlr/v4/runtime/atn/LexerATNSimulator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/Java/src/org/antlr/v4/runtime/atn/LexerATNSimulator.java b/runtime/Java/src/org/antlr/v4/runtime/atn/LexerATNSimulator.java index ec74ce5bd..9b246d3b7 100644 --- a/runtime/Java/src/org/antlr/v4/runtime/atn/LexerATNSimulator.java +++ b/runtime/Java/src/org/antlr/v4/runtime/atn/LexerATNSimulator.java @@ -78,7 +78,7 @@ public class LexerATNSimulator extends ATNSimulator { protected final SimState prevAccept = new SimState(); - public static int match_calls = 0; + public static volatile int match_calls = 0; public LexerATNSimulator(ATN atn, DFA[] decisionToDFA, PredictionContextCache sharedContextCache) From f11ce46ddf244bc61be90775ade6fa3ca2e7833e Mon Sep 17 00:00:00 2001 From: neko1235 Date: Tue, 10 Sep 2019 16:08:49 -0700 Subject: [PATCH 17/33] Update contributors.txt --- contributors.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/contributors.txt b/contributors.txt index f385aeeef..e9cefd6f0 100644 --- a/contributors.txt +++ b/contributors.txt @@ -222,4 +222,5 @@ YYYY/MM/DD, github id, Full name, email 2019/07/16, abhijithneilabraham, Abhijith Neil Abraham, abhijithneilabrahampk@gmail.com 2019/07/26, Braavos96, Eric Hettiaratchi, erichettiaratchi@gmail.com 2019/09/10, ImanHosseini, Iman Hosseini, hosseini.iman@yahoo.com -2019/09/03, João Henrique, johnnyonflame@hotmail.com \ No newline at end of file +2019/09/03, João Henrique, johnnyonflame@hotmail.com +2019/09/10, neko1235, Ihar Mokharau, igor.mohorev@gmail.com From db0a57c6ee4629b02c32abfb12fc2d325eaa5d57 Mon Sep 17 00:00:00 2001 From: neko1235 Date: Tue, 10 Sep 2019 21:16:49 -0700 Subject: [PATCH 18/33] Increment match_calls atomically This ensures the correctness of the counter value, i.e. the value is the number of calls to the match() method. --- .../Java/src/org/antlr/v4/runtime/atn/LexerATNSimulator.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/runtime/Java/src/org/antlr/v4/runtime/atn/LexerATNSimulator.java b/runtime/Java/src/org/antlr/v4/runtime/atn/LexerATNSimulator.java index 9b246d3b7..79c6c73e5 100644 --- a/runtime/Java/src/org/antlr/v4/runtime/atn/LexerATNSimulator.java +++ b/runtime/Java/src/org/antlr/v4/runtime/atn/LexerATNSimulator.java @@ -103,7 +103,9 @@ public class LexerATNSimulator extends ATNSimulator { } public int match(CharStream input, int mode) { - match_calls++; + synchronized (LexerATNSimulator.class) { + match_calls++; + } this.mode = mode; int mark = input.mark(); try { From f88f763983e4b48c48646bd233f80d17f56d949d Mon Sep 17 00:00:00 2001 From: neko1235 Date: Tue, 10 Sep 2019 22:44:42 -0700 Subject: [PATCH 19/33] Remove the match_calls counter This fixes the potential data race caused by unsynchronized concurrent access. --- .../Java/src/org/antlr/v4/runtime/atn/LexerATNSimulator.java | 5 ----- 1 file changed, 5 deletions(-) diff --git a/runtime/Java/src/org/antlr/v4/runtime/atn/LexerATNSimulator.java b/runtime/Java/src/org/antlr/v4/runtime/atn/LexerATNSimulator.java index 79c6c73e5..79d903053 100644 --- a/runtime/Java/src/org/antlr/v4/runtime/atn/LexerATNSimulator.java +++ b/runtime/Java/src/org/antlr/v4/runtime/atn/LexerATNSimulator.java @@ -78,8 +78,6 @@ public class LexerATNSimulator extends ATNSimulator { protected final SimState prevAccept = new SimState(); - public static volatile int match_calls = 0; - public LexerATNSimulator(ATN atn, DFA[] decisionToDFA, PredictionContextCache sharedContextCache) { @@ -103,9 +101,6 @@ public class LexerATNSimulator extends ATNSimulator { } public int match(CharStream input, int mode) { - synchronized (LexerATNSimulator.class) { - match_calls++; - } this.mode = mode; int mark = input.mark(); try { From 789d746636dd9fd84862f4950922feaeb3f9f4b8 Mon Sep 17 00:00:00 2001 From: Marcos Passos Date: Sat, 14 Sep 2019 09:36:37 -0300 Subject: [PATCH 20/33] PHP Target --- .gitmodules | 3 + .travis.yml | 7 + .travis/before-install-linux-php.sh | 10 + .travis/run-tests-php.sh | 9 + README.md | 1 + appveyor.yml | 5 +- contributors.txt | 5 +- doc/php-target.md | 111 ++ doc/targets.md | 7 +- runtime-testsuite/pom.xml | 17 +- .../v4/test/runtime/templates/CSharp.test.stg | 10 + .../v4/test/runtime/templates/Chrome.test.stg | 10 + .../v4/test/runtime/templates/Cpp.test.stg | 6 + .../test/runtime/templates/Explorer.test.stg | 10 + .../test/runtime/templates/Firefox.test.stg | 10 + .../v4/test/runtime/templates/Go.test.stg | 10 + .../v4/test/runtime/templates/Java.test.stg | 10 + .../v4/test/runtime/templates/Node.test.stg | 10 + .../v4/test/runtime/templates/PHP.test.stg | 272 ++++ .../test/runtime/templates/Python2.test.stg | 10 + .../test/runtime/templates/Python3.test.stg | 10 + .../v4/test/runtime/templates/Safari.test.stg | 10 + .../v4/test/runtime/templates/Swift.test.stg | 10 + .../v4/test/runtime/BaseRuntimeTest.java | 2 + .../CompositeParsersDescriptors.java | 4 +- .../FullContextParsingDescriptors.java | 2 +- .../descriptors/LeftRecursionDescriptors.java | 8 +- .../descriptors/LexerExecDescriptors.java | 4 + .../SemPredEvalParserDescriptors.java | 6 +- .../v4/test/runtime/php/BasePHPTest.java | 599 ++++++++ .../test/runtime/php/TestCompositeLexers.java | 25 + .../runtime/php/TestCompositeParsers.java | 25 + .../runtime/php/TestFullContextParsing.java | 25 + .../test/runtime/php/TestLeftRecursion.java | 25 + .../v4/test/runtime/php/TestLexerErrors.java | 25 + .../v4/test/runtime/php/TestLexerExec.java | 25 + .../v4/test/runtime/php/TestListeners.java | 25 + .../v4/test/runtime/php/TestParseTrees.java | 25 + .../v4/test/runtime/php/TestParserErrors.java | 25 + .../v4/test/runtime/php/TestParserExec.java | 25 + .../v4/test/runtime/php/TestPerformance.java | 25 + .../runtime/php/TestSemPredEvalLexer.java | 25 + .../runtime/php/TestSemPredEvalParser.java | 25 + .../antlr/v4/test/runtime/php/TestSets.java | 25 + runtime/PHP | 1 + .../v4/tool/templates/codegen/PHP/PHP.stg | 1231 +++++++++++++++++ .../model/decl/AltLabelStructDecl.java | 2 + .../antlr/v4/codegen/target/PHPTarget.java | 105 ++ 48 files changed, 2854 insertions(+), 23 deletions(-) create mode 100644 .gitmodules create mode 100755 .travis/before-install-linux-php.sh create mode 100755 .travis/run-tests-php.sh create mode 100644 doc/php-target.md create mode 100644 runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/PHP.test.stg create mode 100644 runtime-testsuite/test/org/antlr/v4/test/runtime/php/BasePHPTest.java create mode 100644 runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestCompositeLexers.java create mode 100644 runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestCompositeParsers.java create mode 100644 runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestFullContextParsing.java create mode 100644 runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestLeftRecursion.java create mode 100644 runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestLexerErrors.java create mode 100644 runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestLexerExec.java create mode 100644 runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestListeners.java create mode 100644 runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestParseTrees.java create mode 100644 runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestParserErrors.java create mode 100644 runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestParserExec.java create mode 100644 runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestPerformance.java create mode 100644 runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestSemPredEvalLexer.java create mode 100644 runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestSemPredEvalParser.java create mode 100644 runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestSets.java create mode 160000 runtime/PHP create mode 100644 tool/resources/org/antlr/v4/tool/templates/codegen/PHP/PHP.stg create mode 100644 tool/src/org/antlr/v4/codegen/target/PHPTarget.java diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 000000000..7944e8e32 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "runtime/PHP"] + path = runtime/PHP + url = https://github.com/antlr/antlr-php-runtime.git diff --git a/.travis.yml b/.travis.yml index 880cf8907..0220f4ca2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -152,6 +152,13 @@ matrix: jdk: openjdk8 env: TARGET=csharp stage: main-test + - os: linux + language: php + php: + - 7.2 + jdk: openjdk8 + env: TARGET=php + stage: main-test - os: linux jdk: openjdk8 dist: trusty diff --git a/.travis/before-install-linux-php.sh b/.travis/before-install-linux-php.sh new file mode 100755 index 000000000..b95e3b31d --- /dev/null +++ b/.travis/before-install-linux-php.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +set -euo pipefail + +sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF +sudo apt-get update -qq + +php -v + +mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V \ No newline at end of file diff --git a/.travis/run-tests-php.sh b/.travis/run-tests-php.sh new file mode 100755 index 000000000..853efbd86 --- /dev/null +++ b/.travis/run-tests-php.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +set -euo pipefail + +php_path=$(which php) + +composer install -d ../runtime/PHP + +mvn -q -DPHP_PATH="${php_path}" -Dparallel=methods -DthreadCount=4 -Dtest=php.* test diff --git a/README.md b/README.md index d63bc4f66..ec5c21c62 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,7 @@ ANTLR project lead and supreme dictator for life * [Janyou](https://github.com/janyou) (Swift target) * [Ewan Mellor](https://github.com/ewanmellor), [Hanzhou Shi](https://github.com/hanjoes) (Swift target merging) * [Ben Hamilton](https://github.com/bhamiltoncx) (Full Unicode support in serialized ATN and all languages' runtimes for code points > U+FFFF) +* [Marcos Passos](https://github.com/marcospassos) (PHP target) ## Useful information diff --git a/appveyor.yml b/appveyor.yml index 266eeebad..d58657c98 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -4,6 +4,9 @@ cache: - '%USERPROFILE%\.nuget\packages -> **\project.json' image: Visual Studio 2017 build: off +install: + - git submodule update --init --recursive + - cinst -y php composer build_script: - mvn -DskipTests install --batch-mode - msbuild /target:restore /target:rebuild /property:Configuration=Release /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" /verbosity:detailed runtime/CSharp/runtime/CSharp/Antlr4.dotnet.sln @@ -11,7 +14,7 @@ build_script: after_build: - msbuild /target:pack /property:Configuration=Release /verbosity:detailed runtime/CSharp/runtime/CSharp/Antlr4.dotnet.sln test_script: - - mvn install -Dantlr-python2-python="C:\Python27\python.exe" -Dantlr-python3-python="C:\Python35\python.exe" -Dantlr-javascript-nodejs="C:\Program Files (x86)\nodejs\node.exe" --batch-mode + - mvn install -Dantlr-php-php="C:\tools\php73\php.exe" -Dantlr-python2-python="C:\Python27\python.exe" -Dantlr-python3-python="C:\Python35\python.exe" -Dantlr-javascript-nodejs="C:\Program Files (x86)\nodejs\node.exe" --batch-mode artifacts: - path: 'runtime\**\*.nupkg' name: NuGet \ No newline at end of file diff --git a/contributors.txt b/contributors.txt index f385aeeef..6ff7f398d 100644 --- a/contributors.txt +++ b/contributors.txt @@ -222,4 +222,7 @@ YYYY/MM/DD, github id, Full name, email 2019/07/16, abhijithneilabraham, Abhijith Neil Abraham, abhijithneilabrahampk@gmail.com 2019/07/26, Braavos96, Eric Hettiaratchi, erichettiaratchi@gmail.com 2019/09/10, ImanHosseini, Iman Hosseini, hosseini.iman@yahoo.com -2019/09/03, João Henrique, johnnyonflame@hotmail.com \ No newline at end of file +2019/09/03, João Henrique, johnnyonflame@hotmail.com +2019/09/10, yar3333, Yaroslav Sivakov, yar3333@gmail.com +2019/09/10, marcospassos, Marcos Passos, marcospassos.com@gmail.com +2019/09/10, amorimjuliana, Juliana Amorim, juu.amorim@gmail.com \ No newline at end of file diff --git a/doc/php-target.md b/doc/php-target.md new file mode 100644 index 000000000..75eae465c --- /dev/null +++ b/doc/php-target.md @@ -0,0 +1,111 @@ +# ANTLR4 Runtime for PHP + +### First steps + +#### 1. Install ANTLR4 + +[The getting started guide](https://github.com/antlr/antlr4/blob/master/doc/getting-started.md) +should get you started. + +#### 2. Install the PHP ANTLR runtime + +Each target language for ANTLR has a runtime package for running parser +generated by ANTLR4. The runtime provides a common set of tools for using your parser. + +Install the runtime with Composer: + +```bash +composer install antlr/antlr4 +``` + +#### 3. Generate your parser + +You use the ANTLR4 "tool" to generate a parser. These will reference the ANTLR +runtime, installed above. + +Suppose you're using a UNIX system and have set up an alias for the ANTLR4 tool +as described in [the getting started guide](https://github.com/antlr/antlr4/blob/master/doc/getting-started.md). +To generate your PHP parser, run the following command: + +```bash +antlr4 -Dlanguage=PHP MyGrammar.g4 +``` + +For a full list of antlr4 tool options, please visit the +[tool documentation page](https://github.com/antlr/antlr4/blob/master/doc/tool-options.md). + +### Complete example + +Suppose you're using the JSON grammar from https://github.com/antlr/grammars-v4/tree/master/json. + +Then, invoke `antlr4 -Dlanguage=PHP JSON.g4`. The result of this is a +collection of `.php` files in the `parser` directory including: +``` +JsonParser.php +JsonBaseListener.php +JsonLexer.php +JsonListener.php +``` + +Another common option to the ANTLR tool is `-visitor`, which generates a parse +tree visitor, but we won't be doing that here. For a full list of antlr4 tool +options, please visit the [tool documentation page](tool-options.md). + +We'll write a small main func to call the generated parser/lexer +(assuming they are separate). This one writes out the encountered +`ParseTreeContext`'s: + +```php +getText(); + } +} + +$input = InputStream::fromPath($argv[1]); +$lexer = new JSONLexer($input); +$tokens = new CommonTokenStream($lexer); +$parser = new JSONParser($tokens); +$parser->addErrorListener(new DiagnosticErrorListener()); +$parser->setBuildParseTree(true); +$tree = $parser->json(); + +ParseTreeWalker::default()->walk(new TreeShapeListener(), $tree); +``` + +Create a `example.json` file: +```json +{"a":1} +``` + +Parse the input file: + +``` +php json.php example.json +``` + +The expected output is: + +``` +{"a":1} +{"a":1} +"a":1 +1 +``` \ No newline at end of file diff --git a/doc/targets.md b/doc/targets.md index 418630bb1..c2341ec48 100644 --- a/doc/targets.md +++ b/doc/targets.md @@ -9,12 +9,13 @@ This page lists the available and upcoming ANTLR runtimes. Please note that you * [Go](go-target.md) * [C++](cpp-target.md) * [Swift](swift-target.md) +* [PHP](php-target.md) ## Target feature parity New features generally appear in the Java target and then migrate to the other targets, but these other targets don't always get updated in the same overall tool release. This section tries to identify features added to Java that have not been added to the other targets. -|Feature|Java|C♯|Python2|Python3|JavaScript|Go|C++|Swift| -|---|---|---|---|---|---|---|---|---| -|Ambiguous tree construction|4.5.1|-|-|-|-|-|-|-| +|Feature|Java|C♯|Python2|Python3|JavaScript|Go|C++|Swift|PHP +|---|---|---|---|---|---|---|---|---|---| +|Ambiguous tree construction|4.5.1|-|-|-|-|-|-|-|-| diff --git a/runtime-testsuite/pom.xml b/runtime-testsuite/pom.xml index ebfdbd723..b9e6bd936 100644 --- a/runtime-testsuite/pom.xml +++ b/runtime-testsuite/pom.xml @@ -109,14 +109,15 @@ -Dfile.encoding=UTF-8 - **/csharp/Test*.java - **/java/Test*.java - **/go/Test*.java - **/javascript/node/Test*.java - **/python2/Test*.java - **/python3/Test*.java - ${antlr.tests.swift} - + **/csharp/Test*.java + **/java/Test*.java + **/go/Test*.java + **/javascript/node/Test*.java + **/python2/Test*.java + **/python3/Test*.java + **/php/Test*.java + ${antlr.tests.swift} + diff --git a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/CSharp.test.stg b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/CSharp.test.stg index 597248f2b..fb95440ce 100644 --- a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/CSharp.test.stg +++ b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/CSharp.test.stg @@ -14,6 +14,8 @@ Cast(t,v) ::= "(())" Append(a,b) ::= " + " +AppendStr(a,b) ::= <%%> + Concat(a,b) ::= "" DeclareLocal(s,v) ::= "Object = ;" @@ -26,6 +28,12 @@ InitIntMember(n,v) ::= <%int = ;%> InitBooleanMember(n,v) ::= <%bool = ;%> +InitIntVar(n,v) ::= <%%> + +IntArg(n) ::= "int " + +VarRef(n) ::= "" + GetMember(n) ::= <%this.%> SetMember(n,v) ::= <%this. = ;%> @@ -94,6 +102,8 @@ bool Property() { ParserPropertyCall(p, call) ::= "

." +PositionAdjustingLexerDef() ::= "" + PositionAdjustingLexer() ::= << PositionAdjustingLexer.prototype.resetAcceptPosition = function(index, line, column) { diff --git a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Firefox.test.stg b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Firefox.test.stg index c94be90e8..c8a6c1d57 100644 --- a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Firefox.test.stg +++ b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Firefox.test.stg @@ -14,6 +14,8 @@ Cast(t,v) ::= "" Append(a,b) ::= " + " +AppendStr(a,b) ::= <%%> + Concat(a,b) ::= "" DeclareLocal(s,v) ::= "var = ;" @@ -26,6 +28,12 @@ InitIntMember(n,v) ::= <%this. = ;%> InitBooleanMember(n,v) ::= <%this. = ;%> +InitIntVar(n,v) ::= <%%> + +IntArg(n) ::= "" + +VarRef(n) ::= "" + GetMember(n) ::= <%this.%> SetMember(n,v) ::= <%this. = ;%> @@ -100,6 +108,8 @@ this.Property = function() { ParserPropertyCall(p, call) ::= "

." +PositionAdjustingLexerDef() ::= "" + PositionAdjustingLexer() ::= << PositionAdjustingLexer.prototype.resetAcceptPosition = function(index, line, column) { diff --git a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Go.test.stg b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Go.test.stg index 37fe63441..b2909f4e1 100644 --- a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Go.test.stg +++ b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Go.test.stg @@ -14,6 +14,8 @@ Cast(t,v) ::= "()" Append(a,b) ::= " + fmt.Sprint()" +AppendStr(a,b) ::= " + " + Concat(a,b) ::= "" DeclareLocal(s, v) ::= "var = " @@ -26,6 +28,12 @@ InitIntMember(n, v) ::= <%var int = ; var _ int = ; %> InitBooleanMember(n, v) ::= <%var bool = ; var _ bool = ; %> +InitIntVar(n,v) ::= <%%> + +IntArg(n) ::= "int " + +VarRef(n) ::= "" + GetMember(n) ::= <%%> SetMember(n, v) ::= <% = ;%> @@ -94,6 +102,8 @@ func (p *TParser) Property() bool { ParserPropertyCall(p, call) ::= "

." +PositionAdjustingLexerDef() ::= "" + PositionAdjustingLexer() ::= << func (p *PositionAdjustingLexer) NextToken() antlr.Token { if _, ok := p.Interpreter.(*PositionAdjustingLexerATNSimulator); !ok { diff --git a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Java.test.stg b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Java.test.stg index 5012aa213..11f159743 100644 --- a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Java.test.stg +++ b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Java.test.stg @@ -14,6 +14,8 @@ Cast(t,v) ::= "(())" Append(a,b) ::= " + " +AppendStr(a,b) ::= <%%> + Concat(a,b) ::= "" DeclareLocal(s,v) ::= "Object = ;" @@ -26,6 +28,12 @@ InitIntMember(n,v) ::= <%int = ;%> InitBooleanMember(n,v) ::= <%boolean = ;%> +InitIntVar(n,v) ::= <%%> + +IntArg(n) ::= "int " + +VarRef(n) ::= "" + GetMember(n) ::= <%this.%> SetMember(n,v) ::= <%this. = ;%> @@ -94,6 +102,8 @@ boolean Property() { ParserPropertyCall(p, call) ::= "

." +PositionAdjustingLexerDef() ::= "" + PositionAdjustingLexer() ::= << @Override diff --git a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Node.test.stg b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Node.test.stg index 92cb1dbbb..81573d6c0 100644 --- a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Node.test.stg +++ b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Node.test.stg @@ -14,6 +14,8 @@ Cast(t,v) ::= "" Append(a,b) ::= " + " +AppendStr(a,b) ::= <%%> + Concat(a,b) ::= "" DeclareLocal(s,v) ::= "var = ;" @@ -26,6 +28,12 @@ InitIntMember(n,v) ::= <%this. = ;%> InitBooleanMember(n,v) ::= <%this. = ;%> +InitIntVar(n,v) ::= <%%> + +IntArg(n) ::= "" + +VarRef(n) ::= "" + GetMember(n) ::= <%this.%> SetMember(n,v) ::= <%this. = ;%> @@ -98,6 +106,8 @@ this.Property = function() { ParserPropertyCall(p, call) ::= "

." +PositionAdjustingLexerDef() ::= "" + PositionAdjustingLexer() ::= << PositionAdjustingLexer.prototype.resetAcceptPosition = function(index, line, column) { diff --git a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/PHP.test.stg b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/PHP.test.stg new file mode 100644 index 000000000..a2ea87466 --- /dev/null +++ b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/PHP.test.stg @@ -0,0 +1,272 @@ +writeln(s) ::= < . \PHP_EOL;>> +write(s) ::= <;>> +writeList(s) ::= <;>> + +False() ::= "false" +True() ::= "true" +Not(v) ::= "!" +Assert(s) ::= <);>> +Cast(t,v) ::= "" +Append(a,b) ::= " . " +AppendStr(a,b) ::= <%%> +Concat(a,b) ::= "" + +DeclareLocal(s,v) ::= " = ;" + +AssertIsList(v) ::= "assert(\is_array());" // just use static type system +AssignLocal(s,v) ::= " = ;" + +InitIntMember(n,v) ::= <%public \$ = ;%> +InitBooleanMember(n,v) ::= <%public \$ = ;%> +InitIntVar(n,v) ::= <%\$ = ;%> +IntArg(n) ::= "int " +VarRef(n) ::= "$" + +GetMember(n) ::= <%\$this->%> +SetMember(n,v) ::= <%\$this-> = ;%> +AddMember(n,v) ::= <%\$this-> += ;%> +PlusMember(v,n) ::= <% + \$this->%> +MemberEquals(n,v) ::= <%\$this-> == %> +ModMemberEquals(n,m,v) ::= <%\$this-> % == %> +ModMemberNotEquals(n,m,v) ::= <%\$this-> % !== %> + +DumpDFA() ::= "\$this->dumpDFA();" +Pass() ::= "" + +StringList() ::= "" +BuildParseTrees() ::= "\$this->setBuildParseTree(true);" +BailErrorStrategy() ::= <%\$this->setErrorHandler(new Antlr\\Antlr4\\Runtime\\Error\\BailErrorStrategy());%> + +ToStringTree(s) ::= <%->toStringTree(\$this->getRuleNames())%> +Column() ::= "\$this->getCharPositionInLine()" +Text() ::= "\$this->getText()" +ValEquals(a,b) ::= <%===%> +TextEquals(a) ::= <%\$this->getText() === ""%> +PlusText(a) ::= <%"" . \$this->getText()%> +InputText() ::= "\$this->input->getText()" +LTEquals(i, v) ::= <%\$this->input->LT()->getText() === %> +LANotEquals(i, v) ::= <%\$this->input->LA() !== %> +TokenStartColumnEquals(i) ::= <%\$this->tokenStartCharPositionInLine === %> + +ImportListener(X) ::= "" + +GetExpectedTokenNames() ::= "\$this->getExpectedTokens()->toStringVocabulary(\$this->getVocabulary())" + +RuleInvocationStack() ::= "'[' . \implode(', ', \$this->getRuleInvocationStack()) . ']'" + +LL_EXACT_AMBIG_DETECTION() ::= <<\$this->interp->setPredictionMode(Antlr\\Antlr4\\Runtime\\Atn\\PredictionMode::LL_EXACT_AMBIG_DETECTION);>> + + +ParserToken(parser, token) ::= <%::%> + +Production(p) ::= <%

%> + +Result(r) ::= <%%> + +ParserPropertyMember() ::= << +@members { +public function Property() : bool +{ + return true; +} +} +>> + +ParserPropertyCall(p, call) ::= "

->" + +PositionAdjustingLexerDef() ::= << +class PositionAdjustingLexerATNSimulator extends LexerATNSimulator { + public function resetAcceptPosition(CharStream \$input, int \$index, int \$line, int \$charPositionInLine) : void { + \$input->seek(\$index); + \$this->line = \$line; + \$this->charPositionInLine = \$charPositionInLine; + \$this->consume(\$input); + } +} +>> + +PositionAdjustingLexer() ::= << +public function nextToken() : Antlr\\Antlr4\\Runtime\\Token +{ + if (!\$this->interp instanceof PositionAdjustingLexerATNSimulator) { + \$this->interp = new PositionAdjustingLexerATNSimulator(\$this, self::\$atn, self::\$decisionToDFA, self::\$sharedContextCache); + } + + return parent::nextToken(); +} + +public function emit() : Antlr\\Antlr4\\Runtime\\Token +{ + switch (\$this->type) { + case self::TOKENS: + \$this->handleAcceptPositionForKeyword('tokens'); + break; + + case self::LABEL: + \$this->handleAcceptPositionForIdentifier(); + break; + } + + return parent::emit(); +} + +private function handleAcceptPositionForIdentifier() : bool +{ + \$tokenText = \$this->getText(); + \$identifierLength = 0; + while (\$identifierLength \< \strlen(\$tokenText) && self::isIdentifierChar(\$tokenText[\$identifierLength])) { + \$identifierLength++; + } + + if (\$this->getInputStream()->getIndex() > \$this->tokenStartCharIndex + \$identifierLength) { + \$offset = \$identifierLength - 1; + \$this->getInterpreter()->resetAcceptPosition(\$this->getInputStream(), \$this->tokenStartCharIndex + \$offset, \$this->tokenStartLine, \$this->tokenStartCharPositionInLine + \$offset); + + return true; + } + + return false; +} + +private function handleAcceptPositionForKeyword(string \$keyword) : bool +{ + if (\$this->getInputStream()->getIndex() > \$this->tokenStartCharIndex + \strlen(\$keyword)) { + \$offset = \strlen(\$keyword) - 1; + \$this->getInterpreter()->resetAcceptPosition(\$this->getInputStream(), \$this->tokenStartCharIndex + \$offset, \$this->tokenStartLine, \$this->tokenStartCharPositionInLine + \$offset); + + return true; + } + + return false; +} + +private static function isIdentifierChar(string \$c) : bool +{ + return \ctype_alnum(\$c) || \$c === '_'; +} +>> + +BasicListener(X) ::= << +@parser::definitions { +class LeafListener extends TBaseListener +{ + public function visitTerminal(Antlr\\Antlr4\\Runtime\\Tree\\TerminalNode \$node) : void + { + echo \$node->getSymbol()->getText() . \PHP_EOL; + } +} +} +>> + +WalkListener(s) ::= << +\$walker = new Antlr\\Antlr4\\Runtime\\Tree\\ParseTreeWalker(); +\$walker->walk(new LeafListener(), ); +>> + +TreeNodeWithAltNumField(X) ::= << +@parser::contexts { +class MyRuleNode extends ParserRuleContext +{ + public \$altNum; + + public function getAltNumber() : int + { + return \$this->altNum; + } + + public function setAltNumber(int \$altNum) : void + { + \$this->altNum = \$altNum; + } +} +} +>> + +TokenGetterListener(X) ::= << +@parser::definitions { +class LeafListener extends TBaseListener { + public function exitA(Context\\AContext \$ctx) : void { + if (\$ctx->getChildCount() === 2) { + echo \sprintf('%s %s [%s]',\$ctx->INT(0)->getSymbol()->getText(), \$ctx->INT(1)->getSymbol()->getText(), \implode(', ', \$ctx->INT())) . \PHP_EOL; + } else { + echo \$ctx->ID()->getSymbol() . \PHP_EOL; + } + } +} +} +>> + +RuleGetterListener(X) ::= << +@parser::definitions { +class LeafListener extends TBaseListener { + public function exitA(Context\\AContext \$ctx) : void + { + if (\$ctx->getChildCount() === 2) { + echo \sprintf('%s %s %s', \$ctx->b(0)->start->getText(), \$ctx->b(1)->start->getText(),\$ctx->b()[0]->start->getText()) . \PHP_EOL; + } else { + echo \$ctx->b(0)->start->getText() . \PHP_EOL; + } + } +} +} +>> + + +LRListener(X) ::= << +@parser::definitions { +class LeafListener extends TBaseListener { + public function exitE(Context\\EContext \$ctx) : void + { + if (\$ctx->getChildCount() === 3) { + echo \sprintf('%s %s %s', \$ctx->e(0)->start->getText(), \$ctx->e(1)->start->getText(), \$ctx->e()[0]->start->getText()) . \PHP_EOL; + } else { + echo \$ctx->INT()->getSymbol()->getText() . \PHP_EOL; + } + } +} +} +>> + +LRWithLabelsListener(X) ::= << +@parser::definitions { +class LeafListener extends TBaseListener +{ + public function exitCall(Context\\CallContext \$ctx) : void { + echo \sprintf('%s %s',\$ctx->e()->start->getText(),\$ctx->eList()) . \PHP_EOL; + } + + public function exitInt(Context\\IntContext \$ctx) : void { + echo \$ctx->INT()->getSymbol()->getText() . \PHP_EOL; + } +} +} +>> + +DeclareContextListGettersFunction() ::= << +public function foo() : void { + \$s = null; + \$a = \$s->a(); + \$b = \$s->b(); +} +>> + +Declare_foo() ::= << +public function foo() : void { + echo 'foo' . \PHP_EOL; +} +>> + +Invoke_foo() ::= "\$this->foo();" + +Declare_pred() ::= <pred()" + +ParserTokenType(t) ::= "Parser::" +ContextRuleFunction(ctx, rule) ::= "->" +StringType() ::= "" +ContextMember(ctx, subctx, member) ::= "->->" diff --git a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Python2.test.stg b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Python2.test.stg index cc0d9d9c2..3102f4120 100644 --- a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Python2.test.stg +++ b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Python2.test.stg @@ -14,6 +14,8 @@ Cast(t,v) ::= "" Append(a,b) ::= " + str()" +AppendStr(a,b) ::= " + " + Concat(a,b) ::= "" DeclareLocal(s,v) ::= " = " @@ -26,6 +28,12 @@ InitIntMember(n,v) ::= <% = %> InitBooleanMember(n,v) ::= <% = %> +InitIntVar(n,v) ::= <%%> + +IntArg(n) ::= "" + +VarRef(n) ::= "" + GetMember(n) ::= <%self.%> SetMember(n,v) ::= <%self. = %> @@ -94,6 +102,8 @@ def Property(self): ParserPropertyCall(p, call) ::= "

." +PositionAdjustingLexerDef() ::= "" + PositionAdjustingLexer() ::= << def resetAcceptPosition(self, index, line, column): diff --git a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Python3.test.stg b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Python3.test.stg index c91563017..858b76113 100644 --- a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Python3.test.stg +++ b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Python3.test.stg @@ -14,6 +14,8 @@ Cast(t,v) ::= "" Append(a,b) ::= " + str()" +AppendStr(a,b) ::= " + " + Concat(a,b) ::= "" DeclareLocal(s,v) ::= " = " @@ -26,6 +28,12 @@ InitIntMember(n,v) ::= <% = %> InitBooleanMember(n,v) ::= <% = %> +InitIntVar(n,v) ::= <%%> + +IntArg(n) ::= "" + +VarRef(n) ::= "" + GetMember(n) ::= <%self.%> SetMember(n,v) ::= <%self. = %> @@ -99,6 +107,8 @@ def Property(self): ParserPropertyCall(p, call) ::= "

." +PositionAdjustingLexerDef() ::= "" + PositionAdjustingLexer() ::= << def resetAcceptPosition(self, index, line, column): diff --git a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Safari.test.stg b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Safari.test.stg index 71254e0f2..2a09970c2 100644 --- a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Safari.test.stg +++ b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Safari.test.stg @@ -14,6 +14,8 @@ Cast(t,v) ::= "" Append(a,b) ::= " + " +AppendStr(a,b) ::= <%%> + Concat(a,b) ::= "" DeclareLocal(s,v) ::= "var = ;" @@ -26,6 +28,12 @@ InitIntMember(n,v) ::= <%this. = ;%> InitBooleanMember(n,v) ::= <%this. = ;%> +InitIntVar(n,v) ::= <%%> + +IntArg(n) ::= "" + +VarRef(n) ::= "" + GetMember(n) ::= <%this.%> SetMember(n,v) ::= <%this. = ;%> @@ -98,6 +106,8 @@ this.Property = function() { ParserPropertyCall(p, call) ::= "

." +PositionAdjustingLexerDef() ::= "" + PositionAdjustingLexer() ::= << PositionAdjustingLexer.prototype.resetAcceptPosition = function(index, line, column) { diff --git a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Swift.test.stg b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Swift.test.stg index 100d6f3e7..d45168517 100755 --- a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Swift.test.stg +++ b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Swift.test.stg @@ -14,6 +14,8 @@ Cast(t,v) ::= "(( as! ))" Append(a,b) ::= " + " +AppendStr(a,b) ::= <%%> + Concat(a,b) ::= "" DeclareLocal(s,v) ::= "var = " @@ -26,6 +28,12 @@ InitIntMember(n,v) ::= <%var = %> InitBooleanMember(n,v) ::= <%var = %> +InitIntVar(n,v) ::= <%%> + +IntArg(n) ::= "int " + +VarRef(n) ::= "" + GetMember(n) ::= <%self.%> SetMember(n,v) ::= <%self. = %> @@ -96,6 +104,8 @@ ParserPropertyCall(parser, property) ::= << . >> +PositionAdjustingLexerDef() ::= "" + PositionAdjustingLexer() ::= << override diff --git a/runtime-testsuite/test/org/antlr/v4/test/runtime/BaseRuntimeTest.java b/runtime-testsuite/test/org/antlr/v4/test/runtime/BaseRuntimeTest.java index 71cd1e34d..f7874d671 100644 --- a/runtime-testsuite/test/org/antlr/v4/test/runtime/BaseRuntimeTest.java +++ b/runtime-testsuite/test/org/antlr/v4/test/runtime/BaseRuntimeTest.java @@ -50,6 +50,7 @@ public abstract class BaseRuntimeTest { "Go", "CSharp", "Python2", "Python3", + "PHP", "Node", "Safari", "Firefox", "Explorer", "Chrome" }; public final static String[] JavaScriptTargets = { @@ -116,6 +117,7 @@ public abstract class BaseRuntimeTest { System.out.printf("Ignore "+descriptor); return; } + if ( descriptor.getTestType().contains("Parser") ) { testParser(descriptor); } diff --git a/runtime-testsuite/test/org/antlr/v4/test/runtime/descriptors/CompositeParsersDescriptors.java b/runtime-testsuite/test/org/antlr/v4/test/runtime/descriptors/CompositeParsersDescriptors.java index 435dcc977..6134b265b 100644 --- a/runtime-testsuite/test/org/antlr/v4/test/runtime/descriptors/CompositeParsersDescriptors.java +++ b/runtime-testsuite/test/org/antlr/v4/test/runtime/descriptors/CompositeParsersDescriptors.java @@ -418,7 +418,7 @@ public class CompositeParsersDescriptors { parser grammar S; type_ : 'int' ; decl : type_ ID ';' - | type_ ID init_ ';' {}; + | type_ ID init_ ';' {}; init_ : '=' INT; */ @CommentHasStringValue @@ -532,7 +532,7 @@ public class CompositeParsersDescriptors { /** parser grammar S; - a @after {} : B; + a @after {} : B; */ @CommentHasStringValue public String slaveGrammarS; diff --git a/runtime-testsuite/test/org/antlr/v4/test/runtime/descriptors/FullContextParsingDescriptors.java b/runtime-testsuite/test/org/antlr/v4/test/runtime/descriptors/FullContextParsingDescriptors.java index 942d07be5..fb71b3863 100644 --- a/runtime-testsuite/test/org/antlr/v4/test/runtime/descriptors/FullContextParsingDescriptors.java +++ b/runtime-testsuite/test/org/antlr/v4/test/runtime/descriptors/FullContextParsingDescriptors.java @@ -372,7 +372,7 @@ public class FullContextParsingDescriptors { : expr_or_assign*; expr_or_assign : expr '++' {} - | expr {} + | expr {} ; expr: expr_primary ('\<-' ID)?; expr_primary diff --git a/runtime-testsuite/test/org/antlr/v4/test/runtime/descriptors/LeftRecursionDescriptors.java b/runtime-testsuite/test/org/antlr/v4/test/runtime/descriptors/LeftRecursionDescriptors.java index 66dd5760d..01e868d6e 100644 --- a/runtime-testsuite/test/org/antlr/v4/test/runtime/descriptors/LeftRecursionDescriptors.java +++ b/runtime-testsuite/test/org/antlr/v4/test/runtime/descriptors/LeftRecursionDescriptors.java @@ -529,8 +529,8 @@ public class LeftRecursionDescriptors { | e '+' e {$v = (0)}, {})> + (1)}, {})>;} # binary | INT {$v = $INT.int;} # anInt | '(' e ')' {$v = $e.v;} # parens - | left=e INC {$v = $left.v + 1;} # unary - | left=e DEC {$v = $left.v - 1;} # unary + | left=e INC {$v = $left.v + 1;} # unary + | left=e DEC {$v = $left.v - 1;} # unary | ID {} # anID ; ID : 'a'..'z'+ ; @@ -636,9 +636,9 @@ public class LeftRecursionDescriptors { grammar T; s : e {} ; e returns [ result] - : ID '=' e1=e {$result = "(" + $ID.text + "=" + $e1.result + ")";} + : ID '=' e1=e {$result = ;} | ID {$result = $ID.text;} - | e1=e '+' e2=e {$result = "(" + $e1.result + "+" + $e2.result + ")";} + | e1=e '+' e2=e {$result = ;} ; ID : 'a'..'z'+ ; INT : '0'..'9'+ ; diff --git a/runtime-testsuite/test/org/antlr/v4/test/runtime/descriptors/LexerExecDescriptors.java b/runtime-testsuite/test/org/antlr/v4/test/runtime/descriptors/LexerExecDescriptors.java index 60cb86cb4..7c74e74cb 100644 --- a/runtime-testsuite/test/org/antlr/v4/test/runtime/descriptors/LexerExecDescriptors.java +++ b/runtime-testsuite/test/org/antlr/v4/test/runtime/descriptors/LexerExecDescriptors.java @@ -766,6 +766,10 @@ public class LexerExecDescriptors { /** lexer grammar PositionAdjustingLexer; + @definitions { + + } + @members { } diff --git a/runtime-testsuite/test/org/antlr/v4/test/runtime/descriptors/SemPredEvalParserDescriptors.java b/runtime-testsuite/test/org/antlr/v4/test/runtime/descriptors/SemPredEvalParserDescriptors.java index ed4f9a384..b09f07488 100644 --- a/runtime-testsuite/test/org/antlr/v4/test/runtime/descriptors/SemPredEvalParserDescriptors.java +++ b/runtime-testsuite/test/org/antlr/v4/test/runtime/descriptors/SemPredEvalParserDescriptors.java @@ -144,8 +144,8 @@ public class SemPredEvalParserDescriptors { /** grammar T; s : b[2] ';' | b[2] '.' ; // decision in s drills down to ctx-dependent pred in a; - b[int i] : a[i] ; - a[int i] + b[] : a[] ; + a[] : {}? ID {} | {}? ID {} ; @@ -310,7 +310,7 @@ public class SemPredEvalParserDescriptors { grammar T; @parser::members {} primary - : ID {} + : ID {} | {}? 'enum' {} ; ID : [a-z]+ ; diff --git a/runtime-testsuite/test/org/antlr/v4/test/runtime/php/BasePHPTest.java b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/BasePHPTest.java new file mode 100644 index 000000000..8f2cc5bcc --- /dev/null +++ b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/BasePHPTest.java @@ -0,0 +1,599 @@ +/* + * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. + * Use of this file is governed by the BSD 3-clause license that + * can be found in the LICENSE.txt file in the project root. + */ + +package org.antlr.v4.test.runtime.php; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.antlr.v4.Tool; +import org.antlr.v4.automata.LexerATNFactory; +import org.antlr.v4.automata.ParserATNFactory; +import org.antlr.v4.runtime.atn.ATN; +import org.antlr.v4.runtime.atn.ATNDeserializer; +import org.antlr.v4.runtime.atn.ATNSerializer; +import org.antlr.v4.semantics.SemanticPipeline; +import org.antlr.v4.test.runtime.ErrorQueue; +import org.antlr.v4.test.runtime.RuntimeTestSupport; +import org.antlr.v4.test.runtime.StreamVacuum; +import org.antlr.v4.tool.Grammar; +import org.antlr.v4.tool.LexerGrammar; +import org.stringtemplate.v4.ST; + +import static org.antlr.v4.test.runtime.BaseRuntimeTest.antlrOnString; +import static org.antlr.v4.test.runtime.BaseRuntimeTest.writeFile; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class BasePHPTest implements RuntimeTestSupport { + public static final String newline = System.getProperty("line.separator"); + + public String tmpdir = null; + + /** + * If error during parser execution, store stderr here; can't return + * stdout and stderr. This doesn't trap errors from running antlr. + */ + protected String stderrDuringParse; + + /** + * Errors found while running antlr + */ + protected StringBuilder antlrToolErrors; + + private String getPropertyPrefix() { + return "antlr-php"; + } + + @Override + public void testSetUp() throws Exception { + // new output dir for each test + String propName = getPropertyPrefix() + "-test-dir"; + String prop = System.getProperty(propName); + + if (prop != null && prop.length() > 0) { + tmpdir = prop; + } else { + String classSimpleName = getClass().getSimpleName(); + String threadName = Thread.currentThread().getName(); + String childPath = String.format("%s-%s-%s", classSimpleName, threadName, System.currentTimeMillis()); + tmpdir = new File(System.getProperty("java.io.tmpdir"), childPath).getAbsolutePath(); + } + + antlrToolErrors = new StringBuilder(); + } + + @Override + public void testTearDown() throws Exception { + } + + @Override + public String getTmpDir() { + return tmpdir; + } + + @Override + public String getStdout() { + return null; + } + + @Override + public String getParseErrors() { + return stderrDuringParse; + } + + @Override + public String getANTLRToolErrors() { + if (antlrToolErrors.length() == 0) { + return null; + } + + return antlrToolErrors.toString(); + } + + protected ATN createATN(Grammar g, boolean useSerializer) { + if (g.atn == null) { + semanticProcess(g); + + assertEquals(0, g.tool.getNumErrors()); + + ParserATNFactory f; + + if (g.isLexer()) { + f = new LexerATNFactory((LexerGrammar) g); + } else { + f = new ParserATNFactory(g); + } + + g.atn = f.createATN(); + assertEquals(0, g.tool.getNumErrors()); + } + + ATN atn = g.atn; + + if (useSerializer) { + char[] serialized = ATNSerializer.getSerializedAsChars(atn); + + return new ATNDeserializer().deserialize(serialized); + } + + return atn; + } + + protected void semanticProcess(Grammar g) { + if (g.ast != null && !g.ast.hasErrors) { + Tool antlr = new Tool(); + SemanticPipeline sem = new SemanticPipeline(g); + sem.process(); + + if (g.getImportedGrammars() != null) { + for (Grammar imp: g.getImportedGrammars()) { + antlr.processNonCombinedGrammar(imp, false); + } + } + } + } + + protected String execLexer( + String grammarFileName, + String grammarStr, + String lexerName, + String input + ) { + return execLexer(grammarFileName, grammarStr, lexerName, input, false); + } + + @Override + public String execLexer( + String grammarFileName, + String grammarStr, + String lexerName, + String input, + boolean showDFA + ) { + boolean success = rawGenerateAndBuildRecognizer( + grammarFileName, + grammarStr, + null, + lexerName, + "-no-listener" + ); + assertTrue(success); + writeFile(tmpdir, "input", input); + writeLexerTestFile(lexerName, showDFA); + String output = execModule("Test.php"); + + return output; + } + + public String execParser( + String grammarFileName, + String grammarStr, + String parserName, + String lexerName, + String listenerName, + String visitorName, + String startRuleName, + String input, + boolean showDiagnosticErrors + ) { + return execParser_( + grammarFileName, + grammarStr, + parserName, + lexerName, + listenerName, + visitorName, + startRuleName, + input, + showDiagnosticErrors, + false + ); + } + + public String execParser_( + String grammarFileName, + String grammarStr, + String parserName, + String lexerName, + String listenerName, + String visitorName, + String startRuleName, + String input, + boolean debug, + boolean trace + ) { + boolean success = rawGenerateAndBuildRecognizer( + grammarFileName, + grammarStr, + parserName, + lexerName, + "-visitor" + ); + + assertTrue(success); + + writeFile(tmpdir, "input", input); + + rawBuildRecognizerTestFile( + parserName, + lexerName, + listenerName, + visitorName, + startRuleName, + debug, + trace + ); + + return execRecognizer(); + } + + /** + * Return true if all is well + */ + protected boolean rawGenerateAndBuildRecognizer( + String grammarFileName, + String grammarStr, + String parserName, + String lexerName, + String... extraOptions + ) { + return rawGenerateAndBuildRecognizer( + grammarFileName, + grammarStr, + parserName, + lexerName, + false, + extraOptions + ); + } + + /** + * Return true if all is well + */ + protected boolean rawGenerateAndBuildRecognizer( + String grammarFileName, + String grammarStr, + String parserName, + String lexerName, + boolean defaultListener, + String... extraOptions + ) { + ErrorQueue equeue = antlrOnString(getTmpDir(), "PHP", grammarFileName, grammarStr, defaultListener, extraOptions); + + if (!equeue.errors.isEmpty()) { + return false; + } + + List files = new ArrayList(); + + if (lexerName != null) { + files.add(lexerName + ".php"); + } + + if (parserName != null) { + files.add(parserName + ".php"); + Set optionsSet = new HashSet(Arrays.asList(extraOptions)); + + if (!optionsSet.contains("-no-listener")) { + files.add(grammarFileName.substring(0, grammarFileName.lastIndexOf('.')) + "Listener.php"); + } + + if (optionsSet.contains("-visitor")) { + files.add(grammarFileName.substring(0, grammarFileName.lastIndexOf('.')) + "Visitor.php"); + } + } + + return true; + } + + protected void rawBuildRecognizerTestFile( + String parserName, + String lexerName, + String listenerName, + String visitorName, + String parserStartRuleName, + boolean debug, + boolean trace + ) { + this.stderrDuringParse = null; + if (parserName == null) { + writeLexerTestFile(lexerName, false); + } else { + writeParserTestFile( + parserName, + lexerName, + listenerName, + visitorName, + parserStartRuleName, + debug, + trace + ); + } + } + + public String execRecognizer() { + return execModule("Test.php"); + } + + public String execModule(String fileName) { + String phpPath = locatePhp(); + String runtimePath = locateRuntime(); + + File tmpdirFile = new File(tmpdir); + String modulePath = new File(tmpdirFile, fileName).getAbsolutePath(); + String inputPath = new File(tmpdirFile, "input").getAbsolutePath(); + Path outputPath = tmpdirFile.toPath().resolve("output").toAbsolutePath(); + + try { + ProcessBuilder builder = new ProcessBuilder(phpPath, modulePath, inputPath, outputPath.toString()); + builder.environment().put("RUNTIME", runtimePath); + builder.directory(tmpdirFile); + Process process = builder.start(); + StreamVacuum stdoutVacuum = new StreamVacuum(process.getInputStream()); + StreamVacuum stderrVacuum = new StreamVacuum(process.getErrorStream()); + stdoutVacuum.start(); + stderrVacuum.start(); + process.waitFor(); + stdoutVacuum.join(); + stderrVacuum.join(); + String output = stdoutVacuum.toString(); + + if (output.length() == 0) { + output = null; + } + + if (stderrVacuum.toString().length() > 0) { + this.stderrDuringParse = stderrVacuum.toString(); + } + + return output; + } catch (Exception e) { + System.err.println("can't exec recognizer"); + e.printStackTrace(System.err); + } + return null; + } + + private String locateTool(String tool) { + final String phpPath = System.getProperty("PHP_PATH"); + + if (phpPath != null && new File(phpPath).exists()) { + return phpPath; + } + + String[] roots = {"/usr/local/bin/", "/opt/local/bin", "/usr/bin/"}; + + for (String root: roots) { + if (new File(root + tool).exists()) { + return root + tool; + } + } + + throw new RuntimeException("Could not locate " + tool); + } + + protected String locatePhp() { + String propName = getPropertyPrefix() + "-php"; + String prop = System.getProperty(propName); + + if (prop == null || prop.length() == 0) { + prop = locateTool("php"); + } + + File file = new File(prop); + + if (!file.exists()) { + throw new RuntimeException("Missing system property:" + propName); + } + + return file.getAbsolutePath(); + } + + protected String locateRuntime() { + String propName = "antlr-php-runtime"; + String prop = System.getProperty(propName); + + if (prop == null || prop.length() == 0) { + prop = "../runtime/PHP"; + } + + File file = new File(prop); + + if (!file.exists()) { + throw new RuntimeException("Missing system property:" + propName); + } + + try { + return file.getCanonicalPath(); + } catch (IOException e) { + return file.getAbsolutePath(); + } + } + + protected void mkdir(String dir) { + File f = new File(dir); + f.mkdirs(); + } + + protected void writeLexerTestFile(String lexerName, boolean showDFA) { + ST outputFileST = new ST( + "\\($input);\n" + + "$lexer->addErrorListener(new ConsoleErrorListener());" + + "$tokens = new CommonTokenStream($lexer);\n" + + "$tokens->fill();\n" + + "\n" + + "foreach ($tokens->getAllTokens() as $token) {\n" + + " echo $token . \\PHP_EOL;\n" + + "}" + + (showDFA + ? "echo $lexer->getInterpreter()->getDFA(Lexer::DEFAULT_MODE)->toLexerString();\n" + : "") + ); + + outputFileST.add("lexerName", lexerName); + + writeFile(tmpdir, "Test.php", outputFileST.render()); + } + + protected void writeParserTestFile( + String parserName, String lexerName, + String listenerName, String visitorName, + String parserStartRuleName, boolean debug, boolean trace + ) { + if (!parserStartRuleName.endsWith(")")) { + parserStartRuleName += "()"; + } + ST outputFileST = new ST( + "\\getChildCount(); $i \\< $count; $i++) {\n" + + " $parent = $ctx->getChild($i)->getParent();\n" + + "\n" + + " if (!($parent instanceof RuleNode) || $parent->getRuleContext() !== $ctx) {\n" + + " throw new RuntimeException('Invalid parse tree shape detected.');\n" + + " }\n" + + " }\n" + + " }\n" + + "}" + + "\n" + + "$input = InputStream::fromPath($argv[1]);\n" + + "$lexer = new ($input);\n" + + "$lexer->addErrorListener(new ConsoleErrorListener());" + + "$tokens = new CommonTokenStream($lexer);\n" + + "" + + "$parser->addErrorListener(new ConsoleErrorListener());" + + "$parser->setBuildParseTree(true);\n" + + "$tree = $parser->;\n\n" + + "ParseTreeWalker::default()->walk(new TreeShapeListener(), $tree);\n" + ); + + String stSource = "$parser = new ($tokens);\n"; + + if (debug) { + stSource += "$parser->addErrorListener(new DiagnosticErrorListener());\n"; + } + + if (trace) { + stSource += "$parser->setTrace(true);\n"; + } + + ST createParserST = new ST(stSource); + outputFileST.add("createParser", createParserST); + outputFileST.add("parserName", parserName); + outputFileST.add("lexerName", lexerName); + outputFileST.add("listenerName", listenerName); + outputFileST.add("visitorName", visitorName); + outputFileST.add("parserStartRuleName", parserStartRuleName); + + writeFile(tmpdir, "Test.php", outputFileST.render()); + } + + protected void eraseFiles(File dir) { + String[] files = dir.list(); + for (int i = 0; files != null && i < files.length; i++) { + new File(dir, files[i]).delete(); + } + } + + @Override + public void eraseTempDir() { + boolean doErase = true; + String propName = getPropertyPrefix() + "-erase-test-dir"; + String prop = System.getProperty(propName); + if (prop != null && prop.length() > 0) { + doErase = Boolean.getBoolean(prop); + } + if (doErase) { + File tmpdirF = new File(tmpdir); + if (tmpdirF.exists()) { + eraseFiles(tmpdirF); + tmpdirF.delete(); + } + } + } + + /** + * Sort a list + */ + public > List sort(List data) { + List dup = new ArrayList(); + dup.addAll(data); + Collections.sort(dup); + return dup; + } + + /** + * Return map sorted by key + */ + public , V> LinkedHashMap sort(Map data) { + LinkedHashMap dup = new LinkedHashMap(); + List keys = new ArrayList(); + keys.addAll(data.keySet()); + Collections.sort(keys); + for (K k: keys) { + dup.put(k, data.get(k)); + } + return dup; + } +} diff --git a/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestCompositeLexers.java b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestCompositeLexers.java new file mode 100644 index 000000000..d1d353875 --- /dev/null +++ b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestCompositeLexers.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. + * Use of this file is governed by the BSD 3-clause license that + * can be found in the LICENSE.txt file in the project root. + */ + +package org.antlr.v4.test.runtime.php; + +import org.antlr.v4.test.runtime.BaseRuntimeTest; +import org.antlr.v4.test.runtime.RuntimeTestDescriptor; +import org.antlr.v4.test.runtime.descriptors.CompositeLexersDescriptors; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class TestCompositeLexers extends BaseRuntimeTest { + public TestCompositeLexers(RuntimeTestDescriptor descriptor) { + super(descriptor,new BasePHPTest()); + } + + @Parameterized.Parameters(name="{0}") + public static RuntimeTestDescriptor[] getAllTestDescriptors() { + return BaseRuntimeTest.getRuntimeTestDescriptors(CompositeLexersDescriptors.class, "PHP"); + } +} diff --git a/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestCompositeParsers.java b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestCompositeParsers.java new file mode 100644 index 000000000..dd5b0015a --- /dev/null +++ b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestCompositeParsers.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. + * Use of this file is governed by the BSD 3-clause license that + * can be found in the LICENSE.txt file in the project root. + */ + +package org.antlr.v4.test.runtime.php; + +import org.antlr.v4.test.runtime.BaseRuntimeTest; +import org.antlr.v4.test.runtime.RuntimeTestDescriptor; +import org.antlr.v4.test.runtime.descriptors.CompositeParsersDescriptors; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class TestCompositeParsers extends BaseRuntimeTest { + public TestCompositeParsers(RuntimeTestDescriptor descriptor) { + super(descriptor,new BasePHPTest()); + } + + @Parameterized.Parameters(name="{0}") + public static RuntimeTestDescriptor[] getAllTestDescriptors() { + return BaseRuntimeTest.getRuntimeTestDescriptors(CompositeParsersDescriptors.class, "PHP"); + } +} diff --git a/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestFullContextParsing.java b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestFullContextParsing.java new file mode 100644 index 000000000..60efc0718 --- /dev/null +++ b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestFullContextParsing.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. + * Use of this file is governed by the BSD 3-clause license that + * can be found in the LICENSE.txt file in the project root. + */ + +package org.antlr.v4.test.runtime.php; + +import org.antlr.v4.test.runtime.BaseRuntimeTest; +import org.antlr.v4.test.runtime.RuntimeTestDescriptor; +import org.antlr.v4.test.runtime.descriptors.FullContextParsingDescriptors; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class TestFullContextParsing extends BaseRuntimeTest { + public TestFullContextParsing(RuntimeTestDescriptor descriptor) { + super(descriptor,new BasePHPTest()); + } + + @Parameterized.Parameters(name="{0}") + public static RuntimeTestDescriptor[] getAllTestDescriptors() { + return BaseRuntimeTest.getRuntimeTestDescriptors(FullContextParsingDescriptors.class, "PHP"); + } +} diff --git a/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestLeftRecursion.java b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestLeftRecursion.java new file mode 100644 index 000000000..cb200ef38 --- /dev/null +++ b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestLeftRecursion.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. + * Use of this file is governed by the BSD 3-clause license that + * can be found in the LICENSE.txt file in the project root. + */ + +package org.antlr.v4.test.runtime.php; + +import org.antlr.v4.test.runtime.BaseRuntimeTest; +import org.antlr.v4.test.runtime.RuntimeTestDescriptor; +import org.antlr.v4.test.runtime.descriptors.LeftRecursionDescriptors; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class TestLeftRecursion extends BaseRuntimeTest { + public TestLeftRecursion(RuntimeTestDescriptor descriptor) { + super(descriptor,new BasePHPTest()); + } + + @Parameterized.Parameters(name="{0}") + public static RuntimeTestDescriptor[] getAllTestDescriptors() { + return BaseRuntimeTest.getRuntimeTestDescriptors(LeftRecursionDescriptors.class, "PHP"); + } +} diff --git a/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestLexerErrors.java b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestLexerErrors.java new file mode 100644 index 000000000..cd7a5c596 --- /dev/null +++ b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestLexerErrors.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. + * Use of this file is governed by the BSD 3-clause license that + * can be found in the LICENSE.txt file in the project root. + */ + +package org.antlr.v4.test.runtime.php; + +import org.antlr.v4.test.runtime.BaseRuntimeTest; +import org.antlr.v4.test.runtime.RuntimeTestDescriptor; +import org.antlr.v4.test.runtime.descriptors.LexerErrorsDescriptors; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class TestLexerErrors extends BaseRuntimeTest { + public TestLexerErrors(RuntimeTestDescriptor descriptor) { + super(descriptor,new BasePHPTest()); + } + + @Parameterized.Parameters(name="{0}") + public static RuntimeTestDescriptor[] getAllTestDescriptors() { + return BaseRuntimeTest.getRuntimeTestDescriptors(LexerErrorsDescriptors.class, "PHP"); + } +} diff --git a/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestLexerExec.java b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestLexerExec.java new file mode 100644 index 000000000..03595f564 --- /dev/null +++ b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestLexerExec.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. + * Use of this file is governed by the BSD 3-clause license that + * can be found in the LICENSE.txt file in the project root. + */ + +package org.antlr.v4.test.runtime.php; + +import org.antlr.v4.test.runtime.BaseRuntimeTest; +import org.antlr.v4.test.runtime.RuntimeTestDescriptor; +import org.antlr.v4.test.runtime.descriptors.LexerExecDescriptors; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class TestLexerExec extends BaseRuntimeTest { + public TestLexerExec(RuntimeTestDescriptor descriptor) { + super(descriptor,new BasePHPTest()); + } + + @Parameterized.Parameters(name="{0}") + public static RuntimeTestDescriptor[] getAllTestDescriptors() { + return BaseRuntimeTest.getRuntimeTestDescriptors(LexerExecDescriptors.class, "PHP"); + } +} diff --git a/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestListeners.java b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestListeners.java new file mode 100644 index 000000000..52260158d --- /dev/null +++ b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestListeners.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. + * Use of this file is governed by the BSD 3-clause license that + * can be found in the LICENSE.txt file in the project root. + */ + +package org.antlr.v4.test.runtime.php; + +import org.antlr.v4.test.runtime.BaseRuntimeTest; +import org.antlr.v4.test.runtime.RuntimeTestDescriptor; +import org.antlr.v4.test.runtime.descriptors.ListenersDescriptors; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class TestListeners extends BaseRuntimeTest { + public TestListeners(RuntimeTestDescriptor descriptor) { + super(descriptor,new BasePHPTest()); + } + + @Parameterized.Parameters(name="{0}") + public static RuntimeTestDescriptor[] getAllTestDescriptors() { + return BaseRuntimeTest.getRuntimeTestDescriptors(ListenersDescriptors.class, "PHP"); + } +} diff --git a/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestParseTrees.java b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestParseTrees.java new file mode 100644 index 000000000..656e14d71 --- /dev/null +++ b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestParseTrees.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. + * Use of this file is governed by the BSD 3-clause license that + * can be found in the LICENSE.txt file in the project root. + */ + +package org.antlr.v4.test.runtime.php; + +import org.antlr.v4.test.runtime.BaseRuntimeTest; +import org.antlr.v4.test.runtime.RuntimeTestDescriptor; +import org.antlr.v4.test.runtime.descriptors.ParseTreesDescriptors; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class TestParseTrees extends BaseRuntimeTest { + public TestParseTrees(RuntimeTestDescriptor descriptor) { + super(descriptor,new BasePHPTest()); + } + + @Parameterized.Parameters(name="{0}") + public static RuntimeTestDescriptor[] getAllTestDescriptors() { + return BaseRuntimeTest.getRuntimeTestDescriptors(ParseTreesDescriptors.class, "PHP"); + } +} diff --git a/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestParserErrors.java b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestParserErrors.java new file mode 100644 index 000000000..ac3ab88ef --- /dev/null +++ b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestParserErrors.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. + * Use of this file is governed by the BSD 3-clause license that + * can be found in the LICENSE.txt file in the project root. + */ + +package org.antlr.v4.test.runtime.php; + +import org.antlr.v4.test.runtime.BaseRuntimeTest; +import org.antlr.v4.test.runtime.RuntimeTestDescriptor; +import org.antlr.v4.test.runtime.descriptors.ParserErrorsDescriptors; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class TestParserErrors extends BaseRuntimeTest { + public TestParserErrors(RuntimeTestDescriptor descriptor) { + super(descriptor,new BasePHPTest()); + } + + @Parameterized.Parameters(name="{0}") + public static RuntimeTestDescriptor[] getAllTestDescriptors() { + return BaseRuntimeTest.getRuntimeTestDescriptors(ParserErrorsDescriptors.class, "PHP"); + } +} diff --git a/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestParserExec.java b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestParserExec.java new file mode 100644 index 000000000..01e3f321c --- /dev/null +++ b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestParserExec.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. + * Use of this file is governed by the BSD 3-clause license that + * can be found in the LICENSE.txt file in the project root. + */ + +package org.antlr.v4.test.runtime.php; + +import org.antlr.v4.test.runtime.BaseRuntimeTest; +import org.antlr.v4.test.runtime.RuntimeTestDescriptor; +import org.antlr.v4.test.runtime.descriptors.ParserExecDescriptors; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class TestParserExec extends BaseRuntimeTest { + public TestParserExec(RuntimeTestDescriptor descriptor) { + super(descriptor,new BasePHPTest()); + } + + @Parameterized.Parameters(name="{0}") + public static RuntimeTestDescriptor[] getAllTestDescriptors() { + return BaseRuntimeTest.getRuntimeTestDescriptors(ParserExecDescriptors.class, "PHP"); + } +} diff --git a/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestPerformance.java b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestPerformance.java new file mode 100644 index 000000000..7459d77d8 --- /dev/null +++ b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestPerformance.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. + * Use of this file is governed by the BSD 3-clause license that + * can be found in the LICENSE.txt file in the project root. + */ + +package org.antlr.v4.test.runtime.php; + +import org.antlr.v4.test.runtime.BaseRuntimeTest; +import org.antlr.v4.test.runtime.RuntimeTestDescriptor; +import org.antlr.v4.test.runtime.descriptors.PerformanceDescriptors; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class TestPerformance extends BaseRuntimeTest { + public TestPerformance(RuntimeTestDescriptor descriptor) { + super(descriptor,new BasePHPTest()); + } + + @Parameterized.Parameters(name="{0}") + public static RuntimeTestDescriptor[] getAllTestDescriptors() { + return BaseRuntimeTest.getRuntimeTestDescriptors(PerformanceDescriptors.class, "PHP"); + } +} diff --git a/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestSemPredEvalLexer.java b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestSemPredEvalLexer.java new file mode 100644 index 000000000..ec7f14efc --- /dev/null +++ b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestSemPredEvalLexer.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. + * Use of this file is governed by the BSD 3-clause license that + * can be found in the LICENSE.txt file in the project root. + */ + +package org.antlr.v4.test.runtime.php; + +import org.antlr.v4.test.runtime.BaseRuntimeTest; +import org.antlr.v4.test.runtime.RuntimeTestDescriptor; +import org.antlr.v4.test.runtime.descriptors.SemPredEvalLexerDescriptors; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class TestSemPredEvalLexer extends BaseRuntimeTest { + public TestSemPredEvalLexer(RuntimeTestDescriptor descriptor) { + super(descriptor,new BasePHPTest()); + } + + @Parameterized.Parameters(name="{0}") + public static RuntimeTestDescriptor[] getAllTestDescriptors() { + return BaseRuntimeTest.getRuntimeTestDescriptors(SemPredEvalLexerDescriptors.class, "PHP"); + } +} diff --git a/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestSemPredEvalParser.java b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestSemPredEvalParser.java new file mode 100644 index 000000000..1441444c5 --- /dev/null +++ b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestSemPredEvalParser.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. + * Use of this file is governed by the BSD 3-clause license that + * can be found in the LICENSE.txt file in the project root. + */ + +package org.antlr.v4.test.runtime.php; + +import org.antlr.v4.test.runtime.BaseRuntimeTest; +import org.antlr.v4.test.runtime.RuntimeTestDescriptor; +import org.antlr.v4.test.runtime.descriptors.SemPredEvalParserDescriptors; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class TestSemPredEvalParser extends BaseRuntimeTest { + public TestSemPredEvalParser(RuntimeTestDescriptor descriptor) { + super(descriptor,new BasePHPTest()); + } + + @Parameterized.Parameters(name="{0}") + public static RuntimeTestDescriptor[] getAllTestDescriptors() { + return BaseRuntimeTest.getRuntimeTestDescriptors(SemPredEvalParserDescriptors.class, "PHP"); + } +} diff --git a/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestSets.java b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestSets.java new file mode 100644 index 000000000..996045361 --- /dev/null +++ b/runtime-testsuite/test/org/antlr/v4/test/runtime/php/TestSets.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. + * Use of this file is governed by the BSD 3-clause license that + * can be found in the LICENSE.txt file in the project root. + */ + +package org.antlr.v4.test.runtime.php; + +import org.antlr.v4.test.runtime.BaseRuntimeTest; +import org.antlr.v4.test.runtime.RuntimeTestDescriptor; +import org.antlr.v4.test.runtime.descriptors.SetsDescriptors; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class TestSets extends BaseRuntimeTest { + public TestSets(RuntimeTestDescriptor descriptor) { + super(descriptor,new BasePHPTest()); + } + + @Parameterized.Parameters(name="{0}") + public static RuntimeTestDescriptor[] getAllTestDescriptors() { + return BaseRuntimeTest.getRuntimeTestDescriptors(SetsDescriptors.class, "PHP"); + } +} diff --git a/runtime/PHP b/runtime/PHP new file mode 160000 index 000000000..9e1b759d0 --- /dev/null +++ b/runtime/PHP @@ -0,0 +1 @@ +Subproject commit 9e1b759d02220eedf477771169bdfb6a186a2984 diff --git a/tool/resources/org/antlr/v4/tool/templates/codegen/PHP/PHP.stg b/tool/resources/org/antlr/v4/tool/templates/codegen/PHP/PHP.stg new file mode 100644 index 000000000..5376d3566 --- /dev/null +++ b/tool/resources/org/antlr/v4/tool/templates/codegen/PHP/PHP.stg @@ -0,0 +1,1231 @@ +/* + * [The "BSD license"] + * Copyright (c) 2012-2016 Terence Parr + * Copyright (c) 2012-2016 Sam Harwell + * 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. + */ + +phpTypeInitMap ::= [ + "int":"0", + "long":"0", + "float":"0.0", + "double":"0.0", + "boolean":"false", + default:"null" +] + +// args must be , + +ParserFile(file, parser, namedActions, contextSuperClass) ::= << + + +>> + +ListenerFile(file, header, namedActions) ::= << + + +namespace ; + +

+use Antlr\\Antlr4\\Runtime\\Tree\\ParseTreeListener; + +/** + * This interface defines a complete listener for a parse tree produced by + * {@see }. + */ +interface Listener extends ParseTreeListener { + + * Enter a parse tree produced by the `` + * labeled alternative in {@see ::()\}. + + * Enter a parse tree produced by {@see ::()\}. + + * @param $context The parse tree. + */ +public function enter(Context\\Context $context) : void; +/** + + * Exit a parse tree produced by the `` labeled alternative + * in {@see ::()\}. + + * Exit a parse tree produced by {@see ::()\}. + + * @param $context The parse tree. + */ +public function exit(Context\\Context $context) : void;}; separator="\n"> +} +>> + +BaseListenerFile(file, header, namedActions) ::= << + + +namespace ; + +
+ +use Antlr\\Antlr4\\Runtime\\ParserRuleContext; +use Antlr\\Antlr4\\Runtime\\Tree\\ErrorNode; +use Antlr\\Antlr4\\Runtime\\Tree\\TerminalNode; + +/** + * This class provides an empty implementation of {@see Listener}, + * which can be extended to create a listener which only needs to handle a subset + * of the available methods. + */ +class BaseListener implements Listener +{ + (Context\\Context $context) : void {\} + +/** + * {@inheritdoc\} + * + * The default implementation does nothing. + */ +public function exit(Context\\Context $context) : void {\}}; separator="\n"> + + /** + * {@inheritdoc\} + * + * The default implementation does nothing. + */ + public function enterEveryRule(ParserRuleContext $context) : void {} + + /** + * {@inheritdoc\} + * + * The default implementation does nothing. + */ + public function exitEveryRule(ParserRuleContext $context) : void {} + + /** + * {@inheritdoc\} + * + * The default implementation does nothing. + */ + public function visitTerminal(TerminalNode $node) : void {} + + /** + * {@inheritdoc\} + * + * The default implementation does nothing. + */ + public function visitErrorNode(ErrorNode $node) : void {} +} +>> + +VisitorFile(file, header, namedActions) ::= << + + +namespace ; + +
+use Antlr\\Antlr4\\Runtime\\Tree\\ParseTreeVisitor; + +/** + * This interface defines a complete generic visitor for a parse tree produced + by {@see }. + */ +interface Visitor extends ParseTreeVisitor +{ + + * Visit a parse tree produced by the `` labeled alternative + * in {@see ::()\}. + + * Visit a parse tree produced by {@see ::()\}. + + * @param Context $context The parse tree. + * + * @return mixed The visitor result. + */ +public function visit(Context\\Context $context);}; separator="\n\n"> +} +>> + +BaseVisitorFile(file, header, namedActions) ::= << + + +namespace ; + +
+use Antlr\\Antlr4\\Runtime\\Tree\\AbstractParseTreeVisitor; + +/** + * This class provides an empty implementation of {@see Visitor}, + * which can be extended to create a visitor which only needs to handle a subset + * of the available methods. + */ +class BaseVisitor extends AbstractParseTreeVisitor implements Visitor +{ + (Context\\Context $context) +{ + return $this->visitChildren($context); +\}}; separator="\n\n"> +} +>> + +fileHeader(grammarFileName, ANTLRVersion) ::= << +\ by ANTLR +>> +Parser(parser, funcs, atn, sempredFuncs, superClass) ::= << + +>> + +Parser_(parser, funcs, atn, sempredFuncs, ctor, superClass) ::= << +namespace { + + use Antlr\\Antlr4\\Runtime\\Atn\\ATN; + use Antlr\\Antlr4\\Runtime\\Atn\\ATNDeserializer; + use Antlr\\Antlr4\\Runtime\\Atn\\ParserATNSimulator; + use Antlr\\Antlr4\\Runtime\\Dfa\\DFA; + use Antlr\\Antlr4\\Runtime\\Error\\Exceptions\\FailedPredicateException; + use Antlr\\Antlr4\\Runtime\\Error\\Exceptions\\NoViableAltException; + use Antlr\\Antlr4\\Runtime\\PredictionContexts\\PredictionContextCache; + use Antlr\\Antlr4\\Runtime\\Error\\Exceptions\\RecognitionException; + use Antlr\\Antlr4\\Runtime\\RuleContext; + use Antlr\\Antlr4\\Runtime\\Token; + use Antlr\\Antlr4\\Runtime\\TokenStream; + use Antlr\\Antlr4\\Runtime\\Vocabulary; + use Antlr\\Antlr4\\Runtime\\VocabularyImpl; + use Antlr\\Antlr4\\Runtime\\RuntimeMetaData; + use Antlr\\Antlr4\\Runtime\\Parser; + + + final class extends + { + + public const = }; separator=", ", wrap, anchor>; + + + public const = }; separator=", ", wrap, anchor>; + + /** + * @var array\ + */ + public const RULE_NAMES = [ + '}; separator=", ", wrap, anchor> + ]; + + + + + protected static $atn; + protected static $decisionToDFA; + protected static $sharedContextCache; + + + + + + + + + private static function initialize() : void + { + if (self::$atn !== null) { + return; + } + + RuntimeMetaData::checkVersion('', RuntimeMetaData::VERSION); + + $atn = (new ATNDeserializer())->deserialize(self::SERIALIZED_ATN); + + $decisionToDFA = []; + for ($i = 0, $count = $atn->getNumberOfDecisions(); $i \< $count; $i++) { + $decisionToDFA[] = new DFA($atn->getDecisionState($i), $i); + } + + self::$atn = $atn; + self::$decisionToDFA = $decisionToDFA; + self::$sharedContextCache = new PredictionContextCache(); + } + + public function getGrammarFileName() : string + { + return ""; + } + + public function getRuleNames() : array + { + return self::RULE_NAMES; + } + + public function getSerializedATN() : string + { + return self::SERIALIZED_ATN; + } + + public function getATN() : ATN + { + return self::$atn; + } + + public function getVocabulary() : Vocabulary + { + static $vocabulary; + + return $vocabulary = $vocabulary ?? new VocabularyImpl(self::LITERAL_NAMES, self::SYMBOLIC_NAMES); + } + + + + + + + public function sempred(?RuleContext $localContext, int $ruleIndex, int $predicateIndex) : bool + { + switch ($ruleIndex) { + : + return $this->sempred($localContext, $predicateIndex);}; separator="\n\n"> + + default: + return true; + } + } + + + + } +} + +namespace \\Context { + use Antlr\\Antlr4\\Runtime\\ParserRuleContext; + use Antlr\\Antlr4\\Runtime\\Token; + use Antlr\\Antlr4\\Runtime\\Tree\\ParseTreeVisitor; + use Antlr\\Antlr4\\Runtime\\Tree\\TerminalNode; + use Antlr\\Antlr4\\Runtime\\Tree\\ParseTreeListener; + use \\; + use \\Visitor; + use \\Listener; + + + }; separator="\n\n"> + }; separator="\n\n">}> +} +>> + +vocabulary(literalNames, symbolicNames) ::= << +/** + * @var array\ + */ +private const LITERAL_NAMES = [ + }; null="null", separator=", ", wrap, anchor> +]; + +/** + * @var array\ + */ +private const SYMBOLIC_NAMES = [ + }; null="null", separator=", ", wrap, anchor> +]; +>> + +dumpActions(recog, argFuncs, actionFuncs, sempredFuncs) ::= << + + +public function action(?RuleContext $localContext, int $ruleIndex, int $actionIndex) : void +{ + switch ($ruleIndex) { + : + $this->action($localContext, $actionIndex); + + break;}; separator="\n\n"> + } +} + + + + + +public function sempred(?RuleContext $localContext, int $ruleIndex, int $predicateIndex) : bool +{ + switch ($ruleIndex) { + : + return $this->sempred($localContext, $predicateIndex);}; separator="\n\n"> + } + + return true; +} + + +>> + +parser_ctor(p) ::= << +public function __construct(TokenStream $input) +{ + parent::__construct($input); + + self::initialize(); + + $this->interp = new ParserATNSimulator($this, self::$atn, self::$decisionToDFA, self::$sharedContextCache); +} +>> + +/** + * This generates a private method since the actionIndex is generated, making + * an overriding implementation impossible to maintain. + */ +RuleActionFunction(r, actions) ::= << +private function action(? $localContext, int $actionIndex) : void +{ + switch ($actionIndex) { + : + + + break;}; separator="\n\n"> + } +} +>> + +/** + * This generates a private method since the predicateIndex is generated, making + * an overriding implementation impossible to maintain. + */ +RuleSempredFunction(r, actions) ::= << +private function sempred(?Context\\ $localContext, int $predicateIndex) : bool +{ + switch ($predicateIndex) { + : + return ;}; separator="\n\n"> + } + + return true; +} +>> + +RuleFunction(currentRule,args,code,locals,ruleCtx,altLabelCtxs,namedActions,finallyAction,exceptions,postamble) ::= << +/** + * @throws RecognitionException + */ + }>public function () : Context\\ +{ + $localContext = new Context\\($this->ctx, $this->getState()}>); + + $this->enterRule($localContext, , ::RULE_); + + + + try { + + + + } catch (RecognitionException $exception) { + $localContext->exception = $exception; + $this->errorHandler->reportError($this, $exception); + $this->errorHandler->recover($this, $exception); + } finally { + + $this->exitRule(); + } + + return $localContext; +} +>> + +LeftRecursiveRuleFunction(currentRule,args,code,locals,ruleCtx,altLabelCtxs,namedActions,finallyAction,postamble) ::= << +/** + * @throws RecognitionException + */ + }>public function () : Context\\ +{ + return $this->recursive(0}>); +} + +/** + * @throws RecognitionException + */ +private function recursive(int $precedence}>) : Context\\ +{ + $parentContext = $this->ctx; + $parentState = $this->getState(); + $localContext = new Context\\($this->ctx, $parentState}>); + $previousContext = $localContext; + $startState = ; + $this->enterRecursionRule($localContext, , ::RULE_, $precedence); + + + + try { + + + + } catch (RecognitionException $exception) { + $localContext->exception = $exception; + $this->errorHandler->reportError($this, $exception); + $this->errorHandler->recover($this, $exception); + } finally { + + $this->unrollRecursionContexts($parentContext); + } + + return $localContext; +} +>> + +CodeBlockForOuterMostAlt(currentOuterMostAltCodeBlock, locals, preamble, ops) ::= << +$localContext = new Context\\Context($localContext); +$this->enterOuterAlt($localContext, ); + +>> + +CodeBlockForAlt(currentAltCodeBlock, locals, preamble, ops) ::= << + + + +>> + +LL1AltBlock(choice, preamble, alts, error) ::= << +$this->setState(); +$this->errorHandler->sync($this); + = $this->input->LT(1); + + +switch ($this->input->LA(1)) { + + + break;}; separator="\n\n"> + +default: + +} +>> + +LL1OptionalBlock(choice, alts, error) ::= << +$this->setState(); +$this->errorHandler->sync($this); + +switch ($this->input->LA(1)) { + + + break;}; separator="\n\n"> + +default: + break; +} +>> + +LL1OptionalBlockSingleAlt(choice, expr, alts, preamble, error, followExpr) ::= << +$this->setState(); +$this->errorHandler->sync($this); + + +if () { + +} +>> + +LL1StarBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= << +$this->setState(); +$this->errorHandler->sync($this); + + +while () { + + $this->setState(); + $this->errorHandler->sync($this); + +} +>> + +LL1PlusBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= << +$this->setState(); +$this->errorHandler->sync($this); + + +do { + + $this->setState(); + $this->errorHandler->sync($this); + +} while (); +>> + +// LL(*) stuff + +AltBlock(choice, preamble, alts, error) ::= << +$this->setState(); +$this->errorHandler->sync($this); + = $this->input->LT(1); + + +switch ($this->getInterpreter()->adaptivePredict($this->input, , $this->ctx)) { + : + +break;}; separator="\n\n"> +} +>> + +OptionalBlock(choice, alts, error) ::= << +$this->setState(); +$this->errorHandler->sync($this); + +switch ($this->getInterpreter()->adaptivePredict($this->input, , $this->ctx)) { ++1: + + break;}; separator="\n\n"> +} +>> + +StarBlock(choice, alts, sync, iteration) ::= << +$this->setState(); +$this->errorHandler->sync($this); + +$alt = $this->getInterpreter()->adaptivePredict($this->input, , $this->ctx); + +while ($alt !== && $alt !== ATN::INVALID_ALT_NUMBER) { + if ($alt === 1+1) { + + + } + + $this->setState(); + $this->errorHandler->sync($this); + + $alt = $this->getInterpreter()->adaptivePredict($this->input, , $this->ctx); +} +>> + +PlusBlock(choice, alts, error) ::= << +$this->setState(); +$this->errorHandler->sync($this); + +$alt = 1+1; + +do { + switch ($alt) { + +1: + + + break;}; separator="\n\n"> + default: + + } + + $this->setState(); + $this->errorHandler->sync($this); + + $alt = $this->getInterpreter()->adaptivePredict($this->input, , $this->ctx); +} while ($alt !== && $alt !== ATN::INVALID_ALT_NUMBER); +>> + +Sync(s) ::= "sync();" + +ThrowNoViableAlt(t) ::= "throw new NoViableAltException($this);" + +TestSetInline(s) ::= << +}; separator=" || "> +>> + +// 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) ::= <% +(})> && ((1 \<\< ) & ()}; separator=" | ">)) !== 0) +%> + +isZero ::= [ +"0":true, +default:false +] + +offsetShiftVar(shiftAmount, offset) ::= <% +($ - )$ +%> +offsetShiftConst(shiftAmount, offset) ::= <% +(self:: - )self:: +%> + +// produces more efficient bytecode when bits.ttypes contains at most two items +bitsetInlineComparison(s, bits) ::= <% + === self::}; separator=" || "> +%> + +cases(ttypes) ::= << +:::}; separator="\n"> +>> + +InvokeRule(r, argExprsChunks) ::= << +$this->setState(); + = }>$this->recursive(,); +>> + +MatchToken(m) ::= << +$this->setState(); + = }>$this->match(::); +>> + +MatchSet(m, expr, capture) ::= "" + +MatchNotSet(m, expr, capture) ::= "" + +CommonSetStuff(m, expr, capture, invert) ::= << +$this->setState(); + + = }>$this->input->LT(1); + + +if ($ \<= 0 || !()) { + = }>$this->errorHandler->recoverInline($this); +} else { + if ($this->input->LA(1) === Token::EOF) { + $this->matchedEOF = true; + } + + $this->errorHandler->reportMatch($this); + $this->consume(); +} +>> + +Wildcard(w) ::= << +$this->setState(); + = }>$this->matchWildcard(); +>> + +// ACTION STUFF + +Action(a, foo, chunks) ::= "" + +ArgAction(a, chunks) ::= "" + +SemPred(p, chunks, failChunks) ::= << +$this->setState(); + +if (!()) { + throw new FailedPredicateException($this, , , ); +} +>> + +ExceptionClause(e, catchArg, catchAction) ::= << +catch () { + +} +>> + +// lexer actions are not associated with model objects + +LexerSkipCommand() ::= "$this->skip();" +LexerMoreCommand() ::= "$this->more();" +LexerPopModeCommand() ::= "$this->popMode();" + +LexerTypeCommand(arg, grammar) ::= "$this->type = ;" +LexerChannelCommand(arg, grammar) ::= "$this->channel = ;" +LexerModeCommand(arg, grammar) ::= "$this->mode = ;" +LexerPushModeCommand(arg, grammar) ::= "$this->pushMode();" + +ActionText(t) ::= "" +ActionTemplate(t) ::= "" +ArgRef(a) ::= "$localContext->" +LocalRef(a) ::= "$localContext->" +RetValueRef(a) ::= "$localContext->" +QRetValueRef(a) ::= "->->" +/** How to translate $tokenLabel */ +TokenRef(t) ::= "->" +LabelRef(t) ::= "->" +ListLabelRef(t) ::= "->" +SetAttr(s,rhsChunks) ::= "-> = ;" + +TokenLabelType() ::= "" +InputSymbolType() ::= "" + +TokenPropertyRef_text(t) ::= "(-> !== null ? ->->getText() : null)" +TokenPropertyRef_type(t) ::= "(-> !== null ? ->->getType() : 0)" +TokenPropertyRef_line(t) ::= "(-> !== null ? ->->getLine() : 0)" +TokenPropertyRef_pos(t) ::= "(-> !== null ? ->->getCharPositionInLine() : 0)" +TokenPropertyRef_channel(t) ::= "(-> !== null ? ->->getChannel() : 0)" +TokenPropertyRef_index(t) ::= "(-> !== null ? ->->getTokenIndex() : 0)" +TokenPropertyRef_int(t) ::= "(-> !== null ? (int) ->->getText() : 0)" + +RulePropertyRef_start(r) ::= "(-> !== null ? (->->start) : null)" +RulePropertyRef_stop(r) ::= "(-> !== null ? (->->stop) : null)" +RulePropertyRef_text(r) ::= "(-> !== null ? $this->input->getTextByTokens(->->start, ->->stop) : null)" +RulePropertyRef_ctx(r) ::= "->" +RulePropertyRef_parser(r)::= "\$this" + +ThisRulePropertyRef_start(r) ::= "$localContext->start" +ThisRulePropertyRef_stop(r) ::= "$localContext->stop" +ThisRulePropertyRef_text(r) ::= "$this->input->getTextByTokens($localContext->start, $this->input->LT(-1))" +ThisRulePropertyRef_ctx(r) ::= "$localContext" +ThisRulePropertyRef_parser(r)::= "$this" + +NonLocalAttrRef(s) ::= "\$this->getInvokingContext()->" +SetNonLocalAttr(s, rhsChunks) ::= "\$this->getInvokingContext()-> = ;" + +AddToLabelList(a) ::= "->[] = ;" + +TokenDecl(t) ::= " $" +TokenTypeDecl(t) ::= "" +TokenListDecl(t) ::= "array $ = []" +RuleContextDecl(r) ::= " $" +RuleContextListDecl(rdecl) ::= "array $ = []" +AttributeDecl(d) ::= " $ = " + +PropertiesDecl(struct) ::= << + + |null $ + */ +public $;}; separator="\n\n"> + + + + + + |null $ + */ +public $;}; separator="\n\n"> + + + + + + |null $ + */ +public $;}; separator="\n\n"> + + + + + + \>|null $ + */ +public $;}; separator="\n\n"> + + + + + + |null $ + */ +public $ = ;}; separator="\n\n"> + + +>> + +ContextTokenGetterDecl(t) ::= << +public function () : ?TerminalNode +{ + return $this->getToken(::, 0); +} +>> + +ContextTokenListGetterDecl(t) ::= << +>> + +ContextTokenListIndexedGetterDecl(t) ::= << +/** + * @return array\|TerminalNode|null + */ +public function (?int $index = null) +{ + if ($index === null) { + return $this->getTokens(::); + } + + return $this->getToken(::, $index); +} +>> + +ContextRuleGetterDecl(r) ::= << +public function () : ? +{ + return $this->getTypedRuleContext(::class, 0); +} +>> + +ContextRuleListGetterDecl(r) ::= << +>> + +ContextRuleListIndexedGetterDecl(r) ::= << +/** + * @return array\<\>||null + */ +public function (?int $index = null) +{ + if ($index === null) { + return $this->getTypedRuleContexts(::class); + } + + return $this->getTypedRuleContext(::class, $index); +} +>> + +LexerRuleContext() ::= "RuleContext" + +/** + * The rule context name is the rule followed by a suffix; e.g., r becomes rContext. + */ +RuleContextNameSuffix() ::= "Context" + +ImplicitTokenLabel(tokenName) ::= "" +ImplicitRuleLabel(ruleName) ::= "" +ImplicitSetLabel(id) ::= "_tset" +ListLabelName(label) ::= "

." +PositionAdjustingLexerDef() ::= "" + PositionAdjustingLexer() ::= << public override IToken NextToken() { diff --git a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Chrome.test.stg b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Chrome.test.stg index e02457a90..070409c21 100644 --- a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Chrome.test.stg +++ b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Chrome.test.stg @@ -14,6 +14,8 @@ Cast(t,v) ::= "" Append(a,b) ::= " + " +AppendStr(a,b) ::= <%%> + Concat(a,b) ::= "" DeclareLocal(s,v) ::= "var = ;" @@ -26,6 +28,12 @@ InitIntMember(n,v) ::= <%this. = ;%> InitBooleanMember(n,v) ::= <%this. = ;%> +InitIntVar(n,v) ::= <%%> + +IntArg(n) ::= "" + +VarRef(n) ::= "" + GetMember(n) ::= <%this.%> SetMember(n,v) ::= <%this. = ;%> @@ -92,6 +100,8 @@ this.Property = function() { } >> +PositionAdjustingLexerDef() ::= "" + PositionAdjustingLexer() ::= << PositionAdjustingLexer.prototype.resetAcceptPosition = function(index, line, column) { diff --git a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Cpp.test.stg b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Cpp.test.stg index c2b1a7f84..bd3f0dd79 100644 --- a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Cpp.test.stg +++ b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Cpp.test.stg @@ -9,6 +9,7 @@ Assert(s) ::= "" Cast(t,v) ::= "dynamic_cast\< *>()" // Should actually use a more specific name. We may have to use other casts as well. Append(a,b) ::= " + ->toString()" Concat(a,b) ::= "" +AppendStr(a,b) ::= " + " DeclareLocal(s,v) ::= " = " @@ -17,6 +18,9 @@ AssignLocal(s,v) ::= " = ;" InitIntMember(n,v) ::= "int = ;" InitBooleanMember(n,v) ::= "bool = ;" +InitIntVar(n,v) ::= <%%> +IntArg(n) ::= "int " +VarRef(n) ::= "" GetMember(n) ::= "" SetMember(n,v) ::= " = ;" @@ -68,6 +72,8 @@ bool Property() { ParserPropertyCall(p, call) ::= "" +PositionAdjustingLexerDef() ::= "" + PositionAdjustingLexer() ::= << protected: class PositionAdjustingLexerATNSimulator : public antlr4::atn::LexerATNSimulator { diff --git a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Explorer.test.stg b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Explorer.test.stg index 6cfe9ba27..a3d4cb026 100644 --- a/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Explorer.test.stg +++ b/runtime-testsuite/resources/org/antlr/v4/test/runtime/templates/Explorer.test.stg @@ -14,6 +14,8 @@ Cast(t,v) ::= "" Append(a,b) ::= " + " +AppendStr(a,b) ::= <%%> + Concat(a,b) ::= "" DeclareLocal(s,v) ::= "var = ;" @@ -26,6 +28,12 @@ InitIntMember(n,v) ::= <%this. = ;%> InitBooleanMember(n,v) ::= <%this. = ;%> +InitIntVar(n,v) ::= <%%> + +IntArg(n) ::= "" + +VarRef(n) ::= "" + GetMember(n) ::= <%this.%> SetMember(n,v) ::= <%this. = ;%> @@ -98,6 +106,8 @@ this.Property = function() { ParserPropertyCall(p, call) ::= "