typecheck.cpp 33 KB

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