generateParsers.js 17 KB

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