typecheck.cpp 28 KB

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