typecheck.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  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. case ValKind::VariableType:
  62. return Expression::MakeIdentifierExpression(0, t->GetVariableType().name);
  63. default:
  64. llvm::errs() << line_num << ": expected a type, not " << *t << "\n";
  65. exit(-1);
  66. }
  67. }
  68. // Perform type argument deduction, matching the parameter type `param`
  69. // against the argument type `arg`. Whenever there is an VariableType
  70. // in the parameter type, it is deduced to be the corresponding type
  71. // inside the argument type.
  72. // The `deduced` parameter is an accumulator, that is, it holds the
  73. // results so-far.
  74. auto ArgumentDeduction(int line_num, TypeEnv deduced, const Value* param,
  75. const Value* arg) -> TypeEnv {
  76. switch (param->tag()) {
  77. case ValKind::VariableType: {
  78. std::optional<const Value*> d =
  79. deduced.Get(param->GetVariableType().name);
  80. if (!d) {
  81. deduced.Set(param->GetVariableType().name, arg);
  82. } else {
  83. ExpectType(line_num, "argument deduction", *d, arg);
  84. }
  85. return deduced;
  86. }
  87. case ValKind::TupleValue: {
  88. if (arg->tag() != ValKind::TupleValue) {
  89. ExpectType(line_num, "argument deduction", param, arg);
  90. }
  91. if (param->GetTupleValue().elements.size() !=
  92. arg->GetTupleValue().elements.size()) {
  93. ExpectType(line_num, "argument deduction", param, arg);
  94. }
  95. for (size_t i = 0; i < param->GetTupleValue().elements.size(); ++i) {
  96. if (param->GetTupleValue().elements[i].name !=
  97. arg->GetTupleValue().elements[i].name) {
  98. std::cerr << line_num << ": mismatch in tuple names, "
  99. << param->GetTupleValue().elements[i].name
  100. << " != " << arg->GetTupleValue().elements[i].name
  101. << std::endl;
  102. exit(-1);
  103. }
  104. deduced = ArgumentDeduction(line_num, deduced,
  105. param->GetTupleValue().elements[i].value,
  106. arg->GetTupleValue().elements[i].value);
  107. }
  108. return deduced;
  109. }
  110. case ValKind::FunctionType: {
  111. if (arg->tag() != ValKind::FunctionType) {
  112. ExpectType(line_num, "argument deduction", param, arg);
  113. }
  114. // TODO: handle situation when arg has deduced parameters.
  115. deduced =
  116. ArgumentDeduction(line_num, deduced, param->GetFunctionType().param,
  117. arg->GetFunctionType().param);
  118. deduced =
  119. ArgumentDeduction(line_num, deduced, param->GetFunctionType().ret,
  120. arg->GetFunctionType().ret);
  121. return deduced;
  122. }
  123. case ValKind::PointerType: {
  124. if (arg->tag() != ValKind::PointerType) {
  125. ExpectType(line_num, "argument deduction", param, arg);
  126. }
  127. return ArgumentDeduction(line_num, deduced, param->GetPointerType().type,
  128. arg->GetPointerType().type);
  129. }
  130. // Nothing to do in the case for `auto`.
  131. case ValKind::AutoType: {
  132. return deduced;
  133. }
  134. // For the following cases, we check for type equality.
  135. case ValKind::ContinuationType:
  136. case ValKind::StructType:
  137. case ValKind::ChoiceType:
  138. case ValKind::IntType:
  139. case ValKind::BoolType:
  140. case ValKind::TypeType: {
  141. ExpectType(line_num, "argument deduction", param, arg);
  142. return deduced;
  143. }
  144. // The rest of these cases should never happen.
  145. case ValKind::IntValue:
  146. case ValKind::BoolValue:
  147. case ValKind::FunctionValue:
  148. case ValKind::PointerValue:
  149. case ValKind::StructValue:
  150. case ValKind::AlternativeValue:
  151. case ValKind::BindingPlaceholderValue:
  152. case ValKind::AlternativeConstructorValue:
  153. case ValKind::ContinuationValue:
  154. llvm::errs() << line_num
  155. << ": internal error in ArgumentDeduction: expected type, "
  156. << "not value " << *param << "\n";
  157. exit(-1);
  158. }
  159. }
  160. auto Substitute(TypeEnv dict, const Value* type) -> const Value* {
  161. switch (type->tag()) {
  162. case ValKind::VariableType: {
  163. std::optional<const Value*> t = dict.Get(type->GetVariableType().name);
  164. if (!t) {
  165. return type;
  166. } else {
  167. return *t;
  168. }
  169. }
  170. case ValKind::TupleValue: {
  171. std::vector<TupleElement> elts;
  172. for (const auto& elt : type->GetTupleValue().elements) {
  173. auto t = Substitute(dict, elt.value);
  174. elts.push_back({.name = elt.name, .value = t});
  175. }
  176. return Value::MakeTupleValue(elts);
  177. }
  178. case ValKind::FunctionType: {
  179. auto param = Substitute(dict, type->GetFunctionType().param);
  180. auto ret = Substitute(dict, type->GetFunctionType().ret);
  181. return Value::MakeFunctionType({}, param, ret);
  182. }
  183. case ValKind::PointerType: {
  184. return Value::MakePointerType(
  185. Substitute(dict, type->GetPointerType().type));
  186. }
  187. case ValKind::AutoType:
  188. case ValKind::IntType:
  189. case ValKind::BoolType:
  190. case ValKind::TypeType:
  191. case ValKind::StructType:
  192. case ValKind::ChoiceType:
  193. case ValKind::ContinuationType:
  194. return type;
  195. // The rest of these cases should never happen.
  196. case ValKind::IntValue:
  197. case ValKind::BoolValue:
  198. case ValKind::FunctionValue:
  199. case ValKind::PointerValue:
  200. case ValKind::StructValue:
  201. case ValKind::AlternativeValue:
  202. case ValKind::BindingPlaceholderValue:
  203. case ValKind::AlternativeConstructorValue:
  204. case ValKind::ContinuationValue:
  205. llvm::errs() << "internal error in Substitute: expected type, "
  206. << "not value " << *type << "\n";
  207. exit(-1);
  208. }
  209. }
  210. // The TypeCheckExp function performs semantic analysis on an expression.
  211. // It returns a new version of the expression, its type, and an
  212. // updated environment which are bundled into a TCResult object.
  213. // The purpose of the updated environment is
  214. // to bring pattern variables into scope, for example, in a match case.
  215. // The new version of the expression may include more information,
  216. // for example, the type arguments deduced for the type parameters of a
  217. // generic.
  218. //
  219. // e is the expression to be analyzed.
  220. // types maps variable names to the type of their run-time value.
  221. // values maps variable names to their compile-time values. It is not
  222. // directly used in this function but is passed to InterExp.
  223. // expected is the type that this expression is expected to have.
  224. // This parameter is non-null when the expression is in a pattern context
  225. // and it is used to implement `auto`, otherwise it is null.
  226. // context says what kind of position this expression is nested in,
  227. // whether it's a position that expects a value, a pattern, or a type.
  228. auto TypeCheckExp(const Expression* e, TypeEnv types, Env values,
  229. const Value* expected, TCContext context) -> TCResult {
  230. if (tracing_output) {
  231. switch (context) {
  232. case TCContext::ValueContext:
  233. llvm::outs() << "checking expression ";
  234. break;
  235. case TCContext::PatternContext:
  236. llvm::outs() << "checking pattern, ";
  237. if (expected) {
  238. llvm::outs() << "expecting " << *expected;
  239. }
  240. llvm::outs() << ", ";
  241. break;
  242. case TCContext::TypeContext:
  243. llvm::outs() << "checking type ";
  244. break;
  245. }
  246. llvm::outs() << *e << "\n";
  247. }
  248. switch (e->tag()) {
  249. case ExpressionKind::BindingExpression: {
  250. if (context != TCContext::PatternContext) {
  251. llvm::errs()
  252. << e->line_num
  253. << ": compilation error, pattern variables are only allowed in "
  254. "pattern context"
  255. << "\n";
  256. exit(-1);
  257. }
  258. auto t = InterpExp(values, e->GetBindingExpression().type);
  259. if (t->tag() == ValKind::AutoType) {
  260. if (expected == nullptr) {
  261. llvm::errs() << e->line_num
  262. << ": compilation error, auto not allowed here"
  263. << "\n";
  264. exit(-1);
  265. } else {
  266. t = expected;
  267. }
  268. } else if (expected) {
  269. ExpectType(e->line_num, "pattern variable", t, expected);
  270. }
  271. const std::optional<std::string>& name = e->GetBindingExpression().name;
  272. auto new_e = Expression::MakeBindingExpression(e->line_num, name,
  273. ReifyType(t, e->line_num));
  274. if (name.has_value()) {
  275. types.Set(*name, t);
  276. }
  277. return TCResult(new_e, t, types);
  278. }
  279. case ExpressionKind::IndexExpression: {
  280. auto res = TypeCheckExp(e->GetIndexExpression().aggregate, types, values,
  281. nullptr, TCContext::ValueContext);
  282. auto t = res.type;
  283. switch (t->tag()) {
  284. case ValKind::TupleValue: {
  285. auto i =
  286. InterpExp(values, e->GetIndexExpression().offset)->GetIntValue();
  287. std::string f = std::to_string(i);
  288. const Value* field_t = t->GetTupleValue().FindField(f);
  289. if (field_t == nullptr) {
  290. llvm::errs() << e->line_num << ": compilation error, field " << f
  291. << " is not in the tuple " << *t << "\n";
  292. exit(-1);
  293. }
  294. auto new_e = Expression::MakeIndexExpression(
  295. e->line_num, res.exp, Expression::MakeIntLiteral(e->line_num, i));
  296. return TCResult(new_e, field_t, res.types);
  297. }
  298. default:
  299. llvm::errs() << e->line_num
  300. << ": compilation error, expected a tuple\n";
  301. exit(-1);
  302. }
  303. }
  304. case ExpressionKind::TupleLiteral: {
  305. std::vector<FieldInitializer> new_args;
  306. std::vector<TupleElement> arg_types;
  307. auto new_types = types;
  308. if (expected && expected->tag() != ValKind::TupleValue) {
  309. llvm::errs() << e->line_num
  310. << ": compilation error, didn't expect a tuple\n";
  311. exit(-1);
  312. }
  313. if (expected && e->GetTupleLiteral().fields.size() !=
  314. expected->GetTupleValue().elements.size()) {
  315. llvm::errs() << e->line_num
  316. << ": compilation error, tuples of different length\n";
  317. exit(-1);
  318. }
  319. int i = 0;
  320. for (auto arg = e->GetTupleLiteral().fields.begin();
  321. arg != e->GetTupleLiteral().fields.end(); ++arg, ++i) {
  322. const Value* arg_expected = nullptr;
  323. if (expected && expected->tag() == ValKind::TupleValue) {
  324. if (expected->GetTupleValue().elements[i].name != arg->name) {
  325. llvm::errs()
  326. << e->line_num
  327. << ": compilation error, field names do not match, expected "
  328. << expected->GetTupleValue().elements[i].name << " but got "
  329. << arg->name << "\n";
  330. exit(-1);
  331. }
  332. arg_expected = expected->GetTupleValue().elements[i].value;
  333. }
  334. auto arg_res = TypeCheckExp(arg->expression, new_types, values,
  335. arg_expected, context);
  336. new_types = arg_res.types;
  337. new_args.push_back({.name = arg->name, .expression = arg_res.exp});
  338. arg_types.push_back({.name = arg->name, .value = arg_res.type});
  339. }
  340. auto tuple_e = Expression::MakeTupleLiteral(e->line_num, new_args);
  341. auto tuple_t = Value::MakeTupleValue(std::move(arg_types));
  342. return TCResult(tuple_e, tuple_t, new_types);
  343. }
  344. case ExpressionKind::FieldAccessExpression: {
  345. auto res = TypeCheckExp(e->GetFieldAccessExpression().aggregate, types,
  346. values, nullptr, TCContext::ValueContext);
  347. auto t = res.type;
  348. switch (t->tag()) {
  349. case ValKind::StructType:
  350. // Search for a field
  351. for (auto& field : t->GetStructType().fields) {
  352. if (e->GetFieldAccessExpression().field == field.first) {
  353. const Expression* new_e = Expression::MakeFieldAccessExpression(
  354. e->line_num, res.exp, e->GetFieldAccessExpression().field);
  355. return TCResult(new_e, field.second, res.types);
  356. }
  357. }
  358. // Search for a method
  359. for (auto& method : t->GetStructType().methods) {
  360. if (e->GetFieldAccessExpression().field == method.first) {
  361. const Expression* new_e = Expression::MakeFieldAccessExpression(
  362. e->line_num, res.exp, e->GetFieldAccessExpression().field);
  363. return TCResult(new_e, method.second, res.types);
  364. }
  365. }
  366. llvm::errs() << e->line_num << ": compilation error, struct "
  367. << t->GetStructType().name
  368. << " does not have a field named "
  369. << e->GetFieldAccessExpression().field << "\n";
  370. exit(-1);
  371. case ValKind::TupleValue:
  372. for (const TupleElement& field : t->GetTupleValue().elements) {
  373. if (e->GetFieldAccessExpression().field == field.name) {
  374. auto new_e = Expression::MakeFieldAccessExpression(
  375. e->line_num, res.exp, e->GetFieldAccessExpression().field);
  376. return TCResult(new_e, field.value, res.types);
  377. }
  378. }
  379. llvm::errs() << e->line_num << ": compilation error, struct "
  380. << t->GetStructType().name
  381. << " does not have a field named "
  382. << e->GetFieldAccessExpression().field << "\n";
  383. exit(-1);
  384. case ValKind::ChoiceType:
  385. for (auto vt = t->GetChoiceType().alternatives.begin();
  386. vt != t->GetChoiceType().alternatives.end(); ++vt) {
  387. if (e->GetFieldAccessExpression().field == vt->first) {
  388. const Expression* new_e = Expression::MakeFieldAccessExpression(
  389. e->line_num, res.exp, e->GetFieldAccessExpression().field);
  390. auto fun_ty = Value::MakeFunctionType({}, vt->second, t);
  391. return TCResult(new_e, fun_ty, res.types);
  392. }
  393. }
  394. llvm::errs() << e->line_num << ": compilation error, struct "
  395. << t->GetStructType().name
  396. << " does not have a field named "
  397. << e->GetFieldAccessExpression().field << "\n";
  398. exit(-1);
  399. default:
  400. llvm::errs()
  401. << e->line_num
  402. << ": compilation error in field access, expected a struct\n"
  403. << *e << "\n";
  404. exit(-1);
  405. }
  406. }
  407. case ExpressionKind::IdentifierExpression: {
  408. std::optional<const Value*> type =
  409. types.Get(e->GetIdentifierExpression().name);
  410. if (type) {
  411. return TCResult(e, *type, types);
  412. } else {
  413. llvm::errs() << e->line_num << ": could not find `"
  414. << e->GetIdentifierExpression().name << "`\n";
  415. exit(-1);
  416. }
  417. }
  418. case ExpressionKind::IntLiteral:
  419. return TCResult(e, Value::MakeIntType(), types);
  420. case ExpressionKind::BoolLiteral:
  421. return TCResult(e, Value::MakeBoolType(), types);
  422. case ExpressionKind::PrimitiveOperatorExpression: {
  423. std::vector<const Expression*> es;
  424. std::vector<const Value*> ts;
  425. auto new_types = types;
  426. for (const Expression* argument :
  427. e->GetPrimitiveOperatorExpression().arguments) {
  428. auto res = TypeCheckExp(argument, types, values, nullptr,
  429. TCContext::ValueContext);
  430. new_types = res.types;
  431. es.push_back(res.exp);
  432. ts.push_back(res.type);
  433. }
  434. auto new_e = Expression::MakePrimitiveOperatorExpression(
  435. e->line_num, e->GetPrimitiveOperatorExpression().op, es);
  436. switch (e->GetPrimitiveOperatorExpression().op) {
  437. case Operator::Neg:
  438. ExpectType(e->line_num, "negation", Value::MakeIntType(), ts[0]);
  439. return TCResult(new_e, Value::MakeIntType(), new_types);
  440. case Operator::Add:
  441. ExpectType(e->line_num, "addition(1)", Value::MakeIntType(), ts[0]);
  442. ExpectType(e->line_num, "addition(2)", Value::MakeIntType(), ts[1]);
  443. return TCResult(new_e, Value::MakeIntType(), new_types);
  444. case Operator::Sub:
  445. ExpectType(e->line_num, "subtraction(1)", Value::MakeIntType(),
  446. ts[0]);
  447. ExpectType(e->line_num, "subtraction(2)", Value::MakeIntType(),
  448. ts[1]);
  449. return TCResult(new_e, Value::MakeIntType(), new_types);
  450. case Operator::Mul:
  451. ExpectType(e->line_num, "multiplication(1)", Value::MakeIntType(),
  452. ts[0]);
  453. ExpectType(e->line_num, "multiplication(2)", Value::MakeIntType(),
  454. ts[1]);
  455. return TCResult(new_e, Value::MakeIntType(), new_types);
  456. case Operator::And:
  457. ExpectType(e->line_num, "&&(1)", Value::MakeBoolType(), ts[0]);
  458. ExpectType(e->line_num, "&&(2)", Value::MakeBoolType(), ts[1]);
  459. return TCResult(new_e, Value::MakeBoolType(), new_types);
  460. case Operator::Or:
  461. ExpectType(e->line_num, "||(1)", Value::MakeBoolType(), ts[0]);
  462. ExpectType(e->line_num, "||(2)", Value::MakeBoolType(), ts[1]);
  463. return TCResult(new_e, Value::MakeBoolType(), new_types);
  464. case Operator::Not:
  465. ExpectType(e->line_num, "!", Value::MakeBoolType(), ts[0]);
  466. return TCResult(new_e, Value::MakeBoolType(), new_types);
  467. case Operator::Eq:
  468. ExpectType(e->line_num, "==", ts[0], ts[1]);
  469. return TCResult(new_e, Value::MakeBoolType(), new_types);
  470. case Operator::Deref:
  471. ExpectPointerType(e->line_num, "*", ts[0]);
  472. return TCResult(new_e, ts[0]->GetPointerType().type, new_types);
  473. case Operator::Ptr:
  474. ExpectType(e->line_num, "*", Value::MakeTypeType(), ts[0]);
  475. return TCResult(new_e, Value::MakeTypeType(), new_types);
  476. }
  477. break;
  478. }
  479. case ExpressionKind::CallExpression: {
  480. auto fun_res = TypeCheckExp(e->GetCallExpression().function, types,
  481. values, nullptr, TCContext::ValueContext);
  482. switch (fun_res.type->tag()) {
  483. case ValKind::FunctionType: {
  484. auto fun_t = fun_res.type;
  485. auto arg_res =
  486. TypeCheckExp(e->GetCallExpression().argument, fun_res.types,
  487. values, fun_t->GetFunctionType().param, context);
  488. auto parameter_type = fun_t->GetFunctionType().param;
  489. auto return_type = fun_t->GetFunctionType().ret;
  490. if (fun_t->GetFunctionType().deduced.size() > 0) {
  491. auto deduced_args = ArgumentDeduction(e->line_num, TypeEnv(),
  492. parameter_type, arg_res.type);
  493. for (auto& deduced_param : fun_t->GetFunctionType().deduced) {
  494. // TODO: change the following to a CHECK once the real checking
  495. // has been added to the type checking of function signatures.
  496. if (!deduced_args.Get(deduced_param.name)) {
  497. std::cerr << e->line_num
  498. << ": error, could not deduce type argument for type "
  499. "parameter "
  500. << deduced_param.name << std::endl;
  501. exit(-1);
  502. }
  503. }
  504. parameter_type = Substitute(deduced_args, parameter_type);
  505. return_type = Substitute(deduced_args, return_type);
  506. } else {
  507. ExpectType(e->line_num, "call", parameter_type, arg_res.type);
  508. }
  509. auto new_e = Expression::MakeCallExpression(e->line_num, fun_res.exp,
  510. arg_res.exp);
  511. return TCResult(new_e, return_type, arg_res.types);
  512. }
  513. default: {
  514. llvm::errs() << e->line_num
  515. << ": compilation error in call, expected a function\n"
  516. << *e << "\n";
  517. exit(-1);
  518. }
  519. }
  520. break;
  521. }
  522. case ExpressionKind::FunctionTypeLiteral: {
  523. switch (context) {
  524. case TCContext::ValueContext:
  525. case TCContext::TypeContext: {
  526. auto pt = InterpExp(values, e->GetFunctionTypeLiteral().parameter);
  527. auto rt = InterpExp(values, e->GetFunctionTypeLiteral().return_type);
  528. auto new_e = Expression::MakeFunctionTypeLiteral(
  529. e->line_num, ReifyType(pt, e->line_num),
  530. ReifyType(rt, e->line_num));
  531. return TCResult(new_e, Value::MakeTypeType(), types);
  532. }
  533. case TCContext::PatternContext: {
  534. auto param_res = TypeCheckExp(e->GetFunctionTypeLiteral().parameter,
  535. types, values, nullptr, context);
  536. auto ret_res =
  537. TypeCheckExp(e->GetFunctionTypeLiteral().return_type,
  538. param_res.types, values, nullptr, context);
  539. auto new_e = Expression::MakeFunctionTypeLiteral(
  540. e->line_num, ReifyType(param_res.type, e->line_num),
  541. ReifyType(ret_res.type, e->line_num));
  542. return TCResult(new_e, Value::MakeTypeType(), ret_res.types);
  543. }
  544. }
  545. }
  546. case ExpressionKind::IntTypeLiteral:
  547. return TCResult(e, Value::MakeTypeType(), types);
  548. case ExpressionKind::BoolTypeLiteral:
  549. return TCResult(e, Value::MakeTypeType(), types);
  550. case ExpressionKind::TypeTypeLiteral:
  551. return TCResult(e, Value::MakeTypeType(), types);
  552. case ExpressionKind::AutoTypeLiteral:
  553. return TCResult(e, Value::MakeTypeType(), types);
  554. case ExpressionKind::ContinuationTypeLiteral:
  555. return TCResult(e, Value::MakeTypeType(), types);
  556. }
  557. }
  558. auto TypecheckCase(const Value* expected, const Expression* pat,
  559. const Statement* body, TypeEnv types, Env values,
  560. const Value*& ret_type)
  561. -> std::pair<const Expression*, const Statement*> {
  562. auto pat_res =
  563. TypeCheckExp(pat, types, values, expected, TCContext::PatternContext);
  564. auto res = TypeCheckStmt(body, pat_res.types, values, ret_type);
  565. return std::make_pair(pat, res.stmt);
  566. }
  567. // The TypeCheckStmt function performs semantic analysis on a statement.
  568. // It returns a new version of the statement and a new type environment.
  569. //
  570. // The ret_type parameter is used for analyzing return statements.
  571. // It is the declared return type of the enclosing function definition.
  572. // If the return type is "auto", then the return type is inferred from
  573. // the first return statement.
  574. auto TypeCheckStmt(const Statement* s, TypeEnv types, Env values,
  575. const Value*& ret_type) -> TCStatement {
  576. if (!s) {
  577. return TCStatement(s, types);
  578. }
  579. switch (s->tag()) {
  580. case StatementKind::Match: {
  581. auto res = TypeCheckExp(s->GetMatch().exp, types, values, nullptr,
  582. TCContext::ValueContext);
  583. auto res_type = res.type;
  584. auto new_clauses =
  585. new std::list<std::pair<const Expression*, const Statement*>>();
  586. for (auto& clause : *s->GetMatch().clauses) {
  587. new_clauses->push_back(TypecheckCase(
  588. res_type, clause.first, clause.second, types, values, ret_type));
  589. }
  590. const Statement* new_s =
  591. Statement::MakeMatch(s->line_num, res.exp, new_clauses);
  592. return TCStatement(new_s, types);
  593. }
  594. case StatementKind::While: {
  595. auto cnd_res = TypeCheckExp(s->GetWhile().cond, types, values, nullptr,
  596. TCContext::ValueContext);
  597. ExpectType(s->line_num, "condition of `while`", Value::MakeBoolType(),
  598. cnd_res.type);
  599. auto body_res =
  600. TypeCheckStmt(s->GetWhile().body, types, values, ret_type);
  601. auto new_s =
  602. Statement::MakeWhile(s->line_num, cnd_res.exp, body_res.stmt);
  603. return TCStatement(new_s, types);
  604. }
  605. case StatementKind::Break:
  606. case StatementKind::Continue:
  607. return TCStatement(s, types);
  608. case StatementKind::Block: {
  609. auto stmt_res =
  610. TypeCheckStmt(s->GetBlock().stmt, types, values, ret_type);
  611. return TCStatement(Statement::MakeBlock(s->line_num, stmt_res.stmt),
  612. types);
  613. }
  614. case StatementKind::VariableDefinition: {
  615. auto res = TypeCheckExp(s->GetVariableDefinition().init, types, values,
  616. nullptr, TCContext::ValueContext);
  617. const Value* rhs_ty = res.type;
  618. auto lhs_res = TypeCheckExp(s->GetVariableDefinition().pat, types, values,
  619. rhs_ty, TCContext::PatternContext);
  620. const Statement* new_s = Statement::MakeVariableDefinition(
  621. s->line_num, s->GetVariableDefinition().pat, res.exp);
  622. return TCStatement(new_s, lhs_res.types);
  623. }
  624. case StatementKind::Sequence: {
  625. auto stmt_res =
  626. TypeCheckStmt(s->GetSequence().stmt, types, values, ret_type);
  627. auto types2 = stmt_res.types;
  628. auto next_res =
  629. TypeCheckStmt(s->GetSequence().next, types2, values, ret_type);
  630. auto types3 = next_res.types;
  631. return TCStatement(
  632. Statement::MakeSequence(s->line_num, stmt_res.stmt, next_res.stmt),
  633. types3);
  634. }
  635. case StatementKind::Assign: {
  636. auto rhs_res = TypeCheckExp(s->GetAssign().rhs, types, values, nullptr,
  637. TCContext::ValueContext);
  638. auto rhs_t = rhs_res.type;
  639. auto lhs_res = TypeCheckExp(s->GetAssign().lhs, types, values, rhs_t,
  640. TCContext::ValueContext);
  641. auto lhs_t = lhs_res.type;
  642. ExpectType(s->line_num, "assign", lhs_t, rhs_t);
  643. auto new_s = Statement::MakeAssign(s->line_num, lhs_res.exp, rhs_res.exp);
  644. return TCStatement(new_s, lhs_res.types);
  645. }
  646. case StatementKind::ExpressionStatement: {
  647. auto res = TypeCheckExp(s->GetExpressionStatement().exp, types, values,
  648. nullptr, TCContext::ValueContext);
  649. auto new_s = Statement::MakeExpressionStatement(s->line_num, res.exp);
  650. return TCStatement(new_s, types);
  651. }
  652. case StatementKind::If: {
  653. auto cnd_res = TypeCheckExp(s->GetIf().cond, types, values, nullptr,
  654. TCContext::ValueContext);
  655. ExpectType(s->line_num, "condition of `if`", Value::MakeBoolType(),
  656. cnd_res.type);
  657. auto thn_res =
  658. TypeCheckStmt(s->GetIf().then_stmt, types, values, ret_type);
  659. auto els_res =
  660. TypeCheckStmt(s->GetIf().else_stmt, types, values, ret_type);
  661. auto new_s = Statement::MakeIf(s->line_num, cnd_res.exp, thn_res.stmt,
  662. els_res.stmt);
  663. return TCStatement(new_s, types);
  664. }
  665. case StatementKind::Return: {
  666. auto res = TypeCheckExp(s->GetReturn().exp, types, values, nullptr,
  667. TCContext::ValueContext);
  668. if (ret_type->tag() == ValKind::AutoType) {
  669. // The following infers the return type from the first 'return'
  670. // statement. This will get more difficult with subtyping, when we
  671. // should infer the least-upper bound of all the 'return' statements.
  672. ret_type = res.type;
  673. } else {
  674. ExpectType(s->line_num, "return", ret_type, res.type);
  675. }
  676. return TCStatement(Statement::MakeReturn(s->line_num, res.exp), types);
  677. }
  678. case StatementKind::Continuation: {
  679. TCStatement body_result =
  680. TypeCheckStmt(s->GetContinuation().body, types, values, ret_type);
  681. const Statement* new_continuation = Statement::MakeContinuation(
  682. s->line_num, s->GetContinuation().continuation_variable,
  683. body_result.stmt);
  684. types.Set(s->GetContinuation().continuation_variable,
  685. Value::MakeContinuationType());
  686. return TCStatement(new_continuation, types);
  687. }
  688. case StatementKind::Run: {
  689. TCResult argument_result =
  690. TypeCheckExp(s->GetRun().argument, types, values, nullptr,
  691. TCContext::ValueContext);
  692. ExpectType(s->line_num, "argument of `run`",
  693. Value::MakeContinuationType(), argument_result.type);
  694. const Statement* new_run =
  695. Statement::MakeRun(s->line_num, argument_result.exp);
  696. return TCStatement(new_run, types);
  697. }
  698. case StatementKind::Await: {
  699. // nothing to do here
  700. return TCStatement(s, types);
  701. }
  702. } // switch
  703. }
  704. auto CheckOrEnsureReturn(const Statement* stmt, bool void_return, int line_num)
  705. -> const Statement* {
  706. if (!stmt) {
  707. if (void_return) {
  708. return Statement::MakeReturn(line_num,
  709. Expression::MakeTupleLiteral(line_num, {}));
  710. } else {
  711. llvm::errs()
  712. << "control-flow reaches end of non-void function without a return\n";
  713. exit(-1);
  714. }
  715. }
  716. switch (stmt->tag()) {
  717. case StatementKind::Match: {
  718. auto new_clauses =
  719. new std::list<std::pair<const Expression*, const Statement*>>();
  720. for (auto i = stmt->GetMatch().clauses->begin();
  721. i != stmt->GetMatch().clauses->end(); ++i) {
  722. auto s = CheckOrEnsureReturn(i->second, void_return, stmt->line_num);
  723. new_clauses->push_back(std::make_pair(i->first, s));
  724. }
  725. return Statement::MakeMatch(stmt->line_num, stmt->GetMatch().exp,
  726. new_clauses);
  727. }
  728. case StatementKind::Block:
  729. return Statement::MakeBlock(
  730. stmt->line_num, CheckOrEnsureReturn(stmt->GetBlock().stmt,
  731. void_return, stmt->line_num));
  732. case StatementKind::If:
  733. return Statement::MakeIf(
  734. stmt->line_num, stmt->GetIf().cond,
  735. CheckOrEnsureReturn(stmt->GetIf().then_stmt, void_return,
  736. stmt->line_num),
  737. CheckOrEnsureReturn(stmt->GetIf().else_stmt, void_return,
  738. stmt->line_num));
  739. case StatementKind::Return:
  740. return stmt;
  741. case StatementKind::Sequence:
  742. if (stmt->GetSequence().next) {
  743. return Statement::MakeSequence(
  744. stmt->line_num, stmt->GetSequence().stmt,
  745. CheckOrEnsureReturn(stmt->GetSequence().next, void_return,
  746. stmt->line_num));
  747. } else {
  748. return CheckOrEnsureReturn(stmt->GetSequence().stmt, void_return,
  749. stmt->line_num);
  750. }
  751. case StatementKind::Continuation:
  752. case StatementKind::Run:
  753. case StatementKind::Await:
  754. return stmt;
  755. case StatementKind::Assign:
  756. case StatementKind::ExpressionStatement:
  757. case StatementKind::While:
  758. case StatementKind::Break:
  759. case StatementKind::Continue:
  760. case StatementKind::VariableDefinition:
  761. if (void_return) {
  762. return Statement::MakeSequence(
  763. stmt->line_num, stmt,
  764. Statement::MakeReturn(stmt->line_num, Expression::MakeTupleLiteral(
  765. stmt->line_num, {})));
  766. } else {
  767. llvm::errs()
  768. << stmt->line_num
  769. << ": control-flow reaches end of non-void function without a "
  770. "return\n";
  771. exit(-1);
  772. }
  773. }
  774. }
  775. // TODO: factor common parts of TypeCheckFunDef and TypeOfFunDef into
  776. // a function.
  777. // TODO: Add checking to function definitions to ensure that
  778. // all deduced type parameters will be deduced.
  779. auto TypeCheckFunDef(const FunctionDefinition* f, TypeEnv types, Env values)
  780. -> struct FunctionDefinition* {
  781. // Bring the deduced parameters into scope
  782. for (const auto& deduced : f->deduced_parameters) {
  783. // auto t = InterpExp(values, deduced.type);
  784. Address a =
  785. state->heap.AllocateValue(Value::MakeVariableType(deduced.name));
  786. values.Set(deduced.name, a);
  787. }
  788. // Type check the parameter pattern
  789. auto param_res = TypeCheckExp(f->param_pattern, types, values, nullptr,
  790. TCContext::PatternContext);
  791. // Evaluate the return type expression
  792. auto return_type = InterpExp(values, f->return_type);
  793. if (f->name == "main") {
  794. ExpectType(f->line_num, "return type of `main`", Value::MakeIntType(),
  795. return_type);
  796. // TODO: Check that main doesn't have any parameters.
  797. }
  798. auto res = TypeCheckStmt(f->body, param_res.types, values, return_type);
  799. bool void_return = TypeEqual(return_type, Value::MakeUnitTypeVal());
  800. auto body = CheckOrEnsureReturn(res.stmt, void_return, f->line_num);
  801. return new FunctionDefinition(f->line_num, f->name, f->deduced_parameters,
  802. f->param_pattern,
  803. ReifyType(return_type, f->line_num), body);
  804. }
  805. auto TypeOfFunDef(TypeEnv types, Env values, const FunctionDefinition* fun_def)
  806. -> const Value* {
  807. // Bring the deduced parameters into scope
  808. for (const auto& deduced : fun_def->deduced_parameters) {
  809. // auto t = InterpExp(values, deduced.type);
  810. Address a =
  811. state->heap.AllocateValue(Value::MakeVariableType(deduced.name));
  812. values.Set(deduced.name, a);
  813. }
  814. // Type check the parameter pattern
  815. auto param_res = TypeCheckExp(fun_def->param_pattern, types, values, nullptr,
  816. TCContext::PatternContext);
  817. // Evaluate the return type expression
  818. auto ret = InterpExp(values, fun_def->return_type);
  819. if (ret->tag() == ValKind::AutoType) {
  820. auto f = TypeCheckFunDef(fun_def, types, values);
  821. ret = InterpExp(values, f->return_type);
  822. }
  823. return Value::MakeFunctionType(fun_def->deduced_parameters, param_res.type,
  824. ret);
  825. }
  826. auto TypeOfStructDef(const StructDefinition* sd, TypeEnv /*types*/, Env ct_top)
  827. -> const Value* {
  828. VarValues fields;
  829. VarValues methods;
  830. for (const Member* m : sd->members) {
  831. switch (m->tag()) {
  832. case MemberKind::FieldMember:
  833. auto t = InterpExp(ct_top, m->GetFieldMember().type);
  834. fields.push_back(std::make_pair(m->GetFieldMember().name, t));
  835. break;
  836. }
  837. }
  838. return Value::MakeStructType(sd->name, std::move(fields), std::move(methods));
  839. }
  840. static auto GetName(const Declaration& d) -> const std::string& {
  841. switch (d.tag()) {
  842. case DeclarationKind::FunctionDeclaration:
  843. return d.GetFunctionDeclaration().definition.name;
  844. case DeclarationKind::StructDeclaration:
  845. return d.GetStructDeclaration().definition.name;
  846. case DeclarationKind::ChoiceDeclaration:
  847. return d.GetChoiceDeclaration().name;
  848. case DeclarationKind::VariableDeclaration:
  849. return d.GetVariableDeclaration().name;
  850. }
  851. }
  852. auto MakeTypeChecked(const Declaration& d, const TypeEnv& types,
  853. const Env& values) -> Declaration {
  854. switch (d.tag()) {
  855. case DeclarationKind::FunctionDeclaration:
  856. return Declaration::MakeFunctionDeclaration(*TypeCheckFunDef(
  857. &d.GetFunctionDeclaration().definition, types, values));
  858. case DeclarationKind::StructDeclaration: {
  859. const StructDefinition& struct_def = d.GetStructDeclaration().definition;
  860. std::list<Member*> fields;
  861. for (Member* m : struct_def.members) {
  862. switch (m->tag()) {
  863. case MemberKind::FieldMember:
  864. // TODO: Interpret the type expression and store the result.
  865. fields.push_back(m);
  866. break;
  867. }
  868. }
  869. return Declaration::MakeStructDeclaration(
  870. struct_def.line_num, struct_def.name, std::move(fields));
  871. }
  872. case DeclarationKind::ChoiceDeclaration:
  873. // TODO
  874. return d;
  875. case DeclarationKind::VariableDeclaration: {
  876. const auto& var = d.GetVariableDeclaration();
  877. // Signals a type error if the initializing expression does not have
  878. // the declared type of the variable, otherwise returns this
  879. // declaration with annotated types.
  880. TCResult type_checked_initializer = TypeCheckExp(
  881. var.initializer, types, values, nullptr, TCContext::ValueContext);
  882. const Value* declared_type = InterpExp(values, var.type);
  883. ExpectType(var.source_location, "initializer of variable", declared_type,
  884. type_checked_initializer.type);
  885. return d;
  886. }
  887. }
  888. }
  889. static void TopLevel(const Declaration& d, TypeCheckContext* tops) {
  890. switch (d.tag()) {
  891. case DeclarationKind::FunctionDeclaration: {
  892. const FunctionDefinition& func_def =
  893. d.GetFunctionDeclaration().definition;
  894. auto t = TypeOfFunDef(tops->types, tops->values, &func_def);
  895. tops->types.Set(func_def.name, t);
  896. InitEnv(d, &tops->values);
  897. break;
  898. }
  899. case DeclarationKind::StructDeclaration: {
  900. const StructDefinition& struct_def = d.GetStructDeclaration().definition;
  901. auto st = TypeOfStructDef(&struct_def, tops->types, tops->values);
  902. Address a = state->heap.AllocateValue(st);
  903. tops->values.Set(struct_def.name, a); // Is this obsolete?
  904. std::vector<TupleElement> field_types;
  905. for (const auto& [field_name, field_value] : st->GetStructType().fields) {
  906. field_types.push_back({.name = field_name, .value = field_value});
  907. }
  908. auto fun_ty = Value::MakeFunctionType(
  909. {}, Value::MakeTupleValue(std::move(field_types)), st);
  910. tops->types.Set(struct_def.name, fun_ty);
  911. break;
  912. }
  913. case DeclarationKind::ChoiceDeclaration: {
  914. const auto& choice = d.GetChoiceDeclaration();
  915. VarValues alts;
  916. for (const auto& [name, signature] : choice.alternatives) {
  917. auto t = InterpExp(tops->values, signature);
  918. alts.push_back(std::make_pair(name, t));
  919. }
  920. auto ct = Value::MakeChoiceType(choice.name, std::move(alts));
  921. Address a = state->heap.AllocateValue(ct);
  922. tops->values.Set(choice.name, a); // Is this obsolete?
  923. tops->types.Set(choice.name, ct);
  924. break;
  925. }
  926. case DeclarationKind::VariableDeclaration: {
  927. const auto& var = d.GetVariableDeclaration();
  928. // Associate the variable name with it's declared type in the
  929. // compile-time symbol table.
  930. const Value* declared_type = InterpExp(tops->values, var.type);
  931. tops->types.Set(var.name, declared_type);
  932. break;
  933. }
  934. }
  935. }
  936. auto TopLevel(std::list<Declaration>* fs) -> TypeCheckContext {
  937. TypeCheckContext tops;
  938. bool found_main = false;
  939. for (auto const& d : *fs) {
  940. if (GetName(d) == "main") {
  941. found_main = true;
  942. }
  943. TopLevel(d, &tops);
  944. }
  945. if (found_main == false) {
  946. llvm::errs() << "error, program must contain a function named `main`\n";
  947. exit(-1);
  948. }
  949. return tops;
  950. }
  951. } // namespace Carbon