-
-
Notifications
You must be signed in to change notification settings - Fork 136
/
Copy pathjs_parser.js
321 lines (285 loc) · 9.27 KB
/
js_parser.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/*
* Code takes care of static analysis and generates "out_parsed_typescript.txt"
* The output file consists of information about custom and common bindings that should be generated.
*/
///////////////// CONFIGURATION /////////////////
const enableLogger =
(process.env.JS_PARSER_ENABLE_LOGGING &&
process.env.JS_PARSER_ENABLE_LOGGING.trim() === "true") ||
(process.argv && process.argv.includes("enableVerboseLogging"));
const showErrorsAndWarnings =
(process.env.JS_PARSER_ERROR_LOGGING &&
process.env.JS_PARSER_ERROR_LOGGING.trim() === "true") ||
(!enableLogger &&
process.argv &&
process.argv.includes("enableErrorLogging"));
const loggingSettings = {
logPath: require("path").join(__dirname, "logs", "i.txt"),
strategy: "console",
APP_NAME: "js_parser",
showErrorsAndWarnings: showErrorsAndWarnings,
disable: !enableLogger,
};
const fs = require("fs");
const babelParser = require("@babel/parser");
const traverse = require("@babel/traverse");
const split = require("split");
const logger = require("./helpers/logger")(loggingSettings);
const path = require("path");
const es5_visitors = require("./visitors/es5-visitors");
const eol = require("os").EOL;
let BUILD_TOOLS_DIR = `${__dirname}/../`;
let extendDecoratorName = "JavaProxy";
let interfacesDecoratorName = "Interfaces";
let outFile = "out/out_parsed_typescript.txt"; // default out file
let inputDir = "input_parsed_typescript"; // default input folder
let SBG_INTERFACE_NAMES = "sbg-interface-names.txt";
let interfacesNamesFilePath = getRelativeToBuildTools(SBG_INTERFACE_NAMES); //default interace_names file path
let SBG_INPUT_FILE = "sbg-input-file.txt";
let SBG_BINDINGS_NAME = "sbg-bindings.txt";
let SBG_JS_PARSED_FILES = "sbg-js-parsed-files.txt";
let interfaceNames = [];
let inputFiles = [];
//env variables
if (process.env.JS_PARSER_OUT_FILE) {
outFile = process.env.JS_PARSER_OUT_FILE.trim();
}
if (process.env.JS_PARSER_INPUT_DIR) {
inputDir = process.env.JS_PARSER_INPUT_DIR.trim();
}
if (process.env.JS_PARSER_INTERFACE_FILE_PATH) {
interfacesNamesFilePath = process.env.JS_PARSER_INTERFACE_FILE_PATH.trim();
}
inputDir = fs
.readFileSync(getRelativeToBuildTools(SBG_INPUT_FILE), "UTF-8")
.trim();
try {
fs.unlinkSync(getRelativeToBuildTools(SBG_BINDINGS_NAME)); //delete before each run
} catch (e) {}
outFile = getRelativeToBuildTools(SBG_BINDINGS_NAME);
interfacesNamesFilePath = getRelativeToBuildTools(SBG_INTERFACE_NAMES);
let inputFilesPath = getRelativeToBuildTools(SBG_JS_PARSED_FILES);
function getRelativeToBuildTools(relativePath) {
return path.resolve(`${BUILD_TOOLS_DIR}/${relativePath}`);
}
/////////////// PREPARATION ////////////////
// fileHelpers.createFile(outFile)
/////////////// EXECUTE ////////////////
const tsHelpersFilePath = path.join(
inputDir,
"..",
"internal",
"ts_helpers.js"
);
/*
* If there is an exception anywhere down the line it's caught here
* If the error is criticalthe process is exited.
*/
const exceptionHandler = function (path, reason) {
if (reason.errCode && reason.errCode === 1) {
logger.error(`Error processing '${path}': ${reason.message}`);
logger.error("PROCESS EXITING...");
process.stderr.write(reason.message);
process.exit(4);
} else {
logger.error(`Error processing '${path}:' ` + reason);
}
};
// ENTRY POINT!
readLinesFromFile(inputFilesPath, inputFiles, tsHelpersFilePath)
.then(getFileAst)
.then(readInterfaceNames) //config
.then(traverseAndAnalyseFilesDir) //start
.catch(exceptionHandler.bind(null, inputFilesPath));
/*
* Get's the javascript files that need traversing
*/
function readLinesFromFile(filePath, outArr, resolveParameter) {
return new Promise(function (resolve, reject) {
fs.createReadStream(filePath)
.pipe(split())
.on("data", function (line) {
// skip empty lines
if (/\S/.test(line)) {
outArr.push(line.toString().trim());
}
})
.on("error", function (err) {
return reject(err);
})
.on("close", function (e) {
return resolve(resolveParameter);
});
});
}
/*
* Get line and column of the __extends function from ts_helpers file
*/
function getFileAst(tsHelpersFilePath) {
return new Promise(function (resolve, reject) {
fs.readFile(tsHelpersFilePath, "utf8", function (err, fileContent) {
if (err) {
logger.warn("+DIDN'T parse ast from file " + tsHelpersFilePath);
return reject(err);
}
logger.info("+parsing ast from " + tsHelpersFilePath);
const ast = babelParser.parse(fileContent, {
minify: false,
plugins: [
[
"@babel/plugin-proposal-decorators",
{ decoratorsBeforeExport: true },
],
],
});
return resolve(ast);
});
});
}
/*
* Get's pregenerated interface names from "interfacesNamesFilePath"
* After reading interface names runs the visiting api
*/
function readInterfaceNames(data, err) {
return new Promise(function (resolve, reject) {
fs.createReadStream(interfacesNamesFilePath)
.pipe(split())
.on("data", function (line) {
// skip empty lines
if (/\S/.test(line)) {
interfaceNames.push(line.toString().trim());
}
})
.on("error", function (e) {
return reject(false);
})
.on("close", function (e) {
inputDir = path.normalize(inputDir);
return resolve(inputDir);
});
});
}
/*
* Traverses a given input directory and attempts to visit every ".js" file.
* It passes each found file down the line.
*/
function traverseAndAnalyseFilesDir(inputDir, err) {
if (!fs.existsSync(inputDir)) {
throw "The input dir: " + inputDir + " does not exist!";
}
traverseFiles(inputFiles);
}
function traverseFiles(filesToTraverse) {
for (let i = 0; i < filesToTraverse.length; i += 1) {
const fp = filesToTraverse[i];
logger.info("Visiting JavaScript file: " + fp);
readFile(fp)
.then(astFromFileContent.bind(null, fp))
.then(visitAst.bind(null, fp))
.then(writeToFile)
.catch(exceptionHandler.bind(null, fp));
}
}
/*
* Gets the file content as text and passes it down the line.
*/
const readFile = function (filePath, err) {
return new Promise(function (resolve, reject) {
fs.readFile(filePath, function (err, data) {
if (err) {
logger.warn(`+DIDN'T get content of file: ${filePath}!`);
return reject(err);
}
const fileInfo = {
filePath: filePath,
data: data.toString(),
};
return resolve(fileInfo);
});
});
};
/*
* Get's the AST (https://en.wikipedia.org/wiki/Abstract_syntax_tree) from the file content and passes it down the line.
*/
const astFromFileContent = function (path, data, err) {
return new Promise(function (resolve, reject) {
if (err) {
logger.warn(`+DIDN'T parse ast from file: ${path}!`);
return reject(err);
}
const ast = babelParser.parse(data.data, {
minify: false,
plugins: [
["@babel/plugin-proposal-decorators", { decoratorsBeforeExport: true }],
"objectRestSpread",
],
});
data.ast = ast;
return resolve(data);
});
};
//only unique filter
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
/*
* Visist's the passed AST with a given visitor and extracts nativescript speciffic data.
* Passes the extracted bindings data down the line.
*/
const visitAst = function (path, data, err) {
return new Promise(function (resolve, reject) {
if (err) {
logger.warn(`+DIDN'T visit ast for file: ${path}!`);
return reject(err);
}
traverse.default(data.ast, {
enter: function (path) {
const decoratorConfig = {
logger: logger,
extendDecoratorName: extendDecoratorName,
interfacesDecoratorName: interfacesDecoratorName,
filePath:
data.filePath.substring(
inputDir.length + 1,
data.filePath.length - 3
) || "",
fullPathName: data.filePath
.substring(inputDir.length + 1)
.replace(/[\\]/g, "/"),
interfaceNames: interfaceNames,
};
es5_visitors.es5Visitor(path, decoratorConfig);
},
});
const customExtendsArr = es5_visitors.es5Visitor.getProxyExtendInfo();
const normalExtendsArr = es5_visitors.es5Visitor.getCommonExtendInfo();
const interfacesArr = es5_visitors.es5Visitor.getInterfaceInfo();
const res = customExtendsArr
.concat(normalExtendsArr)
.concat(interfacesArr)
.filter(onlyUnique)
.join(eol);
return resolve(res);
});
};
const writeToFile = function (data, err) {
return new Promise(function (resolve, reject) {
if (data.trim() != "") {
// fs.appendFile(outFile, stringify(data), function (writeFileError) {
fs.appendFile(outFile, data + eol, function (writeFileError) {
if (err) {
logger.warn("Error from writeToFile: " + err);
return reject(err);
}
if (writeFileError) {
logger.warn("Error writing file: " + writeFileError);
return reject(writeFileError);
}
logger.info("+appended '" + data + "' to file: " + outFile);
return resolve(data);
});
} else {
logger.info("No need to generate anything. (UP-TO-DATE)");
}
});
};