ivprogParser.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  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. parseType () {
  453. const token = this.getToken();
  454. if(token.type === this.lexerClass.ID && this.insideScope(IVProgParser.FUNCTION)) {
  455. return Types.VOID;
  456. } else if (token.type === this.lexerClass.RK_VOID && this.insideScope(IVProgParser.FUNCTION)) {
  457. this.pos++;
  458. return Types.VOID;
  459. } else if (this.isVariableType(token)) {
  460. this.pos++;
  461. switch(token.type) {
  462. case this.lexerClass.RK_INTEGER:
  463. return Types.INTEGER;
  464. case this.lexerClass.RK_BOOLEAN:
  465. return Types.BOOLEAN;
  466. case this.lexerClass.RK_REAL:
  467. return Types.REAL;
  468. case this.lexerClass.RK_STRING:
  469. return Types.STRING;
  470. default:
  471. break;
  472. }
  473. }
  474. throw SyntaxErrorFactory.invalid_type(this.getTypeArray(), token);
  475. }
  476. parseCommandBlock (optionalCurly = false) {
  477. let variablesDecl = [];
  478. const commands = [];
  479. let hasOpen = false;
  480. if (this.checkOpenCurly(optionalCurly)) {
  481. this.pos++;
  482. hasOpen = true;
  483. }
  484. this.consumeNewLines();
  485. while(true) {
  486. const cmd = this.parseCommand();
  487. if (cmd === null)
  488. break;
  489. if(cmd !== -1) {
  490. if (cmd instanceof Array) {
  491. variablesDecl = variablesDecl.concat(cmd);
  492. } else {
  493. commands.push(cmd);
  494. }
  495. }
  496. }
  497. this.consumeNewLines();
  498. if (hasOpen) {
  499. this.checkCloseCurly()
  500. this.pos++;
  501. this.consumeNewLines();
  502. }
  503. return new Commands.CommandBlock(variablesDecl, commands);
  504. }
  505. parseCommand () {
  506. const token = this.getToken();
  507. if (this.isVariableType(token)) {
  508. if(!this.insideScope(IVProgParser.FUNCTION)) {
  509. // TODO better error message
  510. throw SyntaxErrorFactory.invalid_var_declaration(token.line);
  511. }
  512. this.pushScope(IVProgParser.BASE);
  513. const varType = this.parseType();
  514. this.popScope();
  515. const cmd = this.parseDeclaration(varType);
  516. this.checkEOS();
  517. this.pos++;
  518. return cmd;
  519. } else if (token.type === this.lexerClass.ID) {
  520. return this.parseIDCommand();
  521. } else if (token.type === this.lexerClass.RK_RETURN) {
  522. return this.parseReturn();
  523. } else if (token.type === this.lexerClass.RK_WHILE) {
  524. return this.parseWhile();
  525. } else if (token.type === this.lexerClass.RK_FOR) {
  526. return this.parseFor();
  527. } else if (token.type === this.lexerClass.RK_BREAK ) {
  528. if(!this.insideScope(IVProgParser.BREAKABLE)) {
  529. // TODO better error message
  530. throw SyntaxErrorFactory.invalid_break_command(
  531. this.lexer.literalNames[this.lexerClass.RK_BREAK],
  532. token
  533. );
  534. }
  535. return this.parseBreak();
  536. } else if (token.type === this.lexerClass.RK_SWITCH) {
  537. return this.parseSwitchCase();
  538. } else if (token.type === this.lexerClass.RK_DO) {
  539. return this.parseDoWhile();
  540. } else if (token.type === this.lexerClass.RK_IF) {
  541. return this.parseIfThenElse();
  542. } else if (this.checkEOS(true)){
  543. this.pos++;
  544. return -1;
  545. } else {
  546. return null;
  547. }
  548. }
  549. parseSwitchCase () {
  550. this.pushScope(IVProgParser.BREAKABLE);
  551. this.pos++;
  552. this.checkOpenParenthesis();
  553. this.pos++;
  554. this.consumeNewLines();
  555. const exp = this.parseExpressionOR();
  556. this.consumeNewLines();
  557. this.checkCloseParenthesis();
  558. this.pos++;
  559. this.consumeNewLines();
  560. this.checkOpenCurly();
  561. this.pos++;
  562. this.consumeNewLines();
  563. const casesList = this.parseCases();
  564. this.consumeNewLines();
  565. this.checkCloseCurly();
  566. this.pos++;
  567. this.consumeNewLines();
  568. this.popScope();
  569. return new Commands.Switch(exp, casesList);
  570. }
  571. parseDoWhile () {
  572. this.pos++;
  573. this.consumeNewLines();
  574. this.pushScope(IVProgParser.BREAKABLE);
  575. const commandsBlock = this.parseCommandBlock();
  576. this.consumeNewLines(); //Maybe not...
  577. const whileToken = this.getToken();
  578. if (whileToken.type !== this.lexerClass.RK_WHILE) {
  579. throw SyntaxErrorFactory.token_missing_one(this.lexer.literalNames[this.lexerClass.RK_WHILE], whileToken);
  580. }
  581. this.pos++;
  582. this.checkOpenParenthesis();
  583. this.pos++;
  584. this.consumeNewLines();
  585. const condition = this.parseExpressionOR();
  586. this.consumeNewLines();
  587. this.checkCloseParenthesis();
  588. this.pos++;
  589. this.checkEOS();
  590. this.popScope();
  591. return new Commands.DoWhile(condition, commandsBlock);
  592. }
  593. parseIfThenElse () {
  594. if(this.insideScope(IVProgParser.BREAKABLE)) {
  595. this.pushScope(IVProgParser.BREAKABLE);
  596. } else {
  597. this.pushScope(IVProgParser.COMMAND);
  598. }
  599. this.pos++;
  600. this.checkOpenParenthesis();
  601. this.pos++;
  602. this.consumeNewLines();
  603. const logicalExpression = this.parseExpressionOR();
  604. this.consumeNewLines();
  605. this.checkCloseParenthesis();
  606. this.pos++;
  607. this.consumeNewLines();
  608. const cmdBlocks = this.parseCommandBlock();
  609. const maybeElse = this.getToken();
  610. if(maybeElse.type === this.lexerClass.RK_ELSE) {
  611. this.pos++;
  612. this.consumeNewLines();
  613. const maybeIf = this.getToken();
  614. let elseBlock = null;
  615. if(this.checkOpenCurly(true)) {
  616. elseBlock = this.parseCommandBlock();
  617. } else if(maybeIf.type === this.lexerClass.RK_IF) {
  618. elseBlock = this.parseIfThenElse();
  619. } else {
  620. // TODO better error message
  621. throw SyntaxErrorFactory.token_missing_list([this.lexer.literalNames[this.lexerClass.RK_IF], '{'], maybeIf);
  622. }
  623. return new Commands.IfThenElse(logicalExpression, cmdBlocks, elseBlock);
  624. }
  625. this.popScope();
  626. return new Commands.IfThenElse(logicalExpression, cmdBlocks, null);
  627. }
  628. parseFor () {
  629. this.pushScope(IVProgParser.BREAKABLE);
  630. this.pos++;
  631. this.checkOpenParenthesis();
  632. this.pos++;
  633. this.consumeNewLines();
  634. const attribution = this.parseForAssign();
  635. this.consumeNewLines();
  636. const condition = this.parseExpressionOR();
  637. this.consumeForSemiColon();
  638. const increment = this.parseForAssign(true);
  639. this.checkCloseParenthesis()
  640. this.pos++;
  641. this.consumeNewLines();
  642. const commandsBlock = this.parseCommandBlock();
  643. this.popScope();
  644. return new Commands.For(attribution, condition, increment, commandsBlock);
  645. }
  646. parseWhile () {
  647. this.pushScope(IVProgParser.BREAKABLE);
  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. this.popScope();
  659. return new Commands.While(logicalExpression, cmdBlocks);
  660. }
  661. parseBreak () {
  662. this.pos++;
  663. this.checkEOS();
  664. this.pos++;
  665. return new Commands.Break();
  666. }
  667. parseReturn () {
  668. this.pos++;
  669. let exp = null;
  670. if(!this.checkEOS(true)) {
  671. exp = this.parseExpressionOR();
  672. this.checkEOS();
  673. }
  674. this.pos++;
  675. return new Commands.Return(exp);
  676. }
  677. parseIDCommand () {
  678. const id = this.parseID();
  679. const equalOrParenthesis = this.getToken();
  680. if (equalOrParenthesis.type === this.lexerClass.EQUAL) {
  681. const sourceInfo = SourceInfo.createSourceInfo(this.getToken());
  682. this.pos++
  683. const exp = this.parseExpressionOR();
  684. this.checkEOS();
  685. this.pos++;
  686. const cmd = new Commands.Assign(id, exp);
  687. cmd.sourceInfo = sourceInfo;
  688. return cmd;
  689. } else if (equalOrParenthesis.type === this.lexerClass.OPEN_PARENTHESIS) {
  690. const funcCall = this.parseFunctionCallCommand(id);
  691. this.checkEOS();
  692. this.pos++;
  693. return funcCall;
  694. } else {
  695. throw SyntaxErrorFactory.token_missing_list(['=','('], equalOrParenthesis);
  696. }
  697. }
  698. parseForAssign (isLast = false) {
  699. if(!isLast)
  700. this.consumeNewLines();
  701. if(this.checkEOS(true)) {
  702. return null;
  703. }
  704. const id = this.parseID();
  705. const equal = this.getToken();
  706. if (equal.type !== this.lexerClass.EQUAL) {
  707. throw SyntaxErrorFactory.token_missing_one('=', equal);
  708. }
  709. this.pos++
  710. const exp = this.parseExpressionOR();
  711. if(!isLast) {
  712. this.consumeForSemiColon();
  713. }
  714. const sourceInfo = SourceInfo.createSourceInfo(equal);
  715. const cmd = new Commands.Assign(id, exp);
  716. cmd.sourceInfo = sourceInfo;
  717. return cmd;
  718. }
  719. parseCases () {
  720. const token = this.getToken();
  721. if(token.type !== this.lexerClass.RK_CASE) {
  722. throw SyntaxErrorFactory.token_missing_one(this.lexer.literalNames[this.lexerClass.RK_CASE], token);
  723. }
  724. this.pos++;
  725. const nextToken = this.getToken();
  726. if(nextToken.type === this.lexerClass.RK_DEFAULT) {
  727. this.pos++;
  728. const colonToken = this.getToken();
  729. if (colonToken.type !== this.lexerClass.COLON) {
  730. throw SyntaxErrorFactory.token_missing_one(':', colonToken);
  731. }
  732. this.pos++;
  733. this.consumeNewLines();
  734. const block = this.parseCommandBlock(true);
  735. const defaultCase = new Commands.Case(null);
  736. defaultCase.setCommands(block.commands);
  737. return [defaultCase];
  738. } else {
  739. const exp = this.parseExpressionOR();
  740. const colonToken = this.getToken();
  741. if (colonToken.type !== this.lexerClass.COLON) {
  742. throw SyntaxErrorFactory.token_missing_one(':', colonToken);
  743. }
  744. this.pos++;
  745. this.consumeNewLines();
  746. const block = this.parseCommandBlock(true);
  747. const aCase = new Commands.Case(exp);
  748. aCase.setCommands(block.commands);
  749. const caseToken = this.getToken();
  750. if(caseToken.type === this.lexerClass.RK_CASE) {
  751. return [aCase].concat(this.parseCases());
  752. } else {
  753. return [aCase];
  754. }
  755. }
  756. }
  757. /*
  758. * Parses an Expression following the structure:
  759. *
  760. * EOR => EAnd ( 'or' EOR)? #expression and
  761. *
  762. * EOR => ENot ('and' EOR)? #expression or
  763. *
  764. * ENot => 'not'? ER #expression not
  765. *
  766. * ER => E ((>=, <=, ==, >, <) E)? #expression relational
  767. *
  768. * E => factor ((+, -) E)? #expression
  769. *
  770. * factor=> term ((*, /, %) factor)?
  771. *
  772. * term => literal || arrayAccess || FuncCall || ID || '('EAnd')'
  773. **/
  774. parseExpressionOR () {
  775. let exp1 = this.parseExpressionAND();
  776. while (this.getToken().type === this.lexerClass.OR_OPERATOR) {
  777. const opToken = this.getToken();
  778. this.pos++;
  779. const or = convertFromString('or');
  780. this.consumeNewLines();
  781. const exp2 = this.parseExpressionAND();
  782. const finalExp = new Expressions.InfixApp(or, exp1, exp2);
  783. finalExp.sourceInfo = SourceInfo.createSourceInfo(opToken);
  784. exp1 = finalExp
  785. }
  786. return exp1;
  787. }
  788. parseExpressionAND () {
  789. let exp1 = this.parseExpressionNot();
  790. while (this.getToken().type === this.lexerClass.AND_OPERATOR) {
  791. const opToken = this.getToken();
  792. this.pos++;
  793. const and = convertFromString('and');
  794. this.consumeNewLines();
  795. const exp2 = this.parseExpressionNot();
  796. const finalExp = new Expressions.InfixApp(and, exp1, exp2);
  797. finalExp.sourceInfo = SourceInfo.createSourceInfo(opToken);
  798. exp1 = finalExp;
  799. }
  800. return exp1;
  801. }
  802. parseExpressionNot () {
  803. const maybeNotToken = this.getToken();
  804. if (maybeNotToken.type === this.lexerClass.NOT_OPERATOR) {
  805. const opToken = this.getToken();
  806. this.pos++;
  807. const not = convertFromString('not');
  808. const exp1 = this.parseExpressionRel();
  809. finalExp = new Expressions.UnaryApp(not, exp1);
  810. finalExp.sourceInfo = SourceInfo.createSourceInfo(opToken);
  811. return finalExp;
  812. } else {
  813. return this.parseExpressionRel();
  814. }
  815. }
  816. parseExpressionRel () {
  817. let exp1 = this.parseExpression();
  818. while (this.getToken().type === this.lexerClass.RELATIONAL_OPERATOR) {
  819. const relToken = this.getToken();
  820. this.pos++;
  821. const rel = convertFromString(relToken.text);
  822. const exp2 = this.parseExpression();
  823. const finalExp = new Expressions.InfixApp(rel, exp1, exp2);
  824. finalExp.sourceInfo = SourceInfo.createSourceInfo(relToken);
  825. exp1 = finalExp;
  826. }
  827. return exp1;
  828. }
  829. parseExpression () {
  830. let factor = this.parseFactor();
  831. while (this.getToken().type === this.lexerClass.SUM_OP) {
  832. const sumOpToken = this.getToken();
  833. this.pos++;
  834. const op = convertFromString(sumOpToken.text);
  835. const factor2 = this.parseFactor();
  836. const finalExp = new Expressions.InfixApp(op, factor, factor2);
  837. finalExp.sourceInfo = SourceInfo.createSourceInfo(sumOpToken);
  838. factor = finalExp;
  839. }
  840. return factor;
  841. }
  842. parseFactor () {
  843. let term = this.parseTerm();
  844. while (this.getToken().type === this.lexerClass.MULTI_OP) {
  845. const multOpToken = this.getToken();
  846. this.pos++;
  847. const op = convertFromString(multOpToken.text);
  848. const term2 =this.parseTerm();
  849. const finalExp = new Expressions.InfixApp(op, term, term2);
  850. finalExp.sourceInfo = SourceInfo.createSourceInfo(multOpToken);
  851. term = finalExp;
  852. }
  853. return term;
  854. }
  855. parseTerm () {
  856. const token = this.getToken();
  857. let sourceInfo = null;
  858. switch(token.type) {
  859. case this.lexerClass.SUM_OP:
  860. this.pos++;
  861. sourceInfo = SourceInfo.createSourceInfo(token);
  862. const exp = new Expressions.UnaryApp(convertFromString(token.text), this.parseTerm());
  863. exp.sourceInfo = sourceInfo;
  864. return exp;
  865. case this.lexerClass.INTEGER:
  866. this.pos++;
  867. return this.getIntLiteral(token);
  868. case this.lexerClass.REAL:
  869. this.pos++;
  870. return this.getRealLiteral(token);
  871. case this.lexerClass.STRING:
  872. this.pos++;
  873. return this.getStringLiteral(token);
  874. case this.lexerClass.RK_TRUE:
  875. case this.lexerClass.RK_FALSE:
  876. this.pos++;
  877. return this.getBoolLiteral(token);
  878. case this.lexerClass.OPEN_CURLY:
  879. return this.parseArrayLiteral();
  880. case this.lexerClass.ID:
  881. return this.parseIDTerm();
  882. case this.lexerClass.OPEN_PARENTHESIS:
  883. return this.parseParenthesisExp();
  884. default:
  885. throw SyntaxErrorFactory.invalid_terminal(token);
  886. }
  887. }
  888. parseIDTerm () {
  889. const id = this.parseID();
  890. const tokenA = this.getToken(this.pos - 1);
  891. if(this.checkOpenBrace(true)) {
  892. let tokenB = null;
  893. this.pos++;
  894. const firstIndex = this.parseExpression();
  895. let secondIndex = null;
  896. this.consumeNewLines();
  897. this.checkCloseBrace();
  898. tokenB = this.getToken();
  899. this.pos++;
  900. if(this.checkOpenBrace(true)){
  901. this.pos++;
  902. secondIndex = this.parseExpression();
  903. this.consumeNewLines();
  904. this.checkCloseBrace();
  905. tokenB = this.getToken();
  906. this.pos++;
  907. }
  908. const sourceInfo = SourceInfo.createSourceInfoFromList(tokenA, tokenB);
  909. const exp = new Expressions.ArrayAccess(id, firstIndex, secondIndex);
  910. exp.sourceInfo = sourceInfo;
  911. return exp;
  912. } else if (this.checkOpenParenthesis(true)) {
  913. return this.parseFunctionCallExpression(id);
  914. } else {
  915. const sourceInfo = SourceInfo.createSourceInfo(tokenA);
  916. const exp = new Expressions.VariableLiteral(id);
  917. exp.sourceInfo = sourceInfo;
  918. return exp;
  919. }
  920. }
  921. getFunctionName (id) {
  922. const name = LanguageDefinedFunction.getInternalName(id);
  923. if (name === null) {
  924. return id;
  925. } else {
  926. return name;
  927. }
  928. }
  929. parseFunctionCallExpression (id) {
  930. const tokenA = this.getToken(this.pos - 1);
  931. const actualParameters = this.parseActualParameters();
  932. const tokenB = this.getToken(this.pos - 1);
  933. const funcName = this.getFunctionName(id);
  934. const sourceInfo = SourceInfo.createSourceInfoFromList(tokenA, tokenB);
  935. const cmd = new Expressions.FunctionCall(funcName, actualParameters);
  936. cmd.sourceInfo = sourceInfo;
  937. return cmd;
  938. }
  939. parseFunctionCallCommand (id) {
  940. return this.parseFunctionCallExpression(id);
  941. }
  942. parseParenthesisExp () {
  943. this.checkOpenParenthesis();
  944. const tokenA = this.getToken();
  945. this.pos++;
  946. this.consumeNewLines();
  947. const exp = this.parseExpressionOR();
  948. this.consumeNewLines();
  949. this.checkCloseParenthesis();
  950. const tokenB = this.getToken();
  951. const sourceInfo = SourceInfo.createSourceInfoFromList(tokenA, tokenB);
  952. this.pos++;
  953. exp.sourceInfo = sourceInfo;
  954. return exp;
  955. }
  956. parseActualParameters () {
  957. this.checkOpenParenthesis();
  958. this.pos++;
  959. if(this.checkCloseParenthesis(true)) {
  960. this.pos++;
  961. return [];
  962. }
  963. this.consumeNewLines();
  964. const list = this.parseExpressionList();
  965. this.consumeNewLines();
  966. this.checkCloseParenthesis();
  967. this.pos++;
  968. return list;
  969. }
  970. parseExpressionList () {
  971. const list = [];
  972. while(true) {
  973. const exp = this.parseExpressionOR();
  974. list.push(exp);
  975. const maybeToken = this.getToken();
  976. if (maybeToken.type !== this.lexerClass.COMMA) {
  977. break;
  978. } else {
  979. this.pos++;
  980. this.consumeNewLines();
  981. }
  982. }
  983. return list;
  984. }
  985. getTypeArray () {
  986. const types = this.insideScope(IVProgParser.FUNCTION) ? this.functionTypes : this.variableTypes;
  987. return types.map( x => this.lexer.literalNames[x]);
  988. }
  989. }