ivprogParser.js 31 KB

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