TypeScript:获取语法树 [英] TypeScript: get syntax tree
问题描述
我读过整个互联网,但是找不到有关从TypeScrypt来源获取语法树(就像在Esprima中一样)的任何示例。
我的意思是我该如何获取这样的对象( Esprima Parser 示例)
I had read "whole internet", but can't find any examples about getting syntax tree (just like in Esprima) from TypeScrypt source. I mean how can i get object like this (Esprima Parser example)
{
"type": "Program",
"body": [
{
"type": "VariableDeclaration",
"declarations": [
{
"type": "VariableDeclarator",
"id": {
"type": "Identifier",
"name": "answer"
},
"init": {
"type": "BinaryExpression",
"operator": "*",
"left": {
"type": "Literal",
"value": 6,
"raw": "6"
},
"right": {
"type": "Literal",
"value": 7,
"raw": "7"
}
}
}
],
"kind": "var"
}
]
}
来自javascript代码
from javascript code
var answer = 6 * 7;
仅适用于TypeScript源文本吗?
only for TypeScript source text?
聚苯乙烯我非常希望您的帮助,因为我不想写您自己的糟糕自行车。
P.S. I hope very much for your help, because I do not want to write your own terrible bicycle)
P.P.S。我认为lib文件typescript.ts(.js)和typescriptServices.ts(.js)可以帮助我,但是我不知道如何:(
P.P.S. I think the lib files typescript.ts(.js) and typescriptServices.ts(.js) to help me, but I do not know how :(
解决了
非常感谢用户Steve Fenton。
这是我的代码,如果有兴趣的人:
Thanks a lot to the user Steve Fenton. Here is my code, if anyone interested in:
// uses
var typeScriptLS = new Harness.TypeScriptLS();
var ServicesFactory = new Services.TypeScriptServicesFactory();
var serviceShim = ServicesFactory.createLanguageServiceShim(typeScriptLS);
// add lib.d.ts
var _libText = window.document.getElementById('lib.d.ts').innerText;
typeScriptLS.addScript('lib.d.ts', _libText.replace(/\r\n?/g,"\n"), true);
// add greeter.ts
var _sourceText = window.document.getElementById('greeter.ts').innerText;
typeScriptLS.addScript('greeter.ts', _sourceText.replace(/\r\n?/g,"\n"), true);
// script name
var _scriptName = 'greeter.ts';
// get syntax tree
var _st = serviceShim.languageService.getSyntaxTree(_scriptName);
//console.log(_st);
console.log(JSON.stringify(_st, "", 2));
推荐答案
This question came up before back in September.
当前没有任何东西可以帮您实现-没有神奇的 getSyntaxTree
方法可以做到这一点。
There isn't currently something that will do this for you - there is no magic getSyntaxTree
method to call that will do this.
TypeScript编译器是开源的,并且完全用TypeScript编写,因此您可以对其进行扫描以查明是否可以使用/添加句柄。
The TypeScript compiler is open-source, though - and written entirely in TypeScript so you can scan it to find out if there is something you can use / add a handle to.
这样做的好处是,您有很大的机会将您的工作作为开源项目发布,这是根据对两个问题的投票决定的,
The up-side of this is that you have a big opportunity to release your work as an open-source project as judging by the up-votes on the two questions, there is some demand for this.
或者,使用 Esprima 或 SpiderMonkey 。
这篇关于TypeScript:获取语法树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!