ivprogParser.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  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. const typeString = this.parseType();
  203. return this.parseDeclararion(typeString);
  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.pushScope(IVProgParser.BASE);
  495. const varType = this.parseType();
  496. this.popScope();
  497. cmd = this.parseDeclararion(varType);
  498. this.checkEOS();
  499. this.pos++;
  500. } else if (token.type === this.lexerClass.ID) {
  501. cmd = this.parseIDCommand();
  502. } else if (token.type === this.lexerClass.RK_RETURN) {
  503. cmd = this.parseReturn();
  504. } else if (token.type === this.lexerClass.RK_WHILE) {
  505. cmd = this.parseWhile();
  506. } else if (token.type === this.lexerClass.RK_FOR) {
  507. cmd = this.parseFor();
  508. } else if (token.type === this.lexerClass.RK_BREAK ) {
  509. if(!this.insideScope(IVProgParser.BREAKABLE)) {
  510. // TODO better error message
  511. throw new Error("Break cannot be used outside of a loop.");
  512. }
  513. cmd = this.parseBreak();
  514. } else if (token.type === this.lexerClass.RK_SWITCH) {
  515. cmd = this.parseSwitchCase();
  516. } else if (token.type === this.lexerClass.RK_DO) {
  517. cmd = this.parseDoWhile();
  518. } else if (token.type === this.lexerClass.RK_IF) {
  519. cmd = this.parseIfThenElse();
  520. } else if (this.checkEOS(true)){
  521. this.pos++;
  522. cmd = -1;
  523. }
  524. return cmd;
  525. }
  526. parseSwitchCase () {
  527. this.pushScope(IVProgParser.BREAKABLE);
  528. this.pos++;
  529. this.checkOpenParenthesis();
  530. this.pos++;
  531. this.consumeNewLines();
  532. const exp = this.parseExpressionOR();
  533. this.consumeNewLines();
  534. this.checkCloseParenthesis();
  535. this.pos++;
  536. this.consumeNewLines();
  537. this.checkOpenCurly();
  538. this.pos++;
  539. this.consumeNewLines();
  540. const casesList = this.parseCases();
  541. this.consumeNewLines();
  542. this.checkCloseCurly();
  543. this.pos++;
  544. this.consumeNewLines();
  545. this.popScope();
  546. return new Commands.Switch(casesList);
  547. }
  548. parseDoWhile () {
  549. this.pos++;
  550. this.consumeNewLines();
  551. this.pushScope(IVProgParser.BREAKABLE);
  552. const commandsBlock = this.parseCommandBlock();
  553. this.consumeNewLines(); //Maybe not...
  554. const whileToken = this.getToken();
  555. if (whileToken.type !== this.lexerClass.RK_WHILE) {
  556. throw SyntaxError.createError(this.lexer.literalNames[this.lexerClass.RK_WHILE], whileToken);
  557. }
  558. this.pos++;
  559. this.checkOpenParenthesis();
  560. this.pos++;
  561. this.consumeNewLines();
  562. const condition = this.parseExpressionOR();
  563. this.consumeNewLines();
  564. this.checkCloseParenthesis();
  565. this.pos++;
  566. this.checkEOS();
  567. this.popScope();
  568. return new Commands.DoWhile(condition, commandsBlock);
  569. }
  570. parseIfThenElse () {
  571. if(this.insideScope(IVProgParser.BREAKABLE)) {
  572. this.pushScope(IVProgParser.BREAKABLE);
  573. } else {
  574. this.pushScope(IVProgParser.COMMAND);
  575. }
  576. this.pos++;
  577. this.checkOpenParenthesis();
  578. this.pos++;
  579. this.consumeNewLines();
  580. const logicalExpression = this.parseExpressionOR();
  581. this.consumeNewLines();
  582. this.checkCloseParenthesis();
  583. this.pos++;
  584. this.consumeNewLines();
  585. const cmdBlocks = this.parseCommandBlock();
  586. const maybeElse = this.getToken();
  587. if(maybeElse.type === this.lexerClass.RK_ELSE) {
  588. this.pos++;
  589. this.consumeNewLines();
  590. let elseBlock = null;
  591. if(this.checkOpenCurly(true)) {
  592. elseBlock = this.parseCommandBlock();
  593. } else {
  594. elseBlock = this.parseIfThenElse();
  595. }
  596. return new Commands.IfThenElse(logicalExpression, cmdBlocks, elseBlock);
  597. }
  598. this.popScope();
  599. return new Commands.IfThenElse(logicalExpression, cmdBlocks, null);
  600. }
  601. parseFor () {
  602. this.pushScope(IVProgParser.BREAKABLE);
  603. this.pos++;
  604. this.checkOpenParenthesis();
  605. this.pos++;
  606. this.consumeNewLines();
  607. const attribution = this.parseForAssign();
  608. this.consumeNewLines();
  609. const condition = this.parseExpressionOR();
  610. this.consumeForSemiColon();
  611. const increment = this.parseForAssign(true);
  612. this.checkCloseParenthesis()
  613. this.pos++;
  614. this.consumeNewLines();
  615. const commandsBlock = this.parseCommandBlock();
  616. this.popScope();
  617. return new Commands.For(attribution, condition, increment, commandsBlock);
  618. }
  619. parseWhile () {
  620. this.pushScope(IVProgParser.BREAKABLE);
  621. this.pos++;
  622. this.checkOpenParenthesis();
  623. this.pos++;
  624. this.consumeNewLines();
  625. const logicalExpression = this.parseExpressionOR();
  626. this.consumeNewLines();
  627. this.checkCloseParenthesis();
  628. this.pos++;
  629. this.consumeNewLines();
  630. const cmdBlocks = this.parseCommandBlock();
  631. this.popScope();
  632. return new Commands.While(logicalExpression, cmdBlocks);
  633. }
  634. parseBreak () {
  635. this.pos++;
  636. this.checkEOS();
  637. this.pos++;
  638. return (new Commands.Break());
  639. }
  640. parseReturn () {
  641. this.pos++;
  642. let exp = null;
  643. if(!this.checkEOS(true)) {
  644. exp = this.parseExpressionOR();
  645. this.checkEOS();
  646. }
  647. this.pos++;
  648. return new Commands.Return(exp);
  649. }
  650. parseIDCommand () {
  651. const id = this.parseID();
  652. const equalOrParenthesis = this.getToken();
  653. if (equalOrParenthesis.type === this.lexerClass.EQUAL) {
  654. this.pos++
  655. const exp = this.parseExpressionOR();
  656. this.checkEOS();
  657. this.pos++;
  658. return (new Commands.Assign(id, exp));
  659. } else if (equalOrParenthesis.type === this.lexerClass.OPEN_PARENTHESIS) {
  660. const actualParameters = this.parseActualParameters();
  661. this.checkEOS();
  662. this.pos++;
  663. return (new Expressions.FunctionCall(id, actualParameters));
  664. } else {
  665. throw SyntaxError.createError("= or (", equalOrParenthesis);
  666. }
  667. }
  668. parseForAssign (isLast = false) {
  669. if(!isLast)
  670. this.consumeNewLines();
  671. if(this.checkEOS(true)) {
  672. return null;
  673. }
  674. const id = this.parseID();
  675. const equal = this.getToken();
  676. if (equal.type !== this.lexerClass.EQUAL) {
  677. throw SyntaxError.createError('=', equal);
  678. }
  679. this.pos++
  680. const exp = this.parseExpressionOR();
  681. if(!isLast) {
  682. this.consumeForSemiColon();
  683. }
  684. return new Commands.Assign(id, exp);
  685. }
  686. parseCases () {
  687. const token = this.getToken();
  688. if(token.type !== this.lexerClass.RK_CASE) {
  689. throw SyntaxError.createError(this.lexer.literalNames[this.lexerClass.RK_CASE], token);
  690. }
  691. this.pos++;
  692. const nextToken = this.getToken();
  693. if(nextToken.type === this.lexerClass.RK_DEFAULT) {
  694. this.pos++;
  695. const colonToken = this.getToken();
  696. if (colonToken.type !== this.lexerClass.COLON) {
  697. throw SyntaxError.createError(':', colonToken);
  698. }
  699. this.pos++;
  700. this.consumeNewLines();
  701. const block = this.parseCommandBlock(true);
  702. const defaultCase = new Commands.Case(null);
  703. defaultCase.setCommands(block.commands);
  704. return [defaultCase];
  705. } else {
  706. const exp = this.parseExpressionOR();
  707. const colonToken = this.getToken();
  708. if (colonToken.type !== this.lexerClass.COLON) {
  709. throw SyntaxError.createError(':', colonToken);
  710. }
  711. this.pos++;
  712. this.consumeNewLines();
  713. const block = this.parseCommandBlock(true);
  714. const aCase = new Commands.Case(exp);
  715. aCase.setCommands(block.commands);
  716. const caseToken = this.getToken();
  717. if(caseToken.type === this.lexerClass.RK_CASE) {
  718. return [aCase].concat(this.parseCases());
  719. } else {
  720. return [aCase];
  721. }
  722. }
  723. }
  724. /*
  725. * Parses an Expression following the structure:
  726. *
  727. * EOR => EAnd ( 'or' EOR)? #expression and
  728. *
  729. * EOR => ENot ('and' EOR)? #expression or
  730. *
  731. * ENot => 'not'? ER #expression not
  732. *
  733. * ER => E ((>=, <=, ==, >, <) E)? #expression relational
  734. *
  735. * E => factor ((+, -) E)? #expression
  736. *
  737. * factor=> term ((*, /, %) factor)?
  738. *
  739. * term => literal || arrayAccess || FuncCall || ID || '('EAnd')'
  740. **/
  741. parseExpressionOR () {
  742. const exp1 = this.parseExpressionAND();
  743. const maybeAnd = this.getToken();
  744. if (maybeAnd.type === this.lexerClass.OR_OPERATOR) {
  745. this.pos++;
  746. const or = 'or';
  747. this.consumeNewLines();
  748. const exp2 = this.parseExpressionOR();
  749. return new Expressions.InfixApp(or, exp1, exp2);
  750. }
  751. return exp1;
  752. }
  753. parseExpressionAND () {
  754. const exp1 = this.parseExpressionNot();
  755. const andToken = this.getToken();
  756. if (andToken.type === this.lexerClass.AND_OPERATOR) {
  757. this.pos++;
  758. const and = 'and';
  759. this.consumeNewLines();
  760. const exp2 = this.parseExpressionAND();
  761. return new Expressions.InfixApp(and, exp1, exp2);
  762. }
  763. return exp1;
  764. }
  765. parseExpressionNot () {
  766. const maybeNotToken = this.getToken();
  767. if (maybeNotToken.type === this.lexerClass.NOT_OPERATOR) {
  768. this.pos++;
  769. const not = 'not';
  770. const exp1 = this.parseExpressionRel();
  771. return new Expressions.UnaryApp(not, exp1);
  772. } else {
  773. return this.parseExpressionRel();
  774. }
  775. }
  776. parseExpressionRel () {
  777. const exp1 = this.parseExpression();
  778. const relToken = this.getToken();
  779. if(relToken.type === this.lexerClass.RELATIONAL_OPERATOR) {
  780. this.pos++;
  781. const rel = relToken.text; // TODO: source code line/column information
  782. const exp2 = this.parseExpression();
  783. return new Expressions.InfixApp(rel, exp1, exp2);
  784. }
  785. return exp1;
  786. }
  787. parseExpression () {
  788. const factor = this.parseFactor();
  789. const sumOpToken = this.getToken();
  790. if(sumOpToken.type === this.lexerClass.SUM_OP) {
  791. this.pos++;
  792. const op = sumOpToken.text; // TODO: source code line/column information
  793. const exp = this.parseExpression();
  794. return new Expressions.InfixApp(op, factor, exp);
  795. }
  796. return factor;
  797. }
  798. parseFactor () {
  799. const term = this.parseTerm();
  800. const multOpToken = this.getToken();
  801. if(multOpToken.type === this.lexerClass.MULTI_OP) {
  802. this.pos++;
  803. const op = multOpToken.text; // TODO: source code line/column information
  804. const factor = this.parseFactor();
  805. return new Expressions.InfixApp(op, term, factor);
  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(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 SyntaxError.createError('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. } else {
  855. this.pos--;
  856. }
  857. return new Expressions.ArrayAccess(id, firstIndex, secondIndex);
  858. } else if (this.checkOpenParenthesis(true)) {
  859. this.pos++;
  860. this.consumeNewLines();
  861. let actualParameters = [];
  862. if(!this.checkCloseParenthesis(true)) {
  863. actualParameters = this.parseActualParameters();
  864. this.consumeNewLines();
  865. this.checkCloseParenthesis();
  866. this.pos++;
  867. } else {
  868. this.pos++;
  869. }
  870. return new Expressions.FunctionCall(id, actualParameters);
  871. } else {
  872. this.pos = last;
  873. return id;
  874. }
  875. }
  876. parseParenthesisExp () {
  877. this.checkOpenParenthesis();
  878. this.pos++;
  879. this.consumeNewLines();
  880. const exp = this.parseExpressionOR();
  881. this.consumeNewLines();
  882. this.checkCloseParenthesis();
  883. this.pos++;
  884. return exp;
  885. }
  886. parseActualParameters () {
  887. this.checkOpenParenthesis();
  888. this.pos++;
  889. this.consumeNewLines();
  890. const list = this.parseExpressionList();
  891. this.consumeNewLines();
  892. this.checkCloseParenthesis();
  893. this.pos++;
  894. return list;
  895. }
  896. parseExpressionList () {
  897. const list = [];
  898. while(true) {
  899. const exp = this.parseExpressionOR();
  900. list.push(exp);
  901. const maybeToken = this.getToken();
  902. if (maybeToken.type !== this.lexerClass.COMMA) {
  903. break;
  904. } else {
  905. this.pos++;
  906. this.consumeNewLines();
  907. }
  908. }
  909. return list;
  910. }
  911. getTypesAsString () {
  912. const types = this.insideScope(IVProgParser.FUNCTION) ? this.functionTypes : this.variableTypes;
  913. return types.map( x => this.lexer.literalNames[x])
  914. .reduce((o, n) => {
  915. if (o.length <= 0)
  916. return n;
  917. else
  918. return o + ", " + n;
  919. }, '');
  920. }
  921. }