generateParsers.js 11 KB

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