1
0

ivprogParser.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  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 || token.type === this.lexerClass.ID) {
  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. parseGlobalVariables () {
  176. const decl = this.parseMaybeConst();
  177. const eosToken = this.getToken();
  178. this.checkEOS();
  179. this.pos++;
  180. return decl;
  181. }
  182. /*
  183. * Checks if the next token is PR_CONST. It's only available
  184. * at global variables declaration level
  185. * @returns Declararion(const, type, id, initVal?)
  186. **/
  187. parseMaybeConst () {
  188. const constToken = this.getToken();
  189. if(constToken.type === this.lexerClass.RK_CONST) {
  190. this.pos++;
  191. const typeString = this.parseType();
  192. return this.parseDeclararion(typeString, true);
  193. } else if(this.isVariableType(constToken)) {
  194. this.pos++;
  195. return this.parseDeclararion(constToken);
  196. } else {
  197. throw SyntaxError.createError(this.lexer.literalNames[this.lexerClass.RK_CONST] + ' or ' + this.getTypesAsString(), constToken);
  198. }
  199. }
  200. /*
  201. * Parses a declarion of the form: type --- id --- (= --- EAnd)?
  202. * @returns a list of Declararion(const, type, id, initVal?)
  203. **/
  204. parseDeclararion (typeString, isConst = false) {
  205. let initial = null;
  206. let dim1 = null;
  207. let dim2 = null;
  208. const idString = this.parseID();
  209. // Check for array or vector
  210. // ID[int/IDi][int/IDj]
  211. if (this.checkOpenBrace(true)) {
  212. this.pos++;
  213. this.consumeNewLines();
  214. dim1 = this.parseArrayDimension();
  215. this.consumeNewLines();
  216. this.checkCloseBrace();
  217. this.pos++;
  218. if(this.checkOpenBrace(true)) {
  219. this.pos++;
  220. this.consumeNewLines();
  221. dim2 = this.parseArrayDimension();
  222. this.consumeNewLines();
  223. this.checkCloseBrace();
  224. this.pos++;
  225. }
  226. }
  227. const equalsToken = this.getToken();
  228. if(equalsToken.type === this.lexerClass.EQUAL) {
  229. this.pos++;
  230. initial = this.parseExpressionOR();
  231. }
  232. let declaration = null;
  233. if (dim1 !== null) {
  234. declaration = new Commands.ArrayDeclaration(idString,
  235. typeString, dim1, dim2, initial, isConst);
  236. } else {
  237. declaration = new Commands.Declaration(idString, typeString, initial, isConst);
  238. }
  239. const commaToken = this.getToken();
  240. if(commaToken.type === this.lexerClass.COMMA) {
  241. console.log("comma found");
  242. this.pos++;
  243. this.consumeNewLines();
  244. return [declaration]
  245. .concat(this.parseDeclararion(typeString, isConst));
  246. } else {
  247. return [declaration]
  248. }
  249. }
  250. consumeNewLines () {
  251. let token = this.getToken();
  252. while(token.type === this.lexerClass.EOS && token.text.match('[\r\n]+')) {
  253. this.pos++;
  254. token = this.getToken();
  255. }
  256. }
  257. isVariableType (token) {
  258. return this.variableTypes.find(v => v === token.type);
  259. }
  260. /*
  261. * Reads the next token of the stream to check if it is a Integer or an ID.
  262. * @returns Integer | ID
  263. **/
  264. parseArrayDimension () {
  265. const dimToken = this.getToken();
  266. if(dimToken.type === this.lexerClass.INTEGER) {
  267. //parse as int literal
  268. this.pos++;
  269. return this.getIntLiteral(dimToken);
  270. } else if(dimToken.type === this.lexerClass.ID) {
  271. //parse as variable
  272. this.pos++;
  273. return this.parseVariable(dimToken);
  274. } else {
  275. throw SyntaxError.createError('int or ID', dimToken);
  276. }
  277. }
  278. /*
  279. * Returns an object {type: 'int', value: value}.
  280. * It checks for binary and hexadecimal integers.
  281. * @returns object with fields type and value
  282. **/
  283. getIntLiteral (token) {
  284. const text = token.text;
  285. let val = null;
  286. if(text.match('^0b|^0B')) {
  287. val = parseInt(text.substring(2), 2);
  288. } else if (text.match('^0x|^0X')) {
  289. val = parseInt(text.substring(2), 16);
  290. } else {
  291. val = parseInt(text);
  292. }
  293. return new Expressions.IntLiteral(val);
  294. }
  295. getRealLiteral (token) {
  296. return new Expressions.RealLiteral(parseFloat(token.text));
  297. }
  298. getStringLiteral (token) {
  299. const text = token.text;
  300. let value = text.replace("\\b", "\b");
  301. value = value.replace("\\t", "\t");
  302. value = value.replace("\\n", "\n");
  303. value = value.replace("\\r", "\r");
  304. value = value.replace("\\\"", "\"");
  305. value = value.replace("\\\'", "\'");
  306. value = value.replace("\\\\", "\\");
  307. return new Expressions.StringLiteral(value);
  308. }
  309. getBoolLiteral (token) {
  310. const val = token.type === this.lexerClass.RK_True ? true : false;
  311. return new Expressions.BoolLiteral(val);
  312. }
  313. parseArrayLiteral () {
  314. this.checkOpenCurly();
  315. const beginArray = this.getToken();
  316. if (this.parsingArrayDimension >= 2) {
  317. // TODO: better error message
  318. throw new Error(`Array dimensions exceed maximum size of 2 at line ${beginArray.line}`);
  319. }
  320. this.pos++;
  321. this.parsingArrayDimension++;
  322. this.consumeNewLines();
  323. const data = this.parseExpressionList();
  324. this.consumeNewLines();
  325. this.checkCloseCurly()
  326. this.pos++;
  327. this.parsingArrayDimension--;
  328. if (this.parsingArrayDimension === 0) {
  329. if (!data.isValid) {
  330. // TODO: better error message
  331. console.log('invalid array');
  332. throw new Error(`Invalid array at line ${beginArray.line}`);
  333. }
  334. }
  335. return new Expressions.ArrayLiteral(data);
  336. }
  337. /*
  338. * Returns an object {type: 'variable', value: value}.
  339. * @returns object with fields type and value
  340. **/
  341. parseVariable (token) {
  342. return new Expressions.VariableLiteral(token.text);
  343. }
  344. /*
  345. * Returns an object representing a function. It has
  346. * four attributes: returnType, id, formalParams and block.
  347. * The block object has two attributes: declarations and commands
  348. **/
  349. parseFunction () {
  350. this.pushScope(IVProgParser.FUNCTION);
  351. let formalParams = [];
  352. const token = this.getToken();
  353. if(token.type !== this.lexerClass.RK_FUNCTION) {
  354. //throw SyntaxError.createError(this.lexer.literalNames[this.lexerClass.PR_FUNCAO], token);
  355. return null;
  356. }
  357. this.pos++;
  358. const returnType = this.parseType();
  359. const functionID = this.parseID();
  360. this.checkOpenParenthesis();
  361. this.pos++;
  362. this.consumeNewLines();
  363. if (!this.checkCloseParenthesis(true)) {
  364. formalParams = this.parseFormalParameters(); // formal parameters
  365. this.consumeNewLines();
  366. this.checkCloseParenthesis();
  367. this.pos++;
  368. } else {
  369. this.pos++;
  370. }
  371. this.consumeNewLines();
  372. const commandsBlock = this.parseCommandBlock();
  373. const func = new Commands.Function(functionID, returnType, formalParams, commandsBlock);
  374. if (functionID === null && !func.isMain) {
  375. // TODO: better error message
  376. throw new Error(`Function ${this.lexerClass.MAIN_FUNCTION_NAME} must return void (line ${token.line})`);
  377. }
  378. this.popScope();
  379. return func;
  380. }
  381. /*
  382. * Parse the formal parameters of a function.
  383. * @returns a list of objects with the following attributes: type, id and dimensions.
  384. **/
  385. parseFormalParameters () {
  386. const list = [];
  387. while(true) {
  388. let dimensions = 0;
  389. const typeString = this.parseType();
  390. const idString = this.parseID();
  391. if (this.checkOpenBrace(true)) {
  392. this.pos++;
  393. dimensions++;
  394. this.checkCloseBrace();
  395. this.pos++;
  396. if(this.checkOpenBrace(true)) {
  397. this.pos++;
  398. dimensions++;
  399. this.checkCloseBrace();
  400. this.pos++;
  401. }
  402. }
  403. list.push({type: typeString, id: idString, dimensions: dimensions});
  404. const commaToken = this.getToken();
  405. if (commaToken.type !== this.lexerClass.COMMA)
  406. break;
  407. this.pos++;
  408. this.consumeNewLines();
  409. }
  410. return list;
  411. }
  412. parseID () {
  413. const token = this.getToken();
  414. if(token.type !== this.lexerClass.ID) {
  415. throw SyntaxError.createError('ID', token);
  416. }
  417. this.pos++;
  418. if (this.insideScope(IVProgParser.FUNCTION)) {
  419. if (token.text === this.lexerClass.MAIN_FUNCTION_NAME){
  420. return null;
  421. }
  422. }
  423. return token.text;
  424. }
  425. parseType () {
  426. const token = this.getToken();
  427. if(token.type === this.lexerClass.ID && this.insideScope(IVProgParser.FUNCTION)) {
  428. return Types.VOID;
  429. } else if (token.type === this.lexerClass.RK_VOID && this.insideScope(IVProgParser.FUNCTION)) {
  430. this.pos++;
  431. return Types.VOID;
  432. } else if (this.isVariableType(token)) {
  433. this.pos++;
  434. switch(token.type) {
  435. case this.lexerClass.RK_INTEGER:
  436. return Types.INTEGER;
  437. case this.lexerClass.RK_LOGIC:
  438. return Types.BOOLEAN;
  439. case this.lexerClass.RK_REAL:
  440. return Types.REAL;
  441. case this.lexerClass.RK_STRING:
  442. return Types.STRING;
  443. default:
  444. break;
  445. }
  446. }
  447. throw SyntaxError.createError(this.getTypesAsString(), token);
  448. }
  449. parseCommandBlock (optionalCurly = false) {
  450. let variablesDecl = [];
  451. const commands = [];
  452. let hasOpen = false;
  453. if (this.checkOpenCurly(optionalCurly)) {
  454. this.pos++;
  455. hasOpen = true;
  456. }
  457. this.consumeNewLines();
  458. while(true) {
  459. const cmd = this.parseCommand();
  460. if (cmd === null)
  461. break;
  462. if(cmd !== -1) {
  463. if (cmd instanceof Commands.Declaration) {
  464. variablesDecl.push(cmd);
  465. } else {
  466. commands.push(cmd);
  467. }
  468. }
  469. }
  470. this.consumeNewLines();
  471. if (hasOpen) {
  472. this.checkCloseCurly()
  473. this.pos++;
  474. this.consumeNewLines();
  475. }
  476. return new Commands.CommandBlock(variablesDecl, commands);
  477. }
  478. parseCommand () {
  479. const token = this.getToken();
  480. let cmd = null;
  481. if (this.isVariableType(token)) {
  482. if(!this.insideScope(IVProgParser.FUNCTION)) {
  483. // TODO better error message
  484. throw new Error(`Cannot declare variable here (line ${token.line})`);
  485. }
  486. this.pos++;
  487. cmd = this.parseDeclararion(token);
  488. this.checkEOS();
  489. this.pos++;
  490. } else if (token.type === this.lexerClass.ID) {
  491. cmd = this.parseIDCommand();
  492. } else if (token.type === this.lexerClass.RK_RETURN) {
  493. cmd = this.parseReturn();
  494. } else if (token.type === this.lexerClass.RK_WHILE) {
  495. cmd = this.parseWhile();
  496. } else if (token.type === this.lexerClass.RK_FOR) {
  497. cmd = this.parseFor();
  498. } else if (token.type === this.lexerClass.RK_BREAK ) {
  499. if(!this.insideScope(IVProgParser.BREAKABLE)) {
  500. // TODO better error message
  501. throw new Error("Break cannot be used outside of a loop.");
  502. }
  503. cmd = this.parseBreak();
  504. } else if (token.type === this.lexerClass.RK_SWITCH) {
  505. cmd = this.parseSwitchCase();
  506. } else if (token.type === this.lexerClass.RK_DO) {
  507. cmd = this.parseDoWhile();
  508. } else if (token.type === this.lexerClass.RK_IF) {
  509. cmd = this.parseIfThenElse();
  510. } else if (this.checkEOS(true)){
  511. this.pos++;
  512. cmd = -1;
  513. }
  514. return cmd;
  515. }
  516. parseSwitchCase () {
  517. this.pushScope(IVProgParser.BREAKABLE);
  518. this.pos++;
  519. this.checkOpenParenthesis();
  520. this.pos++;
  521. this.consumeNewLines();
  522. const exp = this.parseExpressionOR();
  523. this.consumeNewLines();
  524. this.checkCloseParenthesis();
  525. this.pos++;
  526. this.consumeNewLines();
  527. this.checkOpenCurly();
  528. this.pos++;
  529. this.consumeNewLines();
  530. const switchCases = this.parseCases();
  531. this.consumeNewLines();
  532. this.checkCloseCurly();
  533. this.pos++;
  534. this.consumeNewLines();
  535. this.popScope();
  536. return null;
  537. }
  538. parseDoWhile () {
  539. this.pos++;
  540. this.consumeNewLines();
  541. this.pushScope(IVProgParser.BREAKABLE);
  542. const commandsBlock = this.parseCommandBlock();
  543. this.consumeNewLines(); //Maybe not...
  544. const whileToken = this.getToken();
  545. if (whileToken.type !== this.lexerClass.RK_WHILE) {
  546. throw SyntaxError.createError(this.lexer.literalNames[this.lexerClass.RK_WHILE], whileToken);
  547. }
  548. this.pos++;
  549. this.checkOpenParenthesis();
  550. this.pos++;
  551. this.consumeNewLines();
  552. const condition = this.parseExpressionOR();
  553. this.consumeNewLines();
  554. this.checkCloseParenthesis();
  555. this.pos++;
  556. this.checkEOS();
  557. this.popScope();
  558. return new Commands.DoWhile(condition, commandsBlock);
  559. }
  560. parseIfThenElse () {
  561. if(this.insideScope(IVProgParser.BREAKABLE)) {
  562. this.pushScope(IVProgParser.BREAKABLE);
  563. } else {
  564. this.pushScope(IVProgParser.COMMAND);
  565. }
  566. this.pos++;
  567. this.checkOpenParenthesis();
  568. this.pos++;
  569. this.consumeNewLines();
  570. const logicalExpression = this.parseExpressionOR();
  571. this.consumeNewLines();
  572. this.checkCloseParenthesis();
  573. this.pos++;
  574. this.consumeNewLines();
  575. const cmdBlocks = this.parseCommandBlock();
  576. const maybeElse = this.getToken();
  577. if(maybeElse.type === this.lexerClass.RK_ELSE) {
  578. this.pos++;
  579. this.consumeNewLines();
  580. let elseBlock = null;
  581. if(this.checkOpenCurly(true)) {
  582. elseBlock = this.parseCommandBlock();
  583. } else {
  584. elseBlock = this.parseIfThenElse();
  585. }
  586. return new Commands.IfThenElse(logicalExpression, cmdBlocks, elseBlock);
  587. }
  588. this.popScope();
  589. return new Commands.IfThenElse(logicalExpression, cmdBlocks, null);
  590. }
  591. parseFor () {
  592. this.pushScope(IVProgParser.BREAKABLE);
  593. this.pos++;
  594. this.checkOpenParenthesis();
  595. this.pos++;
  596. this.consumeNewLines();
  597. const attribution = this.parseForAssign();
  598. this.consumeNewLines();
  599. const condition = this.parseExpressionOR();
  600. this.checkEOS();
  601. this.pos++;
  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. const 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. this.checkEOS();
  673. this.pos++;
  674. return new Commands.Assign(id, exp);
  675. }
  676. parseCases () {
  677. const token = this.getToken();
  678. if(token.type !== this.lexerClass.RK_CASE) {
  679. throw SyntaxError.createError(this.lexer.literalNames[this.lexerClass.RK_CASE], token);
  680. }
  681. }
  682. /*
  683. * Parses an Expression following the structure:
  684. *
  685. * EOR => EAnd ( 'or' EOR)? #expression and
  686. *
  687. * EOR => ENot ('and' EOR)? #expression or
  688. *
  689. * ENot => 'not'? ER #expression not
  690. *
  691. * ER => E ((>=, <=, ==, >, <) E)? #expression relational
  692. *
  693. * E => factor ((+, -) E)? #expression
  694. *
  695. * factor=> term ((*, /, %) factor)?
  696. *
  697. * term => literal || arrayAccess || FuncCall || ID || '('EAnd')'
  698. **/
  699. parseExpressionOR () {
  700. const exp1 = this.parseExpressionAND();
  701. const maybeAnd = this.getToken();
  702. if (maybeAnd.type === this.lexerClass.OR_OPERATOR) {
  703. this.pos++;
  704. const or = 'or';
  705. this.consumeNewLines();
  706. const exp2 = this.parseExpressionOR();
  707. return new Expressions.InfixApp(or, exp1, exp2);
  708. }
  709. return exp1;
  710. }
  711. parseExpressionAND () {
  712. const exp1 = this.parseExpressionNot();
  713. const andToken = this.getToken();
  714. if (andToken.type === this.lexerClass.AND_OPERATOR) {
  715. this.pos++;
  716. const and = 'and';
  717. this.consumeNewLines();
  718. const exp2 = this.parseExpressionAND();
  719. return new Expressions.InfixApp(and, exp1, exp2);
  720. }
  721. return exp1;
  722. }
  723. parseExpressionNot () {
  724. const maybeNotToken = this.getToken();
  725. if (maybeNotToken.type === this.lexerClass.NOT_OPERATOR) {
  726. this.pos++;
  727. const not = 'not';
  728. const exp1 = this.parseExpressionRel();
  729. return new Expressions.UnaryApp(not, exp1);
  730. } else {
  731. return this.parseExpressionRel();
  732. }
  733. }
  734. parseExpressionRel () {
  735. const exp1 = this.parseExpression();
  736. const relToken = this.getToken();
  737. if(relToken.type === this.lexerClass.RELATIONAL_OPERATOR) {
  738. this.pos++;
  739. const rel = relToken.text; // TODO: source code line/column information
  740. const exp2 = this.parseExpression();
  741. return new Expressions.InfixApp(rel, exp1, exp2);
  742. }
  743. return exp1;
  744. }
  745. parseExpression () {
  746. const factor = this.parseFactor();
  747. const sumOpToken = this.getToken();
  748. if(sumOpToken.type === this.lexerClass.SUM_OP) {
  749. this.pos++;
  750. const op = sumOpToken.text; // TODO: source code line/column information
  751. const exp = this.parseExpression();
  752. return new Expressions.InfixApp(op, factor, exp);
  753. }
  754. return factor;
  755. }
  756. parseFactor () {
  757. const term = this.parseTerm();
  758. const multOpToken = this.getToken();
  759. if(multOpToken.type === this.lexerClass.MULTI_OP) {
  760. this.pos++;
  761. const op = multOpToken.text; // TODO: source code line/column information
  762. const factor = this.parseFactor();
  763. return new Expressions.InfixApp(op, term, factor);
  764. }
  765. return term;
  766. }
  767. parseTerm () {
  768. const token = this.getToken();
  769. switch(token.type) {
  770. case this.lexerClass.INTEGER:
  771. this.pos++;
  772. return this.getIntLiteral(token);
  773. case this.lexerClass.REAL:
  774. this.pos++;
  775. return this.getRealLiteral(token);
  776. case this.lexerClass.STRING:
  777. this.pos++;
  778. return this.getStringLiteral(token);
  779. case this.lexerClass.RK_TRUE:
  780. case this.lexerClass.RK_FALSE:
  781. this.pos++;
  782. return this.getBoolLiteral(token);
  783. case this.lexerClass.OPEN_CURLY:
  784. return this.parseArrayLiteral();
  785. case this.lexerClass.ID:
  786. return this.parseIDTerm();
  787. case this.lexerClass.OPEN_PARENTHESIS:
  788. return this.parseParenthesisExp();
  789. default:
  790. throw SyntaxError.createError('Terminal', token);
  791. }
  792. }
  793. parseIDTerm () {
  794. const id = this.parseID();
  795. const last = this.pos;
  796. if(this.checkOpenBrace(true)) {
  797. this.pos++;
  798. const firstIndex = this.parseExpression();
  799. let secondIndex = null;
  800. this.consumeNewLines();
  801. this.checkCloseBrace();
  802. this.pos++;
  803. if(this.checkOpenBrace(true)){
  804. this.pos++;
  805. secondIndex = this.parseExpression();
  806. this.consumeNewLines();
  807. this.checkCloseBrace();
  808. this.pos++;
  809. } else {
  810. this.pos--;
  811. }
  812. return new Expressions.ArrayAccess(id, firstIndex, secondIndex);
  813. } else if (this.checkOpenParenthesis(true)) {
  814. this.pos++;
  815. this.consumeNewLines();
  816. let actualParameters = [];
  817. if(!this.checkCloseParenthesis(true)) {
  818. actualParameters = this.parseActualParameters();
  819. this.consumeNewLines();
  820. this.checkCloseParenthesis();
  821. this.pos++;
  822. } else {
  823. this.pos++;
  824. }
  825. return new Expressions.FunctionCall(id, actualParameters);
  826. } else {
  827. this.pos = last;
  828. return id;
  829. }
  830. }
  831. parseParenthesisExp () {
  832. this.checkOpenParenthesis();
  833. this.pos++;
  834. this.consumeNewLines();
  835. const exp = this.parseExpressionOR();
  836. this.consumeNewLines();
  837. this.checkCloseParenthesis();
  838. this.pos++;
  839. return exp;
  840. }
  841. parseActualParameters () {
  842. this.checkOpenParenthesis();
  843. this.pos++;
  844. this.consumeNewLines();
  845. list = this.parseExpressionList();
  846. this.consumeNewLines();
  847. this.checkCloseParenthesis();
  848. this.pos++;
  849. return list;
  850. }
  851. parseExpressionList () {
  852. const list = [];
  853. while(true) {
  854. const exp = this.parseExpressionOR();
  855. list.push(exp);
  856. const maybeToken = this.getToken();
  857. if (maybeToken.type !== this.lexerClass.COMMA) {
  858. break;
  859. } else {
  860. this.pos++;
  861. this.consumeNewLines();
  862. }
  863. }
  864. return list;
  865. }
  866. getTypesAsString () {
  867. const types = this.insideScope(IVProgParser.FUNCTION) ? this.functionTypes : this.variableTypes;
  868. return types.map( x => this.lexer.literalNames[x])
  869. .reduce((o, n) => {
  870. if (o.length <= 0)
  871. return n;
  872. else
  873. return o + ", " + n;
  874. }, '');
  875. }
  876. }