typecheck.cpp 28 KB

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