ivprogParser.js 35 KB

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