constant.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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 "toolchain/check/cpp/constant.h"
  5. #include "toolchain/check/cpp/import.h"
  6. #include "toolchain/check/eval.h"
  7. namespace Carbon::Check {
  8. // TODO: dedup with code in `MapConstant` and `TryEvaluateMacroToConstant`.
  9. auto MapAPValueToConstant(Context& context, SemIR::LocId loc_id,
  10. const clang::APValue& ap_value, clang::QualType type)
  11. -> SemIR::ConstantId {
  12. SemIR::TypeId type_id = ImportCppType(context, loc_id, type).type_id;
  13. if (!type_id.has_value()) {
  14. return SemIR::ConstantId::NotConstant;
  15. }
  16. if (ap_value.isInt()) {
  17. if (type->isBooleanType()) {
  18. auto value = SemIR::BoolValue::From(!ap_value.getInt().isZero());
  19. return TryEvalInst(
  20. context, SemIR::BoolLiteral{.type_id = type_id, .value = value});
  21. } else {
  22. CARBON_CHECK(type->isIntegralOrEnumerationType());
  23. IntId int_id = context.ints().Add(ap_value.getInt());
  24. return TryEvalInst(context,
  25. SemIR::IntValue{.type_id = type_id, .int_id = int_id});
  26. }
  27. } else if (ap_value.isFloat()) {
  28. FloatId float_id = context.floats().Add(ap_value.getFloat());
  29. return TryEvalInst(
  30. context, SemIR::FloatValue{.type_id = type_id, .float_id = float_id});
  31. } else {
  32. // TODO: support other types.
  33. return SemIR::ConstantId::NotConstant;
  34. }
  35. }
  36. } // namespace Carbon::Check