ivprogParser.js 42 KB

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