-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
90 lines (77 loc) · 2.11 KB
/
index.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
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
86
87
88
89
90
'use strict';
const PEG = require('peggy');
const fs = require('fs');
const path = require('path');
import { generate } from 'peggy';
import { readFileSync } from 'fs';
import { resolve } from 'path';
const builtParsers = {
solidity: require('./build/parser'),
imports: require('./build/imports_parser'),
};
function parseComments(sourceCode) {
// for Line comment regexp, the "." doesn't cover line termination chars so we're good :)
const comments = [],
commentParser = /(\/\*(\*(?!\/)|[^*])*\*\/)|(\/\/.*)/g;
let nextComment;
// eslint-disable-next-line no-cond-assign
while ((nextComment = commentParser.exec(sourceCode))) {
const text = nextComment[0],
types = { '//': 'Line', '/*': 'Block' };
comments.push({
text,
type: types[text.slice(0, 2)],
start: nextComment.index,
end: nextComment.index + text.length,
});
}
return comments;
}
// TODO: Make all this async.
module.exports = {
getParser(parser_name, rebuild) {
if (rebuild == true) {
let parserfile = fs.readFileSync(path.resolve(`./${parser_name}.pegjs`), {
encoding: 'utf8',
});
return PEG.generate(parserfile);
} else {
return builtParsers[parser_name];
}
},
parse(source, options, parser_name, rebuild) {
if (typeof parser_name == 'boolean') {
rebuild = parser_name;
parser_name = null;
}
if (parser_name == null) {
parser_name = 'solidity';
}
let parser = this.getParser(parser_name, rebuild);
let result;
try {
result = parser.parse(source);
} catch (e) {
if (e instanceof parser.SyntaxError) {
e.message +=
' Line: ' +
e.location.start.line +
', Column: ' +
e.location.start.column;
}
throw e;
}
if (typeof options === 'object' && options.comment === true) {
result.comments = parseComments(source);
}
return result;
},
parseFile(file, parser_name, rebuild) {
return this.parse(
fs.readFileSync(path.resolve(file), { encoding: 'utf8' }),
parser_name,
rebuild,
);
},
parseComments,
};