获取动态链接库
前提条件:需启动docker
java-tree-sitter项目使用Docker来确保构建环境的一致性。在java-tree-sitter的构建过程中,Docker被用来创建一个包含所有必要依赖的环境,然后在这个环境中编译项目。这样可以确保无论你在哪里构建项目,都能得到相同的结果,避免了"在我机器上可以运行"的问题。
https://github.com/seart-group/java-tree-sitter/tree/v1.0.0
- 按ReadMe介绍,git clone 并下载所有的submodule
- mvn clean build
- 获得动态链接库:
- 在项目路径下执行: ./build.py -o libjava-tree-sitter path-to-tree-sitter-css path-to-tree-sitter-python …
- 默认名为 libjava-tree-sitter,后的参数是需要添加的语言库,可根据需要单选或多选
在 Mac 中生成的库后缀为 .dylib
,笔者得到 libjava-tree-sitter-cpp-c-java.dylib 文件。
引入依赖 & 编码
gradle配置文件中添加如下代码:
implementation 'ch.usi.si.seart:java-tree-sitter:1.0.0'
使用
@Test
public void should_get_structure_feature_of_snippet_by_tree_sitter () { System.load("/Users/author/libjava-tree-sitter-cpp-c-java.dylib"); String source = "Datum g_intbig_compress(PG_FUNCTION_ARGS)\n" + "{\n" + " GISTENTRY* entry = (GISTENTRY*)PG_GETARG_POINTER(0);\n" + "\n" + " if (entry->leafkey) {\n" + " GISTENTRY* retval = NULL;\n" + " ArrayType* in = DatumGetArrayTypeP(entry->key);\n" + " int4* ptr = NULL;\n" + " int num;\n" + " GISTTYPE* res = (GISTTYPE*)palloc0(CALCGTSIZE(0));\n" + "\n" + " CHECKARRVALID(in);\n" + " if (ARRISEMPTY(in)) {\n" + " ptr = NULL;\n" + " num = 0;\n" + " } else {\n" + " ptr = ARRPTR(in);\n" + " num = ARRNELEMS(in);\n" + " }"; try ( Parser parser = new Parser(Language.CPP); Tree tree = parser.parseString(source) ) { Node root = tree.getRootNode(); assertEquals(1, root.getChildCount()); assertEquals("translation_unit", root.getType()); assertEquals(0, root.getStartByte()); assertEquals(512, root.getEndByte()); Node function = root.getChild(0); assertEquals("ERROR", function.getType()); assertEquals(14, function.getChildCount()); } catch (Exception ex) { // ... }
}