typecheck.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  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, "==", ts[0], ts[1]);
  282. return TCResult(new_e, MakeBoolTypeVal(), new_types);
  283. }
  284. break;
  285. }
  286. case ExpressionKind::Call: {
  287. auto fun_res = TypeCheckExp(e->u.call.function, types, values, nullptr,
  288. TCContext::ValueContext);
  289. switch (fun_res.type->tag) {
  290. case ValKind::FunctionTV: {
  291. auto fun_t = fun_res.type;
  292. auto arg_res = TypeCheckExp(e->u.call.argument, fun_res.types, values,
  293. fun_t->u.fun_type.param, context);
  294. ExpectType(e->line_num, "call", fun_t->u.fun_type.param,
  295. arg_res.type);
  296. auto new_e = MakeCall(e->line_num, fun_res.exp, arg_res.exp);
  297. return TCResult(new_e, fun_t->u.fun_type.ret, arg_res.types);
  298. }
  299. default: {
  300. std::cerr << e->line_num
  301. << ": compilation error in call, expected a function"
  302. << std::endl;
  303. PrintExp(e);
  304. std::cerr << std::endl;
  305. exit(-1);
  306. }
  307. }
  308. break;
  309. }
  310. case ExpressionKind::FunctionT: {
  311. switch (context) {
  312. case TCContext::ValueContext:
  313. case TCContext::TypeContext: {
  314. auto pt = InterpExp(values, e->u.function_type.parameter);
  315. auto rt = InterpExp(values, e->u.function_type.return_type);
  316. auto new_e = MakeFunType(e->line_num, ReifyType(pt, e->line_num),
  317. ReifyType(rt, e->line_num));
  318. return TCResult(new_e, MakeTypeTypeVal(), types);
  319. }
  320. case TCContext::PatternContext: {
  321. auto param_res = TypeCheckExp(e->u.function_type.parameter, types,
  322. values, nullptr, context);
  323. auto ret_res =
  324. TypeCheckExp(e->u.function_type.return_type, param_res.types,
  325. values, nullptr, context);
  326. auto new_e =
  327. MakeFunType(e->line_num, ReifyType(param_res.type, e->line_num),
  328. ReifyType(ret_res.type, e->line_num));
  329. return TCResult(new_e, MakeTypeTypeVal(), ret_res.types);
  330. }
  331. }
  332. }
  333. case ExpressionKind::IntT:
  334. return TCResult(e, MakeIntTypeVal(), types);
  335. case ExpressionKind::BoolT:
  336. return TCResult(e, MakeBoolTypeVal(), types);
  337. case ExpressionKind::TypeT:
  338. return TCResult(e, MakeTypeTypeVal(), types);
  339. case ExpressionKind::AutoT:
  340. return TCResult(e, MakeAutoTypeVal(), types);
  341. case ExpressionKind::ContinuationT:
  342. return TCResult(e, MakeContinuationTypeVal(), types);
  343. }
  344. }
  345. auto TypecheckCase(const Value* expected, const Expression* pat,
  346. const Statement* body, TypeEnv types, Env values,
  347. const Value*& ret_type)
  348. -> std::pair<const Expression*, const Statement*> {
  349. auto pat_res =
  350. TypeCheckExp(pat, types, values, expected, TCContext::PatternContext);
  351. auto res = TypeCheckStmt(body, pat_res.types, values, ret_type);
  352. return std::make_pair(pat, res.stmt);
  353. }
  354. // The TypeCheckStmt function performs semantic analysis on a statement.
  355. // It returns a new version of the statement and a new type environment.
  356. //
  357. // The ret_type parameter is used for analyzing return statements.
  358. // It is the declared return type of the enclosing function definition.
  359. // If the return type is "auto", then the return type is inferred from
  360. // the first return statement.
  361. auto TypeCheckStmt(const Statement* s, TypeEnv types, Env values,
  362. const Value*& ret_type) -> TCStatement {
  363. if (!s) {
  364. return TCStatement(s, types);
  365. }
  366. switch (s->tag) {
  367. case StatementKind::Match: {
  368. auto res = TypeCheckExp(s->u.match_stmt.exp, types, values, nullptr,
  369. TCContext::ValueContext);
  370. auto res_type = res.type;
  371. auto new_clauses =
  372. new std::list<std::pair<const Expression*, const Statement*>>();
  373. for (auto& clause : *s->u.match_stmt.clauses) {
  374. new_clauses->push_back(TypecheckCase(
  375. res_type, clause.first, clause.second, types, values, ret_type));
  376. }
  377. const Statement* new_s = MakeMatch(s->line_num, res.exp, new_clauses);
  378. return TCStatement(new_s, types);
  379. }
  380. case StatementKind::While: {
  381. auto cnd_res = TypeCheckExp(s->u.while_stmt.cond, types, values, nullptr,
  382. TCContext::ValueContext);
  383. ExpectType(s->line_num, "condition of `while`", MakeBoolTypeVal(),
  384. cnd_res.type);
  385. auto body_res =
  386. TypeCheckStmt(s->u.while_stmt.body, types, values, ret_type);
  387. auto new_s = MakeWhile(s->line_num, cnd_res.exp, body_res.stmt);
  388. return TCStatement(new_s, types);
  389. }
  390. case StatementKind::Break:
  391. case StatementKind::Continue:
  392. return TCStatement(s, types);
  393. case StatementKind::Block: {
  394. auto stmt_res = TypeCheckStmt(s->u.block.stmt, types, values, ret_type);
  395. return TCStatement(MakeBlock(s->line_num, stmt_res.stmt), types);
  396. }
  397. case StatementKind::VariableDefinition: {
  398. auto res = TypeCheckExp(s->u.variable_definition.init, types, values,
  399. nullptr, TCContext::ValueContext);
  400. const Value* rhs_ty = res.type;
  401. auto lhs_res = TypeCheckExp(s->u.variable_definition.pat, types, values,
  402. rhs_ty, TCContext::PatternContext);
  403. const Statement* new_s =
  404. MakeVarDef(s->line_num, s->u.variable_definition.pat, res.exp);
  405. return TCStatement(new_s, lhs_res.types);
  406. }
  407. case StatementKind::Sequence: {
  408. auto stmt_res =
  409. TypeCheckStmt(s->u.sequence.stmt, types, values, ret_type);
  410. auto types2 = stmt_res.types;
  411. auto next_res =
  412. TypeCheckStmt(s->u.sequence.next, types2, values, ret_type);
  413. auto types3 = next_res.types;
  414. return TCStatement(MakeSeq(s->line_num, stmt_res.stmt, next_res.stmt),
  415. types3);
  416. }
  417. case StatementKind::Assign: {
  418. auto rhs_res = TypeCheckExp(s->u.assign.rhs, types, values, nullptr,
  419. TCContext::ValueContext);
  420. auto rhs_t = rhs_res.type;
  421. auto lhs_res = TypeCheckExp(s->u.assign.lhs, types, values, rhs_t,
  422. TCContext::ValueContext);
  423. auto lhs_t = lhs_res.type;
  424. ExpectType(s->line_num, "assign", lhs_t, rhs_t);
  425. auto new_s = MakeAssign(s->line_num, lhs_res.exp, rhs_res.exp);
  426. return TCStatement(new_s, lhs_res.types);
  427. }
  428. case StatementKind::ExpressionStatement: {
  429. auto res = TypeCheckExp(s->u.exp, types, values, nullptr,
  430. TCContext::ValueContext);
  431. auto new_s = MakeExpStmt(s->line_num, res.exp);
  432. return TCStatement(new_s, types);
  433. }
  434. case StatementKind::If: {
  435. auto cnd_res = TypeCheckExp(s->u.if_stmt.cond, types, values, nullptr,
  436. TCContext::ValueContext);
  437. ExpectType(s->line_num, "condition of `if`", MakeBoolTypeVal(),
  438. cnd_res.type);
  439. auto thn_res =
  440. TypeCheckStmt(s->u.if_stmt.then_stmt, types, values, ret_type);
  441. auto els_res =
  442. TypeCheckStmt(s->u.if_stmt.else_stmt, types, values, ret_type);
  443. auto new_s = MakeIf(s->line_num, cnd_res.exp, thn_res.stmt, els_res.stmt);
  444. return TCStatement(new_s, types);
  445. }
  446. case StatementKind::Return: {
  447. auto res = TypeCheckExp(s->u.return_stmt, types, values, nullptr,
  448. TCContext::ValueContext);
  449. if (ret_type->tag == ValKind::AutoTV) {
  450. // The following infers the return type from the first 'return'
  451. // statement. This will get more difficult with subtyping, when we
  452. // should infer the least-upper bound of all the 'return' statements.
  453. ret_type = res.type;
  454. } else {
  455. ExpectType(s->line_num, "return", ret_type, res.type);
  456. }
  457. return TCStatement(MakeReturn(s->line_num, res.exp), types);
  458. }
  459. case StatementKind::Continuation: {
  460. TCStatement body_result =
  461. TypeCheckStmt(s->u.continuation.body, types, values, ret_type);
  462. const Statement* new_continuation = MakeContinuationStatement(
  463. s->line_num, *s->u.continuation.continuation_variable,
  464. body_result.stmt);
  465. types.Set(*s->u.continuation.continuation_variable,
  466. MakeContinuationTypeVal());
  467. return TCStatement(new_continuation, types);
  468. }
  469. case StatementKind::Run: {
  470. TCResult argument_result = TypeCheckExp(s->u.run.argument, types, values,
  471. nullptr, TCContext::ValueContext);
  472. ExpectType(s->line_num, "argument of `run`", MakeContinuationTypeVal(),
  473. argument_result.type);
  474. const Statement* new_run = MakeRun(s->line_num, argument_result.exp);
  475. return TCStatement(new_run, types);
  476. }
  477. case StatementKind::Await: {
  478. // nothing to do here
  479. return TCStatement(s, types);
  480. }
  481. } // switch
  482. }
  483. auto CheckOrEnsureReturn(const Statement* stmt, bool void_return, int line_num)
  484. -> const Statement* {
  485. if (!stmt) {
  486. if (void_return) {
  487. auto args = new std::vector<std::pair<std::string, const Expression*>>();
  488. return MakeReturn(line_num, MakeTuple(line_num, args));
  489. } else {
  490. std::cerr
  491. << "control-flow reaches end of non-void function without a return"
  492. << std::endl;
  493. exit(-1);
  494. }
  495. }
  496. switch (stmt->tag) {
  497. case StatementKind::Match: {
  498. auto new_clauses =
  499. new std::list<std::pair<const Expression*, const Statement*>>();
  500. for (auto i = stmt->u.match_stmt.clauses->begin();
  501. i != stmt->u.match_stmt.clauses->end(); ++i) {
  502. auto s = CheckOrEnsureReturn(i->second, void_return, stmt->line_num);
  503. new_clauses->push_back(std::make_pair(i->first, s));
  504. }
  505. return MakeMatch(stmt->line_num, stmt->u.match_stmt.exp, new_clauses);
  506. }
  507. case StatementKind::Block:
  508. return MakeBlock(
  509. stmt->line_num,
  510. CheckOrEnsureReturn(stmt->u.block.stmt, void_return, stmt->line_num));
  511. case StatementKind::If:
  512. return MakeIf(stmt->line_num, stmt->u.if_stmt.cond,
  513. CheckOrEnsureReturn(stmt->u.if_stmt.then_stmt, void_return,
  514. stmt->line_num),
  515. CheckOrEnsureReturn(stmt->u.if_stmt.else_stmt, void_return,
  516. stmt->line_num));
  517. case StatementKind::Return:
  518. return stmt;
  519. case StatementKind::Sequence:
  520. if (stmt->u.sequence.next) {
  521. return MakeSeq(stmt->line_num, stmt->u.sequence.stmt,
  522. CheckOrEnsureReturn(stmt->u.sequence.next, void_return,
  523. stmt->line_num));
  524. } else {
  525. return CheckOrEnsureReturn(stmt->u.sequence.stmt, void_return,
  526. stmt->line_num);
  527. }
  528. case StatementKind::Continuation:
  529. case StatementKind::Run:
  530. case StatementKind::Await:
  531. return stmt;
  532. case StatementKind::Assign:
  533. case StatementKind::ExpressionStatement:
  534. case StatementKind::While:
  535. case StatementKind::Break:
  536. case StatementKind::Continue:
  537. case StatementKind::VariableDefinition:
  538. if (void_return) {
  539. auto args =
  540. new std::vector<std::pair<std::string, const Expression*>>();
  541. return MakeSeq(
  542. stmt->line_num, stmt,
  543. MakeReturn(stmt->line_num, MakeTuple(stmt->line_num, args)));
  544. } else {
  545. std::cerr
  546. << stmt->line_num
  547. << ": control-flow reaches end of non-void function without a "
  548. "return"
  549. << std::endl;
  550. exit(-1);
  551. }
  552. }
  553. }
  554. auto TypeCheckFunDef(const FunctionDefinition* f, TypeEnv types, Env values)
  555. -> struct FunctionDefinition* {
  556. auto param_res = TypeCheckExp(f->param_pattern, types, values, nullptr,
  557. TCContext::PatternContext);
  558. auto return_type = InterpExp(values, f->return_type);
  559. if (f->name == "main") {
  560. ExpectType(f->line_num, "return type of `main`", MakeIntTypeVal(),
  561. return_type);
  562. // TODO: Check that main doesn't have any parameters.
  563. }
  564. auto res = TypeCheckStmt(f->body, param_res.types, values, return_type);
  565. bool void_return = TypeEqual(return_type, MakeVoidTypeVal());
  566. auto body = CheckOrEnsureReturn(res.stmt, void_return, f->line_num);
  567. return MakeFunDef(f->line_num, f->name, ReifyType(return_type, f->line_num),
  568. f->param_pattern, body);
  569. }
  570. auto TypeOfFunDef(TypeEnv types, Env values, const FunctionDefinition* fun_def)
  571. -> const Value* {
  572. auto param_res = TypeCheckExp(fun_def->param_pattern, types, values, nullptr,
  573. TCContext::PatternContext);
  574. auto ret = InterpExp(values, fun_def->return_type);
  575. if (ret->tag == ValKind::AutoTV) {
  576. auto f = TypeCheckFunDef(fun_def, types, values);
  577. ret = InterpExp(values, f->return_type);
  578. }
  579. return MakeFunTypeVal(param_res.type, ret);
  580. }
  581. auto TypeOfStructDef(const StructDefinition* sd, TypeEnv /*types*/, Env ct_top)
  582. -> const Value* {
  583. auto fields = new VarValues();
  584. auto methods = new VarValues();
  585. for (auto m = sd->members->begin(); m != sd->members->end(); ++m) {
  586. if ((*m)->tag == MemberKind::FieldMember) {
  587. auto t = InterpExp(ct_top, (*m)->u.field.type);
  588. fields->push_back(std::make_pair(*(*m)->u.field.name, t));
  589. }
  590. }
  591. return MakeStructTypeVal(*sd->name, fields, methods);
  592. }
  593. auto FunctionDeclaration::Name() const -> std::string {
  594. return definition->name;
  595. }
  596. auto StructDeclaration::Name() const -> std::string { return *definition.name; }
  597. auto ChoiceDeclaration::Name() const -> std::string { return name; }
  598. // Returns the name of the declared variable.
  599. auto VariableDeclaration::Name() const -> std::string { return name; }
  600. auto StructDeclaration::TypeChecked(TypeEnv types, Env values) const
  601. -> Declaration {
  602. auto fields = new std::list<Member*>();
  603. for (auto& m : *definition.members) {
  604. if (m->tag == MemberKind::FieldMember) {
  605. // TODO: Interpret the type expression and store the result.
  606. fields->push_back(m);
  607. }
  608. }
  609. return StructDeclaration(definition.line_num, *definition.name, fields);
  610. }
  611. auto FunctionDeclaration::TypeChecked(TypeEnv types, Env values) const
  612. -> Declaration {
  613. return FunctionDeclaration(TypeCheckFunDef(definition, types, values));
  614. }
  615. auto ChoiceDeclaration::TypeChecked(TypeEnv types, Env values) const
  616. -> Declaration {
  617. return *this; // TODO.
  618. }
  619. // Signals a type error if the initializing expression does not have
  620. // the declared type of the variable, otherwise returns this
  621. // declaration with annotated types.
  622. auto VariableDeclaration::TypeChecked(TypeEnv types, Env values) const
  623. -> Declaration {
  624. TCResult type_checked_initializer = TypeCheckExp(
  625. initializer, types, values, nullptr, TCContext::ValueContext);
  626. const Value* declared_type = InterpExp(values, type);
  627. ExpectType(source_location, "initializer of variable", declared_type,
  628. type_checked_initializer.type);
  629. return *this;
  630. }
  631. auto TopLevel(std::list<Declaration>* fs) -> TypeCheckContext {
  632. TypeCheckContext tops;
  633. bool found_main = false;
  634. for (auto const& d : *fs) {
  635. if (d.Name() == "main") {
  636. found_main = true;
  637. }
  638. d.TopLevel(tops);
  639. }
  640. if (found_main == false) {
  641. std::cerr << "error, program must contain a function named `main`"
  642. << std::endl;
  643. exit(-1);
  644. }
  645. return tops;
  646. }
  647. auto FunctionDeclaration::TopLevel(TypeCheckContext& tops) const -> void {
  648. auto t = TypeOfFunDef(tops.types, tops.values, definition);
  649. tops.types.Set(Name(), t);
  650. }
  651. auto StructDeclaration::TopLevel(TypeCheckContext& tops) const -> void {
  652. auto st = TypeOfStructDef(&definition, tops.types, tops.values);
  653. Address a = state->AllocateValue(st);
  654. tops.values.Set(Name(), a); // Is this obsolete?
  655. auto field_types = new std::vector<std::pair<std::string, Address>>();
  656. for (const auto& [field_name, field_value] : *st->u.struct_type.fields) {
  657. field_types->push_back({field_name, state->AllocateValue(field_value)});
  658. }
  659. auto fun_ty = MakeFunTypeVal(MakeTupleVal(field_types), st);
  660. tops.types.Set(Name(), fun_ty);
  661. }
  662. auto ChoiceDeclaration::TopLevel(TypeCheckContext& tops) const -> void {
  663. auto alts = new VarValues();
  664. for (auto a : alternatives) {
  665. auto t = InterpExp(tops.values, a.second);
  666. alts->push_back(std::make_pair(a.first, t));
  667. }
  668. auto ct = MakeChoiceTypeVal(name, alts);
  669. Address a = state->AllocateValue(ct);
  670. tops.values.Set(Name(), a); // Is this obsolete?
  671. tops.types.Set(Name(), ct);
  672. }
  673. // Associate the variable name with it's declared type in the
  674. // compile-time symbol table.
  675. auto VariableDeclaration::TopLevel(TypeCheckContext& tops) const -> void {
  676. const Value* declared_type = InterpExp(tops.values, type);
  677. tops.types.Set(Name(), declared_type);
  678. }
  679. } // namespace Carbon