typecheck.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  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 <iostream>
  7. #include <iterator>
  8. #include <map>
  9. #include <set>
  10. #include <vector>
  11. #include "executable_semantics/ast/function_definition.h"
  12. #include "executable_semantics/interpreter/interpreter.h"
  13. namespace Carbon {
  14. void ExpectType(int line_num, const std::string& context, const Value* expected,
  15. const Value* actual) {
  16. if (!TypeEqual(expected, actual)) {
  17. std::cerr << line_num << ": type error in " << context << std::endl;
  18. std::cerr << "expected: ";
  19. PrintValue(expected, std::cerr);
  20. std::cerr << std::endl << "actual: ";
  21. PrintValue(actual, std::cerr);
  22. std::cerr << std::endl;
  23. exit(-1);
  24. }
  25. }
  26. void PrintErrorString(const std::string& s) { std::cerr << s; }
  27. void PrintTypeEnv(TypeEnv types, std::ostream& out) {
  28. for (const auto& [name, value] : types) {
  29. out << name << ": ";
  30. PrintValue(value, out);
  31. out << ", ";
  32. }
  33. }
  34. // Reify type to type expression.
  35. auto ReifyType(const Value* t, int line_num) -> const Expression* {
  36. switch (t->tag) {
  37. case ValKind::VarTV:
  38. return MakeVar(0, *t->u.var_type);
  39. case ValKind::IntTV:
  40. return MakeIntType(0);
  41. case ValKind::BoolTV:
  42. return MakeBoolType(0);
  43. case ValKind::TypeTV:
  44. return MakeTypeType(0);
  45. case ValKind::ContinuationTV:
  46. return MakeContinuationType(0);
  47. case ValKind::FunctionTV:
  48. return MakeFunType(0, ReifyType(t->u.fun_type.param, line_num),
  49. ReifyType(t->u.fun_type.ret, line_num));
  50. case ValKind::TupleV: {
  51. auto args = new std::vector<std::pair<std::string, const Expression*>>();
  52. for (auto& field : *t->u.tuple.elts) {
  53. args->push_back({field.first, ReifyType(state->ReadFromMemory(
  54. field.second, line_num),
  55. line_num)});
  56. }
  57. return MakeTuple(0, args);
  58. }
  59. case ValKind::StructTV:
  60. return MakeVar(0, *t->u.struct_type.name);
  61. case ValKind::ChoiceTV:
  62. return MakeVar(0, *t->u.choice_type.name);
  63. default:
  64. std::cerr << line_num << ": expected a type, not ";
  65. PrintValue(t, std::cerr);
  66. std::cerr << std::endl;
  67. exit(-1);
  68. }
  69. }
  70. // The TypeCheckExp function performs semantic analysis on an expression.
  71. // It returns a new version of the expression, its type, and an
  72. // updated environment which are bundled into a TCResult object.
  73. // The purpose of the updated environment is
  74. // to bring pattern variables into scope, for example, in a match case.
  75. // The new version of the expression may include more information,
  76. // for example, the type arguments deduced for the type parameters of a
  77. // generic.
  78. //
  79. // e is the expression to be analyzed.
  80. // types maps variable names to the type of their run-time value.
  81. // values maps variable names to their compile-time values. It is not
  82. // directly used in this function but is passed to InterExp.
  83. // expected is the type that this expression is expected to have.
  84. // This parameter is non-null when the expression is in a pattern context
  85. // and it is used to implement `auto`, otherwise it is null.
  86. // context says what kind of position this expression is nested in,
  87. // whether it's a position that expects a value, a pattern, or a type.
  88. auto TypeCheckExp(const Expression* e, TypeEnv types, Env values,
  89. const Value* expected, TCContext context) -> TCResult {
  90. switch (e->tag) {
  91. case ExpressionKind::PatternVariable: {
  92. if (context != TCContext::PatternContext) {
  93. std::cerr
  94. << e->line_num
  95. << ": compilation error, pattern variables are only allowed in "
  96. "pattern context"
  97. << std::endl;
  98. exit(-1);
  99. }
  100. auto t = InterpExp(values, e->u.pattern_variable.type);
  101. if (t->tag == ValKind::AutoTV) {
  102. if (expected == nullptr) {
  103. std::cerr << e->line_num
  104. << ": compilation error, auto not allowed here"
  105. << std::endl;
  106. exit(-1);
  107. } else {
  108. t = expected;
  109. }
  110. }
  111. auto new_e = MakeVarPat(e->line_num, *e->u.pattern_variable.name,
  112. ReifyType(t, e->line_num));
  113. types.Set(*e->u.pattern_variable.name, t);
  114. return TCResult(new_e, t, types);
  115. }
  116. case ExpressionKind::Index: {
  117. auto res = TypeCheckExp(e->u.get_field.aggregate, types, values, nullptr,
  118. TCContext::ValueContext);
  119. auto t = res.type;
  120. switch (t->tag) {
  121. case ValKind::TupleV: {
  122. auto i = ToInteger(InterpExp(values, e->u.index.offset));
  123. std::string f = std::to_string(i);
  124. std::optional<Address> field_address = FindTupleField(f, t);
  125. if (field_address == std::nullopt) {
  126. std::cerr << e->line_num << ": compilation error, field " << f
  127. << " is not in the tuple ";
  128. PrintValue(t, std::cerr);
  129. std::cerr << std::endl;
  130. exit(-1);
  131. }
  132. auto field_t = state->ReadFromMemory(*field_address, e->line_num);
  133. auto new_e = MakeIndex(e->line_num, res.exp, MakeInt(e->line_num, i));
  134. return TCResult(new_e, field_t, res.types);
  135. }
  136. default:
  137. std::cerr << e->line_num << ": compilation error, expected a tuple"
  138. << std::endl;
  139. exit(-1);
  140. }
  141. }
  142. case ExpressionKind::Tuple: {
  143. auto new_args =
  144. new std::vector<std::pair<std::string, const Expression*>>();
  145. auto arg_types = new std::vector<std::pair<std::string, Address>>();
  146. auto new_types = types;
  147. int i = 0;
  148. for (auto arg = e->u.tuple.fields->begin();
  149. arg != e->u.tuple.fields->end(); ++arg, ++i) {
  150. const Value* arg_expected = nullptr;
  151. if (expected && expected->tag == ValKind::TupleV) {
  152. std::optional<Address> expected_field =
  153. FindTupleField(arg->first, expected);
  154. if (expected_field == std::nullopt) {
  155. std::cerr << e->line_num << ": compilation error, missing field "
  156. << arg->first << std::endl;
  157. exit(-1);
  158. }
  159. arg_expected = state->ReadFromMemory(*expected_field, e->line_num);
  160. }
  161. auto arg_res =
  162. TypeCheckExp(arg->second, new_types, values, arg_expected, context);
  163. new_types = arg_res.types;
  164. new_args->push_back(std::make_pair(arg->first, arg_res.exp));
  165. arg_types->push_back({arg->first, state->AllocateValue(arg_res.type)});
  166. }
  167. auto tuple_e = MakeTuple(e->line_num, new_args);
  168. auto tuple_t = MakeTupleVal(arg_types);
  169. return TCResult(tuple_e, tuple_t, new_types);
  170. }
  171. case ExpressionKind::GetField: {
  172. auto res = TypeCheckExp(e->u.get_field.aggregate, types, values, nullptr,
  173. TCContext::ValueContext);
  174. auto t = res.type;
  175. switch (t->tag) {
  176. case ValKind::StructTV:
  177. // Search for a field
  178. for (auto& field : *t->u.struct_type.fields) {
  179. if (*e->u.get_field.field == field.first) {
  180. const Expression* new_e =
  181. MakeGetField(e->line_num, res.exp, *e->u.get_field.field);
  182. return TCResult(new_e, field.second, res.types);
  183. }
  184. }
  185. // Search for a method
  186. for (auto& method : *t->u.struct_type.methods) {
  187. if (*e->u.get_field.field == method.first) {
  188. const Expression* new_e =
  189. MakeGetField(e->line_num, res.exp, *e->u.get_field.field);
  190. return TCResult(new_e, method.second, res.types);
  191. }
  192. }
  193. std::cerr << e->line_num << ": compilation error, struct "
  194. << *t->u.struct_type.name << " does not have a field named "
  195. << *e->u.get_field.field << std::endl;
  196. exit(-1);
  197. case ValKind::TupleV:
  198. for (auto& field : *t->u.tuple.elts) {
  199. if (*e->u.get_field.field == field.first) {
  200. auto new_e =
  201. MakeGetField(e->line_num, res.exp, *e->u.get_field.field);
  202. return TCResult(new_e,
  203. state->ReadFromMemory(field.second, e->line_num),
  204. res.types);
  205. }
  206. }
  207. std::cerr << e->line_num << ": compilation error, struct "
  208. << *t->u.struct_type.name << " does not have a field named "
  209. << *e->u.get_field.field << std::endl;
  210. exit(-1);
  211. case ValKind::ChoiceTV:
  212. for (auto vt = t->u.choice_type.alternatives->begin();
  213. vt != t->u.choice_type.alternatives->end(); ++vt) {
  214. if (*e->u.get_field.field == vt->first) {
  215. const Expression* new_e =
  216. MakeGetField(e->line_num, res.exp, *e->u.get_field.field);
  217. auto fun_ty = MakeFunTypeVal(vt->second, t);
  218. return TCResult(new_e, fun_ty, res.types);
  219. }
  220. }
  221. std::cerr << e->line_num << ": compilation error, struct "
  222. << *t->u.struct_type.name << " does not have a field named "
  223. << *e->u.get_field.field << std::endl;
  224. exit(-1);
  225. default:
  226. std::cerr << e->line_num
  227. << ": compilation error in field access, expected a struct"
  228. << std::endl;
  229. PrintExp(e);
  230. std::cerr << std::endl;
  231. exit(-1);
  232. }
  233. }
  234. case ExpressionKind::Variable: {
  235. std::optional<const Value*> type = types.Get(*(e->u.variable.name));
  236. if (type) {
  237. return TCResult(e, *type, types);
  238. } else {
  239. std::cerr << e->line_num << ": could not find `"
  240. << *(e->u.variable.name) << "`" << std::endl;
  241. exit(-1);
  242. }
  243. }
  244. case ExpressionKind::Integer:
  245. return TCResult(e, MakeIntTypeVal(), types);
  246. case ExpressionKind::Boolean:
  247. return TCResult(e, MakeBoolTypeVal(), types);
  248. case ExpressionKind::PrimitiveOp: {
  249. auto es = new std::vector<const Expression*>();
  250. std::vector<const Value*> ts;
  251. auto new_types = types;
  252. for (auto& argument : *e->u.primitive_op.arguments) {
  253. auto res = TypeCheckExp(argument, types, values, nullptr,
  254. TCContext::ValueContext);
  255. new_types = res.types;
  256. es->push_back(res.exp);
  257. ts.push_back(res.type);
  258. }
  259. auto new_e = MakeOp(e->line_num, e->u.primitive_op.op, es);
  260. switch (e->u.primitive_op.op) {
  261. case Operator::Neg:
  262. ExpectType(e->line_num, "negation", MakeIntTypeVal(), ts[0]);
  263. return TCResult(new_e, MakeIntTypeVal(), new_types);
  264. case Operator::Add:
  265. case Operator::Sub:
  266. ExpectType(e->line_num, "subtraction(1)", MakeIntTypeVal(), ts[0]);
  267. ExpectType(e->line_num, "substration(2)", MakeIntTypeVal(), ts[1]);
  268. return TCResult(new_e, MakeIntTypeVal(), new_types);
  269. case Operator::And:
  270. ExpectType(e->line_num, "&&(1)", MakeBoolTypeVal(), ts[0]);
  271. ExpectType(e->line_num, "&&(2)", MakeBoolTypeVal(), ts[1]);
  272. return TCResult(new_e, MakeBoolTypeVal(), new_types);
  273. case Operator::Or:
  274. ExpectType(e->line_num, "||(1)", MakeBoolTypeVal(), ts[0]);
  275. ExpectType(e->line_num, "||(2)", MakeBoolTypeVal(), ts[1]);
  276. return TCResult(new_e, MakeBoolTypeVal(), new_types);
  277. case Operator::Not:
  278. ExpectType(e->line_num, "!", MakeBoolTypeVal(), ts[0]);
  279. return TCResult(new_e, MakeBoolTypeVal(), new_types);
  280. case Operator::Eq:
  281. ExpectType(e->line_num, "==(1)", MakeIntTypeVal(), ts[0]);
  282. ExpectType(e->line_num, "==(2)", MakeIntTypeVal(), ts[1]);
  283. return TCResult(new_e, MakeBoolTypeVal(), new_types);
  284. }
  285. break;
  286. }
  287. case ExpressionKind::Call: {
  288. auto fun_res = TypeCheckExp(e->u.call.function, types, values, nullptr,
  289. TCContext::ValueContext);
  290. switch (fun_res.type->tag) {
  291. case ValKind::FunctionTV: {
  292. auto fun_t = fun_res.type;
  293. auto arg_res = TypeCheckExp(e->u.call.argument, fun_res.types, values,
  294. fun_t->u.fun_type.param, context);
  295. ExpectType(e->line_num, "call", fun_t->u.fun_type.param,
  296. arg_res.type);
  297. auto new_e = MakeCall(e->line_num, fun_res.exp, arg_res.exp);
  298. return TCResult(new_e, fun_t->u.fun_type.ret, arg_res.types);
  299. }
  300. default: {
  301. std::cerr << e->line_num
  302. << ": compilation error in call, expected a function"
  303. << std::endl;
  304. PrintExp(e);
  305. std::cerr << std::endl;
  306. exit(-1);
  307. }
  308. }
  309. break;
  310. }
  311. case ExpressionKind::FunctionT: {
  312. switch (context) {
  313. case TCContext::ValueContext:
  314. case TCContext::TypeContext: {
  315. auto pt = InterpExp(values, e->u.function_type.parameter);
  316. auto rt = InterpExp(values, e->u.function_type.return_type);
  317. auto new_e = MakeFunType(e->line_num, ReifyType(pt, e->line_num),
  318. ReifyType(rt, e->line_num));
  319. return TCResult(new_e, MakeTypeTypeVal(), types);
  320. }
  321. case TCContext::PatternContext: {
  322. auto param_res = TypeCheckExp(e->u.function_type.parameter, types,
  323. values, nullptr, context);
  324. auto ret_res =
  325. TypeCheckExp(e->u.function_type.return_type, param_res.types,
  326. values, nullptr, context);
  327. auto new_e =
  328. MakeFunType(e->line_num, ReifyType(param_res.type, e->line_num),
  329. ReifyType(ret_res.type, e->line_num));
  330. return TCResult(new_e, MakeTypeTypeVal(), ret_res.types);
  331. }
  332. }
  333. }
  334. case ExpressionKind::IntT:
  335. return TCResult(e, MakeIntTypeVal(), types);
  336. case ExpressionKind::BoolT:
  337. return TCResult(e, MakeBoolTypeVal(), types);
  338. case ExpressionKind::TypeT:
  339. return TCResult(e, MakeTypeTypeVal(), types);
  340. case ExpressionKind::AutoT:
  341. return TCResult(e, MakeAutoTypeVal(), types);
  342. case ExpressionKind::ContinuationT:
  343. return TCResult(e, MakeContinuationTypeVal(), types);
  344. }
  345. }
  346. auto TypecheckCase(const Value* expected, const Expression* pat,
  347. const Statement* body, TypeEnv types, Env values,
  348. const Value*& ret_type)
  349. -> std::pair<const Expression*, const Statement*> {
  350. auto pat_res =
  351. TypeCheckExp(pat, types, values, expected, TCContext::PatternContext);
  352. auto res = TypeCheckStmt(body, pat_res.types, values, ret_type);
  353. return std::make_pair(pat, res.stmt);
  354. }
  355. // The TypeCheckStmt function performs semantic analysis on a statement.
  356. // It returns a new version of the statement and a new type environment.
  357. //
  358. // The ret_type parameter is used for analyzing return statements.
  359. // It is the declared return type of the enclosing function definition.
  360. // If the return type is "auto", then the return type is inferred from
  361. // the first return statement.
  362. auto TypeCheckStmt(const Statement* s, TypeEnv types, Env values,
  363. const Value*& ret_type) -> TCStatement {
  364. if (!s) {
  365. return TCStatement(s, types);
  366. }
  367. switch (s->tag) {
  368. case StatementKind::Match: {
  369. auto res = TypeCheckExp(s->u.match_stmt.exp, types, values, nullptr,
  370. TCContext::ValueContext);
  371. auto res_type = res.type;
  372. auto new_clauses =
  373. new std::list<std::pair<const Expression*, const Statement*>>();
  374. for (auto& clause : *s->u.match_stmt.clauses) {
  375. new_clauses->push_back(TypecheckCase(
  376. res_type, clause.first, clause.second, types, values, ret_type));
  377. }
  378. const Statement* new_s = MakeMatch(s->line_num, res.exp, new_clauses);
  379. return TCStatement(new_s, types);
  380. }
  381. case StatementKind::While: {
  382. auto cnd_res = TypeCheckExp(s->u.while_stmt.cond, types, values, nullptr,
  383. TCContext::ValueContext);
  384. ExpectType(s->line_num, "condition of `while`", MakeBoolTypeVal(),
  385. cnd_res.type);
  386. auto body_res =
  387. TypeCheckStmt(s->u.while_stmt.body, types, values, ret_type);
  388. auto new_s = MakeWhile(s->line_num, cnd_res.exp, body_res.stmt);
  389. return TCStatement(new_s, types);
  390. }
  391. case StatementKind::Break:
  392. case StatementKind::Continue:
  393. return TCStatement(s, types);
  394. case StatementKind::Block: {
  395. auto stmt_res = TypeCheckStmt(s->u.block.stmt, types, values, ret_type);
  396. return TCStatement(MakeBlock(s->line_num, stmt_res.stmt), types);
  397. }
  398. case StatementKind::VariableDefinition: {
  399. auto res = TypeCheckExp(s->u.variable_definition.init, types, values,
  400. nullptr, TCContext::ValueContext);
  401. const Value* rhs_ty = res.type;
  402. auto lhs_res = TypeCheckExp(s->u.variable_definition.pat, types, values,
  403. rhs_ty, TCContext::PatternContext);
  404. const Statement* new_s =
  405. MakeVarDef(s->line_num, s->u.variable_definition.pat, res.exp);
  406. return TCStatement(new_s, lhs_res.types);
  407. }
  408. case StatementKind::Sequence: {
  409. auto stmt_res =
  410. TypeCheckStmt(s->u.sequence.stmt, types, values, ret_type);
  411. auto types2 = stmt_res.types;
  412. auto next_res =
  413. TypeCheckStmt(s->u.sequence.next, types2, values, ret_type);
  414. auto types3 = next_res.types;
  415. return TCStatement(MakeSeq(s->line_num, stmt_res.stmt, next_res.stmt),
  416. types3);
  417. }
  418. case StatementKind::Assign: {
  419. auto rhs_res = TypeCheckExp(s->u.assign.rhs, types, values, nullptr,
  420. TCContext::ValueContext);
  421. auto rhs_t = rhs_res.type;
  422. auto lhs_res = TypeCheckExp(s->u.assign.lhs, types, values, rhs_t,
  423. TCContext::ValueContext);
  424. auto lhs_t = lhs_res.type;
  425. ExpectType(s->line_num, "assign", lhs_t, rhs_t);
  426. auto new_s = MakeAssign(s->line_num, lhs_res.exp, rhs_res.exp);
  427. return TCStatement(new_s, lhs_res.types);
  428. }
  429. case StatementKind::ExpressionStatement: {
  430. auto res = TypeCheckExp(s->u.exp, types, values, nullptr,
  431. TCContext::ValueContext);
  432. auto new_s = MakeExpStmt(s->line_num, res.exp);
  433. return TCStatement(new_s, types);
  434. }
  435. case StatementKind::If: {
  436. auto cnd_res = TypeCheckExp(s->u.if_stmt.cond, types, values, nullptr,
  437. TCContext::ValueContext);
  438. ExpectType(s->line_num, "condition of `if`", MakeBoolTypeVal(),
  439. cnd_res.type);
  440. auto thn_res =
  441. TypeCheckStmt(s->u.if_stmt.then_stmt, types, values, ret_type);
  442. auto els_res =
  443. TypeCheckStmt(s->u.if_stmt.else_stmt, types, values, ret_type);
  444. auto new_s = MakeIf(s->line_num, cnd_res.exp, thn_res.stmt, els_res.stmt);
  445. return TCStatement(new_s, types);
  446. }
  447. case StatementKind::Return: {
  448. auto res = TypeCheckExp(s->u.return_stmt, types, values, nullptr,
  449. TCContext::ValueContext);
  450. if (ret_type->tag == ValKind::AutoTV) {
  451. // The following infers the return type from the first 'return'
  452. // statement. This will get more difficult with subtyping, when we
  453. // should infer the least-upper bound of all the 'return' statements.
  454. ret_type = res.type;
  455. } else {
  456. ExpectType(s->line_num, "return", ret_type, res.type);
  457. }
  458. return TCStatement(MakeReturn(s->line_num, res.exp), types);
  459. }
  460. case StatementKind::Continuation: {
  461. TCStatement body_result =
  462. TypeCheckStmt(s->u.continuation.body, types, values, ret_type);
  463. const Statement* new_continuation = MakeContinuationStatement(
  464. s->line_num, *s->u.continuation.continuation_variable,
  465. body_result.stmt);
  466. types.Set(*s->u.continuation.continuation_variable,
  467. MakeContinuationTypeVal());
  468. return TCStatement(new_continuation, types);
  469. }
  470. case StatementKind::Run: {
  471. TCResult argument_result = TypeCheckExp(s->u.run.argument, types, values,
  472. nullptr, TCContext::ValueContext);
  473. ExpectType(s->line_num, "argument of `run`", MakeContinuationTypeVal(),
  474. argument_result.type);
  475. const Statement* new_run = MakeRun(s->line_num, argument_result.exp);
  476. return TCStatement(new_run, types);
  477. }
  478. case StatementKind::Await: {
  479. // nothing to do here
  480. return TCStatement(s, types);
  481. }
  482. } // switch
  483. }
  484. auto CheckOrEnsureReturn(const Statement* stmt, bool void_return, int line_num)
  485. -> const Statement* {
  486. if (!stmt) {
  487. if (void_return) {
  488. auto args = new std::vector<std::pair<std::string, const Expression*>>();
  489. return MakeReturn(line_num, MakeTuple(line_num, args));
  490. } else {
  491. std::cerr
  492. << "control-flow reaches end of non-void function without a return"
  493. << std::endl;
  494. exit(-1);
  495. }
  496. }
  497. switch (stmt->tag) {
  498. case StatementKind::Match: {
  499. auto new_clauses =
  500. new std::list<std::pair<const Expression*, const Statement*>>();
  501. for (auto i = stmt->u.match_stmt.clauses->begin();
  502. i != stmt->u.match_stmt.clauses->end(); ++i) {
  503. auto s = CheckOrEnsureReturn(i->second, void_return, stmt->line_num);
  504. new_clauses->push_back(std::make_pair(i->first, s));
  505. }
  506. return MakeMatch(stmt->line_num, stmt->u.match_stmt.exp, new_clauses);
  507. }
  508. case StatementKind::Block:
  509. return MakeBlock(
  510. stmt->line_num,
  511. CheckOrEnsureReturn(stmt->u.block.stmt, void_return, stmt->line_num));
  512. case StatementKind::If:
  513. return MakeIf(stmt->line_num, stmt->u.if_stmt.cond,
  514. CheckOrEnsureReturn(stmt->u.if_stmt.then_stmt, void_return,
  515. stmt->line_num),
  516. CheckOrEnsureReturn(stmt->u.if_stmt.else_stmt, void_return,
  517. stmt->line_num));
  518. case StatementKind::Return:
  519. return stmt;
  520. case StatementKind::Sequence:
  521. if (stmt->u.sequence.next) {
  522. return MakeSeq(stmt->line_num, stmt->u.sequence.stmt,
  523. CheckOrEnsureReturn(stmt->u.sequence.next, void_return,
  524. stmt->line_num));
  525. } else {
  526. return CheckOrEnsureReturn(stmt->u.sequence.stmt, void_return,
  527. stmt->line_num);
  528. }
  529. case StatementKind::Continuation:
  530. case StatementKind::Run:
  531. case StatementKind::Await:
  532. return stmt;
  533. case StatementKind::Assign:
  534. case StatementKind::ExpressionStatement:
  535. case StatementKind::While:
  536. case StatementKind::Break:
  537. case StatementKind::Continue:
  538. case StatementKind::VariableDefinition:
  539. if (void_return) {
  540. auto args =
  541. new std::vector<std::pair<std::string, const Expression*>>();
  542. return MakeSeq(
  543. stmt->line_num, stmt,
  544. MakeReturn(stmt->line_num, MakeTuple(stmt->line_num, args)));
  545. } else {
  546. std::cerr
  547. << stmt->line_num
  548. << ": control-flow reaches end of non-void function without a "
  549. "return"
  550. << std::endl;
  551. exit(-1);
  552. }
  553. }
  554. }
  555. auto TypeCheckFunDef(const FunctionDefinition* f, TypeEnv types, Env values)
  556. -> struct FunctionDefinition* {
  557. auto param_res = TypeCheckExp(f->param_pattern, types, values, nullptr,
  558. TCContext::PatternContext);
  559. auto return_type = InterpExp(values, f->return_type);
  560. if (f->name == "main") {
  561. ExpectType(f->line_num, "return type of `main`", MakeIntTypeVal(),
  562. return_type);
  563. // TODO: Check that main doesn't have any parameters.
  564. }
  565. auto res = TypeCheckStmt(f->body, param_res.types, values, return_type);
  566. bool void_return = TypeEqual(return_type, MakeVoidTypeVal());
  567. auto body = CheckOrEnsureReturn(res.stmt, void_return, f->line_num);
  568. return MakeFunDef(f->line_num, f->name, ReifyType(return_type, f->line_num),
  569. f->param_pattern, body);
  570. }
  571. auto TypeOfFunDef(TypeEnv types, Env values, const FunctionDefinition* fun_def)
  572. -> const Value* {
  573. auto param_res = TypeCheckExp(fun_def->param_pattern, types, values, nullptr,
  574. TCContext::PatternContext);
  575. auto ret = InterpExp(values, fun_def->return_type);
  576. if (ret->tag == ValKind::AutoTV) {
  577. auto f = TypeCheckFunDef(fun_def, types, values);
  578. ret = InterpExp(values, f->return_type);
  579. }
  580. return MakeFunTypeVal(param_res.type, ret);
  581. }
  582. auto TypeOfStructDef(const StructDefinition* sd, TypeEnv /*types*/, Env ct_top)
  583. -> const Value* {
  584. auto fields = new VarValues();
  585. auto methods = new VarValues();
  586. for (auto m = sd->members->begin(); m != sd->members->end(); ++m) {
  587. if ((*m)->tag == MemberKind::FieldMember) {
  588. auto t = InterpExp(ct_top, (*m)->u.field.type);
  589. fields->push_back(std::make_pair(*(*m)->u.field.name, t));
  590. }
  591. }
  592. return MakeStructTypeVal(*sd->name, fields, methods);
  593. }
  594. auto FunctionDeclaration::Name() const -> std::string {
  595. return definition->name;
  596. }
  597. auto StructDeclaration::Name() const -> std::string { return *definition.name; }
  598. auto ChoiceDeclaration::Name() const -> std::string { return name; }
  599. // Returns the name of the declared variable.
  600. auto VariableDeclaration::Name() const -> std::string { return name; }
  601. auto StructDeclaration::TypeChecked(TypeEnv types, Env values) const
  602. -> Declaration {
  603. auto fields = new std::list<Member*>();
  604. for (auto& m : *definition.members) {
  605. if (m->tag == MemberKind::FieldMember) {
  606. // TODO: Interpret the type expression and store the result.
  607. fields->push_back(m);
  608. }
  609. }
  610. return StructDeclaration(definition.line_num, *definition.name, fields);
  611. }
  612. auto FunctionDeclaration::TypeChecked(TypeEnv types, Env values) const
  613. -> Declaration {
  614. return FunctionDeclaration(TypeCheckFunDef(definition, types, values));
  615. }
  616. auto ChoiceDeclaration::TypeChecked(TypeEnv types, Env values) const
  617. -> Declaration {
  618. return *this; // TODO.
  619. }
  620. // Signals a type error if the initializing expression does not have
  621. // the declared type of the variable, otherwise returns this
  622. // declaration with annotated types.
  623. auto VariableDeclaration::TypeChecked(TypeEnv types, Env values) const
  624. -> Declaration {
  625. TCResult type_checked_initializer = TypeCheckExp(
  626. initializer, types, values, nullptr, TCContext::ValueContext);
  627. const Value* declared_type = InterpExp(values, type);
  628. ExpectType(source_location, "initializer of variable", declared_type,
  629. type_checked_initializer.type);
  630. return *this;
  631. }
  632. auto TopLevel(std::list<Declaration>* fs) -> TypeCheckContext {
  633. TypeCheckContext tops;
  634. bool found_main = false;
  635. for (auto const& d : *fs) {
  636. if (d.Name() == "main") {
  637. found_main = true;
  638. }
  639. d.TopLevel(tops);
  640. }
  641. if (found_main == false) {
  642. std::cerr << "error, program must contain a function named `main`"
  643. << std::endl;
  644. exit(-1);
  645. }
  646. return tops;
  647. }
  648. auto FunctionDeclaration::TopLevel(TypeCheckContext& tops) const -> void {
  649. auto t = TypeOfFunDef(tops.types, tops.values, definition);
  650. tops.types.Set(Name(), t);
  651. }
  652. auto StructDeclaration::TopLevel(TypeCheckContext& tops) const -> void {
  653. auto st = TypeOfStructDef(&definition, tops.types, tops.values);
  654. Address a = state->AllocateValue(st);
  655. tops.values.Set(Name(), a); // Is this obsolete?
  656. auto field_types = new std::vector<std::pair<std::string, Address>>();
  657. for (const auto& [field_name, field_value] : *st->u.struct_type.fields) {
  658. field_types->push_back({field_name, state->AllocateValue(field_value)});
  659. }
  660. auto fun_ty = MakeFunTypeVal(MakeTupleVal(field_types), st);
  661. tops.types.Set(Name(), fun_ty);
  662. }
  663. auto ChoiceDeclaration::TopLevel(TypeCheckContext& tops) const -> void {
  664. auto alts = new VarValues();
  665. for (auto a : alternatives) {
  666. auto t = InterpExp(tops.values, a.second);
  667. alts->push_back(std::make_pair(a.first, t));
  668. }
  669. auto ct = MakeChoiceTypeVal(name, alts);
  670. Address a = state->AllocateValue(ct);
  671. tops.values.Set(Name(), a); // Is this obsolete?
  672. tops.types.Set(Name(), ct);
  673. }
  674. // Associate the variable name with it's declared type in the
  675. // compile-time symbol table.
  676. auto VariableDeclaration::TopLevel(TypeCheckContext& tops) const -> void {
  677. const Value* declared_type = InterpExp(tops.values, type);
  678. tops.types.Set(Name(), declared_type);
  679. }
  680. } // namespace Carbon