-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.js
64 lines (56 loc) · 1.71 KB
/
parse.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
"use strict";
function parse(source,defs){
if(!defs) defs = {};
const lines = source.split('\n');
const listVarName = '__$list$__';
let code = `(function(){
const ${listVarName} = [];\n`;
for(let key of Object.keys(defs)){
code += `const ${key} = ${JSON.stringify(defs[key])};\n`;
}
for(let line of lines){
const checkResult = checkLine(line);
if(checkResult){
switch(checkResult.condition){
case 'if':
code += `if(${checkResult.expr}){\n`;
break;
case 'else':
code += '}else{\n';
break;
case 'elif':
code += `}else if(${checkResult.expr}){\n`;
break;
case 'endif':
code += '}\n';
break;
}
}else{
code += `${listVarName}.push(${JSON.stringify(line)});\n`
}
}
code += `return ${listVarName};
})();`;
try{
const result = eval(code);
return result.join('\n');
}catch(e){
throw new Error('error condition');
}
}
function checkLine(line){
const matchResult = line.match(/\/{3,}[\s]*#(if|else|elif|endif)([\s]+[\s\S]*)?$/);
if(matchResult){
const checkResult = {condition:matchResult[1],expr:(matchResult[2]||'').trim()};
if(
(checkResult.condition==='if'||checkResult.condition==='elif')
&&
checkResult.expr===''
){
return false;
}
return checkResult;
}
return false;
}
module.exports = parse;