Add API sample tests

This commit is contained in:
Mohamed Hegazy 2015-01-29 11:23:02 -08:00
parent 9f977af9cc
commit 5fa30e550c
13 changed files with 32622 additions and 3 deletions

View file

@ -931,6 +931,8 @@ module Harness {
settingsCallback(null);
}
var newLine = '\r\n';
var useCaseSensitiveFileNames = ts.sys.useCaseSensitiveFileNames;
this.settings.forEach(setting => {
switch (setting.flag.toLowerCase()) {
@ -1009,7 +1011,7 @@ module Harness {
case 'newline':
case 'newlines':
ts.sys.newLine = setting.value;
newLine = setting.value;
break;
case 'comments':
@ -1051,7 +1053,7 @@ module Harness {
break;
case 'includebuiltfile':
inputFiles.push({ unitName: setting.value, content: IO.readFile(libFolder + setting.value) });
inputFiles.push({ unitName: setting.value, content: normalizeLineEndings(IO.readFile(libFolder + setting.value), newLine) });
break;
default:
@ -1097,7 +1099,7 @@ module Harness {
onComplete(result, program);
// reset what newline means in case the last test changed it
ts.sys.newLine = '\r\n';
ts.sys.newLine = newLine;
return options;
}
@ -1169,6 +1171,14 @@ module Harness {
}
}
function normalizeLineEndings(text: string, lineEnding: string): string {
var normalized = text.replace(/\r\n?/g, '\n');
if (lineEnding !== '\n') {
normalized = normalized.replace(/\n/g, lineEnding);
}
return normalized;
}
export function getMinimalDiagnostic(err: ts.Diagnostic): HarnessDiagnostic {
var errorLineInfo = err.file ? err.file.getLineAndCharacterFromPosition(err.start) : { line: 0, character: 0 };
return {

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,37 @@
// @module: commonjs
// @includebuiltfile: typescript.d.ts
/*
* Note: This test is a public API sample. The sample sources can be found
at: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#a-minimal-compiler
* Please log a "breaking change" issue for any API breaking change affecting this issue
*/
declare var process: any;
declare var console: any;
import ts = require("typescript");
export function compile(filenames: string[], options: ts.CompilerOptions): void {
var host = ts.createCompilerHost(options);
var program = ts.createProgram(filenames, options, host);
var checker = ts.createTypeChecker(program, /*produceDiagnostics*/ true);
var result = program.emitFiles();
var allDiagnostics = program.getDiagnostics()
.concat(checker.getDiagnostics())
.concat(result.diagnostics);
allDiagnostics.forEach(diagnostic => {
var lineChar = diagnostic.file.getLineAndCharacterFromPosition(diagnostic.start);
console.log(`${diagnostic.file.filename} (${lineChar.line},${lineChar.character}): ${diagnostic.messageText}`);
});
console.log(`Process exiting with code '${result.emitResultStatus}'.`);
process.exit(result.emitResultStatus);
}
compile(process.argv.slice(2), {
noEmitOnError: true, noImplicitAny: true,
target: ts.ScriptTarget.ES5, module: ts.ModuleKind.CommonJS
});

View file

@ -0,0 +1,65 @@
// @module: commonjs
// @includebuiltfile: typescript.d.ts
/*
* Note: This test is a public API sample. The sample sources can be found
at: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#traversing-the-ast-with-a-little-linter
* Please log a "breaking change" issue for any API breaking change affecting this issue
*/
declare var process: any;
declare var console: any;
declare var fs: any;
import ts = require("typescript");
export function delint(sourceFile: ts.SourceFile) {
delintNode(sourceFile);
function delintNode(node: ts.Node) {
switch (node.kind) {
case ts.SyntaxKind.ForStatement:
case ts.SyntaxKind.ForInStatement:
case ts.SyntaxKind.WhileStatement:
case ts.SyntaxKind.DoStatement:
if ((<ts.IterationStatement>node).statement.kind !== ts.SyntaxKind.Block) {
report(node, "A looping statement's contents should be wrapped in a block body.");
}
break;
case ts.SyntaxKind.IfStatement:
var ifStatement = (<ts.IfStatement>node);
if (ifStatement.thenStatement.kind !== ts.SyntaxKind.Block) {
report(ifStatement.thenStatement, "An if statement's contents should be wrapped in a block body.");
}
if (ifStatement.elseStatement &&
ifStatement.elseStatement.kind !== ts.SyntaxKind.Block && ifStatement.elseStatement.kind !== ts.SyntaxKind.IfStatement) {
report(ifStatement.elseStatement, "An else statement's contents should be wrapped in a block body.");
}
break;
case ts.SyntaxKind.BinaryExpression:
var op = (<ts.BinaryExpression>node).operator;
if (op === ts.SyntaxKind.EqualsEqualsToken || op === ts.SyntaxKind.ExclamationEqualsToken) {
report(node, "Use '===' and '!=='.")
}
break;
}
ts.forEachChild(node, delintNode);
}
function report(node: ts.Node, message: string) {
var lineChar = sourceFile.getLineAndCharacterFromPosition(node.getStart());
console.log(`${sourceFile.filename} (${lineChar.line},${lineChar.character}): ${message}`)
}
}
var filenames = process.argv.slice(2);
filenames.forEach(filename => {
// Parse a file
var sourceFile = ts.createSourceFile(filename, fs.readFileSync(filename).toString(), ts.ScriptTarget.ES6, /*setParentNodes */ true);
// delint it
delint(sourceFile);
});

View file

@ -0,0 +1,67 @@
// @module: commonjs
// @includebuiltfile: typescript.d.ts
/*
* Note: This test is a public API sample. The sample sources can be found
at: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#a-simple-transform-function
* Please log a "breaking change" issue for any API breaking change affecting this issue
*/
declare var process: any;
declare var console: any;
declare var fs: any;
declare var path: any;
import ts = require("typescript");
function transform(contents: string, compilerOptions: ts.CompilerOptions = {}) {
// Sources
var files = {
"file.ts": contents,
"lib.d.ts": fs.readFileSync(ts.getDefaultLibFilePath(compilerOptions)).toString()
};
// Generated outputs
var outputs = [];
// Create a compilerHost object to allow the compiler to read and write files
var compilerHost = {
getSourceFile: (filename, target) => {
return files[filename] !== undefined ?
ts.createSourceFile(filename, files[filename], target) : undefined;
},
writeFile: (name, text, writeByteOrderMark) => {
outputs.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
},
getDefaultLibFilename: () => "lib.d.ts",
useCaseSensitiveFileNames: () => false,
getCanonicalFileName: (filename) => filename,
getCurrentDirectory: () => "",
getNewLine: () => "\n"
};
// Create a program from inputs
var program = ts.createProgram(["file.ts"], compilerOptions, compilerHost);
// Query for early errors
var errors = program.getDiagnostics();
// Do not generate code in the presence of early errors
if (!errors.length) {
// Type check and get semantic errors
var checker = program.getTypeChecker(true);
errors = checker.getDiagnostics();
// Generate output
program.emitFiles();
}
return {
outputs: outputs,
errors: errors.map(function (e) { return e.file.filename + "(" + e.file.getLineAndCharacterFromPosition(e.start).line + "): " + e.messageText; })
};
}
// Calling our transform function using a simple TypeScript variable declarations,
// and loading the default library like:
var source = "var x: number = 'string'";
var result = transform(source);
console.log(JSON.stringify(result));

View file

@ -0,0 +1,104 @@
// @module: commonjs
// @includebuiltfile: typescript.d.ts
/*
* Note: This test is a public API sample. The sample sources can be found
at: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#incremental-build-support-using-the-language-services
* Please log a "breaking change" issue for any API breaking change affecting this issue
*/
declare var process: any;
declare var console: any;
declare var fs: any;
declare var path: any;
import ts = require("typescript");
function watch(rootFilenames: string[], options: ts.CompilerOptions) {
var files: ts.Map<{ version: number }> = {};
// initialize the list of files
rootFilenames.forEach(filename => {
files[filename] = { version: 0 };
});
// Create the language service host to allow the LS to communicate with the host
var servicesHost: ts.LanguageServiceHost = {
getScriptFileNames: () => rootFilenames,
getScriptVersion: (filename) => files[filename] && files[filename].version.toString(),
getScriptSnapshot: (filename) => {
if (!fs.existsSync(filename)) {
return undefined;
}
return ts.ScriptSnapshot.fromString(fs.readFileSync(filename).toString());
},
getCurrentDirectory: () => process.cwd(),
getCompilationSettings: () => options,
getDefaultLibFilename: (options) => ts.getDefaultLibFilePath(options),
};
// Create the language service files
var services = ts.createLanguageService(servicesHost, ts.createDocumentRegistry())
// Now let's watch the files
rootFilenames.forEach(filename => {
// First time around, emit all files
emitFile(filename);
// Add a watch on the file to handle next change
fs.watchFile(filename,
{ persistent: true, interval: 250 },
(curr, prev) => {
// Check timestamp
if (+curr.mtime <= +prev.mtime) {
return;
}
// Update the version to signal a change in the file
files[filename].version++;
// write the changes to disk
emitFile(filename);
});
});
function emitFile(filename: string) {
var output = services.getEmitOutput(filename);
if (output.emitOutputStatus === ts.EmitReturnStatus.Succeeded) {
console.log(`Emitting ${filename}`);
}
else {
console.log(`Emitting ${filename} failed`);
logErrors(filename);
}
output.outputFiles.forEach(o => {
fs.writeFileSync(o.name, o.text, "utf8");
});
}
function logErrors(filename: string) {
var allDiagnostics = services.getCompilerOptionsDiagnostics()
.concat(services.getSyntacticDiagnostics(filename))
.concat(services.getSemanticDiagnostics(filename));
allDiagnostics.forEach(diagnostic => {
if (diagnostic.file) {
var lineChar = diagnostic.file.getLineAndCharacterFromPosition(diagnostic.start);
console.log(` Error ${diagnostic.file.filename} (${lineChar.line},${lineChar.character}): ${diagnostic.messageText}`);
}
else {
console.log(` Error: ${diagnostic.messageText}`);
}
});
}
}
// Initialize files constituting the program as all .ts files in the current directory
var currentDirectoryFiles = fs.readdirSync(process.cwd()).
filter(filename=> filename.length >= 3 && filename.substr(filename.length - 3, 3) === ".ts");
// Start the watcher
watch(currentDirectoryFiles, { module: ts.ModuleKind.CommonJS });