typecheck.cpp 46 KB

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