antlr4
antlr4 copied to clipboard
Cannot read properties of undefined (reading 'ATNDeserializer') or Python3Lexer.Python3Lexer is not a constructor?
//antlr4Xpy.js
const antlr4 = require('antlr4');
const Python3Lexer = require('./lang_parser/Python3Lexer.js');
const Python3Parser = require('./lang_parser/Python3Parser.js');
function parsePythonFile(filePath) {
const fs = require('fs');
const content = fs.readFileSync(filePath, 'utf-8');
const input = new antlr4.InputStream(content);
const lexer = new Python3Lexer.Python3Lexer(input);
const tokenStream = new antlr4.CommonTokenStream(lexer);
const parser = new Python3Parser.Python3Parser(tokenStream);
const tree = parser.file_input();
console.log(tree.toStringTree(parser));
}
if (process.argv.length > 2) {
const filePath = process.argv[2];
parsePythonFile(filePath);
} else {
console.log('Usage: node antlr4Xpy.js <file.py>');
}
I tried running the above program on Node.js v18.19.0: node antlr4Xpy.js fitting.py It is known that there are the following files generated using antlr4-4.13.2 in the lang_parser subdirectories of the current directory: Python3Lexer.js Python3LexerBase.js Python3Parser.js Python3ParserBase.js Python3ParserListener.js But get:
C:\temp\lang_parser\Python3Lexer.js:3
import antlr4 from 'antlr4';
^^^^^^
SyntaxError: Cannot use import statement outside a module
Import A from B in Python3Lexer.js; Change to A=require ('B '); Run again to obtain:
node antlr4Xpy.js fitting.py
C:\temp\lang_parser\Python3Parser.js:521
const atn = new antlr4.atn.ATNDeserializer().deserialize(serializedATN);
^
TypeError: Cannot read properties of undefined (reading 'ATNDeserializer') at Object.<anonymous> (C:\temp\obsidian-code-outline\lang_parser\Python3Parser.js:521:28)
I replace "antlr4. atn." and "antlr4. dfa" with "antlr4." in lang_parser/*.js and run again to get:
node antlr4Xpy.js fitting.py
C:\temp\obsidian-code-outline\antlr4Xpy.js:11
const lexer = new Python3Lexer.Python3Lexer(input);
^
TypeError: Python3Lexer.Python3Lexer is not a constructor
May I ask if this is a bug in antlr4?
You need to use esm, see https://nodejs.org/api/esm.html
You need to use esm, see https://nodejs.org/api/esm.html
Thank you!