generateParsers.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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:\n' + stderr + '\n\nstdout:\n' + stdout);
  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.join('')).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. const findParser = (fileIndex, folder, sharedFiles, autocomplete) => {
  187. const prefix = autocomplete ? 'autocomplete' : 'syntax';
  188. if (fileIndex[prefix + '_header.jison'] && fileIndex[prefix + '_footer.jison']) {
  189. const parserName = folder + (autocomplete ? 'AutocompleteParser' : 'SyntaxParser');
  190. const parserDefinition = {
  191. sources: ['sql/' + folder + '/' + prefix + '_header.jison'].concat(sharedFiles),
  192. lexer: 'sql/' + folder + '/sql.jisonlex',
  193. target: 'sql/' + folder + '/' + parserName + '.jison',
  194. afterParse: contents =>
  195. new Promise(resolve => {
  196. resolve(
  197. LICENSE +
  198. contents
  199. .replace(
  200. 'var ' + parserName + ' = ',
  201. "import SqlParseSupport from 'parse/sqlParseSupport';\n\nvar " +
  202. parserName +
  203. ' = '
  204. )
  205. .replace(
  206. 'loc: yyloc,',
  207. "loc: lexer.yylloc, ruleId: stack.slice(stack.length - 2, stack.length).join(''),"
  208. ) +
  209. '\nexport default ' +
  210. parserName +
  211. ';\n'
  212. );
  213. })
  214. };
  215. parserDefinition.sources.push('sql/' + folder + '/' + prefix + '_footer.jison');
  216. parserDefinitions[parserName] = parserDefinition;
  217. } else {
  218. console.log(
  219. "Warn: Could not find '" +
  220. prefix +
  221. "_header.jison' or '" +
  222. prefix +
  223. "_footer.jison' in " +
  224. JISON_FOLDER +
  225. 'sql/' +
  226. folder +
  227. '/'
  228. );
  229. }
  230. };
  231. const identifySqlParsers = () =>
  232. new Promise(resolve => {
  233. listDir(JISON_FOLDER + 'sql').then(files => {
  234. const promises = [];
  235. files.forEach(folder => {
  236. promises.push(
  237. listDir(JISON_FOLDER + 'sql/' + folder).then(jisonFiles => {
  238. const fileIndex = {};
  239. jisonFiles.forEach(jisonFile => {
  240. fileIndex[jisonFile] = true;
  241. });
  242. const sharedFiles = jisonFiles
  243. .filter(jisonFile => jisonFile.indexOf('sql_') !== -1)
  244. .map(jisonFile => 'sql/' + folder + '/' + jisonFile);
  245. if (fileIndex['sql.jisonlex']) {
  246. findParser(fileIndex, folder, sharedFiles, true);
  247. findParser(fileIndex, folder, sharedFiles, false);
  248. } else {
  249. console.log(
  250. "Warn: Could not find 'sql.jisonlex' in " + JISON_FOLDER + 'sql/' + folder + '/'
  251. );
  252. }
  253. })
  254. );
  255. });
  256. Promise.all(promises).then(resolve);
  257. });
  258. });
  259. identifySqlParsers().then(() => {
  260. process.argv.forEach(arg => {
  261. if (appFound) {
  262. if (arg === 'all') {
  263. all = true;
  264. } else if (parserDefinitions[arg]) {
  265. parsersToGenerate.push(arg);
  266. } else {
  267. invalid.push(arg);
  268. }
  269. } else if (arg.indexOf('generateParsers.js') !== -1) {
  270. appFound = true;
  271. }
  272. });
  273. if (all) {
  274. parsersToGenerate = Object.keys(parserDefinitions);
  275. }
  276. if (invalid.length) {
  277. console.log("No parser config found for: '" + invalid.join("', '") + "'");
  278. console.log(
  279. '\nPossible options are:\n ' +
  280. ['all'].concat(Object.keys(parserDefinitions)).join('\n ') +
  281. '\n'
  282. );
  283. return;
  284. }
  285. const parserCount = parsersToGenerate.length;
  286. let idx = 0;
  287. const generateRecursive = () => {
  288. idx++;
  289. if (parsersToGenerate.length) {
  290. const parserName = parsersToGenerate.pop();
  291. if (parserCount > 1) {
  292. console.log("Generating '" + parserName + "' (" + idx + '/' + parserCount + ')...');
  293. } else {
  294. console.log("Generating '" + parserName + "'...");
  295. }
  296. generateParser(parserName)
  297. .then(generateRecursive)
  298. .catch(error => {
  299. console.log(error);
  300. console.log('FAIL!');
  301. });
  302. }
  303. };
  304. generateRecursive();
  305. });