ivprogParser.js 34 KB

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