typecheck.cpp 32 KB

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