typecheck.cpp 29 KB

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