1
0

ivprogParser.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  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. const token = this.getToken();
  677. this.pos++;
  678. this.checkOpenParenthesis();
  679. this.pos++;
  680. this.consumeNewLines();
  681. const logicalExpression = this.parseExpressionOR();
  682. this.consumeNewLines();
  683. this.checkCloseParenthesis();
  684. this.pos++;
  685. this.consumeNewLines();
  686. const cmdBlocks = this.parseCommandBlock();
  687. const maybeElse = this.getToken();
  688. if(maybeElse.type === this.lexerClass.RK_ELSE) {
  689. this.pos++;
  690. this.consumeNewLines();
  691. const maybeIf = this.getToken();
  692. let elseBlock = null;
  693. if(this.checkOpenCurly(true)) {
  694. elseBlock = this.parseCommandBlock();
  695. } else if(maybeIf.type === this.lexerClass.RK_IF) {
  696. elseBlock = this.parseIfThenElse();
  697. } else {
  698. throw SyntaxErrorFactory.token_missing_list([this.lexer.literalNames[this.lexerClass.RK_IF], '{'], maybeIf);
  699. }
  700. this.popScope();
  701. const cmd = new Commands.IfThenElse(logicalExpression, cmdBlocks, elseBlock);
  702. cmd.sourceInfo = SourceInfo.createSourceInfo(token);
  703. return cmd;
  704. }
  705. this.popScope();
  706. const cmd = new Commands.IfThenElse(logicalExpression, cmdBlocks, null);
  707. cmd.sourceInfo = SourceInfo.createSourceInfo(token);
  708. return cmd;
  709. }
  710. parseFor () {
  711. this.pushScope(IVProgParser.BREAKABLE);
  712. this.pos++;
  713. this.checkOpenParenthesis();
  714. this.pos++;
  715. this.consumeNewLines();
  716. const attribution = this.parseForAssign();
  717. this.consumeNewLines();
  718. const condition = this.parseExpressionOR();
  719. this.consumeForSemiColon();
  720. const increment = this.parseForAssign(true);
  721. this.checkCloseParenthesis()
  722. this.pos++;
  723. this.consumeNewLines();
  724. const commandsBlock = this.parseCommandBlock();
  725. this.popScope();
  726. return new Commands.For(attribution, condition, increment, commandsBlock);
  727. }
  728. parseWhile () {
  729. this.pushScope(IVProgParser.BREAKABLE);
  730. const token = this.getToken();
  731. this.pos++;
  732. this.checkOpenParenthesis();
  733. this.pos++;
  734. this.consumeNewLines();
  735. const logicalExpression = this.parseExpressionOR();
  736. this.consumeNewLines();
  737. this.checkCloseParenthesis();
  738. this.pos++;
  739. this.consumeNewLines();
  740. const cmdBlocks = this.parseCommandBlock();
  741. this.popScope();
  742. const cmd = new Commands.While(logicalExpression, cmdBlocks);
  743. cmd.sourceInfo = SourceInfo.createSourceInfo(token);
  744. return cmd;
  745. }
  746. parseBreak () {
  747. this.pos++;
  748. this.checkEOS();
  749. this.pos++;
  750. return new Commands.Break();
  751. }
  752. parseReturn () {
  753. this.pos++;
  754. let exp = null;
  755. if(!this.checkEOS(true)) {
  756. exp = this.parseExpressionOR();
  757. this.checkEOS();
  758. }
  759. this.pos++;
  760. return new Commands.Return(exp);
  761. }
  762. parseIDCommand () {
  763. const refToken = this.getToken();
  764. const isID = refToken.type === this.lexerClass.ID;
  765. const id = this.parseMaybeLibID();
  766. if(this.checkOpenBrace(true)) {
  767. this.pos++;
  768. let lineExpression = null;
  769. let columnExpression = null;
  770. this.consumeNewLines();
  771. lineExpression = this.parseExpression()
  772. this.consumeNewLines();
  773. this.checkCloseBrace();
  774. this.pos++;
  775. if (this.checkOpenBrace(true)) {
  776. this.pos++
  777. this.consumeNewLines();
  778. columnExpression = this.parseExpression();
  779. this.consumeNewLines();
  780. this.checkCloseBrace();
  781. this.pos++;
  782. }
  783. const equalToken = this.getToken();
  784. if (equalToken.type !== this.lexerClass.EQUAL) {
  785. throw SyntaxErrorFactory.token_missing_one('=', equalToken);
  786. }
  787. this.pos++;
  788. const exp = this.parseExpressionOR();
  789. this.checkEOS();
  790. this.pos++;
  791. const cmd = new Commands.ArrayIndexAssign(id, lineExpression, columnExpression, exp);
  792. cmd.sourceInfo = SourceInfo.createSourceInfo(equalToken);
  793. return cmd;
  794. }
  795. const equalOrParenthesis = this.getToken();
  796. if (isID && equalOrParenthesis.type === this.lexerClass.EQUAL) {
  797. this.pos++
  798. const exp = this.parseExpressionOR();
  799. this.checkEOS();
  800. this.pos++;
  801. const cmd = new Commands.Assign(id, exp);
  802. cmd.sourceInfo = SourceInfo.createSourceInfo(equalOrParenthesis);
  803. return cmd;
  804. } else if (equalOrParenthesis.type === this.lexerClass.OPEN_PARENTHESIS) {
  805. const funcCall = this.parseFunctionCallCommand(id);
  806. this.checkEOS();
  807. this.pos++;
  808. return funcCall;
  809. } else if (isID) {
  810. throw SyntaxErrorFactory.token_missing_list(['=','('], equalOrParenthesis);
  811. } else {
  812. throw SyntaxErrorFactory.invalid_id_format(refToken);
  813. }
  814. }
  815. parseForAssign (isLast = false) {
  816. if(!isLast)
  817. this.consumeNewLines();
  818. if(this.checkEOS(true)) {
  819. return null;
  820. }
  821. const id = this.parseID();
  822. const equal = this.getToken();
  823. if (equal.type !== this.lexerClass.EQUAL) {
  824. throw SyntaxErrorFactory.token_missing_one('=', equal);
  825. }
  826. this.pos++
  827. const exp = this.parseExpressionOR();
  828. if(!isLast) {
  829. this.consumeForSemiColon();
  830. }
  831. const sourceInfo = SourceInfo.createSourceInfo(equal);
  832. const cmd = new Commands.Assign(id, exp);
  833. cmd.sourceInfo = sourceInfo;
  834. return cmd;
  835. }
  836. parseCases () {
  837. const token = this.getToken();
  838. if(token.type !== this.lexerClass.RK_CASE) {
  839. throw SyntaxErrorFactory.token_missing_one(this.lexer.literalNames[this.lexerClass.RK_CASE], token);
  840. }
  841. this.pos++;
  842. const nextToken = this.getToken();
  843. if(nextToken.type === this.lexerClass.RK_DEFAULT) {
  844. this.pos++;
  845. const colonToken = this.getToken();
  846. if (colonToken.type !== this.lexerClass.COLON) {
  847. throw SyntaxErrorFactory.token_missing_one(':', colonToken);
  848. }
  849. this.pos++;
  850. this.consumeNewLines();
  851. const block = this.parseCommandBlock(true);
  852. const defaultCase = new Commands.Case(null);
  853. defaultCase.setCommands(block.commands);
  854. return [defaultCase];
  855. } else {
  856. const exp = this.parseExpressionOR();
  857. const colonToken = this.getToken();
  858. if (colonToken.type !== this.lexerClass.COLON) {
  859. throw SyntaxErrorFactory.token_missing_one(':', colonToken);
  860. }
  861. this.pos++;
  862. this.consumeNewLines();
  863. const block = this.parseCommandBlock(true);
  864. const aCase = new Commands.Case(exp);
  865. aCase.setCommands(block.commands);
  866. const caseToken = this.getToken();
  867. if(caseToken.type === this.lexerClass.RK_CASE) {
  868. return [aCase].concat(this.parseCases());
  869. } else {
  870. return [aCase];
  871. }
  872. }
  873. }
  874. /*
  875. * Parses an Expression following the structure:
  876. *
  877. * EOR => EAnd ( 'or' EOR)? #expression and
  878. *
  879. * EOR => ENot ('and' EOR)? #expression or
  880. *
  881. * ENot => 'not'? ER #expression not
  882. *
  883. * ER => E ((>=, <=, ==, >, <) E)? #expression relational
  884. *
  885. * E => factor ((+, -) E)? #expression
  886. *
  887. * factor=> term ((*, /, %) factor)?
  888. *
  889. * term => literal || arrayAccess || FuncCall || ID || '('EAnd')'
  890. **/
  891. parseExpressionOR () {
  892. let exp1 = this.parseExpressionAND();
  893. while (this.getToken().type === this.lexerClass.OR_OPERATOR) {
  894. const opToken = this.getToken();
  895. this.pos++;
  896. const or = convertFromString('or');
  897. this.consumeNewLines();
  898. const exp2 = this.parseExpressionAND();
  899. const finalExp = new Expressions.InfixApp(or, exp1, exp2);
  900. finalExp.sourceInfo = SourceInfo.createSourceInfo(opToken);
  901. exp1 = finalExp
  902. }
  903. return exp1;
  904. }
  905. parseExpressionAND () {
  906. let exp1 = this.parseExpressionNot();
  907. while (this.getToken().type === this.lexerClass.AND_OPERATOR) {
  908. const opToken = this.getToken();
  909. this.pos++;
  910. const and = convertFromString('and');
  911. this.consumeNewLines();
  912. const exp2 = this.parseExpressionNot();
  913. const finalExp = new Expressions.InfixApp(and, exp1, exp2);
  914. finalExp.sourceInfo = SourceInfo.createSourceInfo(opToken);
  915. exp1 = finalExp;
  916. }
  917. return exp1;
  918. }
  919. parseExpressionNot () {
  920. const maybeNotToken = this.getToken();
  921. if (maybeNotToken.type === this.lexerClass.NOT_OPERATOR) {
  922. const opToken = this.getToken();
  923. this.pos++;
  924. const not = convertFromString('not');
  925. const exp1 = this.parseExpressionRel();
  926. finalExp = new Expressions.UnaryApp(not, exp1);
  927. finalExp.sourceInfo = SourceInfo.createSourceInfo(opToken);
  928. return finalExp;
  929. } else {
  930. return this.parseExpressionRel();
  931. }
  932. }
  933. parseExpressionRel () {
  934. let exp1 = this.parseExpression();
  935. while (this.getToken().type === this.lexerClass.RELATIONAL_OPERATOR) {
  936. const relToken = this.getToken();
  937. this.pos++;
  938. const rel = convertFromString(relToken.text);
  939. const exp2 = this.parseExpression();
  940. const finalExp = new Expressions.InfixApp(rel, exp1, exp2);
  941. finalExp.sourceInfo = SourceInfo.createSourceInfo(relToken);
  942. exp1 = finalExp;
  943. }
  944. return exp1;
  945. }
  946. parseExpression () {
  947. let factor = this.parseFactor();
  948. while (this.getToken().type === this.lexerClass.SUM_OP) {
  949. const sumOpToken = this.getToken();
  950. this.pos++;
  951. const op = convertFromString(sumOpToken.text);
  952. const factor2 = this.parseFactor();
  953. const finalExp = new Expressions.InfixApp(op, factor, factor2);
  954. finalExp.sourceInfo = SourceInfo.createSourceInfo(sumOpToken);
  955. factor = finalExp;
  956. }
  957. return factor;
  958. }
  959. parseFactor () {
  960. let term = this.parseTerm();
  961. while (this.getToken().type === this.lexerClass.MULTI_OP) {
  962. const multOpToken = this.getToken();
  963. this.pos++;
  964. const op = convertFromString(multOpToken.text);
  965. const term2 =this.parseTerm();
  966. const finalExp = new Expressions.InfixApp(op, term, term2);
  967. finalExp.sourceInfo = SourceInfo.createSourceInfo(multOpToken);
  968. term = finalExp;
  969. }
  970. return term;
  971. }
  972. parseTerm () {
  973. const token = this.getToken();
  974. let sourceInfo = null;
  975. switch(token.type) {
  976. case this.lexerClass.SUM_OP:
  977. this.pos++;
  978. sourceInfo = SourceInfo.createSourceInfo(token);
  979. const exp = new Expressions.UnaryApp(convertFromString(token.text), this.parseTerm());
  980. exp.sourceInfo = sourceInfo;
  981. return exp;
  982. case this.lexerClass.INTEGER:
  983. this.pos++;
  984. return this.getIntLiteral(token);
  985. case this.lexerClass.REAL:
  986. this.pos++;
  987. return this.getRealLiteral(token);
  988. case this.lexerClass.STRING:
  989. this.pos++;
  990. return this.getStringLiteral(token);
  991. case this.lexerClass.RK_TRUE:
  992. case this.lexerClass.RK_FALSE:
  993. this.pos++;
  994. return this.getBoolLiteral(token);
  995. case this.lexerClass.OPEN_CURLY:
  996. return this.parseArrayLiteral();
  997. case this.lexerClass.ID:
  998. case this.lexerClass.LIB_ID:
  999. return this.parseIDTerm();
  1000. case this.lexerClass.OPEN_PARENTHESIS:
  1001. return this.parseParenthesisExp();
  1002. default:
  1003. throw SyntaxErrorFactory.invalid_terminal(token);
  1004. }
  1005. }
  1006. parseIDTerm () {
  1007. const tokenA = this.getToken();
  1008. const id = this.parseMaybeLibID();
  1009. const isID = tokenA.type === this.lexerClass.ID;
  1010. if(isID && this.checkOpenBrace(true)) {
  1011. let tokenB = null;
  1012. this.pos++;
  1013. const firstIndex = this.parseExpression();
  1014. let secondIndex = null;
  1015. this.consumeNewLines();
  1016. this.checkCloseBrace();
  1017. tokenB = this.getToken();
  1018. this.pos++;
  1019. if(this.checkOpenBrace(true)){
  1020. this.pos++;
  1021. secondIndex = this.parseExpression();
  1022. this.consumeNewLines();
  1023. this.checkCloseBrace();
  1024. tokenB = this.getToken();
  1025. this.pos++;
  1026. }
  1027. const sourceInfo = SourceInfo.createSourceInfoFromList(tokenA, tokenB);
  1028. const exp = new Expressions.ArrayAccess(id, firstIndex, secondIndex);
  1029. exp.sourceInfo = sourceInfo;
  1030. return exp;
  1031. } else if (this.checkOpenParenthesis(true)) {
  1032. return this.parseFunctionCallExpression(id);
  1033. } else if (isID) {
  1034. const sourceInfo = SourceInfo.createSourceInfo(tokenA);
  1035. const exp = new Expressions.VariableLiteral(id);
  1036. exp.sourceInfo = sourceInfo;
  1037. return exp;
  1038. } else {
  1039. throw SyntaxErrorFactory.invalid_id_format(tokenA);
  1040. }
  1041. }
  1042. getFunctionName (id) {
  1043. const name = LanguageDefinedFunction.getInternalName(id);
  1044. if (name === null) {
  1045. if (id === LanguageDefinedFunction.getMainFunctionName()) {
  1046. return null;
  1047. }
  1048. return id;
  1049. } else {
  1050. return name;
  1051. }
  1052. }
  1053. parseFunctionCallExpression (id) {
  1054. const tokenA = this.getToken(this.pos - 1);
  1055. const actualParameters = this.parseActualParameters();
  1056. const tokenB = this.getToken(this.pos - 1);
  1057. const funcName = this.getFunctionName(id);
  1058. const sourceInfo = SourceInfo.createSourceInfoFromList(tokenA, tokenB);
  1059. const cmd = new Expressions.FunctionCall(funcName, actualParameters);
  1060. cmd.sourceInfo = sourceInfo;
  1061. return cmd;
  1062. }
  1063. parseFunctionCallCommand (id) {
  1064. return this.parseFunctionCallExpression(id);
  1065. }
  1066. parseParenthesisExp () {
  1067. this.checkOpenParenthesis();
  1068. const tokenA = this.getToken();
  1069. this.pos++;
  1070. this.consumeNewLines();
  1071. const exp = this.parseExpressionOR();
  1072. this.consumeNewLines();
  1073. this.checkCloseParenthesis();
  1074. const tokenB = this.getToken();
  1075. const sourceInfo = SourceInfo.createSourceInfoFromList(tokenA, tokenB);
  1076. this.pos++;
  1077. exp.sourceInfo = sourceInfo;
  1078. return exp;
  1079. }
  1080. parseActualParameters () {
  1081. this.checkOpenParenthesis();
  1082. this.pos++;
  1083. if(this.checkCloseParenthesis(true)) {
  1084. this.pos++;
  1085. return [];
  1086. }
  1087. this.consumeNewLines();
  1088. const list = this.parseExpressionList();
  1089. this.consumeNewLines();
  1090. this.checkCloseParenthesis();
  1091. this.pos++;
  1092. return list;
  1093. }
  1094. parseExpressionList () {
  1095. const list = [];
  1096. while(true) {
  1097. const exp = this.parseExpressionOR();
  1098. list.push(exp);
  1099. const maybeToken = this.getToken();
  1100. if (maybeToken.type !== this.lexerClass.COMMA) {
  1101. break;
  1102. } else {
  1103. this.pos++;
  1104. this.consumeNewLines();
  1105. }
  1106. }
  1107. return list;
  1108. }
  1109. getTypeArray () {
  1110. const types = this.insideScope(IVProgParser.FUNCTION) ? this.functionTypes : this.variableTypes;
  1111. return types.map( x => this.lexer.literalNames[x]);
  1112. }
  1113. }