ivprogParser.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350
  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. const 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. throw SyntaxErrorFactory.invalid_matrix_id_dimension(SourceInfo.createSourceInfo(equalsToken));
  317. }
  318. }
  319. if(isConst && equalsToken.type !== this.lexerClass.EQUAL ) {
  320. throw SyntaxErrorFactory.const_not_init(sourceInfo);
  321. }
  322. if(equalsToken.type === this.lexerClass.EQUAL) {
  323. if(dim_is_id) {
  324. if(dimensions == 1) {
  325. throw SyntaxErrorFactory.invalid_vector_init(SourceInfo.createSourceInfo(equalsToken));
  326. } else {
  327. throw SyntaxErrorFactory.invalid_matrix_init(SourceInfo.createSourceInfo(equalsToken));
  328. }
  329. }
  330. this.pos += 1
  331. initial = this.parseArrayLiteral(typeString);
  332. }
  333. if(initial == null && dim1 == null) {
  334. if(dimensions > 1) {
  335. throw SyntaxErrorFactory.cannot_infer_matrix_line(idString, sourceInfo);
  336. }
  337. throw SyntaxErrorFactory.cannot_infer_vector_size(idString, sourceInfo);
  338. }
  339. if(dimensions > 1) {
  340. if(initial == null && dim2 == null) {
  341. throw SyntaxErrorFactory.cannot_infer_matrix_column(idString, sourceInfo);
  342. }
  343. }
  344. if(dimensions === 1 && initial != null && !initial.isVector) {
  345. const expString = initial.toString();
  346. throw SyntaxErrorFactory.matrix_to_vector_literal_attr(idString, expString, initial.sourceInfo);
  347. } else if (dimensions > 1 && initial != null && initial.isVector) {
  348. const expString = initial.toString();
  349. throw SyntaxErrorFactory.vector_to_matrix_literal_attr(idString, expString, initial.sourceInfo);
  350. }
  351. if(dim1 == null) {
  352. n_lines = new Expressions.IntLiteral(toInt(initial.lines));
  353. n_lines.sourceInfo = sourceInfo;
  354. }
  355. if (dimensions > 1) {
  356. if(dim2 == null) {
  357. n_columns = new Expressions.IntLiteral(toInt(initial.columns));
  358. n_columns.sourceInfo = sourceInfo;
  359. }
  360. }
  361. const declaration = new Commands.ArrayDeclaration(idString,
  362. new ArrayType(typeString, dimensions), n_lines, n_columns, initial, isConst);
  363. declaration.sourceInfo = sourceInfo;
  364. const commaToken = this.getToken();
  365. if(commaToken.type === this.lexerClass.COMMA) {
  366. this.pos++;
  367. this.consumeNewLines();
  368. return [declaration]
  369. .concat(this.parseDeclaration(typeString, isConst));
  370. } else {
  371. return [declaration]
  372. }
  373. }
  374. consumeNewLines () {
  375. let token = this.getToken();
  376. while(token.type === this.lexerClass.EOS && token.text.match('[\r\n]+')) {
  377. this.pos++;
  378. token = this.getToken();
  379. }
  380. }
  381. isVariableType (token) {
  382. return this.variableTypes.find(v => v === token.type);
  383. }
  384. /*
  385. * Reads the next token of the stream to check if it is a Integer or an ID.
  386. * @returns Integer | ID
  387. **/
  388. parseArrayDimension () {
  389. const dimToken = this.getToken();
  390. if(dimToken.type === this.lexerClass.INTEGER) {
  391. //parse as int literal
  392. this.pos++;
  393. return this.getIntLiteral(dimToken);
  394. } else if(dimToken.type === this.lexerClass.ID) {
  395. //parse as variable
  396. this.pos++;
  397. return this.parseVariable(dimToken);
  398. } else if(dimToken.type === this.lexerClass.CLOSE_BRACE) {
  399. return null;
  400. } else {
  401. throw SyntaxErrorFactory.invalid_array_dimension(this.lexer.literalNames[this.lexerClass.RK_INTEGER], dimToken);
  402. }
  403. }
  404. /*
  405. * Returns an object {type: 'int', value: value}.
  406. * It checks for binary and hexadecimal integers.
  407. * @returns object with fields type and value
  408. **/
  409. getIntLiteral (token) {
  410. const text = token.text;
  411. const sourceInfo = SourceInfo.createSourceInfo(token);
  412. const exp = new Expressions.IntLiteral(toInt(text));
  413. exp.sourceInfo = sourceInfo;
  414. return exp;
  415. }
  416. getRealLiteral (token) {
  417. const sourceInfo = SourceInfo.createSourceInfo(token);
  418. const exp = new Expressions.RealLiteral(toReal(token.text));
  419. exp.sourceInfo = sourceInfo;
  420. return exp;
  421. }
  422. getStringLiteral (token) {
  423. const text = token.text;
  424. const sourceInfo = SourceInfo.createSourceInfo(token);
  425. const exp = new Expressions.StringLiteral(toString(text));
  426. exp.sourceInfo = sourceInfo;
  427. return exp;
  428. }
  429. getBoolLiteral (token) {
  430. const val = toBool(token.text);
  431. const exp = new Expressions.BoolLiteral(val);
  432. exp.sourceInfo = SourceInfo.createSourceInfo(token);
  433. return exp;
  434. }
  435. parseArrayLiteral (typeString) {
  436. const openCurly = this.checkOpenCurly(true);
  437. if(!openCurly) {
  438. const invalid_token = this.getToken();
  439. throw SyntaxErrorFactory.array_init_not_literal(SourceInfo.createSourceInfo(invalid_token));
  440. }
  441. const beginArray = this.getToken();
  442. if (this.parsingArrayDimension >= 2) {
  443. throw SyntaxErrorFactory.array_exceeds_2d(SourceInfo.createSourceInfo(beginArray));
  444. }
  445. this.pos += 1;
  446. this.parsingArrayDimension += 1;
  447. this.consumeNewLines();
  448. let data = null;
  449. const maybeCurlyOpen = this.checkOpenCurly(true);
  450. if(maybeCurlyOpen) {
  451. // This is potentially a list of vectors
  452. data = this.parseVectorList(typeString);
  453. } else {
  454. data = this.parseExpressionList();
  455. }
  456. this.consumeNewLines();
  457. this.checkCloseCurly()
  458. const endArray = this.getToken();
  459. this.pos += 1;
  460. this.parsingArrayDimension -= 1;
  461. const sourceInfo = SourceInfo.createSourceInfoFromList(beginArray, endArray);
  462. let dataDim = 1;
  463. if(data[0] instanceof Expressions.ArrayLiteral) {
  464. dataDim += 1;
  465. } else if(data.length == 1) {
  466. console.log("Talvez uma variável seja uma melhor opção");
  467. }
  468. const type = new ArrayType(typeString, dataDim);
  469. const exp = new Expressions.ArrayLiteral(type, data);
  470. exp.sourceInfo = sourceInfo;
  471. return exp;
  472. }
  473. /**
  474. * Returns a list of ArrayLiterals. Helper function for parsing matrices
  475. */
  476. parseVectorList (typeString) {
  477. const list = [];
  478. let lastSize = null;
  479. for(;;) {
  480. this.checkOpenCurly();
  481. const beginArray = this.getToken();
  482. if (this.parsingArrayDimension >= 2) {
  483. throw SyntaxErrorFactory.array_exceeds_2d(SourceInfo.createSourceInfo(beginArray));
  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. let reference = false;
  595. const typeString = this.parseType();
  596. let maybeIDToken = this.getToken();
  597. if(maybeIDToken.type === this.lexerClass.RK_REFERENCE) {
  598. reference = true;
  599. this.pos += 1;
  600. maybeIDToken = this.getToken();
  601. }
  602. const idString = this.parseID();
  603. this.checkVariableDuplicate(idString, maybeIDToken);
  604. if (this.checkOpenBrace(true)) {
  605. this.pos += 1;
  606. dimensions += 1;
  607. this.checkCloseBrace();
  608. this.pos += 1;
  609. if(this.checkOpenBrace(true)) {
  610. this.pos += 1;
  611. dimensions += 1;
  612. this.checkCloseBrace();
  613. this.pos += 1;
  614. }
  615. }
  616. let type = null;
  617. if(dimensions > 0) {
  618. type = new ArrayType(typeString, dimensions);
  619. } else {
  620. type = typeString;
  621. }
  622. const parameter = new Commands.FormalParameter(type, idString, reference);
  623. parameter.sourceInfo = SourceInfo.createSourceInfo(maybeIDToken);
  624. list.push(parameter);
  625. const commaToken = this.getToken();
  626. if (commaToken.type !== this.lexerClass.COMMA)
  627. break;
  628. this.pos++;
  629. this.consumeNewLines();
  630. }
  631. return list;
  632. }
  633. parseID () {
  634. const token = this.getToken();
  635. if(token.type !== this.lexerClass.ID) {
  636. throw SyntaxErrorFactory.id_missing(token);
  637. }
  638. this.pos++;
  639. if (this.insideScope(IVProgParser.FUNCTION)) {
  640. if (token.text === LanguageDefinedFunction.getMainFunctionName()){
  641. return null;
  642. }
  643. }
  644. return token.text;
  645. }
  646. parseMaybeLibID () {
  647. const token = this.getToken();
  648. if(token.type !== this.lexerClass.ID && token.type !== this.lexerClass.LIB_ID) {
  649. throw SyntaxErrorFactory.id_missing(token);
  650. }
  651. this.pos++;
  652. return token.text;
  653. }
  654. parseType () {
  655. const token = this.getToken();
  656. if(token.type === this.lexerClass.ID && this.insideScope(IVProgParser.FUNCTION)) {
  657. return Types.VOID;
  658. } else if (token.type === this.lexerClass.RK_VOID && this.insideScope(IVProgParser.FUNCTION)) {
  659. this.pos++;
  660. return Types.VOID;
  661. } else if (this.isVariableType(token)) {
  662. this.pos++;
  663. switch(token.type) {
  664. case this.lexerClass.RK_INTEGER:
  665. return Types.INTEGER;
  666. case this.lexerClass.RK_BOOLEAN:
  667. return Types.BOOLEAN;
  668. case this.lexerClass.RK_REAL:
  669. return Types.REAL;
  670. case this.lexerClass.RK_STRING:
  671. return Types.STRING;
  672. default:
  673. break;
  674. }
  675. }
  676. throw SyntaxErrorFactory.invalid_type(this.getTypeArray(), token);
  677. }
  678. parseCommandBlock (optionalCurly = false) {
  679. let variablesDecl = [];
  680. const commands = [];
  681. let hasOpen = false;
  682. if (this.checkOpenCurly(optionalCurly)) {
  683. this.pos++;
  684. hasOpen = true;
  685. }
  686. this.consumeNewLines();
  687. let parsedCommand = false;
  688. for(;;) {
  689. const cmd = this.parseCommand();
  690. if (cmd === null)
  691. break;
  692. if(cmd !== -1) {
  693. if (cmd instanceof Array) {
  694. if(parsedCommand) {
  695. const lastToken = this.getToken(this.pos - 1);
  696. throw SyntaxErrorFactory.invalid_var_declaration(lastToken);
  697. }
  698. variablesDecl = variablesDecl.concat(cmd);
  699. } else {
  700. parsedCommand = true;
  701. commands.push(cmd);
  702. }
  703. }
  704. }
  705. this.consumeNewLines();
  706. if (hasOpen) {
  707. this.checkCloseCurly()
  708. this.pos++;
  709. this.consumeNewLines();
  710. }
  711. return new Commands.CommandBlock(variablesDecl, commands);
  712. }
  713. parseCommand () {
  714. const token = this.getToken();
  715. if (this.isVariableType(token)) {
  716. if(!this.insideScope(IVProgParser.FUNCTION)) {
  717. throw SyntaxErrorFactory.invalid_var_declaration(token);
  718. }
  719. this.pushScope(IVProgParser.BASE);
  720. const varType = this.parseType();
  721. this.popScope();
  722. const cmd = this.parseDeclaration(varType);
  723. this.checkEOS();
  724. this.pos++;
  725. return cmd;
  726. } else if (token.type === this.lexerClass.ID) {
  727. return this.parseIDCommand();
  728. } else if (token.type === this.lexerClass.LIB_ID) {
  729. return this.parseIDCommand();
  730. } else if (token.type === this.lexerClass.RK_RETURN) {
  731. return this.parseReturn();
  732. } else if (token.type === this.lexerClass.RK_WHILE || token.type === this.lexerClass.RK_WHILE_ALT) {
  733. return this.parseWhile();
  734. } else if (token.type === this.lexerClass.RK_FOR || token.type === this.lexerClass.RK_FOR_ALT) {
  735. return this.parseFor();
  736. } else if (token.type === this.lexerClass.RK_BREAK ) {
  737. if(!this.insideScope(IVProgParser.BREAKABLE)) {
  738. throw SyntaxErrorFactory.invalid_break_command(
  739. this.lexer.literalNames[this.lexerClass.RK_BREAK],
  740. token
  741. );
  742. }
  743. return this.parseBreak();
  744. } else if (token.type === this.lexerClass.RK_SWITCH) {
  745. return this.parseSwitchCase();
  746. } else if (token.type === this.lexerClass.RK_DO) {
  747. return this.parseRepeatUntil();
  748. } else if (token.type === this.lexerClass.RK_IF) {
  749. return this.parseIfThenElse();
  750. } else if (this.checkEOS(true)){
  751. this.pos++;
  752. return -1;
  753. } else {
  754. return null;
  755. }
  756. }
  757. parseSwitchCase () {
  758. this.pushScope(IVProgParser.BREAKABLE);
  759. this.pos++;
  760. this.checkOpenParenthesis();
  761. this.pos++;
  762. this.consumeNewLines();
  763. const exp = this.parseExpressionOR();
  764. this.consumeNewLines();
  765. this.checkCloseParenthesis();
  766. this.pos++;
  767. this.consumeNewLines();
  768. this.checkOpenCurly();
  769. this.pos++;
  770. this.consumeNewLines();
  771. const casesList = this.parseCases();
  772. this.consumeNewLines();
  773. this.checkCloseCurly();
  774. this.pos++;
  775. this.consumeNewLines();
  776. this.popScope();
  777. return new Commands.Switch(exp, casesList);
  778. }
  779. parseRepeatUntil () {
  780. this.pos++;
  781. this.consumeNewLines();
  782. this.pushScope(IVProgParser.BREAKABLE);
  783. const commandsBlock = this.parseCommandBlock();
  784. this.consumeNewLines(); //Maybe not...
  785. const whileToken = this.getToken();
  786. if (whileToken.type !== this.lexerClass.RK_DO_UNTIL) {
  787. throw SyntaxErrorFactory.token_missing_one(this.lexer.literalNames[this.lexerClass.RK_DO_UNTIL], whileToken);
  788. }
  789. this.pos++;
  790. this.checkOpenParenthesis();
  791. this.pos++;
  792. this.consumeNewLines();
  793. const condition = this.parseExpressionOR();
  794. this.consumeNewLines();
  795. this.checkCloseParenthesis();
  796. this.pos++;
  797. this.checkEOS();
  798. this.popScope();
  799. return new Commands.RepeatUntil(condition, commandsBlock);
  800. }
  801. parseIfThenElse () {
  802. if(this.insideScope(IVProgParser.BREAKABLE)) {
  803. this.pushScope(IVProgParser.BREAKABLE);
  804. } else {
  805. this.pushScope(IVProgParser.COMMAND);
  806. }
  807. const token = this.getToken();
  808. this.pos++;
  809. this.checkOpenParenthesis();
  810. this.pos++;
  811. this.consumeNewLines();
  812. const logicalExpression = this.parseExpressionOR();
  813. this.consumeNewLines();
  814. this.checkCloseParenthesis();
  815. this.pos++;
  816. this.consumeNewLines();
  817. const cmdBlocks = this.parseCommandBlock();
  818. const maybeElse = this.getToken();
  819. if(maybeElse.type === this.lexerClass.RK_ELSE) {
  820. this.pos++;
  821. this.consumeNewLines();
  822. const maybeIf = this.getToken();
  823. let elseBlock = null;
  824. if(this.checkOpenCurly(true)) {
  825. elseBlock = this.parseCommandBlock();
  826. } else if(maybeIf.type === this.lexerClass.RK_IF) {
  827. elseBlock = this.parseIfThenElse();
  828. } else {
  829. throw SyntaxErrorFactory.token_missing_list([this.lexer.literalNames[this.lexerClass.RK_IF], '{'], maybeIf);
  830. }
  831. this.popScope();
  832. const cmd = new Commands.IfThenElse(logicalExpression, cmdBlocks, elseBlock);
  833. cmd.sourceInfo = SourceInfo.createSourceInfo(token);
  834. return cmd;
  835. }
  836. this.popScope();
  837. const cmd = new Commands.IfThenElse(logicalExpression, cmdBlocks, null);
  838. cmd.sourceInfo = SourceInfo.createSourceInfo(token);
  839. return cmd;
  840. }
  841. parseFor () {
  842. this.pushScope(IVProgParser.BREAKABLE);
  843. const for_token = this.getToken();
  844. this.pos += 1;
  845. // parse ID
  846. const id_token = this.getToken();
  847. const id = this.parseID();
  848. const for_id = new Expressions.VariableLiteral(id);
  849. for_id.sourceInfo = SourceInfo.createSourceInfo(id_token);
  850. // END parse ID
  851. const for_from = this.parseForParameters(this.lexerClass.RK_FOR_FROM);
  852. const for_to = this.parseForParameters(this.lexerClass.RK_FOR_TO);
  853. const maybePass = this.parseForParameters(this.lexerClass.RK_FOR_PASS);
  854. this.consumeNewLines();
  855. const commandsBlock = this.parseCommandBlock();
  856. this.popScope();
  857. const cmd = new Commands.For(for_id, for_from, for_to, maybePass, commandsBlock);
  858. cmd.sourceInfo = SourceInfo.createSourceInfo(for_token);
  859. return cmd;
  860. }
  861. parseWhile () {
  862. this.pushScope(IVProgParser.BREAKABLE);
  863. const token = this.getToken();
  864. this.pos++;
  865. this.checkOpenParenthesis();
  866. this.pos++;
  867. this.consumeNewLines();
  868. const logicalExpression = this.parseExpressionOR();
  869. this.consumeNewLines();
  870. this.checkCloseParenthesis();
  871. this.pos++;
  872. this.consumeNewLines();
  873. const cmdBlocks = this.parseCommandBlock();
  874. this.popScope();
  875. const cmd = new Commands.While(logicalExpression, cmdBlocks);
  876. cmd.sourceInfo = SourceInfo.createSourceInfo(token);
  877. return cmd;
  878. }
  879. parseBreak () {
  880. this.pos++;
  881. this.checkEOS();
  882. this.pos++;
  883. return new Commands.Break();
  884. }
  885. parseReturn () {
  886. this.pos++;
  887. let exp = null;
  888. if(!this.checkEOS(true)) {
  889. exp = this.parseExpressionOR();
  890. this.checkEOS();
  891. }
  892. this.pos++;
  893. return new Commands.Return(exp);
  894. }
  895. parseIDCommand () {
  896. const refToken = this.getToken();
  897. const isID = refToken.type === this.lexerClass.ID;
  898. const id = this.parseMaybeLibID();
  899. if(this.checkOpenBrace(true)) {
  900. this.pos++;
  901. let lineExpression = null;
  902. let columnExpression = null;
  903. this.consumeNewLines();
  904. lineExpression = this.parseExpression()
  905. this.consumeNewLines();
  906. this.checkCloseBrace();
  907. this.pos++;
  908. if (this.checkOpenBrace(true)) {
  909. this.pos++
  910. this.consumeNewLines();
  911. columnExpression = this.parseExpression();
  912. this.consumeNewLines();
  913. this.checkCloseBrace();
  914. this.pos++;
  915. }
  916. const equalToken = this.getToken();
  917. if (equalToken.type !== this.lexerClass.EQUAL) {
  918. throw SyntaxErrorFactory.token_missing_one('=', equalToken);
  919. }
  920. this.pos++;
  921. const exp = this.parseExpressionOR();
  922. this.checkEOS();
  923. this.pos++;
  924. const cmd = new Commands.ArrayIndexAssign(id, lineExpression, columnExpression, exp);
  925. cmd.sourceInfo = SourceInfo.createSourceInfo(equalToken);
  926. return cmd;
  927. }
  928. const equalOrParenthesis = this.getToken();
  929. if (isID && equalOrParenthesis.type === this.lexerClass.EQUAL) {
  930. this.pos++
  931. const exp = this.parseExpressionOR();
  932. this.checkEOS();
  933. this.pos++;
  934. const cmd = new Commands.Assign(id, exp);
  935. cmd.sourceInfo = SourceInfo.createSourceInfo(equalOrParenthesis);
  936. return cmd;
  937. } else if (equalOrParenthesis.type === this.lexerClass.OPEN_PARENTHESIS) {
  938. const funcCall = this.parseFunctionCallCommand(id);
  939. this.checkEOS();
  940. this.pos++;
  941. return funcCall;
  942. } else if (isID) {
  943. throw SyntaxErrorFactory.token_missing_list(['=','('], equalOrParenthesis);
  944. } else {
  945. throw SyntaxErrorFactory.invalid_id_format(refToken);
  946. }
  947. }
  948. parseForParameters (keyword_code) {
  949. if(keyword_code === this.lexerClass.RK_FOR_PASS) {
  950. if(this.checkOpenCurly(true)) {
  951. return null;
  952. }
  953. }
  954. const from_token = this.getToken();
  955. if (from_token.type !== keyword_code) {
  956. // TODO better error message
  957. const keyword = this.lexer.literalNames[keyword_code];
  958. throw new Error("Error de sintaxe no comando repita_para: esperava-se "+keyword+" mas encontrou "+from_token.text);
  959. }
  960. this.pos += 1;
  961. let int_or_id = this.getToken();
  962. let is_unary_op = false;
  963. let op = null;
  964. if(int_or_id.type === this.lexerClass.SUM_OP) {
  965. is_unary_op = true;
  966. op = int_or_id.text;
  967. this.pos += 1;
  968. int_or_id = this.getToken();
  969. }
  970. let for_from = null;
  971. if (int_or_id.type === this.lexerClass.ID) {
  972. for_from = new Expressions.VariableLiteral(this.parseID());
  973. for_from.sourceInfo = SourceInfo.createSourceInfo(int_or_id);
  974. } else if (int_or_id.type === this.lexerClass.INTEGER) {
  975. this.pos += 1;
  976. for_from = this.getIntLiteral(int_or_id);
  977. }
  978. if (for_from == null) {
  979. // TODO better error message
  980. const keyword = this.lexer.literalNames[keyword_code];
  981. 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.");
  982. }
  983. if (is_unary_op) {
  984. for_from = new Expressions.UnaryApp(convertFromString(op), for_from);
  985. }
  986. return for_from;
  987. }
  988. parseCases () {
  989. const token = this.getToken();
  990. if(token.type !== this.lexerClass.RK_CASE) {
  991. throw SyntaxErrorFactory.token_missing_one(this.lexer.literalNames[this.lexerClass.RK_CASE], token);
  992. }
  993. this.pos++;
  994. const nextToken = this.getToken();
  995. if(nextToken.type === this.lexerClass.RK_DEFAULT) {
  996. this.pos++;
  997. const colonToken = this.getToken();
  998. if (colonToken.type !== this.lexerClass.COLON) {
  999. throw SyntaxErrorFactory.token_missing_one(':', colonToken);
  1000. }
  1001. this.pos++;
  1002. this.consumeNewLines();
  1003. const block = this.parseCommandBlock(true);
  1004. const defaultCase = new Commands.Case(null);
  1005. defaultCase.setCommands(block.commands);
  1006. return [defaultCase];
  1007. } else {
  1008. const exp = this.parseExpressionOR();
  1009. const colonToken = this.getToken();
  1010. if (colonToken.type !== this.lexerClass.COLON) {
  1011. throw SyntaxErrorFactory.token_missing_one(':', colonToken);
  1012. }
  1013. this.pos++;
  1014. this.consumeNewLines();
  1015. const block = this.parseCommandBlock(true);
  1016. const aCase = new Commands.Case(exp);
  1017. aCase.setCommands(block.commands);
  1018. const caseToken = this.getToken();
  1019. if(caseToken.type === this.lexerClass.RK_CASE) {
  1020. return [aCase].concat(this.parseCases());
  1021. } else {
  1022. return [aCase];
  1023. }
  1024. }
  1025. }
  1026. /*
  1027. * Parses an Expression following the structure:
  1028. *
  1029. * EOR => EAnd ( 'or' EOR)? #expression and
  1030. *
  1031. * EOR => ENot ('and' EOR)? #expression or
  1032. *
  1033. * ENot => 'not'? ER #expression not
  1034. *
  1035. * ER => E ((>=, <=, ==, >, <) E)? #expression relational
  1036. *
  1037. * E => factor ((+, -) E)? #expression
  1038. *
  1039. * factor=> term ((*, /, %) factor)?
  1040. *
  1041. * term => literal || arrayAccess || FuncCall || ID || '('EAnd')'
  1042. **/
  1043. parseExpressionOR () {
  1044. let exp1 = this.parseExpressionAND();
  1045. while (this.getToken().type === this.lexerClass.OR_OPERATOR) {
  1046. const opToken = this.getToken();
  1047. this.pos++;
  1048. const or = convertFromString('or');
  1049. this.consumeNewLines();
  1050. const exp2 = this.parseExpressionAND();
  1051. const finalExp = new Expressions.InfixApp(or, exp1, exp2);
  1052. finalExp.sourceInfo = SourceInfo.createSourceInfo(opToken);
  1053. exp1 = finalExp
  1054. }
  1055. return exp1;
  1056. }
  1057. parseExpressionAND () {
  1058. let exp1 = this.parseExpressionNot();
  1059. while (this.getToken().type === this.lexerClass.AND_OPERATOR) {
  1060. const opToken = this.getToken();
  1061. this.pos++;
  1062. const and = convertFromString('and');
  1063. this.consumeNewLines();
  1064. const exp2 = this.parseExpressionNot();
  1065. const finalExp = new Expressions.InfixApp(and, exp1, exp2);
  1066. finalExp.sourceInfo = SourceInfo.createSourceInfo(opToken);
  1067. exp1 = finalExp;
  1068. }
  1069. return exp1;
  1070. }
  1071. parseExpressionNot () {
  1072. const maybeNotToken = this.getToken();
  1073. if (maybeNotToken.type === this.lexerClass.NOT_OPERATOR) {
  1074. const opToken = this.getToken();
  1075. this.pos++;
  1076. const not = convertFromString('not');
  1077. const exp1 = this.parseExpressionRel();
  1078. const finalExp = new Expressions.UnaryApp(not, exp1);
  1079. finalExp.sourceInfo = SourceInfo.createSourceInfo(opToken);
  1080. return finalExp;
  1081. } else {
  1082. return this.parseExpressionRel();
  1083. }
  1084. }
  1085. parseExpressionRel () {
  1086. let exp1 = this.parseExpression();
  1087. while (this.getToken().type === this.lexerClass.RELATIONAL_OPERATOR) {
  1088. const relToken = this.getToken();
  1089. this.pos++;
  1090. const rel = convertFromString(relToken.text);
  1091. const exp2 = this.parseExpression();
  1092. const finalExp = new Expressions.InfixApp(rel, exp1, exp2);
  1093. finalExp.sourceInfo = SourceInfo.createSourceInfo(relToken);
  1094. exp1 = finalExp;
  1095. }
  1096. return exp1;
  1097. }
  1098. parseExpression () {
  1099. let factor = this.parseFactor();
  1100. while (this.getToken().type === this.lexerClass.SUM_OP) {
  1101. const sumOpToken = this.getToken();
  1102. this.pos++;
  1103. const op = convertFromString(sumOpToken.text);
  1104. const factor2 = this.parseFactor();
  1105. const finalExp = new Expressions.InfixApp(op, factor, factor2);
  1106. finalExp.sourceInfo = SourceInfo.createSourceInfo(sumOpToken);
  1107. factor = finalExp;
  1108. }
  1109. return factor;
  1110. }
  1111. parseFactor () {
  1112. let term = this.parseTerm();
  1113. while (this.getToken().type === this.lexerClass.MULTI_OP) {
  1114. const multOpToken = this.getToken();
  1115. this.pos++;
  1116. const op = convertFromString(multOpToken.text);
  1117. const term2 =this.parseTerm();
  1118. const finalExp = new Expressions.InfixApp(op, term, term2);
  1119. finalExp.sourceInfo = SourceInfo.createSourceInfo(multOpToken);
  1120. term = finalExp;
  1121. }
  1122. return term;
  1123. }
  1124. parseTerm () {
  1125. const token = this.getToken();
  1126. let sourceInfo = null;
  1127. let exp = null;
  1128. switch(token.type) {
  1129. case this.lexerClass.SUM_OP:
  1130. this.pos++;
  1131. sourceInfo = SourceInfo.createSourceInfo(token);
  1132. exp = new Expressions.UnaryApp(convertFromString(token.text), this.parseTerm());
  1133. exp.sourceInfo = sourceInfo;
  1134. return exp;
  1135. case this.lexerClass.INTEGER:
  1136. this.pos++;
  1137. return this.getIntLiteral(token);
  1138. case this.lexerClass.REAL:
  1139. this.pos++;
  1140. return this.getRealLiteral(token);
  1141. case this.lexerClass.STRING:
  1142. this.pos++;
  1143. return this.getStringLiteral(token);
  1144. case this.lexerClass.RK_TRUE:
  1145. case this.lexerClass.RK_FALSE:
  1146. this.pos++;
  1147. return this.getBoolLiteral(token);
  1148. case this.lexerClass.OPEN_CURLY:
  1149. // No more annonymous array
  1150. // return this.parseArrayLiteral();
  1151. throw SyntaxErrorFactory.annonymous_array_literal(token);
  1152. case this.lexerClass.ID:
  1153. case this.lexerClass.LIB_ID:
  1154. return this.parseIDTerm();
  1155. case this.lexerClass.OPEN_PARENTHESIS:
  1156. return this.parseParenthesisExp();
  1157. default:
  1158. throw SyntaxErrorFactory.invalid_terminal(token);
  1159. }
  1160. }
  1161. parseIDTerm () {
  1162. const tokenA = this.getToken();
  1163. const id = this.parseMaybeLibID();
  1164. const isID = tokenA.type === this.lexerClass.ID;
  1165. if(isID && this.checkOpenBrace(true)) {
  1166. let tokenB = null;
  1167. this.pos++;
  1168. const firstIndex = this.parseExpression();
  1169. let secondIndex = null;
  1170. this.consumeNewLines();
  1171. this.checkCloseBrace();
  1172. tokenB = this.getToken();
  1173. this.pos++;
  1174. if(this.checkOpenBrace(true)){
  1175. this.pos++;
  1176. secondIndex = this.parseExpression();
  1177. this.consumeNewLines();
  1178. this.checkCloseBrace();
  1179. tokenB = this.getToken();
  1180. this.pos++;
  1181. }
  1182. const sourceInfo = SourceInfo.createSourceInfoFromList(tokenA, tokenB);
  1183. const exp = new Expressions.ArrayAccess(id, firstIndex, secondIndex);
  1184. exp.sourceInfo = sourceInfo;
  1185. return exp;
  1186. } else if (this.checkOpenParenthesis(true)) {
  1187. return this.parseFunctionCallExpression(id);
  1188. } else if (isID) {
  1189. const sourceInfo = SourceInfo.createSourceInfo(tokenA);
  1190. const exp = new Expressions.VariableLiteral(id);
  1191. exp.sourceInfo = sourceInfo;
  1192. return exp;
  1193. } else {
  1194. throw SyntaxErrorFactory.invalid_id_format(tokenA);
  1195. }
  1196. }
  1197. getFunctionName (id) {
  1198. const name = LanguageDefinedFunction.getInternalName(id);
  1199. if (name === null) {
  1200. if (id === LanguageDefinedFunction.getMainFunctionName()) {
  1201. return null;
  1202. }
  1203. return id;
  1204. } else {
  1205. return name;
  1206. }
  1207. }
  1208. parseFunctionCallExpression (id) {
  1209. const tokenA = this.getToken(this.pos - 1);
  1210. const actualParameters = this.parseActualParameters();
  1211. const tokenB = this.getToken(this.pos - 1);
  1212. const funcName = this.getFunctionName(id);
  1213. const sourceInfo = SourceInfo.createSourceInfoFromList(tokenA, tokenB);
  1214. const cmd = new Expressions.FunctionCall(funcName, actualParameters);
  1215. cmd.sourceInfo = sourceInfo;
  1216. return cmd;
  1217. }
  1218. parseFunctionCallCommand (id) {
  1219. return this.parseFunctionCallExpression(id);
  1220. }
  1221. parseParenthesisExp () {
  1222. this.checkOpenParenthesis();
  1223. const tokenA = this.getToken();
  1224. this.pos += 1;
  1225. this.consumeNewLines();
  1226. const exp = this.parseExpressionOR();
  1227. this.consumeNewLines();
  1228. this.checkCloseParenthesis();
  1229. const tokenB = this.getToken();
  1230. this.pos += 1;
  1231. exp.sourceInfo = SourceInfo.createSourceInfoFromList(tokenA, tokenB);
  1232. exp.parenthesis = true;
  1233. return exp;
  1234. }
  1235. parseActualParameters () {
  1236. this.checkOpenParenthesis();
  1237. this.pos++;
  1238. if(this.checkCloseParenthesis(true)) {
  1239. this.pos++;
  1240. return [];
  1241. }
  1242. this.consumeNewLines();
  1243. const list = this.parseExpressionList();
  1244. this.consumeNewLines();
  1245. this.checkCloseParenthesis();
  1246. this.pos++;
  1247. return list;
  1248. }
  1249. parseExpressionList () {
  1250. const list = [];
  1251. for(;;) {
  1252. const exp = this.parseExpressionOR();
  1253. list.push(exp);
  1254. const maybeToken = this.getToken();
  1255. if (maybeToken.type !== this.lexerClass.COMMA) {
  1256. break;
  1257. } else {
  1258. this.pos++;
  1259. this.consumeNewLines();
  1260. }
  1261. }
  1262. return list;
  1263. }
  1264. getTypeArray () {
  1265. const types = this.insideScope(IVProgParser.FUNCTION) ? this.functionTypes : this.variableTypes;
  1266. return types.map( x => this.lexer.literalNames[x]);
  1267. }
  1268. }