typecheck.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  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 Statement::Kind::Match: {
  632. const auto& match = cast<Match>(*s);
  633. auto res = TypeCheckExp(match.Exp(), types, values);
  634. auto res_type = res.type;
  635. auto new_clauses =
  636. global_arena
  637. ->New<std::list<std::pair<const Pattern*, const Statement*>>>();
  638. for (auto& clause : *match.Clauses()) {
  639. new_clauses->push_back(TypecheckCase(res_type, clause.first,
  640. clause.second, types, values,
  641. ret_type, is_omitted_ret_type));
  642. }
  643. const Statement* new_s =
  644. global_arena->New<Match>(s->LineNumber(), res.exp, new_clauses);
  645. return TCStatement(new_s, types);
  646. }
  647. case Statement::Kind::While: {
  648. const auto& while_stmt = cast<While>(*s);
  649. auto cnd_res = TypeCheckExp(while_stmt.Cond(), types, values);
  650. ExpectType(s->LineNumber(), "condition of `while`",
  651. global_arena->New<BoolType>(), cnd_res.type);
  652. auto body_res = TypeCheckStmt(while_stmt.Body(), types, values, ret_type,
  653. is_omitted_ret_type);
  654. auto new_s =
  655. global_arena->New<While>(s->LineNumber(), cnd_res.exp, body_res.stmt);
  656. return TCStatement(new_s, types);
  657. }
  658. case Statement::Kind::Break:
  659. case Statement::Kind::Continue:
  660. return TCStatement(s, types);
  661. case Statement::Kind::Block: {
  662. auto stmt_res = TypeCheckStmt(cast<Block>(*s).Stmt(), types, values,
  663. ret_type, is_omitted_ret_type);
  664. return TCStatement(
  665. global_arena->New<Block>(s->LineNumber(), stmt_res.stmt), types);
  666. }
  667. case Statement::Kind::VariableDefinition: {
  668. const auto& var = cast<VariableDefinition>(*s);
  669. auto res = TypeCheckExp(var.Init(), types, values);
  670. const Value* rhs_ty = res.type;
  671. auto lhs_res = TypeCheckPattern(var.Pat(), types, values, rhs_ty);
  672. const Statement* new_s = global_arena->New<VariableDefinition>(
  673. s->LineNumber(), var.Pat(), res.exp);
  674. return TCStatement(new_s, lhs_res.types);
  675. }
  676. case Statement::Kind::Sequence: {
  677. const auto& seq = cast<Sequence>(*s);
  678. auto stmt_res = TypeCheckStmt(seq.Stmt(), types, values, ret_type,
  679. is_omitted_ret_type);
  680. auto types2 = stmt_res.types;
  681. auto next_res = TypeCheckStmt(seq.Next(), types2, values, ret_type,
  682. is_omitted_ret_type);
  683. auto types3 = next_res.types;
  684. return TCStatement(global_arena->New<Sequence>(
  685. s->LineNumber(), stmt_res.stmt, next_res.stmt),
  686. types3);
  687. }
  688. case Statement::Kind::Assign: {
  689. const auto& assign = cast<Assign>(*s);
  690. auto rhs_res = TypeCheckExp(assign.Rhs(), types, values);
  691. auto rhs_t = rhs_res.type;
  692. auto lhs_res = TypeCheckExp(assign.Lhs(), types, values);
  693. auto lhs_t = lhs_res.type;
  694. ExpectType(s->LineNumber(), "assign", lhs_t, rhs_t);
  695. auto new_s =
  696. global_arena->New<Assign>(s->LineNumber(), lhs_res.exp, rhs_res.exp);
  697. return TCStatement(new_s, lhs_res.types);
  698. }
  699. case Statement::Kind::ExpressionStatement: {
  700. auto res =
  701. TypeCheckExp(cast<ExpressionStatement>(*s).Exp(), types, values);
  702. auto new_s =
  703. global_arena->New<ExpressionStatement>(s->LineNumber(), res.exp);
  704. return TCStatement(new_s, types);
  705. }
  706. case Statement::Kind::If: {
  707. const auto& if_stmt = cast<If>(*s);
  708. auto cnd_res = TypeCheckExp(if_stmt.Cond(), types, values);
  709. ExpectType(s->LineNumber(), "condition of `if`",
  710. global_arena->New<BoolType>(), cnd_res.type);
  711. auto then_res = TypeCheckStmt(if_stmt.ThenStmt(), types, values, ret_type,
  712. is_omitted_ret_type);
  713. auto else_res = TypeCheckStmt(if_stmt.ElseStmt(), types, values, ret_type,
  714. is_omitted_ret_type);
  715. auto new_s = global_arena->New<If>(s->LineNumber(), cnd_res.exp,
  716. then_res.stmt, else_res.stmt);
  717. return TCStatement(new_s, types);
  718. }
  719. case Statement::Kind::Return: {
  720. const auto& ret = cast<Return>(*s);
  721. auto res = TypeCheckExp(ret.Exp(), types, values);
  722. if (ret_type->Tag() == Value::Kind::AutoType) {
  723. // The following infers the return type from the first 'return'
  724. // statement. This will get more difficult with subtyping, when we
  725. // should infer the least-upper bound of all the 'return' statements.
  726. ret_type = res.type;
  727. } else {
  728. ExpectType(s->LineNumber(), "return", ret_type, res.type);
  729. }
  730. if (ret.IsOmittedExp() != is_omitted_ret_type) {
  731. FATAL_COMPILATION_ERROR(s->LineNumber())
  732. << *s << " should" << (is_omitted_ret_type ? " not" : "")
  733. << " provide a return value, to match the function's signature.";
  734. }
  735. return TCStatement(global_arena->New<Return>(s->LineNumber(), res.exp,
  736. ret.IsOmittedExp()),
  737. types);
  738. }
  739. case Statement::Kind::Continuation: {
  740. const auto& cont = cast<Continuation>(*s);
  741. TCStatement body_result = TypeCheckStmt(cont.Body(), types, values,
  742. ret_type, is_omitted_ret_type);
  743. const Statement* new_continuation = global_arena->New<Continuation>(
  744. s->LineNumber(), cont.ContinuationVariable(), body_result.stmt);
  745. types.Set(cont.ContinuationVariable(),
  746. global_arena->New<ContinuationType>());
  747. return TCStatement(new_continuation, types);
  748. }
  749. case Statement::Kind::Run: {
  750. TCExpression argument_result =
  751. TypeCheckExp(cast<Run>(*s).Argument(), types, values);
  752. ExpectType(s->LineNumber(), "argument of `run`",
  753. global_arena->New<ContinuationType>(), argument_result.type);
  754. const Statement* new_run =
  755. global_arena->New<Run>(s->LineNumber(), argument_result.exp);
  756. return TCStatement(new_run, types);
  757. }
  758. case Statement::Kind::Await: {
  759. // nothing to do here
  760. return TCStatement(s, types);
  761. }
  762. } // switch
  763. }
  764. static auto CheckOrEnsureReturn(const Statement* stmt, bool omitted_ret_type,
  765. int line_num) -> const Statement* {
  766. if (!stmt) {
  767. if (omitted_ret_type) {
  768. return global_arena->New<Return>(line_num, nullptr,
  769. /*is_omitted_exp=*/true);
  770. } else {
  771. FATAL_COMPILATION_ERROR(line_num)
  772. << "control-flow reaches end of function that provides a `->` return "
  773. "type without reaching a return statement";
  774. }
  775. }
  776. switch (stmt->Tag()) {
  777. case Statement::Kind::Match: {
  778. const auto& match = cast<Match>(*stmt);
  779. auto new_clauses =
  780. global_arena
  781. ->New<std::list<std::pair<const Pattern*, const Statement*>>>();
  782. for (const auto& clause : *match.Clauses()) {
  783. auto s = CheckOrEnsureReturn(clause.second, omitted_ret_type,
  784. stmt->LineNumber());
  785. new_clauses->push_back(std::make_pair(clause.first, s));
  786. }
  787. return global_arena->New<Match>(stmt->LineNumber(), match.Exp(),
  788. new_clauses);
  789. }
  790. case Statement::Kind::Block:
  791. return global_arena->New<Block>(
  792. stmt->LineNumber(),
  793. CheckOrEnsureReturn(cast<Block>(*stmt).Stmt(), omitted_ret_type,
  794. stmt->LineNumber()));
  795. case Statement::Kind::If: {
  796. const auto& if_stmt = cast<If>(*stmt);
  797. return global_arena->New<If>(
  798. stmt->LineNumber(), if_stmt.Cond(),
  799. CheckOrEnsureReturn(if_stmt.ThenStmt(), omitted_ret_type,
  800. stmt->LineNumber()),
  801. CheckOrEnsureReturn(if_stmt.ElseStmt(), omitted_ret_type,
  802. stmt->LineNumber()));
  803. }
  804. case Statement::Kind::Return:
  805. return stmt;
  806. case Statement::Kind::Sequence: {
  807. const auto& seq = cast<Sequence>(*stmt);
  808. if (seq.Next()) {
  809. return global_arena->New<Sequence>(
  810. stmt->LineNumber(), seq.Stmt(),
  811. CheckOrEnsureReturn(seq.Next(), omitted_ret_type,
  812. stmt->LineNumber()));
  813. } else {
  814. return CheckOrEnsureReturn(seq.Stmt(), omitted_ret_type,
  815. stmt->LineNumber());
  816. }
  817. }
  818. case Statement::Kind::Continuation:
  819. case Statement::Kind::Run:
  820. case Statement::Kind::Await:
  821. return stmt;
  822. case Statement::Kind::Assign:
  823. case Statement::Kind::ExpressionStatement:
  824. case Statement::Kind::While:
  825. case Statement::Kind::Break:
  826. case Statement::Kind::Continue:
  827. case Statement::Kind::VariableDefinition:
  828. if (omitted_ret_type) {
  829. return global_arena->New<Sequence>(
  830. stmt->LineNumber(), stmt,
  831. global_arena->New<Return>(line_num, nullptr,
  832. /*is_omitted_exp=*/true));
  833. } else {
  834. FATAL_COMPILATION_ERROR(stmt->LineNumber())
  835. << "control-flow reaches end of function that provides a `->` "
  836. "return type without reaching a return statement";
  837. }
  838. }
  839. }
  840. // TODO: factor common parts of TypeCheckFunDef and TypeOfFunDef into
  841. // a function.
  842. // TODO: Add checking to function definitions to ensure that
  843. // all deduced type parameters will be deduced.
  844. static auto TypeCheckFunDef(const FunctionDefinition* f, TypeEnv types,
  845. Env values) -> struct FunctionDefinition* {
  846. // Bring the deduced parameters into scope
  847. for (const auto& deduced : f->deduced_parameters) {
  848. // auto t = InterpExp(values, deduced.type);
  849. Address a = state->heap.AllocateValue(
  850. global_arena->New<VariableType>(deduced.name));
  851. values.Set(deduced.name, a);
  852. }
  853. // Type check the parameter pattern
  854. auto param_res = TypeCheckPattern(f->param_pattern, types, values, nullptr);
  855. // Evaluate the return type expression
  856. auto return_type = InterpPattern(values, f->return_type);
  857. if (f->name == "main") {
  858. ExpectType(f->line_num, "return type of `main`",
  859. global_arena->New<IntType>(), return_type);
  860. // TODO: Check that main doesn't have any parameters.
  861. }
  862. auto res = TypeCheckStmt(f->body, param_res.types, values, return_type,
  863. f->is_omitted_return_type);
  864. auto body =
  865. CheckOrEnsureReturn(res.stmt, f->is_omitted_return_type, f->line_num);
  866. return global_arena->New<FunctionDefinition>(
  867. f->line_num, f->name, f->deduced_parameters, f->param_pattern,
  868. global_arena->New<ExpressionPattern>(ReifyType(return_type, f->line_num)),
  869. /*is_omitted_return_type=*/false, body);
  870. }
  871. static auto TypeOfFunDef(TypeEnv types, Env values,
  872. const FunctionDefinition* fun_def) -> const Value* {
  873. // Bring the deduced parameters into scope
  874. for (const auto& deduced : fun_def->deduced_parameters) {
  875. // auto t = InterpExp(values, deduced.type);
  876. Address a = state->heap.AllocateValue(
  877. global_arena->New<VariableType>(deduced.name));
  878. values.Set(deduced.name, a);
  879. }
  880. // Type check the parameter pattern
  881. auto param_res =
  882. TypeCheckPattern(fun_def->param_pattern, types, values, nullptr);
  883. // Evaluate the return type expression
  884. auto ret = InterpPattern(values, fun_def->return_type);
  885. if (ret->Tag() == Value::Kind::AutoType) {
  886. auto f = TypeCheckFunDef(fun_def, types, values);
  887. ret = InterpPattern(values, f->return_type);
  888. }
  889. return global_arena->New<FunctionType>(fun_def->deduced_parameters,
  890. param_res.type, ret);
  891. }
  892. static auto TypeOfStructDef(const StructDefinition* sd, TypeEnv /*types*/,
  893. Env ct_top) -> const Value* {
  894. VarValues fields;
  895. VarValues methods;
  896. for (const Member* m : sd->members) {
  897. switch (m->Tag()) {
  898. case Member::Kind::FieldMember: {
  899. const BindingPattern* binding = cast<FieldMember>(*m).Binding();
  900. if (!binding->Name().has_value()) {
  901. FATAL_COMPILATION_ERROR(binding->LineNumber())
  902. << "Struct members must have names";
  903. }
  904. const Expression* type_expression =
  905. dyn_cast<ExpressionPattern>(binding->Type())->Expression();
  906. if (type_expression == nullptr) {
  907. FATAL_COMPILATION_ERROR(binding->LineNumber())
  908. << "Struct members must have explicit types";
  909. }
  910. auto type = InterpExp(ct_top, type_expression);
  911. fields.push_back(std::make_pair(*binding->Name(), type));
  912. break;
  913. }
  914. }
  915. }
  916. return global_arena->New<StructType>(sd->name, std::move(fields),
  917. std::move(methods));
  918. }
  919. static auto GetName(const Declaration& d) -> const std::string& {
  920. switch (d.Tag()) {
  921. case Declaration::Kind::FunctionDeclaration:
  922. return cast<FunctionDeclaration>(d).Definition().name;
  923. case Declaration::Kind::StructDeclaration:
  924. return cast<StructDeclaration>(d).Definition().name;
  925. case Declaration::Kind::ChoiceDeclaration:
  926. return cast<ChoiceDeclaration>(d).Name();
  927. case Declaration::Kind::VariableDeclaration: {
  928. const BindingPattern* binding = cast<VariableDeclaration>(d).Binding();
  929. if (!binding->Name().has_value()) {
  930. FATAL_COMPILATION_ERROR(binding->LineNumber())
  931. << "Top-level variable declarations must have names";
  932. }
  933. return *binding->Name();
  934. }
  935. }
  936. }
  937. auto MakeTypeChecked(const Declaration& d, const TypeEnv& types,
  938. const Env& values) -> const Declaration* {
  939. switch (d.Tag()) {
  940. case Declaration::Kind::FunctionDeclaration:
  941. return global_arena->New<FunctionDeclaration>(*TypeCheckFunDef(
  942. &cast<FunctionDeclaration>(d).Definition(), types, values));
  943. case Declaration::Kind::StructDeclaration: {
  944. const StructDefinition& struct_def =
  945. cast<StructDeclaration>(d).Definition();
  946. std::list<Member*> fields;
  947. for (Member* m : struct_def.members) {
  948. switch (m->Tag()) {
  949. case Member::Kind::FieldMember:
  950. // TODO: Interpret the type expression and store the result.
  951. fields.push_back(m);
  952. break;
  953. }
  954. }
  955. return global_arena->New<StructDeclaration>(
  956. struct_def.line_num, struct_def.name, std::move(fields));
  957. }
  958. case Declaration::Kind::ChoiceDeclaration:
  959. // TODO
  960. return &d;
  961. case Declaration::Kind::VariableDeclaration: {
  962. const auto& var = cast<VariableDeclaration>(d);
  963. // Signals a type error if the initializing expression does not have
  964. // the declared type of the variable, otherwise returns this
  965. // declaration with annotated types.
  966. TCExpression type_checked_initializer =
  967. TypeCheckExp(var.Initializer(), types, values);
  968. const Expression* type =
  969. dyn_cast<ExpressionPattern>(var.Binding()->Type())->Expression();
  970. if (type == nullptr) {
  971. // TODO: consider adding support for `auto`
  972. FATAL_COMPILATION_ERROR(var.LineNumber())
  973. << "Type of a top-level variable must be an expression.";
  974. }
  975. const Value* declared_type = InterpExp(values, type);
  976. ExpectType(var.LineNumber(), "initializer of variable", declared_type,
  977. type_checked_initializer.type);
  978. return &d;
  979. }
  980. }
  981. }
  982. static void TopLevel(const Declaration& d, TypeCheckContext* tops) {
  983. switch (d.Tag()) {
  984. case Declaration::Kind::FunctionDeclaration: {
  985. const FunctionDefinition& func_def =
  986. cast<FunctionDeclaration>(d).Definition();
  987. auto t = TypeOfFunDef(tops->types, tops->values, &func_def);
  988. tops->types.Set(func_def.name, t);
  989. InitEnv(d, &tops->values);
  990. break;
  991. }
  992. case Declaration::Kind::StructDeclaration: {
  993. const StructDefinition& struct_def =
  994. cast<StructDeclaration>(d).Definition();
  995. auto st = TypeOfStructDef(&struct_def, tops->types, tops->values);
  996. Address a = state->heap.AllocateValue(st);
  997. tops->values.Set(struct_def.name, a); // Is this obsolete?
  998. std::vector<TupleElement> field_types;
  999. for (const auto& [field_name, field_value] :
  1000. cast<StructType>(*st).Fields()) {
  1001. field_types.push_back({.name = field_name, .value = field_value});
  1002. }
  1003. auto fun_ty = global_arena->New<FunctionType>(
  1004. std::vector<GenericBinding>(),
  1005. global_arena->New<TupleValue>(std::move(field_types)), st);
  1006. tops->types.Set(struct_def.name, fun_ty);
  1007. break;
  1008. }
  1009. case Declaration::Kind::ChoiceDeclaration: {
  1010. const auto& choice = cast<ChoiceDeclaration>(d);
  1011. VarValues alts;
  1012. for (const auto& [name, signature] : choice.Alternatives()) {
  1013. auto t = InterpExp(tops->values, signature);
  1014. alts.push_back(std::make_pair(name, t));
  1015. }
  1016. auto ct = global_arena->New<ChoiceType>(choice.Name(), std::move(alts));
  1017. Address a = state->heap.AllocateValue(ct);
  1018. tops->values.Set(choice.Name(), a); // Is this obsolete?
  1019. tops->types.Set(choice.Name(), ct);
  1020. break;
  1021. }
  1022. case Declaration::Kind::VariableDeclaration: {
  1023. const auto& var = cast<VariableDeclaration>(d);
  1024. // Associate the variable name with it's declared type in the
  1025. // compile-time symbol table.
  1026. const Expression* type =
  1027. cast<ExpressionPattern>(var.Binding()->Type())->Expression();
  1028. const Value* declared_type = InterpExp(tops->values, type);
  1029. tops->types.Set(*var.Binding()->Name(), declared_type);
  1030. break;
  1031. }
  1032. }
  1033. }
  1034. auto TopLevel(const std::list<const Declaration*>& fs) -> TypeCheckContext {
  1035. TypeCheckContext tops;
  1036. bool found_main = false;
  1037. for (auto const& d : fs) {
  1038. if (GetName(*d) == "main") {
  1039. found_main = true;
  1040. }
  1041. TopLevel(*d, &tops);
  1042. }
  1043. if (found_main == false) {
  1044. FATAL_COMPILATION_ERROR_NO_LINE()
  1045. << "program must contain a function named `main`";
  1046. }
  1047. return tops;
  1048. }
  1049. } // namespace Carbon