re2-js-generator/parse_source_lexeme.js

33 lines
1.6 KiB
JavaScript

/**
* Created by Aleksey Chichenkov <a.chichenkov@initi.ru> on 1/23/19.
*/
var js_beautify = require("js-beautify");
var fs = require("fs");
var exec = require('child_process').exec;
exec("re2c -i lexer.l", function(err, stdout, stderr) {
err && console.log("ERROR: ", err);
err && process.exit(1);
post_process_lexer(stdout);
});
var post_process_lexer = function (_string) {
_string = _string.replace(/^.*(_r2c_var_.*;|unsigned int yyaccept = 0;)\n/gm, ""); // replace var yych;
_string = _string.replace(/(yych = \*YYCURSOR);\n/gm, "\tcase 1:\n yych = str[YYCURSOR];\n"); // insert "case 1:" before;
_string = _string.replace(/\*(.*?);/gm, "str[$1];"); // замена разыменовываний
_string = _string.replace(/^yy(\d*?):/gm, "case $1:"); // replace goto marker onto case
_string = _string.replace(/\) goto yy(\d*?);/gm, ") { id = $1; break; }"); // replace goto inside if
_string = _string.replace(/goto yy(\d*?);/gm, "id = $1; break;"); // replace goto outside if
_string = _string.replace(/\{ (addLexeme.*break;) \}/gm, "$1"); // replace addLexeme
_string = _string.replace(/\{ (unknownSymbol.*break;) \}/gm, "$1"); // replace unknownSymbol
_string = _string.replace(/0x00/gm, 'undefined'); // replace 0x00
// black magic
_string = _string.replace(/(switch \(yych\) \{[\s\S]*?})/gm, "(function(){$1})(); break;"); // добавим замыкание что бы обработать свиче в свиче
_string = js_beautify(_string, {indent_size: 4, space_in_empty_paren: true});
fs.writeFileSync("out.js", _string);
};