typecheck.cpp 33 KB

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