typecheck.cpp 32 KB

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