【问题标题】:Parsing rhino script for imports解析 rhino 脚本以进行导入
【发布时间】:2018-02-07 11:55:11
【问题描述】:

我需要找到在 rhino 脚本中使用的所有导入。例如,像这样的进口:- importPackage(Packages.org.json) importPackage(Packages.java.lang)

var jsonResponse = (Packages.java.lang.String)(xyz 代码)。

如何使用 rhino parser/ast 有效地实现这一点?

【问题讨论】:

    标签: java rhino


    【解决方案1】:

    我通过以下方式实现了所需(如果其他人偶然发现了这个问题): 我使用了 mozilla 的 javascript 解析器,它给了我一个 AstNode。有了这个 AstNode 后,我创建了另一个实现 mozilla NodeVisitor 的类,并在该类中根据需要覆盖访问方法。

    这里是代码 sn-ps :-

    public class ASTtry {
    static class Visitor implements NodeVisitor {
        List<String> ls;
    
        Visitor(List<String> loc) {
            ls = loc;
        }
    
        @Override
        public boolean visit(AstNode node) {
            if (node instanceof Name) {
                ls.add(node.getString());
            }
            if (node instanceof Loop) {
                int type = node.getType();
                ls.add(Token.typeToName(type));
            }
            return true;
        }
    }
    
    public static void main(String[] args) throws IOException {
        ASTtry ast = new ASTtry();
        CompilerEnvirons env = new CompilerEnvirons();
        setEnvironmentVariables(env);
        File scriptFile = new File("whatever path my file was");
        FileReader fr = new FileReader(scriptFile);
        AstNode root = new Parser(env).parse(fr, null, 1);
        List<String> allTokens = new ArrayList<>();
        root.visit(new Visitor(allTokens));
        Properties properties = new Properties();
        InputStream propFile;
        propFile = new FileInputStream("I had imports seperated by commas in this file");
        properties.load(propFile);
        ast.check(properties, allTokens);
    }
    
    private static void setEnvironmentVariables(CompilerEnvirons env) {
        env.setRecordingLocalJsDocComments(true);
        env.setAllowSharpComments(true);
        env.setRecordingComments(true);
        env.setIdeMode(true);
        env.setErrorReporter(new ErrReporter());
        env.setRecoverFromErrors(true);
        env.setGenerateObserverCount(true);
    }
    
    public boolean check(Properties properties, List<String> loc) {
        once I had all the lines of code, imports, i can easily loop around them for all the validations I need.
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-14
      • 2014-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-10
      • 2015-09-23
      相关资源
      最近更新 更多