ivprogParser.js 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  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. if(this.checkOpenBrace(true)) {
  692. this.pos++;
  693. let lineExpression = null;
  694. let columnExpression = null;
  695. this.consumeNewLines();
  696. lineExpression = this.parseExpression()
  697. this.consumeNewLines();
  698. this.checkCloseBrace();
  699. this.pos++;
  700. if (this.checkOpenBrace(true)) {
  701. this.pos++
  702. this.consumeNewLines();
  703. columnExpression = this.parseExpression();
  704. this.consumeNewLines();
  705. this.checkCloseBrace();
  706. this.pos++;
  707. }
  708. const equalToken = this.getToken();
  709. if (equalToken.type !== this.lexerClass.EQUAL) {
  710. throw SyntaxErrorFactory.token_missing_one('=', equalToken);
  711. }
  712. this.pos++;
  713. const exp = this.parseExpressionOR();
  714. this.checkEOS();
  715. this.pos++;
  716. const cmd = new Commands.ArrayIndexAssign(id, lineExpression, columnExpression, exp);
  717. cmd.sourceInfo = SourceInfo.createSourceInfo(equalToken);
  718. return cmd;
  719. }
  720. const equalOrParenthesis = this.getToken();
  721. if (isID && equalOrParenthesis.type === this.lexerClass.EQUAL) {
  722. this.pos++
  723. const exp = this.parseExpressionOR();
  724. this.checkEOS();
  725. this.pos++;
  726. const cmd = new Commands.Assign(id, exp);
  727. cmd.sourceInfo = SourceInfo.createSourceInfo(equalOrParenthesis);
  728. return cmd;
  729. } else if (equalOrParenthesis.type === this.lexerClass.OPEN_PARENTHESIS) {
  730. const funcCall = this.parseFunctionCallCommand(id);
  731. this.checkEOS();
  732. this.pos++;
  733. return funcCall;
  734. } else if (isID) {
  735. throw SyntaxErrorFactory.token_missing_list(['=','('], equalOrParenthesis);
  736. } else {
  737. throw SyntaxErrorFactory.invalid_id_format(refToken);
  738. }
  739. }
  740. parseForAssign (isLast = false) {
  741. if(!isLast)
  742. this.consumeNewLines();
  743. if(this.checkEOS(true)) {
  744. return null;
  745. }
  746. const id = this.parseID();
  747. const equal = this.getToken();
  748. if (equal.type !== this.lexerClass.EQUAL) {
  749. throw SyntaxErrorFactory.token_missing_one('=', equal);
  750. }
  751. this.pos++
  752. const exp = this.parseExpressionOR();
  753. if(!isLast) {
  754. this.consumeForSemiColon();
  755. }
  756. const sourceInfo = SourceInfo.createSourceInfo(equal);
  757. const cmd = new Commands.Assign(id, exp);
  758. cmd.sourceInfo = sourceInfo;
  759. return cmd;
  760. }
  761. parseCases () {
  762. const token = this.getToken();
  763. if(token.type !== this.lexerClass.RK_CASE) {
  764. throw SyntaxErrorFactory.token_missing_one(this.lexer.literalNames[this.lexerClass.RK_CASE], token);
  765. }
  766. this.pos++;
  767. const nextToken = this.getToken();
  768. if(nextToken.type === this.lexerClass.RK_DEFAULT) {
  769. this.pos++;
  770. const colonToken = this.getToken();
  771. if (colonToken.type !== this.lexerClass.COLON) {
  772. throw SyntaxErrorFactory.token_missing_one(':', colonToken);
  773. }
  774. this.pos++;
  775. this.consumeNewLines();
  776. const block = this.parseCommandBlock(true);
  777. const defaultCase = new Commands.Case(null);
  778. defaultCase.setCommands(block.commands);
  779. return [defaultCase];
  780. } else {
  781. const exp = this.parseExpressionOR();
  782. const colonToken = this.getToken();
  783. if (colonToken.type !== this.lexerClass.COLON) {
  784. throw SyntaxErrorFactory.token_missing_one(':', colonToken);
  785. }
  786. this.pos++;
  787. this.consumeNewLines();
  788. const block = this.parseCommandBlock(true);
  789. const aCase = new Commands.Case(exp);
  790. aCase.setCommands(block.commands);
  791. const caseToken = this.getToken();
  792. if(caseToken.type === this.lexerClass.RK_CASE) {
  793. return [aCase].concat(this.parseCases());
  794. } else {
  795. return [aCase];
  796. }
  797. }
  798. }
  799. /*
  800. * Parses an Expression following the structure:
  801. *
  802. * EOR => EAnd ( 'or' EOR)? #expression and
  803. *
  804. * EOR => ENot ('and' EOR)? #expression or
  805. *
  806. * ENot => 'not'? ER #expression not
  807. *
  808. * ER => E ((>=, <=, ==, >, <) E)? #expression relational
  809. *
  810. * E => factor ((+, -) E)? #expression
  811. *
  812. * factor=> term ((*, /, %) factor)?
  813. *
  814. * term => literal || arrayAccess || FuncCall || ID || '('EAnd')'
  815. **/
  816. parseExpressionOR () {
  817. let exp1 = this.parseExpressionAND();
  818. while (this.getToken().type === this.lexerClass.OR_OPERATOR) {
  819. const opToken = this.getToken();
  820. this.pos++;
  821. const or = convertFromString('or');
  822. this.consumeNewLines();
  823. const exp2 = this.parseExpressionAND();
  824. const finalExp = new Expressions.InfixApp(or, exp1, exp2);
  825. finalExp.sourceInfo = SourceInfo.createSourceInfo(opToken);
  826. exp1 = finalExp
  827. }
  828. return exp1;
  829. }
  830. parseExpressionAND () {
  831. let exp1 = this.parseExpressionNot();
  832. while (this.getToken().type === this.lexerClass.AND_OPERATOR) {
  833. const opToken = this.getToken();
  834. this.pos++;
  835. const and = convertFromString('and');
  836. this.consumeNewLines();
  837. const exp2 = this.parseExpressionNot();
  838. const finalExp = new Expressions.InfixApp(and, exp1, exp2);
  839. finalExp.sourceInfo = SourceInfo.createSourceInfo(opToken);
  840. exp1 = finalExp;
  841. }
  842. return exp1;
  843. }
  844. parseExpressionNot () {
  845. const maybeNotToken = this.getToken();
  846. if (maybeNotToken.type === this.lexerClass.NOT_OPERATOR) {
  847. const opToken = this.getToken();
  848. this.pos++;
  849. const not = convertFromString('not');
  850. const exp1 = this.parseExpressionRel();
  851. finalExp = new Expressions.UnaryApp(not, exp1);
  852. finalExp.sourceInfo = SourceInfo.createSourceInfo(opToken);
  853. return finalExp;
  854. } else {
  855. return this.parseExpressionRel();
  856. }
  857. }
  858. parseExpressionRel () {
  859. let exp1 = this.parseExpression();
  860. while (this.getToken().type === this.lexerClass.RELATIONAL_OPERATOR) {
  861. const relToken = this.getToken();
  862. this.pos++;
  863. const rel = convertFromString(relToken.text);
  864. const exp2 = this.parseExpression();
  865. const finalExp = new Expressions.InfixApp(rel, exp1, exp2);
  866. finalExp.sourceInfo = SourceInfo.createSourceInfo(relToken);
  867. exp1 = finalExp;
  868. }
  869. return exp1;
  870. }
  871. parseExpression () {
  872. let factor = this.parseFactor();
  873. while (this.getToken().type === this.lexerClass.SUM_OP) {
  874. const sumOpToken = this.getToken();
  875. this.pos++;
  876. const op = convertFromString(sumOpToken.text);
  877. const factor2 = this.parseFactor();
  878. const finalExp = new Expressions.InfixApp(op, factor, factor2);
  879. finalExp.sourceInfo = SourceInfo.createSourceInfo(sumOpToken);
  880. factor = finalExp;
  881. }
  882. return factor;
  883. }
  884. parseFactor () {
  885. let term = this.parseTerm();
  886. while (this.getToken().type === this.lexerClass.MULTI_OP) {
  887. const multOpToken = this.getToken();
  888. this.pos++;
  889. const op = convertFromString(multOpToken.text);
  890. const term2 =this.parseTerm();
  891. const finalExp = new Expressions.InfixApp(op, term, term2);
  892. finalExp.sourceInfo = SourceInfo.createSourceInfo(multOpToken);
  893. term = finalExp;
  894. }
  895. return term;
  896. }
  897. parseTerm () {
  898. const token = this.getToken();
  899. let sourceInfo = null;
  900. switch(token.type) {
  901. case this.lexerClass.SUM_OP:
  902. this.pos++;
  903. sourceInfo = SourceInfo.createSourceInfo(token);
  904. const exp = new Expressions.UnaryApp(convertFromString(token.text), this.parseTerm());
  905. exp.sourceInfo = sourceInfo;
  906. return exp;
  907. case this.lexerClass.INTEGER:
  908. this.pos++;
  909. return this.getIntLiteral(token);
  910. case this.lexerClass.REAL:
  911. this.pos++;
  912. return this.getRealLiteral(token);
  913. case this.lexerClass.STRING:
  914. this.pos++;
  915. return this.getStringLiteral(token);
  916. case this.lexerClass.RK_TRUE:
  917. case this.lexerClass.RK_FALSE:
  918. this.pos++;
  919. return this.getBoolLiteral(token);
  920. case this.lexerClass.OPEN_CURLY:
  921. return this.parseArrayLiteral();
  922. case this.lexerClass.ID:
  923. case this.lexerClass.LIB_ID:
  924. return this.parseIDTerm();
  925. case this.lexerClass.OPEN_PARENTHESIS:
  926. return this.parseParenthesisExp();
  927. default:
  928. throw SyntaxErrorFactory.invalid_terminal(token);
  929. }
  930. }
  931. parseIDTerm () {
  932. const tokenA = this.getToken();
  933. const id = this.parseMaybeLibID();
  934. const isID = tokenA.type === this.lexerClass.ID;
  935. if(isID && this.checkOpenBrace(true)) {
  936. let tokenB = null;
  937. this.pos++;
  938. const firstIndex = this.parseExpression();
  939. let secondIndex = null;
  940. this.consumeNewLines();
  941. this.checkCloseBrace();
  942. tokenB = this.getToken();
  943. this.pos++;
  944. if(this.checkOpenBrace(true)){
  945. this.pos++;
  946. secondIndex = this.parseExpression();
  947. this.consumeNewLines();
  948. this.checkCloseBrace();
  949. tokenB = this.getToken();
  950. this.pos++;
  951. }
  952. const sourceInfo = SourceInfo.createSourceInfoFromList(tokenA, tokenB);
  953. const exp = new Expressions.ArrayAccess(id, firstIndex, secondIndex);
  954. exp.sourceInfo = sourceInfo;
  955. return exp;
  956. } else if (this.checkOpenParenthesis(true)) {
  957. return this.parseFunctionCallExpression(id);
  958. } else if (isID) {
  959. const sourceInfo = SourceInfo.createSourceInfo(tokenA);
  960. const exp = new Expressions.VariableLiteral(id);
  961. exp.sourceInfo = sourceInfo;
  962. return exp;
  963. } else {
  964. throw SyntaxErrorFactory.invalid_id_format(tokenA);
  965. }
  966. }
  967. getFunctionName (id) {
  968. const name = LanguageDefinedFunction.getInternalName(id);
  969. if (name === null) {
  970. return id;
  971. } else {
  972. return name;
  973. }
  974. }
  975. parseFunctionCallExpression (id) {
  976. const tokenA = this.getToken(this.pos - 1);
  977. const actualParameters = this.parseActualParameters();
  978. const tokenB = this.getToken(this.pos - 1);
  979. const funcName = this.getFunctionName(id);
  980. const sourceInfo = SourceInfo.createSourceInfoFromList(tokenA, tokenB);
  981. const cmd = new Expressions.FunctionCall(funcName, actualParameters);
  982. cmd.sourceInfo = sourceInfo;
  983. return cmd;
  984. }
  985. parseFunctionCallCommand (id) {
  986. return this.parseFunctionCallExpression(id);
  987. }
  988. parseParenthesisExp () {
  989. this.checkOpenParenthesis();
  990. const tokenA = this.getToken();
  991. this.pos++;
  992. this.consumeNewLines();
  993. const exp = this.parseExpressionOR();
  994. this.consumeNewLines();
  995. this.checkCloseParenthesis();
  996. const tokenB = this.getToken();
  997. const sourceInfo = SourceInfo.createSourceInfoFromList(tokenA, tokenB);
  998. this.pos++;
  999. exp.sourceInfo = sourceInfo;
  1000. return exp;
  1001. }
  1002. parseActualParameters () {
  1003. this.checkOpenParenthesis();
  1004. this.pos++;
  1005. if(this.checkCloseParenthesis(true)) {
  1006. this.pos++;
  1007. return [];
  1008. }
  1009. this.consumeNewLines();
  1010. const list = this.parseExpressionList();
  1011. this.consumeNewLines();
  1012. this.checkCloseParenthesis();
  1013. this.pos++;
  1014. return list;
  1015. }
  1016. parseExpressionList () {
  1017. const list = [];
  1018. while(true) {
  1019. const exp = this.parseExpressionOR();
  1020. list.push(exp);
  1021. const maybeToken = this.getToken();
  1022. if (maybeToken.type !== this.lexerClass.COMMA) {
  1023. break;
  1024. } else {
  1025. this.pos++;
  1026. this.consumeNewLines();
  1027. }
  1028. }
  1029. return list;
  1030. }
  1031. getTypeArray () {
  1032. const types = this.insideScope(IVProgParser.FUNCTION) ? this.functionTypes : this.variableTypes;
  1033. return types.map( x => this.lexer.literalNames[x]);
  1034. }
  1035. }