1
0

ivprogParser.js 33 KB

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