typecheck.cpp 28 KB

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