typecheck.cpp 27 KB

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