typecheck.cpp 31 KB

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