Files
carbon-lang/toolchain/check/handle_inline_decl.cpp
T
Richard Smith 8b59e85b16 Add support for inline Cpp declarations. (#6994)
For #6830, add support for inline C++ fragments as a declaration rather
than as a packaging directive. For now, this uses `inline Cpp
<string-literal>;` as syntax. The prior `import Cpp inline
<string-literal>;` is left alone for the time being. We can decide
separately whether to remove that.

`inline Cpp` requires that there was at least one `import Cpp`. It's not
clear to me if that's the right design long-term, but it seems
reasonable for now.

Assisted-by: Gemini via Google Antigravity
2026-03-31 22:27:43 +00:00

57 lines
2.1 KiB
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
#include "common/check.h"
#include "toolchain/check/context.h"
#include "toolchain/check/cpp/generate_ast.h"
#include "toolchain/check/diagnostic_helpers.h"
#include "toolchain/check/handle.h"
#include "toolchain/check/inst.h"
#include "toolchain/lex/token_kind.h"
#include "toolchain/parse/node_ids.h"
#include "toolchain/parse/typed_nodes.h"
#include "toolchain/sem_ir/typed_insts.h"
namespace Carbon::Check {
auto HandleParseNode(Context& /*context*/,
Parse::InlineIntroducerId /*node_id*/) -> bool {
return true;
}
auto HandleParseNode(Context& context, Parse::InlineCppDeclId node_id) -> bool {
auto body_id = context.node_stack()
.PopForSoloNodeId<Parse::NodeKind::InlineImportBody>();
// If there are no Cpp imports prior to this point, the `Cpp` expression after
// `import` will have already produced an error.
//
// TODO: It'd be nice to produce a clearer error saying to insert an `import
// Cpp` in a file that uses `inline Cpp` and doesn't otherwise import anything
// from package `Cpp`.
if (context.constant_values().Get(
context.node_stack().Pop<Parse::NodeKind::CppNameExpr>()) ==
SemIR::ErrorInst::ConstantId) {
return true;
}
CARBON_CHECK(context.cpp_context(), "Have `Cpp` name but no Cpp context");
auto string_token = context.parse_tree().node_token(body_id);
auto string_value_id = context.tokens().GetStringLiteralValue(string_token);
auto string_value = context.string_literal_values().Get(string_value_id);
if (context.scope_stack().PeekIndex() != ScopeIndex::Package) {
CARBON_DIAGNOSTIC(InlineDeclNotAtFileScope, Error,
"`inline Cpp` declaration not at file scope");
context.emitter().Emit(node_id, InlineDeclNotAtFileScope);
return true;
}
InjectAstFromInlineCode(context, SemIR::LocId(body_id), string_value);
AddInst<SemIR::InlineCppDecl>(context, node_id, {.text_id = string_value_id});
return true;
}
} // namespace Carbon::Check