parseFromVisual.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. import { IVProgParser } from "../ast/ivprogParser";
  2. import * as Expressions from "../ast/expressions";
  3. import { Types } from "../typeSystem/types";
  4. import { convertBoolToString } from "../typeSystem/parsers";
  5. import * as Commands from "../ast/commands";
  6. import { ArrayType } from "../typeSystem/array_type";
  7. import { Literal } from "../ast/expressions/literal";
  8. const TYPES = {
  9. VARIABLE: "var",
  10. CONST: "const",
  11. FUNCTION: "function",
  12. RELATIONAL: "relational",
  13. LOGIC: "logic",
  14. ARITHMETIC: "arithmetic",
  15. };
  16. function translateOp (type, op) {
  17. switch (type) {
  18. case TYPES.ARITHMETIC:
  19. return op.value;
  20. case TYPES.RELATIONAL:
  21. return op.value;
  22. case TYPES.LOGIC: {
  23. if (op.ord === 11) {
  24. return "and";
  25. } else if (op.ord === 12) {
  26. return "or";
  27. } else {
  28. return "not";
  29. }
  30. }
  31. }
  32. }
  33. function getOpType (op) {
  34. switch (op.ord) {
  35. case 0:
  36. case 1:
  37. case 2:
  38. case 3:
  39. case 4:
  40. return TYPES.ARITHMETIC;
  41. case 5:
  42. case 6:
  43. case 7:
  44. case 8:
  45. case 9:
  46. case 10:
  47. return TYPES.RELATIONAL;
  48. default:
  49. return TYPES.LOGIC;
  50. }
  51. }
  52. /**
  53. * @param {Commands.Case} switchCase
  54. * */
  55. function switchCaseWalker (switchCase) {
  56. const commands = switchCase.commands.map(commandWalker);
  57. const expression = switchCase.isDefault
  58. ? null
  59. : expressionWalker(switchCase.expression);
  60. return {
  61. type: "switchcase",
  62. expression,
  63. commands,
  64. };
  65. }
  66. /**
  67. * @param {Commands.Switch} switchCommand
  68. * */
  69. function switchWalker (switchCommand) {
  70. const expression = expressionWalker(switchCommand.expression);
  71. const cases = switchCommand.cases.map(switchCaseWalker);
  72. return {
  73. type: "switch",
  74. expression,
  75. cases,
  76. };
  77. }
  78. /**
  79. * @param {Commands.Return} returnCommand
  80. * */
  81. function returnWalker (returnCommand) {
  82. const expression = expressionWalker(returnCommand.expression);
  83. return {
  84. type: "return",
  85. expression,
  86. };
  87. }
  88. function breakWalker (_) {
  89. return { type: "break" };
  90. }
  91. /**
  92. * @param {Commands.For} forLoop
  93. * */
  94. // function forWalker (forLoop) {
  95. //
  96. // const var_attribution = forLoop.for_id;
  97. // const commands = forLoop.commands.map(commandWalker)
  98. //
  99. // return {var_attribution,
  100. // var_incrementation,
  101. // expression1,
  102. // expression2,
  103. // expression3,
  104. // commands,
  105. // }
  106. // }
  107. /**
  108. * @param {Commands.While} whileLoop
  109. * */
  110. function whileWalker (whileLoop) {
  111. const expression = expressionWalker(whileLoop.expression);
  112. const commands = whileLoop.commands.map(commandWalker);
  113. let type = whileLoop.testFirst ? "whiletrue" : "dowhiletrue";
  114. return {
  115. type,
  116. expression,
  117. commands,
  118. };
  119. }
  120. /**
  121. * @param {Commands.IfThenElse} ifthenelse
  122. * */
  123. function ifThenElseWalker (ifthenelse) {
  124. //ifthenelse.
  125. const expression = expressionWalker(ifthenelse.condition);
  126. const ifTrue = ifthenelse.ifTrue.commands.map(commandWalker);
  127. let ifFalse = [];
  128. if (ifthenelse.ifFalse) {
  129. if (ifthenelse.ifFalse instanceof Commands.CommandBlock) {
  130. ifFalse = ifthenelse.ifFalse.commands.map(commandWalker);
  131. } else {
  132. ifFalse = [ifThenElseWalker(ifthenelse.ifFalse)];
  133. }
  134. }
  135. return {
  136. type: "iftrue",
  137. expression,
  138. ifTrue,
  139. ifFalse,
  140. };
  141. }
  142. /**
  143. * @param {Commands.Assign} assingment
  144. * */
  145. function assignmentWalker (assingment) {
  146. let variable = null;
  147. if (assingment instanceof Commands.ArrayIndexAssign) {
  148. const line = expressionWalker(assingment.line);
  149. let arrayClass = "vector";
  150. let column = null;
  151. if (assingment.column) {
  152. arrayClass = "matrix";
  153. column = expressionWalker(assingment.column);
  154. }
  155. variable = [
  156. {
  157. instance: "expression",
  158. type: TYPES.VARIABLE,
  159. class: arrayClass,
  160. column: column,
  161. line: line,
  162. value: assingment.id,
  163. },
  164. ];
  165. } else {
  166. variable = [
  167. { instance: "expression", type: TYPES.VARIABLE, value: assingment.id },
  168. ];
  169. }
  170. const expression = expressionWalker(assingment.expression);
  171. return {
  172. type: "attribution",
  173. variable,
  174. expression,
  175. };
  176. }
  177. /**
  178. * @param {Command} command
  179. * */
  180. function commandWalker (command) {
  181. let parsedCommand = null;
  182. if (command instanceof Commands.FunctionCall) {
  183. parsedCommand = functionCallWalker(command);
  184. } else if (command instanceof Commands.Assign) {
  185. parsedCommand = assignmentWalker(command);
  186. } else if (command instanceof Commands.IfThenElse) {
  187. parsedCommand = ifThenElseWalker(command);
  188. } else if (command instanceof Commands.While) {
  189. parsedCommand = whileWalker(command);
  190. } else if (command instanceof Commands.Break) {
  191. parsedCommand = breakWalker(command);
  192. } else if (command instanceof Commands.Return) {
  193. parsedCommand = returnWalker(command);
  194. } else if (command instanceof Commands.Switch) {
  195. parsedCommand = switchWalker(command);
  196. } else {
  197. throw new Error("not implemented");
  198. }
  199. parsedCommand.line = command.sourceInfo.line;
  200. return parsedCommand;
  201. }
  202. /**
  203. * @param {Commands.FunctionCall} functionCall
  204. * */
  205. function functionCallWalker (functionCall) {
  206. let name = functionCall.id;
  207. if (name.indexOf(".") !== -1) {
  208. name = name.split(".")[1];
  209. }
  210. const parameters = functionCall.actualParameters.map(expressionWalker);
  211. if (name === "$write") {
  212. const lastInput = parameters[parameters.length - 1][0];
  213. // if lastInput is an object with value === '\n', newLine is true
  214. const newLine = lastInput.value && lastInput.value.match(/^\n$/) !== null;
  215. const content = newLine
  216. ? parameters.slice(0, parameters.length - 1)
  217. : parameters;
  218. return {
  219. type: "writer",
  220. newLine,
  221. content,
  222. };
  223. }
  224. if (name === "$read") {
  225. return {
  226. type: "reader",
  227. variable: parameters[0],
  228. };
  229. }
  230. return {
  231. type: "functioncall",
  232. parameters_list: parameters,
  233. name: functionCall.id,
  234. };
  235. }
  236. /**
  237. * @param {Commands.Function} func
  238. * */
  239. function functionWalker (func) {
  240. const funcDeclaration = {
  241. name: func.name,
  242. line: func.sourceInfo.line,
  243. return_type: "",
  244. return_dimensions: 0,
  245. parameters_list: [],
  246. variables_list: [],
  247. commands: [],
  248. };
  249. if (func.returnType instanceof ArrayType) {
  250. funcDeclaration.return_type = func.returnType.innerType.value;
  251. funcDeclaration.return_dimensions = func.returnType.dimensions;
  252. } else {
  253. funcDeclaration.return_type = func.returnType.value;
  254. }
  255. funcDeclaration.parameters_list = func.formalParameters.map(
  256. functionParameterWalker
  257. );
  258. funcDeclaration.variables_list = func.variablesDeclarations.map(
  259. variableDeclarationWalker
  260. );
  261. funcDeclaration.commands = func.commands.map(commandWalker);
  262. return funcDeclaration;
  263. }
  264. /**
  265. * @param {Commands.FormalParameter} formalParameter
  266. * */
  267. function functionParameterWalker (formalParameter) {
  268. const variable = {
  269. name: formalParameter.id,
  270. line: formalParameter.sourceInfo.line,
  271. type: "",
  272. rows: 0,
  273. columns: 0,
  274. dimension: 0,
  275. value: 0,
  276. is_const: false,
  277. reference: formalParameter.byRef,
  278. };
  279. if (formalParameter.type instanceof ArrayType) {
  280. variable.type = formalParameter.type.innerType.value;
  281. variable.dimension = formalParameter.type.dimensions;
  282. } else {
  283. variable.type = formalParameter.type.value;
  284. }
  285. return variable;
  286. }
  287. /**
  288. * @param {Commands.Declaration} command
  289. * @param {boolean} global
  290. * */
  291. function variableDeclarationWalker (command, global = false) {
  292. const variable = {
  293. name: command.id,
  294. line: command.sourceInfo.line,
  295. type: "",
  296. rows: 0,
  297. columns: 0,
  298. dimension: 0,
  299. value: 0,
  300. is_const: false,
  301. };
  302. variable.is_const = global && command.isConst;
  303. if (command instanceof Commands.ArrayDeclaration) {
  304. // array
  305. const lines = expressionWalker(command.lines).pop();
  306. variable.type = command.type.innerType.value;
  307. if (command.isVector) {
  308. variable.columns = lines.value;
  309. variable.dimension = 1;
  310. const values = command.initial.value.map((exp) =>
  311. variableInitialWalker(exp)
  312. );
  313. variable.value = values;
  314. } else {
  315. const columns = expressionWalker(command.columns).pop();
  316. variable.dimension = 2;
  317. variable.rows = lines.value;
  318. variable.columns = columns.value;
  319. const values = command.initial.value.map((rows) =>
  320. rows.value.map((exp) => variableInitialWalker(exp))
  321. );
  322. variable.value = values;
  323. }
  324. } else {
  325. // atomic
  326. variable.type = command.type.value;
  327. variable.value = variableInitialWalker(command.initial);
  328. }
  329. return variable;
  330. }
  331. /**
  332. * @param {any} expression
  333. * */
  334. function variableInitialWalker (expression) {
  335. if (expression instanceof Expressions.UnaryApp) {
  336. const left = variableInitialWalker(expression.left);
  337. const opType = getOpType(expression.op);
  338. if (opType !== TYPES.ARITHMETIC) {
  339. throw new Error(
  340. "invalid variable initial value: " + expression.toString()
  341. );
  342. }
  343. return `${expression.op.value}${left}`;
  344. } else if (expression instanceof Expressions.BoolLiteral) {
  345. const value = expression.value;
  346. return convertBoolToString(value);
  347. } else if (expression instanceof Literal) {
  348. let value = expression.value;
  349. if (expression.value.toNumber) {
  350. if (
  351. Types.REAL.isCompatible(expression.type) &&
  352. expression.value.decimalPlaces() == 0
  353. ) {
  354. value = expression.value.toFixed(2);
  355. } else {
  356. value = expression.value.toNumber();
  357. }
  358. }
  359. return value;
  360. }
  361. throw new Error("invalid variable initial value: " + expression.toString());
  362. }
  363. /**
  364. *
  365. * @return {[]}
  366. **/
  367. function expressionWalker (expression) {
  368. let result;
  369. if (expression instanceof Expressions.VariableLiteral) {
  370. result = [
  371. { instance: "expression", type: TYPES.VARIABLE, value: expression.id },
  372. ];
  373. } else if (expression instanceof Expressions.FunctionCall) {
  374. const funcObj = {
  375. instance: "expression",
  376. type: TYPES.FUNCTION,
  377. value: expression.id,
  378. };
  379. const paramsList = expression.actualParameters.map((e) =>
  380. expressionWalker(e)
  381. );
  382. //const params = Array.prototype.concat.apply([], paramsList);
  383. funcObj.params = paramsList;
  384. result = [funcObj];
  385. } else if (expression instanceof Expressions.UnaryApp) {
  386. console.log(expression);
  387. const left = expressionWalker(expression.left);
  388. const opType = getOpType(expression.op);
  389. const opValue = translateOp(opType, expression.op);
  390. result = [{ instance: "operator", type: opType, value: opValue }, ...left];
  391. } else if (expression instanceof Expressions.InfixApp) {
  392. const left = expressionWalker(expression.left);
  393. const right = expressionWalker(expression.right);
  394. const opType = getOpType(expression.op);
  395. const opValue = translateOp(opType, expression.op);
  396. result = [
  397. ...left,
  398. { instance: "operator", type: opType, value: opValue },
  399. ...right,
  400. ];
  401. } else if (expression instanceof Expressions.ArrayAccess) {
  402. const line = expressionWalker(expression.line);
  403. let arrayClass = "vector";
  404. let column = null;
  405. if (expression.column) {
  406. arrayClass = "matrix";
  407. column = expressionWalker(expression.column);
  408. }
  409. result = [
  410. {
  411. instance: "expression",
  412. type: TYPES.VARIABLE,
  413. class: arrayClass,
  414. column: column,
  415. line: line,
  416. value: expression.id,
  417. },
  418. ];
  419. } else if (expression instanceof Expressions.BoolLiteral) {
  420. const value = expression.value;
  421. result = [
  422. {
  423. instance: "expression",
  424. class: "simple",
  425. type: TYPES.CONST,
  426. value: convertBoolToString(value),
  427. },
  428. ];
  429. } else {
  430. let value = expression.value;
  431. if (expression.value.toNumber) {
  432. if (
  433. Types.REAL.isCompatible(expression.type) &&
  434. expression.value.decimalPlaces() == 0
  435. ) {
  436. value = expression.value.toFixed(2);
  437. } else {
  438. value = expression.value.toNumber();
  439. }
  440. }
  441. result = [
  442. {
  443. instance: "expression",
  444. class: "simple",
  445. type: TYPES.CONST,
  446. value: value,
  447. },
  448. ];
  449. }
  450. if (expression.parenthesis) return ["(", ...result, ")"];
  451. else return result;
  452. }
  453. export function parseExpression (text) {
  454. const parser = IVProgParser.createParser(text);
  455. const expressionAST = parser.parseExpressionOR();
  456. return expressionWalker(expressionAST);
  457. }
  458. /**
  459. * @param {string} text
  460. * */
  461. export function parseCode (text) {
  462. const parser = IVProgParser.createParser(text, false);
  463. const codeLinesMap = new Map();
  464. const tokens = Array.from(parser.lexer.reset(text));
  465. const tokenStream = [];
  466. for (const token of tokens) {
  467. if (token.type === parser.ruleNames.ERROR) {
  468. return null;
  469. }
  470. if (token.type === parser.ruleNames.COMMENTS) {
  471. for (let i = 0; i <= token.lineBreaks; i++) {
  472. if (codeLinesMap.has(i + token.line))
  473. codeLinesMap.get(i + token.line).push(token);
  474. else codeLinesMap.set(i + token.line, [token]);
  475. }
  476. continue;
  477. }
  478. if (token.type !== parser.ruleNames.WHITESPACE) {
  479. tokenStream.push(token);
  480. }
  481. }
  482. parser.fill(tokenStream);
  483. try {
  484. const program = parser.parseTree();
  485. const globals = program.global.map((decl) =>
  486. variableDeclarationWalker(decl, true)
  487. );
  488. const functions = program.functions.map(functionWalker);
  489. return { globals, functions };
  490. } catch (e) {
  491. console.error(e)
  492. return null;
  493. }
  494. }