ivprogParser.js 30 KB

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