forked from Mikerah/AirScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
85 lines (74 loc) · 2.77 KB
/
Copy pathindex.ts
File metadata and controls
85 lines (74 loc) · 2.77 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
// IMPORTS
// ================================================================================================
import { AirSchema } from '@guildofweavers/air-assembly';
import * as fs from 'fs';
import * as path from 'path';
import { lexer } from './lib/lexer';
import { parser } from './lib/parser';
import { visitor } from './lib/visitor';
import { AirScriptError } from './lib/errors';
// PUBLIC FUNCTIONS
// ================================================================================================
export function compile(sourceOrPath: string | Buffer, componentName = 'default'): AirSchema {
// determine the source of the script
let source: string, basedir: string;
if (Buffer.isBuffer(sourceOrPath)) {
source = sourceOrPath.toString('utf8');
basedir = getCallerDirectory()!;
}
else {
if (typeof sourceOrPath !== 'string')
throw new TypeError(`source path '${sourceOrPath}' is invalid`);
try {
if (!path.isAbsolute(sourceOrPath)) {
sourceOrPath = path.resolve(getCallerDirectory(), sourceOrPath);
}
source = fs.readFileSync(sourceOrPath, { encoding: 'utf8' });
basedir = path.dirname(sourceOrPath);
}
catch (error) {
throw new AirScriptError([error]);
}
}
// tokenize input
const lexResult = lexer.tokenize(source);
if(lexResult.errors.length > 0) {
throw new AirScriptError(lexResult.errors);
}
// apply grammar rules
parser.input = lexResult.tokens;
const cst = parser.script();
if (parser.errors.length > 0) {
throw new AirScriptError(parser.errors);
}
// build AIR module
try {
const schema: AirSchema = visitor.visit(cst, { name: componentName, basedir });
return schema;
}
catch (error) {
throw new AirScriptError([error]);
}
}
// HELPER FUNCTIONS
// ================================================================================================
function getCallerDirectory(): string {
let callerFile: string | undefined;
try {
const origPrepareStackTrace = Error.prepareStackTrace
Error.prepareStackTrace = function (err, stack) { return stack; };
const err: any = new Error();
let currentFile: string = err.stack.shift().getFileName();
while (err.stack.length) {
callerFile = err.stack.shift().getFileName();
if (currentFile !== callerFile) break;
}
Error.prepareStackTrace = origPrepareStackTrace
} catch (err) {
throw new Error(`could not determine base directory for the script`);
}
if (!callerFile) {
throw new Error(`could not determine base directory for the script`);
}
return path.dirname(callerFile);
}