typecheck.cpp 43 KB

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