ivprogParser.js 32 KB

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