Files
carbon-lang/toolchain/check/cpp/macros.h
T
Ivana Ivanovska 3b0dad9dd5 Add support for simple object-like macros (#6326)
Adds support for object-like macros with a single replacement
numeric-literal kind token. Only macros that evaluate to an integer
constant are supported for now. When detected at name lookup, they are
imported as a constant integer value in Carbon.

Demo:

```c++
// --- macros.h

#define CONFIG_VALUE 2
```

``` c++
// main.carbon
library "Main";

import Cpp library "macros.h";
import Core library "io";

fn Run() {
    let a: i32 = Cpp.CONFIG_VALUE;
    Core.Print(a);
}
```

```c++
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link main.o \--output=demo_carbon
$ ./demo_carbon
2
```

Part of #6303
2025-11-11 11:24:20 +00:00

24 lines
953 B
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
#ifndef CARBON_TOOLCHAIN_CHECK_CPP_MACROS_H_
#define CARBON_TOOLCHAIN_CHECK_CPP_MACROS_H_
#include "toolchain/check/context.h"
namespace Carbon::Check {
// Tries to evaluate the given macro to a constant expression. Returns the
// evaluated expression on success or nullptr otherwise. Currently supports only
// simple object-like macros with a single replacement token that is a numeric
// literal token.
// TODO: Add support for multiple tokens and other literal types.
auto TryEvaluateMacroToConstant(Context& context, SemIR::LocId loc_id,
SemIR::NameId name_id,
clang::MacroInfo* macro_info) -> clang::Expr*;
} // namespace Carbon::Check
#endif // CARBON_TOOLCHAIN_CHECK_CPP_MACROS_H_