typecheck.cpp 29 KB

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