typecheck.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  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 = Statement::MakeAssign(s->line_num, lhs_res.exp, rhs_res.exp);
  516. return TCStatement(new_s, lhs_res.types);
  517. }
  518. case StatementKind::ExpressionStatement: {
  519. auto res = TypeCheckExp(s->GetExpression(), types, values, nullptr,
  520. TCContext::ValueContext);
  521. auto new_s = Statement::MakeExpStmt(s->line_num, res.exp);
  522. return TCStatement(new_s, types);
  523. }
  524. case StatementKind::If: {
  525. auto cnd_res = TypeCheckExp(s->GetIf().cond, types, values, nullptr,
  526. TCContext::ValueContext);
  527. ExpectType(s->line_num, "condition of `if`", Value::MakeBoolTypeVal(),
  528. cnd_res.type);
  529. auto thn_res =
  530. TypeCheckStmt(s->GetIf().then_stmt, types, values, ret_type);
  531. auto els_res =
  532. TypeCheckStmt(s->GetIf().else_stmt, types, values, ret_type);
  533. auto new_s = Statement::MakeIf(s->line_num, cnd_res.exp, thn_res.stmt,
  534. els_res.stmt);
  535. return TCStatement(new_s, types);
  536. }
  537. case StatementKind::Return: {
  538. auto res = TypeCheckExp(s->GetReturn(), types, values, nullptr,
  539. TCContext::ValueContext);
  540. if (ret_type->tag == ValKind::AutoTV) {
  541. // The following infers the return type from the first 'return'
  542. // statement. This will get more difficult with subtyping, when we
  543. // should infer the least-upper bound of all the 'return' statements.
  544. ret_type = res.type;
  545. } else {
  546. ExpectType(s->line_num, "return", ret_type, res.type);
  547. }
  548. return TCStatement(Statement::MakeReturn(s->line_num, res.exp), types);
  549. }
  550. case StatementKind::Continuation: {
  551. TCStatement body_result =
  552. TypeCheckStmt(s->GetContinuation().body, types, values, ret_type);
  553. const Statement* new_continuation = Statement::MakeContinuation(
  554. s->line_num, *s->GetContinuation().continuation_variable,
  555. body_result.stmt);
  556. types.Set(*s->GetContinuation().continuation_variable,
  557. Value::MakeContinuationTypeVal());
  558. return TCStatement(new_continuation, types);
  559. }
  560. case StatementKind::Run: {
  561. TCResult argument_result =
  562. TypeCheckExp(s->GetRun().argument, types, values, nullptr,
  563. TCContext::ValueContext);
  564. ExpectType(s->line_num, "argument of `run`",
  565. Value::MakeContinuationTypeVal(), argument_result.type);
  566. const Statement* new_run =
  567. Statement::MakeRun(s->line_num, argument_result.exp);
  568. return TCStatement(new_run, types);
  569. }
  570. case StatementKind::Await: {
  571. // nothing to do here
  572. return TCStatement(s, types);
  573. }
  574. } // switch
  575. }
  576. auto CheckOrEnsureReturn(const Statement* stmt, bool void_return, int line_num)
  577. -> const Statement* {
  578. if (!stmt) {
  579. if (void_return) {
  580. return Statement::MakeReturn(line_num,
  581. Expression::MakeTuple(line_num, {}));
  582. } else {
  583. std::cerr
  584. << "control-flow reaches end of non-void function without a return"
  585. << std::endl;
  586. exit(-1);
  587. }
  588. }
  589. switch (stmt->tag) {
  590. case StatementKind::Match: {
  591. auto new_clauses =
  592. new std::list<std::pair<const Expression*, const Statement*>>();
  593. for (auto i = stmt->GetMatch().clauses->begin();
  594. i != stmt->GetMatch().clauses->end(); ++i) {
  595. auto s = CheckOrEnsureReturn(i->second, void_return, stmt->line_num);
  596. new_clauses->push_back(std::make_pair(i->first, s));
  597. }
  598. return Statement::MakeMatch(stmt->line_num, stmt->GetMatch().exp,
  599. new_clauses);
  600. }
  601. case StatementKind::Block:
  602. return Statement::MakeBlock(
  603. stmt->line_num, CheckOrEnsureReturn(stmt->GetBlock().stmt,
  604. void_return, stmt->line_num));
  605. case StatementKind::If:
  606. return Statement::MakeIf(
  607. stmt->line_num, stmt->GetIf().cond,
  608. CheckOrEnsureReturn(stmt->GetIf().then_stmt, void_return,
  609. stmt->line_num),
  610. CheckOrEnsureReturn(stmt->GetIf().else_stmt, void_return,
  611. stmt->line_num));
  612. case StatementKind::Return:
  613. return stmt;
  614. case StatementKind::Sequence:
  615. if (stmt->GetSequence().next) {
  616. return Statement::MakeSeq(
  617. stmt->line_num, stmt->GetSequence().stmt,
  618. CheckOrEnsureReturn(stmt->GetSequence().next, void_return,
  619. stmt->line_num));
  620. } else {
  621. return CheckOrEnsureReturn(stmt->GetSequence().stmt, void_return,
  622. stmt->line_num);
  623. }
  624. case StatementKind::Continuation:
  625. case StatementKind::Run:
  626. case StatementKind::Await:
  627. return stmt;
  628. case StatementKind::Assign:
  629. case StatementKind::ExpressionStatement:
  630. case StatementKind::While:
  631. case StatementKind::Break:
  632. case StatementKind::Continue:
  633. case StatementKind::VariableDefinition:
  634. if (void_return) {
  635. return Statement::MakeSeq(
  636. stmt->line_num, stmt,
  637. Statement::MakeReturn(stmt->line_num,
  638. Expression::MakeTuple(stmt->line_num, {})));
  639. } else {
  640. std::cerr
  641. << stmt->line_num
  642. << ": control-flow reaches end of non-void function without a "
  643. "return"
  644. << std::endl;
  645. exit(-1);
  646. }
  647. }
  648. }
  649. auto TypeCheckFunDef(const FunctionDefinition* f, TypeEnv types, Env values)
  650. -> struct FunctionDefinition* {
  651. auto param_res = TypeCheckExp(f->param_pattern, types, values, nullptr,
  652. TCContext::PatternContext);
  653. auto return_type = InterpExp(values, f->return_type);
  654. if (f->name == "main") {
  655. ExpectType(f->line_num, "return type of `main`", Value::MakeIntTypeVal(),
  656. return_type);
  657. // TODO: Check that main doesn't have any parameters.
  658. }
  659. auto res = TypeCheckStmt(f->body, param_res.types, values, return_type);
  660. bool void_return = TypeEqual(return_type, Value::MakeUnitTypeVal());
  661. auto body = CheckOrEnsureReturn(res.stmt, void_return, f->line_num);
  662. return MakeFunDef(f->line_num, f->name, ReifyType(return_type, f->line_num),
  663. f->param_pattern, body);
  664. }
  665. auto TypeOfFunDef(TypeEnv types, Env values, const FunctionDefinition* fun_def)
  666. -> const Value* {
  667. auto param_res = TypeCheckExp(fun_def->param_pattern, types, values, nullptr,
  668. TCContext::PatternContext);
  669. auto ret = InterpExp(values, fun_def->return_type);
  670. if (ret->tag == ValKind::AutoTV) {
  671. auto f = TypeCheckFunDef(fun_def, types, values);
  672. ret = InterpExp(values, f->return_type);
  673. }
  674. return Value::MakeFunTypeVal(param_res.type, ret);
  675. }
  676. auto TypeOfStructDef(const StructDefinition* sd, TypeEnv /*types*/, Env ct_top)
  677. -> const Value* {
  678. auto fields = new VarValues();
  679. auto methods = new VarValues();
  680. for (auto m = sd->members->begin(); m != sd->members->end(); ++m) {
  681. if ((*m)->tag == MemberKind::FieldMember) {
  682. auto t = InterpExp(ct_top, (*m)->u.field.type);
  683. fields->push_back(std::make_pair(*(*m)->u.field.name, t));
  684. }
  685. }
  686. return Value::MakeStructTypeVal(*sd->name, fields, methods);
  687. }
  688. auto FunctionDeclaration::Name() const -> std::string {
  689. return definition->name;
  690. }
  691. auto StructDeclaration::Name() const -> std::string { return *definition.name; }
  692. auto ChoiceDeclaration::Name() const -> std::string { return name; }
  693. // Returns the name of the declared variable.
  694. auto VariableDeclaration::Name() const -> std::string { return name; }
  695. auto StructDeclaration::TypeChecked(TypeEnv types, Env values) const
  696. -> Declaration {
  697. auto fields = new std::list<Member*>();
  698. for (auto& m : *definition.members) {
  699. if (m->tag == MemberKind::FieldMember) {
  700. // TODO: Interpret the type expression and store the result.
  701. fields->push_back(m);
  702. }
  703. }
  704. return StructDeclaration(definition.line_num, *definition.name, fields);
  705. }
  706. auto FunctionDeclaration::TypeChecked(TypeEnv types, Env values) const
  707. -> Declaration {
  708. return FunctionDeclaration(TypeCheckFunDef(definition, types, values));
  709. }
  710. auto ChoiceDeclaration::TypeChecked(TypeEnv types, Env values) const
  711. -> Declaration {
  712. return *this; // TODO.
  713. }
  714. // Signals a type error if the initializing expression does not have
  715. // the declared type of the variable, otherwise returns this
  716. // declaration with annotated types.
  717. auto VariableDeclaration::TypeChecked(TypeEnv types, Env values) const
  718. -> Declaration {
  719. TCResult type_checked_initializer = TypeCheckExp(
  720. initializer, types, values, nullptr, TCContext::ValueContext);
  721. const Value* declared_type = InterpExp(values, type);
  722. ExpectType(source_location, "initializer of variable", declared_type,
  723. type_checked_initializer.type);
  724. return *this;
  725. }
  726. auto TopLevel(std::list<Declaration>* fs) -> TypeCheckContext {
  727. TypeCheckContext tops;
  728. bool found_main = false;
  729. for (auto const& d : *fs) {
  730. if (d.Name() == "main") {
  731. found_main = true;
  732. }
  733. d.TopLevel(tops);
  734. }
  735. if (found_main == false) {
  736. std::cerr << "error, program must contain a function named `main`"
  737. << std::endl;
  738. exit(-1);
  739. }
  740. return tops;
  741. }
  742. auto FunctionDeclaration::TopLevel(TypeCheckContext& tops) const -> void {
  743. auto t = TypeOfFunDef(tops.types, tops.values, definition);
  744. tops.types.Set(Name(), t);
  745. InitGlobals(tops.values);
  746. }
  747. auto StructDeclaration::TopLevel(TypeCheckContext& tops) const -> void {
  748. auto st = TypeOfStructDef(&definition, tops.types, tops.values);
  749. Address a = state->heap.AllocateValue(st);
  750. tops.values.Set(Name(), a); // Is this obsolete?
  751. auto field_types = new std::vector<TupleElement>();
  752. for (const auto& [field_name, field_value] : *st->GetStructType().fields) {
  753. field_types->push_back({.name = field_name,
  754. .address = state->heap.AllocateValue(field_value)});
  755. }
  756. auto fun_ty = Value::MakeFunTypeVal(Value::MakeTupleVal(field_types), st);
  757. tops.types.Set(Name(), fun_ty);
  758. }
  759. auto ChoiceDeclaration::TopLevel(TypeCheckContext& tops) const -> void {
  760. auto alts = new VarValues();
  761. for (auto a : alternatives) {
  762. auto t = InterpExp(tops.values, a.second);
  763. alts->push_back(std::make_pair(a.first, t));
  764. }
  765. auto ct = Value::MakeChoiceTypeVal(name, alts);
  766. Address a = state->heap.AllocateValue(ct);
  767. tops.values.Set(Name(), a); // Is this obsolete?
  768. tops.types.Set(Name(), ct);
  769. }
  770. // Associate the variable name with it's declared type in the
  771. // compile-time symbol table.
  772. auto VariableDeclaration::TopLevel(TypeCheckContext& tops) const -> void {
  773. const Value* declared_type = InterpExp(tops.values, type);
  774. tops.types.Set(Name(), declared_type);
  775. }
  776. } // namespace Carbon