typecheck.cpp 26 KB

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