ivprogParser.js 27 KB

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