parseFromVisual.js 13 KB

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