Last active
August 29, 2015 14:16
-
-
Save chrisber/9354ef8327e8fbc8b89e to your computer and use it in GitHub Desktop.
TypeScript Compiler API usage from http://www.scottlogic.com/blog/2015/01/20/typescript-compiler-api.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Blog post from Nicholas Wolverson | |
// http://www.scottlogic.com/blog/2015/01/20/typescript-compiler-api.html | |
function getCompilerOutput(text) { | |
host.addFile(dummyScriptName, text); | |
var output = languageService.getEmitOutput(dummyScriptName).outputFiles; | |
return output && output.length > 0 ? output[0].text : ""; | |
} | |
function getMatchingBracePosition(text, pos) { | |
host.addFile(dummyScriptName, text); | |
var braces = languageService.getBraceMatchingAtPosition(dummyScriptName, pos); | |
return braces.map(function (b) { return b.start(); }); | |
} | |
function getQuickInfo(text, pos) { | |
host.addFile(dummyScriptName, text); | |
var info = languageService.getQuickInfoAtPosition(dummyScriptName, pos); | |
var text = info.displayParts.map(function (x) { return x.text; }).join(""); | |
return text; | |
} | |
function typeDecls(text) { | |
host.addFile(dummyScriptName, text); | |
var program = ts.createProgram([dummyScriptName], host.getCompilationSettings(), host); | |
var typeChecker = program.getTypeChecker(true); | |
var sf = program.getSourceFile(dummyScriptName); | |
var decls = sf.getNamedDeclarations().map(function (nd) { return nd.symbol.name + ": " + typeChecker.typeToString(typeChecker.getTypeAtLocation(nd)); }); | |
return decls.join("\n"); | |
} | |
function getNodes(sf) { | |
var nodes = []; | |
function allNodes(n) { | |
ts.forEachChild(n, function (n) { | |
nodes.push(n); | |
allNodes(n); | |
return false; | |
}); | |
} | |
; | |
allNodes(sf); | |
return nodes; | |
} | |
function typeIdentifiers(text) { | |
host.addFile(dummyScriptName, text); | |
var program = ts.createProgram([dummyScriptName], host.getCompilationSettings(), host); | |
var typeChecker = program.getTypeChecker(true); | |
var sf = program.getSourceFile(dummyScriptName); | |
var idNodes = getNodes(sf).filter(function (n) { return n.kind === 63 /* Identifier */; }); | |
var typed = idNodes.map(function (n) { return n.text + ": " + typeChecker.typeToString(typeChecker.getTypeAtLocation(n)); }); | |
return typed.join("\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment