ivprogParser.js 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  1. import { CommonTokenStream, InputStream } from "antlr4/index";
  2. import * as Expressions from "./expressions";
  3. import * as Commands from "./commands";
  4. import * as AstHelpers from "./ast_helpers";
  5. import * as Parsers from "../typeSystem/parsers";
  6. import { Types } from "../typeSystem/types";
  7. import { ArrayType } from "../typeSystem/array_type";
  8. import { SourceInfo } from "./sourceInfo";
  9. import { convertFromString } from "./operators";
  10. import { SyntaxErrorFactory } from "./error/syntaxErrorFactory";
  11. import { LanguageDefinedFunction } from "../processor/definedFunctions";
  12. import { LanguageService } from "../services/languageService";
  13. export class IVProgParser {
  14. static createParser (input) {
  15. const lexerClass = LanguageService.getCurrentLexer();
  16. return new IVProgParser(input, lexerClass);
  17. }
  18. // <BEGIN scope consts>
  19. static get BASE () {
  20. return 0;
  21. }
  22. static get FUNCTION () {
  23. return 1;
  24. }
  25. static get COMMAND () {
  26. return 2;
  27. }
  28. static get BREAKABLE () {
  29. return 4;
  30. }
  31. // </ END scope consts>
  32. constructor (input, lexerClass) {
  33. this.lexerClass = lexerClass;
  34. this.inputStream = new InputStream(input);
  35. this.lexer = new lexerClass(this.inputStream);
  36. this.lexer.recover = AstHelpers.recover.bind(this.lexer);
  37. this.tokenStream = new CommonTokenStream(this.lexer);
  38. this.tokenStream.fill();
  39. this.pos = 1;
  40. this.variableTypes = [
  41. this.lexerClass.RK_INTEGER,
  42. this.lexerClass.RK_REAL,
  43. this.lexerClass.RK_BOOLEAN,
  44. this.lexerClass.RK_STRING,
  45. this.lexerClass.RK_CHARACTER,
  46. ];
  47. this.functionTypes = this.variableTypes.concat(this.lexerClass.RK_VOID);
  48. this.parsingArrayDimension = 0;
  49. this.scope = [];
  50. this.langFuncs = LanguageService.getCurrentLangFuncs();
  51. this.definedFuncsNameList = [];
  52. this.definedVariablesStack = [];
  53. }
  54. parseTree () {
  55. return this.parseProgram();
  56. }
  57. getToken (index = this.pos) {
  58. // if(index === null)
  59. // index = this.pos;
  60. return this.tokenStream.LT(index);
  61. }
  62. insideScope (scope) {
  63. if (this.scope.length <= 0) {
  64. return IVProgParser.BASE === scope;
  65. } else {
  66. return this.scope[this.scope.length - 1] === scope;
  67. }
  68. }
  69. pushScope (scope) {
  70. this.scope.push(scope);
  71. }
  72. pushVariableStack () {
  73. this.definedVariablesStack.push([]);
  74. }
  75. popScope () {
  76. return this.scope.pop();
  77. }
  78. popVariableStack () {
  79. return this.definedVariablesStack.pop();
  80. }
  81. getCurrentVariableStack () {
  82. return this.definedVariablesStack[this.definedVariablesStack.length - 1];
  83. }
  84. isEOF () {
  85. this.getToken(this.pos);
  86. return this.tokenStream.fetchedEOF;
  87. }
  88. parseProgram () {
  89. this.consumeNewLines();
  90. const token = this.getToken();
  91. let globalVars = [];
  92. let functions = [];
  93. if (this.lexerClass.RK_PROGRAM === token.type) {
  94. this.pos++;
  95. this.consumeNewLines();
  96. this.checkOpenCurly();
  97. this.pos++;
  98. this.pushVariableStack();
  99. for (;;) {
  100. this.consumeNewLines();
  101. const token = this.getToken();
  102. if (
  103. token.type === this.lexerClass.RK_CONST ||
  104. this.isVariableType(token)
  105. ) {
  106. globalVars = globalVars.concat(this.parseGlobalVariables());
  107. } else if (token.type === this.lexerClass.RK_FUNCTION) {
  108. this.pushVariableStack();
  109. functions = functions.concat(this.parseFunction());
  110. this.popVariableStack();
  111. } else {
  112. break;
  113. }
  114. }
  115. this.consumeNewLines();
  116. this.checkCloseCurly();
  117. this.pos++;
  118. this.consumeNewLines();
  119. if (!this.isEOF()) {
  120. throw SyntaxErrorFactory.extra_lines();
  121. }
  122. this.popVariableStack();
  123. return { global: globalVars, functions: functions };
  124. } else {
  125. throw SyntaxErrorFactory.token_missing_one(
  126. this.lexer.literalNames[this.lexerClass.RK_PROGRAM],
  127. token
  128. );
  129. }
  130. }
  131. checkOpenCurly (attempt = false) {
  132. const token = this.getToken();
  133. if (this.lexerClass.OPEN_CURLY !== token.type) {
  134. if (!attempt) throw SyntaxErrorFactory.token_missing_one("{", token);
  135. else return false;
  136. }
  137. return true;
  138. }
  139. checkCloseCurly (attempt = false) {
  140. const token = this.getToken();
  141. if (this.lexerClass.CLOSE_CURLY !== token.type) {
  142. if (!attempt) throw SyntaxErrorFactory.token_missing_one("}", token);
  143. else return false;
  144. }
  145. return true;
  146. }
  147. /* It checks if the current token at position pos is a ']'.
  148. * As a check function it doesn't increment pos.
  149. *
  150. * @params bool:attempt, indicates that the token is optional. Defaults: false
  151. *
  152. * @returns true if the attempt is true and current token is '[',
  153. * false is attempt is true and current token is not '['
  154. **/
  155. checkOpenBrace (attempt = false) {
  156. const token = this.getToken();
  157. if (this.lexerClass.OPEN_BRACE !== token.type) {
  158. if (!attempt) {
  159. throw SyntaxErrorFactory.token_missing_one("[", token);
  160. } else {
  161. return false;
  162. }
  163. }
  164. return true;
  165. }
  166. checkCloseBrace (attempt = false) {
  167. const token = this.getToken();
  168. if (this.lexerClass.CLOSE_BRACE !== token.type) {
  169. if (!attempt) {
  170. throw SyntaxErrorFactory.token_missing_one("]", token);
  171. } else {
  172. return false;
  173. }
  174. }
  175. return true;
  176. }
  177. checkOpenParenthesis (attempt = false) {
  178. const token = this.getToken();
  179. if (this.lexerClass.OPEN_PARENTHESIS !== token.type) {
  180. if (!attempt) {
  181. throw SyntaxErrorFactory.token_missing_one("(", token);
  182. } else {
  183. return false;
  184. }
  185. }
  186. return true;
  187. }
  188. checkCloseParenthesis (attempt = false) {
  189. const token = this.getToken();
  190. if (this.lexerClass.CLOSE_PARENTHESIS !== token.type) {
  191. if (!attempt) {
  192. throw SyntaxErrorFactory.token_missing_one(")", token);
  193. } else {
  194. return false;
  195. }
  196. }
  197. return true;
  198. }
  199. checkEOS (attempt = false) {
  200. const eosToken = this.getToken();
  201. if (eosToken.type !== this.lexerClass.EOS) {
  202. if (!attempt) throw SyntaxErrorFactory.eos_missing(eosToken);
  203. else return false;
  204. }
  205. return true;
  206. }
  207. checkFunctionDuplicate (functionID, funcIDToken) {
  208. const id = functionID === null ? "$main" : functionID;
  209. const index = this.definedFuncsNameList.indexOf(id);
  210. if (index !== -1) {
  211. throw SyntaxErrorFactory.duplicate_function(funcIDToken);
  212. }
  213. this.definedFuncsNameList.push(id);
  214. }
  215. checkVariableDuplicate (variableID, sourceInfo) {
  216. const index = this.getCurrentVariableStack().indexOf(variableID);
  217. if (index !== -1) {
  218. throw SyntaxErrorFactory.duplicate_variable(sourceInfo);
  219. }
  220. this.getCurrentVariableStack().push(variableID);
  221. }
  222. consumeForSemiColon () {
  223. const eosToken = this.getToken();
  224. if (eosToken.type === this.lexerClass.EOS && eosToken.text.match(";")) {
  225. this.pos++;
  226. return;
  227. }
  228. throw SyntaxErrorFactory.token_missing_one(";", eosToken);
  229. }
  230. parseGlobalVariables () {
  231. const decl = this.parseMaybeConst();
  232. this.checkEOS();
  233. this.pos++;
  234. return decl;
  235. }
  236. /*
  237. * Checks if the next token is PR_CONST. It's only available
  238. * at global variables declaration level
  239. * @returns Declararion(const, type, id, initVal?)
  240. **/
  241. parseMaybeConst () {
  242. const constToken = this.getToken();
  243. if (constToken.type === this.lexerClass.RK_CONST) {
  244. this.pos++;
  245. const typeString = this.parseType();
  246. return this.parseDeclaration(typeString, true);
  247. } else if (this.isVariableType(constToken)) {
  248. const typeString = this.parseType();
  249. return this.parseDeclaration(typeString);
  250. } else {
  251. throw SyntaxErrorFactory.token_missing_list(
  252. [this.lexer.literalNames[this.lexerClass.RK_CONST]].concat(
  253. this.getTypeArray()
  254. ),
  255. constToken
  256. );
  257. }
  258. }
  259. /*
  260. * Parses a declarion of the form: type --- id --- (= --- EAnd)?
  261. * @returns a list of Declararion(const, type, id, initVal?)
  262. **/
  263. parseDeclaration (typeString, isConst = false) {
  264. let initial = null;
  265. let dim1 = null;
  266. let dim2 = null;
  267. let dimensions = 0;
  268. const sourceInfo = SourceInfo.createSourceInfo(this.getToken());
  269. const idString = this.parseID();
  270. this.checkVariableDuplicate(idString, sourceInfo);
  271. // Check for array or vector
  272. // ID[int/IDi?][int/IDj?]
  273. if (this.checkOpenBrace(true)) {
  274. this.pos += 1;
  275. this.consumeNewLines();
  276. dim1 = this.parseArrayDimension();
  277. this.consumeNewLines();
  278. this.checkCloseBrace();
  279. this.pos += 1;
  280. dimensions += 1;
  281. if (this.checkOpenBrace(true)) {
  282. this.pos += 1;
  283. this.consumeNewLines();
  284. dim2 = this.parseArrayDimension();
  285. this.consumeNewLines();
  286. this.checkCloseBrace();
  287. this.pos += 1;
  288. dimensions += 1;
  289. }
  290. return this.parseArrayDeclaration(
  291. typeString,
  292. isConst,
  293. idString,
  294. sourceInfo,
  295. dimensions,
  296. dim1,
  297. dim2
  298. );
  299. } else {
  300. const equalsToken = this.getToken();
  301. if (isConst && equalsToken.type !== this.lexerClass.EQUAL) {
  302. throw SyntaxErrorFactory.const_not_init(sourceInfo);
  303. }
  304. if (equalsToken.type === this.lexerClass.EQUAL) {
  305. this.pos++;
  306. initial = this.parseExpressionOR();
  307. }
  308. const declaration = new Commands.Declaration(
  309. idString,
  310. typeString,
  311. initial,
  312. isConst
  313. );
  314. declaration.sourceInfo = sourceInfo;
  315. const commaToken = this.getToken();
  316. if (commaToken.type === this.lexerClass.COMMA) {
  317. this.pos++;
  318. this.consumeNewLines();
  319. return [declaration].concat(this.parseDeclaration(typeString, isConst));
  320. } else {
  321. return [declaration];
  322. }
  323. }
  324. }
  325. parseArrayDeclaration (
  326. typeString,
  327. isConst,
  328. idString,
  329. sourceInfo,
  330. dimensions,
  331. dim1,
  332. dim2
  333. ) {
  334. const equalsToken = this.getToken();
  335. let n_lines = dim1;
  336. let n_columns = dim2;
  337. let initial = null;
  338. let dim_is_id = false;
  339. if (
  340. dim1 instanceof Expressions.VariableLiteral ||
  341. dim2 instanceof Expressions.VariableLiteral
  342. ) {
  343. dim_is_id = true;
  344. if (dimensions > 1 && (dim1 == null || dim2 == null)) {
  345. throw SyntaxErrorFactory.invalid_matrix_id_dimension(
  346. SourceInfo.createSourceInfo(equalsToken)
  347. );
  348. }
  349. }
  350. if (isConst && equalsToken.type !== this.lexerClass.EQUAL) {
  351. throw SyntaxErrorFactory.const_not_init(sourceInfo);
  352. }
  353. if (equalsToken.type === this.lexerClass.EQUAL) {
  354. if (dim_is_id) {
  355. if (dimensions == 1) {
  356. throw SyntaxErrorFactory.invalid_vector_init(
  357. SourceInfo.createSourceInfo(equalsToken)
  358. );
  359. } else {
  360. throw SyntaxErrorFactory.invalid_matrix_init(
  361. SourceInfo.createSourceInfo(equalsToken)
  362. );
  363. }
  364. }
  365. this.pos += 1;
  366. initial = this.parseArrayLiteral(typeString);
  367. }
  368. if (initial == null && dim1 == null) {
  369. if (dimensions > 1) {
  370. throw SyntaxErrorFactory.cannot_infer_matrix_line(idString, sourceInfo);
  371. }
  372. throw SyntaxErrorFactory.cannot_infer_vector_size(idString, sourceInfo);
  373. }
  374. if (dimensions > 1) {
  375. if (initial == null && dim2 == null) {
  376. throw SyntaxErrorFactory.cannot_infer_matrix_column(
  377. idString,
  378. sourceInfo
  379. );
  380. }
  381. }
  382. if (dimensions === 1 && initial != null && !initial.isVector) {
  383. const expString = initial.toString();
  384. throw SyntaxErrorFactory.matrix_to_vector_literal_attr(
  385. idString,
  386. expString,
  387. initial.sourceInfo
  388. );
  389. } else if (dimensions > 1 && initial != null && initial.isVector) {
  390. const expString = initial.toString();
  391. throw SyntaxErrorFactory.vector_to_matrix_literal_attr(
  392. idString,
  393. expString,
  394. initial.sourceInfo
  395. );
  396. }
  397. if (dim1 == null) {
  398. n_lines = new Expressions.IntLiteral(Parsers.toInt(initial.lines));
  399. n_lines.sourceInfo = sourceInfo;
  400. }
  401. if (dimensions > 1) {
  402. if (dim2 == null) {
  403. n_columns = new Expressions.IntLiteral(Parsers.toInt(initial.columns));
  404. n_columns.sourceInfo = sourceInfo;
  405. }
  406. }
  407. const declaration = new Commands.ArrayDeclaration(
  408. idString,
  409. new ArrayType(typeString, dimensions),
  410. n_lines,
  411. n_columns,
  412. initial,
  413. isConst
  414. );
  415. declaration.sourceInfo = sourceInfo;
  416. const commaToken = this.getToken();
  417. if (commaToken.type === this.lexerClass.COMMA) {
  418. this.pos++;
  419. this.consumeNewLines();
  420. return [declaration].concat(this.parseDeclaration(typeString, isConst));
  421. } else {
  422. return [declaration];
  423. }
  424. }
  425. consumeNewLines () {
  426. let token = this.getToken();
  427. while (token.type === this.lexerClass.EOS && token.text.match("[\r\n]+")) {
  428. this.pos++;
  429. token = this.getToken();
  430. }
  431. }
  432. isVariableType (token) {
  433. return this.variableTypes.find((v) => v === token.type);
  434. }
  435. /*
  436. * Reads the next token of the stream to check if it is a Integer or an ID.
  437. * @returns Integer | ID
  438. **/
  439. parseArrayDimension () {
  440. const dimToken = this.getToken();
  441. if (dimToken.type === this.lexerClass.INTEGER) {
  442. //parse as int literal
  443. this.pos++;
  444. return this.getIntLiteral(dimToken);
  445. } else if (dimToken.type === this.lexerClass.ID) {
  446. //parse as variable
  447. this.pos++;
  448. return this.parseVariable(dimToken);
  449. } else if (dimToken.type === this.lexerClass.CLOSE_BRACE) {
  450. return null;
  451. } else {
  452. throw SyntaxErrorFactory.invalid_array_dimension(
  453. this.lexer.literalNames[this.lexerClass.RK_INTEGER],
  454. dimToken
  455. );
  456. }
  457. }
  458. /*
  459. * Returns an object {type: 'int', value: value}.
  460. * It checks for binary and hexadecimal integers.
  461. * @returns object with fields type and value
  462. **/
  463. getIntLiteral (token) {
  464. const text = token.text;
  465. const sourceInfo = SourceInfo.createSourceInfo(token);
  466. const exp = new Expressions.IntLiteral(Parsers.toInt(text));
  467. exp.sourceInfo = sourceInfo;
  468. return exp;
  469. }
  470. getRealLiteral (token) {
  471. const sourceInfo = SourceInfo.createSourceInfo(token);
  472. const exp = new Expressions.RealLiteral(Parsers.toReal(token.text));
  473. exp.sourceInfo = sourceInfo;
  474. return exp;
  475. }
  476. getStringLiteral (token) {
  477. const text = token.text;
  478. const sourceInfo = SourceInfo.createSourceInfo(token);
  479. const exp = new Expressions.StringLiteral(Parsers.toString(text));
  480. exp.sourceInfo = sourceInfo;
  481. return exp;
  482. }
  483. getCharLiteral (token) {
  484. const text = token.text;
  485. const exp = new Expressions.CharLiteral(Parsers.toChar(text));
  486. exp.sourceInfo = SourceInfo.createSourceInfo(token);
  487. return exp;
  488. }
  489. getBoolLiteral (token) {
  490. const val = Parsers.toBool(token.text);
  491. const exp = new Expressions.BoolLiteral(val);
  492. exp.sourceInfo = SourceInfo.createSourceInfo(token);
  493. return exp;
  494. }
  495. parseArrayLiteral (typeString) {
  496. const openCurly = this.checkOpenCurly(true);
  497. if (!openCurly) {
  498. const invalid_token = this.getToken();
  499. throw SyntaxErrorFactory.array_init_not_literal(
  500. SourceInfo.createSourceInfo(invalid_token)
  501. );
  502. }
  503. const beginArray = this.getToken();
  504. if (this.parsingArrayDimension >= 2) {
  505. throw SyntaxErrorFactory.array_exceeds_2d(
  506. SourceInfo.createSourceInfo(beginArray)
  507. );
  508. }
  509. this.pos += 1;
  510. this.parsingArrayDimension += 1;
  511. this.consumeNewLines();
  512. let data = null;
  513. const maybeCurlyOpen = this.checkOpenCurly(true);
  514. if (maybeCurlyOpen) {
  515. // This is potentially a list of vectors
  516. data = this.parseVectorList(typeString);
  517. } else {
  518. data = this.parseExpressionList();
  519. }
  520. this.consumeNewLines();
  521. this.checkCloseCurly();
  522. const endArray = this.getToken();
  523. this.pos += 1;
  524. this.parsingArrayDimension -= 1;
  525. const sourceInfo = SourceInfo.createSourceInfoFromList(
  526. beginArray,
  527. endArray
  528. );
  529. let dataDim = 1;
  530. if (data[0] instanceof Expressions.ArrayLiteral) {
  531. dataDim += 1;
  532. } else if (data.length == 1) {
  533. console.log("Talvez uma variável seja uma melhor opção");
  534. }
  535. const type = new ArrayType(typeString, dataDim);
  536. const exp = new Expressions.ArrayLiteral(type, data);
  537. exp.sourceInfo = sourceInfo;
  538. return exp;
  539. }
  540. /**
  541. * Returns a list of ArrayLiterals. Helper function for parsing matrices
  542. */
  543. parseVectorList (typeString) {
  544. const list = [];
  545. let lastSize = null;
  546. for (;;) {
  547. this.checkOpenCurly();
  548. const beginArray = this.getToken();
  549. if (this.parsingArrayDimension >= 2) {
  550. throw SyntaxErrorFactory.array_exceeds_2d(
  551. SourceInfo.createSourceInfo(beginArray)
  552. );
  553. }
  554. this.pos += 1;
  555. this.parsingArrayDimension += 1;
  556. this.consumeNewLines();
  557. const data = this.parseExpressionList();
  558. this.consumeNewLines();
  559. this.checkCloseCurly();
  560. const endArray = this.getToken();
  561. this.pos += 1;
  562. this.parsingArrayDimension -= 1;
  563. const sourceInfo = SourceInfo.createSourceInfoFromList(
  564. beginArray,
  565. endArray
  566. );
  567. if (lastSize == null) {
  568. lastSize = data.length;
  569. } else if (lastSize !== data.length) {
  570. const expString = this.inputStream.getText(
  571. beginArray.start,
  572. endArray.stop
  573. );
  574. throw SyntaxErrorFactory.invalid_matrix_literal_line(
  575. expString,
  576. sourceInfo
  577. );
  578. }
  579. const type = new ArrayType(typeString, 1);
  580. const exp = new Expressions.ArrayLiteral(type, data);
  581. exp.sourceInfo = sourceInfo;
  582. list.push(exp);
  583. const commaToken = this.getToken();
  584. if (commaToken.type !== this.lexerClass.COMMA) {
  585. break;
  586. }
  587. this.pos += 1;
  588. this.consumeNewLines();
  589. }
  590. if (list.length == 1) {
  591. console.log("Talvez um vetor seja uma melhor opção");
  592. }
  593. return list;
  594. }
  595. /*
  596. * Returns an object {type: 'variable', value: value}.
  597. * @returns object with fields type and value
  598. **/
  599. parseVariable (token) {
  600. const sourceInfo = SourceInfo.createSourceInfo(token);
  601. const exp = new Expressions.VariableLiteral(token.text);
  602. exp.sourceInfo = sourceInfo;
  603. return exp;
  604. }
  605. /*
  606. * Returns an object representing a function. It has
  607. * four attributes: returnType, id, formalParams and block.
  608. * The block object has two attributes: declarations and commands
  609. **/
  610. parseFunction () {
  611. this.pushScope(IVProgParser.FUNCTION);
  612. let formalParams = [];
  613. const token = this.getToken();
  614. if (token.type !== this.lexerClass.RK_FUNCTION) {
  615. //throw SyntaxError.createError(this.lexer.literalNames[this.lexerClass.PR_FUNCAO], token);
  616. return null;
  617. }
  618. this.pos++;
  619. const funType = this.parseType();
  620. let dimensions = 0;
  621. if (this.checkOpenBrace(true)) {
  622. this.pos++;
  623. this.checkCloseBrace();
  624. this.pos++;
  625. dimensions++;
  626. if (this.checkOpenBrace(true)) {
  627. this.pos++;
  628. this.checkCloseBrace();
  629. this.pos++;
  630. dimensions++;
  631. }
  632. }
  633. const funcIDToken = this.getToken();
  634. const functionID = this.parseID();
  635. this.checkFunctionDuplicate(functionID, funcIDToken);
  636. this.checkOpenParenthesis();
  637. this.pos++;
  638. this.consumeNewLines();
  639. if (!this.checkCloseParenthesis(true)) {
  640. formalParams = this.parseFormalParameters(); // formal parameters
  641. this.consumeNewLines();
  642. this.checkCloseParenthesis();
  643. this.pos++;
  644. } else {
  645. this.pos++;
  646. }
  647. this.consumeNewLines();
  648. const commandsBlock = this.parseCommandBlock();
  649. let returnType = funType;
  650. if (dimensions > 0) {
  651. returnType = new ArrayType(funType, dimensions);
  652. }
  653. const func = new Commands.Function(
  654. functionID,
  655. returnType,
  656. formalParams,
  657. commandsBlock
  658. );
  659. if (functionID === null && !func.isMain) {
  660. throw SyntaxErrorFactory.invalid_main_return(
  661. LanguageDefinedFunction.getMainFunctionName(),
  662. this.lexer.literalNames[this.lexerClass.RK_VOID],
  663. token.line
  664. );
  665. } else if (func.isMain && formalParams.length !== 0) {
  666. throw SyntaxErrorFactory.main_parameters();
  667. }
  668. this.popScope();
  669. return func;
  670. }
  671. /*
  672. * Parse the formal parameters of a function.
  673. * @returns a list of objects with the following attributes: type, id and dimensions.
  674. **/
  675. parseFormalParameters () {
  676. const list = [];
  677. for (;;) {
  678. let dimensions = 0;
  679. let reference = false;
  680. const typeString = this.parseType();
  681. let maybeIDToken = this.getToken();
  682. if (maybeIDToken.type === this.lexerClass.RK_REFERENCE) {
  683. reference = true;
  684. this.pos += 1;
  685. maybeIDToken = this.getToken();
  686. }
  687. const idString = this.parseID();
  688. this.checkVariableDuplicate(idString, maybeIDToken);
  689. if (this.checkOpenBrace(true)) {
  690. this.pos += 1;
  691. dimensions += 1;
  692. this.checkCloseBrace();
  693. this.pos += 1;
  694. if (this.checkOpenBrace(true)) {
  695. this.pos += 1;
  696. dimensions += 1;
  697. this.checkCloseBrace();
  698. this.pos += 1;
  699. }
  700. }
  701. let type = null;
  702. if (dimensions > 0) {
  703. type = new ArrayType(typeString, dimensions);
  704. } else {
  705. type = typeString;
  706. }
  707. const parameter = new Commands.FormalParameter(type, idString, reference);
  708. parameter.sourceInfo = SourceInfo.createSourceInfo(maybeIDToken);
  709. list.push(parameter);
  710. const commaToken = this.getToken();
  711. if (commaToken.type !== this.lexerClass.COMMA) break;
  712. this.pos++;
  713. this.consumeNewLines();
  714. }
  715. return list;
  716. }
  717. parseID () {
  718. const token = this.getToken();
  719. if (token.type !== this.lexerClass.ID) {
  720. throw SyntaxErrorFactory.id_missing(token);
  721. }
  722. this.pos++;
  723. if (this.insideScope(IVProgParser.FUNCTION)) {
  724. if (token.text === LanguageDefinedFunction.getMainFunctionName()) {
  725. return null;
  726. }
  727. }
  728. return token.text;
  729. }
  730. parseMaybeLibID () {
  731. const token = this.getToken();
  732. if (
  733. token.type !== this.lexerClass.ID &&
  734. token.type !== this.lexerClass.LIB_ID
  735. ) {
  736. throw SyntaxErrorFactory.id_missing(token);
  737. }
  738. this.pos++;
  739. return token.text;
  740. }
  741. parseType () {
  742. const token = this.getToken();
  743. if (
  744. token.type === this.lexerClass.ID &&
  745. this.insideScope(IVProgParser.FUNCTION)
  746. ) {
  747. return Types.VOID;
  748. } else if (
  749. token.type === this.lexerClass.RK_VOID &&
  750. this.insideScope(IVProgParser.FUNCTION)
  751. ) {
  752. this.pos++;
  753. return Types.VOID;
  754. } else if (this.isVariableType(token)) {
  755. this.pos++;
  756. switch (token.type) {
  757. case this.lexerClass.RK_INTEGER:
  758. return Types.INTEGER;
  759. case this.lexerClass.RK_BOOLEAN:
  760. return Types.BOOLEAN;
  761. case this.lexerClass.RK_REAL:
  762. return Types.REAL;
  763. case this.lexerClass.RK_STRING:
  764. return Types.STRING;
  765. case this.lexerClass.RK_CHARACTER:
  766. return Types.CHAR;
  767. default:
  768. break;
  769. }
  770. }
  771. throw SyntaxErrorFactory.invalid_type(this.getTypeArray(), token);
  772. }
  773. parseCommandBlock (optionalCurly = false) {
  774. let variablesDecl = [];
  775. const commands = [];
  776. let hasOpen = false;
  777. if (this.checkOpenCurly(optionalCurly)) {
  778. this.pos++;
  779. hasOpen = true;
  780. }
  781. this.consumeNewLines();
  782. let parsedCommand = false;
  783. for (;;) {
  784. const cmd = this.parseCommand();
  785. if (cmd === null) break;
  786. if (cmd !== -1) {
  787. if (cmd instanceof Array) {
  788. if (parsedCommand) {
  789. const lastToken = this.getToken(this.pos - 1);
  790. throw SyntaxErrorFactory.invalid_var_declaration(lastToken);
  791. }
  792. variablesDecl = variablesDecl.concat(cmd);
  793. } else {
  794. parsedCommand = true;
  795. commands.push(cmd);
  796. }
  797. }
  798. }
  799. this.consumeNewLines();
  800. if (hasOpen) {
  801. this.checkCloseCurly();
  802. this.pos++;
  803. this.consumeNewLines();
  804. }
  805. return new Commands.CommandBlock(variablesDecl, commands);
  806. }
  807. parseCommand () {
  808. const token = this.getToken();
  809. if (this.isVariableType(token)) {
  810. if (!this.insideScope(IVProgParser.FUNCTION)) {
  811. throw SyntaxErrorFactory.invalid_var_declaration(token);
  812. }
  813. this.pushScope(IVProgParser.BASE);
  814. const varType = this.parseType();
  815. this.popScope();
  816. const cmd = this.parseDeclaration(varType);
  817. this.checkEOS();
  818. this.pos++;
  819. return cmd;
  820. } else if (token.type === this.lexerClass.ID) {
  821. return this.parseIDCommand();
  822. } else if (token.type === this.lexerClass.LIB_ID) {
  823. return this.parseIDCommand();
  824. } else if (token.type === this.lexerClass.RK_RETURN) {
  825. return this.parseReturn();
  826. } else if (
  827. token.type === this.lexerClass.RK_WHILE ||
  828. token.type === this.lexerClass.RK_WHILE_ALT
  829. ) {
  830. return this.parseWhile();
  831. } else if (
  832. token.type === this.lexerClass.RK_FOR ||
  833. token.type === this.lexerClass.RK_FOR_ALT
  834. ) {
  835. return this.parseFor();
  836. } else if (token.type === this.lexerClass.RK_BREAK) {
  837. if (!this.insideScope(IVProgParser.BREAKABLE)) {
  838. throw SyntaxErrorFactory.invalid_break_command(
  839. this.lexer.literalNames[this.lexerClass.RK_BREAK],
  840. token
  841. );
  842. }
  843. return this.parseBreak();
  844. } else if (token.type === this.lexerClass.RK_SWITCH) {
  845. return this.parseSwitchCase();
  846. } else if (token.type === this.lexerClass.RK_DO) {
  847. return this.parseRepeatUntil();
  848. } else if (token.type === this.lexerClass.RK_IF) {
  849. return this.parseIfThenElse();
  850. } else if (this.checkEOS(true)) {
  851. this.pos++;
  852. return -1;
  853. } else {
  854. return null;
  855. }
  856. }
  857. parseSwitchCase () {
  858. this.pushScope(IVProgParser.BREAKABLE);
  859. this.pos++;
  860. this.checkOpenParenthesis();
  861. this.pos++;
  862. this.consumeNewLines();
  863. const exp = this.parseExpressionOR();
  864. this.consumeNewLines();
  865. this.checkCloseParenthesis();
  866. this.pos++;
  867. this.consumeNewLines();
  868. this.checkOpenCurly();
  869. this.pos++;
  870. this.consumeNewLines();
  871. const casesList = this.parseCases();
  872. this.consumeNewLines();
  873. this.checkCloseCurly();
  874. this.pos++;
  875. this.consumeNewLines();
  876. this.popScope();
  877. return new Commands.Switch(exp, casesList);
  878. }
  879. parseRepeatUntil () {
  880. this.pos++;
  881. this.consumeNewLines();
  882. this.pushScope(IVProgParser.BREAKABLE);
  883. const commandsBlock = this.parseCommandBlock();
  884. this.consumeNewLines(); //Maybe not...
  885. const whileToken = this.getToken();
  886. if (whileToken.type !== this.lexerClass.RK_DO_UNTIL) {
  887. throw SyntaxErrorFactory.token_missing_one(
  888. this.lexer.literalNames[this.lexerClass.RK_DO_UNTIL],
  889. whileToken
  890. );
  891. }
  892. this.pos++;
  893. this.checkOpenParenthesis();
  894. this.pos++;
  895. this.consumeNewLines();
  896. const condition = this.parseExpressionOR();
  897. this.consumeNewLines();
  898. this.checkCloseParenthesis();
  899. this.pos++;
  900. this.checkEOS();
  901. this.popScope();
  902. return new Commands.RepeatUntil(condition, commandsBlock);
  903. }
  904. parseIfThenElse () {
  905. if (this.insideScope(IVProgParser.BREAKABLE)) {
  906. this.pushScope(IVProgParser.BREAKABLE);
  907. } else {
  908. this.pushScope(IVProgParser.COMMAND);
  909. }
  910. const token = this.getToken();
  911. this.pos++;
  912. this.checkOpenParenthesis();
  913. this.pos++;
  914. this.consumeNewLines();
  915. const logicalExpression = this.parseExpressionOR();
  916. this.consumeNewLines();
  917. this.checkCloseParenthesis();
  918. this.pos++;
  919. this.consumeNewLines();
  920. const cmdBlocks = this.parseCommandBlock();
  921. const maybeElse = this.getToken();
  922. if (maybeElse.type === this.lexerClass.RK_ELSE) {
  923. this.pos++;
  924. this.consumeNewLines();
  925. const maybeIf = this.getToken();
  926. let elseBlock = null;
  927. if (this.checkOpenCurly(true)) {
  928. elseBlock = this.parseCommandBlock();
  929. } else if (maybeIf.type === this.lexerClass.RK_IF) {
  930. elseBlock = this.parseIfThenElse();
  931. } else {
  932. throw SyntaxErrorFactory.token_missing_list(
  933. [this.lexer.literalNames[this.lexerClass.RK_IF], "{"],
  934. maybeIf
  935. );
  936. }
  937. this.popScope();
  938. const cmd = new Commands.IfThenElse(
  939. logicalExpression,
  940. cmdBlocks,
  941. elseBlock
  942. );
  943. cmd.sourceInfo = SourceInfo.createSourceInfo(token);
  944. return cmd;
  945. }
  946. this.popScope();
  947. const cmd = new Commands.IfThenElse(logicalExpression, cmdBlocks, null);
  948. cmd.sourceInfo = SourceInfo.createSourceInfo(token);
  949. return cmd;
  950. }
  951. parseFor () {
  952. this.pushScope(IVProgParser.BREAKABLE);
  953. const for_token = this.getToken();
  954. this.pos += 1;
  955. // parse ID
  956. const id_token = this.getToken();
  957. const id = this.parseID();
  958. const for_id = new Expressions.VariableLiteral(id);
  959. for_id.sourceInfo = SourceInfo.createSourceInfo(id_token);
  960. // END parse ID
  961. const for_from = this.parseForParameters(this.lexerClass.RK_FOR_FROM);
  962. const for_to = this.parseForParameters(this.lexerClass.RK_FOR_TO);
  963. const maybePass = this.parseForParameters(this.lexerClass.RK_FOR_PASS);
  964. this.consumeNewLines();
  965. const commandsBlock = this.parseCommandBlock();
  966. this.popScope();
  967. const cmd = new Commands.For(
  968. for_id,
  969. for_from,
  970. for_to,
  971. maybePass,
  972. commandsBlock
  973. );
  974. cmd.sourceInfo = SourceInfo.createSourceInfo(for_token);
  975. return cmd;
  976. }
  977. parseWhile () {
  978. this.pushScope(IVProgParser.BREAKABLE);
  979. const token = this.getToken();
  980. this.pos++;
  981. this.checkOpenParenthesis();
  982. this.pos++;
  983. this.consumeNewLines();
  984. const logicalExpression = this.parseExpressionOR();
  985. this.consumeNewLines();
  986. this.checkCloseParenthesis();
  987. this.pos++;
  988. this.consumeNewLines();
  989. const cmdBlocks = this.parseCommandBlock();
  990. this.popScope();
  991. const cmd = new Commands.While(logicalExpression, cmdBlocks);
  992. cmd.sourceInfo = SourceInfo.createSourceInfo(token);
  993. return cmd;
  994. }
  995. parseBreak () {
  996. const token = this.getToken();
  997. this.pos++;
  998. this.checkEOS();
  999. this.pos++;
  1000. const command = new Commands.Break();
  1001. command.sourceInfo = SourceInfo.createSourceInfo(token);
  1002. return command;
  1003. }
  1004. parseReturn () {
  1005. this.pos++;
  1006. let exp = null;
  1007. if (!this.checkEOS(true)) {
  1008. exp = this.parseExpressionOR();
  1009. this.checkEOS();
  1010. }
  1011. this.pos++;
  1012. return new Commands.Return(exp);
  1013. }
  1014. parseIDCommand () {
  1015. const refToken = this.getToken();
  1016. const isID = refToken.type === this.lexerClass.ID;
  1017. const id = this.parseMaybeLibID();
  1018. if (this.checkOpenBrace(true)) {
  1019. this.pos++;
  1020. let lineExpression = null;
  1021. let columnExpression = null;
  1022. this.consumeNewLines();
  1023. lineExpression = this.parseExpression();
  1024. this.consumeNewLines();
  1025. this.checkCloseBrace();
  1026. this.pos++;
  1027. if (this.checkOpenBrace(true)) {
  1028. this.pos++;
  1029. this.consumeNewLines();
  1030. columnExpression = this.parseExpression();
  1031. this.consumeNewLines();
  1032. this.checkCloseBrace();
  1033. this.pos++;
  1034. }
  1035. const equalToken = this.getToken();
  1036. if (equalToken.type !== this.lexerClass.EQUAL) {
  1037. throw SyntaxErrorFactory.token_missing_one("=", equalToken);
  1038. }
  1039. this.pos++;
  1040. const exp = this.parseExpressionOR();
  1041. this.checkEOS();
  1042. this.pos++;
  1043. const cmd = new Commands.ArrayIndexAssign(
  1044. id,
  1045. lineExpression,
  1046. columnExpression,
  1047. exp
  1048. );
  1049. cmd.sourceInfo = SourceInfo.createSourceInfo(equalToken);
  1050. return cmd;
  1051. }
  1052. const equalOrParenthesis = this.getToken();
  1053. if (isID && equalOrParenthesis.type === this.lexerClass.EQUAL) {
  1054. this.pos++;
  1055. const exp = this.parseExpressionOR();
  1056. this.checkEOS();
  1057. this.pos++;
  1058. const cmd = new Commands.Assign(id, exp);
  1059. cmd.sourceInfo = SourceInfo.createSourceInfo(equalOrParenthesis);
  1060. return cmd;
  1061. } else if (equalOrParenthesis.type === this.lexerClass.OPEN_PARENTHESIS) {
  1062. const funcCall = this.parseFunctionCallCommand(id);
  1063. this.checkEOS();
  1064. this.pos++;
  1065. return funcCall;
  1066. } else if (isID) {
  1067. throw SyntaxErrorFactory.token_missing_list(
  1068. ["=", "("],
  1069. equalOrParenthesis
  1070. );
  1071. } else {
  1072. throw SyntaxErrorFactory.invalid_id_format(refToken);
  1073. }
  1074. }
  1075. parseForParameters (keyword_code) {
  1076. if (keyword_code === this.lexerClass.RK_FOR_PASS) {
  1077. if (this.checkOpenCurly(true)) {
  1078. return null;
  1079. }
  1080. }
  1081. const from_token = this.getToken();
  1082. if (from_token.type !== keyword_code) {
  1083. // TODO better error message
  1084. const keyword = this.lexer.literalNames[keyword_code];
  1085. throw new Error(
  1086. "Error de sintaxe no comando repita_para: esperava-se " +
  1087. keyword +
  1088. " mas encontrou " +
  1089. from_token.text
  1090. );
  1091. }
  1092. this.pos += 1;
  1093. let int_or_id = this.getToken();
  1094. let is_unary_op = false;
  1095. let op = null;
  1096. if (int_or_id.type === this.lexerClass.SUM_OP) {
  1097. is_unary_op = true;
  1098. op = int_or_id.text;
  1099. this.pos += 1;
  1100. int_or_id = this.getToken();
  1101. }
  1102. let for_from = null;
  1103. if (int_or_id.type === this.lexerClass.ID) {
  1104. for_from = new Expressions.VariableLiteral(this.parseID());
  1105. for_from.sourceInfo = SourceInfo.createSourceInfo(int_or_id);
  1106. } else if (int_or_id.type === this.lexerClass.INTEGER) {
  1107. this.pos += 1;
  1108. for_from = this.getIntLiteral(int_or_id);
  1109. }
  1110. if (for_from == null) {
  1111. // TODO better error message
  1112. const keyword = this.lexer.literalNames[keyword_code];
  1113. throw new Error(
  1114. "Error de sintaxe no comando repeita_para: " +
  1115. int_or_id.text +
  1116. " não é compativel com o esperado para o paramentro " +
  1117. keyword +
  1118. ". O valor deve ser um inteiro ou variável."
  1119. );
  1120. }
  1121. if (is_unary_op) {
  1122. for_from = new Expressions.UnaryApp(convertFromString(op), for_from);
  1123. }
  1124. return for_from;
  1125. }
  1126. parseCases () {
  1127. const token = this.getToken();
  1128. if (token.type !== this.lexerClass.RK_CASE) {
  1129. throw SyntaxErrorFactory.token_missing_one(
  1130. this.lexer.literalNames[this.lexerClass.RK_CASE],
  1131. token
  1132. );
  1133. }
  1134. this.pos++;
  1135. const nextToken = this.getToken();
  1136. if (nextToken.type === this.lexerClass.RK_DEFAULT) {
  1137. this.pos++;
  1138. const colonToken = this.getToken();
  1139. if (colonToken.type !== this.lexerClass.COLON) {
  1140. throw SyntaxErrorFactory.token_missing_one(":", colonToken);
  1141. }
  1142. this.pos++;
  1143. this.consumeNewLines();
  1144. const block = this.parseCommandBlock(true);
  1145. const defaultCase = new Commands.Case(null);
  1146. defaultCase.setCommands(block.commands);
  1147. return [defaultCase];
  1148. } else {
  1149. const exp = this.parseExpressionOR();
  1150. const colonToken = this.getToken();
  1151. if (colonToken.type !== this.lexerClass.COLON) {
  1152. throw SyntaxErrorFactory.token_missing_one(":", colonToken);
  1153. }
  1154. this.pos++;
  1155. this.consumeNewLines();
  1156. const block = this.parseCommandBlock(true);
  1157. const aCase = new Commands.Case(exp);
  1158. aCase.setCommands(block.commands);
  1159. const caseToken = this.getToken();
  1160. if (caseToken.type === this.lexerClass.RK_CASE) {
  1161. return [aCase].concat(this.parseCases());
  1162. } else {
  1163. return [aCase];
  1164. }
  1165. }
  1166. }
  1167. /*
  1168. * Parses an Expression following the structure:
  1169. *
  1170. * EOR => EAnd ( 'or' EOR)? #expression and
  1171. *
  1172. * EOR => ENot ('and' EOR)? #expression or
  1173. *
  1174. * ENot => 'not'? ER #expression not
  1175. *
  1176. * ER => E ((>=, <=, ==, >, <) E)? #expression relational
  1177. *
  1178. * E => factor ((+, -) E)? #expression
  1179. *
  1180. * factor=> term ((*, /, %) factor)?
  1181. *
  1182. * term => literal || arrayAccess || FuncCall || ID || '('EAnd')'
  1183. **/
  1184. parseExpressionOR () {
  1185. let exp1 = this.parseExpressionAND();
  1186. while (this.getToken().type === this.lexerClass.OR_OPERATOR) {
  1187. const opToken = this.getToken();
  1188. this.pos++;
  1189. const or = convertFromString("or");
  1190. this.consumeNewLines();
  1191. const exp2 = this.parseExpressionAND();
  1192. const finalExp = new Expressions.InfixApp(or, exp1, exp2);
  1193. finalExp.sourceInfo = SourceInfo.createSourceInfo(opToken);
  1194. exp1 = finalExp;
  1195. }
  1196. return exp1;
  1197. }
  1198. parseExpressionAND () {
  1199. let exp1 = this.parseExpressionNot();
  1200. while (this.getToken().type === this.lexerClass.AND_OPERATOR) {
  1201. const opToken = this.getToken();
  1202. this.pos++;
  1203. const and = convertFromString("and");
  1204. this.consumeNewLines();
  1205. const exp2 = this.parseExpressionNot();
  1206. const finalExp = new Expressions.InfixApp(and, exp1, exp2);
  1207. finalExp.sourceInfo = SourceInfo.createSourceInfo(opToken);
  1208. exp1 = finalExp;
  1209. }
  1210. return exp1;
  1211. }
  1212. parseExpressionNot () {
  1213. const maybeNotToken = this.getToken();
  1214. if (maybeNotToken.type === this.lexerClass.NOT_OPERATOR) {
  1215. const opToken = this.getToken();
  1216. this.pos++;
  1217. const not = convertFromString("not");
  1218. const exp1 = this.parseExpressionRel();
  1219. const finalExp = new Expressions.UnaryApp(not, exp1);
  1220. finalExp.sourceInfo = SourceInfo.createSourceInfo(opToken);
  1221. return finalExp;
  1222. } else {
  1223. return this.parseExpressionRel();
  1224. }
  1225. }
  1226. parseExpressionRel () {
  1227. let exp1 = this.parseExpression();
  1228. while (this.getToken().type === this.lexerClass.RELATIONAL_OPERATOR) {
  1229. const relToken = this.getToken();
  1230. this.pos++;
  1231. const rel = convertFromString(relToken.text);
  1232. const exp2 = this.parseExpression();
  1233. const finalExp = new Expressions.InfixApp(rel, exp1, exp2);
  1234. finalExp.sourceInfo = SourceInfo.createSourceInfo(relToken);
  1235. exp1 = finalExp;
  1236. }
  1237. return exp1;
  1238. }
  1239. parseExpression () {
  1240. let factor = this.parseFactor();
  1241. while (this.getToken().type === this.lexerClass.SUM_OP) {
  1242. const sumOpToken = this.getToken();
  1243. this.pos++;
  1244. const op = convertFromString(sumOpToken.text);
  1245. const factor2 = this.parseFactor();
  1246. const finalExp = new Expressions.InfixApp(op, factor, factor2);
  1247. finalExp.sourceInfo = SourceInfo.createSourceInfo(sumOpToken);
  1248. factor = finalExp;
  1249. }
  1250. return factor;
  1251. }
  1252. parseFactor () {
  1253. let term = this.parseTerm();
  1254. while (this.getToken().type === this.lexerClass.MULTI_OP) {
  1255. const multOpToken = this.getToken();
  1256. this.pos++;
  1257. const op = convertFromString(multOpToken.text);
  1258. const term2 = this.parseTerm();
  1259. const finalExp = new Expressions.InfixApp(op, term, term2);
  1260. finalExp.sourceInfo = SourceInfo.createSourceInfo(multOpToken);
  1261. term = finalExp;
  1262. }
  1263. return term;
  1264. }
  1265. parseTerm () {
  1266. const token = this.getToken();
  1267. let sourceInfo = null;
  1268. let exp = null;
  1269. switch (token.type) {
  1270. case this.lexerClass.SUM_OP:
  1271. this.pos++;
  1272. sourceInfo = SourceInfo.createSourceInfo(token);
  1273. exp = new Expressions.UnaryApp(
  1274. convertFromString(token.text),
  1275. this.parseTerm()
  1276. );
  1277. exp.sourceInfo = sourceInfo;
  1278. return exp;
  1279. case this.lexerClass.INTEGER:
  1280. this.pos++;
  1281. return this.getIntLiteral(token);
  1282. case this.lexerClass.REAL:
  1283. this.pos++;
  1284. return this.getRealLiteral(token);
  1285. case this.lexerClass.STRING:
  1286. this.pos++;
  1287. return this.getStringLiteral(token);
  1288. case this.lexerClass.CHARACTER:
  1289. this.pos++;
  1290. return this.getCharLiteral(token);
  1291. case this.lexerClass.RK_TRUE:
  1292. case this.lexerClass.RK_FALSE:
  1293. this.pos++;
  1294. return this.getBoolLiteral(token);
  1295. case this.lexerClass.OPEN_CURLY:
  1296. // No more annonymous array
  1297. // return this.parseArrayLiteral();
  1298. throw SyntaxErrorFactory.annonymous_array_literal(token);
  1299. case this.lexerClass.ID:
  1300. case this.lexerClass.LIB_ID:
  1301. return this.parseIDTerm();
  1302. case this.lexerClass.OPEN_PARENTHESIS:
  1303. return this.parseParenthesisExp();
  1304. default:
  1305. throw SyntaxErrorFactory.invalid_terminal(token);
  1306. }
  1307. }
  1308. parseIDTerm () {
  1309. const tokenA = this.getToken();
  1310. const id = this.parseMaybeLibID();
  1311. const isID = tokenA.type === this.lexerClass.ID;
  1312. if (isID && this.checkOpenBrace(true)) {
  1313. let tokenB = null;
  1314. this.pos++;
  1315. const firstIndex = this.parseExpression();
  1316. let secondIndex = null;
  1317. this.consumeNewLines();
  1318. this.checkCloseBrace();
  1319. tokenB = this.getToken();
  1320. this.pos++;
  1321. if (this.checkOpenBrace(true)) {
  1322. this.pos++;
  1323. secondIndex = this.parseExpression();
  1324. this.consumeNewLines();
  1325. this.checkCloseBrace();
  1326. tokenB = this.getToken();
  1327. this.pos++;
  1328. }
  1329. const sourceInfo = SourceInfo.createSourceInfoFromList(tokenA, tokenB);
  1330. const exp = new Expressions.ArrayAccess(id, firstIndex, secondIndex);
  1331. exp.sourceInfo = sourceInfo;
  1332. return exp;
  1333. } else if (this.checkOpenParenthesis(true)) {
  1334. return this.parseFunctionCallExpression(id);
  1335. } else if (isID) {
  1336. const sourceInfo = SourceInfo.createSourceInfo(tokenA);
  1337. const exp = new Expressions.VariableLiteral(id);
  1338. exp.sourceInfo = sourceInfo;
  1339. return exp;
  1340. } else {
  1341. throw SyntaxErrorFactory.invalid_id_format(tokenA);
  1342. }
  1343. }
  1344. getFunctionName (id) {
  1345. const name = LanguageDefinedFunction.getInternalName(id);
  1346. if (name === null) {
  1347. if (id === LanguageDefinedFunction.getMainFunctionName()) {
  1348. return null;
  1349. }
  1350. return id;
  1351. } else {
  1352. return name;
  1353. }
  1354. }
  1355. parseFunctionCallExpression (id) {
  1356. const tokenA = this.getToken(this.pos - 1);
  1357. const actualParameters = this.parseActualParameters();
  1358. const tokenB = this.getToken(this.pos - 1);
  1359. const funcName = this.getFunctionName(id);
  1360. const sourceInfo = SourceInfo.createSourceInfoFromList(tokenA, tokenB);
  1361. const cmd = new Expressions.FunctionCall(funcName, actualParameters);
  1362. cmd.sourceInfo = sourceInfo;
  1363. return cmd;
  1364. }
  1365. parseFunctionCallCommand (id) {
  1366. return this.parseFunctionCallExpression(id);
  1367. }
  1368. parseParenthesisExp () {
  1369. this.checkOpenParenthesis();
  1370. const tokenA = this.getToken();
  1371. this.pos += 1;
  1372. this.consumeNewLines();
  1373. const exp = this.parseExpressionOR();
  1374. this.consumeNewLines();
  1375. this.checkCloseParenthesis();
  1376. const tokenB = this.getToken();
  1377. this.pos += 1;
  1378. exp.sourceInfo = SourceInfo.createSourceInfoFromList(tokenA, tokenB);
  1379. exp.parenthesis = true;
  1380. return exp;
  1381. }
  1382. parseActualParameters () {
  1383. this.checkOpenParenthesis();
  1384. this.pos++;
  1385. if (this.checkCloseParenthesis(true)) {
  1386. this.pos++;
  1387. return [];
  1388. }
  1389. this.consumeNewLines();
  1390. const list = this.parseExpressionList();
  1391. this.consumeNewLines();
  1392. this.checkCloseParenthesis();
  1393. this.pos++;
  1394. return list;
  1395. }
  1396. parseExpressionList () {
  1397. const list = [];
  1398. for (;;) {
  1399. const exp = this.parseExpressionOR();
  1400. list.push(exp);
  1401. const maybeToken = this.getToken();
  1402. if (maybeToken.type !== this.lexerClass.COMMA) {
  1403. break;
  1404. } else {
  1405. this.pos++;
  1406. this.consumeNewLines();
  1407. }
  1408. }
  1409. return list;
  1410. }
  1411. getTypeArray () {
  1412. const types = this.insideScope(IVProgParser.FUNCTION)
  1413. ? this.functionTypes
  1414. : this.variableTypes;
  1415. return types.map((x) => this.lexer.literalNames[x]);
  1416. }
  1417. }