ivprogParser.js 27 KB

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