1
0

ivprogParser.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  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 { 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. let val = null;
  295. if(text.match('^0b|^0B')) {
  296. val = parseInt(text.substring(2), 2);
  297. } else if (text.match('^0x|^0X')) {
  298. val = parseInt(text.substring(2), 16);
  299. } else {
  300. val = parseInt(text);
  301. }
  302. return new Expressions.IntLiteral(val);
  303. }
  304. getRealLiteral (token) {
  305. return new Expressions.RealLiteral(parseFloat(token.text));
  306. }
  307. getStringLiteral (token) {
  308. const text = token.text;
  309. let value = text.replace("\\b", "\b");
  310. value = value.replace("\\t", "\t");
  311. value = value.replace("\\n", "\n");
  312. value = value.replace("\\r", "\r");
  313. value = value.replace("\\\"", "\"");
  314. value = value.replace("\\\'", "\'");
  315. value = value.replace("\\\\", "\\");
  316. return new Expressions.StringLiteral(value);
  317. }
  318. getBoolLiteral (token) {
  319. const val = token.type === this.lexerClass.RK_TRUE ? true : false;
  320. return new Expressions.BoolLiteral(val);
  321. }
  322. parseArrayLiteral () {
  323. this.checkOpenCurly();
  324. const beginArray = this.getToken();
  325. if (this.parsingArrayDimension >= 2) {
  326. // TODO: better error message
  327. throw new Error(`Array dimensions exceed maximum size of 2 at line ${beginArray.line}`);
  328. }
  329. this.pos++;
  330. this.parsingArrayDimension++;
  331. this.consumeNewLines();
  332. const data = this.parseExpressionList();
  333. this.consumeNewLines();
  334. this.checkCloseCurly()
  335. this.pos++;
  336. this.parsingArrayDimension--;
  337. if (this.parsingArrayDimension === 0) {
  338. if (!data.isValid) {
  339. // TODO: better error message
  340. console.log('invalid array');
  341. throw new Error(`Invalid array at line ${beginArray.line}`);
  342. }
  343. }
  344. return new Expressions.ArrayLiteral(data);
  345. }
  346. /*
  347. * Returns an object {type: 'variable', value: value}.
  348. * @returns object with fields type and value
  349. **/
  350. parseVariable (token) {
  351. return new Expressions.VariableLiteral(token.text);
  352. }
  353. /*
  354. * Returns an object representing a function. It has
  355. * four attributes: returnType, id, formalParams and block.
  356. * The block object has two attributes: declarations and commands
  357. **/
  358. parseFunction () {
  359. this.pushScope(IVProgParser.FUNCTION);
  360. let formalParams = [];
  361. const token = this.getToken();
  362. if(token.type !== this.lexerClass.RK_FUNCTION) {
  363. //throw SyntaxError.createError(this.lexer.literalNames[this.lexerClass.PR_FUNCAO], token);
  364. return null;
  365. }
  366. this.pos++;
  367. const returnType = this.parseType();
  368. const functionID = this.parseID();
  369. this.checkOpenParenthesis();
  370. this.pos++;
  371. this.consumeNewLines();
  372. if (!this.checkCloseParenthesis(true)) {
  373. formalParams = this.parseFormalParameters(); // formal parameters
  374. this.consumeNewLines();
  375. this.checkCloseParenthesis();
  376. this.pos++;
  377. } else {
  378. this.pos++;
  379. }
  380. this.consumeNewLines();
  381. const commandsBlock = this.parseCommandBlock();
  382. const func = new Commands.Function(functionID, returnType, formalParams, commandsBlock);
  383. if (functionID === null && !func.isMain) {
  384. // TODO: better error message
  385. throw new Error(`Function ${this.lexerClass.MAIN_FUNCTION_NAME} must return void (line ${token.line})`);
  386. }
  387. this.popScope();
  388. return func;
  389. }
  390. /*
  391. * Parse the formal parameters of a function.
  392. * @returns a list of objects with the following attributes: type, id and dimensions.
  393. **/
  394. parseFormalParameters () {
  395. const list = [];
  396. while(true) {
  397. let dimensions = 0;
  398. const typeString = this.parseType();
  399. const idString = this.parseID();
  400. if (this.checkOpenBrace(true)) {
  401. this.pos++;
  402. dimensions++;
  403. this.checkCloseBrace();
  404. this.pos++;
  405. if(this.checkOpenBrace(true)) {
  406. this.pos++;
  407. dimensions++;
  408. this.checkCloseBrace();
  409. this.pos++;
  410. }
  411. }
  412. list.push({type: typeString, id: idString, dimensions: dimensions});
  413. const commaToken = this.getToken();
  414. if (commaToken.type !== this.lexerClass.COMMA)
  415. break;
  416. this.pos++;
  417. this.consumeNewLines();
  418. }
  419. return list;
  420. }
  421. parseID () {
  422. const token = this.getToken();
  423. if(token.type !== this.lexerClass.ID) {
  424. throw SyntaxError.createError('ID', token);
  425. }
  426. this.pos++;
  427. if (this.insideScope(IVProgParser.FUNCTION)) {
  428. if (token.text === this.lexerClass.MAIN_FUNCTION_NAME){
  429. return null;
  430. }
  431. }
  432. return token.text;
  433. }
  434. parseType () {
  435. const token = this.getToken();
  436. if(token.type === this.lexerClass.ID && this.insideScope(IVProgParser.FUNCTION)) {
  437. return Types.VOID;
  438. } else if (token.type === this.lexerClass.RK_VOID && this.insideScope(IVProgParser.FUNCTION)) {
  439. this.pos++;
  440. return Types.VOID;
  441. } else if (this.isVariableType(token)) {
  442. this.pos++;
  443. switch(token.type) {
  444. case this.lexerClass.RK_INTEGER:
  445. return Types.INTEGER;
  446. case this.lexerClass.RK_LOGIC:
  447. return Types.BOOLEAN;
  448. case this.lexerClass.RK_REAL:
  449. return Types.REAL;
  450. case this.lexerClass.RK_STRING:
  451. return Types.STRING;
  452. default:
  453. break;
  454. }
  455. }
  456. throw SyntaxError.createError(this.getTypesAsString(), token);
  457. }
  458. parseCommandBlock (optionalCurly = false) {
  459. let variablesDecl = [];
  460. const commands = [];
  461. let hasOpen = false;
  462. if (this.checkOpenCurly(optionalCurly)) {
  463. this.pos++;
  464. hasOpen = true;
  465. }
  466. this.consumeNewLines();
  467. while(true) {
  468. const cmd = this.parseCommand();
  469. if (cmd === null)
  470. break;
  471. if(cmd !== -1) {
  472. if (cmd instanceof Array) {
  473. variablesDecl = variablesDecl.concat(cmd);
  474. } else {
  475. commands.push(cmd);
  476. }
  477. }
  478. }
  479. this.consumeNewLines();
  480. if (hasOpen) {
  481. this.checkCloseCurly()
  482. this.pos++;
  483. this.consumeNewLines();
  484. }
  485. return new Commands.CommandBlock(variablesDecl, commands);
  486. }
  487. parseCommand () {
  488. const token = this.getToken();
  489. if (this.isVariableType(token)) {
  490. if(!this.insideScope(IVProgParser.FUNCTION)) {
  491. // TODO better error message
  492. throw new Error(`Cannot declare variable here (line ${token.line})`);
  493. }
  494. this.pushScope(IVProgParser.BASE);
  495. const varType = this.parseType();
  496. this.popScope();
  497. const cmd = this.parseDeclaration(varType);
  498. this.checkEOS();
  499. this.pos++;
  500. return cmd;
  501. } else if (token.type === this.lexerClass.ID) {
  502. return this.parseIDCommand();
  503. } else if (token.type === this.lexerClass.RK_RETURN) {
  504. return this.parseReturn();
  505. } else if (token.type === this.lexerClass.RK_WHILE) {
  506. return this.parseWhile();
  507. } else if (token.type === this.lexerClass.RK_FOR) {
  508. return this.parseFor();
  509. } else if (token.type === this.lexerClass.RK_BREAK ) {
  510. if(!this.insideScope(IVProgParser.BREAKABLE)) {
  511. // TODO better error message
  512. throw new Error("Break cannot be used outside of a loop.");
  513. }
  514. return this.parseBreak();
  515. } else if (token.type === this.lexerClass.RK_SWITCH) {
  516. return this.parseSwitchCase();
  517. } else if (token.type === this.lexerClass.RK_DO) {
  518. return this.parseDoWhile();
  519. } else if (token.type === this.lexerClass.RK_IF) {
  520. return this.parseIfThenElse();
  521. } else if (this.checkEOS(true)){
  522. this.pos++;
  523. return -1;
  524. } else {
  525. return null;
  526. }
  527. }
  528. parseSwitchCase () {
  529. this.pushScope(IVProgParser.BREAKABLE);
  530. this.pos++;
  531. this.checkOpenParenthesis();
  532. this.pos++;
  533. this.consumeNewLines();
  534. const exp = this.parseExpressionOR();
  535. this.consumeNewLines();
  536. this.checkCloseParenthesis();
  537. this.pos++;
  538. this.consumeNewLines();
  539. this.checkOpenCurly();
  540. this.pos++;
  541. this.consumeNewLines();
  542. const casesList = this.parseCases();
  543. this.consumeNewLines();
  544. this.checkCloseCurly();
  545. this.pos++;
  546. this.consumeNewLines();
  547. this.popScope();
  548. return new Commands.Switch(exp, casesList);
  549. }
  550. parseDoWhile () {
  551. this.pos++;
  552. this.consumeNewLines();
  553. this.pushScope(IVProgParser.BREAKABLE);
  554. const commandsBlock = this.parseCommandBlock();
  555. this.consumeNewLines(); //Maybe not...
  556. const whileToken = this.getToken();
  557. if (whileToken.type !== this.lexerClass.RK_WHILE) {
  558. throw SyntaxError.createError(this.lexer.literalNames[this.lexerClass.RK_WHILE], whileToken);
  559. }
  560. this.pos++;
  561. this.checkOpenParenthesis();
  562. this.pos++;
  563. this.consumeNewLines();
  564. const condition = this.parseExpressionOR();
  565. this.consumeNewLines();
  566. this.checkCloseParenthesis();
  567. this.pos++;
  568. this.checkEOS();
  569. this.popScope();
  570. return new Commands.DoWhile(condition, commandsBlock);
  571. }
  572. parseIfThenElse () {
  573. if(this.insideScope(IVProgParser.BREAKABLE)) {
  574. this.pushScope(IVProgParser.BREAKABLE);
  575. } else {
  576. this.pushScope(IVProgParser.COMMAND);
  577. }
  578. this.pos++;
  579. this.checkOpenParenthesis();
  580. this.pos++;
  581. this.consumeNewLines();
  582. const logicalExpression = this.parseExpressionOR();
  583. this.consumeNewLines();
  584. this.checkCloseParenthesis();
  585. this.pos++;
  586. this.consumeNewLines();
  587. const cmdBlocks = this.parseCommandBlock();
  588. const maybeElse = this.getToken();
  589. if(maybeElse.type === this.lexerClass.RK_ELSE) {
  590. this.pos++;
  591. this.consumeNewLines();
  592. const maybeIf = this.getToken();
  593. let elseBlock = null;
  594. if(this.checkOpenCurly(true)) {
  595. elseBlock = this.parseCommandBlock();
  596. } else if(maybeIf.type === this.lexerClass.RK_IF) {
  597. elseBlock = this.parseIfThenElse();
  598. } else {
  599. // TODO better error message
  600. throw SyntaxError.createError(`${this.lexer.literalNames[this.lexerClass.RK_IF]} or {`, maybeIf);
  601. }
  602. return new Commands.IfThenElse(logicalExpression, cmdBlocks, elseBlock);
  603. }
  604. this.popScope();
  605. return new Commands.IfThenElse(logicalExpression, cmdBlocks, null);
  606. }
  607. parseFor () {
  608. this.pushScope(IVProgParser.BREAKABLE);
  609. this.pos++;
  610. this.checkOpenParenthesis();
  611. this.pos++;
  612. this.consumeNewLines();
  613. const attribution = this.parseForAssign();
  614. this.consumeNewLines();
  615. const condition = this.parseExpressionOR();
  616. this.consumeForSemiColon();
  617. const increment = this.parseForAssign(true);
  618. this.checkCloseParenthesis()
  619. this.pos++;
  620. this.consumeNewLines();
  621. const commandsBlock = this.parseCommandBlock();
  622. this.popScope();
  623. return new Commands.For(attribution, condition, increment, commandsBlock);
  624. }
  625. parseWhile () {
  626. this.pushScope(IVProgParser.BREAKABLE);
  627. this.pos++;
  628. this.checkOpenParenthesis();
  629. this.pos++;
  630. this.consumeNewLines();
  631. const logicalExpression = this.parseExpressionOR();
  632. this.consumeNewLines();
  633. this.checkCloseParenthesis();
  634. this.pos++;
  635. this.consumeNewLines();
  636. const cmdBlocks = this.parseCommandBlock();
  637. this.popScope();
  638. return new Commands.While(logicalExpression, cmdBlocks);
  639. }
  640. parseBreak () {
  641. this.pos++;
  642. this.checkEOS();
  643. this.pos++;
  644. return (new Commands.Break());
  645. }
  646. parseReturn () {
  647. this.pos++;
  648. let exp = null;
  649. if(!this.checkEOS(true)) {
  650. exp = this.parseExpressionOR();
  651. this.checkEOS();
  652. }
  653. this.pos++;
  654. return new Commands.Return(exp);
  655. }
  656. parseIDCommand () {
  657. const id = this.parseID();
  658. const equalOrParenthesis = this.getToken();
  659. if (equalOrParenthesis.type === this.lexerClass.EQUAL) {
  660. this.pos++
  661. const exp = this.parseExpressionOR();
  662. this.checkEOS();
  663. this.pos++;
  664. return (new Commands.Assign(id, exp));
  665. } else if (equalOrParenthesis.type === this.lexerClass.OPEN_PARENTHESIS) {
  666. const actualParameters = this.parseActualParameters();
  667. this.checkEOS();
  668. this.pos++;
  669. return (new Expressions.FunctionCall(id, actualParameters));
  670. } else {
  671. throw SyntaxError.createError("= or (", equalOrParenthesis);
  672. }
  673. }
  674. parseForAssign (isLast = false) {
  675. if(!isLast)
  676. this.consumeNewLines();
  677. if(this.checkEOS(true)) {
  678. return null;
  679. }
  680. const id = this.parseID();
  681. const equal = this.getToken();
  682. if (equal.type !== this.lexerClass.EQUAL) {
  683. throw SyntaxError.createError('=', equal);
  684. }
  685. this.pos++
  686. const exp = this.parseExpressionOR();
  687. if(!isLast) {
  688. this.consumeForSemiColon();
  689. }
  690. return new Commands.Assign(id, exp);
  691. }
  692. parseCases () {
  693. const token = this.getToken();
  694. if(token.type !== this.lexerClass.RK_CASE) {
  695. throw SyntaxError.createError(this.lexer.literalNames[this.lexerClass.RK_CASE], token);
  696. }
  697. this.pos++;
  698. const nextToken = this.getToken();
  699. if(nextToken.type === this.lexerClass.RK_DEFAULT) {
  700. this.pos++;
  701. const colonToken = this.getToken();
  702. if (colonToken.type !== this.lexerClass.COLON) {
  703. throw SyntaxError.createError(':', colonToken);
  704. }
  705. this.pos++;
  706. this.consumeNewLines();
  707. const block = this.parseCommandBlock(true);
  708. const defaultCase = new Commands.Case(null);
  709. defaultCase.setCommands(block.commands);
  710. return [defaultCase];
  711. } else {
  712. const exp = this.parseExpressionOR();
  713. const colonToken = this.getToken();
  714. if (colonToken.type !== this.lexerClass.COLON) {
  715. throw SyntaxError.createError(':', colonToken);
  716. }
  717. this.pos++;
  718. this.consumeNewLines();
  719. const block = this.parseCommandBlock(true);
  720. const aCase = new Commands.Case(exp);
  721. aCase.setCommands(block.commands);
  722. const caseToken = this.getToken();
  723. if(caseToken.type === this.lexerClass.RK_CASE) {
  724. return [aCase].concat(this.parseCases());
  725. } else {
  726. return [aCase];
  727. }
  728. }
  729. }
  730. /*
  731. * Parses an Expression following the structure:
  732. *
  733. * EOR => EAnd ( 'or' EOR)? #expression and
  734. *
  735. * EOR => ENot ('and' EOR)? #expression or
  736. *
  737. * ENot => 'not'? ER #expression not
  738. *
  739. * ER => E ((>=, <=, ==, >, <) E)? #expression relational
  740. *
  741. * E => factor ((+, -) E)? #expression
  742. *
  743. * factor=> term ((*, /, %) factor)?
  744. *
  745. * term => literal || arrayAccess || FuncCall || ID || '('EAnd')'
  746. **/
  747. parseExpressionOR () {
  748. const exp1 = this.parseExpressionAND();
  749. const maybeAnd = this.getToken();
  750. if (maybeAnd.type === this.lexerClass.OR_OPERATOR) {
  751. this.pos++;
  752. const or = convertFromString('or');
  753. this.consumeNewLines();
  754. const exp2 = this.parseExpressionOR();
  755. return new Expressions.InfixApp(or, exp1, exp2);
  756. }
  757. return exp1;
  758. }
  759. parseExpressionAND () {
  760. const exp1 = this.parseExpressionNot();
  761. const andToken = this.getToken();
  762. if (andToken.type === this.lexerClass.AND_OPERATOR) {
  763. this.pos++;
  764. const and = convertFromString('and');
  765. this.consumeNewLines();
  766. const exp2 = this.parseExpressionAND();
  767. return new Expressions.InfixApp(and, exp1, exp2);
  768. }
  769. return exp1;
  770. }
  771. parseExpressionNot () {
  772. const maybeNotToken = this.getToken();
  773. if (maybeNotToken.type === this.lexerClass.NOT_OPERATOR) {
  774. this.pos++;
  775. const not = convertFromString('not');
  776. const exp1 = this.parseExpressionRel();
  777. return new Expressions.UnaryApp(not, exp1);
  778. } else {
  779. return this.parseExpressionRel();
  780. }
  781. }
  782. parseExpressionRel () {
  783. const exp1 = this.parseExpression();
  784. const relToken = this.getToken();
  785. if(relToken.type === this.lexerClass.RELATIONAL_OPERATOR) {
  786. this.pos++;
  787. const rel = convertFromString(relToken.text); // TODO: source code line/column information
  788. const exp2 = this.parseExpression();
  789. return new Expressions.InfixApp(rel, exp1, exp2);
  790. }
  791. return exp1;
  792. }
  793. parseExpression () {
  794. const factor = this.parseFactor();
  795. const sumOpToken = this.getToken();
  796. if(sumOpToken.type === this.lexerClass.SUM_OP) {
  797. this.pos++;
  798. const op = convertFromString(sumOpToken.text); // TODO: source code line/column information
  799. const exp = this.parseExpression();
  800. return new Expressions.InfixApp(op, factor, exp);
  801. }
  802. return factor;
  803. }
  804. parseFactor () {
  805. const term = this.parseTerm();
  806. const multOpToken = this.getToken();
  807. if(multOpToken.type === this.lexerClass.MULTI_OP) {
  808. this.pos++;
  809. const op = convertFromString(multOpToken.text); // TODO: source code line/column information
  810. const factor = this.parseFactor();
  811. return new Expressions.InfixApp(op, term, factor);
  812. }
  813. return term;
  814. }
  815. parseTerm () {
  816. const token = this.getToken();
  817. switch(token.type) {
  818. case this.lexerClass.SUM_OP:
  819. this.pos++;
  820. return new Expressions.UnaryApp(convertFromString(token.text), this.parseTerm());
  821. case this.lexerClass.INTEGER:
  822. this.pos++;
  823. return this.getIntLiteral(token);
  824. case this.lexerClass.REAL:
  825. this.pos++;
  826. return this.getRealLiteral(token);
  827. case this.lexerClass.STRING:
  828. this.pos++;
  829. return this.getStringLiteral(token);
  830. case this.lexerClass.RK_TRUE:
  831. case this.lexerClass.RK_FALSE:
  832. this.pos++;
  833. return this.getBoolLiteral(token);
  834. case this.lexerClass.OPEN_CURLY:
  835. return this.parseArrayLiteral();
  836. case this.lexerClass.ID:
  837. return this.parseIDTerm();
  838. case this.lexerClass.OPEN_PARENTHESIS:
  839. return this.parseParenthesisExp();
  840. default:
  841. throw SyntaxError.createError('Terminal', token);
  842. }
  843. }
  844. parseIDTerm () {
  845. const id = this.parseID();
  846. const last = this.pos;
  847. if(this.checkOpenBrace(true)) {
  848. this.pos++;
  849. const firstIndex = this.parseExpression();
  850. let secondIndex = null;
  851. this.consumeNewLines();
  852. this.checkCloseBrace();
  853. this.pos++;
  854. if(this.checkOpenBrace(true)){
  855. this.pos++;
  856. secondIndex = this.parseExpression();
  857. this.consumeNewLines();
  858. this.checkCloseBrace();
  859. this.pos++;
  860. } else {
  861. this.pos--;
  862. }
  863. return new Expressions.ArrayAccess(id, firstIndex, secondIndex);
  864. } else if (this.checkOpenParenthesis(true)) {
  865. this.pos++;
  866. this.consumeNewLines();
  867. let actualParameters = [];
  868. if(!this.checkCloseParenthesis(true)) {
  869. actualParameters = this.parseActualParameters();
  870. this.consumeNewLines();
  871. this.checkCloseParenthesis();
  872. this.pos++;
  873. } else {
  874. this.pos++;
  875. }
  876. return new Expressions.FunctionCall(id, actualParameters);
  877. } else {
  878. this.pos = last;
  879. return id;
  880. }
  881. }
  882. parseParenthesisExp () {
  883. this.checkOpenParenthesis();
  884. this.pos++;
  885. this.consumeNewLines();
  886. const exp = this.parseExpressionOR();
  887. this.consumeNewLines();
  888. this.checkCloseParenthesis();
  889. this.pos++;
  890. return exp;
  891. }
  892. parseActualParameters () {
  893. this.checkOpenParenthesis();
  894. this.pos++;
  895. if(this.checkCloseParenthesis(true)) {
  896. this.pos++;
  897. return [];
  898. }
  899. this.consumeNewLines();
  900. const list = this.parseExpressionList();
  901. this.consumeNewLines();
  902. this.checkCloseParenthesis();
  903. this.pos++;
  904. return list;
  905. }
  906. parseExpressionList () {
  907. const list = [];
  908. while(true) {
  909. const exp = this.parseExpressionOR();
  910. list.push(exp);
  911. const maybeToken = this.getToken();
  912. if (maybeToken.type !== this.lexerClass.COMMA) {
  913. break;
  914. } else {
  915. this.pos++;
  916. this.consumeNewLines();
  917. }
  918. }
  919. return list;
  920. }
  921. getTypesAsString () {
  922. const types = this.insideScope(IVProgParser.FUNCTION) ? this.functionTypes : this.variableTypes;
  923. return types.map( x => this.lexer.literalNames[x])
  924. .reduce((o, n) => {
  925. if (o.length <= 0)
  926. return n;
  927. else
  928. return o + ", " + n;
  929. }, '');
  930. }
  931. }