ivprogParser.js 28 KB

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