typecheck.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  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/cons_list.h"
  13. #include "executable_semantics/interpreter/interpreter.h"
  14. namespace Carbon {
  15. void ExpectType(int line_num, const std::string& context, Value* expected,
  16. Value* actual) {
  17. if (!TypeEqual(expected, actual)) {
  18. std::cerr << line_num << ": type error in " << context << std::endl;
  19. std::cerr << "expected: ";
  20. PrintValue(expected, std::cerr);
  21. std::cerr << std::endl << "actual: ";
  22. PrintValue(actual, std::cerr);
  23. std::cerr << std::endl;
  24. exit(-1);
  25. }
  26. }
  27. void PrintErrorString(const std::string& s) { std::cerr << s; }
  28. void PrintTypeEnv(TypeEnv* env, std::ostream& out) {
  29. if (env) {
  30. out << env->key << ": ";
  31. PrintValue(env->value, out);
  32. out << ", ";
  33. PrintTypeEnv(env->next, out);
  34. }
  35. }
  36. // Convert tuples to tuple types.
  37. auto ToType(int line_num, Value* val) -> Value* {
  38. switch (val->tag) {
  39. case ValKind::TupleV: {
  40. auto fields = new VarValues();
  41. for (auto& elt : *val->u.tuple.elts) {
  42. Value* ty = ToType(line_num, state->heap[elt.second]);
  43. fields->push_back(std::make_pair(elt.first, ty));
  44. }
  45. return MakeTupleTypeVal(fields);
  46. }
  47. case ValKind::TupleTV: {
  48. auto fields = new VarValues();
  49. for (auto& field : *val->u.tuple_type.fields) {
  50. Value* ty = ToType(line_num, field.second);
  51. fields->push_back(std::make_pair(field.first, ty));
  52. }
  53. return MakeTupleTypeVal(fields);
  54. }
  55. case ValKind::PointerTV: {
  56. return MakePtrTypeVal(ToType(line_num, val->u.ptr_type.type));
  57. }
  58. case ValKind::FunctionTV: {
  59. return MakeFunTypeVal(ToType(line_num, val->u.fun_type.param),
  60. ToType(line_num, val->u.fun_type.ret));
  61. }
  62. case ValKind::VarPatV: {
  63. return MakeVarPatVal(*val->u.var_pat.name,
  64. ToType(line_num, val->u.var_pat.type));
  65. }
  66. case ValKind::ChoiceTV:
  67. case ValKind::StructTV:
  68. case ValKind::TypeTV:
  69. case ValKind::VarTV:
  70. case ValKind::BoolTV:
  71. case ValKind::IntTV:
  72. case ValKind::AutoTV:
  73. return val;
  74. default:
  75. std::cerr << line_num << ": in ToType, expected a type, not ";
  76. PrintValue(val, std::cerr);
  77. std::cerr << std::endl;
  78. exit(-1);
  79. }
  80. }
  81. // Reify type to type expression.
  82. auto ReifyType(Value* t, int line_num) -> Expression* {
  83. switch (t->tag) {
  84. case ValKind::VarTV:
  85. return MakeVar(0, *t->u.var_type);
  86. case ValKind::IntTV:
  87. return MakeIntType(0);
  88. case ValKind::BoolTV:
  89. return MakeBoolType(0);
  90. case ValKind::TypeTV:
  91. return MakeTypeType(0);
  92. case ValKind::FunctionTV:
  93. return MakeFunType(0, ReifyType(t->u.fun_type.param, line_num),
  94. ReifyType(t->u.fun_type.ret, line_num));
  95. case ValKind::TupleTV: {
  96. auto args = new std::vector<std::pair<std::string, Expression*>>();
  97. for (auto& field : *t->u.tuple_type.fields) {
  98. args->push_back(
  99. make_pair(field.first, ReifyType(field.second, line_num)));
  100. }
  101. return MakeTuple(0, args);
  102. }
  103. case ValKind::StructTV:
  104. return MakeVar(0, *t->u.struct_type.name);
  105. case ValKind::ChoiceTV:
  106. return MakeVar(0, *t->u.choice_type.name);
  107. default:
  108. std::cerr << line_num << ": expected a type, not ";
  109. PrintValue(t, std::cerr);
  110. std::cerr << std::endl;
  111. exit(-1);
  112. }
  113. }
  114. // The TypeCheckExp function performs semantic analysis on an expression.
  115. // It returns a new version of the expression, its type, and an
  116. // updated environment which are bundled into a TCResult object.
  117. // The purpose of the updated environment is
  118. // to bring pattern variables into scope, for example, in a match case.
  119. // The new version of the expression may include more information,
  120. // for example, the type arguments deduced for the type parameters of a
  121. // generic.
  122. //
  123. // e is the expression to be analyzed.
  124. // env maps variable names to the type of their run-time value.
  125. // ct_env maps variable names to their compile-time values. It is not
  126. // directly used in this function but is passed to InterExp.
  127. // expected is the type that this expression is expected to have.
  128. // This parameter is non-null when the expression is in a pattern context
  129. // and it is used to implement `auto`, otherwise it is null.
  130. // context says what kind of position this expression is nested in,
  131. // whether it's a position that expects a value, a pattern, or a type.
  132. auto TypeCheckExp(Expression* e, TypeEnv* env, Env* ct_env, Value* expected,
  133. TCContext context) -> TCResult {
  134. switch (e->tag) {
  135. case ExpressionKind::PatternVariable: {
  136. if (context != TCContext::PatternContext) {
  137. std::cerr
  138. << e->line_num
  139. << ": compilation error, pattern variables are only allowed in "
  140. "pattern context"
  141. << std::endl;
  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 =
  328. TypeCheckExp(e->u.call.argument, fun_res.env, ct_env,
  329. fun_t->u.fun_type.param, TCContext::ValueContext);
  330. ExpectType(e->line_num, "call", fun_t->u.fun_type.param,
  331. arg_res.type);
  332. auto new_e = MakeCall(e->line_num, fun_res.exp, arg_res.exp);
  333. return TCResult(new_e, fun_t->u.fun_type.ret, arg_res.env);
  334. }
  335. default: {
  336. std::cerr << e->line_num
  337. << ": compilation error in call, expected a function"
  338. << std::endl;
  339. PrintExp(e);
  340. std::cerr << std::endl;
  341. exit(-1);
  342. }
  343. }
  344. break;
  345. }
  346. case ExpressionKind::FunctionT: {
  347. switch (context) {
  348. case TCContext::ValueContext:
  349. case TCContext::TypeContext: {
  350. auto pt = ToType(e->line_num,
  351. InterpExp(ct_env, e->u.function_type.parameter));
  352. auto rt = ToType(e->line_num,
  353. InterpExp(ct_env, e->u.function_type.return_type));
  354. auto new_e = MakeFunType(e->line_num, ReifyType(pt, e->line_num),
  355. ReifyType(rt, e->line_num));
  356. return TCResult(new_e, MakeTypeTypeVal(), env);
  357. }
  358. case TCContext::PatternContext: {
  359. auto param_res = TypeCheckExp(e->u.function_type.parameter, env,
  360. ct_env, nullptr, context);
  361. auto ret_res = TypeCheckExp(e->u.function_type.return_type,
  362. param_res.env, ct_env, nullptr, context);
  363. auto new_e =
  364. MakeFunType(e->line_num, ReifyType(param_res.type, e->line_num),
  365. ReifyType(ret_res.type, e->line_num));
  366. return TCResult(new_e, MakeTypeTypeVal(), ret_res.env);
  367. }
  368. }
  369. }
  370. case ExpressionKind::IntT:
  371. case ExpressionKind::BoolT:
  372. case ExpressionKind::TypeT:
  373. case ExpressionKind::AutoT:
  374. return TCResult(e, MakeTypeTypeVal(), env);
  375. }
  376. }
  377. auto TypecheckCase(Value* expected, Expression* pat, Statement* body,
  378. TypeEnv* env, Env* ct_env, Value* ret_type)
  379. -> std::pair<Expression*, Statement*> {
  380. auto pat_res =
  381. TypeCheckExp(pat, env, ct_env, expected, TCContext::PatternContext);
  382. auto res = TypeCheckStmt(body, pat_res.env, ct_env, ret_type);
  383. return std::make_pair(pat, res.stmt);
  384. }
  385. // The TypeCheckStmt function performs semantic analysis on a statement.
  386. // It returns a new version of the statement and a new type environment.
  387. //
  388. // The ret_type parameter is used for analyzing return statements.
  389. // It is the declared return type of the enclosing function definition.
  390. // If the return type is "auto", then the return type is inferred from
  391. // the first return statement.
  392. auto TypeCheckStmt(Statement* s, TypeEnv* env, Env* ct_env, Value* ret_type)
  393. -> TCStatement {
  394. if (!s) {
  395. return TCStatement(s, env);
  396. }
  397. switch (s->tag) {
  398. case StatementKind::Match: {
  399. auto res = TypeCheckExp(s->u.match_stmt.exp, env, ct_env, nullptr,
  400. TCContext::ValueContext);
  401. auto res_type = res.type;
  402. auto new_clauses = new std::list<std::pair<Expression*, Statement*>>();
  403. for (auto& clause : *s->u.match_stmt.clauses) {
  404. new_clauses->push_back(TypecheckCase(
  405. res_type, clause.first, clause.second, env, ct_env, ret_type));
  406. }
  407. Statement* new_s = MakeMatch(s->line_num, res.exp, new_clauses);
  408. return TCStatement(new_s, env);
  409. }
  410. case StatementKind::While: {
  411. auto cnd_res = TypeCheckExp(s->u.while_stmt.cond, env, ct_env, nullptr,
  412. TCContext::ValueContext);
  413. ExpectType(s->line_num, "condition of `while`", MakeBoolTypeVal(),
  414. cnd_res.type);
  415. auto body_res =
  416. TypeCheckStmt(s->u.while_stmt.body, env, ct_env, ret_type);
  417. auto new_s = MakeWhile(s->line_num, cnd_res.exp, body_res.stmt);
  418. return TCStatement(new_s, env);
  419. }
  420. case StatementKind::Break:
  421. case StatementKind::Continue:
  422. return TCStatement(s, env);
  423. case StatementKind::Block: {
  424. auto stmt_res = TypeCheckStmt(s->u.block.stmt, env, ct_env, ret_type);
  425. return TCStatement(MakeBlock(s->line_num, stmt_res.stmt), env);
  426. }
  427. case StatementKind::VariableDefinition: {
  428. auto res = TypeCheckExp(s->u.variable_definition.init, env, ct_env,
  429. nullptr, TCContext::ValueContext);
  430. Value* rhs_ty = res.type;
  431. auto lhs_res = TypeCheckExp(s->u.variable_definition.pat, env, ct_env,
  432. rhs_ty, TCContext::PatternContext);
  433. Statement* new_s =
  434. MakeVarDef(s->line_num, s->u.variable_definition.pat, res.exp);
  435. return TCStatement(new_s, lhs_res.env);
  436. }
  437. case StatementKind::Sequence: {
  438. auto stmt_res = TypeCheckStmt(s->u.sequence.stmt, env, ct_env, ret_type);
  439. auto env2 = stmt_res.env;
  440. auto next_res = TypeCheckStmt(s->u.sequence.next, env2, ct_env, ret_type);
  441. auto env3 = next_res.env;
  442. return TCStatement(MakeSeq(s->line_num, stmt_res.stmt, next_res.stmt),
  443. env3);
  444. }
  445. case StatementKind::Assign: {
  446. auto rhs_res = TypeCheckExp(s->u.assign.rhs, env, ct_env, nullptr,
  447. TCContext::ValueContext);
  448. auto rhs_t = rhs_res.type;
  449. auto lhs_res = TypeCheckExp(s->u.assign.lhs, env, ct_env, rhs_t,
  450. TCContext::ValueContext);
  451. auto lhs_t = lhs_res.type;
  452. ExpectType(s->line_num, "assign", lhs_t, rhs_t);
  453. auto new_s = MakeAssign(s->line_num, lhs_res.exp, rhs_res.exp);
  454. return TCStatement(new_s, lhs_res.env);
  455. }
  456. case StatementKind::ExpressionStatement: {
  457. auto res =
  458. TypeCheckExp(s->u.exp, env, ct_env, nullptr, TCContext::ValueContext);
  459. auto new_s = MakeExpStmt(s->line_num, res.exp);
  460. return TCStatement(new_s, env);
  461. }
  462. case StatementKind::If: {
  463. auto cnd_res = TypeCheckExp(s->u.if_stmt.cond, env, ct_env, nullptr,
  464. TCContext::ValueContext);
  465. ExpectType(s->line_num, "condition of `if`", MakeBoolTypeVal(),
  466. cnd_res.type);
  467. auto thn_res =
  468. TypeCheckStmt(s->u.if_stmt.then_stmt, env, ct_env, ret_type);
  469. auto els_res =
  470. TypeCheckStmt(s->u.if_stmt.else_stmt, env, ct_env, ret_type);
  471. auto new_s = MakeIf(s->line_num, cnd_res.exp, thn_res.stmt, els_res.stmt);
  472. return TCStatement(new_s, env);
  473. }
  474. case StatementKind::Return: {
  475. auto res = TypeCheckExp(s->u.return_stmt, env, ct_env, nullptr,
  476. TCContext::ValueContext);
  477. if (ret_type->tag == ValKind::AutoTV) {
  478. // The following infers the return type from the first 'return'
  479. // statement. This will get more difficult with subtyping, when we
  480. // should infer the least-upper bound of all the 'return' statements.
  481. *ret_type = *res.type;
  482. } else {
  483. ExpectType(s->line_num, "return", ret_type, res.type);
  484. }
  485. return TCStatement(MakeReturn(s->line_num, res.exp), env);
  486. }
  487. }
  488. }
  489. auto CheckOrEnsureReturn(Statement* stmt, bool void_return, int line_num)
  490. -> Statement* {
  491. if (!stmt) {
  492. if (void_return) {
  493. auto args = new std::vector<std::pair<std::string, Expression*>>();
  494. return MakeReturn(line_num, MakeTuple(line_num, args));
  495. } else {
  496. std::cerr
  497. << "control-flow reaches end of non-void function without a return"
  498. << std::endl;
  499. exit(-1);
  500. }
  501. }
  502. switch (stmt->tag) {
  503. case StatementKind::Match: {
  504. auto new_clauses = new std::list<std::pair<Expression*, Statement*>>();
  505. for (auto i = stmt->u.match_stmt.clauses->begin();
  506. i != stmt->u.match_stmt.clauses->end(); ++i) {
  507. auto s = CheckOrEnsureReturn(i->second, void_return, stmt->line_num);
  508. new_clauses->push_back(std::make_pair(i->first, s));
  509. }
  510. return MakeMatch(stmt->line_num, stmt->u.match_stmt.exp, new_clauses);
  511. }
  512. case StatementKind::Block:
  513. return MakeBlock(
  514. stmt->line_num,
  515. CheckOrEnsureReturn(stmt->u.block.stmt, void_return, stmt->line_num));
  516. case StatementKind::If:
  517. return MakeIf(stmt->line_num, stmt->u.if_stmt.cond,
  518. CheckOrEnsureReturn(stmt->u.if_stmt.then_stmt, void_return,
  519. stmt->line_num),
  520. CheckOrEnsureReturn(stmt->u.if_stmt.else_stmt, void_return,
  521. stmt->line_num));
  522. case StatementKind::Return:
  523. return stmt;
  524. case StatementKind::Sequence:
  525. if (stmt->u.sequence.next) {
  526. return MakeSeq(stmt->line_num, stmt->u.sequence.stmt,
  527. CheckOrEnsureReturn(stmt->u.sequence.next, void_return,
  528. stmt->line_num));
  529. } else {
  530. return CheckOrEnsureReturn(stmt->u.sequence.stmt, void_return,
  531. stmt->line_num);
  532. }
  533. case StatementKind::Assign:
  534. case StatementKind::ExpressionStatement:
  535. case StatementKind::While:
  536. case StatementKind::Break:
  537. case StatementKind::Continue:
  538. case StatementKind::VariableDefinition:
  539. if (void_return) {
  540. auto args = new std::vector<std::pair<std::string, Expression*>>();
  541. return MakeSeq(
  542. stmt->line_num, stmt,
  543. MakeReturn(stmt->line_num, MakeTuple(stmt->line_num, args)));
  544. } else {
  545. std::cerr
  546. << stmt->line_num
  547. << ": control-flow reaches end of non-void function without a "
  548. "return"
  549. << std::endl;
  550. exit(-1);
  551. }
  552. }
  553. }
  554. auto TypeCheckFunDef(const FunctionDefinition* f, TypeEnv* env, Env* ct_env)
  555. -> struct FunctionDefinition* {
  556. auto param_res = TypeCheckExp(f->param_pattern, env, ct_env, nullptr,
  557. TCContext::PatternContext);
  558. auto return_type = ToType(f->line_num, InterpExp(ct_env, f->return_type));
  559. if (f->name == "main") {
  560. ExpectType(f->line_num, "return type of `main`", MakeIntTypeVal(),
  561. return_type);
  562. // TODO: Check that main doesn't have any parameters.
  563. }
  564. auto res = TypeCheckStmt(f->body, param_res.env, ct_env, return_type);
  565. bool void_return = TypeEqual(return_type, MakeVoidTypeVal());
  566. auto body = CheckOrEnsureReturn(res.stmt, void_return, f->line_num);
  567. return MakeFunDef(f->line_num, f->name, ReifyType(return_type, f->line_num),
  568. f->param_pattern, body);
  569. }
  570. auto TypeOfFunDef(TypeEnv* env, Env* ct_env, const FunctionDefinition* fun_def)
  571. -> Value* {
  572. auto param_res = TypeCheckExp(fun_def->param_pattern, env, ct_env, nullptr,
  573. TCContext::PatternContext);
  574. auto param_type = ToType(fun_def->line_num, param_res.type);
  575. auto ret = InterpExp(ct_env, fun_def->return_type);
  576. if (ret->tag == ValKind::AutoTV) {
  577. auto f = TypeCheckFunDef(fun_def, env, ct_env);
  578. ret = InterpExp(ct_env, f->return_type);
  579. }
  580. return MakeFunTypeVal(param_type, ret);
  581. }
  582. auto TypeOfStructDef(const StructDefinition* sd, TypeEnv* /*env*/, Env* ct_top)
  583. -> Value* {
  584. auto fields = new VarValues();
  585. auto methods = new VarValues();
  586. for (auto m = sd->members->begin(); m != sd->members->end(); ++m) {
  587. if ((*m)->tag == MemberKind::FieldMember) {
  588. auto t = ToType(sd->line_num, InterpExp(ct_top, (*m)->u.field.type));
  589. fields->push_back(std::make_pair(*(*m)->u.field.name, t));
  590. }
  591. }
  592. return MakeStructTypeVal(*sd->name, fields, methods);
  593. }
  594. auto FunctionDeclaration::Name() const -> std::string {
  595. return definition->name;
  596. }
  597. auto StructDeclaration::Name() const -> std::string { return *definition.name; }
  598. auto ChoiceDeclaration::Name() const -> std::string { return name; }
  599. auto StructDeclaration::TypeChecked(TypeEnv* env, Env* ct_env) const
  600. -> Declaration {
  601. auto fields = new std::list<Member*>();
  602. for (auto& m : *definition.members) {
  603. if (m->tag == MemberKind::FieldMember) {
  604. // TODO: Interpret the type expression and store the result.
  605. fields->push_back(m);
  606. }
  607. }
  608. return StructDeclaration(definition.line_num, *definition.name, fields);
  609. }
  610. auto FunctionDeclaration::TypeChecked(TypeEnv* env, Env* ct_env) const
  611. -> Declaration {
  612. return FunctionDeclaration(TypeCheckFunDef(definition, env, ct_env));
  613. }
  614. auto ChoiceDeclaration::TypeChecked(TypeEnv* env, Env* ct_env) const
  615. -> Declaration {
  616. return *this; // TODO.
  617. }
  618. auto TopLevel(std::list<Declaration>* fs) -> std::pair<TypeEnv*, Env*> {
  619. ExecutionEnvironment tops = {nullptr, nullptr};
  620. bool found_main = false;
  621. for (auto const& d : *fs) {
  622. if (d.Name() == "main") {
  623. found_main = true;
  624. }
  625. d.TopLevel(tops);
  626. }
  627. if (found_main == false) {
  628. std::cerr << "error, program must contain a function named `main`"
  629. << std::endl;
  630. exit(-1);
  631. }
  632. return tops;
  633. }
  634. auto FunctionDeclaration::TopLevel(ExecutionEnvironment& tops) const -> void {
  635. auto t = TypeOfFunDef(tops.first, tops.second, definition);
  636. tops.first = new TypeEnv(Name(), t, tops.first);
  637. }
  638. auto StructDeclaration::TopLevel(ExecutionEnvironment& tops) const -> void {
  639. auto st = TypeOfStructDef(&definition, tops.first, tops.second);
  640. Address a = AllocateValue(st);
  641. tops.second = new Env(Name(), a, tops.second); // Is this obsolete?
  642. auto params = MakeTupleTypeVal(st->u.struct_type.fields);
  643. auto fun_ty = MakeFunTypeVal(params, st);
  644. tops.first = new TypeEnv(Name(), fun_ty, tops.first);
  645. }
  646. auto ChoiceDeclaration::TopLevel(ExecutionEnvironment& tops) const -> void {
  647. auto alts = new VarValues();
  648. for (auto a : alternatives) {
  649. auto t = ToType(line_num, InterpExp(tops.second, a.second));
  650. alts->push_back(std::make_pair(a.first, t));
  651. }
  652. auto ct = MakeChoiceTypeVal(name, alts);
  653. Address a = AllocateValue(ct);
  654. tops.second = new Env(Name(), a, tops.second); // Is this obsolete?
  655. tops.first = new TypeEnv(Name(), ct, tops.first);
  656. }
  657. } // namespace Carbon