typecheck.cpp 33 KB

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