ivprogParser.js 31 KB

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