typecheck.cpp 32 KB

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