1
0

ivprogParser.js 33 KB

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