How can I parse a javascript class in order to get a list of all its methods?
So far I have tried below parsers:
- [email protected], [email protected] in nodejs
- esprima==4.0.1 in python.
Here's all my attempts:
Nodejs
import * as esprima from "esprima";
import * as acorn from "acorn";
const snippets = [
"class Foo {}", // 0
"class Foo { constructor() {} }", // 1
"class Foo { constructor() {}; bar() {} }", // 2
"class Foo { constructor() {}; bar() {}; baz = () => {}; }", // 3
"let baz = () => {}", // 4
]
console.log("--------esprima--------");
for(let [i,snippet] of Object.entries(snippets)) {
try {
esprima.parseScript(snippet);
console.log(`snippet ${i}: ok`);
} catch(e) {
console.log(`snippet ${i}: failed`);
}
}
console.log("--------acorn--------");
for(let [i,snippet] of Object.entries(snippets)) {
try {
acorn.parse(snippet);
console.log(`snippet ${i}: ok`);
} catch(e) {
console.log(`snippet ${i}: failed`);
}
}
output:
--------esprima--------
snippet 0: ok
snippet 1: ok
snippet 2: ok
snippet 3: failed
snippet 4: ok
--------acorn--------
snippet 0: ok
snippet 1: ok
snippet 2: ok
snippet 3: failed
snippet 4: ok
Python
import esprima
snippets = [
"class Foo {}", # 0
"class Foo { constructor() {} }", # 1
"class Foo { constructor() {}; bar() {} }", # 2
"class Foo { constructor() {}; bar() {}; baz = () => {}; }", # 3
"let baz = () => {}", # 4
]
print("--------esprima--------")
for [i, snippet] in enumerate(snippets):
try:
esprima.parseScript(snippet)
print(f"snippet {i}: ok")
except:
print(f"snippet {i}: failed")
output:
--------esprima--------
snippet 0: ok
snippet 1: ok
snippet 2: ok
snippet 3: failed
snippet 4: ok
As you can see when using arrow functions as methods the above parsers will fail. That's not good as the classes from the project I'm trying to parse/analize will be mostly es9 syntax (await, async, spread operator, arrow function methods, ...).