ivprogParser.js 35 KB

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