typecheck.cpp 43 KB

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