forked from ariatemplates/hashspace
/
compiler.js
60 lines (52 loc) · 2.63 KB
/
compiler.js
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
var parser = require("./parser/index");
var treebuilder = require("./treebuilder/index");
var jsgenerator = require("./jsgenerator/index");
var transpiler = require("../transpiler/index");
/**
* Compiles a template and return a JS compiled string and a list of errors.
* @param {String} template the template file content as a string.
* @param {String} path path of a file being compiled (optional - used for error messages).
* @param {Object} compiler options; supported options are:
* includeSyntaxTree if true, the result object will contain the syntax tree generated by the compiler.
* bypassJSvalidation if true, the validation of the generated JS file (including non-template code) is bypassed - default:false.
* mode the type of module system the code shold comply with: either "commonJS" or "global"
* globalRef the name of the runtime global reference when the "global" mode is used (default: "hsp")
* @return {Object} a JSON structure with the following properties:
* errors: {Array} the error list - each error having the following structure:
* description: {String} - a message describing the error
* line: {Number} - the error line number
* column: {Number} - the error column number
* code: {String} - a code extract showing where the error occurs (optional)
* code: {String} the generated JavaScript code
* syntaxTree: {JSON} the syntax tree generated by the parser (optional - cf. parameters)
* lineMap: {Array} array of the new line indexes: lineMap[3] returns the new line index for line 4 in
* the orginal file (lineMap[0] is always 0 as all line count starts at 1 for both input and output values)
*/
exports.compile = function (template, path, options) {
options = options || {};
if (!path) {
throw new Error('The template "path" argument is mandatory.');
}
if (!template) {
throw new Error('The template "' + path+ '" is empty but content to compile is mandatory.');
}
// Parsing might throw an exception
var res;
var m = path.match(/[^\/]+$/),
fileName = m ? m[0] : 'unknown',
dirPath = '';
if (fileName.length < path.length) {
dirPath = path.slice(0, -fileName.length);
}
//Step 1: parser
var blockList = parser.parse(template);
//Step2 : treebuilder
res = treebuilder.build(blockList);
//Step3 : jsgenerator
res = jsgenerator.generate(res, template, fileName, dirPath, options);
//Step4 : transpiler
if (!res.errors || res.errors.length===0) {
res.code=transpiler.processString(res.code, path, options).code;
}
return res;
};