Files
carbon-lang/toolchain/check/cpp/constant.cpp
T
Nicholas Bishop 069c6f4447 Refactor TryEvaluateMacroToConstant to simplify and dedup code (#6820)
For integral and float types, `TryEvaluateMacroToConstant` now calls
`MapAPValueToConstant` to directly convert from an APValue, rather than
converting the `APValue` to an expression and importing it with
`MapConstant`.

`MapConstant` is still used, but only for string literals and nullptrs.
Since it's only used by `TryEvaluateMacroToConstant`, moved it to
`macros.cpp` and removed the code for other types of expressions.
2026-03-02 21:00:07 +00:00

43 lines
1.4 KiB
C++

// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "toolchain/check/cpp/constant.h"
#include "toolchain/check/cpp/import.h"
#include "toolchain/check/eval.h"
namespace Carbon::Check {
auto MapAPValueToConstant(Context& context, SemIR::LocId loc_id,
const clang::APValue& ap_value, clang::QualType type)
-> SemIR::ConstantId {
SemIR::TypeId type_id = ImportCppType(context, loc_id, type).type_id;
if (!type_id.has_value()) {
return SemIR::ConstantId::NotConstant;
}
if (ap_value.isInt()) {
if (type->isBooleanType()) {
auto value = SemIR::BoolValue::From(!ap_value.getInt().isZero());
return TryEvalInst(
context, SemIR::BoolLiteral{.type_id = type_id, .value = value});
} else {
CARBON_CHECK(type->isIntegralOrEnumerationType());
IntId int_id = context.ints().Add(ap_value.getInt());
return TryEvalInst(context,
SemIR::IntValue{.type_id = type_id, .int_id = int_id});
}
} else if (ap_value.isFloat()) {
FloatId float_id = context.floats().Add(ap_value.getFloat());
return TryEvalInst(
context, SemIR::FloatValue{.type_id = type_id, .float_id = float_id});
} else {
// TODO: support other types.
return SemIR::ConstantId::NotConstant;
}
}
} // namespace Carbon::Check