Skip to content

C++ Interop: Import object-like macros #6303

@ivanaivanovska

Description

@ivanaivanovska

Design doc: Carbon: C++ interop for C/C++ object-like macros.

Summary:

An object-like macro that evaluates to a constant expression at compile time is imported as a constant in Carbon if the value can be represented in Carbon.

Supported

  • Primitive literals:

    • Integer literals (123, 0xFF, 42L) -> imported as Carbon integer const.
    • Floating-point literals (3.14, 1.0e-9) -> imported as Carbon floating-point const.
    • Boolean literals (true, false) -> imported as Carbon bool const.
    • Character literals ('a', '\n', '\0') -> imported as Carbon char const.
    • String literals ("hello") -> imported as Carbon str const.
    • Null pointer literals (nullptr) -> imported as Carbon Core.CppCompat.NullptrT.
  • Constant expressions:

    Any expression that evaluates to a constant of a supported type, including operators like unary, binary, casting etc., is supported. There are no restrictions on the number or type of operands.

    #define ADDITION 1+2+3
    
    #define MyIntLambda (([] { return 7; })())
    
    #define CONCAT_STR(A, B) #A #B
    #define Indirect CONCAT_STR(x, y)
  • Macros expanding to an identifier:

    • enum constant: enum Color { Red = 1 }; #define MY_RED ::Red
    • constexpr variables: constexpr int X = 10; #define M ::X

Not supported:

  • User-defined literals: 100_km

  • Macros expanding to a non-primitive literal:

    • struct or class type: #define ORIGIN MyPoint{0,0}
  • Macros expanding to non-constant expressions:

    • int x; #define VAL x
  • Macros not expanding to expressions:

    • Type names: #define MY_INT int
    • Statements or keywords: #define RET return, #define FOREVER for(;;)
    • Empty macros: #define EMPTY

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions