generateParsers.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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 parserDefinitions = {
  42. globalSearchParser: {
  43. sources: ['globalSearchParser.jison'],
  44. target: 'globalSearchParser.jison',
  45. outputFolder: 'desktop/core/src/desktop/js/parse/',
  46. afterParse: contents =>
  47. new Promise(resolve => {
  48. resolve(
  49. LICENSE +
  50. contents.replace(
  51. 'var globalSearchParser = ',
  52. "import SqlParseSupport from 'parse/sqlParseSupport';\n\nvar globalSearchParser = "
  53. ) +
  54. '\nexport default globalSearchParser;\n'
  55. );
  56. })
  57. },
  58. solrFormulaParser: {
  59. sources: ['solrFormulaParser.jison'],
  60. target: 'solrFormulaParser.jison',
  61. outputFolder: 'desktop/core/src/desktop/js/parse/',
  62. afterParse: contents =>
  63. new Promise(resolve => {
  64. resolve(LICENSE + contents + 'export default solrFormulaParser;\n');
  65. })
  66. },
  67. solrQueryParser: {
  68. sources: ['solrQueryParser.jison'],
  69. target: 'solrQueryParser.jison',
  70. outputFolder: 'desktop/core/src/desktop/js/parse/',
  71. afterParse: contents =>
  72. new Promise(resolve => {
  73. resolve(LICENSE + contents + 'export default solrQueryParser;\n');
  74. })
  75. },
  76. sqlStatementsParser: {
  77. sources: ['sqlStatementsParser.jison'],
  78. target: 'sqlStatementsParser.jison',
  79. outputFolder: 'desktop/core/src/desktop/js/parse/',
  80. afterParse: contents =>
  81. new Promise(resolve => {
  82. resolve(
  83. LICENSE +
  84. contents.replace(
  85. 'parse: function parse',
  86. SQL_STATEMENTS_PARSER_JSDOC + 'parse: function parse'
  87. ) +
  88. 'export default sqlStatementsParser;\n'
  89. );
  90. })
  91. }
  92. };
  93. const readFile = path =>
  94. new Promise((resolve, reject) => {
  95. fs.readFile(path, (err, buf) => {
  96. if (err) {
  97. reject();
  98. }
  99. resolve(buf.toString());
  100. });
  101. });
  102. const writeFile = (path, contents) =>
  103. new Promise((resolve, reject) => {
  104. fs.writeFile(path, contents, err => {
  105. if (err) {
  106. reject();
  107. }
  108. resolve();
  109. });
  110. });
  111. const deleteFile = path => {
  112. fs.unlinkSync(path);
  113. };
  114. const execCmd = cmd =>
  115. new Promise((resolve, reject) => {
  116. exec(cmd, (err, stdout, stderr) => {
  117. if (err) {
  118. reject('stderr:\n' + stderr + '\n\nstdout:\n' + stdout);
  119. }
  120. resolve();
  121. });
  122. });
  123. const generateParser = parserName =>
  124. new Promise((resolve, reject) => {
  125. const parserConfig = parserDefinitions[parserName];
  126. const concatPromise = new Promise((resolve, reject) => {
  127. if (parserConfig.sources.length > 1 && parserConfig.target) {
  128. console.log('Concatenating files...');
  129. const promises = parserConfig.sources.map(fileName => readFile(JISON_FOLDER + fileName));
  130. Promise.all(promises)
  131. .then(contents => {
  132. writeFile(JISON_FOLDER + parserConfig.target, contents.join('')).then(() => {
  133. resolve(JISON_FOLDER + parserConfig.target);
  134. });
  135. })
  136. .catch(reject);
  137. } else if (parserConfig.sources.length === 1) {
  138. resolve(JISON_FOLDER + parserConfig.sources[0]);
  139. } else {
  140. reject('No jison source specified');
  141. }
  142. });
  143. concatPromise
  144. .then(targetPath => {
  145. let jisonCommand = 'jison ' + targetPath;
  146. if (parserConfig.lexer) {
  147. jisonCommand += ' ' + JISON_FOLDER + parserConfig.lexer;
  148. }
  149. jisonCommand += ' -m js';
  150. console.log('Generating parser...');
  151. execCmd(jisonCommand)
  152. .then(() => {
  153. if (parserConfig.sources.length > 1) {
  154. deleteFile(targetPath); // Remove concatenated file
  155. }
  156. console.log('Adjusting JS...');
  157. const generatedJsFileName = parserConfig.target.replace('.jison', '.js');
  158. readFile(generatedJsFileName)
  159. .then(contents => {
  160. parserConfig
  161. .afterParse(contents)
  162. .then(finalContents => {
  163. writeFile(parserConfig.outputFolder + generatedJsFileName, finalContents)
  164. .then(() => {
  165. deleteFile(generatedJsFileName);
  166. console.log('Done!\n');
  167. resolve();
  168. })
  169. .catch(reject);
  170. })
  171. .catch(reject);
  172. })
  173. .catch(reject);
  174. })
  175. .catch(reject);
  176. })
  177. .catch(reject);
  178. });
  179. let parsersToGenerate = [];
  180. const invalid = [];
  181. let all = false;
  182. let appFound = false;
  183. const listDir = folder =>
  184. new Promise(resolve => {
  185. fs.readdir(folder, (err, files) => {
  186. resolve(files);
  187. });
  188. });
  189. const findParser = (fileIndex, folder, sharedFiles, autocomplete) => {
  190. const prefix = autocomplete ? 'autocomplete' : 'syntax';
  191. if (fileIndex[prefix + '_header.jison'] && fileIndex[prefix + '_footer.jison']) {
  192. const parserName = folder + (autocomplete ? 'AutocompleteParser' : 'SyntaxParser');
  193. const parserDefinition = {
  194. sources: ['sql/' + folder + '/' + prefix + '_header.jison'].concat(sharedFiles),
  195. lexer: 'sql/' + folder + '/sql.jisonlex',
  196. target: 'sql/' + folder + '/' + parserName + '.jison',
  197. outputFolder: 'desktop/core/src/desktop/js/parse/sql/' + folder + '/',
  198. afterParse: contents =>
  199. new Promise(resolve => {
  200. resolve(
  201. LICENSE +
  202. contents
  203. .replace(
  204. 'var ' + parserName + ' = ',
  205. "import SqlParseSupport from 'parse/sql/" +
  206. folder +
  207. "/sqlParseSupport';\n\nvar " +
  208. parserName +
  209. ' = '
  210. )
  211. .replace(
  212. 'loc: yyloc,',
  213. "loc: lexer.yylloc, ruleId: stack.slice(stack.length - 2, stack.length).join(''),"
  214. ) +
  215. '\nexport default ' +
  216. parserName +
  217. ';\n'
  218. );
  219. })
  220. };
  221. parserDefinition.sources.push('sql/' + folder + '/' + prefix + '_footer.jison');
  222. parserDefinitions[parserName] = parserDefinition;
  223. } else {
  224. console.log(
  225. "Warn: Could not find '" +
  226. prefix +
  227. "_header.jison' or '" +
  228. prefix +
  229. "_footer.jison' in " +
  230. JISON_FOLDER +
  231. 'sql/' +
  232. folder +
  233. '/'
  234. );
  235. }
  236. };
  237. const identifySqlParsers = () =>
  238. new Promise(resolve => {
  239. listDir(JISON_FOLDER + 'sql').then(files => {
  240. const promises = [];
  241. files.forEach(folder => {
  242. promises.push(
  243. listDir(JISON_FOLDER + 'sql/' + folder).then(jisonFiles => {
  244. const fileIndex = {};
  245. jisonFiles.forEach(jisonFile => {
  246. fileIndex[jisonFile] = true;
  247. });
  248. const sharedFiles = jisonFiles
  249. .filter(jisonFile => jisonFile.indexOf('sql_') !== -1)
  250. .map(jisonFile => 'sql/' + folder + '/' + jisonFile);
  251. if (fileIndex['sql.jisonlex']) {
  252. findParser(fileIndex, folder, sharedFiles, true);
  253. findParser(fileIndex, folder, sharedFiles, false);
  254. } else {
  255. console.log(
  256. "Warn: Could not find 'sql.jisonlex' in " + JISON_FOLDER + 'sql/' + folder + '/'
  257. );
  258. }
  259. })
  260. );
  261. });
  262. Promise.all(promises).then(resolve);
  263. });
  264. });
  265. identifySqlParsers().then(() => {
  266. process.argv.forEach(arg => {
  267. if (appFound) {
  268. if (arg === 'all') {
  269. all = true;
  270. } else if (parserDefinitions[arg]) {
  271. parsersToGenerate.push(arg);
  272. } else {
  273. let prefixFound = false;
  274. Object.keys(parserDefinitions).forEach(key => {
  275. if (key.indexOf(arg) === 0) {
  276. prefixFound = true;
  277. parsersToGenerate.push(key);
  278. }
  279. });
  280. if (!prefixFound) {
  281. invalid.push(arg);
  282. }
  283. }
  284. } else if (arg.indexOf('generateParsers.js') !== -1) {
  285. appFound = true;
  286. }
  287. });
  288. if (all) {
  289. parsersToGenerate = Object.keys(parserDefinitions);
  290. }
  291. if (invalid.length) {
  292. console.log("No parser config found for: '" + invalid.join("', '") + "'");
  293. console.log(
  294. '\nPossible options are:\n ' +
  295. ['all'].concat(Object.keys(parserDefinitions)).join('\n ') +
  296. '\n'
  297. );
  298. return;
  299. }
  300. const parserCount = parsersToGenerate.length;
  301. let idx = 0;
  302. const generateRecursive = () => {
  303. idx++;
  304. if (parsersToGenerate.length) {
  305. const parserName = parsersToGenerate.pop();
  306. if (parserCount > 1) {
  307. console.log("Generating '" + parserName + "' (" + idx + '/' + parserCount + ')...');
  308. } else {
  309. console.log("Generating '" + parserName + "'...");
  310. }
  311. generateParser(parserName)
  312. .then(generateRecursive)
  313. .catch(error => {
  314. console.log(error);
  315. console.log('FAIL!');
  316. });
  317. }
  318. };
  319. generateRecursive();
  320. });