parseFromVisual.js 15 KB

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