typecheck.cpp 29 KB

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