generateParsers.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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.ts';
  46. const SYNTAX_PARSER_IMPORT_TEMPLATE =
  47. ' KEY: () => import(/* webpackChunkName: "KEY-parser" */ \'./KEY/KEYSyntaxParser\')';
  48. const AUTOCOMPLETE_PARSER_IMPORT_TEMPLATE =
  49. ' KEY: () => import(/* webpackChunkName: "KEY-parser" */ \'./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 addParserDefinition = (sources, dialect, autocomplete, lexer) => {
  218. const parserName = dialect + (autocomplete ? 'AutocompleteParser' : 'SyntaxParser');
  219. const parserDefinition = {
  220. sources: sources,
  221. lexer: 'sql/' + dialect + '/' + lexer,
  222. target: 'sql/' + dialect + '/' + parserName + '.jison',
  223. sqlParser: autocomplete ? 'AUTOCOMPLETE' : 'SYNTAX',
  224. outputFolder: OUTPUT_FOLDER + 'sql/' + dialect + '/',
  225. afterParse: contents =>
  226. new Promise(resolve => {
  227. resolve(
  228. LICENSE +
  229. contents
  230. .replace(
  231. 'var ' + parserName + ' = ',
  232. "import SqlParseSupport from 'parse/sql/" +
  233. dialect +
  234. "/sqlParseSupport';\n\nvar " +
  235. parserName +
  236. ' = '
  237. )
  238. .replace(
  239. 'loc: yyloc,',
  240. "loc: lexer.yylloc, ruleId: stack.slice(stack.length - 2, stack.length).join(''),"
  241. ) +
  242. '\nexport default ' +
  243. parserName +
  244. ';\n'
  245. );
  246. })
  247. };
  248. parserDefinitions[parserName] = parserDefinition;
  249. };
  250. const addParsersFromStructure = (structure, dialect) => {
  251. addParserDefinition(
  252. structure.autocomplete.map(source => 'sql/' + dialect + '/' + source),
  253. dialect,
  254. true,
  255. structure.lexer
  256. );
  257. addParserDefinition(
  258. structure.syntax.map(source => 'sql/' + dialect + '/' + source),
  259. dialect,
  260. false,
  261. structure.lexer
  262. );
  263. };
  264. const identifySqlParsers = () =>
  265. new Promise(resolve => {
  266. listDir(JISON_FOLDER + 'sql').then(files => {
  267. const promises = [];
  268. files.forEach(folder => {
  269. promises.push(
  270. listDir(JISON_FOLDER + 'sql/' + folder).then(async jisonFiles => {
  271. if (jisonFiles.find(fileName => fileName === 'structure.json')) {
  272. const structure = JSON.parse(
  273. await readFile(JISON_FOLDER + 'sql/' + folder + '/structure.json')
  274. );
  275. addParsersFromStructure(structure, folder);
  276. } else {
  277. console.log(
  278. "Warn: Could not find 'structure.jisonlex' in " +
  279. JISON_FOLDER +
  280. 'sql/' +
  281. folder +
  282. '/'
  283. );
  284. }
  285. })
  286. );
  287. });
  288. Promise.all(promises).then(resolve);
  289. });
  290. });
  291. const copyTests = (source, target) =>
  292. new Promise((resolve, reject) => {
  293. const replaceRegexp = new RegExp(source + '(Autocomplete|Syntax)Parser', 'g');
  294. mkdir(PARSER_FOLDER + target)
  295. .then(() => {
  296. mkdir(PARSER_FOLDER + target + '/test')
  297. .then(() => {
  298. listDir(PARSER_FOLDER + source + '/test')
  299. .then(testFiles => {
  300. const copyPromises = [];
  301. testFiles.forEach(testFile => {
  302. copyPromises.push(
  303. copyFile(
  304. PARSER_FOLDER + source + '/test/' + testFile,
  305. PARSER_FOLDER + target + '/test/' + testFile.replace(source, target),
  306. contents => contents.replace(replaceRegexp, target + '$1Parser')
  307. )
  308. );
  309. });
  310. Promise.all(copyPromises).then(resolve).catch(reject);
  311. })
  312. .catch(reject);
  313. })
  314. .catch(reject);
  315. })
  316. .catch(reject);
  317. });
  318. const prepareForNewParser = () =>
  319. new Promise((resolve, reject) => {
  320. if (process.argv.length === 3 && process.argv[0] === '-new') {
  321. process.argv.shift();
  322. const source = process.argv.shift();
  323. const target = process.argv.shift();
  324. console.log("Generating new parser '" + target + "' based on '" + source + "'...");
  325. process.argv.push(target);
  326. if (
  327. !Object.keys(parserDefinitions).some(key => {
  328. if (key.indexOf(source) === 0) {
  329. copyTests(source, target)
  330. .then(() => {
  331. mkdir(JISON_FOLDER + 'sql/' + target)
  332. .then(() => {
  333. listDir(JISON_FOLDER + 'sql/' + source).then(files => {
  334. const copyPromises = [];
  335. files.forEach(file => {
  336. copyPromises.push(
  337. copyFile(
  338. JISON_FOLDER + 'sql/' + source + '/' + file,
  339. JISON_FOLDER + 'sql/' + target + '/' + file
  340. )
  341. );
  342. });
  343. Promise.all(copyPromises).then(() => {
  344. const autocompleteSources = [
  345. 'sql/' + target + '/autocomplete_header.jison'
  346. ];
  347. const syntaxSources = ['sql/' + target + '/syntax_header.jison'];
  348. files.forEach(file => {
  349. if (file.indexOf('sql_') === 0) {
  350. autocompleteSources.push('sql/' + target + '/' + file);
  351. syntaxSources.push('sql/' + target + '/' + file);
  352. }
  353. });
  354. autocompleteSources.push('sql/' + target + '/autocomplete_footer.jison');
  355. syntaxSources.push('sql/' + target + '/syntax_footer.jison');
  356. mkdir(PARSER_FOLDER + target).then(() => {
  357. copyFile(
  358. PARSER_FOLDER + source + '/sqlParseSupport.js',
  359. PARSER_FOLDER + target + '/sqlParseSupport.js',
  360. contents =>
  361. contents.replace(
  362. /parser\.yy\.activeDialect = '[^']+';'/g,
  363. "parser.yy.activeDialect = '" + target + "';"
  364. )
  365. ).then(() => {
  366. identifySqlParsers().then(resolve).catch(reject);
  367. });
  368. });
  369. });
  370. });
  371. })
  372. .catch(err => {
  373. console.log(err);
  374. });
  375. })
  376. .catch(reject);
  377. return true;
  378. }
  379. })
  380. ) {
  381. reject("No existing parser found for '" + source + "'");
  382. }
  383. } else {
  384. resolve();
  385. }
  386. });
  387. identifySqlParsers().then(() => {
  388. process.argv.shift();
  389. process.argv.shift();
  390. prepareForNewParser().then(() => {
  391. process.argv.forEach(arg => {
  392. if (arg === 'all') {
  393. all = true;
  394. } else if (parserDefinitions[arg]) {
  395. parsersToGenerate.push(arg);
  396. } else {
  397. let prefixFound = false;
  398. Object.keys(parserDefinitions).forEach(key => {
  399. if (key.indexOf(arg) === 0) {
  400. prefixFound = true;
  401. parsersToGenerate.push(key);
  402. }
  403. });
  404. if (!prefixFound) {
  405. invalid.push(arg);
  406. }
  407. }
  408. });
  409. if (all) {
  410. parsersToGenerate = Object.keys(parserDefinitions);
  411. }
  412. if (invalid.length) {
  413. console.log("No parser config found for: '" + invalid.join("', '") + "'");
  414. console.log(
  415. '\nPossible options are:\n ' +
  416. ['all'].concat(Object.keys(parserDefinitions)).join('\n ') +
  417. '\n'
  418. );
  419. return;
  420. }
  421. const parserCount = parsersToGenerate.length;
  422. let idx = 0;
  423. const generateRecursive = () => {
  424. idx++;
  425. if (parsersToGenerate.length) {
  426. const parserName = parsersToGenerate.pop();
  427. if (parserCount > 1) {
  428. console.log("Generating '" + parserName + "' (" + idx + '/' + parserCount + ')...');
  429. } else {
  430. console.log("Generating '" + parserName + "'...");
  431. }
  432. generateParser(parserName)
  433. .then(generateRecursive)
  434. .catch(error => {
  435. console.log(error);
  436. console.log('FAIL!');
  437. });
  438. } else {
  439. const autocompParsers = [];
  440. const syntaxParsers = [];
  441. console.log('Updating sqlParserRepository.ts...');
  442. Object.keys(parserDefinitions).forEach(key => {
  443. if (parserDefinitions[key].sqlParser === 'AUTOCOMPLETE') {
  444. autocompParsers.push(
  445. AUTOCOMPLETE_PARSER_IMPORT_TEMPLATE.replace(
  446. /KEY/g,
  447. key.replace('AutocompleteParser', '')
  448. )
  449. );
  450. } else if (parserDefinitions[key].sqlParser === 'SYNTAX') {
  451. syntaxParsers.push(
  452. SYNTAX_PARSER_IMPORT_TEMPLATE.replace(/KEY/g, key.replace('SyntaxParser', ''))
  453. );
  454. }
  455. });
  456. readFile(SQL_PARSER_REPOSITORY_PATH).then(contents => {
  457. contents = contents.replace(
  458. /const SYNTAX_MODULES = [^}]+}/,
  459. 'const SYNTAX_MODULES = {\n' + syntaxParsers.sort().join(',\n') + '\n}'
  460. );
  461. contents = contents.replace(
  462. /const AUTOCOMPLETE_MODULES = [^}]+}/,
  463. 'const AUTOCOMPLETE_MODULES = {\n' + autocompParsers.sort().join(',\n') + '\n}'
  464. );
  465. writeFile(SQL_PARSER_REPOSITORY_PATH, contents).then(() => {
  466. console.log('Done!\n');
  467. });
  468. });
  469. }
  470. };
  471. generateRecursive();
  472. });
  473. });
  474. /* eslint-enable no-restricted-syntax */