(expr: Expression, target: Type, source: Type)
| 229 | * Conversions between optionals. |
| 230 | */ |
| 231 | export function castOptional(expr: Expression, target: Type, source: Type): Expression { |
| 232 | // Use helper when there is template type. |
| 233 | if (source.category == 'template' || target.category == 'template') { |
| 234 | if (source.isOptional) { |
| 235 | return new CustomExpression(target, (ctx) => { |
| 236 | return `compilets::GetOptionalValue(${expr.print(ctx)})`; |
| 237 | }); |
| 238 | } |
| 239 | } |
| 240 | // Convert undefined to std::nullopt. |
| 241 | if (source.category == 'undefined' && target.isStdOptional()) { |
| 242 | if (target.isProperty) |
| 243 | return expr; |
| 244 | return new CustomExpression(target, (ctx) => 'std::nullopt'); |
| 245 | } |
| 246 | // Get the optional value first before converting to other types. |
| 247 | if (source.isStdOptional() && !target.isStdOptional()) { |
| 248 | return new CustomExpression(source.noOptional(), (ctx) => { |
| 249 | return `${printExpressionValue(expr, ctx)}.value()`; |
| 250 | }); |
| 251 | } |
| 252 | return expr; |
| 253 | } |
no test coverage detected