semanticAnalyser.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. import { ProcessorErrorFactory } from './../error/processorErrorFactory';
  2. import { LanguageDefinedFunction } from './../definedFunctions';
  3. import { LanguageService } from './../../services/languageService';
  4. import { ArrayDeclaration, While, For, Switch, Case, Declaration, Assign, Break, IfThenElse, Return, ArrayIndexAssign } from '../../ast/commands';
  5. import { InfixApp, UnaryApp, FunctionCall, IntLiteral, RealLiteral, StringLiteral, BoolLiteral, VariableLiteral, ArrayLiteral, ArrayAccess } from '../../ast/expressions';
  6. import { Literal } from '../../ast/expressions/literal';
  7. import { resultTypeAfterInfixOp, resultTypeAfterUnaryOp } from '../compatibilityTable';
  8. import { Types } from '../../typeSystem/types';
  9. import { CompoundType } from '../../typeSystem/compoundType';
  10. import { MultiType } from '../../typeSystem/multiType';
  11. export class SemanticAnalyser {
  12. constructor(ast) {
  13. this.ast = ast;
  14. this.lexerClass = LanguageService.getCurrentLexer();
  15. const lexer = new this.lexerClass(null);
  16. this.literalNames = lexer.literalNames;
  17. this.symbolMap = null;
  18. }
  19. pushMap () {
  20. if(this.symbolMap === null) {
  21. this.symbolMap = {map:{}, next: null};
  22. } else {
  23. const n = {map:{}, next: this.symbolMap};
  24. this.symbolMap = n;
  25. }
  26. }
  27. popMap () {
  28. if(this.symbolMap !== null) {
  29. this.symbolMap = this.symbolMap.next;
  30. }
  31. }
  32. insertSymbol (id, typeInfo) {
  33. this.symbolMap.map[id] = typeInfo;
  34. }
  35. findSymbol (id, symMap) {
  36. if(!symMap.map[id]) {
  37. if(symMap.next) {
  38. return this.findSymbol(id, symMap.next);
  39. }
  40. throw new Error("variable not defined "+id);
  41. } else {
  42. return symMap.map[id];
  43. }
  44. }
  45. getMainFunction () {
  46. return this.ast.functions.find(v => v.isMain);
  47. }
  48. findFunction (name) {
  49. if(name.match(/^\$.+$/)) {
  50. const fun = LanguageDefinedFunction.getFunction(name);
  51. if(!!!fun) {
  52. throw new Error("!!!Internal Error. Language defined function not implemented -> " + name + "!!!");
  53. }
  54. return fun;
  55. } else {
  56. const val = this.ast.functions.find( v => v.name === name);
  57. if (!!!val) {
  58. // TODO: better error message;
  59. throw new Error(`Function ${name} is not defined.`);
  60. }
  61. return val;
  62. }
  63. }
  64. analyseTree () {
  65. const globalVars = this.ast.global;
  66. this.pushMap();
  67. this.assertDeclarations(globalVars);
  68. const functions = this.ast.functions;
  69. const mainFunc = functions.filter((f) => f.name === null);
  70. if (mainFunc.length <= 0) {
  71. throw new Error("no main func...");
  72. } else if (mainFunc.length > 1) {
  73. throw new Error("only one main func...");
  74. }
  75. for (let i = 0; i < functions.length; i++) {
  76. const fun = functions[i];
  77. this.assertFunction(fun);
  78. }
  79. return this.ast;
  80. }
  81. assertDeclarations (list) {
  82. for (let i = 0; i < list.length; i++) {
  83. this.assertDeclaration(list[i]);
  84. }
  85. }
  86. assertDeclaration (declaration) {
  87. if (declaration instanceof ArrayDeclaration) {
  88. if(declaration.initial === null) {
  89. const lineType = this.evaluateExpressionType(declaration.lines);
  90. if (!lineType.isCompatible(Types.INTEGER)) {
  91. throw new Error("dim must be int");
  92. }
  93. if (declaration.columns !== null) {
  94. const columnType = this.evaluateExpressionType(declaration.columns);
  95. if (!columnType.isCompatible(Types.INTEGER)) {
  96. throw new Error("dim must be int");
  97. }
  98. }
  99. this.insertSymbol(declaration.id, {id: declaration.id, lines: declaration.lines, columns: declaration.columns, type: declaration.type});
  100. return;
  101. }
  102. this.evaluateArrayLiteral(declaration.lines, declaration.columns, declaration.type, declaration.initial);
  103. this.insertSymbol(declaration.id, {id: declaration.id, lines: declaration.lines, columns: declaration.columns, type: declaration.type});
  104. } else {
  105. if(declaration.initial === null) {
  106. this.insertSymbol(declaration.id, {id: declaration.id, type: declaration.type});
  107. return;
  108. }
  109. const resultType = this.evaluateExpressionType(declaration.initial);
  110. if(resultType instanceof MultiType) {
  111. if(!resultType.isCompatible(declaration.type)) {
  112. throw new Error('Invalid type');
  113. }
  114. this.insertSymbol(declaration.id, {id: declaration.id, type: declaration.type})
  115. } else if(!declaration.type.isCompatible(resultType)) {
  116. throw new Error('Invalid type');
  117. } else {
  118. this.insertSymbol(declaration.id, {id: declaration.id, type: declaration.type})
  119. }
  120. }
  121. }
  122. evaluateExpressionType (expression) {
  123. if(expression instanceof UnaryApp) {
  124. const op = expression.op;
  125. const resultType = this.evaluateExpressionType(expression.left);
  126. return resultTypeAfterUnaryOp(op, resultType);
  127. } else if (expression instanceof InfixApp) {
  128. const op = expression.op;
  129. const resultTypeLeft = this.evaluateExpressionType(expression.left);
  130. const resultTypeRight = this.evaluateExpressionType(expression.right);
  131. return resultTypeAfterInfixOp(op, resultTypeLeft, resultTypeRight);
  132. } else if (expression instanceof Literal) {
  133. return this.evaluateLiteralType(expression);
  134. } else if (expression instanceof FunctionCall) {
  135. if (expression.isMainCall) {
  136. throw new Error("void return used in expression");
  137. }
  138. const fun = this.findFunction(expression.id);
  139. if (fun.returnType.isCompatible(Types.VOID)) {
  140. throw new Error("void return used in expression");
  141. }
  142. this.assertParameters(fun, expression.actualParameters);
  143. return fun.returnType;
  144. } else if (expression instanceof ArrayAccess) {
  145. const arrayTypeInfo = this.findSymbol(expression.id, this.symbolMap);
  146. if (!(arrayTypeInfo.type instanceof CompoundType)) {
  147. throw new Error("it's not an array");
  148. }
  149. const lineType = this.evaluateExpressionType(expression.line);
  150. if (!lineType.isCompatible(Types.INTEGER)) {
  151. throw new Error("line must be integer");
  152. }
  153. if (expression.column !== null) {
  154. if (arrayTypeInfo.columns === null) {
  155. throw new Error("it's not a matrix");
  156. }
  157. const columnType = this.evaluateExpressionType(expression.column);
  158. if(!columnType.isCompatible(Types.INTEGER)) {
  159. throw new Error("column must be integer");
  160. }
  161. }
  162. const arrType = arrayTypeInfo.type;
  163. if(expression.column !== null) {
  164. // indexing matrix
  165. return arrType.innerType;
  166. } else {
  167. if(arrayTypeInfo.columns === null) {
  168. return arrType.innerType;
  169. }
  170. return new CompoundType(arrType.innerType, 1);
  171. }
  172. }
  173. }
  174. evaluateLiteralType (literal) {
  175. if(literal instanceof IntLiteral) {
  176. return literal.type;
  177. } else if (literal instanceof RealLiteral) {
  178. return literal.type;
  179. } else if (literal instanceof StringLiteral) {
  180. return literal.type;
  181. } else if (literal instanceof BoolLiteral) {
  182. return literal.type;
  183. } else if (literal instanceof VariableLiteral) {
  184. const typeInfo = this.findSymbol(literal.id, this.symbolMap);
  185. if (typeInfo.type instanceof CompoundType) {
  186. return typeInfo.type;
  187. }
  188. return typeInfo.type;
  189. } else {
  190. console.warn("Evaluating type only for an array literal...");
  191. let last = null;
  192. if(literal.value.length === 1) {
  193. last = this.evaluateExpressionType(literal.value[0]);
  194. } else {
  195. for (let i = 0; i < literal.value.length; i++) {
  196. const e = this.evaluateExpressionType(literal.value[i]);
  197. if(last === null) {
  198. last = e;
  199. } else if(!last.isCompatible(e)) {
  200. throw new Error("invalid value type for array");
  201. } else {
  202. last = e;
  203. }
  204. }
  205. }
  206. if(last instanceof CompoundType) {
  207. return new CompoundType(last.innerType, last.dimensions + 1);
  208. }
  209. return new CompoundType(last, 1);
  210. }
  211. }
  212. evaluateArrayLiteral (lines, columns, type, literal) {
  213. if (literal instanceof ArrayLiteral) {
  214. if (columns === null) {
  215. // it's a vector...
  216. const dimType = this.evaluateExpressionType(lines);
  217. if (!dimType.isCompatible(Types.INTEGER)) {
  218. throw new Error("dim must be int");
  219. }
  220. if ((lines instanceof IntLiteral) && !lines.value.eq(literal.value.length)) {
  221. throw new Error("invalid array size");
  222. }
  223. literal.value.reduce((last, next) => {
  224. const eType = this.evaluateExpressionType(next);
  225. if (!last.canAccept(eType)) {
  226. throw new Error("invalid value type for array");
  227. }
  228. return last;
  229. }, type);
  230. return true;
  231. } else {
  232. const dimType = this.evaluateExpressionType(columns);
  233. if (!dimType.isCompatible(Types.INTEGER)) {
  234. throw new Error("dim must be int");
  235. }
  236. if ((columns instanceof IntLiteral) && !columns.value.eq(literal.value.length)) {
  237. throw new Error("invalid array size");
  238. }
  239. for (let i = 0; i < columns; i++) {
  240. const anotherArray = literal.value[i];
  241. this.evaluateArrayLiteral(lines, null, type, anotherArray)
  242. }
  243. }
  244. } else {
  245. const resultType = this.evaluateExpressionType(literal);
  246. if (!(resultType instanceof CompoundType)) {
  247. throw new Error("initial must be of type array");
  248. }
  249. if (!type.isCompatible(resultType)) {
  250. throw new Error("invalid array type");
  251. }
  252. return true;
  253. }
  254. }
  255. assertFunction (fun) {
  256. this.pushMap();
  257. fun.formalParameters.forEach(formalParam => {
  258. if(formalParam.type instanceof CompoundType) {
  259. if(formalParam.type.dimensions > 1) {
  260. this.insertSymbol(formalParam.id, {id: formalParam.id, lines: -1, columns: -1, type: formalParam.type});
  261. } else {
  262. this.insertSymbol(formalParam.id, {id: formalParam.id, lines: -1, columns: null, type: formalParam.type});
  263. }
  264. } else {
  265. this.insertSymbol(formalParam.id, {id: formalParam.id, type: formalParam.type});
  266. }
  267. })
  268. this.assertDeclarations(fun.variablesDeclarations);
  269. const optional = fun.returnType.isCompatible(Types.VOID);
  270. const valid = this.assertReturn(fun, optional);
  271. if (!valid) {
  272. throw new Error("function has no accessible return");
  273. }
  274. this.popMap();
  275. }
  276. assertReturn (fun, optional) {
  277. return fun.commands.reduce(
  278. (last, next) => this.checkCommand(fun.returnType, next, optional) || last, optional
  279. );
  280. }
  281. checkCommand (type, cmd, optional) {
  282. if (cmd instanceof While) {
  283. const resultType = this.evaluateExpressionType(cmd.expression);
  284. if (!resultType.isCompatible(Types.BOOLEAN)) {
  285. throw new Error("condition not boolean");
  286. }
  287. this.checkCommands(type, cmd.commands, optional);
  288. return false;
  289. } else if (cmd instanceof For) {
  290. this.checkCommand(type, cmd.assignment, optional);
  291. const resultType = this.evaluateExpressionType(cmd.condition);
  292. if (!resultType.isCompatible(Types.BOOLEAN)) {
  293. throw new Error("condition not boolean");
  294. }
  295. this.checkCommand(type, cmd.increment, optional);
  296. this.checkCommands(type, cmd.commands, optional);
  297. return false;
  298. } else if (cmd instanceof Switch) {
  299. const sType = this.evaluateExpressionType(cmd.expression);
  300. let result = optional;
  301. let hasDefault = false;
  302. for (let i = 0; i < cmd.cases.length; i++) {
  303. const aCase = cmd.cases[i];
  304. if (aCase.expression !== null) {
  305. const caseType = this.evaluateExpressionType(aCase.expression);
  306. if (!sType.isCompatible(caseType)) {
  307. throw new Error("invalid type in case");
  308. }
  309. } else {
  310. hasDefault = true;
  311. }
  312. result = result && this.checkCommands(type, aCase.commands, result);
  313. }
  314. return result && hasDefault;
  315. } else if (cmd instanceof ArrayIndexAssign) {
  316. const typeInfo = this.findSymbol(cmd.id, this.symbolMap);
  317. if(!(typeInfo.type instanceof CompoundType)) {
  318. throw new Error(cmd.id + " is not an array.");
  319. }
  320. const exp = cmd.expression;
  321. const lineExp = cmd.line;
  322. const lineType = this.evaluateExpressionType(lineExp);
  323. if (!lineType.isCompatible(Types.INTEGER)) {
  324. throw new Error("array dimension must be of type int");
  325. }
  326. const columnExp = cmd.column;
  327. if (typeInfo.columns === null && columnExp !== null) {
  328. throw new Error(cmd.id + " is not a matrix");
  329. } else if (columnExp !== null) {
  330. const columnType = this.evaluateExpressionType(columnExp);
  331. if (!columnType.isCompatible(Types.INTEGER)) {
  332. throw new Error("array dimension must be of type int");
  333. }
  334. }
  335. // exp can be a arrayLiteral, a single value exp or an array access
  336. if(exp instanceof ArrayLiteral) {
  337. this.evaluateArrayLiteral(typeInfo.lines, (columnExp ? typeInfo.columns : null), typeInfo.type, exp);
  338. } else {
  339. // cannot properly evaluate since type system is poorly constructed
  340. }
  341. return optional;
  342. } else if (cmd instanceof Assign) {
  343. const typeInfo = this.findSymbol(cmd.id, this.symbolMap);
  344. const exp = cmd.expression;
  345. if(exp instanceof ArrayLiteral) {
  346. if(!(typeInfo.type instanceof CompoundType)) {
  347. throw new Error("type not compatible");
  348. }
  349. this.evaluateArrayLiteral(typeInfo.lines, typeInfo.columns, typeInfo.type, exp);
  350. } else {
  351. const resultType = this.evaluateExpressionType(exp);
  352. if(!resultType.isCompatible(typeInfo.type)) {
  353. throw new Error("type not compatible");
  354. }
  355. }
  356. return optional;
  357. } else if (cmd instanceof Break) {
  358. return optional;
  359. } else if (cmd instanceof IfThenElse) {
  360. const resultType = this.evaluateExpressionType(cmd.condition);
  361. if (!resultType.isCompatible(Types.BOOLEAN)) {
  362. throw new Error("condition not boolean");
  363. }
  364. if(cmd.ifFalse instanceof IfThenElse) {
  365. return this.checkCommands(type, cmd.ifTrue.commands, optional) && this.checkCommand(type, cmd.ifFalse, optional);
  366. } else {
  367. return this.checkCommands(type, cmd.ifTrue.commands, optional) && this.checkCommands(type, cmd.ifFalse.commands,optional);
  368. }
  369. } else if (cmd instanceof FunctionCall) {
  370. let fun = null;
  371. if (cmd.isMainCall) {
  372. fun = this.getMainFunction();
  373. } else {
  374. fun = this.findFunction(cmd.id);
  375. }
  376. this.assertParameters(fun, cmd.actualParameters);
  377. return optional;
  378. } else if (cmd instanceof Return) {
  379. if (cmd.expression === null && !type.isCompatible(Types.VOID)) {
  380. throw new Error('invalid return type');
  381. } else if (cmd.expression !== null) {
  382. const resultType = this.evaluateExpressionType(cmd.expression);
  383. if (!type.isCompatible(resultType)) {
  384. console.log(resultType);
  385. throw new Error('invalid return type');
  386. } else {
  387. return true;
  388. }
  389. } else {
  390. return true;
  391. }
  392. }
  393. }
  394. checkCommands (type, cmds, optional) {
  395. return cmds.reduce(
  396. (last, next) => this.checkCommand(type, next, optional) || last, optional
  397. );
  398. }
  399. assertParameters (fun, actualParametersList) {
  400. if (fun.formalParameters.length !== actualParametersList.length) {
  401. throw new Error("wrong number of parameters...");
  402. }
  403. for (let i = 0; i < actualParametersList.length; i++) {
  404. const param = actualParametersList[i];
  405. const formalParam = fun.formalParameters[i];
  406. if(formalParam.byRef) {
  407. if (!(param instanceof VariableLiteral || param instanceof ArrayAccess)) {
  408. throw new Error("Invalid param type for ref");
  409. }
  410. }
  411. const resultType = this.evaluateExpressionType(param);
  412. if(resultType instanceof MultiType && formalParam.type instanceof MultiType) {
  413. let shared = 0
  414. for (let j = 0; j < resultType.types.length; j++) {
  415. const element = resultType.types[j];
  416. if(formalParam.type.types.indexOf(element) !== -1) {
  417. shared++;
  418. }
  419. }
  420. if(shared <= 0) {
  421. throw new Error(`Parameter ${formalParam.id} is not compatible with the value given.`);
  422. }
  423. } else if (resultType instanceof MultiType) {
  424. if(!resultType.isCompatible(formalParam.type)) {
  425. throw new Error(`Parameter ${formalParam.id} is not compatible with the value given.`);
  426. }
  427. } else if(!formalParam.type.isCompatible(resultType)) {
  428. console.log("####");
  429. console.log(resultType);
  430. console.log("####");
  431. console.log(formalParam.type);
  432. throw new Error(`Parameter ${formalParam.id} is not compatible with the value given.`);
  433. }
  434. }
  435. }
  436. }