typecheck.cpp 42 KB

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