semanticAnalyser.js 16 KB

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