macros.cpp 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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/macros.h"
  5. #include "clang/AST/ASTContext.h"
  6. #include "clang/AST/Expr.h"
  7. #include "clang/Parse/Parser.h"
  8. #include "clang/Sema/Sema.h"
  9. #include "common/check.h"
  10. #include "toolchain/check/cpp/constant.h"
  11. #include "toolchain/check/cpp/import.h"
  12. #include "toolchain/check/literal.h"
  13. #include "toolchain/check/member_access.h"
  14. #include "toolchain/check/type_completion.h"
  15. namespace Carbon::Check {
  16. // Maps a Clang literal expression to a Carbon constant.
  17. static auto MapConstant(Context& context, SemIR::LocId loc_id,
  18. clang::Expr* expr) -> SemIR::InstId {
  19. CARBON_CHECK(expr, "empty expression");
  20. if (auto* string_literal = dyn_cast<clang::StringLiteral>(expr)) {
  21. if (!string_literal->isOrdinary() && !string_literal->isUTF8()) {
  22. context.TODO(loc_id,
  23. llvm::formatv("Unsupported: string literal type: {0}",
  24. expr->getType()));
  25. return SemIR::ErrorInst::InstId;
  26. }
  27. StringLiteralValueId string_id =
  28. context.string_literal_values().Add(string_literal->getString());
  29. auto inst_id =
  30. MakeStringLiteral(context, Parse::StringLiteralId::None, string_id);
  31. return inst_id;
  32. } else if (isa<clang::CXXNullPtrLiteralExpr>(expr)) {
  33. auto type_id = ImportCppType(context, loc_id, expr->getType()).type_id;
  34. return GetOrAddInst<SemIR::UninitializedValue>(context, SemIR::LocId::None,
  35. {.type_id = type_id});
  36. }
  37. context.TODO(loc_id,
  38. llvm::formatv("Unsupported: C++ constant expression type: '{0}'",
  39. expr->getType().getAsString()));
  40. return SemIR::ErrorInst::InstId;
  41. }
  42. auto TryEvaluateMacro(Context& context, SemIR::LocId loc_id,
  43. SemIR::NameId name_id, clang::MacroInfo* macro_info)
  44. -> SemIR::InstId {
  45. auto name_str_opt = context.names().GetAsStringIfIdentifier(name_id);
  46. CARBON_CHECK(macro_info, "macro info missing");
  47. if (macro_info->getNumTokens() == 0) {
  48. context.TODO(loc_id, "Unsupported: macro with 0 replacement tokens");
  49. return SemIR::ErrorInst::InstId;
  50. }
  51. clang::Sema& sema = context.clang_sema();
  52. clang::Preprocessor& preprocessor = sema.getPreprocessor();
  53. auto& parser = context.cpp_context()->parser();
  54. llvm::SmallVector<clang::Token> tokens(macro_info->tokens().begin(),
  55. macro_info->tokens().end());
  56. clang::Token current_token = parser.getCurToken();
  57. // Add eof token
  58. clang::Token eof;
  59. eof.startToken();
  60. eof.setKind(clang::tok::eof);
  61. eof.setLocation(current_token.getEndLoc());
  62. tokens.push_back(eof);
  63. tokens.push_back(current_token);
  64. preprocessor.EnterTokenStream(tokens, /*DisableMacroExpansion=*/false,
  65. /*IsReinject=*/false);
  66. parser.ConsumeAnyToken(true);
  67. clang::ExprResult result = parser.ParseConstantExpression();
  68. clang::Expr* result_expr = result.get();
  69. bool success =
  70. !result.isInvalid() && parser.getCurToken().is(clang::tok::eof);
  71. if (!success) {
  72. parser.SkipUntil(clang::tok::eof);
  73. CARBON_DIAGNOSTIC(
  74. InCppMacroEvaluation, Error,
  75. "failed to parse macro Cpp.{0} to a valid constant expression",
  76. std::string);
  77. context.emitter().Emit(loc_id, InCppMacroEvaluation, (*name_str_opt).str());
  78. return SemIR::ErrorInst::InstId;
  79. }
  80. result_expr = result_expr->IgnoreParenImpCasts();
  81. if (isa<clang::StringLiteral>(result_expr) ||
  82. isa<clang::CXXNullPtrLiteralExpr>(result_expr)) {
  83. return MapConstant(context, loc_id, result_expr);
  84. }
  85. clang::Expr::EvalResult evaluated_result;
  86. if (!result_expr->EvaluateAsConstantExpr(evaluated_result,
  87. sema.getASTContext())) {
  88. CARBON_FATAL("failed to evaluate macro as constant expression");
  89. }
  90. clang::APValue ap_value = evaluated_result.Val;
  91. // TODO: Add support for other types.
  92. if (result_expr->isGLValue()) {
  93. const auto* value_decl =
  94. ap_value.getLValueBase().get<const clang::ValueDecl*>();
  95. if (!ap_value.hasLValuePath()) {
  96. context.TODO(loc_id, "Macro expanded to lvalue with no path");
  97. return SemIR::ErrorInst::InstId;
  98. }
  99. if (ap_value.isLValueOnePastTheEnd()) {
  100. context.TODO(loc_id, "Macro expanded to a one-past-the-end lvalue");
  101. return SemIR::ErrorInst::InstId;
  102. }
  103. auto key = SemIR::ClangDeclKey::ForNonFunctionDecl(
  104. // TODO: can this const_cast be avoided?
  105. const_cast<clang::ValueDecl*>(value_decl));
  106. auto inst_id = ImportCppDecl(context, loc_id, key);
  107. if (ap_value.getLValuePath().size() == 0) {
  108. return inst_id;
  109. }
  110. // Import the base type so that its fields can be accessed.
  111. auto var_storage = context.insts().GetAs<SemIR::VarStorage>(inst_id);
  112. // TODO: currently an error isn't reachable here because incomplete
  113. // array types can't be imported. Once that changes, switch to
  114. // `RequireCompleteType` and handle the error.
  115. CompleteTypeOrCheckFail(context, var_storage.type_id);
  116. clang::QualType qual_type = ap_value.getLValueBase().getType();
  117. for (const auto& entry : ap_value.getLValuePath()) {
  118. if (qual_type->isArrayType()) {
  119. context.TODO(loc_id, "Macro expanded to array type");
  120. } else {
  121. const auto* decl =
  122. cast<clang::Decl>(entry.getAsBaseOrMember().getPointer());
  123. const auto* field_decl = dyn_cast<clang::FieldDecl>(decl);
  124. if (!field_decl) {
  125. context.TODO(loc_id, "Macro expanded to a base class subobject");
  126. return SemIR::ErrorInst::InstId;
  127. }
  128. auto field_inst_id =
  129. ImportCppDecl(context, loc_id,
  130. SemIR::ClangDeclKey::ForNonFunctionDecl(
  131. const_cast<clang::FieldDecl*>(field_decl)));
  132. if (field_inst_id == SemIR::ErrorInst::InstId) {
  133. context.TODO(loc_id,
  134. "Unsupported field in macro expansion: " +
  135. ap_value.getAsString(context.ast_context(),
  136. result_expr->getType()));
  137. return SemIR::ErrorInst::InstId;
  138. }
  139. const SemIR::FieldDecl& field_decl_inst =
  140. context.insts().GetAs<SemIR::FieldDecl>(field_inst_id);
  141. qual_type = field_decl->getType();
  142. inst_id = PerformMemberAccess(context, loc_id, inst_id,
  143. field_decl_inst.name_id);
  144. }
  145. }
  146. return inst_id;
  147. } else {
  148. auto const_id =
  149. MapAPValueToConstant(context, loc_id, ap_value, result_expr->getType());
  150. if (const_id == SemIR::ConstantId::NotConstant) {
  151. context.TODO(loc_id,
  152. "Unsupported: macro evaluated to a constant of type: " +
  153. result_expr->getType().getAsString());
  154. return SemIR::ErrorInst::InstId;
  155. }
  156. return context.constant_values().GetInstId(const_id);
  157. }
  158. }
  159. } // namespace Carbon::Check