generateParsers.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. // Licensed to Cloudera, Inc. under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. Cloudera, Inc. licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. const fs = require('fs');
  17. const exec = require('child_process').exec;
  18. const LICENSE =
  19. '// Licensed to Cloudera, Inc. under one\n' +
  20. '// or more contributor license agreements. See the NOTICE file\n' +
  21. '// distributed with this work for additional information\n' +
  22. '// regarding copyright ownership. Cloudera, Inc. licenses this file\n' +
  23. '// to you under the Apache License, Version 2.0 (the\n' +
  24. '// "License"); you may not use this file except in compliance\n' +
  25. '// with the License. You may obtain a copy of the License at\n' +
  26. '//\n' +
  27. '// http://www.apache.org/licenses/LICENSE-2.0\n' +
  28. '//\n' +
  29. '// Unless required by applicable law or agreed to in writing, software\n' +
  30. '// distributed under the License is distributed on an "AS IS" BASIS,\n' +
  31. '// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n' +
  32. '// See the License for the specific language governing permissions and\n' +
  33. '// limitations under the License.\n';
  34. const SQL_STATEMENTS_PARSER_JSDOC =
  35. '/**\n' +
  36. ' * @param {string} input\n' +
  37. ' *\n' +
  38. ' * @return {SqlStatementsParserResult}\n' +
  39. ' */\n';
  40. const JISON_FOLDER = 'desktop/core/src/desktop/js/parse/jison/';
  41. const SQL_PARSER_REPOSITORY_PATH = 'desktop/core/src/desktop/js/parse/sql/sqlParserRepository.js';
  42. const SYNTAX_PARSER_IMPORT_TEMPLATE =
  43. ' KEY: () => import(/* webpackChunkName: "KEY-parser" */ \'parse/sql/KEY/KEYSyntaxParser\')';
  44. const AUTOCOMPLETE_PARSER_IMPORT_TEMPLATE =
  45. ' KEY: () => import(/* webpackChunkName: "KEY-parser" */ \'parse/sql/KEY/KEYAutocompleteParser\')';
  46. const parserDefinitions = {
  47. globalSearchParser: {
  48. sources: ['globalSearchParser.jison'],
  49. target: 'globalSearchParser.jison',
  50. outputFolder: 'desktop/core/src/desktop/js/parse/',
  51. afterParse: contents =>
  52. new Promise(resolve => {
  53. resolve(
  54. LICENSE +
  55. contents.replace(
  56. 'var globalSearchParser = ',
  57. "import SqlParseSupport from 'parse/sqlParseSupport';\n\nvar globalSearchParser = "
  58. ) +
  59. '\nexport default globalSearchParser;\n'
  60. );
  61. })
  62. },
  63. solrFormulaParser: {
  64. sources: ['solrFormulaParser.jison'],
  65. target: 'solrFormulaParser.jison',
  66. outputFolder: 'desktop/core/src/desktop/js/parse/',
  67. afterParse: contents =>
  68. new Promise(resolve => {
  69. resolve(LICENSE + contents + 'export default solrFormulaParser;\n');
  70. })
  71. },
  72. solrQueryParser: {
  73. sources: ['solrQueryParser.jison'],
  74. target: 'solrQueryParser.jison',
  75. outputFolder: 'desktop/core/src/desktop/js/parse/',
  76. afterParse: contents =>
  77. new Promise(resolve => {
  78. resolve(LICENSE + contents + 'export default solrQueryParser;\n');
  79. })
  80. },
  81. sqlStatementsParser: {
  82. sources: ['sqlStatementsParser.jison'],
  83. target: 'sqlStatementsParser.jison',
  84. outputFolder: 'desktop/core/src/desktop/js/parse/',
  85. afterParse: contents =>
  86. new Promise(resolve => {
  87. resolve(
  88. LICENSE +
  89. contents.replace(
  90. 'parse: function parse',
  91. SQL_STATEMENTS_PARSER_JSDOC + 'parse: function parse'
  92. ) +
  93. 'export default sqlStatementsParser;\n'
  94. );
  95. })
  96. }
  97. };
  98. const readFile = path =>
  99. new Promise((resolve, reject) => {
  100. fs.readFile(path, (err, buf) => {
  101. if (err) {
  102. reject();
  103. }
  104. resolve(buf.toString());
  105. });
  106. });
  107. const writeFile = (path, contents) =>
  108. new Promise((resolve, reject) => {
  109. fs.writeFile(path, contents, err => {
  110. if (err) {
  111. reject();
  112. }
  113. resolve();
  114. });
  115. });
  116. const deleteFile = path => {
  117. fs.unlinkSync(path);
  118. };
  119. const execCmd = cmd =>
  120. new Promise((resolve, reject) => {
  121. exec(cmd, (err, stdout, stderr) => {
  122. if (err) {
  123. reject('stderr:\n' + stderr + '\n\nstdout:\n' + stdout);
  124. }
  125. resolve(stdout);
  126. });
  127. });
  128. const generateParser = parserName =>
  129. new Promise((resolve, reject) => {
  130. const parserConfig = parserDefinitions[parserName];
  131. const concatPromise = new Promise((resolve, reject) => {
  132. if (parserConfig.sources.length > 1 && parserConfig.target) {
  133. console.log('Concatenating files...');
  134. const promises = parserConfig.sources.map(fileName => readFile(JISON_FOLDER + fileName));
  135. Promise.all(promises)
  136. .then(contents => {
  137. writeFile(JISON_FOLDER + parserConfig.target, contents.join('')).then(() => {
  138. resolve(JISON_FOLDER + parserConfig.target);
  139. });
  140. })
  141. .catch(reject);
  142. } else if (parserConfig.sources.length === 1) {
  143. resolve(JISON_FOLDER + parserConfig.sources[0]);
  144. } else {
  145. reject('No jison source specified');
  146. }
  147. });
  148. concatPromise
  149. .then(targetPath => {
  150. let jisonCommand = 'jison ' + targetPath;
  151. if (parserConfig.lexer) {
  152. jisonCommand += ' ' + JISON_FOLDER + parserConfig.lexer;
  153. }
  154. jisonCommand += ' -m js';
  155. console.log('Generating parser...');
  156. execCmd(jisonCommand)
  157. .then(stdout => {
  158. if (/\S/.test(stdout)) {
  159. console.log('got output for: ' + jisonCommand);
  160. console.log(stdout);
  161. }
  162. if (parserConfig.sources.length > 1) {
  163. deleteFile(targetPath); // Remove concatenated file
  164. }
  165. console.log('Adjusting JS...');
  166. const generatedJsFileName = parserConfig.target.replace('.jison', '.js');
  167. readFile(generatedJsFileName)
  168. .then(contents => {
  169. parserConfig
  170. .afterParse(contents)
  171. .then(finalContents => {
  172. writeFile(parserConfig.outputFolder + generatedJsFileName, finalContents)
  173. .then(() => {
  174. deleteFile(generatedJsFileName);
  175. resolve();
  176. })
  177. .catch(reject);
  178. })
  179. .catch(reject);
  180. })
  181. .catch(reject);
  182. })
  183. .catch(reject);
  184. })
  185. .catch(reject);
  186. });
  187. let parsersToGenerate = [];
  188. const invalid = [];
  189. let all = false;
  190. let appFound = false;
  191. const listDir = folder =>
  192. new Promise(resolve => {
  193. fs.readdir(folder, (err, files) => {
  194. resolve(files);
  195. });
  196. });
  197. const findParser = (fileIndex, folder, sharedFiles, autocomplete) => {
  198. const prefix = autocomplete ? 'autocomplete' : 'syntax';
  199. if (fileIndex[prefix + '_header.jison'] && fileIndex[prefix + '_footer.jison']) {
  200. const parserName = folder + (autocomplete ? 'AutocompleteParser' : 'SyntaxParser');
  201. const parserDefinition = {
  202. sources: ['sql/' + folder + '/' + prefix + '_header.jison'].concat(sharedFiles),
  203. lexer: 'sql/' + folder + '/sql.jisonlex',
  204. target: 'sql/' + folder + '/' + parserName + '.jison',
  205. sqlParser: autocomplete ? 'AUTOCOMPLETE' : 'SYNTAX',
  206. outputFolder: 'desktop/core/src/desktop/js/parse/sql/' + folder + '/',
  207. afterParse: contents =>
  208. new Promise(resolve => {
  209. resolve(
  210. LICENSE +
  211. contents
  212. .replace(
  213. 'var ' + parserName + ' = ',
  214. "import SqlParseSupport from 'parse/sql/" +
  215. folder +
  216. "/sqlParseSupport';\n\nvar " +
  217. parserName +
  218. ' = '
  219. )
  220. .replace(
  221. 'loc: yyloc,',
  222. "loc: lexer.yylloc, ruleId: stack.slice(stack.length - 2, stack.length).join(''),"
  223. ) +
  224. '\nexport default ' +
  225. parserName +
  226. ';\n'
  227. );
  228. })
  229. };
  230. parserDefinition.sources.push('sql/' + folder + '/' + prefix + '_footer.jison');
  231. parserDefinitions[parserName] = parserDefinition;
  232. } else {
  233. console.log(
  234. "Warn: Could not find '" +
  235. prefix +
  236. "_header.jison' or '" +
  237. prefix +
  238. "_footer.jison' in " +
  239. JISON_FOLDER +
  240. 'sql/' +
  241. folder +
  242. '/'
  243. );
  244. }
  245. };
  246. const identifySqlParsers = () =>
  247. new Promise(resolve => {
  248. listDir(JISON_FOLDER + 'sql').then(files => {
  249. const promises = [];
  250. files.forEach(folder => {
  251. promises.push(
  252. listDir(JISON_FOLDER + 'sql/' + folder).then(jisonFiles => {
  253. const fileIndex = {};
  254. jisonFiles.forEach(jisonFile => {
  255. fileIndex[jisonFile] = true;
  256. });
  257. const sharedFiles = jisonFiles
  258. .filter(jisonFile => jisonFile.indexOf('sql_') !== -1)
  259. .map(jisonFile => 'sql/' + folder + '/' + jisonFile);
  260. if (fileIndex['sql.jisonlex']) {
  261. findParser(fileIndex, folder, sharedFiles, true);
  262. findParser(fileIndex, folder, sharedFiles, false);
  263. } else {
  264. console.log(
  265. "Warn: Could not find 'sql.jisonlex' in " + JISON_FOLDER + 'sql/' + folder + '/'
  266. );
  267. }
  268. })
  269. );
  270. });
  271. Promise.all(promises).then(resolve);
  272. });
  273. });
  274. identifySqlParsers().then(() => {
  275. process.argv.forEach(arg => {
  276. if (appFound) {
  277. if (arg === 'all') {
  278. all = true;
  279. } else if (parserDefinitions[arg]) {
  280. parsersToGenerate.push(arg);
  281. } else {
  282. let prefixFound = false;
  283. Object.keys(parserDefinitions).forEach(key => {
  284. if (key.indexOf(arg) === 0) {
  285. prefixFound = true;
  286. parsersToGenerate.push(key);
  287. }
  288. });
  289. if (!prefixFound) {
  290. invalid.push(arg);
  291. }
  292. }
  293. } else if (arg.indexOf('generateParsers.js') !== -1) {
  294. appFound = true;
  295. }
  296. });
  297. if (all) {
  298. parsersToGenerate = Object.keys(parserDefinitions);
  299. }
  300. if (invalid.length) {
  301. console.log("No parser config found for: '" + invalid.join("', '") + "'");
  302. console.log(
  303. '\nPossible options are:\n ' +
  304. ['all'].concat(Object.keys(parserDefinitions)).join('\n ') +
  305. '\n'
  306. );
  307. return;
  308. }
  309. const parserCount = parsersToGenerate.length;
  310. let idx = 0;
  311. const generateRecursive = () => {
  312. idx++;
  313. if (parsersToGenerate.length) {
  314. const parserName = parsersToGenerate.pop();
  315. if (parserCount > 1) {
  316. console.log("Generating '" + parserName + "' (" + idx + '/' + parserCount + ')...');
  317. } else {
  318. console.log("Generating '" + parserName + "'...");
  319. }
  320. generateParser(parserName)
  321. .then(generateRecursive)
  322. .catch(error => {
  323. console.log(error);
  324. console.log('FAIL!');
  325. });
  326. } else {
  327. const autocompParsers = [];
  328. const syntaxParsers = [];
  329. console.log('Updating sqlParserRepository.js...');
  330. Object.keys(parserDefinitions).forEach(key => {
  331. if (parserDefinitions[key].sqlParser === 'AUTOCOMPLETE') {
  332. autocompParsers.push(
  333. AUTOCOMPLETE_PARSER_IMPORT_TEMPLATE.replace(
  334. /KEY/g,
  335. key.replace('AutocompleteParser', '')
  336. )
  337. );
  338. } else if (parserDefinitions[key].sqlParser === 'SYNTAX') {
  339. syntaxParsers.push(
  340. SYNTAX_PARSER_IMPORT_TEMPLATE.replace(/KEY/g, key.replace('SyntaxParser', ''))
  341. );
  342. }
  343. });
  344. readFile(SQL_PARSER_REPOSITORY_PATH).then(contents => {
  345. contents = contents.replace(
  346. /const SYNTAX_MODULES = [^}]+}/,
  347. 'const SYNTAX_MODULES = {\n' + syntaxParsers.join(',\n') + '\n}'
  348. );
  349. contents = contents.replace(
  350. /const AUTOCOMPLETE_MODULES = [^}]+}/,
  351. 'const AUTOCOMPLETE_MODULES = {\n' + autocompParsers.join(',\n') + '\n}'
  352. );
  353. writeFile(SQL_PARSER_REPOSITORY_PATH, contents).then(() => {
  354. console.log('Done!\n');
  355. });
  356. });
  357. }
  358. };
  359. generateRecursive();
  360. });