Skip to content

Commit 109e39c

Browse files
Add support for nullptr literals in macros (carbon-language#6426)
Adding support for macros that evaluate to nullptr literal. Demo: ```c++ // macros.h void foo(int a[2]); #define MyNullPtr nullptr ``` ```c++ // macros.cpp void foo(int a[2]) { if (!a) { printf("array a is nullptr\n"); return; } printf("a[0] = %d \n", a[0]); } ``` ```c++ // main.carbon library "Main"; import Cpp library "macros.h"; fn Run() -> i32 { Cpp.foo(Cpp.MyNullPtr); return 0; } ``` ``` $ clang -c macros.cpp; $ bazel-bin/toolchain/carbon compile main.carbon $ bazel-bin/toolchain/carbon link macros.o main.o \--output=demo_carbon $ ./demo_carbon array a is nullptr ``` Part of carbon-language#6303
1 parent 62cb185 commit 109e39c

File tree

3 files changed

+21
-2
lines changed

3 files changed

+21
-2
lines changed

toolchain/check/cpp/import.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2264,6 +2264,10 @@ static auto MapConstant(Context& context, SemIR::LocId loc_id,
22642264
MakeStringLiteral(context, Parse::StringLiteralId::None, string_id);
22652265
context.imports().push_back(inst_id);
22662266
return inst_id;
2267+
} else if (isa<clang::CXXNullPtrLiteralExpr>(expr)) {
2268+
auto type_id = MapNullptrType(context, loc_id).type_id;
2269+
return GetOrAddInst<SemIR::UninitializedValue>(context, SemIR::LocId::None,
2270+
{.type_id = type_id});
22672271
}
22682272

22692273
SemIR::TypeId type_id = MapType(context, loc_id, expr->getType()).type_id;

toolchain/check/cpp/macros.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,8 @@ auto TryEvaluateMacroToConstant(Context& context, SemIR::LocId loc_id,
6262
}
6363

6464
if (isa<clang::StringLiteral>(result_expr) ||
65-
isa<clang::CharacterLiteral>(result_expr)) {
65+
isa<clang::CharacterLiteral>(result_expr) ||
66+
isa<clang::CXXNullPtrLiteralExpr>(result_expr)) {
6667
return result_expr;
6768
}
6869

toolchain/check/testdata/interop/cpp/macros.carbon

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
// Exceptions. See /LICENSE for license information.
33
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
44
//
5-
// INCLUDE-FILE: toolchain/testing/testdata/min_prelude/primitives.carbon
5+
// INCLUDE-FILE: toolchain/testing/testdata/min_prelude/full.carbon
66
//
77
// AUTOUPDATE
88
// TIP: To test this file alone, run:
@@ -595,6 +595,20 @@ fn F() {
595595
Cpp.M_TRUE = false;
596596
}
597597

598+
// --- nullptr.carbon
599+
600+
library "[[@TEST_NAME]]";
601+
602+
import Cpp inline '''
603+
#define MyNullPtr nullptr
604+
void foo(int arr[2]);
605+
''';
606+
607+
fn F() {
608+
Cpp.foo(Cpp.MyNullPtr);
609+
}
610+
611+
598612
// --- lambda.carbon
599613

600614
library "[[@TEST_NAME]]";

0 commit comments

Comments
 (0)