generateParsers.js 16 KB

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