-
Notifications
You must be signed in to change notification settings - Fork 38
/
parser.ts
72 lines (63 loc) · 1.93 KB
/
parser.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import * as path from "path";
import { CompilerOptions, Project, ts } from "ts-morph";
import { Contract } from "./definitions";
import { parseContract } from "./parsers/contract-parser";
export function parse(sourcePath: string): Contract {
const project = createProject();
// Add all dependent files that the project requires
const sourceFile = project.addSourceFileAtPath(sourcePath);
project.resolveSourceFileDependencies();
// Validate that the project has no TypeScript syntax errors
validateProject(project);
const result = parseContract(sourceFile);
// TODO: print human readable errors
if (result.isErr()) throw result.unwrapErr();
return result.unwrap().contract;
}
/**
* Create a new project configured for Spot
*/
function createProject(): Project {
const compilerOptions: CompilerOptions = {
target: ts.ScriptTarget.ESNext,
module: ts.ModuleKind.CommonJS,
strict: true,
noImplicitAny: true,
strictNullChecks: true,
strictFunctionTypes: true,
strictPropertyInitialization: true,
noImplicitThis: true,
resolveJsonModule: true,
alwaysStrict: true,
noImplicitReturns: true,
noFallthroughCasesInSwitch: true,
moduleResolution: ts.ModuleResolutionKind.NodeJs,
experimentalDecorators: true,
baseUrl: "./",
paths: {
"@airtasker/spot": [path.join(__dirname, "../lib")]
}
};
// Creates a new typescript program in memory
return new Project({ compilerOptions });
}
/**
* Validate an AST project's correctness.
*
* @param project an AST project
*/
function validateProject(project: Project): void {
const diagnostics = project.getPreEmitDiagnostics();
if (diagnostics.length > 0) {
throw new Error(
diagnostics
.map(diagnostic => {
const message = diagnostic.getMessageText();
return typeof message === "string"
? message
: message.getMessageText();
})
.join("\n")
);
}
}