TypeScript Parser - syntax tree

Topics: General
Mar 20, 2014 at 2:52 PM
Edited Mar 20, 2014 at 2:54 PM
Is there a way to access the typescript source files' syntax tree using node or typescript.
I am currently implementing a documentation module and it would be really helpful if I can manage to access the code model of the source ts files at hand.
As for me to iterate through it.

Thank you,
Moe
Coordinator
Mar 20, 2014 at 4:55 PM
Edited Mar 20, 2014 at 4:56 PM
In one line:
var parseResult = TypeScript.Parser.parse('foo.ts', TypeScript.SimpleText.fromString(fileContent), false, new TypeScript.ParseOptions(TypeScript.LanguageVersion.EcmaScript5, true));
See also http://stackoverflow.com/a/20197641/1704166
Sep 28, 2014 at 5:13 PM
I'm trying to parse TypeScript code to recognize and mantain user added code (methods, var declarations, classes) to an autogenerated TypeScript source.
Obviouvsly the best way to do this is to use TypeScript parser that mantains also leading and trailing triva!
Thanks to your example I'm now at 99% of the work.
But when I need to signal as an error some kind of non permitted operations to my user, I can't find in tree nodes info about line/column or absolute start position of the token itself. Methods like .fullText() and .text() and .fullWidth() are great, but what about position (the same you use to report error in the form of line/column info)?
Is there some other kind of method I can call to get a more detailed AST?
p.s. thanks you and all the team for your great and awesome work!
Coordinator
Sep 29, 2014 at 5:25 PM
Edited Sep 29, 2014 at 5:26 PM
you will need to use line maps to get you the mapping from the position to line, character. Please note that we have moved to github: https://github.com/Microsoft/TypeScript, and we are now working on a revamped code base, where trees look significantly different.

See https://github.com/Microsoft/TypeScript/blob/master/src/compiler/tsc.ts#L88 for how the compiler does it.
Oct 1, 2014 at 10:01 AM
At the moment I've solved recumputating the start offset (this is the key info missed) for each node/token with a full tree walk using the .fullLength of each node/token. Then to obtain line/row from offset than I'm obviusly using line maps and internal TS helper function.
I know you are rewriting a full new version of the compiler and I'm ready to review all my code when the next version of TS with the new compiler will be released.