- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
public static AstRoot parse (String code) {
CompilerEnvirons env = new CompilerEnvirons();
env.setRecoverFromErrors(true);
env.setGenerateDebugInfo(true);
env.setRecordingComments(true);
// try to ignore errors - does not seem to work
env.setIdeMode(true);
IRFactory factory = new IRFactory(env);
AstRoot root = factory.parse(code, null, 0);
// work around rhino bug 800616 (not fixed in neither rhino nor closure)
root.visit(new NodeVisitor() {
@Override
public boolean visit(AstNode node) {
if (node instanceof NumberLiteral) {
NumberLiteral num = (NumberLiteral)node;
int from = num.getAbsolutePosition();
int to = from + num.getLength() + 2;
if (to < code.length()) {
String hex = "0x" + num.toSource();
if (code.substring(from, to).equals(hex)) {
// reset node value and length
num.setValue(hex); num.setLength(hex.length());
}
}
return false;
}
return true;
}
});
// work around rhino SwitchStatement.toSource() bug with empty switches
// https://github.com/mozilla/rhino/blob/master/src/org/mozilla/javascript/ast/SwitchStatement.java#L96
// https://github.com/mozilla/rhino/blob/master/src/org/mozilla/javascript/ast/SwitchStatement.java#L107-L109
// https://github.com/mozilla/rhino/blob/master/src/org/mozilla/javascript/ast/SwitchStatement.java#L158
root.visit(new NodeVisitor() {
@Override
public boolean visit(AstNode node) {
if (node instanceof SwitchStatement) {
SwitchStatement ss = (SwitchStatement)node;
if (ss.getCases().isEmpty()) {
// need to add at least one node to make ss.cases non-null
ArrayList<SwitchCase> cases = new ArrayList<>();
cases.add(new SwitchCase());
ss.setCases(cases);
// set this back to empty list
cases.clear();
ss.setCases(cases);
}
return false;
}
return true;
}
});
return root;
}
И ещё немножко трудовыебуднев пользователей рино: правда клёво взять и распарсить джаваскрипт одним простым методом? Авотхуй.
guest 08.11.2013 20:52 # 0
makc3d 08.11.2013 20:54 # 0
такое генерит тайпскрипт, приходится хавать