ivprogParser.js 31 KB

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