typecheck.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "executable_semantics/interpreter/typecheck.h"
  5. #include <algorithm>
  6. #include <iterator>
  7. #include <map>
  8. #include <set>
  9. #include <vector>
  10. #include "common/ostream.h"
  11. #include "executable_semantics/ast/function_definition.h"
  12. #include "executable_semantics/common/arena.h"
  13. #include "executable_semantics/common/error.h"
  14. #include "executable_semantics/common/tracing_flag.h"
  15. #include "executable_semantics/interpreter/interpreter.h"
  16. #include "executable_semantics/interpreter/value.h"
  17. #include "llvm/Support/Casting.h"
  18. using llvm::cast;
  19. using llvm::dyn_cast;
  20. namespace Carbon {
  21. static void ExpectType(int line_num, const std::string& context,
  22. const Value* expected, const Value* actual) {
  23. if (!TypeEqual(expected, actual)) {
  24. FATAL_COMPILATION_ERROR(line_num) << "type error in " << context << "\n"
  25. << "expected: " << *expected << "\n"
  26. << "actual: " << *actual;
  27. }
  28. }
  29. static void ExpectPointerType(int line_num, const std::string& context,
  30. const Value* actual) {
  31. if (actual->Tag() != Value::Kind::PointerType) {
  32. FATAL_COMPILATION_ERROR(line_num) << "type error in " << context << "\n"
  33. << "expected a pointer type\n"
  34. << "actual: " << *actual;
  35. }
  36. }
  37. // Reify type to type expression.
  38. static auto ReifyType(const Value* t, int line_num) -> const Expression* {
  39. switch (t->Tag()) {
  40. case Value::Kind::IntType:
  41. return Expression::MakeIntTypeLiteral(0);
  42. case Value::Kind::BoolType:
  43. return Expression::MakeBoolTypeLiteral(0);
  44. case Value::Kind::TypeType:
  45. return Expression::MakeTypeTypeLiteral(0);
  46. case Value::Kind::ContinuationType:
  47. return Expression::MakeContinuationTypeLiteral(0);
  48. case Value::Kind::FunctionType: {
  49. const auto& fn_type = cast<FunctionType>(*t);
  50. return Expression::MakeFunctionTypeLiteral(
  51. 0, ReifyType(fn_type.Param(), line_num),
  52. ReifyType(fn_type.Ret(), line_num),
  53. /*is_omitted_return_type=*/false);
  54. }
  55. case Value::Kind::TupleValue: {
  56. std::vector<FieldInitializer> args;
  57. for (const TupleElement& field : cast<TupleValue>(*t).Elements()) {
  58. args.push_back(
  59. FieldInitializer(field.name, ReifyType(field.value, line_num)));
  60. }
  61. return Expression::MakeTupleLiteral(0, args);
  62. }
  63. case Value::Kind::StructType:
  64. return Expression::MakeIdentifierExpression(0,
  65. cast<StructType>(*t).Name());
  66. case Value::Kind::ChoiceType:
  67. return Expression::MakeIdentifierExpression(0,
  68. cast<ChoiceType>(*t).Name());
  69. case Value::Kind::PointerType:
  70. return Expression::MakePrimitiveOperatorExpression(
  71. 0, Operator::Ptr,
  72. {ReifyType(cast<PointerType>(*t).Type(), line_num)});
  73. case Value::Kind::VariableType:
  74. return Expression::MakeIdentifierExpression(
  75. 0, cast<VariableType>(*t).Name());
  76. default:
  77. FATAL() << "expected a type, not " << *t;
  78. }
  79. }
  80. // Perform type argument deduction, matching the parameter type `param`
  81. // against the argument type `arg`. Whenever there is an VariableType
  82. // in the parameter type, it is deduced to be the corresponding type
  83. // inside the argument type.
  84. // The `deduced` parameter is an accumulator, that is, it holds the
  85. // results so-far.
  86. static auto ArgumentDeduction(int line_num, TypeEnv deduced, const Value* param,
  87. const Value* arg) -> TypeEnv {
  88. switch (param->Tag()) {
  89. case Value::Kind::VariableType: {
  90. const auto& var_type = cast<VariableType>(*param);
  91. std::optional<const Value*> d = deduced.Get(var_type.Name());
  92. if (!d) {
  93. deduced.Set(var_type.Name(), arg);
  94. } else {
  95. ExpectType(line_num, "argument deduction", *d, arg);
  96. }
  97. return deduced;
  98. }
  99. case Value::Kind::TupleValue: {
  100. if (arg->Tag() != Value::Kind::TupleValue) {
  101. ExpectType(line_num, "argument deduction", param, arg);
  102. }
  103. const auto& param_tup = cast<TupleValue>(*param);
  104. const auto& arg_tup = cast<TupleValue>(*arg);
  105. if (param_tup.Elements().size() != arg_tup.Elements().size()) {
  106. ExpectType(line_num, "argument deduction", param, arg);
  107. }
  108. for (size_t i = 0; i < param_tup.Elements().size(); ++i) {
  109. if (param_tup.Elements()[i].name != arg_tup.Elements()[i].name) {
  110. FATAL_COMPILATION_ERROR(line_num)
  111. << "mismatch in tuple names, " << param_tup.Elements()[i].name
  112. << " != " << arg_tup.Elements()[i].name;
  113. }
  114. deduced =
  115. ArgumentDeduction(line_num, deduced, param_tup.Elements()[i].value,
  116. arg_tup.Elements()[i].value);
  117. }
  118. return deduced;
  119. }
  120. case Value::Kind::FunctionType: {
  121. if (arg->Tag() != Value::Kind::FunctionType) {
  122. ExpectType(line_num, "argument deduction", param, arg);
  123. }
  124. const auto& param_fn = cast<FunctionType>(*param);
  125. const auto& arg_fn = cast<FunctionType>(*arg);
  126. // TODO: handle situation when arg has deduced parameters.
  127. deduced = ArgumentDeduction(line_num, deduced, param_fn.Param(),
  128. arg_fn.Param());
  129. deduced =
  130. ArgumentDeduction(line_num, deduced, param_fn.Ret(), arg_fn.Ret());
  131. return deduced;
  132. }
  133. case Value::Kind::PointerType: {
  134. if (arg->Tag() != Value::Kind::PointerType) {
  135. ExpectType(line_num, "argument deduction", param, arg);
  136. }
  137. return ArgumentDeduction(line_num, deduced,
  138. cast<PointerType>(*param).Type(),
  139. cast<PointerType>(*arg).Type());
  140. }
  141. // Nothing to do in the case for `auto`.
  142. case Value::Kind::AutoType: {
  143. return deduced;
  144. }
  145. // For the following cases, we check for type equality.
  146. case Value::Kind::ContinuationType:
  147. case Value::Kind::StructType:
  148. case Value::Kind::ChoiceType:
  149. case Value::Kind::IntType:
  150. case Value::Kind::BoolType:
  151. case Value::Kind::TypeType: {
  152. ExpectType(line_num, "argument deduction", param, arg);
  153. return deduced;
  154. }
  155. // The rest of these cases should never happen.
  156. case Value::Kind::IntValue:
  157. case Value::Kind::BoolValue:
  158. case Value::Kind::FunctionValue:
  159. case Value::Kind::PointerValue:
  160. case Value::Kind::StructValue:
  161. case Value::Kind::AlternativeValue:
  162. case Value::Kind::BindingPlaceholderValue:
  163. case Value::Kind::AlternativeConstructorValue:
  164. case Value::Kind::ContinuationValue:
  165. FATAL() << "In ArgumentDeduction: expected type, not value " << *param;
  166. }
  167. }
  168. static auto Substitute(TypeEnv dict, const Value* type) -> const Value* {
  169. switch (type->Tag()) {
  170. case Value::Kind::VariableType: {
  171. std::optional<const Value*> t =
  172. dict.Get(cast<VariableType>(*type).Name());
  173. if (!t) {
  174. return type;
  175. } else {
  176. return *t;
  177. }
  178. }
  179. case Value::Kind::TupleValue: {
  180. std::vector<TupleElement> elts;
  181. for (const auto& elt : cast<TupleValue>(*type).Elements()) {
  182. auto t = Substitute(dict, elt.value);
  183. elts.push_back({.name = elt.name, .value = t});
  184. }
  185. return global_arena->New<TupleValue>(elts);
  186. }
  187. case Value::Kind::FunctionType: {
  188. const auto& fn_type = cast<FunctionType>(*type);
  189. auto param = Substitute(dict, fn_type.Param());
  190. auto ret = Substitute(dict, fn_type.Ret());
  191. return global_arena->New<FunctionType>(std::vector<GenericBinding>(),
  192. param, ret);
  193. }
  194. case Value::Kind::PointerType: {
  195. return global_arena->New<PointerType>(
  196. Substitute(dict, cast<PointerType>(*type).Type()));
  197. }
  198. case Value::Kind::AutoType:
  199. case Value::Kind::IntType:
  200. case Value::Kind::BoolType:
  201. case Value::Kind::TypeType:
  202. case Value::Kind::StructType:
  203. case Value::Kind::ChoiceType:
  204. case Value::Kind::ContinuationType:
  205. return type;
  206. // The rest of these cases should never happen.
  207. case Value::Kind::IntValue:
  208. case Value::Kind::BoolValue:
  209. case Value::Kind::FunctionValue:
  210. case Value::Kind::PointerValue:
  211. case Value::Kind::StructValue:
  212. case Value::Kind::AlternativeValue:
  213. case Value::Kind::BindingPlaceholderValue:
  214. case Value::Kind::AlternativeConstructorValue:
  215. case Value::Kind::ContinuationValue:
  216. FATAL() << "In Substitute: expected type, not value " << *type;
  217. }
  218. }
  219. // The TypeCheckExp function performs semantic analysis on an expression.
  220. // It returns a new version of the expression, its type, and an
  221. // updated environment which are bundled into a TCResult object.
  222. // The purpose of the updated environment is
  223. // to bring pattern variables into scope, for example, in a match case.
  224. // The new version of the expression may include more information,
  225. // for example, the type arguments deduced for the type parameters of a
  226. // generic.
  227. //
  228. // e is the expression to be analyzed.
  229. // types maps variable names to the type of their run-time value.
  230. // values maps variable names to their compile-time values. It is not
  231. // directly used in this function but is passed to InterExp.
  232. auto TypeCheckExp(const Expression* e, TypeEnv types, Env values)
  233. -> TCExpression {
  234. if (tracing_output) {
  235. llvm::outs() << "checking expression " << *e << "\n";
  236. }
  237. switch (e->tag()) {
  238. case ExpressionKind::IndexExpression: {
  239. auto res = TypeCheckExp(e->GetIndexExpression().aggregate, types, values);
  240. auto t = res.type;
  241. switch (t->Tag()) {
  242. case Value::Kind::TupleValue: {
  243. auto i =
  244. cast<IntValue>(*InterpExp(values, e->GetIndexExpression().offset))
  245. .Val();
  246. std::string f = std::to_string(i);
  247. const Value* field_t = cast<TupleValue>(*t).FindField(f);
  248. if (field_t == nullptr) {
  249. FATAL_COMPILATION_ERROR(e->line_num)
  250. << "field " << f << " is not in the tuple " << *t;
  251. }
  252. auto new_e = Expression::MakeIndexExpression(
  253. e->line_num, res.exp, Expression::MakeIntLiteral(e->line_num, i));
  254. return TCExpression(new_e, field_t, res.types);
  255. }
  256. default:
  257. FATAL_COMPILATION_ERROR(e->line_num) << "expected a tuple";
  258. }
  259. }
  260. case ExpressionKind::TupleLiteral: {
  261. std::vector<FieldInitializer> new_args;
  262. std::vector<TupleElement> arg_types;
  263. auto new_types = types;
  264. int i = 0;
  265. for (auto arg = e->GetTupleLiteral().fields.begin();
  266. arg != e->GetTupleLiteral().fields.end(); ++arg, ++i) {
  267. auto arg_res = TypeCheckExp(arg->expression, new_types, values);
  268. new_types = arg_res.types;
  269. new_args.push_back(FieldInitializer(arg->name, arg_res.exp));
  270. arg_types.push_back({.name = arg->name, .value = arg_res.type});
  271. }
  272. auto tuple_e = Expression::MakeTupleLiteral(e->line_num, new_args);
  273. auto tuple_t = global_arena->New<TupleValue>(std::move(arg_types));
  274. return TCExpression(tuple_e, tuple_t, new_types);
  275. }
  276. case ExpressionKind::FieldAccessExpression: {
  277. auto res =
  278. TypeCheckExp(e->GetFieldAccessExpression().aggregate, types, values);
  279. auto t = res.type;
  280. switch (t->Tag()) {
  281. case Value::Kind::StructType: {
  282. const auto& t_struct = cast<StructType>(*t);
  283. // Search for a field
  284. for (auto& field : t_struct.Fields()) {
  285. if (e->GetFieldAccessExpression().field == field.first) {
  286. const Expression* new_e = Expression::MakeFieldAccessExpression(
  287. e->line_num, res.exp, e->GetFieldAccessExpression().field);
  288. return TCExpression(new_e, field.second, res.types);
  289. }
  290. }
  291. // Search for a method
  292. for (auto& method : t_struct.Methods()) {
  293. if (e->GetFieldAccessExpression().field == method.first) {
  294. const Expression* new_e = Expression::MakeFieldAccessExpression(
  295. e->line_num, res.exp, e->GetFieldAccessExpression().field);
  296. return TCExpression(new_e, method.second, res.types);
  297. }
  298. }
  299. FATAL_COMPILATION_ERROR(e->line_num)
  300. << "struct " << t_struct.Name() << " does not have a field named "
  301. << e->GetFieldAccessExpression().field;
  302. }
  303. case Value::Kind::TupleValue: {
  304. const auto& tup = cast<TupleValue>(*t);
  305. for (const TupleElement& field : tup.Elements()) {
  306. if (e->GetFieldAccessExpression().field == field.name) {
  307. auto new_e = Expression::MakeFieldAccessExpression(
  308. e->line_num, res.exp, e->GetFieldAccessExpression().field);
  309. return TCExpression(new_e, field.value, res.types);
  310. }
  311. }
  312. FATAL_COMPILATION_ERROR(e->line_num)
  313. << "tuple " << tup << " does not have a field named "
  314. << e->GetFieldAccessExpression().field;
  315. }
  316. case Value::Kind::ChoiceType: {
  317. const auto& choice = cast<ChoiceType>(*t);
  318. for (const auto& vt : choice.Alternatives()) {
  319. if (e->GetFieldAccessExpression().field == vt.first) {
  320. const Expression* new_e = Expression::MakeFieldAccessExpression(
  321. e->line_num, res.exp, e->GetFieldAccessExpression().field);
  322. auto fun_ty = global_arena->New<FunctionType>(
  323. std::vector<GenericBinding>(), vt.second, t);
  324. return TCExpression(new_e, fun_ty, res.types);
  325. }
  326. }
  327. FATAL_COMPILATION_ERROR(e->line_num)
  328. << "choice " << choice.Name() << " does not have a field named "
  329. << e->GetFieldAccessExpression().field;
  330. }
  331. default:
  332. FATAL_COMPILATION_ERROR(e->line_num)
  333. << "field access, expected a struct\n"
  334. << *e;
  335. }
  336. }
  337. case ExpressionKind::IdentifierExpression: {
  338. std::optional<const Value*> type =
  339. types.Get(e->GetIdentifierExpression().name);
  340. if (type) {
  341. return TCExpression(e, *type, types);
  342. } else {
  343. FATAL_COMPILATION_ERROR(e->line_num)
  344. << "could not find `" << e->GetIdentifierExpression().name << "`";
  345. }
  346. }
  347. case ExpressionKind::IntLiteral:
  348. return TCExpression(e, global_arena->New<IntType>(), types);
  349. case ExpressionKind::BoolLiteral:
  350. return TCExpression(e, global_arena->New<BoolType>(), types);
  351. case ExpressionKind::PrimitiveOperatorExpression: {
  352. std::vector<const Expression*> es;
  353. std::vector<const Value*> ts;
  354. auto new_types = types;
  355. for (const Expression* argument :
  356. e->GetPrimitiveOperatorExpression().arguments) {
  357. auto res = TypeCheckExp(argument, types, values);
  358. new_types = res.types;
  359. es.push_back(res.exp);
  360. ts.push_back(res.type);
  361. }
  362. auto new_e = Expression::MakePrimitiveOperatorExpression(
  363. e->line_num, e->GetPrimitiveOperatorExpression().op, es);
  364. switch (e->GetPrimitiveOperatorExpression().op) {
  365. case Operator::Neg:
  366. ExpectType(e->line_num, "negation", global_arena->New<IntType>(),
  367. ts[0]);
  368. return TCExpression(new_e, global_arena->New<IntType>(), new_types);
  369. case Operator::Add:
  370. ExpectType(e->line_num, "addition(1)", global_arena->New<IntType>(),
  371. ts[0]);
  372. ExpectType(e->line_num, "addition(2)", global_arena->New<IntType>(),
  373. ts[1]);
  374. return TCExpression(new_e, global_arena->New<IntType>(), new_types);
  375. case Operator::Sub:
  376. ExpectType(e->line_num, "subtraction(1)",
  377. global_arena->New<IntType>(), ts[0]);
  378. ExpectType(e->line_num, "subtraction(2)",
  379. global_arena->New<IntType>(), ts[1]);
  380. return TCExpression(new_e, global_arena->New<IntType>(), new_types);
  381. case Operator::Mul:
  382. ExpectType(e->line_num, "multiplication(1)",
  383. global_arena->New<IntType>(), ts[0]);
  384. ExpectType(e->line_num, "multiplication(2)",
  385. global_arena->New<IntType>(), ts[1]);
  386. return TCExpression(new_e, global_arena->New<IntType>(), new_types);
  387. case Operator::And:
  388. ExpectType(e->line_num, "&&(1)", global_arena->New<BoolType>(),
  389. ts[0]);
  390. ExpectType(e->line_num, "&&(2)", global_arena->New<BoolType>(),
  391. ts[1]);
  392. return TCExpression(new_e, global_arena->New<BoolType>(), new_types);
  393. case Operator::Or:
  394. ExpectType(e->line_num, "||(1)", global_arena->New<BoolType>(),
  395. ts[0]);
  396. ExpectType(e->line_num, "||(2)", global_arena->New<BoolType>(),
  397. ts[1]);
  398. return TCExpression(new_e, global_arena->New<BoolType>(), new_types);
  399. case Operator::Not:
  400. ExpectType(e->line_num, "!", global_arena->New<BoolType>(), ts[0]);
  401. return TCExpression(new_e, global_arena->New<BoolType>(), new_types);
  402. case Operator::Eq:
  403. ExpectType(e->line_num, "==", ts[0], ts[1]);
  404. return TCExpression(new_e, global_arena->New<BoolType>(), new_types);
  405. case Operator::Deref:
  406. ExpectPointerType(e->line_num, "*", ts[0]);
  407. return TCExpression(new_e, cast<PointerType>(*ts[0]).Type(),
  408. new_types);
  409. case Operator::Ptr:
  410. ExpectType(e->line_num, "*", global_arena->New<TypeType>(), ts[0]);
  411. return TCExpression(new_e, global_arena->New<TypeType>(), new_types);
  412. }
  413. break;
  414. }
  415. case ExpressionKind::CallExpression: {
  416. auto fun_res =
  417. TypeCheckExp(e->GetCallExpression().function, types, values);
  418. switch (fun_res.type->Tag()) {
  419. case Value::Kind::FunctionType: {
  420. const auto& fun_t = cast<FunctionType>(*fun_res.type);
  421. auto arg_res = TypeCheckExp(e->GetCallExpression().argument,
  422. fun_res.types, values);
  423. auto parameter_type = fun_t.Param();
  424. auto return_type = fun_t.Ret();
  425. if (!fun_t.Deduced().empty()) {
  426. auto deduced_args = ArgumentDeduction(e->line_num, TypeEnv(),
  427. parameter_type, arg_res.type);
  428. for (auto& deduced_param : fun_t.Deduced()) {
  429. // TODO: change the following to a CHECK once the real checking
  430. // has been added to the type checking of function signatures.
  431. if (!deduced_args.Get(deduced_param.name)) {
  432. FATAL_COMPILATION_ERROR(e->line_num)
  433. << "could not deduce type argument for type parameter "
  434. << deduced_param.name;
  435. }
  436. }
  437. parameter_type = Substitute(deduced_args, parameter_type);
  438. return_type = Substitute(deduced_args, return_type);
  439. } else {
  440. ExpectType(e->line_num, "call", parameter_type, arg_res.type);
  441. }
  442. auto new_e = Expression::MakeCallExpression(e->line_num, fun_res.exp,
  443. arg_res.exp);
  444. return TCExpression(new_e, return_type, arg_res.types);
  445. }
  446. default: {
  447. FATAL_COMPILATION_ERROR(e->line_num)
  448. << "in call, expected a function\n"
  449. << *e;
  450. }
  451. }
  452. break;
  453. }
  454. case ExpressionKind::FunctionTypeLiteral: {
  455. auto pt = InterpExp(values, e->GetFunctionTypeLiteral().parameter);
  456. auto rt = InterpExp(values, e->GetFunctionTypeLiteral().return_type);
  457. auto new_e = Expression::MakeFunctionTypeLiteral(
  458. e->line_num, ReifyType(pt, e->line_num), ReifyType(rt, e->line_num),
  459. /*is_omitted_return_type=*/false);
  460. return TCExpression(new_e, global_arena->New<TypeType>(), types);
  461. }
  462. case ExpressionKind::IntTypeLiteral:
  463. return TCExpression(e, global_arena->New<TypeType>(), types);
  464. case ExpressionKind::BoolTypeLiteral:
  465. return TCExpression(e, global_arena->New<TypeType>(), types);
  466. case ExpressionKind::TypeTypeLiteral:
  467. return TCExpression(e, global_arena->New<TypeType>(), types);
  468. case ExpressionKind::ContinuationTypeLiteral:
  469. return TCExpression(e, global_arena->New<TypeType>(), types);
  470. }
  471. }
  472. // Equivalent to TypeCheckExp, but operates on Patterns instead of Expressions.
  473. // `expected` is the type that this pattern is expected to have, if the
  474. // surrounding context gives us that information. Otherwise, it is null.
  475. auto TypeCheckPattern(const Pattern* p, TypeEnv types, Env values,
  476. const Value* expected) -> TCPattern {
  477. if (tracing_output) {
  478. llvm::outs() << "checking pattern, ";
  479. if (expected) {
  480. llvm::outs() << "expecting " << *expected;
  481. }
  482. llvm::outs() << ", " << *p << "\n";
  483. }
  484. switch (p->Tag()) {
  485. case Pattern::Kind::AutoPattern: {
  486. return {
  487. .pattern = p, .type = global_arena->New<TypeType>(), .types = types};
  488. }
  489. case Pattern::Kind::BindingPattern: {
  490. const auto& binding = cast<BindingPattern>(*p);
  491. const Value* type;
  492. switch (binding.Type()->Tag()) {
  493. case Pattern::Kind::AutoPattern: {
  494. if (expected == nullptr) {
  495. FATAL_COMPILATION_ERROR(binding.LineNumber())
  496. << "auto not allowed here";
  497. } else {
  498. type = expected;
  499. }
  500. break;
  501. }
  502. case Pattern::Kind::ExpressionPattern: {
  503. type = InterpExp(
  504. values, cast<ExpressionPattern>(binding.Type())->Expression());
  505. CHECK(type->Tag() != Value::Kind::AutoType);
  506. if (expected != nullptr) {
  507. ExpectType(binding.LineNumber(), "pattern variable", type,
  508. expected);
  509. }
  510. break;
  511. }
  512. case Pattern::Kind::TuplePattern:
  513. case Pattern::Kind::BindingPattern:
  514. case Pattern::Kind::AlternativePattern:
  515. FATAL_COMPILATION_ERROR(binding.LineNumber())
  516. << "Unsupported type pattern";
  517. }
  518. auto new_p = global_arena->New<BindingPattern>(
  519. binding.LineNumber(), binding.Name(),
  520. global_arena->New<ExpressionPattern>(
  521. ReifyType(type, binding.LineNumber())));
  522. if (binding.Name().has_value()) {
  523. types.Set(*binding.Name(), type);
  524. }
  525. return {.pattern = new_p, .type = type, .types = types};
  526. }
  527. case Pattern::Kind::TuplePattern: {
  528. const auto& tuple = cast<TuplePattern>(*p);
  529. std::vector<TuplePattern::Field> new_fields;
  530. std::vector<TupleElement> field_types;
  531. auto new_types = types;
  532. if (expected && expected->Tag() != Value::Kind::TupleValue) {
  533. FATAL_COMPILATION_ERROR(p->LineNumber()) << "didn't expect a tuple";
  534. }
  535. if (expected && tuple.Fields().size() !=
  536. cast<TupleValue>(*expected).Elements().size()) {
  537. FATAL_COMPILATION_ERROR(tuple.LineNumber())
  538. << "tuples of different length";
  539. }
  540. for (size_t i = 0; i < tuple.Fields().size(); ++i) {
  541. const TuplePattern::Field& field = tuple.Fields()[i];
  542. const Value* expected_field_type = nullptr;
  543. if (expected != nullptr) {
  544. const TupleElement& expected_element =
  545. cast<TupleValue>(*expected).Elements()[i];
  546. if (expected_element.name != field.name) {
  547. FATAL_COMPILATION_ERROR(tuple.LineNumber())
  548. << "field names do not match, expected "
  549. << expected_element.name << " but got " << field.name;
  550. }
  551. expected_field_type = expected_element.value;
  552. }
  553. auto field_result = TypeCheckPattern(field.pattern, new_types, values,
  554. expected_field_type);
  555. new_types = field_result.types;
  556. new_fields.push_back(
  557. TuplePattern::Field(field.name, field_result.pattern));
  558. field_types.push_back({.name = field.name, .value = field_result.type});
  559. }
  560. auto new_tuple =
  561. global_arena->New<TuplePattern>(tuple.LineNumber(), new_fields);
  562. auto tuple_t = global_arena->New<TupleValue>(std::move(field_types));
  563. return {.pattern = new_tuple, .type = tuple_t, .types = new_types};
  564. }
  565. case Pattern::Kind::AlternativePattern: {
  566. const auto& alternative = cast<AlternativePattern>(*p);
  567. const Value* choice_type = InterpExp(values, alternative.ChoiceType());
  568. if (choice_type->Tag() != Value::Kind::ChoiceType) {
  569. FATAL_COMPILATION_ERROR(alternative.LineNumber())
  570. << "alternative pattern does not name a choice type.";
  571. }
  572. if (expected != nullptr) {
  573. ExpectType(alternative.LineNumber(), "alternative pattern", expected,
  574. choice_type);
  575. }
  576. const Value* parameter_types =
  577. FindInVarValues(alternative.AlternativeName(),
  578. cast<ChoiceType>(*choice_type).Alternatives());
  579. if (parameter_types == nullptr) {
  580. FATAL_COMPILATION_ERROR(alternative.LineNumber())
  581. << "'" << alternative.AlternativeName()
  582. << "' is not an alternative of " << choice_type;
  583. }
  584. TCPattern arg_results = TypeCheckPattern(alternative.Arguments(), types,
  585. values, parameter_types);
  586. return {.pattern = global_arena->New<AlternativePattern>(
  587. alternative.LineNumber(),
  588. ReifyType(choice_type, alternative.LineNumber()),
  589. alternative.AlternativeName(),
  590. cast<TuplePattern>(arg_results.pattern)),
  591. .type = choice_type,
  592. .types = arg_results.types};
  593. }
  594. case Pattern::Kind::ExpressionPattern: {
  595. TCExpression result =
  596. TypeCheckExp(cast<ExpressionPattern>(p)->Expression(), types, values);
  597. return {.pattern = global_arena->New<ExpressionPattern>(result.exp),
  598. .type = result.type,
  599. .types = result.types};
  600. }
  601. }
  602. }
  603. static auto TypecheckCase(const Value* expected, const Pattern* pat,
  604. const Statement* body, TypeEnv types, Env values,
  605. const Value*& ret_type, bool is_omitted_ret_type)
  606. -> std::pair<const Pattern*, const Statement*> {
  607. auto pat_res = TypeCheckPattern(pat, types, values, expected);
  608. auto res =
  609. TypeCheckStmt(body, pat_res.types, values, ret_type, is_omitted_ret_type);
  610. return std::make_pair(pat, res.stmt);
  611. }
  612. // The TypeCheckStmt function performs semantic analysis on a statement.
  613. // It returns a new version of the statement and a new type environment.
  614. //
  615. // The ret_type parameter is used for analyzing return statements.
  616. // It is the declared return type of the enclosing function definition.
  617. // If the return type is "auto", then the return type is inferred from
  618. // the first return statement.
  619. auto TypeCheckStmt(const Statement* s, TypeEnv types, Env values,
  620. const Value*& ret_type, bool is_omitted_ret_type)
  621. -> TCStatement {
  622. if (!s) {
  623. return TCStatement(s, types);
  624. }
  625. switch (s->tag()) {
  626. case StatementKind::Match: {
  627. auto res = TypeCheckExp(s->GetMatch().exp, types, values);
  628. auto res_type = res.type;
  629. auto new_clauses =
  630. global_arena
  631. ->New<std::list<std::pair<const Pattern*, const Statement*>>>();
  632. for (auto& clause : *s->GetMatch().clauses) {
  633. new_clauses->push_back(TypecheckCase(res_type, clause.first,
  634. clause.second, types, values,
  635. ret_type, is_omitted_ret_type));
  636. }
  637. const Statement* new_s =
  638. Statement::MakeMatch(s->line_num, res.exp, new_clauses);
  639. return TCStatement(new_s, types);
  640. }
  641. case StatementKind::While: {
  642. auto cnd_res = TypeCheckExp(s->GetWhile().cond, types, values);
  643. ExpectType(s->line_num, "condition of `while`",
  644. global_arena->New<BoolType>(), cnd_res.type);
  645. auto body_res = TypeCheckStmt(s->GetWhile().body, types, values, ret_type,
  646. is_omitted_ret_type);
  647. auto new_s =
  648. Statement::MakeWhile(s->line_num, cnd_res.exp, body_res.stmt);
  649. return TCStatement(new_s, types);
  650. }
  651. case StatementKind::Break:
  652. case StatementKind::Continue:
  653. return TCStatement(s, types);
  654. case StatementKind::Block: {
  655. auto stmt_res = TypeCheckStmt(s->GetBlock().stmt, types, values, ret_type,
  656. is_omitted_ret_type);
  657. return TCStatement(Statement::MakeBlock(s->line_num, stmt_res.stmt),
  658. types);
  659. }
  660. case StatementKind::VariableDefinition: {
  661. auto res = TypeCheckExp(s->GetVariableDefinition().init, types, values);
  662. const Value* rhs_ty = res.type;
  663. auto lhs_res = TypeCheckPattern(s->GetVariableDefinition().pat, types,
  664. values, rhs_ty);
  665. const Statement* new_s = Statement::MakeVariableDefinition(
  666. s->line_num, s->GetVariableDefinition().pat, res.exp);
  667. return TCStatement(new_s, lhs_res.types);
  668. }
  669. case StatementKind::Sequence: {
  670. auto stmt_res = TypeCheckStmt(s->GetSequence().stmt, types, values,
  671. ret_type, is_omitted_ret_type);
  672. auto types2 = stmt_res.types;
  673. auto next_res = TypeCheckStmt(s->GetSequence().next, types2, values,
  674. ret_type, is_omitted_ret_type);
  675. auto types3 = next_res.types;
  676. return TCStatement(
  677. Statement::MakeSequence(s->line_num, stmt_res.stmt, next_res.stmt),
  678. types3);
  679. }
  680. case StatementKind::Assign: {
  681. auto rhs_res = TypeCheckExp(s->GetAssign().rhs, types, values);
  682. auto rhs_t = rhs_res.type;
  683. auto lhs_res = TypeCheckExp(s->GetAssign().lhs, types, values);
  684. auto lhs_t = lhs_res.type;
  685. ExpectType(s->line_num, "assign", lhs_t, rhs_t);
  686. auto new_s = Statement::MakeAssign(s->line_num, lhs_res.exp, rhs_res.exp);
  687. return TCStatement(new_s, lhs_res.types);
  688. }
  689. case StatementKind::ExpressionStatement: {
  690. auto res = TypeCheckExp(s->GetExpressionStatement().exp, types, values);
  691. auto new_s = Statement::MakeExpressionStatement(s->line_num, res.exp);
  692. return TCStatement(new_s, types);
  693. }
  694. case StatementKind::If: {
  695. auto cnd_res = TypeCheckExp(s->GetIf().cond, types, values);
  696. ExpectType(s->line_num, "condition of `if`",
  697. global_arena->New<BoolType>(), cnd_res.type);
  698. auto thn_res = TypeCheckStmt(s->GetIf().then_stmt, types, values,
  699. ret_type, is_omitted_ret_type);
  700. auto els_res = TypeCheckStmt(s->GetIf().else_stmt, types, values,
  701. ret_type, is_omitted_ret_type);
  702. auto new_s = Statement::MakeIf(s->line_num, cnd_res.exp, thn_res.stmt,
  703. els_res.stmt);
  704. return TCStatement(new_s, types);
  705. }
  706. case StatementKind::Return: {
  707. const auto& ret = s->GetReturn();
  708. auto res = TypeCheckExp(ret.exp, types, values);
  709. if (ret_type->Tag() == Value::Kind::AutoType) {
  710. // The following infers the return type from the first 'return'
  711. // statement. This will get more difficult with subtyping, when we
  712. // should infer the least-upper bound of all the 'return' statements.
  713. ret_type = res.type;
  714. } else {
  715. ExpectType(s->line_num, "return", ret_type, res.type);
  716. }
  717. if (ret.is_omitted_exp != is_omitted_ret_type) {
  718. FATAL_COMPILATION_ERROR(s->line_num)
  719. << *s << " should" << (is_omitted_ret_type ? " not" : "")
  720. << " provide a return value, to match the function's signature.";
  721. }
  722. return TCStatement(
  723. Statement::MakeReturn(s->line_num, res.exp, ret.is_omitted_exp),
  724. types);
  725. }
  726. case StatementKind::Continuation: {
  727. TCStatement body_result =
  728. TypeCheckStmt(s->GetContinuation().body, types, values, ret_type,
  729. is_omitted_ret_type);
  730. const Statement* new_continuation = Statement::MakeContinuation(
  731. s->line_num, s->GetContinuation().continuation_variable,
  732. body_result.stmt);
  733. types.Set(s->GetContinuation().continuation_variable,
  734. global_arena->New<ContinuationType>());
  735. return TCStatement(new_continuation, types);
  736. }
  737. case StatementKind::Run: {
  738. TCExpression argument_result =
  739. TypeCheckExp(s->GetRun().argument, types, values);
  740. ExpectType(s->line_num, "argument of `run`",
  741. global_arena->New<ContinuationType>(), argument_result.type);
  742. const Statement* new_run =
  743. Statement::MakeRun(s->line_num, argument_result.exp);
  744. return TCStatement(new_run, types);
  745. }
  746. case StatementKind::Await: {
  747. // nothing to do here
  748. return TCStatement(s, types);
  749. }
  750. } // switch
  751. }
  752. static auto CheckOrEnsureReturn(const Statement* stmt, bool omitted_ret_type,
  753. int line_num) -> const Statement* {
  754. if (!stmt) {
  755. if (omitted_ret_type) {
  756. return Statement::MakeReturn(line_num, nullptr,
  757. /*is_omitted_exp=*/true);
  758. } else {
  759. FATAL_COMPILATION_ERROR(line_num)
  760. << "control-flow reaches end of function that provides a `->` return "
  761. "type without reaching a return statement";
  762. }
  763. }
  764. switch (stmt->tag()) {
  765. case StatementKind::Match: {
  766. auto new_clauses =
  767. global_arena
  768. ->New<std::list<std::pair<const Pattern*, const Statement*>>>();
  769. for (auto i = stmt->GetMatch().clauses->begin();
  770. i != stmt->GetMatch().clauses->end(); ++i) {
  771. auto s =
  772. CheckOrEnsureReturn(i->second, omitted_ret_type, stmt->line_num);
  773. new_clauses->push_back(std::make_pair(i->first, s));
  774. }
  775. return Statement::MakeMatch(stmt->line_num, stmt->GetMatch().exp,
  776. new_clauses);
  777. }
  778. case StatementKind::Block:
  779. return Statement::MakeBlock(
  780. stmt->line_num,
  781. CheckOrEnsureReturn(stmt->GetBlock().stmt, omitted_ret_type,
  782. stmt->line_num));
  783. case StatementKind::If:
  784. return Statement::MakeIf(
  785. stmt->line_num, stmt->GetIf().cond,
  786. CheckOrEnsureReturn(stmt->GetIf().then_stmt, omitted_ret_type,
  787. stmt->line_num),
  788. CheckOrEnsureReturn(stmt->GetIf().else_stmt, omitted_ret_type,
  789. stmt->line_num));
  790. case StatementKind::Return:
  791. return stmt;
  792. case StatementKind::Sequence:
  793. if (stmt->GetSequence().next) {
  794. return Statement::MakeSequence(
  795. stmt->line_num, stmt->GetSequence().stmt,
  796. CheckOrEnsureReturn(stmt->GetSequence().next, omitted_ret_type,
  797. stmt->line_num));
  798. } else {
  799. return CheckOrEnsureReturn(stmt->GetSequence().stmt, omitted_ret_type,
  800. stmt->line_num);
  801. }
  802. case StatementKind::Continuation:
  803. case StatementKind::Run:
  804. case StatementKind::Await:
  805. return stmt;
  806. case StatementKind::Assign:
  807. case StatementKind::ExpressionStatement:
  808. case StatementKind::While:
  809. case StatementKind::Break:
  810. case StatementKind::Continue:
  811. case StatementKind::VariableDefinition:
  812. if (omitted_ret_type) {
  813. return Statement::MakeSequence(
  814. stmt->line_num, stmt,
  815. Statement::MakeReturn(line_num, nullptr,
  816. /*is_omitted_exp=*/true));
  817. } else {
  818. FATAL_COMPILATION_ERROR(stmt->line_num)
  819. << "control-flow reaches end of function that provides a `->` "
  820. "return type without reaching a return statement";
  821. }
  822. }
  823. }
  824. // TODO: factor common parts of TypeCheckFunDef and TypeOfFunDef into
  825. // a function.
  826. // TODO: Add checking to function definitions to ensure that
  827. // all deduced type parameters will be deduced.
  828. static auto TypeCheckFunDef(const FunctionDefinition* f, TypeEnv types,
  829. Env values) -> struct FunctionDefinition* {
  830. // Bring the deduced parameters into scope
  831. for (const auto& deduced : f->deduced_parameters) {
  832. // auto t = InterpExp(values, deduced.type);
  833. Address a = state->heap.AllocateValue(
  834. global_arena->New<VariableType>(deduced.name));
  835. values.Set(deduced.name, a);
  836. }
  837. // Type check the parameter pattern
  838. auto param_res = TypeCheckPattern(f->param_pattern, types, values, nullptr);
  839. // Evaluate the return type expression
  840. auto return_type = InterpPattern(values, f->return_type);
  841. if (f->name == "main") {
  842. ExpectType(f->line_num, "return type of `main`",
  843. global_arena->New<IntType>(), return_type);
  844. // TODO: Check that main doesn't have any parameters.
  845. }
  846. auto res = TypeCheckStmt(f->body, param_res.types, values, return_type,
  847. f->is_omitted_return_type);
  848. auto body =
  849. CheckOrEnsureReturn(res.stmt, f->is_omitted_return_type, f->line_num);
  850. return global_arena->New<FunctionDefinition>(
  851. f->line_num, f->name, f->deduced_parameters, f->param_pattern,
  852. global_arena->New<ExpressionPattern>(ReifyType(return_type, f->line_num)),
  853. /*is_omitted_return_type=*/false, body);
  854. }
  855. static auto TypeOfFunDef(TypeEnv types, Env values,
  856. const FunctionDefinition* fun_def) -> const Value* {
  857. // Bring the deduced parameters into scope
  858. for (const auto& deduced : fun_def->deduced_parameters) {
  859. // auto t = InterpExp(values, deduced.type);
  860. Address a = state->heap.AllocateValue(
  861. global_arena->New<VariableType>(deduced.name));
  862. values.Set(deduced.name, a);
  863. }
  864. // Type check the parameter pattern
  865. auto param_res =
  866. TypeCheckPattern(fun_def->param_pattern, types, values, nullptr);
  867. // Evaluate the return type expression
  868. auto ret = InterpPattern(values, fun_def->return_type);
  869. if (ret->Tag() == Value::Kind::AutoType) {
  870. auto f = TypeCheckFunDef(fun_def, types, values);
  871. ret = InterpPattern(values, f->return_type);
  872. }
  873. return global_arena->New<FunctionType>(fun_def->deduced_parameters,
  874. param_res.type, ret);
  875. }
  876. static auto TypeOfStructDef(const StructDefinition* sd, TypeEnv /*types*/,
  877. Env ct_top) -> const Value* {
  878. VarValues fields;
  879. VarValues methods;
  880. for (const Member* m : sd->members) {
  881. switch (m->tag()) {
  882. case MemberKind::FieldMember: {
  883. const BindingPattern* binding = m->GetFieldMember().binding;
  884. if (!binding->Name().has_value()) {
  885. FATAL_COMPILATION_ERROR(binding->LineNumber())
  886. << "Struct members must have names";
  887. }
  888. const Expression* type_expression =
  889. dyn_cast<ExpressionPattern>(binding->Type())->Expression();
  890. if (type_expression == nullptr) {
  891. FATAL_COMPILATION_ERROR(binding->LineNumber())
  892. << "Struct members must have explicit types";
  893. }
  894. auto type = InterpExp(ct_top, type_expression);
  895. fields.push_back(std::make_pair(*binding->Name(), type));
  896. break;
  897. }
  898. }
  899. }
  900. return global_arena->New<StructType>(sd->name, std::move(fields),
  901. std::move(methods));
  902. }
  903. static auto GetName(const Declaration& d) -> const std::string& {
  904. switch (d.Tag()) {
  905. case Declaration::Kind::FunctionDeclaration:
  906. return cast<FunctionDeclaration>(d).Definition().name;
  907. case Declaration::Kind::StructDeclaration:
  908. return cast<StructDeclaration>(d).Definition().name;
  909. case Declaration::Kind::ChoiceDeclaration:
  910. return cast<ChoiceDeclaration>(d).Name();
  911. case Declaration::Kind::VariableDeclaration: {
  912. const BindingPattern* binding = cast<VariableDeclaration>(d).Binding();
  913. if (!binding->Name().has_value()) {
  914. FATAL_COMPILATION_ERROR(binding->LineNumber())
  915. << "Top-level variable declarations must have names";
  916. }
  917. return *binding->Name();
  918. }
  919. }
  920. }
  921. auto MakeTypeChecked(const Declaration& d, const TypeEnv& types,
  922. const Env& values) -> const Declaration* {
  923. switch (d.Tag()) {
  924. case Declaration::Kind::FunctionDeclaration:
  925. return global_arena->New<FunctionDeclaration>(*TypeCheckFunDef(
  926. &cast<FunctionDeclaration>(d).Definition(), types, values));
  927. case Declaration::Kind::StructDeclaration: {
  928. const StructDefinition& struct_def =
  929. cast<StructDeclaration>(d).Definition();
  930. std::list<Member*> fields;
  931. for (Member* m : struct_def.members) {
  932. switch (m->tag()) {
  933. case MemberKind::FieldMember:
  934. // TODO: Interpret the type expression and store the result.
  935. fields.push_back(m);
  936. break;
  937. }
  938. }
  939. return global_arena->New<StructDeclaration>(
  940. struct_def.line_num, struct_def.name, std::move(fields));
  941. }
  942. case Declaration::Kind::ChoiceDeclaration:
  943. // TODO
  944. return &d;
  945. case Declaration::Kind::VariableDeclaration: {
  946. const auto& var = cast<VariableDeclaration>(d);
  947. // Signals a type error if the initializing expression does not have
  948. // the declared type of the variable, otherwise returns this
  949. // declaration with annotated types.
  950. TCExpression type_checked_initializer =
  951. TypeCheckExp(var.Initializer(), types, values);
  952. const Expression* type =
  953. dyn_cast<ExpressionPattern>(var.Binding()->Type())->Expression();
  954. if (type == nullptr) {
  955. // TODO: consider adding support for `auto`
  956. FATAL_COMPILATION_ERROR(var.LineNumber())
  957. << "Type of a top-level variable must be an expression.";
  958. }
  959. const Value* declared_type = InterpExp(values, type);
  960. ExpectType(var.LineNumber(), "initializer of variable", declared_type,
  961. type_checked_initializer.type);
  962. return &d;
  963. }
  964. }
  965. }
  966. static void TopLevel(const Declaration& d, TypeCheckContext* tops) {
  967. switch (d.Tag()) {
  968. case Declaration::Kind::FunctionDeclaration: {
  969. const FunctionDefinition& func_def =
  970. cast<FunctionDeclaration>(d).Definition();
  971. auto t = TypeOfFunDef(tops->types, tops->values, &func_def);
  972. tops->types.Set(func_def.name, t);
  973. InitEnv(d, &tops->values);
  974. break;
  975. }
  976. case Declaration::Kind::StructDeclaration: {
  977. const StructDefinition& struct_def =
  978. cast<StructDeclaration>(d).Definition();
  979. auto st = TypeOfStructDef(&struct_def, tops->types, tops->values);
  980. Address a = state->heap.AllocateValue(st);
  981. tops->values.Set(struct_def.name, a); // Is this obsolete?
  982. std::vector<TupleElement> field_types;
  983. for (const auto& [field_name, field_value] :
  984. cast<StructType>(*st).Fields()) {
  985. field_types.push_back({.name = field_name, .value = field_value});
  986. }
  987. auto fun_ty = global_arena->New<FunctionType>(
  988. std::vector<GenericBinding>(),
  989. global_arena->New<TupleValue>(std::move(field_types)), st);
  990. tops->types.Set(struct_def.name, fun_ty);
  991. break;
  992. }
  993. case Declaration::Kind::ChoiceDeclaration: {
  994. const auto& choice = cast<ChoiceDeclaration>(d);
  995. VarValues alts;
  996. for (const auto& [name, signature] : choice.Alternatives()) {
  997. auto t = InterpExp(tops->values, signature);
  998. alts.push_back(std::make_pair(name, t));
  999. }
  1000. auto ct = global_arena->New<ChoiceType>(choice.Name(), std::move(alts));
  1001. Address a = state->heap.AllocateValue(ct);
  1002. tops->values.Set(choice.Name(), a); // Is this obsolete?
  1003. tops->types.Set(choice.Name(), ct);
  1004. break;
  1005. }
  1006. case Declaration::Kind::VariableDeclaration: {
  1007. const auto& var = cast<VariableDeclaration>(d);
  1008. // Associate the variable name with it's declared type in the
  1009. // compile-time symbol table.
  1010. const Expression* type =
  1011. cast<ExpressionPattern>(var.Binding()->Type())->Expression();
  1012. const Value* declared_type = InterpExp(tops->values, type);
  1013. tops->types.Set(*var.Binding()->Name(), declared_type);
  1014. break;
  1015. }
  1016. }
  1017. }
  1018. auto TopLevel(const std::list<const Declaration*>& fs) -> TypeCheckContext {
  1019. TypeCheckContext tops;
  1020. bool found_main = false;
  1021. for (auto const& d : fs) {
  1022. if (GetName(*d) == "main") {
  1023. found_main = true;
  1024. }
  1025. TopLevel(*d, &tops);
  1026. }
  1027. if (found_main == false) {
  1028. FATAL_COMPILATION_ERROR_NO_LINE()
  1029. << "program must contain a function named `main`";
  1030. }
  1031. return tops;
  1032. }
  1033. } // namespace Carbon