ivprogParser.js 28 KB

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