ivprogParser.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  1. import { CommonTokenStream, InputStream } from 'antlr4/index';
  2. import * as Expressions from './expressions/';
  3. import * as Commands from './commands/';
  4. import { Types, toInt, toString } from './types';
  5. import { convertFromString } from './operators';
  6. import { SyntaxErrorFactory } from './error/syntaxErrorFactory';
  7. import { NAMES } from './../processor/definedFunctions';
  8. export class IVProgParser {
  9. // <BEGIN scope consts>
  10. static get BASE () {
  11. return 0;
  12. }
  13. static get FUNCTION () {
  14. return 1;
  15. }
  16. static get COMMAND () {
  17. return 2;
  18. }
  19. static get BREAKABLE () {
  20. return 4;
  21. }
  22. // </ END scope consts>
  23. constructor (input, lexerClass) {
  24. this.lexerClass = lexerClass;
  25. this.lexer = new lexerClass(new InputStream(input));
  26. this.tokenStream = new CommonTokenStream(this.lexer);
  27. this.tokenStream.fill();
  28. this.pos = 1;
  29. this.variableTypes = [this.lexerClass.RK_INTEGER,
  30. this.lexerClass.RK_REAL,
  31. this.lexerClass.RK_BOOLEAN,
  32. this.lexerClass.RK_STRING
  33. ];
  34. this.functionTypes = this.variableTypes.concat(this.lexerClass.RK_VOID);
  35. this.parsingArrayDimension = 0;
  36. this.scope = [];
  37. }
  38. parseTree () {
  39. return this.parseProgram();
  40. }
  41. getToken (index = this.pos) {
  42. // if(index === null)
  43. // index = this.pos;
  44. return this.tokenStream.LT(index);
  45. }
  46. insideScope (scope) {
  47. if(this.scope.length <= 0) {
  48. return IVProgParser.BASE === scope;
  49. } else {
  50. return this.scope[this.scope.length-1] === scope;
  51. }
  52. }
  53. pushScope (scope) {
  54. this.scope.push(scope);
  55. }
  56. popScope () {
  57. return this.scope.pop();
  58. }
  59. isEOF () {
  60. this.getToken(this.pos);
  61. return this.tokenStream.fetchedEOF;
  62. }
  63. parseProgram () {
  64. const token = this.getToken();
  65. let globalVars = [];
  66. let functions = [];
  67. if(this.lexerClass.RK_PROGRAM === token.type) {
  68. this.pos++;
  69. this.consumeNewLines();
  70. this.checkOpenCurly();
  71. this.pos++;
  72. while(true) {
  73. this.consumeNewLines();
  74. const token = this.getToken();
  75. if (token.type === this.lexerClass.RK_CONST || this.isVariableType(token)) {
  76. globalVars = globalVars.concat(this.parseGlobalVariables());
  77. } else if (token.type === this.lexerClass.RK_FUNCTION) {
  78. functions = functions.concat(this.parseFunction());
  79. } else {
  80. break;
  81. }
  82. }
  83. this.consumeNewLines();
  84. this.checkCloseCurly();
  85. this.pos++;
  86. this.consumeNewLines();
  87. if(!this.isEOF()) {
  88. throw SyntaxErrorFactory.extra_lines();
  89. }
  90. return {global: globalVars, functions: functions};
  91. } else {
  92. throw SyntaxErrorFactory.token_missing_one(this.lexer.literalNames[this.lexerClass.RK_PROGRAM], token);
  93. }
  94. }
  95. checkOpenCurly (attempt = false) {
  96. const token = this.getToken();
  97. if(this.lexerClass.OPEN_CURLY !== token.type){
  98. if(!attempt)
  99. throw SyntaxErrorFactory.token_missing_one('{', token);
  100. else
  101. return false;
  102. }
  103. return true;
  104. }
  105. checkCloseCurly (attempt = false) {
  106. const token = this.getToken();
  107. if(this.lexerClass.CLOSE_CURLY !== token.type){
  108. if(!attempt)
  109. throw SyntaxErrorFactory.token_missing_one('}', token);
  110. else
  111. return false;
  112. }
  113. return true;
  114. }
  115. /* It checks if the current token at position pos is a ']'.
  116. * As a check function it doesn't increment pos.
  117. *
  118. * @params bool:attempt, indicates that the token is optional. Defaults: false
  119. *
  120. * @returns true if the attempt is true and current token is '[',
  121. * false is attempt is true and current token is not '['
  122. **/
  123. checkOpenBrace (attempt = false) {
  124. const token = this.getToken();
  125. if(this.lexerClass.OPEN_BRACE !== token.type){
  126. if (!attempt) {
  127. throw SyntaxErrorFactory.token_missing_one('[', token);
  128. } else {
  129. return false;
  130. }
  131. }
  132. return true;
  133. }
  134. checkCloseBrace (attempt = false) {
  135. const token = this.getToken();
  136. if(this.lexerClass.CLOSE_BRACE !== token.type){
  137. if (!attempt) {
  138. throw SyntaxErrorFactory.token_missing_one(']', token);
  139. } else {
  140. return false;
  141. }
  142. }
  143. return true;
  144. }
  145. checkOpenParenthesis (attempt = false) {
  146. const token = this.getToken();
  147. if(this.lexerClass.OPEN_PARENTHESIS !== token.type){
  148. if (!attempt) {
  149. throw SyntaxErrorFactory.token_missing_one('(', token);
  150. } else {
  151. return false;
  152. }
  153. }
  154. return true;
  155. }
  156. checkCloseParenthesis (attempt = false) {
  157. const token = this.getToken();
  158. if(this.lexerClass.CLOSE_PARENTHESIS !== token.type){
  159. if (!attempt) {
  160. throw SyntaxErrorFactory.token_missing_one(')', token);
  161. } else {
  162. return false;
  163. }
  164. }
  165. return true;
  166. }
  167. checkEOS (attempt = false) {
  168. const eosToken = this.getToken();
  169. if (eosToken.type !== this.lexerClass.EOS) {
  170. if (!attempt)
  171. throw SyntaxErrorFactory.eos_missing(eosToken);
  172. else
  173. return false;
  174. }
  175. return true;
  176. }
  177. consumeForSemiColon () {
  178. const eosToken = this.getToken();
  179. if (eosToken.type === this.lexerClass.EOS && eosToken.text.match(';')) {
  180. this.pos++;
  181. return;
  182. }
  183. throw SyntaxErrorFactory.token_missing_one(';', eosToken);
  184. }
  185. parseGlobalVariables () {
  186. const decl = this.parseMaybeConst();
  187. const eosToken = this.getToken();
  188. this.checkEOS();
  189. this.pos++;
  190. return decl;
  191. }
  192. /*
  193. * Checks if the next token is PR_CONST. It's only available
  194. * at global variables declaration level
  195. * @returns Declararion(const, type, id, initVal?)
  196. **/
  197. parseMaybeConst () {
  198. const constToken = this.getToken();
  199. if(constToken.type === this.lexerClass.RK_CONST) {
  200. this.pos++;
  201. const typeString = this.parseType();
  202. return this.parseDeclaration(typeString, true);
  203. } else if(this.isVariableType(constToken)) {
  204. const typeString = this.parseType();
  205. return this.parseDeclaration(typeString);
  206. } else {
  207. throw SyntaxErrorFactory.token_missing_list(
  208. [this.lexer.literalNames[this.lexerClass.RK_CONST]].concat(this.getTypeArray()), constToken);
  209. }
  210. }
  211. /*
  212. * Parses a declarion of the form: type --- id --- (= --- EAnd)?
  213. * @returns a list of Declararion(const, type, id, initVal?)
  214. **/
  215. parseDeclaration (typeString, isConst = false) {
  216. let initial = null;
  217. let dim1 = null;
  218. let dim2 = null;
  219. const idString = this.parseID();
  220. // Check for array or vector
  221. // ID[int/IDi][int/IDj]
  222. if (this.checkOpenBrace(true)) {
  223. this.pos++;
  224. this.consumeNewLines();
  225. dim1 = this.parseArrayDimension();
  226. this.consumeNewLines();
  227. this.checkCloseBrace();
  228. this.pos++;
  229. if(this.checkOpenBrace(true)) {
  230. this.pos++;
  231. this.consumeNewLines();
  232. dim2 = this.parseArrayDimension();
  233. this.consumeNewLines();
  234. this.checkCloseBrace();
  235. this.pos++;
  236. }
  237. }
  238. const equalsToken = this.getToken();
  239. if(equalsToken.type === this.lexerClass.EQUAL) {
  240. this.pos++;
  241. initial = this.parseExpressionOR();
  242. }
  243. let declaration = null;
  244. if (dim1 !== null) {
  245. declaration = new Commands.ArrayDeclaration(idString,
  246. typeString, dim1, dim2, initial, isConst);
  247. } else {
  248. declaration = new Commands.Declaration(idString, typeString, initial, isConst);
  249. }
  250. const commaToken = this.getToken();
  251. if(commaToken.type === this.lexerClass.COMMA) {
  252. this.pos++;
  253. this.consumeNewLines();
  254. return [declaration]
  255. .concat(this.parseDeclaration(typeString, isConst));
  256. } else {
  257. return [declaration]
  258. }
  259. }
  260. consumeNewLines () {
  261. let token = this.getToken();
  262. while(token.type === this.lexerClass.EOS && token.text.match('[\r\n]+')) {
  263. this.pos++;
  264. token = this.getToken();
  265. }
  266. }
  267. isVariableType (token) {
  268. return this.variableTypes.find(v => v === token.type);
  269. }
  270. /*
  271. * Reads the next token of the stream to check if it is a Integer or an ID.
  272. * @returns Integer | ID
  273. **/
  274. parseArrayDimension () {
  275. const dimToken = this.getToken();
  276. if(dimToken.type === this.lexerClass.INTEGER) {
  277. //parse as int literal
  278. this.pos++;
  279. return this.getIntLiteral(dimToken);
  280. } else if(dimToken.type === this.lexerClass.ID) {
  281. //parse as variable
  282. this.pos++;
  283. return this.parseVariable(dimToken);
  284. } else {
  285. throw SyntaxErrorFactory.invalid_array_dimension(this.lexer.literalNames[this.lexerClass.RK_INTEGER], dimToken);
  286. }
  287. }
  288. /*
  289. * Returns an object {type: 'int', value: value}.
  290. * It checks for binary and hexadecimal integers.
  291. * @returns object with fields type and value
  292. **/
  293. getIntLiteral (token) {
  294. const text = token.text;
  295. return new Expressions.IntLiteral(toInt(text));
  296. }
  297. getRealLiteral (token) {
  298. return new Expressions.RealLiteral(parseFloat(token.text));
  299. }
  300. getStringLiteral (token) {
  301. const text = token.text;
  302. return new Expressions.StringLiteral(toString(text));
  303. }
  304. getBoolLiteral (token) {
  305. const val = token.type === this.lexerClass.RK_TRUE ? true : false;
  306. return new Expressions.BoolLiteral(val);
  307. }
  308. parseArrayLiteral () {
  309. this.checkOpenCurly();
  310. const beginArray = this.getToken();
  311. if (this.parsingArrayDimension >= 2) {
  312. // TODO: better error message
  313. throw SyntaxErrorFactory.token_missing_list(`Array dimensions exceed maximum size of 2 at line ${beginArray.line}`);
  314. }
  315. this.pos++;
  316. this.parsingArrayDimension++;
  317. this.consumeNewLines();
  318. const data = this.parseExpressionList();
  319. this.consumeNewLines();
  320. this.checkCloseCurly()
  321. this.pos++;
  322. this.parsingArrayDimension--;
  323. if (this.parsingArrayDimension === 0) {
  324. // if (!data.isValid) {
  325. // // TODO: better error message
  326. // console.log('invalid array');
  327. // throw new Error(`Invalid array at line ${beginArray.line}`);
  328. // }
  329. }
  330. return new Expressions.ArrayLiteral(data);
  331. }
  332. /*
  333. * Returns an object {type: 'variable', value: value}.
  334. * @returns object with fields type and value
  335. **/
  336. parseVariable (token) {
  337. return new Expressions.VariableLiteral(token.text);
  338. }
  339. /*
  340. * Returns an object representing a function. It has
  341. * four attributes: returnType, id, formalParams and block.
  342. * The block object has two attributes: declarations and commands
  343. **/
  344. parseFunction () {
  345. this.pushScope(IVProgParser.FUNCTION);
  346. let formalParams = [];
  347. const token = this.getToken();
  348. if(token.type !== this.lexerClass.RK_FUNCTION) {
  349. //throw SyntaxError.createError(this.lexer.literalNames[this.lexerClass.PR_FUNCAO], token);
  350. return null;
  351. }
  352. this.pos++;
  353. const returnType = this.parseType();
  354. const functionID = this.parseID();
  355. this.checkOpenParenthesis();
  356. this.pos++;
  357. this.consumeNewLines();
  358. if (!this.checkCloseParenthesis(true)) {
  359. formalParams = this.parseFormalParameters(); // formal parameters
  360. this.consumeNewLines();
  361. this.checkCloseParenthesis();
  362. this.pos++;
  363. } else {
  364. this.pos++;
  365. }
  366. this.consumeNewLines();
  367. const commandsBlock = this.parseCommandBlock();
  368. const func = new Commands.Function(functionID, returnType, formalParams, commandsBlock);
  369. if (functionID === null && !func.isMain) {
  370. // TODO: better error message
  371. throw SyntaxErrorFactory.invalid_main_return(this.lexerClass.MAIN_FUNCTION_NAME,
  372. this.lexer.literalNames[this.lexerClass.RK_VOID],
  373. token.line);
  374. }
  375. this.popScope();
  376. return func;
  377. }
  378. /*
  379. * Parse the formal parameters of a function.
  380. * @returns a list of objects with the following attributes: type, id and dimensions.
  381. **/
  382. parseFormalParameters () {
  383. const list = [];
  384. while(true) {
  385. let dimensions = 0;
  386. const typeString = this.parseType();
  387. const idString = this.parseID();
  388. if (this.checkOpenBrace(true)) {
  389. this.pos++;
  390. dimensions++;
  391. this.checkCloseBrace();
  392. this.pos++;
  393. if(this.checkOpenBrace(true)) {
  394. this.pos++;
  395. dimensions++;
  396. this.checkCloseBrace();
  397. this.pos++;
  398. }
  399. }
  400. list.push(new Commands.FormalParameter(typeString, idString, dimensions));
  401. const commaToken = this.getToken();
  402. if (commaToken.type !== this.lexerClass.COMMA)
  403. break;
  404. this.pos++;
  405. this.consumeNewLines();
  406. }
  407. return list;
  408. }
  409. parseID () {
  410. const token = this.getToken();
  411. if(token.type !== this.lexerClass.ID) {
  412. throw SyntaxErrorFactory.id_missing(token);
  413. }
  414. this.pos++;
  415. if (this.insideScope(IVProgParser.FUNCTION)) {
  416. if (token.text === this.lexerClass.MAIN_FUNCTION_NAME){
  417. return null;
  418. }
  419. }
  420. return token.text;
  421. }
  422. parseType () {
  423. const token = this.getToken();
  424. if(token.type === this.lexerClass.ID && this.insideScope(IVProgParser.FUNCTION)) {
  425. return Types.VOID;
  426. } else if (token.type === this.lexerClass.RK_VOID && this.insideScope(IVProgParser.FUNCTION)) {
  427. this.pos++;
  428. return Types.VOID;
  429. } else if (this.isVariableType(token)) {
  430. this.pos++;
  431. switch(token.type) {
  432. case this.lexerClass.RK_INTEGER:
  433. return Types.INTEGER;
  434. case this.lexerClass.RK_LOGIC:
  435. return Types.BOOLEAN;
  436. case this.lexerClass.RK_REAL:
  437. return Types.REAL;
  438. case this.lexerClass.RK_STRING:
  439. return Types.STRING;
  440. default:
  441. break;
  442. }
  443. }
  444. throw SyntaxErrorFactory.invalid_type(this.getTypeArray(), token);
  445. }
  446. parseCommandBlock (optionalCurly = false) {
  447. let variablesDecl = [];
  448. const commands = [];
  449. let hasOpen = false;
  450. if (this.checkOpenCurly(optionalCurly)) {
  451. this.pos++;
  452. hasOpen = true;
  453. }
  454. this.consumeNewLines();
  455. while(true) {
  456. const cmd = this.parseCommand();
  457. if (cmd === null)
  458. break;
  459. if(cmd !== -1) {
  460. if (cmd instanceof Array) {
  461. variablesDecl = variablesDecl.concat(cmd);
  462. } else {
  463. commands.push(cmd);
  464. }
  465. }
  466. }
  467. this.consumeNewLines();
  468. if (hasOpen) {
  469. this.checkCloseCurly()
  470. this.pos++;
  471. this.consumeNewLines();
  472. }
  473. return new Commands.CommandBlock(variablesDecl, commands);
  474. }
  475. parseCommand () {
  476. const token = this.getToken();
  477. if (this.isVariableType(token)) {
  478. if(!this.insideScope(IVProgParser.FUNCTION)) {
  479. // TODO better error message
  480. throw SyntaxErrorFactory.invalid_var_declaration(token.line);
  481. }
  482. this.pushScope(IVProgParser.BASE);
  483. const varType = this.parseType();
  484. this.popScope();
  485. const cmd = this.parseDeclaration(varType);
  486. this.checkEOS();
  487. this.pos++;
  488. return cmd;
  489. } else if (token.type === this.lexerClass.ID) {
  490. return this.parseIDCommand();
  491. } else if (token.type === this.lexerClass.RK_RETURN) {
  492. return this.parseReturn();
  493. } else if (token.type === this.lexerClass.RK_WHILE) {
  494. return this.parseWhile();
  495. } else if (token.type === this.lexerClass.RK_FOR) {
  496. return this.parseFor();
  497. } else if (token.type === this.lexerClass.RK_BREAK ) {
  498. if(!this.insideScope(IVProgParser.BREAKABLE)) {
  499. // TODO better error message
  500. throw SyntaxErrorFactory.invalid_break_command(
  501. this.lexer.literalNames[this.lexerClass.RK_BREAK],
  502. token
  503. );
  504. }
  505. return this.parseBreak();
  506. } else if (token.type === this.lexerClass.RK_SWITCH) {
  507. return this.parseSwitchCase();
  508. } else if (token.type === this.lexerClass.RK_DO) {
  509. return this.parseDoWhile();
  510. } else if (token.type === this.lexerClass.RK_IF) {
  511. return this.parseIfThenElse();
  512. } else if (this.checkEOS(true)){
  513. this.pos++;
  514. return -1;
  515. } else {
  516. return null;
  517. }
  518. }
  519. parseSwitchCase () {
  520. this.pushScope(IVProgParser.BREAKABLE);
  521. this.pos++;
  522. this.checkOpenParenthesis();
  523. this.pos++;
  524. this.consumeNewLines();
  525. const exp = this.parseExpressionOR();
  526. this.consumeNewLines();
  527. this.checkCloseParenthesis();
  528. this.pos++;
  529. this.consumeNewLines();
  530. this.checkOpenCurly();
  531. this.pos++;
  532. this.consumeNewLines();
  533. const casesList = this.parseCases();
  534. this.consumeNewLines();
  535. this.checkCloseCurly();
  536. this.pos++;
  537. this.consumeNewLines();
  538. this.popScope();
  539. return new Commands.Switch(exp, casesList);
  540. }
  541. parseDoWhile () {
  542. this.pos++;
  543. this.consumeNewLines();
  544. this.pushScope(IVProgParser.BREAKABLE);
  545. const commandsBlock = this.parseCommandBlock();
  546. this.consumeNewLines(); //Maybe not...
  547. const whileToken = this.getToken();
  548. if (whileToken.type !== this.lexerClass.RK_WHILE) {
  549. throw SyntaxErrorFactory.token_missing_one(this.lexer.literalNames[this.lexerClass.RK_WHILE], whileToken);
  550. }
  551. this.pos++;
  552. this.checkOpenParenthesis();
  553. this.pos++;
  554. this.consumeNewLines();
  555. const condition = this.parseExpressionOR();
  556. this.consumeNewLines();
  557. this.checkCloseParenthesis();
  558. this.pos++;
  559. this.checkEOS();
  560. this.popScope();
  561. return new Commands.DoWhile(condition, commandsBlock);
  562. }
  563. parseIfThenElse () {
  564. if(this.insideScope(IVProgParser.BREAKABLE)) {
  565. this.pushScope(IVProgParser.BREAKABLE);
  566. } else {
  567. this.pushScope(IVProgParser.COMMAND);
  568. }
  569. this.pos++;
  570. this.checkOpenParenthesis();
  571. this.pos++;
  572. this.consumeNewLines();
  573. const logicalExpression = this.parseExpressionOR();
  574. this.consumeNewLines();
  575. this.checkCloseParenthesis();
  576. this.pos++;
  577. this.consumeNewLines();
  578. const cmdBlocks = this.parseCommandBlock();
  579. const maybeElse = this.getToken();
  580. if(maybeElse.type === this.lexerClass.RK_ELSE) {
  581. this.pos++;
  582. this.consumeNewLines();
  583. const maybeIf = this.getToken();
  584. let elseBlock = null;
  585. if(this.checkOpenCurly(true)) {
  586. elseBlock = this.parseCommandBlock();
  587. } else if(maybeIf.type === this.lexerClass.RK_IF) {
  588. elseBlock = this.parseIfThenElse();
  589. } else {
  590. // TODO better error message
  591. throw SyntaxErrorFactory.token_missing_list([this.lexer.literalNames[this.lexerClass.RK_IF], '{'], maybeIf);
  592. }
  593. return new Commands.IfThenElse(logicalExpression, cmdBlocks, elseBlock);
  594. }
  595. this.popScope();
  596. return new Commands.IfThenElse(logicalExpression, cmdBlocks, null);
  597. }
  598. parseFor () {
  599. this.pushScope(IVProgParser.BREAKABLE);
  600. this.pos++;
  601. this.checkOpenParenthesis();
  602. this.pos++;
  603. this.consumeNewLines();
  604. const attribution = this.parseForAssign();
  605. this.consumeNewLines();
  606. const condition = this.parseExpressionOR();
  607. this.consumeForSemiColon();
  608. const increment = this.parseForAssign(true);
  609. this.checkCloseParenthesis()
  610. this.pos++;
  611. this.consumeNewLines();
  612. const commandsBlock = this.parseCommandBlock();
  613. this.popScope();
  614. return new Commands.For(attribution, condition, increment, commandsBlock);
  615. }
  616. parseWhile () {
  617. this.pushScope(IVProgParser.BREAKABLE);
  618. this.pos++;
  619. this.checkOpenParenthesis();
  620. this.pos++;
  621. this.consumeNewLines();
  622. const logicalExpression = this.parseExpressionOR();
  623. this.consumeNewLines();
  624. this.checkCloseParenthesis();
  625. this.pos++;
  626. this.consumeNewLines();
  627. const cmdBlocks = this.parseCommandBlock();
  628. this.popScope();
  629. return new Commands.While(logicalExpression, cmdBlocks);
  630. }
  631. parseBreak () {
  632. this.pos++;
  633. this.checkEOS();
  634. this.pos++;
  635. return new Commands.Break();
  636. }
  637. parseReturn () {
  638. this.pos++;
  639. let exp = null;
  640. if(!this.checkEOS(true)) {
  641. exp = this.parseExpressionOR();
  642. this.checkEOS();
  643. }
  644. this.pos++;
  645. return new Commands.Return(exp);
  646. }
  647. parseIDCommand () {
  648. const id = this.parseID();
  649. const equalOrParenthesis = this.getToken();
  650. if (equalOrParenthesis.type === this.lexerClass.EQUAL) {
  651. this.pos++
  652. const exp = this.parseExpressionOR();
  653. this.checkEOS();
  654. this.pos++;
  655. return (new Commands.Assign(id, exp));
  656. } else if (equalOrParenthesis.type === this.lexerClass.OPEN_PARENTHESIS) {
  657. const funcCall = this.parseFunctionCallCommand(id);
  658. this.checkEOS();
  659. this.pos++;
  660. return funcCall;
  661. } else {
  662. throw SyntaxErrorFactory.token_missing_list(['=','('], equalOrParenthesis);
  663. }
  664. }
  665. parseForAssign (isLast = false) {
  666. if(!isLast)
  667. this.consumeNewLines();
  668. if(this.checkEOS(true)) {
  669. return null;
  670. }
  671. const id = this.parseID();
  672. const equal = this.getToken();
  673. if (equal.type !== this.lexerClass.EQUAL) {
  674. throw SyntaxErrorFactory.token_missing_one('=', equal);
  675. }
  676. this.pos++
  677. const exp = this.parseExpressionOR();
  678. if(!isLast) {
  679. this.consumeForSemiColon();
  680. }
  681. return new Commands.Assign(id, exp);
  682. }
  683. parseCases () {
  684. const token = this.getToken();
  685. if(token.type !== this.lexerClass.RK_CASE) {
  686. throw SyntaxErrorFactory.token_missing_one(this.lexer.literalNames[this.lexerClass.RK_CASE], token);
  687. }
  688. this.pos++;
  689. const nextToken = this.getToken();
  690. if(nextToken.type === this.lexerClass.RK_DEFAULT) {
  691. this.pos++;
  692. const colonToken = this.getToken();
  693. if (colonToken.type !== this.lexerClass.COLON) {
  694. throw SyntaxErrorFactory.token_missing_one(':', colonToken);
  695. }
  696. this.pos++;
  697. this.consumeNewLines();
  698. const block = this.parseCommandBlock(true);
  699. const defaultCase = new Commands.Case(null);
  700. defaultCase.setCommands(block.commands);
  701. return [defaultCase];
  702. } else {
  703. const exp = this.parseExpressionOR();
  704. const colonToken = this.getToken();
  705. if (colonToken.type !== this.lexerClass.COLON) {
  706. throw SyntaxErrorFactory.token_missing_one(':', colonToken);
  707. }
  708. this.pos++;
  709. this.consumeNewLines();
  710. const block = this.parseCommandBlock(true);
  711. const aCase = new Commands.Case(exp);
  712. aCase.setCommands(block.commands);
  713. const caseToken = this.getToken();
  714. if(caseToken.type === this.lexerClass.RK_CASE) {
  715. return [aCase].concat(this.parseCases());
  716. } else {
  717. return [aCase];
  718. }
  719. }
  720. }
  721. /*
  722. * Parses an Expression following the structure:
  723. *
  724. * EOR => EAnd ( 'or' EOR)? #expression and
  725. *
  726. * EOR => ENot ('and' EOR)? #expression or
  727. *
  728. * ENot => 'not'? ER #expression not
  729. *
  730. * ER => E ((>=, <=, ==, >, <) E)? #expression relational
  731. *
  732. * E => factor ((+, -) E)? #expression
  733. *
  734. * factor=> term ((*, /, %) factor)?
  735. *
  736. * term => literal || arrayAccess || FuncCall || ID || '('EAnd')'
  737. **/
  738. parseExpressionOR () {
  739. let exp1 = this.parseExpressionAND();
  740. while (this.getToken().type === this.lexerClass.OR_OPERATOR) {
  741. this.pos++;
  742. const or = convertFromString('or');
  743. this.consumeNewLines();
  744. const exp2 = this.parseExpressionAND();
  745. const finalExp = new Expressions.InfixApp(or, exp1, exp2);
  746. exp1 = finalExp
  747. }
  748. return exp1;
  749. }
  750. parseExpressionAND () {
  751. let exp1 = this.parseExpressionNot();
  752. while (this.getToken().type === this.lexerClass.AND_OPERATOR) {
  753. this.pos++;
  754. const and = convertFromString('and');
  755. this.consumeNewLines();
  756. const exp2 = this.parseExpressionNot();
  757. const finalExp = new Expressions.InfixApp(and, exp1, exp2);
  758. exp1 = finalExp;
  759. }
  760. return exp1;
  761. }
  762. parseExpressionNot () {
  763. const maybeNotToken = this.getToken();
  764. if (maybeNotToken.type === this.lexerClass.NOT_OPERATOR) {
  765. this.pos++;
  766. const not = convertFromString('not');
  767. const exp1 = this.parseExpressionRel();
  768. return new Expressions.UnaryApp(not, exp1);
  769. } else {
  770. return this.parseExpressionRel();
  771. }
  772. }
  773. parseExpressionRel () {
  774. let exp1 = this.parseExpression();
  775. while (this.getToken().type === this.lexerClass.RELATIONAL_OPERATOR) {
  776. const relToken = this.getToken();
  777. this.pos++;
  778. const rel = convertFromString(relToken.text);
  779. const exp2 = this.parseExpression();
  780. const finalExp = new Expressions.InfixApp(rel, exp1, exp2);
  781. exp1 = finalExp;
  782. }
  783. return exp1;
  784. }
  785. parseExpression () {
  786. let factor = this.parseFactor();
  787. while (this.getToken().type === this.lexerClass.SUM_OP) {
  788. const sumOpToken = this.getToken();
  789. this.pos++;
  790. const op = convertFromString(sumOpToken.text);
  791. const factor2 = this.parseFactor();
  792. const finalExp = new Expressions.InfixApp(op, factor, factor2);
  793. factor = finalExp;
  794. }
  795. return factor;
  796. }
  797. parseFactor () {
  798. let term = this.parseTerm();
  799. while (this.getToken().type === this.lexerClass.MULTI_OP) {
  800. const multOpToken = this.getToken();
  801. this.pos++;
  802. const op = convertFromString(multOpToken.text);
  803. const term2 =this.parseTerm();
  804. const finalExp = new Expressions.InfixApp(op, term, term2);
  805. term = finalExp;
  806. }
  807. return term;
  808. }
  809. parseTerm () {
  810. const token = this.getToken();
  811. switch(token.type) {
  812. case this.lexerClass.SUM_OP:
  813. this.pos++;
  814. return new Expressions.UnaryApp(convertFromString(token.text), this.parseTerm());
  815. case this.lexerClass.INTEGER:
  816. this.pos++;
  817. return this.getIntLiteral(token);
  818. case this.lexerClass.REAL:
  819. this.pos++;
  820. return this.getRealLiteral(token);
  821. case this.lexerClass.STRING:
  822. this.pos++;
  823. return this.getStringLiteral(token);
  824. case this.lexerClass.RK_TRUE:
  825. case this.lexerClass.RK_FALSE:
  826. this.pos++;
  827. return this.getBoolLiteral(token);
  828. case this.lexerClass.OPEN_CURLY:
  829. return this.parseArrayLiteral();
  830. case this.lexerClass.ID:
  831. return this.parseIDTerm();
  832. case this.lexerClass.OPEN_PARENTHESIS:
  833. return this.parseParenthesisExp();
  834. default:
  835. throw SyntaxErrorFactory.invalid_terminal(token);
  836. }
  837. }
  838. parseIDTerm () {
  839. const id = this.parseID();
  840. const last = this.pos;
  841. if(this.checkOpenBrace(true)) {
  842. this.pos++;
  843. const firstIndex = this.parseExpression();
  844. let secondIndex = null;
  845. this.consumeNewLines();
  846. this.checkCloseBrace();
  847. this.pos++;
  848. if(this.checkOpenBrace(true)){
  849. this.pos++;
  850. secondIndex = this.parseExpression();
  851. this.consumeNewLines();
  852. this.checkCloseBrace();
  853. this.pos++;
  854. }
  855. return new Expressions.ArrayAccess(id, firstIndex, secondIndex);
  856. } else if (this.checkOpenParenthesis(true)) {
  857. return this.parseFunctionCallExpression(id);
  858. } else {
  859. this.pos = last;
  860. return new Expressions.VariableLiteral(id);
  861. }
  862. }
  863. getFunctionName (id) {
  864. if (id === this.lexerClass.READ_FUNCTION_NAME) {
  865. return NAMES.READ;
  866. } else if (id === this.lexerClass.WRITE_FUNCTION_NAME) {
  867. return NAMES.WRITE;
  868. } else {
  869. return id;
  870. }
  871. }
  872. parseFunctionCallExpression (id) {
  873. const actualParameters = this.parseActualParameters();
  874. const funcName = this.getFunctionName(id);
  875. return new Expressions.FunctionCall(funcName, actualParameters);
  876. }
  877. parseFunctionCallCommand (id) {
  878. return this.parseFunctionCallExpression(id);
  879. }
  880. parseParenthesisExp () {
  881. this.checkOpenParenthesis();
  882. this.pos++;
  883. this.consumeNewLines();
  884. const exp = this.parseExpressionOR();
  885. this.consumeNewLines();
  886. this.checkCloseParenthesis();
  887. this.pos++;
  888. return exp;
  889. }
  890. parseActualParameters () {
  891. this.checkOpenParenthesis();
  892. this.pos++;
  893. if(this.checkCloseParenthesis(true)) {
  894. this.pos++;
  895. return [];
  896. }
  897. this.consumeNewLines();
  898. const list = this.parseExpressionList();
  899. this.consumeNewLines();
  900. this.checkCloseParenthesis();
  901. this.pos++;
  902. return list;
  903. }
  904. parseExpressionList () {
  905. const list = [];
  906. while(true) {
  907. const exp = this.parseExpressionOR();
  908. list.push(exp);
  909. const maybeToken = this.getToken();
  910. if (maybeToken.type !== this.lexerClass.COMMA) {
  911. break;
  912. } else {
  913. this.pos++;
  914. this.consumeNewLines();
  915. }
  916. }
  917. return list;
  918. }
  919. getTypeArray () {
  920. const types = this.insideScope(IVProgParser.FUNCTION) ? this.functionTypes : this.variableTypes;
  921. return types.map( x => this.lexer.literalNames[x]);
  922. }
  923. }