ivprogParser.js 33 KB

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