ivprogParser.js 28 KB

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