typecheck.cpp 45 KB

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