typecheck.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954
  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. FATAL_COMPILATION_ERROR(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. FATAL_COMPILATION_ERROR(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. FATAL_COMPILATION_ERROR(e->line_num)
  252. << "pattern variables are only allowed in pattern context";
  253. }
  254. auto t = InterpExp(values, e->GetBindingExpression().type);
  255. if (t->tag() == ValKind::AutoType) {
  256. if (expected == nullptr) {
  257. FATAL_COMPILATION_ERROR(e->line_num) << " auto not allowed here";
  258. } else {
  259. t = expected;
  260. }
  261. } else if (expected) {
  262. ExpectType(e->line_num, "pattern variable", t, expected);
  263. }
  264. const std::optional<std::string>& name = e->GetBindingExpression().name;
  265. auto new_e = Expression::MakeBindingExpression(e->line_num, name,
  266. ReifyType(t, e->line_num));
  267. if (name.has_value()) {
  268. types.Set(*name, t);
  269. }
  270. return TCResult(new_e, t, types);
  271. }
  272. case ExpressionKind::IndexExpression: {
  273. auto res = TypeCheckExp(e->GetIndexExpression().aggregate, types, values,
  274. nullptr, TCContext::ValueContext);
  275. auto t = res.type;
  276. switch (t->tag()) {
  277. case ValKind::TupleValue: {
  278. auto i =
  279. InterpExp(values, e->GetIndexExpression().offset)->GetIntValue();
  280. std::string f = std::to_string(i);
  281. const Value* field_t = t->GetTupleValue().FindField(f);
  282. if (field_t == nullptr) {
  283. FATAL_COMPILATION_ERROR(e->line_num)
  284. << "field " << f << " is not in the tuple " << *t;
  285. }
  286. auto new_e = Expression::MakeIndexExpression(
  287. e->line_num, res.exp, Expression::MakeIntLiteral(e->line_num, i));
  288. return TCResult(new_e, field_t, res.types);
  289. }
  290. default:
  291. FATAL_COMPILATION_ERROR(e->line_num) << "expected a tuple";
  292. }
  293. }
  294. case ExpressionKind::TupleLiteral: {
  295. std::vector<FieldInitializer> new_args;
  296. std::vector<TupleElement> arg_types;
  297. auto new_types = types;
  298. if (expected && expected->tag() != ValKind::TupleValue) {
  299. FATAL_COMPILATION_ERROR(e->line_num) << "didn't expect a tuple";
  300. }
  301. if (expected && e->GetTupleLiteral().fields.size() !=
  302. expected->GetTupleValue().elements.size()) {
  303. FATAL_COMPILATION_ERROR(e->line_num) << "tuples of different length";
  304. }
  305. int i = 0;
  306. for (auto arg = e->GetTupleLiteral().fields.begin();
  307. arg != e->GetTupleLiteral().fields.end(); ++arg, ++i) {
  308. const Value* arg_expected = nullptr;
  309. if (expected && expected->tag() == ValKind::TupleValue) {
  310. if (expected->GetTupleValue().elements[i].name != arg->name) {
  311. FATAL_COMPILATION_ERROR(e->line_num)
  312. << "field names do not match, expected "
  313. << expected->GetTupleValue().elements[i].name << " but got "
  314. << arg->name;
  315. }
  316. arg_expected = expected->GetTupleValue().elements[i].value;
  317. }
  318. auto arg_res = TypeCheckExp(arg->expression, new_types, values,
  319. arg_expected, context);
  320. new_types = arg_res.types;
  321. new_args.push_back({.name = arg->name, .expression = arg_res.exp});
  322. arg_types.push_back({.name = arg->name, .value = arg_res.type});
  323. }
  324. auto tuple_e = Expression::MakeTupleLiteral(e->line_num, new_args);
  325. auto tuple_t = Value::MakeTupleValue(std::move(arg_types));
  326. return TCResult(tuple_e, tuple_t, new_types);
  327. }
  328. case ExpressionKind::FieldAccessExpression: {
  329. auto res = TypeCheckExp(e->GetFieldAccessExpression().aggregate, types,
  330. values, nullptr, TCContext::ValueContext);
  331. auto t = res.type;
  332. switch (t->tag()) {
  333. case ValKind::StructType:
  334. // Search for a field
  335. for (auto& field : t->GetStructType().fields) {
  336. if (e->GetFieldAccessExpression().field == field.first) {
  337. const Expression* new_e = Expression::MakeFieldAccessExpression(
  338. e->line_num, res.exp, e->GetFieldAccessExpression().field);
  339. return TCResult(new_e, field.second, res.types);
  340. }
  341. }
  342. // Search for a method
  343. for (auto& method : t->GetStructType().methods) {
  344. if (e->GetFieldAccessExpression().field == method.first) {
  345. const Expression* new_e = Expression::MakeFieldAccessExpression(
  346. e->line_num, res.exp, e->GetFieldAccessExpression().field);
  347. return TCResult(new_e, method.second, res.types);
  348. }
  349. }
  350. FATAL_COMPILATION_ERROR(e->line_num)
  351. << "struct " << t->GetStructType().name
  352. << " does not have a field named "
  353. << e->GetFieldAccessExpression().field;
  354. case ValKind::TupleValue:
  355. for (const TupleElement& field : t->GetTupleValue().elements) {
  356. if (e->GetFieldAccessExpression().field == field.name) {
  357. auto new_e = Expression::MakeFieldAccessExpression(
  358. e->line_num, res.exp, e->GetFieldAccessExpression().field);
  359. return TCResult(new_e, field.value, res.types);
  360. }
  361. }
  362. FATAL_COMPILATION_ERROR(e->line_num)
  363. << "struct " << t->GetStructType().name
  364. << " does not have a field named "
  365. << e->GetFieldAccessExpression().field;
  366. case ValKind::ChoiceType:
  367. for (auto vt = t->GetChoiceType().alternatives.begin();
  368. vt != t->GetChoiceType().alternatives.end(); ++vt) {
  369. if (e->GetFieldAccessExpression().field == vt->first) {
  370. const Expression* new_e = Expression::MakeFieldAccessExpression(
  371. e->line_num, res.exp, e->GetFieldAccessExpression().field);
  372. auto fun_ty = Value::MakeFunctionType({}, vt->second, t);
  373. return TCResult(new_e, fun_ty, res.types);
  374. }
  375. }
  376. FATAL_COMPILATION_ERROR(e->line_num)
  377. << "struct " << t->GetStructType().name
  378. << " does not have a field named "
  379. << e->GetFieldAccessExpression().field;
  380. default:
  381. FATAL_COMPILATION_ERROR(e->line_num)
  382. << "field access, expected a struct\n"
  383. << *e;
  384. }
  385. }
  386. case ExpressionKind::IdentifierExpression: {
  387. std::optional<const Value*> type =
  388. types.Get(e->GetIdentifierExpression().name);
  389. if (type) {
  390. return TCResult(e, *type, types);
  391. } else {
  392. FATAL_COMPILATION_ERROR(e->line_num)
  393. << "could not find `" << e->GetIdentifierExpression().name << "`";
  394. }
  395. }
  396. case ExpressionKind::IntLiteral:
  397. return TCResult(e, Value::MakeIntType(), types);
  398. case ExpressionKind::BoolLiteral:
  399. return TCResult(e, Value::MakeBoolType(), types);
  400. case ExpressionKind::PrimitiveOperatorExpression: {
  401. std::vector<const Expression*> es;
  402. std::vector<const Value*> ts;
  403. auto new_types = types;
  404. for (const Expression* argument :
  405. e->GetPrimitiveOperatorExpression().arguments) {
  406. auto res = TypeCheckExp(argument, types, values, nullptr,
  407. TCContext::ValueContext);
  408. new_types = res.types;
  409. es.push_back(res.exp);
  410. ts.push_back(res.type);
  411. }
  412. auto new_e = Expression::MakePrimitiveOperatorExpression(
  413. e->line_num, e->GetPrimitiveOperatorExpression().op, es);
  414. switch (e->GetPrimitiveOperatorExpression().op) {
  415. case Operator::Neg:
  416. ExpectType(e->line_num, "negation", Value::MakeIntType(), ts[0]);
  417. return TCResult(new_e, Value::MakeIntType(), new_types);
  418. case Operator::Add:
  419. ExpectType(e->line_num, "addition(1)", Value::MakeIntType(), ts[0]);
  420. ExpectType(e->line_num, "addition(2)", Value::MakeIntType(), ts[1]);
  421. return TCResult(new_e, Value::MakeIntType(), new_types);
  422. case Operator::Sub:
  423. ExpectType(e->line_num, "subtraction(1)", Value::MakeIntType(),
  424. ts[0]);
  425. ExpectType(e->line_num, "subtraction(2)", Value::MakeIntType(),
  426. ts[1]);
  427. return TCResult(new_e, Value::MakeIntType(), new_types);
  428. case Operator::Mul:
  429. ExpectType(e->line_num, "multiplication(1)", Value::MakeIntType(),
  430. ts[0]);
  431. ExpectType(e->line_num, "multiplication(2)", Value::MakeIntType(),
  432. ts[1]);
  433. return TCResult(new_e, Value::MakeIntType(), new_types);
  434. case Operator::And:
  435. ExpectType(e->line_num, "&&(1)", Value::MakeBoolType(), ts[0]);
  436. ExpectType(e->line_num, "&&(2)", Value::MakeBoolType(), ts[1]);
  437. return TCResult(new_e, Value::MakeBoolType(), new_types);
  438. case Operator::Or:
  439. ExpectType(e->line_num, "||(1)", Value::MakeBoolType(), ts[0]);
  440. ExpectType(e->line_num, "||(2)", Value::MakeBoolType(), ts[1]);
  441. return TCResult(new_e, Value::MakeBoolType(), new_types);
  442. case Operator::Not:
  443. ExpectType(e->line_num, "!", Value::MakeBoolType(), ts[0]);
  444. return TCResult(new_e, Value::MakeBoolType(), new_types);
  445. case Operator::Eq:
  446. ExpectType(e->line_num, "==", ts[0], ts[1]);
  447. return TCResult(new_e, Value::MakeBoolType(), new_types);
  448. case Operator::Deref:
  449. ExpectPointerType(e->line_num, "*", ts[0]);
  450. return TCResult(new_e, ts[0]->GetPointerType().type, new_types);
  451. case Operator::Ptr:
  452. ExpectType(e->line_num, "*", Value::MakeTypeType(), ts[0]);
  453. return TCResult(new_e, Value::MakeTypeType(), new_types);
  454. }
  455. break;
  456. }
  457. case ExpressionKind::CallExpression: {
  458. auto fun_res = TypeCheckExp(e->GetCallExpression().function, types,
  459. values, nullptr, TCContext::ValueContext);
  460. switch (fun_res.type->tag()) {
  461. case ValKind::FunctionType: {
  462. auto fun_t = fun_res.type;
  463. auto arg_res =
  464. TypeCheckExp(e->GetCallExpression().argument, fun_res.types,
  465. values, fun_t->GetFunctionType().param, context);
  466. auto parameter_type = fun_t->GetFunctionType().param;
  467. auto return_type = fun_t->GetFunctionType().ret;
  468. if (fun_t->GetFunctionType().deduced.size() > 0) {
  469. auto deduced_args = ArgumentDeduction(e->line_num, TypeEnv(),
  470. parameter_type, arg_res.type);
  471. for (auto& deduced_param : fun_t->GetFunctionType().deduced) {
  472. // TODO: change the following to a CHECK once the real checking
  473. // has been added to the type checking of function signatures.
  474. if (!deduced_args.Get(deduced_param.name)) {
  475. std::cerr << e->line_num
  476. << ": error, could not deduce type argument for type "
  477. "parameter "
  478. << deduced_param.name << std::endl;
  479. exit(-1);
  480. }
  481. }
  482. parameter_type = Substitute(deduced_args, parameter_type);
  483. return_type = Substitute(deduced_args, return_type);
  484. } else {
  485. ExpectType(e->line_num, "call", parameter_type, arg_res.type);
  486. }
  487. auto new_e = Expression::MakeCallExpression(e->line_num, fun_res.exp,
  488. arg_res.exp);
  489. return TCResult(new_e, return_type, arg_res.types);
  490. }
  491. default: {
  492. FATAL_COMPILATION_ERROR(e->line_num)
  493. << "in call, expected a function\n"
  494. << *e;
  495. }
  496. }
  497. break;
  498. }
  499. case ExpressionKind::FunctionTypeLiteral: {
  500. switch (context) {
  501. case TCContext::ValueContext:
  502. case TCContext::TypeContext: {
  503. auto pt = InterpExp(values, e->GetFunctionTypeLiteral().parameter);
  504. auto rt = InterpExp(values, e->GetFunctionTypeLiteral().return_type);
  505. auto new_e = Expression::MakeFunctionTypeLiteral(
  506. e->line_num, ReifyType(pt, e->line_num),
  507. ReifyType(rt, e->line_num));
  508. return TCResult(new_e, Value::MakeTypeType(), types);
  509. }
  510. case TCContext::PatternContext: {
  511. auto param_res = TypeCheckExp(e->GetFunctionTypeLiteral().parameter,
  512. types, values, nullptr, context);
  513. auto ret_res =
  514. TypeCheckExp(e->GetFunctionTypeLiteral().return_type,
  515. param_res.types, values, nullptr, context);
  516. auto new_e = Expression::MakeFunctionTypeLiteral(
  517. e->line_num, ReifyType(param_res.type, e->line_num),
  518. ReifyType(ret_res.type, e->line_num));
  519. return TCResult(new_e, Value::MakeTypeType(), ret_res.types);
  520. }
  521. }
  522. }
  523. case ExpressionKind::IntTypeLiteral:
  524. return TCResult(e, Value::MakeTypeType(), types);
  525. case ExpressionKind::BoolTypeLiteral:
  526. return TCResult(e, Value::MakeTypeType(), types);
  527. case ExpressionKind::TypeTypeLiteral:
  528. return TCResult(e, Value::MakeTypeType(), types);
  529. case ExpressionKind::AutoTypeLiteral:
  530. return TCResult(e, Value::MakeTypeType(), types);
  531. case ExpressionKind::ContinuationTypeLiteral:
  532. return TCResult(e, Value::MakeTypeType(), types);
  533. }
  534. }
  535. auto TypecheckCase(const Value* expected, const Expression* pat,
  536. const Statement* body, TypeEnv types, Env values,
  537. const Value*& ret_type)
  538. -> std::pair<const Expression*, const Statement*> {
  539. auto pat_res =
  540. TypeCheckExp(pat, types, values, expected, TCContext::PatternContext);
  541. auto res = TypeCheckStmt(body, pat_res.types, values, ret_type);
  542. return std::make_pair(pat, res.stmt);
  543. }
  544. // The TypeCheckStmt function performs semantic analysis on a statement.
  545. // It returns a new version of the statement and a new type environment.
  546. //
  547. // The ret_type parameter is used for analyzing return statements.
  548. // It is the declared return type of the enclosing function definition.
  549. // If the return type is "auto", then the return type is inferred from
  550. // the first return statement.
  551. auto TypeCheckStmt(const Statement* s, TypeEnv types, Env values,
  552. const Value*& ret_type) -> TCStatement {
  553. if (!s) {
  554. return TCStatement(s, types);
  555. }
  556. switch (s->tag()) {
  557. case StatementKind::Match: {
  558. auto res = TypeCheckExp(s->GetMatch().exp, types, values, nullptr,
  559. TCContext::ValueContext);
  560. auto res_type = res.type;
  561. auto new_clauses =
  562. new std::list<std::pair<const Expression*, const Statement*>>();
  563. for (auto& clause : *s->GetMatch().clauses) {
  564. new_clauses->push_back(TypecheckCase(
  565. res_type, clause.first, clause.second, types, values, ret_type));
  566. }
  567. const Statement* new_s =
  568. Statement::MakeMatch(s->line_num, res.exp, new_clauses);
  569. return TCStatement(new_s, types);
  570. }
  571. case StatementKind::While: {
  572. auto cnd_res = TypeCheckExp(s->GetWhile().cond, types, values, nullptr,
  573. TCContext::ValueContext);
  574. ExpectType(s->line_num, "condition of `while`", Value::MakeBoolType(),
  575. cnd_res.type);
  576. auto body_res =
  577. TypeCheckStmt(s->GetWhile().body, types, values, ret_type);
  578. auto new_s =
  579. Statement::MakeWhile(s->line_num, cnd_res.exp, body_res.stmt);
  580. return TCStatement(new_s, types);
  581. }
  582. case StatementKind::Break:
  583. case StatementKind::Continue:
  584. return TCStatement(s, types);
  585. case StatementKind::Block: {
  586. auto stmt_res =
  587. TypeCheckStmt(s->GetBlock().stmt, types, values, ret_type);
  588. return TCStatement(Statement::MakeBlock(s->line_num, stmt_res.stmt),
  589. types);
  590. }
  591. case StatementKind::VariableDefinition: {
  592. auto res = TypeCheckExp(s->GetVariableDefinition().init, types, values,
  593. nullptr, TCContext::ValueContext);
  594. const Value* rhs_ty = res.type;
  595. auto lhs_res = TypeCheckExp(s->GetVariableDefinition().pat, types, values,
  596. rhs_ty, TCContext::PatternContext);
  597. const Statement* new_s = Statement::MakeVariableDefinition(
  598. s->line_num, s->GetVariableDefinition().pat, res.exp);
  599. return TCStatement(new_s, lhs_res.types);
  600. }
  601. case StatementKind::Sequence: {
  602. auto stmt_res =
  603. TypeCheckStmt(s->GetSequence().stmt, types, values, ret_type);
  604. auto types2 = stmt_res.types;
  605. auto next_res =
  606. TypeCheckStmt(s->GetSequence().next, types2, values, ret_type);
  607. auto types3 = next_res.types;
  608. return TCStatement(
  609. Statement::MakeSequence(s->line_num, stmt_res.stmt, next_res.stmt),
  610. types3);
  611. }
  612. case StatementKind::Assign: {
  613. auto rhs_res = TypeCheckExp(s->GetAssign().rhs, types, values, nullptr,
  614. TCContext::ValueContext);
  615. auto rhs_t = rhs_res.type;
  616. auto lhs_res = TypeCheckExp(s->GetAssign().lhs, types, values, rhs_t,
  617. TCContext::ValueContext);
  618. auto lhs_t = lhs_res.type;
  619. ExpectType(s->line_num, "assign", lhs_t, rhs_t);
  620. auto new_s = Statement::MakeAssign(s->line_num, lhs_res.exp, rhs_res.exp);
  621. return TCStatement(new_s, lhs_res.types);
  622. }
  623. case StatementKind::ExpressionStatement: {
  624. auto res = TypeCheckExp(s->GetExpressionStatement().exp, types, values,
  625. nullptr, TCContext::ValueContext);
  626. auto new_s = Statement::MakeExpressionStatement(s->line_num, res.exp);
  627. return TCStatement(new_s, types);
  628. }
  629. case StatementKind::If: {
  630. auto cnd_res = TypeCheckExp(s->GetIf().cond, types, values, nullptr,
  631. TCContext::ValueContext);
  632. ExpectType(s->line_num, "condition of `if`", Value::MakeBoolType(),
  633. cnd_res.type);
  634. auto thn_res =
  635. TypeCheckStmt(s->GetIf().then_stmt, types, values, ret_type);
  636. auto els_res =
  637. TypeCheckStmt(s->GetIf().else_stmt, types, values, ret_type);
  638. auto new_s = Statement::MakeIf(s->line_num, cnd_res.exp, thn_res.stmt,
  639. els_res.stmt);
  640. return TCStatement(new_s, types);
  641. }
  642. case StatementKind::Return: {
  643. auto res = TypeCheckExp(s->GetReturn().exp, types, values, nullptr,
  644. TCContext::ValueContext);
  645. if (ret_type->tag() == ValKind::AutoType) {
  646. // The following infers the return type from the first 'return'
  647. // statement. This will get more difficult with subtyping, when we
  648. // should infer the least-upper bound of all the 'return' statements.
  649. ret_type = res.type;
  650. } else {
  651. ExpectType(s->line_num, "return", ret_type, res.type);
  652. }
  653. return TCStatement(Statement::MakeReturn(s->line_num, res.exp), types);
  654. }
  655. case StatementKind::Continuation: {
  656. TCStatement body_result =
  657. TypeCheckStmt(s->GetContinuation().body, types, values, ret_type);
  658. const Statement* new_continuation = Statement::MakeContinuation(
  659. s->line_num, s->GetContinuation().continuation_variable,
  660. body_result.stmt);
  661. types.Set(s->GetContinuation().continuation_variable,
  662. Value::MakeContinuationType());
  663. return TCStatement(new_continuation, types);
  664. }
  665. case StatementKind::Run: {
  666. TCResult argument_result =
  667. TypeCheckExp(s->GetRun().argument, types, values, nullptr,
  668. TCContext::ValueContext);
  669. ExpectType(s->line_num, "argument of `run`",
  670. Value::MakeContinuationType(), argument_result.type);
  671. const Statement* new_run =
  672. Statement::MakeRun(s->line_num, argument_result.exp);
  673. return TCStatement(new_run, types);
  674. }
  675. case StatementKind::Await: {
  676. // nothing to do here
  677. return TCStatement(s, types);
  678. }
  679. } // switch
  680. }
  681. auto CheckOrEnsureReturn(const Statement* stmt, bool void_return, int line_num)
  682. -> const Statement* {
  683. if (!stmt) {
  684. if (void_return) {
  685. return Statement::MakeReturn(line_num,
  686. Expression::MakeTupleLiteral(line_num, {}));
  687. } else {
  688. FATAL_COMPILATION_ERROR(line_num)
  689. << "control-flow reaches end of non-void function without a return";
  690. }
  691. }
  692. switch (stmt->tag()) {
  693. case StatementKind::Match: {
  694. auto new_clauses =
  695. new std::list<std::pair<const Expression*, const Statement*>>();
  696. for (auto i = stmt->GetMatch().clauses->begin();
  697. i != stmt->GetMatch().clauses->end(); ++i) {
  698. auto s = CheckOrEnsureReturn(i->second, void_return, stmt->line_num);
  699. new_clauses->push_back(std::make_pair(i->first, s));
  700. }
  701. return Statement::MakeMatch(stmt->line_num, stmt->GetMatch().exp,
  702. new_clauses);
  703. }
  704. case StatementKind::Block:
  705. return Statement::MakeBlock(
  706. stmt->line_num, CheckOrEnsureReturn(stmt->GetBlock().stmt,
  707. void_return, stmt->line_num));
  708. case StatementKind::If:
  709. return Statement::MakeIf(
  710. stmt->line_num, stmt->GetIf().cond,
  711. CheckOrEnsureReturn(stmt->GetIf().then_stmt, void_return,
  712. stmt->line_num),
  713. CheckOrEnsureReturn(stmt->GetIf().else_stmt, void_return,
  714. stmt->line_num));
  715. case StatementKind::Return:
  716. return stmt;
  717. case StatementKind::Sequence:
  718. if (stmt->GetSequence().next) {
  719. return Statement::MakeSequence(
  720. stmt->line_num, stmt->GetSequence().stmt,
  721. CheckOrEnsureReturn(stmt->GetSequence().next, void_return,
  722. stmt->line_num));
  723. } else {
  724. return CheckOrEnsureReturn(stmt->GetSequence().stmt, void_return,
  725. stmt->line_num);
  726. }
  727. case StatementKind::Continuation:
  728. case StatementKind::Run:
  729. case StatementKind::Await:
  730. return stmt;
  731. case StatementKind::Assign:
  732. case StatementKind::ExpressionStatement:
  733. case StatementKind::While:
  734. case StatementKind::Break:
  735. case StatementKind::Continue:
  736. case StatementKind::VariableDefinition:
  737. if (void_return) {
  738. return Statement::MakeSequence(
  739. stmt->line_num, stmt,
  740. Statement::MakeReturn(stmt->line_num, Expression::MakeTupleLiteral(
  741. stmt->line_num, {})));
  742. } else {
  743. FATAL_COMPILATION_ERROR(stmt->line_num)
  744. << "control-flow reaches end of non-void function without a return";
  745. }
  746. }
  747. }
  748. // TODO: factor common parts of TypeCheckFunDef and TypeOfFunDef into
  749. // a function.
  750. // TODO: Add checking to function definitions to ensure that
  751. // all deduced type parameters will be deduced.
  752. auto TypeCheckFunDef(const FunctionDefinition* f, TypeEnv types, Env values)
  753. -> struct FunctionDefinition* {
  754. // Bring the deduced parameters into scope
  755. for (const auto& deduced : f->deduced_parameters) {
  756. // auto t = InterpExp(values, deduced.type);
  757. Address a =
  758. state->heap.AllocateValue(Value::MakeVariableType(deduced.name));
  759. values.Set(deduced.name, a);
  760. }
  761. // Type check the parameter pattern
  762. auto param_res = TypeCheckExp(f->param_pattern, types, values, nullptr,
  763. TCContext::PatternContext);
  764. // Evaluate the return type expression
  765. auto return_type = InterpExp(values, f->return_type);
  766. if (f->name == "main") {
  767. ExpectType(f->line_num, "return type of `main`", Value::MakeIntType(),
  768. return_type);
  769. // TODO: Check that main doesn't have any parameters.
  770. }
  771. auto res = TypeCheckStmt(f->body, param_res.types, values, return_type);
  772. bool void_return = TypeEqual(return_type, Value::MakeUnitTypeVal());
  773. auto body = CheckOrEnsureReturn(res.stmt, void_return, f->line_num);
  774. return new FunctionDefinition(f->line_num, f->name, f->deduced_parameters,
  775. f->param_pattern,
  776. ReifyType(return_type, f->line_num), body);
  777. }
  778. auto TypeOfFunDef(TypeEnv types, Env values, const FunctionDefinition* fun_def)
  779. -> const Value* {
  780. // Bring the deduced parameters into scope
  781. for (const auto& deduced : fun_def->deduced_parameters) {
  782. // auto t = InterpExp(values, deduced.type);
  783. Address a =
  784. state->heap.AllocateValue(Value::MakeVariableType(deduced.name));
  785. values.Set(deduced.name, a);
  786. }
  787. // Type check the parameter pattern
  788. auto param_res = TypeCheckExp(fun_def->param_pattern, types, values, nullptr,
  789. TCContext::PatternContext);
  790. // Evaluate the return type expression
  791. auto ret = InterpExp(values, fun_def->return_type);
  792. if (ret->tag() == ValKind::AutoType) {
  793. auto f = TypeCheckFunDef(fun_def, types, values);
  794. ret = InterpExp(values, f->return_type);
  795. }
  796. return Value::MakeFunctionType(fun_def->deduced_parameters, param_res.type,
  797. ret);
  798. }
  799. auto TypeOfStructDef(const StructDefinition* sd, TypeEnv /*types*/, Env ct_top)
  800. -> const Value* {
  801. VarValues fields;
  802. VarValues methods;
  803. for (const Member* m : sd->members) {
  804. switch (m->tag()) {
  805. case MemberKind::FieldMember:
  806. auto t = InterpExp(ct_top, m->GetFieldMember().type);
  807. fields.push_back(std::make_pair(m->GetFieldMember().name, t));
  808. break;
  809. }
  810. }
  811. return Value::MakeStructType(sd->name, std::move(fields), std::move(methods));
  812. }
  813. static auto GetName(const Declaration& d) -> const std::string& {
  814. switch (d.tag()) {
  815. case DeclarationKind::FunctionDeclaration:
  816. return d.GetFunctionDeclaration().definition.name;
  817. case DeclarationKind::StructDeclaration:
  818. return d.GetStructDeclaration().definition.name;
  819. case DeclarationKind::ChoiceDeclaration:
  820. return d.GetChoiceDeclaration().name;
  821. case DeclarationKind::VariableDeclaration:
  822. return d.GetVariableDeclaration().name;
  823. }
  824. }
  825. auto MakeTypeChecked(const Declaration& d, const TypeEnv& types,
  826. const Env& values) -> Declaration {
  827. switch (d.tag()) {
  828. case DeclarationKind::FunctionDeclaration:
  829. return Declaration::MakeFunctionDeclaration(*TypeCheckFunDef(
  830. &d.GetFunctionDeclaration().definition, types, values));
  831. case DeclarationKind::StructDeclaration: {
  832. const StructDefinition& struct_def = d.GetStructDeclaration().definition;
  833. std::list<Member*> fields;
  834. for (Member* m : struct_def.members) {
  835. switch (m->tag()) {
  836. case MemberKind::FieldMember:
  837. // TODO: Interpret the type expression and store the result.
  838. fields.push_back(m);
  839. break;
  840. }
  841. }
  842. return Declaration::MakeStructDeclaration(
  843. struct_def.line_num, struct_def.name, std::move(fields));
  844. }
  845. case DeclarationKind::ChoiceDeclaration:
  846. // TODO
  847. return d;
  848. case DeclarationKind::VariableDeclaration: {
  849. const auto& var = d.GetVariableDeclaration();
  850. // Signals a type error if the initializing expression does not have
  851. // the declared type of the variable, otherwise returns this
  852. // declaration with annotated types.
  853. TCResult type_checked_initializer = TypeCheckExp(
  854. var.initializer, types, values, nullptr, TCContext::ValueContext);
  855. const Value* declared_type = InterpExp(values, var.type);
  856. ExpectType(var.source_location, "initializer of variable", declared_type,
  857. type_checked_initializer.type);
  858. return d;
  859. }
  860. }
  861. }
  862. static void TopLevel(const Declaration& d, TypeCheckContext* tops) {
  863. switch (d.tag()) {
  864. case DeclarationKind::FunctionDeclaration: {
  865. const FunctionDefinition& func_def =
  866. d.GetFunctionDeclaration().definition;
  867. auto t = TypeOfFunDef(tops->types, tops->values, &func_def);
  868. tops->types.Set(func_def.name, t);
  869. InitEnv(d, &tops->values);
  870. break;
  871. }
  872. case DeclarationKind::StructDeclaration: {
  873. const StructDefinition& struct_def = d.GetStructDeclaration().definition;
  874. auto st = TypeOfStructDef(&struct_def, tops->types, tops->values);
  875. Address a = state->heap.AllocateValue(st);
  876. tops->values.Set(struct_def.name, a); // Is this obsolete?
  877. std::vector<TupleElement> field_types;
  878. for (const auto& [field_name, field_value] : st->GetStructType().fields) {
  879. field_types.push_back({.name = field_name, .value = field_value});
  880. }
  881. auto fun_ty = Value::MakeFunctionType(
  882. {}, Value::MakeTupleValue(std::move(field_types)), st);
  883. tops->types.Set(struct_def.name, fun_ty);
  884. break;
  885. }
  886. case DeclarationKind::ChoiceDeclaration: {
  887. const auto& choice = d.GetChoiceDeclaration();
  888. VarValues alts;
  889. for (const auto& [name, signature] : choice.alternatives) {
  890. auto t = InterpExp(tops->values, signature);
  891. alts.push_back(std::make_pair(name, t));
  892. }
  893. auto ct = Value::MakeChoiceType(choice.name, std::move(alts));
  894. Address a = state->heap.AllocateValue(ct);
  895. tops->values.Set(choice.name, a); // Is this obsolete?
  896. tops->types.Set(choice.name, ct);
  897. break;
  898. }
  899. case DeclarationKind::VariableDeclaration: {
  900. const auto& var = d.GetVariableDeclaration();
  901. // Associate the variable name with it's declared type in the
  902. // compile-time symbol table.
  903. const Value* declared_type = InterpExp(tops->values, var.type);
  904. tops->types.Set(var.name, declared_type);
  905. break;
  906. }
  907. }
  908. }
  909. auto TopLevel(std::list<Declaration>* fs) -> TypeCheckContext {
  910. TypeCheckContext tops;
  911. bool found_main = false;
  912. for (auto const& d : *fs) {
  913. if (GetName(d) == "main") {
  914. found_main = true;
  915. }
  916. TopLevel(d, &tops);
  917. }
  918. if (found_main == false) {
  919. FATAL_COMPILATION_ERROR_NO_LINE()
  920. << "program must contain a function named `main`";
  921. }
  922. return tops;
  923. }
  924. } // namespace Carbon