parseFromVisual.js 13 KB

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