generateParsers.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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. /* eslint-disable no-restricted-syntax */
  17. const fs = require('fs');
  18. const exec = require('child_process').exec;
  19. const LICENSE =
  20. '// Licensed to Cloudera, Inc. under one\n' +
  21. '// or more contributor license agreements. See the NOTICE file\n' +
  22. '// distributed with this work for additional information\n' +
  23. '// regarding copyright ownership. Cloudera, Inc. licenses this file\n' +
  24. '// to you under the Apache License, Version 2.0 (the\n' +
  25. '// "License"); you may not use this file except in compliance\n' +
  26. '// with the License. You may obtain a copy of the License at\n' +
  27. '//\n' +
  28. '// http://www.apache.org/licenses/LICENSE-2.0\n' +
  29. '//\n' +
  30. '// Unless required by applicable law or agreed to in writing, software\n' +
  31. '// distributed under the License is distributed on an "AS IS" BASIS,\n' +
  32. '// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n' +
  33. '// See the License for the specific language governing permissions and\n' +
  34. '// limitations under the License.\n';
  35. const SQL_STATEMENTS_PARSER_JSDOC =
  36. '/**\n' +
  37. ' * @param {string} input\n' +
  38. ' *\n' +
  39. ' * @return {SqlStatementsParserResult}\n' +
  40. ' */\n';
  41. const PARSER_FOLDER = 'desktop/core/src/desktop/js/parse/sql/';
  42. const JISON_FOLDER = 'desktop/core/src/desktop/js/parse/jison/';
  43. const SQL_PARSER_REPOSITORY_PATH = 'desktop/core/src/desktop/js/parse/sql/sqlParserRepository.js';
  44. const SYNTAX_PARSER_IMPORT_TEMPLATE =
  45. ' KEY: () => import(/* webpackChunkName: "KEY-parser" */ \'parse/sql/KEY/KEYSyntaxParser\')';
  46. const AUTOCOMPLETE_PARSER_IMPORT_TEMPLATE =
  47. ' KEY: () => import(/* webpackChunkName: "KEY-parser" */ \'parse/sql/KEY/KEYAutocompleteParser\')';
  48. const parserDefinitions = {
  49. globalSearchParser: {
  50. sources: ['globalSearchParser.jison'],
  51. target: 'globalSearchParser.jison',
  52. outputFolder: 'desktop/core/src/desktop/js/parse/',
  53. afterParse: contents =>
  54. new Promise(resolve => {
  55. resolve(
  56. LICENSE +
  57. contents.replace(
  58. 'var globalSearchParser = ',
  59. "import SqlParseSupport from 'parse/sqlParseSupport';\n\nvar globalSearchParser = "
  60. ) +
  61. '\nexport default globalSearchParser;\n'
  62. );
  63. })
  64. },
  65. solrFormulaParser: {
  66. sources: ['solrFormulaParser.jison'],
  67. target: 'solrFormulaParser.jison',
  68. outputFolder: 'desktop/core/src/desktop/js/parse/',
  69. afterParse: contents =>
  70. new Promise(resolve => {
  71. resolve(LICENSE + contents + 'export default solrFormulaParser;\n');
  72. })
  73. },
  74. solrQueryParser: {
  75. sources: ['solrQueryParser.jison'],
  76. target: 'solrQueryParser.jison',
  77. outputFolder: 'desktop/core/src/desktop/js/parse/',
  78. afterParse: contents =>
  79. new Promise(resolve => {
  80. resolve(LICENSE + contents + 'export default solrQueryParser;\n');
  81. })
  82. },
  83. sqlStatementsParser: {
  84. sources: ['sqlStatementsParser.jison'],
  85. target: 'sqlStatementsParser.jison',
  86. outputFolder: 'desktop/core/src/desktop/js/parse/',
  87. afterParse: contents =>
  88. new Promise(resolve => {
  89. resolve(
  90. LICENSE +
  91. contents.replace(
  92. 'parse: function parse',
  93. SQL_STATEMENTS_PARSER_JSDOC + 'parse: function parse'
  94. ) +
  95. 'export default sqlStatementsParser;\n'
  96. );
  97. })
  98. }
  99. };
  100. const mkdir = path =>
  101. new Promise((resolve, reject) => {
  102. if (fs.existsSync(path)) {
  103. resolve();
  104. } else {
  105. fs.mkdir(path, err => {
  106. if (err) {
  107. reject(err);
  108. }
  109. resolve();
  110. });
  111. }
  112. });
  113. const readFile = path =>
  114. new Promise((resolve, reject) => {
  115. fs.readFile(path, (err, buf) => {
  116. if (err) {
  117. reject(err);
  118. }
  119. resolve(buf ? buf.toString() : '');
  120. });
  121. });
  122. const writeFile = (path, contents) =>
  123. new Promise((resolve, reject) => {
  124. fs.writeFile(path, contents, err => {
  125. if (err) {
  126. reject();
  127. }
  128. resolve();
  129. });
  130. });
  131. const copyFile = (source, destination, contentsCallback) =>
  132. new Promise((resolve, reject) => {
  133. readFile(source)
  134. .then(contents => {
  135. writeFile(destination, contentsCallback ? contentsCallback(contents) : contents)
  136. .then(resolve)
  137. .catch(reject);
  138. })
  139. .catch(reject);
  140. });
  141. const deleteFile = path => {
  142. fs.unlinkSync(path);
  143. };
  144. const execCmd = cmd =>
  145. new Promise((resolve, reject) => {
  146. exec(cmd, (err, stdout, stderr) => {
  147. if (err) {
  148. reject('stderr:\n' + stderr + '\n\nstdout:\n' + stdout);
  149. }
  150. resolve(stdout);
  151. });
  152. });
  153. const generateParser = parserName =>
  154. new Promise((resolve, reject) => {
  155. const parserConfig = parserDefinitions[parserName];
  156. const concatPromise = new Promise((resolve, reject) => {
  157. if (parserConfig.sources.length > 1 && parserConfig.target) {
  158. console.log('Concatenating files...');
  159. const promises = parserConfig.sources.map(fileName => readFile(JISON_FOLDER + fileName));
  160. Promise.all(promises)
  161. .then(contents => {
  162. writeFile(JISON_FOLDER + parserConfig.target, contents.join('')).then(() => {
  163. resolve(JISON_FOLDER + parserConfig.target);
  164. });
  165. })
  166. .catch(reject);
  167. } else if (parserConfig.sources.length === 1) {
  168. resolve(JISON_FOLDER + parserConfig.sources[0]);
  169. } else {
  170. reject('No jison source specified');
  171. }
  172. });
  173. concatPromise
  174. .then(targetPath => {
  175. let jisonCommand = 'jison ' + targetPath;
  176. if (parserConfig.lexer) {
  177. jisonCommand += ' ' + JISON_FOLDER + parserConfig.lexer;
  178. }
  179. jisonCommand += ' -m js';
  180. console.log('Generating parser...');
  181. execCmd(jisonCommand)
  182. .then(stdout => {
  183. if (/\S/.test(stdout)) {
  184. console.log('got output for: ' + jisonCommand);
  185. console.log(stdout);
  186. }
  187. if (parserConfig.sources.length > 1) {
  188. deleteFile(targetPath); // Remove concatenated file
  189. }
  190. console.log('Adjusting JS...');
  191. const generatedJsFileName = parserConfig.target
  192. .replace('.jison', '.js')
  193. .replace(/^.*\/([^/]+)$/, '$1');
  194. readFile(generatedJsFileName)
  195. .then(contents => {
  196. parserConfig
  197. .afterParse(contents)
  198. .then(finalContents => {
  199. writeFile(parserConfig.outputFolder + generatedJsFileName, finalContents)
  200. .then(() => {
  201. deleteFile(generatedJsFileName);
  202. resolve();
  203. })
  204. .catch(reject);
  205. })
  206. .catch(reject);
  207. })
  208. .catch(reject);
  209. })
  210. .catch(reject);
  211. })
  212. .catch(reject);
  213. });
  214. let parsersToGenerate = [];
  215. const invalid = [];
  216. let all = false;
  217. const listDir = folder =>
  218. new Promise(resolve => {
  219. fs.readdir(folder, (err, files) => {
  220. resolve(files);
  221. });
  222. });
  223. const findParser = (fileIndex, folder, sharedFiles, autocomplete) => {
  224. const prefix = autocomplete ? 'autocomplete' : 'syntax';
  225. if (fileIndex[prefix + '_header.jison'] && fileIndex[prefix + '_footer.jison']) {
  226. const parserName = folder + (autocomplete ? 'AutocompleteParser' : 'SyntaxParser');
  227. const parserDefinition = {
  228. sources: ['sql/' + folder + '/' + prefix + '_header.jison'].concat(sharedFiles),
  229. lexer: 'sql/' + folder + '/sql.jisonlex',
  230. target: 'sql/' + folder + '/' + parserName + '.jison',
  231. sqlParser: autocomplete ? 'AUTOCOMPLETE' : 'SYNTAX',
  232. outputFolder: 'desktop/core/src/desktop/js/parse/sql/' + folder + '/',
  233. afterParse: contents =>
  234. new Promise(resolve => {
  235. resolve(
  236. LICENSE +
  237. contents
  238. .replace(
  239. 'var ' + parserName + ' = ',
  240. "import SqlParseSupport from 'parse/sql/" +
  241. folder +
  242. "/sqlParseSupport';\n\nvar " +
  243. parserName +
  244. ' = '
  245. )
  246. .replace(
  247. 'loc: yyloc,',
  248. "loc: lexer.yylloc, ruleId: stack.slice(stack.length - 2, stack.length).join(''),"
  249. ) +
  250. '\nexport default ' +
  251. parserName +
  252. ';\n'
  253. );
  254. })
  255. };
  256. parserDefinition.sources.push('sql/' + folder + '/' + prefix + '_footer.jison');
  257. parserDefinitions[parserName] = parserDefinition;
  258. } else {
  259. console.log(
  260. "Warn: Could not find '" +
  261. prefix +
  262. "_header.jison' or '" +
  263. prefix +
  264. "_footer.jison' in " +
  265. JISON_FOLDER +
  266. 'sql/' +
  267. folder +
  268. '/'
  269. );
  270. }
  271. };
  272. const identifySqlParsers = () =>
  273. new Promise(resolve => {
  274. listDir(JISON_FOLDER + 'sql').then(files => {
  275. const promises = [];
  276. files.forEach(folder => {
  277. promises.push(
  278. listDir(JISON_FOLDER + 'sql/' + folder).then(jisonFiles => {
  279. const fileIndex = {};
  280. jisonFiles.forEach(jisonFile => {
  281. fileIndex[jisonFile] = true;
  282. });
  283. const sharedFiles = jisonFiles
  284. .filter(jisonFile => jisonFile.indexOf('sql_') !== -1)
  285. .map(jisonFile => 'sql/' + folder + '/' + jisonFile);
  286. if (fileIndex['sql.jisonlex']) {
  287. findParser(fileIndex, folder, sharedFiles, true);
  288. findParser(
  289. fileIndex,
  290. folder,
  291. sharedFiles.filter(path => path.indexOf('_error.jison') === -1),
  292. false
  293. );
  294. } else {
  295. console.log(
  296. "Warn: Could not find 'sql.jisonlex' in " + JISON_FOLDER + 'sql/' + folder + '/'
  297. );
  298. }
  299. })
  300. );
  301. });
  302. Promise.all(promises).then(resolve);
  303. });
  304. });
  305. const copySpecs = (source, target) =>
  306. new Promise((resolve, reject) => {
  307. const replaceRegexp = new RegExp(source + '(Autocomplete|Syntax)Parser', 'g');
  308. mkdir(PARSER_FOLDER + target)
  309. .then(() => {
  310. mkdir(PARSER_FOLDER + target + '/spec')
  311. .then(() => {
  312. listDir(PARSER_FOLDER + source + '/spec')
  313. .then(specFiles => {
  314. const copyPromises = [];
  315. specFiles.forEach(specFile => {
  316. copyPromises.push(
  317. copyFile(
  318. PARSER_FOLDER + source + '/spec/' + specFile,
  319. PARSER_FOLDER + target + '/spec/' + specFile.replace(source, target),
  320. contents => contents.replace(replaceRegexp, target + '$1Parser')
  321. )
  322. );
  323. });
  324. Promise.all(copyPromises)
  325. .then(resolve)
  326. .catch(reject);
  327. })
  328. .catch(reject);
  329. })
  330. .catch(reject);
  331. })
  332. .catch(reject);
  333. });
  334. const prepareForNewParser = () =>
  335. new Promise((resolve, reject) => {
  336. if (process.argv.length === 3 && process.argv[0] === '-new') {
  337. process.argv.shift();
  338. const source = process.argv.shift();
  339. const target = process.argv.shift();
  340. console.log("Generating new parser '" + target + "' based on '" + source + "'...");
  341. process.argv.push(target);
  342. if (
  343. !Object.keys(parserDefinitions).some(key => {
  344. if (key.indexOf(source) === 0) {
  345. copySpecs(source, target)
  346. .then(() => {
  347. mkdir(JISON_FOLDER + 'sql/' + target)
  348. .then(() => {
  349. listDir(JISON_FOLDER + 'sql/' + source).then(files => {
  350. const copyPromises = [];
  351. files.forEach(file => {
  352. copyPromises.push(
  353. copyFile(
  354. JISON_FOLDER + 'sql/' + source + '/' + file,
  355. JISON_FOLDER + 'sql/' + target + '/' + file
  356. )
  357. );
  358. });
  359. Promise.all(copyPromises).then(() => {
  360. const autocompleteSources = [
  361. 'sql/' + target + '/autocomplete_header.jison'
  362. ];
  363. const syntaxSources = ['sql/' + target + '/syntax_header.jison'];
  364. files.forEach(file => {
  365. if (file.indexOf('sql_') === 0) {
  366. autocompleteSources.push('sql/' + target + '/' + file);
  367. syntaxSources.push('sql/' + target + '/' + file);
  368. }
  369. });
  370. autocompleteSources.push('sql/' + target + '/autocomplete_footer.jison');
  371. syntaxSources.push('sql/' + target + '/syntax_footer.jison');
  372. mkdir('desktop/core/src/desktop/js/parse/sql/' + target).then(() => {
  373. copyFile(
  374. 'desktop/core/src/desktop/js/parse/sql/' +
  375. source +
  376. '/sqlParseSupport.js',
  377. 'desktop/core/src/desktop/js/parse/sql/' +
  378. target +
  379. '/sqlParseSupport.js',
  380. contents =>
  381. contents.replace(
  382. /parser\.yy\.activeDialect = '[^']+';'/g,
  383. "parser.yy.activeDialect = '" + target + "';"
  384. )
  385. ).then(() => {
  386. identifySqlParsers()
  387. .then(resolve)
  388. .catch(reject);
  389. });
  390. });
  391. });
  392. });
  393. })
  394. .catch(err => {
  395. console.log(err);
  396. });
  397. })
  398. .catch(reject);
  399. return true;
  400. }
  401. })
  402. ) {
  403. reject("No existing parser found for '" + source + "'");
  404. }
  405. } else {
  406. resolve();
  407. }
  408. });
  409. identifySqlParsers().then(() => {
  410. process.argv.shift();
  411. process.argv.shift();
  412. prepareForNewParser().then(() => {
  413. process.argv.forEach(arg => {
  414. if (arg === 'all') {
  415. all = true;
  416. } else if (parserDefinitions[arg]) {
  417. parsersToGenerate.push(arg);
  418. } else {
  419. let prefixFound = false;
  420. Object.keys(parserDefinitions).forEach(key => {
  421. if (key.indexOf(arg) === 0) {
  422. prefixFound = true;
  423. parsersToGenerate.push(key);
  424. }
  425. });
  426. if (!prefixFound) {
  427. invalid.push(arg);
  428. }
  429. }
  430. });
  431. if (all) {
  432. parsersToGenerate = Object.keys(parserDefinitions);
  433. }
  434. if (invalid.length) {
  435. console.log("No parser config found for: '" + invalid.join("', '") + "'");
  436. console.log(
  437. '\nPossible options are:\n ' +
  438. ['all'].concat(Object.keys(parserDefinitions)).join('\n ') +
  439. '\n'
  440. );
  441. return;
  442. }
  443. const parserCount = parsersToGenerate.length;
  444. let idx = 0;
  445. const generateRecursive = () => {
  446. idx++;
  447. if (parsersToGenerate.length) {
  448. const parserName = parsersToGenerate.pop();
  449. if (parserCount > 1) {
  450. console.log("Generating '" + parserName + "' (" + idx + '/' + parserCount + ')...');
  451. } else {
  452. console.log("Generating '" + parserName + "'...");
  453. }
  454. generateParser(parserName)
  455. .then(generateRecursive)
  456. .catch(error => {
  457. console.log(error);
  458. console.log('FAIL!');
  459. });
  460. } else {
  461. const autocompParsers = [];
  462. const syntaxParsers = [];
  463. console.log('Updating sqlParserRepository.js...');
  464. Object.keys(parserDefinitions).forEach(key => {
  465. if (parserDefinitions[key].sqlParser === 'AUTOCOMPLETE') {
  466. autocompParsers.push(
  467. AUTOCOMPLETE_PARSER_IMPORT_TEMPLATE.replace(
  468. /KEY/g,
  469. key.replace('AutocompleteParser', '')
  470. )
  471. );
  472. } else if (parserDefinitions[key].sqlParser === 'SYNTAX') {
  473. syntaxParsers.push(
  474. SYNTAX_PARSER_IMPORT_TEMPLATE.replace(/KEY/g, key.replace('SyntaxParser', ''))
  475. );
  476. }
  477. });
  478. readFile(SQL_PARSER_REPOSITORY_PATH).then(contents => {
  479. contents = contents.replace(
  480. /const SYNTAX_MODULES = [^}]+}/,
  481. 'const SYNTAX_MODULES = {\n' + syntaxParsers.sort().join(',\n') + '\n}'
  482. );
  483. contents = contents.replace(
  484. /const AUTOCOMPLETE_MODULES = [^}]+}/,
  485. 'const AUTOCOMPLETE_MODULES = {\n' + autocompParsers.sort().join(',\n') + '\n}'
  486. );
  487. writeFile(SQL_PARSER_REPOSITORY_PATH, contents).then(() => {
  488. console.log('Done!\n');
  489. });
  490. });
  491. }
  492. };
  493. generateRecursive();
  494. });
  495. });
  496. /* eslint-enable no-restricted-syntax */