semanticAnalyser.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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");
  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. return Types.UNDEFINED;
  186. }
  187. }
  188. evaluateArrayLiteral (lines, columns, type, literal) {
  189. if (literal instanceof ArrayLiteral) {
  190. if (columns === null) {
  191. // it's a vector...
  192. const dimType = this.evaluateExpressionType(lines);
  193. if (!dimType.isCompatible(Types.INTEGER)) {
  194. throw new Error("dim must be int");
  195. }
  196. if ((lines instanceof IntLiteral) && !lines.value.eq(literal.value.length)) {
  197. throw new Error("invalid array size");
  198. }
  199. literal.value.reduce((last, next) => {
  200. const eType = this.evaluateExpressionType(next);
  201. if (!last.canAccept(eType)) {
  202. throw new Error("invalid value type for array");
  203. }
  204. return last;
  205. }, type);
  206. return true;
  207. } else {
  208. const dimType = this.evaluateExpressionType(columns);
  209. if (!dimType.isCompatible(Types.INTEGER)) {
  210. throw new Error("dim must be int");
  211. }
  212. if ((columns instanceof IntLiteral) && !columns.value.eq(literal.value.length)) {
  213. throw new Error("invalid array size");
  214. }
  215. for (let i = 0; i < columns; i++) {
  216. const anotherArray = literal.value[i];
  217. this.evaluateArrayLiteral(lines, null, type, anotherArray)
  218. }
  219. }
  220. } else {
  221. const resultType = this.evaluateExpressionType(literal);
  222. if (!(resultType.type instanceof CompoundType)) {
  223. throw new Error("initial must be of type array");
  224. }
  225. if (!type.isCompatible(resultType.type)) {
  226. throw new Error("invalid array type");
  227. }
  228. return true;
  229. }
  230. }
  231. assertFunction (fun) {
  232. this.pushMap();
  233. this.assertDeclarations(fun.variablesDeclarations);
  234. const optional = fun.returnType.isCompatible(Types.VOID);
  235. const valid = this.assertReturn(fun, optional);
  236. if (!valid) {
  237. throw new Error("function has no accessible return");
  238. }
  239. this.popMap();
  240. }
  241. assertReturn (fun, optional) {
  242. return fun.commands.reduce(
  243. (last, next) => this.checkCommand(fun.returnType, next, optional) || last, optional
  244. );
  245. }
  246. checkCommand (type, cmd, optional) {
  247. if (cmd instanceof While) {
  248. const resultType = this.evaluateExpressionType(cmd.expression);
  249. if (!resultType.isCompatible(Types.BOOLEAN)) {
  250. throw new Error("condition not boolean");
  251. }
  252. this.checkCommands(type, cmd.commands, optional);
  253. return false;
  254. } else if (cmd instanceof For) {
  255. this.checkCommand(type, cmd.assignment, optional);
  256. const resultType = this.evaluateExpressionType(cmd.condition);
  257. if (!resultType.isCompatible(Types.BOOLEAN)) {
  258. throw new Error("condition not boolean");
  259. }
  260. this.checkCommand(type, cmd.increment, optional);
  261. this.checkCommands(type, cmd.commands, optional);
  262. return false;
  263. } else if (cmd instanceof Switch) {
  264. const sType = this.evaluateExpressionType(cmd.expression);
  265. let result = optional;
  266. let hasDefault = false;
  267. for (let i = 0; i < cmd.cases.length; i++) {
  268. const aCase = cmd.cases[i];
  269. if (aCase.expression !== null) {
  270. const caseType = this.evaluateExpressionType(aCase.expression);
  271. if (!sType.isCompatible(caseType)) {
  272. throw new Error("invalid type in case");
  273. }
  274. } else {
  275. hasDefault = true;
  276. }
  277. result = result && this.checkCommands(type, aCase.commands, result);
  278. }
  279. return result && hasDefault;
  280. } else if (cmd instanceof ArrayIndexAssign) {
  281. const typeInfo = this.findSymbol(cmd.id, this.symbolMap);
  282. if(!(typeInfo.type instanceof CompoundType)) {
  283. throw new Error(cmd.id + " is not an array.");
  284. }
  285. const exp = cmd.expression;
  286. const lineExp = cmd.line;
  287. const lineType = this.evaluateExpressionType(lineExp);
  288. if (!lineType.isCompatible(Types.INTEGER)) {
  289. throw new Error("array dimension must be of type int");
  290. }
  291. const columnExp = cmd.column;
  292. if (typeInfo.columns === null && columnExp !== null) {
  293. throw new Error(cmd.id + " is not a matrix");
  294. } else if (columnExp !== null) {
  295. const columnType = this.evaluateExpressionType(columnExp);
  296. if (!columnType.isCompatible(Types.INTEGER)) {
  297. throw new Error("array dimension must be of type int");
  298. }
  299. }
  300. // exp can be a arrayLiteral, a single value exp or an array access
  301. if(exp instanceof ArrayLiteral) {
  302. this.evaluateArrayLiteral(typeInfo.lines, (columnExp ? typeInfo.columns : null), typeInfo.type, exp);
  303. } else {
  304. // cannot properly evaluate since type system is poorly constructed
  305. }
  306. return optional;
  307. } else if (cmd instanceof Assign) {
  308. const typeInfo = this.findSymbol(cmd.id, this.symbolMap);
  309. const exp = cmd.expression;
  310. if(exp instanceof ArrayLiteral) {
  311. if(!(typeInfo.type instanceof CompoundType)) {
  312. throw new Error("type not compatible");
  313. }
  314. this.evaluateArrayLiteral(typeInfo.lines, typeInfo.columns, typeInfo.type, exp);
  315. } else {
  316. const resultType = this.evaluateExpressionType(exp);
  317. if(!resultType.isCompatible(typeInfo.type)) {
  318. throw new Error("type not compatible");
  319. }
  320. }
  321. return optional;
  322. } else if (cmd instanceof Break) {
  323. return optional;
  324. } else if (cmd instanceof IfThenElse) {
  325. const resultType = this.evaluateExpressionType(cmd.condition);
  326. if (!resultType.isCompatible(Types.BOOLEAN)) {
  327. throw new Error("condition not boolean");
  328. }
  329. if(cmd.ifFalse instanceof IfThenElse) {
  330. return this.checkCommands(type, cmd.ifTrue.commands, optional) && this.checkCommand(type, cmd.ifFalse, optional);
  331. } else {
  332. return this.checkCommands(type, cmd.ifTrue.commands, optional) && this.checkCommands(type, cmd.ifFalse.commands,optional);
  333. }
  334. } else if (cmd instanceof FunctionCall) {
  335. const fun = this.findFunction(cmd.id);
  336. this.assertParameters(fun, cmd.actualParameters);
  337. return optional;
  338. } else if (cmd instanceof Return) {
  339. if (cmd.expression === null && !type.isCompatible(Types.VOID)) {
  340. throw new Error('invalid return type');
  341. } else if (cmd.expression !== null) {
  342. const resultType = this.evaluateExpressionType(cmd.expression);
  343. if (!resultType.isCompatible(type)) {
  344. throw new Error('invalid return type');
  345. } else {
  346. return true;
  347. }
  348. } else {
  349. return true;
  350. }
  351. }
  352. }
  353. checkCommands (type, cmds, optional) {
  354. return cmds.reduce(
  355. (last, next) => this.checkCommand(type, next, optional) || last, optional
  356. );
  357. }
  358. assertParameters (fun, actualParametersList) {
  359. if (fun.formalParameters.length !== actualParametersList.length) {
  360. throw new Error("wrong number of parameters...");
  361. }
  362. for (let i = 0; i < actualParametersList.length; i++) {
  363. const param = actualParametersList[i];
  364. const formalParam = fun.formalParameters[i];
  365. if(formalParam.byRef) {
  366. if (!(param instanceof VariableLiteral || param instanceof ArrayAccess)) {
  367. throw new Error("Invalid param type for ref");
  368. }
  369. }
  370. const resultType = this.evaluateExpressionType(param);
  371. if(resultType instanceof MultiType && formalParam.type instanceof MultiType) {
  372. let shared = 0
  373. for (let j = 0; j < resultType.types.length; j++) {
  374. const element = resultType.types[j];
  375. if(formalParam.type.types.indexOf(element) !== -1) {
  376. shared++;
  377. }
  378. }
  379. if(shared <= 0) {
  380. throw new Error(`Parameter ${formalParam.id} is not compatible with the value given.`);
  381. }
  382. } else if (resultType instanceof MultiType) {
  383. if(!resultType.isCompatible(formalParam.type)) {
  384. throw new Error(`Parameter ${formalParam.id} is not compatible with the value given.`);
  385. }
  386. } else if(!formalParam.type.isCompatible(resultType)) {
  387. console.log("####");
  388. console.log(resultType);
  389. console.log("####");
  390. console.log(formalParam.type);
  391. throw new Error(`Parameter ${formalParam.id} is not compatible with the value given.`);
  392. }
  393. }
  394. }
  395. }