ivprogParser.js 30 KB

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