'Javascript grammar in antlr4 and python
I have used the following link for JavaScript grammar .
https://github.com/antlr/grammars-v4/tree/master/javascript/javascript/Python
i have used antlr4.8 and ntlr4-python3-runtime==4.8. when i use the following code it gives following error .
error:
PS N:\antlr4\sample\py4.8> python main.py test.js
Running
Test started for: test.js
Created parsers
Traceback (most recent call last):
File "main.py", line 25, in <module>
main(sys.argv)
File "main.py", line 20, in main
tree = parser.program()
File "N:\antlr4\sample\py4.8\JavaScriptParser.py", line 880, in program
self.enterRule(localctx, 0, self.RULE_program)
File "C:\Users\root\AppData\Local\Programs\Python\Python38\lib\site-packages\antlr4\Parser.py", line 366, in enterRule
self._ctx.start = self._input.LT(1)
.
.
.
File "N:\antlr4\sample\py4.8\JavaScriptLexer.py", line 919, in sempred
return pred(localctx, predIndex)
File "N:\antlr4\sample\py4.8\JavaScriptLexer.py", line 925, in HashBangLine_sempred
return this.IsStartOfFile()
NameError: name 'this' is not defined
code:
import sys
from antlr4 import *
import JavaScriptLexer
import JavaScriptParser
JSL = JavaScriptLexer.JavaScriptLexer
JSP = JavaScriptParser.JavaScriptParser
class WriteTreeListener(ParseTreeListener):
def visitTerminal(self, node:TerminalNode):
print ("Visit Terminal: " + str(node) + " - " + repr(node))
def main(argv):
input_stream = FileStream(argv[1])
print("Test started for: " + argv[1])
lexer = JSL(input_stream)
stream = CommonTokenStream(lexer)
parser = JSP(stream)
print("Created parsers")
tree = parser.program()
ParseTreeWalker.DEFAULT.walk(WriteTreeListener(), tree)
if __name__ == '__main__':
print("Running")
main(sys.argv)
print("Hello")
What have I done wrong ?
Solution 1:[1]
Replace this
with self
(ref here). Example:
Change
return this.IsStartOfFile()
to
return self.IsStartOfFile()
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | AJH |