(
expr: Box<dyn Expr>,
target_type: Box<dyn DataType>,
location: SourceLocation,
)
| 70 | } |
| 71 | |
| 72 | fn cast_expression_or_error( |
| 73 | expr: Box<dyn Expr>, |
| 74 | target_type: Box<dyn DataType>, |
| 75 | location: SourceLocation, |
| 76 | ) -> Result<Box<dyn Expr>, Box<Diagnostic>> { |
| 77 | // Check if it's possiable to perform implicit cast directly |
| 78 | if target_type.has_implicit_cast_from(&expr) { |
| 79 | return Ok(Box::new(CastExpr { |
| 80 | value: expr, |
| 81 | result_type: target_type, |
| 82 | })); |
| 83 | } |
| 84 | |
| 85 | // Check if it's supported to cast this value to result type, just return CastExpr |
| 86 | let value_type: Box<dyn DataType> = expr.expr_type(); |
| 87 | if value_type.equals(&target_type) { |
| 88 | return Ok(expr); |
| 89 | } |
| 90 | |
| 91 | let value_expected_types = value_type.can_perform_explicit_cast_op_to(); |
| 92 | if value_expected_types.contains(&target_type) { |
| 93 | return Ok(Box::new(CastExpr { |
| 94 | value: expr, |
| 95 | result_type: target_type, |
| 96 | })); |
| 97 | } |
| 98 | |
| 99 | // Check if it's possible to implicit cast the value to one of the expected type of result type |
| 100 | // then Cast from expected type to the result type |
| 101 | // Examples: Cast("true" as Int) can be casted as Text -> Bool -> Int |
| 102 | let expected_types = target_type.can_perform_explicit_cast_op_to(); |
| 103 | for expected_type in expected_types { |
| 104 | if expected_type.has_implicit_cast_from(&expr) { |
| 105 | let casting = Box::new(CastExpr { |
| 106 | value: expr, |
| 107 | result_type: expected_type.clone(), |
| 108 | }); |
| 109 | |
| 110 | return Ok(Box::new(CastExpr { |
| 111 | value: casting, |
| 112 | result_type: target_type, |
| 113 | })); |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | Err(Diagnostic::error(&format!( |
| 118 | "Unsupported `CAST` operator from type `{}` to type `{}`", |
| 119 | value_type.literal(), |
| 120 | target_type.literal(), |
| 121 | )) |
| 122 | .with_location(location) |
| 123 | .as_boxed()) |
| 124 | } |
no test coverage detected
searching dependent graphs…