我需要一种在 Rascal 中序列化数据的方法,因为某些操作可能相对较慢,并且需要某种快速形式的缓存。例如 AST 的构建。
我使用以下代码段从项目的指定位置构建 AST:
list[Declaration] getASTs(loc projectLocation) {
M3 model = createM3FromMavenProject(projectLocation);
list[Declaration] asts = [createAstFromFile(f, true)
| f <- files(model.containment), isCompilationUnit(f)];
return asts;
}
Run Code Online (Sandbox Code Playgroud)
现在构建一个特定的 AST 需要一些时间(大约 2-3 秒)。因此,我希望将结果缓存在某个转储文件中:
loc smallsqlLoc = projectLoc + "smallsql0.21_src";
loc dumpLoc = projectLoc + "dump/smallsql.bin";
if(!exists(dumpLoc)) {
list[Declaration] dumpAsts = getASTs(smallsqlLoc);
writeFile(dumpLoc, dumpAsts);
}
Run Code Online (Sandbox Code Playgroud)
并将其读回内存(希望会更快):
if(!exists(dumpLoc))
throw "Error: dump does not exist.";
list[Declaration] asts = readFile(dumpLoc);
Run Code Online (Sandbox Code Playgroud)
但 readFile 的返回类型是str, 不是list[Declaration]。简单的强制转换显然不能解决问题。如何将最初写入文件的 AST 恢复到内存中?更一般地说,如何在 Rascal 中对文件中的任何数据类型进行序列化和反序列化?