typecheck.cpp 33 KB

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