typecheck.cpp 44 KB

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