ivprogParser.js 35 KB

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