typecheck.cpp 27 KB

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