1 #include "analysis/type_check.h"
5 #include "ast/intrinsic.h"
6 #include "ast/context.h"
8 #include "source_file/token.h"
11 using namespace tanlang;
13 bool TypeCheck::CanImplicitlyConvert(
Type *from,
Type *to) {
14 TAN_ASSERT(from && to);
20 int s1 = from->get_size_bits();
21 int s2 = to->get_size_bits();
22 if (from->is_int() && to->is_int()) {
23 bool u1 = from->is_unsigned();
24 bool u2 = to->is_unsigned();
31 }
else if (from->is_float() && to->is_float()) {
36 else if (from->is_int() && to->is_float()) {
41 else if (from->is_bool() && to->is_num()) {
46 else if ((from->is_num() || from->is_pointer()) && to->is_bool()) {
56 Type *TypeCheck::ImplicitTypePromote(
Type *t1,
Type *t2) {
63 int s1 = t1->get_size_bits();
64 int s2 = t2->get_size_bits();
65 if (t1->is_int() && t2->is_int()) {
66 bool u1 = t1->is_unsigned();
67 bool u2 = t2->is_unsigned();
70 return s1 >= s2 ? t1 : t2;
87 }
else if (t1->is_float() && t2->is_float()) {
88 return s1 >= s2 ? t1 : t2;
92 else if (t1->is_float() && t2->is_int()) {
94 }
else if (t1->is_int() && t2->is_float()) {
99 else if (t1->is_bool() && (t2->is_num() || t2->is_pointer())) {
101 }
else if ((t1->is_num() || t1->is_pointer()) && t2->is_bool()) {
111 Cast *TypeCheck::create_implicit_conversion(
Expr *from,
Type *to) {
112 if (!CanImplicitlyConvert(from->get_type(), to)) {
113 error(ErrorType::TYPE_ERROR,
115 fmt::format(
"Cannot implicitly convert type {} to {}", from->get_type()->get_typename(), to->get_typename()));
118 auto *cast = Cast::Create(from->src());
125 auto *lhs = bop->get_lhs();
126 auto *rhs = bop->get_rhs();
127 auto *lhs_type = lhs->get_type();
128 auto *rhs_type = rhs->get_type();
130 auto *promoted_type = ImplicitTypePromote(lhs_type, rhs_type);
131 if (!promoted_type) {
132 error(ErrorType::TYPE_ERROR,
134 fmt::format(
"Cannot find a valid type promotion between {} and {}",
135 lhs_type->get_typename(),
136 rhs_type->get_typename()));
139 TAN_ASSERT(promoted_type == lhs_type || promoted_type == rhs_type);
140 if (promoted_type != lhs_type) {
141 auto *cast = Cast::Create(bop->src());
143 cast->set_type(promoted_type);
146 auto *cast = Cast::Create(bop->src());
148 cast->set_type(promoted_type);
152 return promoted_type;
Type is immutable once created. The exception is StructType. Its information is updated in multiple s...