ivprogParser.js 33 KB

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