typecheck.cpp 33 KB

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