typecheck.cpp 32 KB

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