parseFromVisual.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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.IfThenElse} ifthenelse
  54. * */
  55. function ifThenElseWalker (ifthenelse) {
  56. //ifthenelse.
  57. const expression = expressionWalker(ifthenelse.condition);
  58. const ifTrue = ifthenelse.ifTrue.commands.map(commandWalker);
  59. let ifFalse = [];
  60. if (ifthenelse.ifFalse) {
  61. if (ifthenelse.ifFalse instanceof Commands.CommandBlock) {
  62. ifFalse = ifthenelse.ifFalse.commands.map(commandWalker);
  63. } else {
  64. ifFalse = [ifThenElseWalker(ifthenelse.ifFalse)];
  65. }
  66. }
  67. return {
  68. type: "iftrue",
  69. expression,
  70. ifTrue,
  71. ifFalse,
  72. };
  73. }
  74. /**
  75. * @param {Commands.Assign} assingment
  76. * */
  77. function assignmentWalker (assingment) {
  78. let variable = null;
  79. if (assingment instanceof Commands.ArrayIndexAssign) {
  80. const line = expressionWalker(assingment.line);
  81. let arrayClass = "vector";
  82. let column = null;
  83. if (assingment.column) {
  84. arrayClass = "matrix";
  85. column = expressionWalker(assingment.column);
  86. }
  87. variable = [
  88. {
  89. instance: "expression",
  90. type: TYPES.VARIABLE,
  91. class: arrayClass,
  92. column: column,
  93. line: line,
  94. value: assingment.id,
  95. },
  96. ];
  97. } else {
  98. variable = [
  99. { instance: "expression", type: TYPES.VARIABLE, value: assingment.id },
  100. ];
  101. }
  102. const expression = expressionWalker(assingment.expression);
  103. return {
  104. type: "attribution",
  105. variable,
  106. expression,
  107. };
  108. }
  109. /**
  110. * @param {Command} command
  111. * */
  112. function commandWalker (command) {
  113. if (command instanceof Commands.FunctionCall) {
  114. return functionCallWalker(command);
  115. } else if (command instanceof Commands.Assign) {
  116. return assignmentWalker(command);
  117. } else if (command instanceof Commands.IfThenElse) {
  118. return ifThenElseWalker(command);
  119. }
  120. throw new Error("not implemented");
  121. }
  122. /**
  123. * @param {Commands.FunctionCall} functionCall
  124. * */
  125. function functionCallWalker (functionCall) {
  126. let name = functionCall.id;
  127. if (name.indexOf(".") !== -1) {
  128. name = name.split(".")[1];
  129. }
  130. const parameters = functionCall.actualParameters.map(expressionWalker);
  131. if (name === "$write") {
  132. const lastInput = parameters[parameters.length - 1][0];
  133. // if lastInput is an object with value === '\n', newLine is true
  134. const newLine = lastInput.value && lastInput.value.match(/^\n$/) !== null;
  135. const content = newLine
  136. ? parameters.slice(0, parameters.length - 1)
  137. : parameters;
  138. return {
  139. type: "writer",
  140. newLine,
  141. content,
  142. };
  143. }
  144. if (name === "$read") {
  145. return {
  146. type: "reader",
  147. variable: parameters[0],
  148. };
  149. }
  150. return {
  151. type: "functioncall",
  152. parameters_list: parameters,
  153. name: functionCall.id,
  154. };
  155. }
  156. /**
  157. * @param {Commands.Function} func
  158. * */
  159. function functionWalker (func) {
  160. const funcDeclaration = {
  161. name: func.name,
  162. return_type: "",
  163. return_dimensions: 0,
  164. parameters_list: [],
  165. variables_list: [],
  166. commands: [],
  167. };
  168. if (func.returnType instanceof ArrayType) {
  169. funcDeclaration.return_type = func.returnType.innerType.value;
  170. funcDeclaration.return_dimensions = func.returnType.dimensions;
  171. } else {
  172. funcDeclaration.return_type = func.returnType.value;
  173. }
  174. funcDeclaration.parameters_list = func.formalParameters.map(
  175. functionParameterWalker
  176. );
  177. funcDeclaration.variables_list = func.variablesDeclarations.map(
  178. variableDeclarationWalker
  179. );
  180. funcDeclaration.commands = func.commands.map(commandWalker);
  181. return funcDeclaration;
  182. }
  183. /**
  184. * @param {Commands.FormalParameter} formalParameter
  185. * */
  186. function functionParameterWalker (formalParameter) {
  187. const variable = {
  188. name: formalParameter.id,
  189. type: "",
  190. rows: 0,
  191. columns: 0,
  192. dimension: 0,
  193. value: 0,
  194. is_const: false,
  195. reference: formalParameter.byRef,
  196. };
  197. if (formalParameter.type instanceof ArrayType) {
  198. variable.type = formalParameter.type.innerType.value;
  199. variable.dimension = formalParameter.type.dimensions;
  200. } else {
  201. variable.type = formalParameter.type.value;
  202. }
  203. return variable;
  204. }
  205. /**
  206. * @param {Commands.Declaration} command
  207. * @param {boolean} global
  208. * */
  209. function variableDeclarationWalker (command, global = false) {
  210. const variable = {
  211. name: command.id,
  212. type: "",
  213. rows: 0,
  214. columns: 0,
  215. dimension: 0,
  216. value: 0,
  217. is_const: false,
  218. };
  219. variable.is_const = global && command.isConst;
  220. if (command instanceof Commands.ArrayDeclaration) {
  221. // array
  222. const lines = expressionWalker(command.lines).pop();
  223. variable.type = command.type.innerType.value;
  224. if (command.isVector) {
  225. variable.columns = lines.value;
  226. variable.dimension = 1;
  227. const values = command.initial.value.map((exp) =>
  228. variableInitialWalker(exp)
  229. );
  230. variable.value = values;
  231. } else {
  232. const columns = expressionWalker(command.columns).pop();
  233. variable.dimension = 2;
  234. variable.rows = lines.value;
  235. variable.columns = columns.value;
  236. const values = command.initial.value.map((rows) =>
  237. rows.value.map((exp) => variableInitialWalker(exp))
  238. );
  239. variable.value = values;
  240. }
  241. } else {
  242. // atomic
  243. variable.type = command.type.value;
  244. variable.value = variableInitialWalker(command.initial);
  245. }
  246. return variable;
  247. }
  248. /**
  249. * @param {any} expression
  250. * */
  251. function variableInitialWalker (expression) {
  252. if (expression instanceof Expressions.UnaryApp) {
  253. const left = variableInitialWalker(expression.left);
  254. const opType = getOpType(expression.op);
  255. if (opType !== TYPES.ARITHMETIC) {
  256. throw new Error(
  257. "invalid variable initial value: " + expression.toString()
  258. );
  259. }
  260. return `${expression.op.value}${left}`;
  261. } else if (expression instanceof Expressions.BoolLiteral) {
  262. const value = expression.value;
  263. return convertBoolToString(value);
  264. } else if (expression instanceof Literal) {
  265. let value = expression.value;
  266. if (expression.value.toNumber) {
  267. if (
  268. Types.REAL.isCompatible(expression.type) &&
  269. expression.value.decimalPlaces() == 0
  270. ) {
  271. value = expression.value.toFixed(2);
  272. } else {
  273. value = expression.value.toNumber();
  274. }
  275. }
  276. return value;
  277. }
  278. throw new Error("invalid variable initial value: " + expression.toString());
  279. }
  280. /**
  281. *
  282. * @return {[]}
  283. **/
  284. function expressionWalker (expression) {
  285. let result;
  286. if (expression instanceof Expressions.VariableLiteral) {
  287. result = [
  288. { instance: "expression", type: TYPES.VARIABLE, value: expression.id },
  289. ];
  290. } else if (expression instanceof Expressions.FunctionCall) {
  291. const funcObj = {
  292. instance: "expression",
  293. type: TYPES.FUNCTION,
  294. value: expression.id,
  295. };
  296. const paramsList = expression.actualParameters.map((e) =>
  297. expressionWalker(e)
  298. );
  299. //const params = Array.prototype.concat.apply([], paramsList);
  300. funcObj.params = paramsList;
  301. result = [funcObj];
  302. } else if (expression instanceof Expressions.UnaryApp) {
  303. console.log(expression);
  304. const left = expressionWalker(expression.left);
  305. const opType = getOpType(expression.op);
  306. const opValue = translateOp(opType, expression.op);
  307. result = [{ instance: "operator", type: opType, value: opValue }, ...left];
  308. } else if (expression instanceof Expressions.InfixApp) {
  309. const left = expressionWalker(expression.left);
  310. const right = expressionWalker(expression.right);
  311. const opType = getOpType(expression.op);
  312. const opValue = translateOp(opType, expression.op);
  313. result = [
  314. ...left,
  315. { instance: "operator", type: opType, value: opValue },
  316. ...right,
  317. ];
  318. } else if (expression instanceof Expressions.ArrayAccess) {
  319. const line = expressionWalker(expression.line);
  320. let arrayClass = "vector";
  321. let column = null;
  322. if (expression.column) {
  323. arrayClass = "matrix";
  324. column = expressionWalker(expression.column);
  325. }
  326. result = [
  327. {
  328. instance: "expression",
  329. type: TYPES.VARIABLE,
  330. class: arrayClass,
  331. column: column,
  332. line: line,
  333. value: expression.id,
  334. },
  335. ];
  336. } else if (expression instanceof Expressions.BoolLiteral) {
  337. const value = expression.value;
  338. result = [
  339. {
  340. instance: "expression",
  341. class: "simple",
  342. type: TYPES.CONST,
  343. value: convertBoolToString(value),
  344. },
  345. ];
  346. } else {
  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. result = [
  359. {
  360. instance: "expression",
  361. class: "simple",
  362. type: TYPES.CONST,
  363. value: value,
  364. },
  365. ];
  366. }
  367. if (expression.parenthesis) return ["(", ...result, ")"];
  368. else return result;
  369. }
  370. export function parseExpression (text) {
  371. const parser = IVProgParser.createParser(text);
  372. const expressionAST = parser.parseExpressionOR();
  373. return expressionWalker(expressionAST);
  374. }
  375. /**
  376. * @param {string} text
  377. * */
  378. export function parseCode (text) {
  379. const parser = IVProgParser.createParser(text, false);
  380. const codeLinesMap = new Map();
  381. const tokens = Array.from(parser.lexer.reset(text));
  382. const tokenStream = [];
  383. for (const token of tokens) {
  384. if (token.type === parser.ruleNames.ERROR) {
  385. return null;
  386. }
  387. if (token.type === parser.ruleNames.COMMENTS) {
  388. for (let i = 0; i <= token.lineBreaks; i++) {
  389. if (codeLinesMap.has(i + token.line))
  390. codeLinesMap.get(i + token.line).push(token);
  391. else codeLinesMap.set(i + token.line, [token]);
  392. }
  393. continue;
  394. }
  395. if (token.type !== parser.ruleNames.WHITESPACE) {
  396. tokenStream.push(token);
  397. }
  398. }
  399. parser.fill(tokenStream);
  400. try {
  401. const program = parser.parseTree();
  402. const globals = program.global.map((decl) =>
  403. variableDeclarationWalker(decl, true)
  404. );
  405. const functions = program.functions.map(functionWalker);
  406. return { globals, functions };
  407. } catch {
  408. return null;
  409. }
  410. }