diff --git a/common/BUILD b/common/BUILD index 81fcf9eb1895..f39b46fadfd6 100644 --- a/common/BUILD +++ b/common/BUILD @@ -45,6 +45,7 @@ cc_library( ], hdrs = ["check.h"], deps = [ + ":ostream", "@llvm-project//llvm:Support", ], ) diff --git a/common/check_internal.h b/common/check_internal.h index cfaedc00e93f..75304c927055 100644 --- a/common/check_internal.h +++ b/common/check_internal.h @@ -7,7 +7,7 @@ #include -#include "llvm/Support/raw_ostream.h" +#include "common/ostream.h" namespace Carbon::Internal { diff --git a/toolchain/driver/driver.cpp b/toolchain/driver/driver.cpp index a9f427eed0df..923cb7f6aa4a 100644 --- a/toolchain/driver/driver.cpp +++ b/toolchain/driver/driver.cpp @@ -438,9 +438,9 @@ auto Driver::Compile(const CompileOptions& options) -> bool { return !has_errors; } - const SemanticsIR builtin_ir = SemanticsIR::MakeBuiltinIR(); + const SemIR::File builtin_ir = SemIR::File::MakeBuiltinIR(); CARBON_VLOG() << "*** SemanticsIR::MakeFromParseTree ***\n"; - const SemanticsIR semantics_ir = SemanticsIR::MakeFromParseTree( + const SemIR::File semantics_ir = SemIR::File::MakeFromParseTree( builtin_ir, tokenized_source, parse_tree, *consumer, vlog_stream_); // We've finished all steps that can produce diagnostics. Emit the @@ -449,7 +449,7 @@ auto Driver::Compile(const CompileOptions& options) -> bool { consumer->Flush(); has_errors |= semantics_ir.has_errors(); - CARBON_VLOG() << "*** SemanticsIR::MakeFromParseTree done ***\n"; + CARBON_VLOG() << "*** SemIR::File::MakeFromParseTree done ***\n"; if (options.dump_raw_semantics_ir) { semantics_ir.Print(output_stream_, options.builtin_semantics_ir); if (options.dump_semantics_ir) { @@ -458,7 +458,7 @@ auto Driver::Compile(const CompileOptions& options) -> bool { } if (options.dump_semantics_ir) { consumer->Flush(); - FormatSemanticsIR(tokenized_source, parse_tree, semantics_ir, + SemIR::FormatFile(tokenized_source, parse_tree, semantics_ir, output_stream_); } CARBON_VLOG() << "semantics_ir: " << semantics_ir; diff --git a/toolchain/lowering/lower_to_llvm.cpp b/toolchain/lowering/lower_to_llvm.cpp index d447fac8ca0a..87b5c143818a 100644 --- a/toolchain/lowering/lower_to_llvm.cpp +++ b/toolchain/lowering/lower_to_llvm.cpp @@ -9,7 +9,7 @@ namespace Carbon { auto LowerToLLVM(llvm::LLVMContext& llvm_context, llvm::StringRef module_name, - const SemanticsIR& semantics_ir, + const SemIR::File& semantics_ir, llvm::raw_ostream* vlog_stream) -> std::unique_ptr { LoweringContext context(llvm_context, module_name, semantics_ir, vlog_stream); diff --git a/toolchain/lowering/lower_to_llvm.h b/toolchain/lowering/lower_to_llvm.h index df2cc1e7e232..e937be498511 100644 --- a/toolchain/lowering/lower_to_llvm.h +++ b/toolchain/lowering/lower_to_llvm.h @@ -11,9 +11,9 @@ namespace Carbon { -// Lowers Semantics IR to LLVM IR. +// Lowers SemIR to LLVM IR. auto LowerToLLVM(llvm::LLVMContext& llvm_context, llvm::StringRef module_name, - const SemanticsIR& semantics_ir, + const SemIR::File& semantics_ir, llvm::raw_ostream* vlog_stream) -> std::unique_ptr; diff --git a/toolchain/lowering/lowering_context.cpp b/toolchain/lowering/lowering_context.cpp index 265bb6d17f0c..4002e0009355 100644 --- a/toolchain/lowering/lowering_context.cpp +++ b/toolchain/lowering/lowering_context.cpp @@ -16,14 +16,14 @@ namespace Carbon { LoweringContext::LoweringContext(llvm::LLVMContext& llvm_context, llvm::StringRef module_name, - const SemanticsIR& semantics_ir, + const SemIR::File& semantics_ir, llvm::raw_ostream* vlog_stream) : llvm_context_(&llvm_context), llvm_module_(std::make_unique(module_name, llvm_context)), semantics_ir_(&semantics_ir), vlog_stream_(vlog_stream) { CARBON_CHECK(!semantics_ir.has_errors()) - << "Generating LLVM IR from invalid SemanticsIR is unsupported."; + << "Generating LLVM IR from invalid SemIR::File is unsupported."; } // TODO: Move this to lower_to_llvm.cpp. @@ -40,14 +40,14 @@ auto LoweringContext::Run() -> std::unique_ptr { // Lower function declarations. functions_.resize_for_overwrite(semantics_ir_->functions_size()); for (auto i : llvm::seq(semantics_ir_->functions_size())) { - functions_[i] = BuildFunctionDeclaration(SemanticsFunctionId(i)); + functions_[i] = BuildFunctionDeclaration(SemIR::FunctionId(i)); } // TODO: Lower global variable declarations. // Lower function definitions. for (auto i : llvm::seq(semantics_ir_->functions_size())) { - BuildFunctionDefinition(SemanticsFunctionId(i)); + BuildFunctionDefinition(SemIR::FunctionId(i)); } // TODO: Lower global variable initializers. @@ -55,7 +55,7 @@ auto LoweringContext::Run() -> std::unique_ptr { return std::move(llvm_module_); } -auto LoweringContext::BuildFunctionDeclaration(SemanticsFunctionId function_id) +auto LoweringContext::BuildFunctionDeclaration(SemIR::FunctionId function_id) -> llvm::Function* { auto function = semantics_ir().GetFunction(function_id); @@ -87,7 +87,7 @@ auto LoweringContext::BuildFunctionDeclaration(SemanticsFunctionId function_id) return llvm_function; } -auto LoweringContext::BuildFunctionDefinition(SemanticsFunctionId function_id) +auto LoweringContext::BuildFunctionDefinition(SemIR::FunctionId function_id) -> void { auto function = semantics_ir().GetFunction(function_id); const auto& body_block_ids = function.body_block_ids; @@ -118,7 +118,7 @@ auto LoweringContext::BuildFunctionDefinition(SemanticsFunctionId function_id) CARBON_VLOG() << "Lowering " << node_id << ": " << node << "\n"; switch (node.kind()) { #define CARBON_SEMANTICS_NODE_KIND(Name) \ - case SemanticsNodeKind::Name: \ + case SemIR::NodeKind::Name: \ LoweringHandle##Name(function_lowering, node_id, node); \ break; #include "toolchain/semantics/semantics_node_kind.def" @@ -127,15 +127,15 @@ auto LoweringContext::BuildFunctionDefinition(SemanticsFunctionId function_id) } } -auto LoweringContext::BuildType(SemanticsNodeId node_id) -> llvm::Type* { +auto LoweringContext::BuildType(SemIR::NodeId node_id) -> llvm::Type* { switch (node_id.index) { - case SemanticsBuiltinKind::FloatingPointType.AsInt(): + case SemIR::BuiltinKind::FloatingPointType.AsInt(): // TODO: Handle different sizes. return llvm::Type::getDoubleTy(*llvm_context_); - case SemanticsBuiltinKind::IntegerType.AsInt(): + case SemIR::BuiltinKind::IntegerType.AsInt(): // TODO: Handle different sizes. return llvm::Type::getInt32Ty(*llvm_context_); - case SemanticsBuiltinKind::BoolType.AsInt(): + case SemIR::BuiltinKind::BoolType.AsInt(): // TODO: We may want to have different representations for `bool` storage // (`i8`) versus for `bool` values (`i1`). return llvm::Type::getInt1Ty(*llvm_context_); @@ -143,16 +143,16 @@ auto LoweringContext::BuildType(SemanticsNodeId node_id) -> llvm::Type* { auto node = semantics_ir_->GetNode(node_id); switch (node.kind()) { - case SemanticsNodeKind::ArrayType: { + case SemIR::NodeKind::ArrayType: { auto [bound_node_id, type_id] = node.GetAsArrayType(); return llvm::ArrayType::get( GetType(type_id), semantics_ir_->GetArrayBoundValue(bound_node_id)); } - case SemanticsNodeKind::ConstType: + case SemIR::NodeKind::ConstType: return GetType(node.GetAsConstType()); - case SemanticsNodeKind::PointerType: + case SemIR::NodeKind::PointerType: return llvm::PointerType::get(*llvm_context_, /*AddressSpace=*/0); - case SemanticsNodeKind::StructType: { + case SemIR::NodeKind::StructType: { auto refs = semantics_ir_->GetNodeBlock(node.GetAsStructType()); llvm::SmallVector subtypes; subtypes.reserve(refs.size()); @@ -161,13 +161,13 @@ auto LoweringContext::BuildType(SemanticsNodeId node_id) -> llvm::Type* { semantics_ir_->GetNode(ref_id).GetAsStructTypeField(); // TODO: Handle recursive types. The restriction for builtins prevents // recursion while still letting them cache. - CARBON_CHECK(field_type_id.index < SemanticsBuiltinKind::ValidCount) + CARBON_CHECK(field_type_id.index < SemIR::BuiltinKind::ValidCount) << field_type_id; subtypes.push_back(GetType(field_type_id)); } return llvm::StructType::get(*llvm_context_, subtypes); } - case SemanticsNodeKind::TupleType: { + case SemIR::NodeKind::TupleType: { // TODO: Investigate special-casing handling of empty tuples so that they // can be collectively replaced with LLVM's void, particularly around // function returns. LLVM doesn't allow declaring variables with a void diff --git a/toolchain/lowering/lowering_context.h b/toolchain/lowering/lowering_context.h index f4d9dfe98a53..85a4d5934333 100644 --- a/toolchain/lowering/lowering_context.h +++ b/toolchain/lowering/lowering_context.h @@ -18,23 +18,23 @@ class LoweringContext { public: explicit LoweringContext(llvm::LLVMContext& llvm_context, llvm::StringRef module_name, - const SemanticsIR& semantics_ir, + const SemIR::File& semantics_ir, llvm::raw_ostream* vlog_stream); - // Lowers the SemanticsIR to LLVM IR. Should only be called once, and handles + // Lowers the SemIR::File to LLVM IR. Should only be called once, and handles // the main execution loop. auto Run() -> std::unique_ptr; // Gets a callable's function. - auto GetFunction(SemanticsFunctionId function_id) -> llvm::Function* { + auto GetFunction(SemIR::FunctionId function_id) -> llvm::Function* { CARBON_CHECK(functions_[function_id.index] != nullptr) << function_id; return functions_[function_id.index]; } // Returns a lowered type for the given type_id. - auto GetType(SemanticsTypeId type_id) -> llvm::Type* { + auto GetType(SemIR::TypeId type_id) -> llvm::Type* { // InvalidType should not be passed in. - if (type_id == SemanticsTypeId::TypeType) { + if (type_id == SemIR::TypeId::TypeType) { return GetTypeType(); } CARBON_CHECK(type_id.index >= 0) << type_id; @@ -48,21 +48,21 @@ class LoweringContext { auto llvm_context() -> llvm::LLVMContext& { return *llvm_context_; } auto llvm_module() -> llvm::Module& { return *llvm_module_; } - auto semantics_ir() -> const SemanticsIR& { return *semantics_ir_; } + auto semantics_ir() -> const SemIR::File& { return *semantics_ir_; } private: // Builds the declaration for the given function, which should then be cached // by the caller. - auto BuildFunctionDeclaration(SemanticsFunctionId function_id) + auto BuildFunctionDeclaration(SemIR::FunctionId function_id) -> llvm::Function*; // Builds the definition for the given function. If the function is only a // declaration with no definition, does nothing. - auto BuildFunctionDefinition(SemanticsFunctionId function_id) -> void; + auto BuildFunctionDefinition(SemIR::FunctionId function_id) -> void; // Builds the type for the given node, which should then be cached by the // caller. - auto BuildType(SemanticsNodeId node_id) -> llvm::Type*; + auto BuildType(SemIR::NodeId node_id) -> llvm::Type*; // Returns the empty LLVM struct type used to represent the type `type`. auto GetTypeType() -> llvm::StructType* { @@ -77,13 +77,13 @@ class LoweringContext { llvm::LLVMContext* llvm_context_; std::unique_ptr llvm_module_; - // The input Semantics IR. - const SemanticsIR* const semantics_ir_; + // The input SemIR. + const SemIR::File* const semantics_ir_; // The optional vlog stream. llvm::raw_ostream* vlog_stream_; - // Maps callables to lowered functions. Semantics treats callables as the + // Maps callables to lowered functions. SemIR treats callables as the // canonical form of a function, so lowering needs to do the same. llvm::SmallVector functions_; diff --git a/toolchain/lowering/lowering_function_context.cpp b/toolchain/lowering/lowering_function_context.cpp index b79fc2a24a61..5401b48b0023 100644 --- a/toolchain/lowering/lowering_function_context.cpp +++ b/toolchain/lowering/lowering_function_context.cpp @@ -14,7 +14,7 @@ LoweringFunctionContext::LoweringFunctionContext( function_(function), builder_(lowering_context.llvm_context()) {} -auto LoweringFunctionContext::GetBlock(SemanticsNodeBlockId block_id) +auto LoweringFunctionContext::GetBlock(SemIR::NodeBlockId block_id) -> llvm::BasicBlock* { llvm::BasicBlock*& entry = blocks_[block_id]; if (!entry) { @@ -23,7 +23,7 @@ auto LoweringFunctionContext::GetBlock(SemanticsNodeBlockId block_id) return entry; } -auto LoweringFunctionContext::TryToReuseBlock(SemanticsNodeBlockId block_id, +auto LoweringFunctionContext::TryToReuseBlock(SemIR::NodeBlockId block_id, llvm::BasicBlock* block) -> bool { if (!blocks_.insert({block_id, block}).second) { return false; @@ -34,8 +34,8 @@ auto LoweringFunctionContext::TryToReuseBlock(SemanticsNodeBlockId block_id, return true; } -auto LoweringFunctionContext::GetBlockArg(SemanticsNodeBlockId block_id, - SemanticsTypeId type_id) +auto LoweringFunctionContext::GetBlockArg(SemIR::NodeBlockId block_id, + SemIR::TypeId type_id) -> llvm::PHINode* { llvm::BasicBlock* block = GetBlock(block_id); @@ -60,7 +60,7 @@ auto LoweringFunctionContext::CreateSyntheticBlock() -> llvm::BasicBlock* { return synthetic_block_; } -auto LoweringFunctionContext::GetLocalLoaded(SemanticsNodeId node_id) +auto LoweringFunctionContext::GetLocalLoaded(SemIR::NodeId node_id) -> llvm::Value* { auto* value = GetLocal(node_id); if (llvm::isa(value)) { diff --git a/toolchain/lowering/lowering_function_context.h b/toolchain/lowering/lowering_function_context.h index 05457a894400..d487bcc89660 100644 --- a/toolchain/lowering/lowering_function_context.h +++ b/toolchain/lowering/lowering_function_context.h @@ -25,23 +25,23 @@ class LoweringFunctionContext { // Returns a basic block corresponding to the start of the given semantics // block, and enqueues it for emission. - auto GetBlock(SemanticsNodeBlockId block_id) -> llvm::BasicBlock*; + auto GetBlock(SemIR::NodeBlockId block_id) -> llvm::BasicBlock*; // If we have not yet allocated a `BasicBlock` for this `block_id`, set it to // `block`, and enqueue `block_id` for emission. Returns whether we set the // block. - auto TryToReuseBlock(SemanticsNodeBlockId block_id, llvm::BasicBlock* block) + auto TryToReuseBlock(SemIR::NodeBlockId block_id, llvm::BasicBlock* block) -> bool; // Returns a phi node corresponding to the block argument of the given basic // block. - auto GetBlockArg(SemanticsNodeBlockId block_id, SemanticsTypeId type_id) + auto GetBlockArg(SemIR::NodeBlockId block_id, SemIR::TypeId type_id) -> llvm::PHINode*; // Returns a local (versus global) value for the given node. - auto GetLocal(SemanticsNodeId node_id) -> llvm::Value* { + auto GetLocal(SemIR::NodeId node_id) -> llvm::Value* { // All builtins are types, with the same empty lowered value. - if (node_id.index < SemanticsBuiltinKind::ValidCount) { + if (node_id.index < SemIR::BuiltinKind::ValidCount) { return GetTypeAsValue(); } @@ -52,10 +52,10 @@ class LoweringFunctionContext { // Returns a local (versus global) value for the given node in loaded state. // Loads will only be inserted on an as-needed basis. - auto GetLocalLoaded(SemanticsNodeId node_id) -> llvm::Value*; + auto GetLocalLoaded(SemIR::NodeId node_id) -> llvm::Value*; // Sets the value for the given node. - auto SetLocal(SemanticsNodeId node_id, llvm::Value* value) { + auto SetLocal(SemIR::NodeId node_id, llvm::Value* value) { bool added = locals_.insert({node_id, value}).second; CARBON_CHECK(added) << "Duplicate local insert: " << node_id; } @@ -71,12 +71,12 @@ class LoweringFunctionContext { } // Gets a callable's function. - auto GetFunction(SemanticsFunctionId function_id) -> llvm::Function* { + auto GetFunction(SemIR::FunctionId function_id) -> llvm::Function* { return lowering_context_->GetFunction(function_id); } // Returns a lowered type for the given type_id. - auto GetType(SemanticsTypeId type_id) -> llvm::Type* { + auto GetType(SemIR::TypeId type_id) -> llvm::Type* { return lowering_context_->GetType(type_id); } @@ -85,10 +85,10 @@ class LoweringFunctionContext { return lowering_context_->GetTypeAsValue(); } - // Create a synthetic block that corresponds to no SemanticsNodeBlockId. Such + // Create a synthetic block that corresponds to no SemIR::NodeBlockId. Such // a block should only ever have a single predecessor, and is used when we // need multiple `llvm::BasicBlock`s to model the linear control flow in a - // single SemanticsIR block. + // single SemIR::File block. auto CreateSyntheticBlock() -> llvm::BasicBlock*; // Determine whether block is the most recently created synthetic block. @@ -103,7 +103,7 @@ class LoweringFunctionContext { return lowering_context_->llvm_module(); } auto builder() -> llvm::IRBuilder<>& { return builder_; } - auto semantics_ir() -> const SemanticsIR& { + auto semantics_ir() -> const SemIR::File& { return lowering_context_->semantics_ir(); } @@ -116,23 +116,23 @@ class LoweringFunctionContext { llvm::IRBuilder<> builder_; - // Maps a function's SemanticsIR blocks to lowered blocks. - llvm::DenseMap blocks_; + // Maps a function's SemIR::File blocks to lowered blocks. + llvm::DenseMap blocks_; // The synthetic block we most recently created. May be null if there is no // such block. llvm::BasicBlock* synthetic_block_ = nullptr; - // Maps a function's SemanticsIR nodes to lowered values. + // Maps a function's SemIR::File nodes to lowered values. // TODO: Handle nested scopes. Right now this is just cleared at the end of // every block. - llvm::DenseMap locals_; + llvm::DenseMap locals_; }; -// Declare handlers for each SemanticsIR node. -#define CARBON_SEMANTICS_NODE_KIND(Name) \ - auto LoweringHandle##Name(LoweringFunctionContext& context, \ - SemanticsNodeId node_id, SemanticsNode node) \ +// Declare handlers for each SemIR::File node. +#define CARBON_SEMANTICS_NODE_KIND(Name) \ + auto LoweringHandle##Name(LoweringFunctionContext& context, \ + SemIR::NodeId node_id, SemIR::Node node) \ ->void; #include "toolchain/semantics/semantics_node_kind.def" diff --git a/toolchain/lowering/lowering_handle.cpp b/toolchain/lowering/lowering_handle.cpp index c30ecd383cb8..3bc1f797c85a 100644 --- a/toolchain/lowering/lowering_handle.cpp +++ b/toolchain/lowering/lowering_handle.cpp @@ -10,26 +10,24 @@ namespace Carbon { auto LoweringHandleInvalid(LoweringFunctionContext& /*context*/, - SemanticsNodeId /*node_id*/, SemanticsNode /*node*/) + SemIR::NodeId /*node_id*/, SemIR::Node /*node*/) -> void { llvm_unreachable("never in actual IR"); } auto LoweringHandleCrossReference(LoweringFunctionContext& /*context*/, - SemanticsNodeId /*node_id*/, - SemanticsNode node) -> void { + SemIR::NodeId /*node_id*/, SemIR::Node node) + -> void { CARBON_FATAL() << "TODO: Add support: " << node; } auto LoweringHandleAddressOf(LoweringFunctionContext& context, - SemanticsNodeId node_id, SemanticsNode node) - -> void { + SemIR::NodeId node_id, SemIR::Node node) -> void { context.SetLocal(node_id, context.GetLocal(node.GetAsAddressOf())); } auto LoweringHandleArrayIndex(LoweringFunctionContext& context, - SemanticsNodeId node_id, SemanticsNode node) - -> void { + SemIR::NodeId node_id, SemIR::Node node) -> void { auto [array_node_id, index_node_id] = node.GetAsArrayIndex(); auto* array_value = context.GetLocal(array_node_id); auto* llvm_type = @@ -37,7 +35,7 @@ auto LoweringHandleArrayIndex(LoweringFunctionContext& context, auto index_node = context.semantics_ir().GetNode(index_node_id); llvm::Value* array_element_value; - if (index_node.kind() == SemanticsNodeKind::IntegerLiteral) { + if (index_node.kind() == SemIR::NodeKind::IntegerLiteral) { const auto index = context.semantics_ir() .GetIntegerLiteral(index_node.GetAsIntegerLiteral()) .getZExtValue(); @@ -54,8 +52,7 @@ auto LoweringHandleArrayIndex(LoweringFunctionContext& context, } auto LoweringHandleArrayValue(LoweringFunctionContext& context, - SemanticsNodeId node_id, SemanticsNode node) - -> void { + SemIR::NodeId node_id, SemIR::Node node) -> void { auto* llvm_type = context.GetType(node.type_id()); auto* alloca = context.builder().CreateAlloca(llvm_type, /*ArraySize=*/nullptr, "array"); @@ -80,34 +77,32 @@ auto LoweringHandleArrayValue(LoweringFunctionContext& context, } auto LoweringHandleAssign(LoweringFunctionContext& context, - SemanticsNodeId /*node_id*/, SemanticsNode node) - -> void { + SemIR::NodeId /*node_id*/, SemIR::Node node) -> void { auto [storage_id, value_id] = node.GetAsAssign(); context.builder().CreateStore(context.GetLocalLoaded(value_id), context.GetLocal(storage_id)); } auto LoweringHandleBinaryOperatorAdd(LoweringFunctionContext& /*context*/, - SemanticsNodeId /*node_id*/, - SemanticsNode node) -> void { + SemIR::NodeId /*node_id*/, + SemIR::Node node) -> void { CARBON_FATAL() << "TODO: Add support: " << node; } auto LoweringHandleBindName(LoweringFunctionContext& /*context*/, - SemanticsNodeId /*node_id*/, SemanticsNode /*node*/) + SemIR::NodeId /*node_id*/, SemIR::Node /*node*/) -> void { // Probably need to do something here, but not necessary for now. } auto LoweringHandleBlockArg(LoweringFunctionContext& context, - SemanticsNodeId node_id, SemanticsNode node) - -> void { - SemanticsNodeBlockId block_id = node.GetAsBlockArg(); + SemIR::NodeId node_id, SemIR::Node node) -> void { + SemIR::NodeBlockId block_id = node.GetAsBlockArg(); context.SetLocal(node_id, context.GetBlockArg(block_id, node.type_id())); } auto LoweringHandleBoolLiteral(LoweringFunctionContext& context, - SemanticsNodeId node_id, SemanticsNode node) + SemIR::NodeId node_id, SemIR::Node node) -> void { llvm::Value* v = llvm::ConstantInt::get(context.builder().getInt1Ty(), node.GetAsBoolLiteral().index); @@ -115,9 +110,8 @@ auto LoweringHandleBoolLiteral(LoweringFunctionContext& context, } auto LoweringHandleBranch(LoweringFunctionContext& context, - SemanticsNodeId /*node_id*/, SemanticsNode node) - -> void { - SemanticsNodeBlockId target_block_id = node.GetAsBranch(); + SemIR::NodeId /*node_id*/, SemIR::Node node) -> void { + SemIR::NodeBlockId target_block_id = node.GetAsBranch(); // Opportunistically avoid creating a BasicBlock that contains just a branch. llvm::BasicBlock* block = context.builder().GetInsertBlock(); @@ -131,7 +125,7 @@ auto LoweringHandleBranch(LoweringFunctionContext& context, } auto LoweringHandleBranchIf(LoweringFunctionContext& context, - SemanticsNodeId /*node_id*/, SemanticsNode node) + SemIR::NodeId /*node_id*/, SemIR::Node node) -> void { auto [target_block_id, cond_id] = node.GetAsBranchIf(); llvm::Value* cond = context.GetLocalLoaded(cond_id); @@ -142,12 +136,11 @@ auto LoweringHandleBranchIf(LoweringFunctionContext& context, } auto LoweringHandleBranchWithArg(LoweringFunctionContext& context, - SemanticsNodeId /*node_id*/, - SemanticsNode node) -> void { + SemIR::NodeId /*node_id*/, SemIR::Node node) + -> void { auto [target_block_id, arg_id] = node.GetAsBranchWithArg(); llvm::Value* arg = context.GetLocalLoaded(arg_id); - SemanticsTypeId arg_type_id = - context.semantics_ir().GetNode(arg_id).type_id(); + SemIR::TypeId arg_type_id = context.semantics_ir().GetNode(arg_id).type_id(); // Opportunistically avoid creating a BasicBlock that contains just a branch. // We only do this for a block that we know will only have a single @@ -171,13 +164,13 @@ auto LoweringHandleBranchWithArg(LoweringFunctionContext& context, } auto LoweringHandleBuiltin(LoweringFunctionContext& /*context*/, - SemanticsNodeId /*node_id*/, SemanticsNode node) + SemIR::NodeId /*node_id*/, SemIR::Node node) -> void { CARBON_FATAL() << "TODO: Add support: " << node; } -auto LoweringHandleCall(LoweringFunctionContext& context, - SemanticsNodeId node_id, SemanticsNode node) -> void { +auto LoweringHandleCall(LoweringFunctionContext& context, SemIR::NodeId node_id, + SemIR::Node node) -> void { auto [refs_id, function_id] = node.GetAsCall(); auto* function = context.GetFunction(function_id); std::vector args; @@ -198,14 +191,14 @@ auto LoweringHandleCall(LoweringFunctionContext& context, } auto LoweringHandleDereference(LoweringFunctionContext& context, - SemanticsNodeId node_id, SemanticsNode node) + SemIR::NodeId node_id, SemIR::Node node) -> void { context.SetLocal(node_id, context.GetLocal(node.GetAsDereference())); } auto LoweringHandleFunctionDeclaration(LoweringFunctionContext& /*context*/, - SemanticsNodeId /*node_id*/, - SemanticsNode node) -> void { + SemIR::NodeId /*node_id*/, + SemIR::Node node) -> void { CARBON_FATAL() << "Should not be encountered. If that changes, we may want to change " "higher-level logic to skip them rather than calling this. " @@ -213,7 +206,7 @@ auto LoweringHandleFunctionDeclaration(LoweringFunctionContext& /*context*/, } auto LoweringHandleIntegerLiteral(LoweringFunctionContext& context, - SemanticsNodeId node_id, SemanticsNode node) + SemIR::NodeId node_id, SemIR::Node node) -> void { llvm::APInt i = context.semantics_ir().GetIntegerLiteral(node.GetAsIntegerLiteral()); @@ -224,21 +217,21 @@ auto LoweringHandleIntegerLiteral(LoweringFunctionContext& context, } auto LoweringHandleNamespace(LoweringFunctionContext& /*context*/, - SemanticsNodeId /*node_id*/, - SemanticsNode /*node*/) -> void { + SemIR::NodeId /*node_id*/, SemIR::Node /*node*/) + -> void { // No action to take. } auto LoweringHandleParameter(LoweringFunctionContext& /*context*/, - SemanticsNodeId /*node_id*/, - SemanticsNode /*node*/) -> void { + SemIR::NodeId /*node_id*/, SemIR::Node /*node*/) + -> void { CARBON_FATAL() << "Parameters should be lowered by `BuildFunctionDefinition`"; } auto LoweringHandleRealLiteral(LoweringFunctionContext& context, - SemanticsNodeId node_id, SemanticsNode node) + SemIR::NodeId node_id, SemIR::Node node) -> void { - SemanticsRealLiteral real = + SemIR::RealLiteral real = context.semantics_ir().GetRealLiteral(node.GetAsRealLiteral()); // TODO: This will probably have overflow issues, and should be fixed. double val = @@ -250,26 +243,26 @@ auto LoweringHandleRealLiteral(LoweringFunctionContext& context, } auto LoweringHandleReturn(LoweringFunctionContext& context, - SemanticsNodeId /*node_id*/, SemanticsNode /*node*/) + SemIR::NodeId /*node_id*/, SemIR::Node /*node*/) -> void { context.builder().CreateRetVoid(); } auto LoweringHandleReturnExpression(LoweringFunctionContext& context, - SemanticsNodeId /*node_id*/, - SemanticsNode node) -> void { - SemanticsNodeId expr_id = node.GetAsReturnExpression(); + SemIR::NodeId /*node_id*/, SemIR::Node node) + -> void { + SemIR::NodeId expr_id = node.GetAsReturnExpression(); context.builder().CreateRet(context.GetLocalLoaded(expr_id)); } auto LoweringHandleStringLiteral(LoweringFunctionContext& /*context*/, - SemanticsNodeId /*node_id*/, - SemanticsNode node) -> void { + SemIR::NodeId /*node_id*/, SemIR::Node node) + -> void { CARBON_FATAL() << "TODO: Add support: " << node; } auto LoweringHandleStructAccess(LoweringFunctionContext& context, - SemanticsNodeId node_id, SemanticsNode node) + SemIR::NodeId node_id, SemIR::Node node) -> void { auto [struct_id, member_index] = node.GetAsStructAccess(); auto struct_type_id = context.semantics_ir().GetNode(struct_id).type_id(); @@ -292,8 +285,7 @@ auto LoweringHandleStructAccess(LoweringFunctionContext& context, } auto LoweringHandleTupleIndex(LoweringFunctionContext& context, - SemanticsNodeId node_id, SemanticsNode node) - -> void { + SemIR::NodeId node_id, SemIR::Node node) -> void { auto [tuple_node_id, index_node_id] = node.GetAsTupleIndex(); auto* tuple_value = context.GetLocal(tuple_node_id); auto index_node = context.semantics_ir().GetNode(index_node_id); @@ -307,8 +299,7 @@ auto LoweringHandleTupleIndex(LoweringFunctionContext& context, } auto LoweringHandleTupleValue(LoweringFunctionContext& context, - SemanticsNodeId node_id, SemanticsNode node) - -> void { + SemIR::NodeId node_id, SemIR::Node node) -> void { auto* llvm_type = context.GetType(node.type_id()); auto* alloca = context.builder().CreateAlloca(llvm_type, /*ArraySize=*/nullptr, "tuple"); @@ -321,13 +312,13 @@ auto LoweringHandleTupleValue(LoweringFunctionContext& context, } auto LoweringHandleStructTypeField(LoweringFunctionContext& /*context*/, - SemanticsNodeId /*node_id*/, - SemanticsNode /*node*/) -> void { + SemIR::NodeId /*node_id*/, + SemIR::Node /*node*/) -> void { // No action to take. } auto LoweringHandleStructValue(LoweringFunctionContext& context, - SemanticsNodeId node_id, SemanticsNode node) + SemIR::NodeId node_id, SemIR::Node node) -> void { auto* llvm_type = context.GetType(node.type_id()); auto* alloca = context.builder().CreateAlloca( @@ -351,21 +342,20 @@ auto LoweringHandleStructValue(LoweringFunctionContext& context, } auto LoweringHandleStubReference(LoweringFunctionContext& context, - SemanticsNodeId node_id, SemanticsNode node) + SemIR::NodeId node_id, SemIR::Node node) -> void { context.SetLocal(node_id, context.GetLocal(node.GetAsStubReference())); } auto LoweringHandleUnaryOperatorNot(LoweringFunctionContext& context, - SemanticsNodeId node_id, SemanticsNode node) + SemIR::NodeId node_id, SemIR::Node node) -> void { context.SetLocal(node_id, context.builder().CreateNot(context.GetLocal( node.GetAsUnaryOperatorNot()))); } auto LoweringHandleVarStorage(LoweringFunctionContext& context, - SemanticsNodeId node_id, SemanticsNode node) - -> void { + SemIR::NodeId node_id, SemIR::Node node) -> void { // TODO: Eventually this name will be optional, and we'll want to provide // something like `var` as a default. However, that's not possible right now // so cannot be tested. diff --git a/toolchain/lowering/lowering_handle_type.cpp b/toolchain/lowering/lowering_handle_type.cpp index cb812065f38a..ae4b120c5e3f 100644 --- a/toolchain/lowering/lowering_handle_type.cpp +++ b/toolchain/lowering/lowering_handle_type.cpp @@ -7,31 +7,31 @@ namespace Carbon { auto LoweringHandleArrayType(LoweringFunctionContext& context, - SemanticsNodeId node_id, SemanticsNode /*node*/) + SemIR::NodeId node_id, SemIR::Node /*node*/) -> void { context.SetLocal(node_id, context.GetTypeAsValue()); } auto LoweringHandleConstType(LoweringFunctionContext& context, - SemanticsNodeId node_id, SemanticsNode /*node*/) + SemIR::NodeId node_id, SemIR::Node /*node*/) -> void { context.SetLocal(node_id, context.GetTypeAsValue()); } auto LoweringHandlePointerType(LoweringFunctionContext& context, - SemanticsNodeId node_id, SemanticsNode /*node*/) + SemIR::NodeId node_id, SemIR::Node /*node*/) -> void { context.SetLocal(node_id, context.GetTypeAsValue()); } auto LoweringHandleStructType(LoweringFunctionContext& context, - SemanticsNodeId node_id, SemanticsNode /*node*/) + SemIR::NodeId node_id, SemIR::Node /*node*/) -> void { context.SetLocal(node_id, context.GetTypeAsValue()); } auto LoweringHandleTupleType(LoweringFunctionContext& context, - SemanticsNodeId node_id, SemanticsNode /*node*/) + SemIR::NodeId node_id, SemIR::Node /*node*/) -> void { context.SetLocal(node_id, context.GetTypeAsValue()); } diff --git a/toolchain/semantics/semantics_builtin_kind.h b/toolchain/semantics/semantics_builtin_kind.h index d84fbfdb2dfe..1a9ef965974b 100644 --- a/toolchain/semantics/semantics_builtin_kind.h +++ b/toolchain/semantics/semantics_builtin_kind.h @@ -52,6 +52,11 @@ static_assert( static_assert(sizeof(SemanticsBuiltinKind) == 1, "Kind objects include padding!"); +// TODO: Refactor EnumBase to remove the need for this alias. +namespace SemIR { +using BuiltinKind = SemanticsBuiltinKind; +} // namespace SemIR + } // namespace Carbon #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_BUILTIN_KIND_H_ diff --git a/toolchain/semantics/semantics_context.cpp b/toolchain/semantics/semantics_context.cpp index 58553524e8c0..94293aff3b59 100644 --- a/toolchain/semantics/semantics_context.cpp +++ b/toolchain/semantics/semantics_context.cpp @@ -18,13 +18,12 @@ #include "toolchain/semantics/semantics_node_block_stack.h" #include "toolchain/semantics/semantics_node_kind.h" -namespace Carbon { +namespace Carbon::Check { -SemanticsContext::SemanticsContext(const TokenizedBuffer& tokens, - DiagnosticEmitter& emitter, - const ParseTree& parse_tree, - SemanticsIR& semantics_ir, - llvm::raw_ostream* vlog_stream) +Context::Context(const TokenizedBuffer& tokens, + DiagnosticEmitter& emitter, + const ParseTree& parse_tree, SemIR::File& semantics_ir, + llvm::raw_ostream* vlog_stream) : tokens_(&tokens), emitter_(&emitter), parse_tree_(&parse_tree), @@ -37,21 +36,19 @@ SemanticsContext::SemanticsContext(const TokenizedBuffer& tokens, declaration_name_stack_(this) { // Inserts the "Error" and "Type" types as "used types" so that // canonicalization can skip them. We don't emit either for lowering. + canonical_types_.insert({SemIR::NodeId::BuiltinError, SemIR::TypeId::Error}); canonical_types_.insert( - {SemanticsNodeId::BuiltinError, SemanticsTypeId::Error}); - canonical_types_.insert( - {SemanticsNodeId::BuiltinTypeType, SemanticsTypeId::TypeType}); + {SemIR::NodeId::BuiltinTypeType, SemIR::TypeId::TypeType}); } -auto SemanticsContext::TODO(ParseTree::Node parse_node, std::string label) - -> bool { +auto Context::TODO(ParseTree::Node parse_node, std::string label) -> bool { CARBON_DIAGNOSTIC(SemanticsTodo, Error, "Semantics TODO: `{0}`.", std::string); emitter_->Emit(parse_node, SemanticsTodo, std::move(label)); return false; } -auto SemanticsContext::VerifyOnFinish() -> void { +auto Context::VerifyOnFinish() -> void { // Information in all the various context objects should be cleaned up as // various pieces of context go out of scope. At this point, nothing should // remain. @@ -62,25 +59,24 @@ auto SemanticsContext::VerifyOnFinish() -> void { CARBON_CHECK(params_or_args_stack_.empty()) << params_or_args_stack_.size(); } -auto SemanticsContext::AddNode(SemanticsNode node) -> SemanticsNodeId { +auto Context::AddNode(SemIR::Node node) -> SemIR::NodeId { return AddNodeToBlock(node_block_stack_.PeekForAdd(), node); } -auto SemanticsContext::AddNodeToBlock(SemanticsNodeBlockId block, - SemanticsNode node) -> SemanticsNodeId { +auto Context::AddNodeToBlock(SemIR::NodeBlockId block, SemIR::Node node) + -> SemIR::NodeId { CARBON_VLOG() << "AddNode " << block << ": " << node << "\n"; return semantics_ir_->AddNode(block, node); } -auto SemanticsContext::AddNodeAndPush(ParseTree::Node parse_node, - SemanticsNode node) -> void { +auto Context::AddNodeAndPush(ParseTree::Node parse_node, SemIR::Node node) + -> void { auto node_id = AddNode(node); node_stack_.Push(parse_node, node_id); } -auto SemanticsContext::DiagnoseDuplicateName(ParseTree::Node parse_node, - SemanticsNodeId prev_def_id) - -> void { +auto Context::DiagnoseDuplicateName(ParseTree::Node parse_node, + SemIR::NodeId prev_def_id) -> void { CARBON_DIAGNOSTIC(NameDeclarationDuplicate, Error, "Duplicate name being declared in the same scope."); CARBON_DIAGNOSTIC(NameDeclarationPrevious, Note, @@ -91,16 +87,16 @@ auto SemanticsContext::DiagnoseDuplicateName(ParseTree::Node parse_node, .Emit(); } -auto SemanticsContext::DiagnoseNameNotFound(ParseTree::Node parse_node, - SemanticsStringId name_id) -> void { +auto Context::DiagnoseNameNotFound(ParseTree::Node parse_node, + SemIR::StringId name_id) -> void { CARBON_DIAGNOSTIC(NameNotFound, Error, "Name `{0}` not found.", llvm::StringRef); emitter_->Emit(parse_node, NameNotFound, semantics_ir_->GetString(name_id)); } -auto SemanticsContext::AddNameToLookup(ParseTree::Node name_node, - SemanticsStringId name_id, - SemanticsNodeId target_id) -> void { +auto Context::AddNameToLookup(ParseTree::Node name_node, + SemIR::StringId name_id, SemIR::NodeId target_id) + -> void { if (current_scope().names.insert(name_id).second) { name_lookup_[name_id].push_back(target_id); } else { @@ -108,17 +104,16 @@ auto SemanticsContext::AddNameToLookup(ParseTree::Node name_node, } } -auto SemanticsContext::LookupName(ParseTree::Node parse_node, - SemanticsStringId name_id, - SemanticsNameScopeId scope_id, - bool print_diagnostics) -> SemanticsNodeId { - if (scope_id == SemanticsNameScopeId::Invalid) { +auto Context::LookupName(ParseTree::Node parse_node, SemIR::StringId name_id, + SemIR::NameScopeId scope_id, bool print_diagnostics) + -> SemIR::NodeId { + if (scope_id == SemIR::NameScopeId::Invalid) { auto it = name_lookup_.find(name_id); if (it == name_lookup_.end()) { if (print_diagnostics) { DiagnoseNameNotFound(parse_node, name_id); } - return SemanticsNodeId::BuiltinError; + return SemIR::NodeId::BuiltinError; } CARBON_CHECK(!it->second.empty()) << "Should have been erased: " << semantics_ir_->GetString(name_id); @@ -132,16 +127,16 @@ auto SemanticsContext::LookupName(ParseTree::Node parse_node, if (print_diagnostics) { DiagnoseNameNotFound(parse_node, name_id); } - return SemanticsNodeId::BuiltinError; + return SemIR::NodeId::BuiltinError; } return it->second; } } -auto SemanticsContext::PushScope() -> void { scope_stack_.push_back({}); } +auto Context::PushScope() -> void { scope_stack_.push_back({}); } -auto SemanticsContext::PopScope() -> void { +auto Context::PopScope() -> void { auto scope = scope_stack_.pop_back_val(); for (const auto& str_id : scope.names) { auto it = name_lookup_.find(str_id); @@ -155,83 +150,81 @@ auto SemanticsContext::PopScope() -> void { } template -static auto AddDominatedBlockAndBranchImpl(SemanticsContext& context, +static auto AddDominatedBlockAndBranchImpl(Context& context, ParseTree::Node parse_node, - Args... args) - -> SemanticsNodeBlockId { + Args... args) -> SemIR::NodeBlockId { if (!context.node_block_stack().is_current_block_reachable()) { - return SemanticsNodeBlockId::Unreachable; + return SemIR::NodeBlockId::Unreachable; } auto block_id = context.semantics_ir().AddNodeBlock(); context.AddNode(BranchNode::Make(parse_node, block_id, args...)); return block_id; } -auto SemanticsContext::AddDominatedBlockAndBranch(ParseTree::Node parse_node) - -> SemanticsNodeBlockId { - return AddDominatedBlockAndBranchImpl(*this, - parse_node); +auto Context::AddDominatedBlockAndBranch(ParseTree::Node parse_node) + -> SemIR::NodeBlockId { + return AddDominatedBlockAndBranchImpl(*this, parse_node); } -auto SemanticsContext::AddDominatedBlockAndBranchWithArg( - ParseTree::Node parse_node, SemanticsNodeId arg_id) - -> SemanticsNodeBlockId { - return AddDominatedBlockAndBranchImpl( +auto Context::AddDominatedBlockAndBranchWithArg(ParseTree::Node parse_node, + SemIR::NodeId arg_id) + -> SemIR::NodeBlockId { + return AddDominatedBlockAndBranchImpl( *this, parse_node, arg_id); } -auto SemanticsContext::AddDominatedBlockAndBranchIf(ParseTree::Node parse_node, - SemanticsNodeId cond_id) - -> SemanticsNodeBlockId { - return AddDominatedBlockAndBranchImpl( +auto Context::AddDominatedBlockAndBranchIf(ParseTree::Node parse_node, + SemIR::NodeId cond_id) + -> SemIR::NodeBlockId { + return AddDominatedBlockAndBranchImpl( *this, parse_node, cond_id); } -auto SemanticsContext::AddConvergenceBlockAndPush( +auto Context::AddConvergenceBlockAndPush( ParseTree::Node parse_node, - std::initializer_list blocks) -> void { + std::initializer_list blocks) -> void { CARBON_CHECK(blocks.size() >= 2) << "no convergence"; - SemanticsNodeBlockId new_block_id = SemanticsNodeBlockId::Unreachable; - for (SemanticsNodeBlockId block_id : blocks) { - if (block_id != SemanticsNodeBlockId::Unreachable) { - if (new_block_id == SemanticsNodeBlockId::Unreachable) { + SemIR::NodeBlockId new_block_id = SemIR::NodeBlockId::Unreachable; + for (SemIR::NodeBlockId block_id : blocks) { + if (block_id != SemIR::NodeBlockId::Unreachable) { + if (new_block_id == SemIR::NodeBlockId::Unreachable) { new_block_id = semantics_ir().AddNodeBlock(); } AddNodeToBlock(block_id, - SemanticsNode::Branch::Make(parse_node, new_block_id)); + SemIR::Node::Branch::Make(parse_node, new_block_id)); } } node_block_stack().Push(new_block_id); } -auto SemanticsContext::AddConvergenceBlockWithArgAndPush( +auto Context::AddConvergenceBlockWithArgAndPush( ParseTree::Node parse_node, - std::initializer_list> - blocks_and_args) -> SemanticsNodeId { + std::initializer_list> + blocks_and_args) -> SemIR::NodeId { CARBON_CHECK(blocks_and_args.size() >= 2) << "no convergence"; - SemanticsNodeBlockId new_block_id = SemanticsNodeBlockId::Unreachable; + SemIR::NodeBlockId new_block_id = SemIR::NodeBlockId::Unreachable; for (auto [block_id, arg_id] : blocks_and_args) { - if (block_id != SemanticsNodeBlockId::Unreachable) { - if (new_block_id == SemanticsNodeBlockId::Unreachable) { + if (block_id != SemIR::NodeBlockId::Unreachable) { + if (new_block_id == SemIR::NodeBlockId::Unreachable) { new_block_id = semantics_ir().AddNodeBlock(); } - AddNodeToBlock(block_id, SemanticsNode::BranchWithArg::Make( + AddNodeToBlock(block_id, SemIR::Node::BranchWithArg::Make( parse_node, new_block_id, arg_id)); } } node_block_stack().Push(new_block_id); // Acquire the result value. - SemanticsTypeId result_type_id = + SemIR::TypeId result_type_id = semantics_ir().GetNode(blocks_and_args.begin()->second).type_id(); return AddNode( - SemanticsNode::BlockArg::Make(parse_node, result_type_id, new_block_id)); + SemIR::Node::BlockArg::Make(parse_node, result_type_id, new_block_id)); } // Add the current code block to the enclosing function. -auto SemanticsContext::AddCurrentCodeBlockToFunction() -> void { +auto Context::AddCurrentCodeBlockToFunction() -> void { CARBON_CHECK(!node_block_stack().empty()) << "no current code block"; CARBON_CHECK(!return_scope_stack().empty()) << "no current function"; @@ -248,12 +241,12 @@ auto SemanticsContext::AddCurrentCodeBlockToFunction() -> void { .body_block_ids.push_back(node_block_stack().PeekForAdd()); } -auto SemanticsContext::is_current_position_reachable() -> bool { +auto Context::is_current_position_reachable() -> bool { switch (auto block_id = node_block_stack().Peek(); block_id.index) { - case SemanticsNodeBlockId::Unreachable.index: { + case SemIR::NodeBlockId::Unreachable.index: { return false; } - case SemanticsNodeBlockId::Invalid.index: { + case SemIR::NodeBlockId::Invalid.index: { return true; } default: { @@ -265,19 +258,19 @@ auto SemanticsContext::is_current_position_reachable() -> bool { } const auto& last_node = semantics_ir().GetNode(block_contents.back()); return last_node.kind().terminator_kind() != - SemanticsTerminatorKind::Terminator; + SemIR::TerminatorKind::Terminator; } } } -auto SemanticsContext::ImplicitAsForArgs( - SemanticsNodeBlockId arg_refs_id, ParseTree::Node param_parse_node, - SemanticsNodeBlockId param_refs_id, +auto Context::ImplicitAsForArgs( + SemIR::NodeBlockId arg_refs_id, ParseTree::Node param_parse_node, + SemIR::NodeBlockId param_refs_id, DiagnosticEmitter::DiagnosticBuilder* diagnostic) -> bool { // If both arguments and parameters are empty, return quickly. Otherwise, // we'll fetch both so that errors are consistent. - if (arg_refs_id == SemanticsNodeBlockId::Empty && - param_refs_id == SemanticsNodeBlockId::Empty) { + if (arg_refs_id == SemIR::NodeBlockId::Empty && + param_refs_id == SemIR::NodeBlockId::Empty) { return true; } @@ -320,11 +313,10 @@ auto SemanticsContext::ImplicitAsForArgs( return true; } -auto SemanticsContext::ImplicitAsRequired(ParseTree::Node parse_node, - SemanticsNodeId value_id, - SemanticsTypeId as_type_id) - -> SemanticsNodeId { - SemanticsNodeId output_value_id = value_id; +auto Context::ImplicitAsRequired(ParseTree::Node parse_node, + SemIR::NodeId value_id, + SemIR::TypeId as_type_id) -> SemIR::NodeId { + SemIR::NodeId output_value_id = value_id; if (ImplicitAsImpl(value_id, as_type_id, &output_value_id) == ImplicitAsKind::Incompatible) { // Only error when the system is trying to use the result. @@ -341,37 +333,34 @@ auto SemanticsContext::ImplicitAsRequired(ParseTree::Node parse_node, return output_value_id; } -auto SemanticsContext::ImplicitAsBool(ParseTree::Node parse_node, - SemanticsNodeId value_id) - -> SemanticsNodeId { +auto Context::ImplicitAsBool(ParseTree::Node parse_node, SemIR::NodeId value_id) + -> SemIR::NodeId { return ImplicitAsRequired(parse_node, value_id, - CanonicalizeType(SemanticsNodeId::BuiltinBoolType)); + CanonicalizeType(SemIR::NodeId::BuiltinBoolType)); } -auto SemanticsContext::ImplicitAsImpl(SemanticsNodeId value_id, - SemanticsTypeId as_type_id, - SemanticsNodeId* output_value_id) - -> ImplicitAsKind { +auto Context::ImplicitAsImpl(SemIR::NodeId value_id, SemIR::TypeId as_type_id, + SemIR::NodeId* output_value_id) -> ImplicitAsKind { // Start by making sure both sides are valid. If any part is invalid, the // result is invalid and we shouldn't error. - if (value_id == SemanticsNodeId::BuiltinError) { + if (value_id == SemIR::NodeId::BuiltinError) { // If the value is invalid, we can't do much, but do "succeed". return ImplicitAsKind::Identical; } auto value = semantics_ir_->GetNode(value_id); auto value_type_id = value.type_id(); - if (value_type_id == SemanticsTypeId::Error) { + if (value_type_id == SemIR::TypeId::Error) { // Although the source type is invalid, this still changes the value. if (output_value_id != nullptr) { - *output_value_id = SemanticsNodeId::BuiltinError; + *output_value_id = SemIR::NodeId::BuiltinError; } return ImplicitAsKind::Compatible; } - if (as_type_id == SemanticsTypeId::Error) { + if (as_type_id == SemIR::TypeId::Error) { // Although the target type is invalid, this still changes the value. if (output_value_id != nullptr) { - *output_value_id = SemanticsNodeId::BuiltinError; + *output_value_id = SemIR::NodeId::BuiltinError; } return ImplicitAsKind::Compatible; } @@ -383,13 +372,13 @@ auto SemanticsContext::ImplicitAsImpl(SemanticsNodeId value_id, auto as_type = semantics_ir_->GetTypeAllowBuiltinTypes(as_type_id); auto as_type_node = semantics_ir_->GetNode(as_type); - if (as_type_node.kind() == SemanticsNodeKind::ArrayType) { + if (as_type_node.kind() == SemIR::NodeKind::ArrayType) { auto [bound_node_id, element_type_id] = as_type_node.GetAsArrayType(); // To resolve lambda issue. auto element_type = element_type_id; auto value_type_node = semantics_ir_->GetNode( semantics_ir_->GetTypeAllowBuiltinTypes(value_type_id)); - if (value_type_node.kind() == SemanticsNodeKind::TupleType) { + if (value_type_node.kind() == SemIR::NodeKind::TupleType) { auto tuple_type_block_id = value_type_node.GetAsTupleType(); const auto& type_block = semantics_ir_->GetTypeBlock(tuple_type_block_id); if (type_block.size() == @@ -397,7 +386,7 @@ auto SemanticsContext::ImplicitAsImpl(SemanticsNodeId value_id, std::all_of(type_block.begin(), type_block.end(), [&](auto type) { return type == element_type; })) { if (output_value_id != nullptr) { - *output_value_id = AddNode(SemanticsNode::ArrayValue::Make( + *output_value_id = AddNode(SemIR::Node::ArrayValue::Make( value.parse_node(), as_type_id, value_id)); } return ImplicitAsKind::Compatible; @@ -405,12 +394,12 @@ auto SemanticsContext::ImplicitAsImpl(SemanticsNodeId value_id, } } - if (as_type_id == SemanticsTypeId::TypeType) { - if (value.kind() == SemanticsNodeKind::TupleValue) { + if (as_type_id == SemIR::TypeId::TypeType) { + if (value.kind() == SemIR::NodeKind::TupleValue) { auto tuple_block_id = value.GetAsTupleValue(); - llvm::SmallVector type_ids; + llvm::SmallVector type_ids; // If it is empty tuple type, we don't fetch anything. - if (tuple_block_id != SemanticsNodeBlockId::Empty) { + if (tuple_block_id != SemIR::NodeBlockId::Empty) { const auto& tuple_block = semantics_ir_->GetNodeBlock(tuple_block_id); for (auto tuple_node_id : tuple_block) { // TODO: Eventually ExpressionAsType will insert implicit cast @@ -429,8 +418,8 @@ auto SemanticsContext::ImplicitAsImpl(SemanticsNodeId value_id, return ImplicitAsKind::Compatible; } // When converting `{}` to a type, the result is `{} as Type`. - if (value.kind() == SemanticsNodeKind::StructValue && - value.GetAsStructValue() == SemanticsNodeBlockId::Empty) { + if (value.kind() == SemIR::NodeKind::StructValue && + value.GetAsStructValue() == SemIR::NodeBlockId::Empty) { if (output_value_id != nullptr) { *output_value_id = semantics_ir_->GetType(value_type_id); } @@ -441,34 +430,32 @@ auto SemanticsContext::ImplicitAsImpl(SemanticsNodeId value_id, // TODO: Handle ImplicitAs for compatible structs and tuples. if (output_value_id != nullptr) { - *output_value_id = SemanticsNodeId::BuiltinError; + *output_value_id = SemIR::NodeId::BuiltinError; } return ImplicitAsKind::Incompatible; } -auto SemanticsContext::ParamOrArgStart() -> void { - params_or_args_stack_.Push(); -} +auto Context::ParamOrArgStart() -> void { params_or_args_stack_.Push(); } -auto SemanticsContext::ParamOrArgComma(bool for_args) -> void { +auto Context::ParamOrArgComma(bool for_args) -> void { ParamOrArgSave(for_args); } -auto SemanticsContext::ParamOrArgEnd(bool for_args, ParseNodeKind start_kind) - -> SemanticsNodeBlockId { +auto Context::ParamOrArgEnd(bool for_args, ParseNodeKind start_kind) + -> SemIR::NodeBlockId { if (parse_tree_->node_kind(node_stack_.PeekParseNode()) != start_kind) { ParamOrArgSave(for_args); } return params_or_args_stack_.Pop(); } -auto SemanticsContext::ParamOrArgSave(bool for_args) -> void { +auto Context::ParamOrArgSave(bool for_args) -> void { auto [entry_parse_node, entry_node_id] = node_stack_.PopExpressionWithParseNode(); if (for_args) { // For an argument, we add a stub reference to the expression on the top of // the stack. There may not be anything on the IR prior to this. - entry_node_id = AddNode(SemanticsNode::StubReference::Make( + entry_node_id = AddNode(SemIR::Node::StubReference::Make( entry_parse_node, semantics_ir_->GetNode(entry_node_id).type_id(), entry_node_id)); } @@ -479,10 +466,10 @@ auto SemanticsContext::ParamOrArgSave(bool for_args) -> void { params_or_args.push_back(entry_node_id); } -auto SemanticsContext::CanonicalizeTypeImpl( - SemanticsNodeKind kind, +auto Context::CanonicalizeTypeImpl( + SemIR::NodeKind kind, llvm::function_ref profile_type, - llvm::function_ref make_node) -> SemanticsTypeId { + llvm::function_ref make_node) -> SemIR::TypeId { llvm::FoldingSetNodeID canonical_id; kind.Profile(canonical_id); profile_type(canonical_id); @@ -514,7 +501,7 @@ auto SemanticsContext::CanonicalizeTypeImpl( } // Compute a fingerprint for a tuple type, for use as a key in a folding set. -static auto ProfileTupleType(const llvm::SmallVector& type_ids, +static auto ProfileTupleType(const llvm::SmallVector& type_ids, llvm::FoldingSetNodeID& canonical_id) -> void { for (const auto& type_id : type_ids) { canonical_id.AddInteger(type_id.index); @@ -522,20 +509,20 @@ static auto ProfileTupleType(const llvm::SmallVector& type_ids, } // Compute a fingerprint for a type, for use as a key in a folding set. -static auto ProfileType(SemanticsContext& semantics_context, SemanticsNode node, +static auto ProfileType(Context& semantics_context, SemIR::Node node, llvm::FoldingSetNodeID& canonical_id) -> void { switch (node.kind()) { - case SemanticsNodeKind::ArrayType: { + case SemIR::NodeKind::ArrayType: { auto [bound_id, element_type_id] = node.GetAsArrayType(); canonical_id.AddInteger( semantics_context.semantics_ir().GetArrayBoundValue(bound_id)); canonical_id.AddInteger(element_type_id.index); break; } - case SemanticsNodeKind::Builtin: + case SemIR::NodeKind::Builtin: canonical_id.AddInteger(node.GetAsBuiltin().AsInt()); break; - case SemanticsNodeKind::CrossReference: { + case SemIR::NodeKind::CrossReference: { // TODO: Cross-references should be canonicalized by looking at their // target rather than treating them as new unique types. auto [xref_id, node_id] = node.GetAsCrossReference(); @@ -543,14 +530,14 @@ static auto ProfileType(SemanticsContext& semantics_context, SemanticsNode node, canonical_id.AddInteger(node_id.index); break; } - case SemanticsNodeKind::ConstType: + case SemIR::NodeKind::ConstType: canonical_id.AddInteger( semantics_context.GetUnqualifiedType(node.GetAsConstType()).index); break; - case SemanticsNodeKind::PointerType: + case SemIR::NodeKind::PointerType: canonical_id.AddInteger(node.GetAsPointerType().index); break; - case SemanticsNodeKind::StructType: { + case SemIR::NodeKind::StructType: { auto refs = semantics_context.semantics_ir().GetNodeBlock(node.GetAsStructType()); for (const auto& ref_id : refs) { @@ -561,17 +548,17 @@ static auto ProfileType(SemanticsContext& semantics_context, SemanticsNode node, } break; } - case SemanticsNodeKind::StubReference: { + case SemIR::NodeKind::StubReference: { // We rely on stub references not referring to each other to ensure we // only recurse once here. auto inner = semantics_context.semantics_ir().GetNode(node.GetAsStubReference()); - CARBON_CHECK(inner.kind() != SemanticsNodeKind::StubReference) + CARBON_CHECK(inner.kind() != SemIR::NodeKind::StubReference) << "A stub reference should never refer to another stub reference."; ProfileType(semantics_context, inner, canonical_id); break; } - case SemanticsNodeKind::TupleType: + case SemIR::NodeKind::TupleType: ProfileTupleType( semantics_context.semantics_ir().GetTypeBlock(node.GetAsTupleType()), canonical_id); @@ -581,8 +568,8 @@ static auto ProfileType(SemanticsContext& semantics_context, SemanticsNode node, } } -auto SemanticsContext::CanonicalizeTypeAndAddNodeIfNew(SemanticsNode node) - -> SemanticsTypeId { +auto Context::CanonicalizeTypeAndAddNodeIfNew(SemIR::Node node) + -> SemIR::TypeId { auto profile_node = [&](llvm::FoldingSetNodeID& canonical_id) { ProfileType(*this, node, canonical_id); }; @@ -590,8 +577,7 @@ auto SemanticsContext::CanonicalizeTypeAndAddNodeIfNew(SemanticsNode node) return CanonicalizeTypeImpl(node.kind(), profile_node, make_node); } -auto SemanticsContext::CanonicalizeType(SemanticsNodeId node_id) - -> SemanticsTypeId { +auto Context::CanonicalizeType(SemIR::NodeId node_id) -> SemIR::TypeId { auto it = canonical_types_.find(node_id); if (it != canonical_types_.end()) { return it->second; @@ -605,17 +591,17 @@ auto SemanticsContext::CanonicalizeType(SemanticsNodeId node_id) return CanonicalizeTypeImpl(node.kind(), profile_node, make_node); } -auto SemanticsContext::CanonicalizeStructType(ParseTree::Node parse_node, - SemanticsNodeBlockId refs_id) - -> SemanticsTypeId { - return CanonicalizeTypeAndAddNodeIfNew(SemanticsNode::StructType::Make( - parse_node, SemanticsTypeId::TypeType, refs_id)); +auto Context::CanonicalizeStructType(ParseTree::Node parse_node, + SemIR::NodeBlockId refs_id) + -> SemIR::TypeId { + return CanonicalizeTypeAndAddNodeIfNew(SemIR::Node::StructType::Make( + parse_node, SemIR::TypeId::TypeType, refs_id)); } -auto SemanticsContext::CanonicalizeTupleType( - ParseTree::Node parse_node, llvm::SmallVector&& type_ids) - -> SemanticsTypeId { - // Defer allocating a SemanticsTypeBlockId until we know this is a new type. +auto Context::CanonicalizeTupleType(ParseTree::Node parse_node, + llvm::SmallVector&& type_ids) + -> SemIR::TypeId { + // Defer allocating a SemIR::TypeBlockId until we know this is a new type. auto profile_tuple = [&](llvm::FoldingSetNodeID& canonical_id) { ProfileTupleType(type_ids, canonical_id); }; @@ -623,36 +609,33 @@ auto SemanticsContext::CanonicalizeTupleType( auto type_block_id = semantics_ir_->AddTypeBlock(); auto& type_block = semantics_ir_->GetTypeBlock(type_block_id); type_block = std::move(type_ids); - return AddNode(SemanticsNode::TupleType::Make( - parse_node, SemanticsTypeId::TypeType, type_block_id)); + return AddNode(SemIR::Node::TupleType::Make( + parse_node, SemIR::TypeId::TypeType, type_block_id)); }; - return CanonicalizeTypeImpl(SemanticsNodeKind::TupleType, profile_tuple, + return CanonicalizeTypeImpl(SemIR::NodeKind::TupleType, profile_tuple, make_tuple_node); } -auto SemanticsContext::GetPointerType(ParseTree::Node parse_node, - SemanticsTypeId pointee_type_id) - -> SemanticsTypeId { - return CanonicalizeTypeAndAddNodeIfNew(SemanticsNode::PointerType::Make( - parse_node, SemanticsTypeId::TypeType, pointee_type_id)); +auto Context::GetPointerType(ParseTree::Node parse_node, + SemIR::TypeId pointee_type_id) -> SemIR::TypeId { + return CanonicalizeTypeAndAddNodeIfNew(SemIR::Node::PointerType::Make( + parse_node, SemIR::TypeId::TypeType, pointee_type_id)); } -auto SemanticsContext::GetUnqualifiedType(SemanticsTypeId type_id) - -> SemanticsTypeId { - SemanticsNode type_node = +auto Context::GetUnqualifiedType(SemIR::TypeId type_id) -> SemIR::TypeId { + SemIR::Node type_node = semantics_ir_->GetNode(semantics_ir_->GetTypeAllowBuiltinTypes(type_id)); - if (type_node.kind() == SemanticsNodeKind::ConstType) { + if (type_node.kind() == SemIR::NodeKind::ConstType) { return type_node.GetAsConstType(); } return type_id; } -auto SemanticsContext::PrintForStackDump(llvm::raw_ostream& output) const - -> void { +auto Context::PrintForStackDump(llvm::raw_ostream& output) const -> void { node_stack_.PrintForStackDump(output); node_block_stack_.PrintForStackDump(output); params_or_args_stack_.PrintForStackDump(output); args_type_info_stack_.PrintForStackDump(output); } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_context.h b/toolchain/semantics/semantics_context.h index a335d81c608e..7be99a98a364 100644 --- a/toolchain/semantics/semantics_context.h +++ b/toolchain/semantics/semantics_context.h @@ -16,16 +16,16 @@ #include "toolchain/semantics/semantics_node_block_stack.h" #include "toolchain/semantics/semantics_node_stack.h" -namespace Carbon { +namespace Carbon::Check { // Context and shared functionality for semantics handlers. -class SemanticsContext { +class Context { public: // Stores references for work. - explicit SemanticsContext(const TokenizedBuffer& tokens, - DiagnosticEmitter& emitter, - const ParseTree& parse_tree, SemanticsIR& semantics, - llvm::raw_ostream* vlog_stream); + explicit Context(const TokenizedBuffer& tokens, + DiagnosticEmitter& emitter, + const ParseTree& parse_tree, SemIR::File& semantics, + llvm::raw_ostream* vlog_stream); // Marks an implementation TODO. Always returns false. auto TODO(ParseTree::Node parse_node, std::string label) -> bool; @@ -34,33 +34,33 @@ class SemanticsContext { auto VerifyOnFinish() -> void; // Adds a node to the current block, returning the produced ID. - auto AddNode(SemanticsNode node) -> SemanticsNodeId; + auto AddNode(SemIR::Node node) -> SemIR::NodeId; // Adds a node to the given block, returning the produced ID. - auto AddNodeToBlock(SemanticsNodeBlockId block, SemanticsNode node) - -> SemanticsNodeId; + auto AddNodeToBlock(SemIR::NodeBlockId block, SemIR::Node node) + -> SemIR::NodeId; - // Pushes a parse tree node onto the stack, storing the SemanticsNode as the + // Pushes a parse tree node onto the stack, storing the SemIR::Node as the // result. - auto AddNodeAndPush(ParseTree::Node parse_node, SemanticsNode node) -> void; + auto AddNodeAndPush(ParseTree::Node parse_node, SemIR::Node node) -> void; // Adds a name to name lookup. Prints a diagnostic for name conflicts. - auto AddNameToLookup(ParseTree::Node name_node, SemanticsStringId name_id, - SemanticsNodeId target_id) -> void; + auto AddNameToLookup(ParseTree::Node name_node, SemIR::StringId name_id, + SemIR::NodeId target_id) -> void; // Performs name lookup in a specified scope, returning the referenced node. // If scope_id is invalid, uses the current contextual scope. - auto LookupName(ParseTree::Node parse_node, SemanticsStringId name_id, - SemanticsNameScopeId scope_id, bool print_diagnostics) - -> SemanticsNodeId; + auto LookupName(ParseTree::Node parse_node, SemIR::StringId name_id, + SemIR::NameScopeId scope_id, bool print_diagnostics) + -> SemIR::NodeId; // Prints a diagnostic for a duplicate name. auto DiagnoseDuplicateName(ParseTree::Node parse_node, - SemanticsNodeId prev_def_id) -> void; + SemIR::NodeId prev_def_id) -> void; // Prints a diagnostic for a missing name. - auto DiagnoseNameNotFound(ParseTree::Node parse_node, - SemanticsStringId name_id) -> void; + auto DiagnoseNameNotFound(ParseTree::Node parse_node, SemIR::StringId name_id) + -> void; // Pushes a new scope onto scope_stack_. auto PushScope() -> void; @@ -72,28 +72,28 @@ class SemanticsContext { // the new block. All paths to the branch target must go through the current // block, though not necessarily through this branch. auto AddDominatedBlockAndBranch(ParseTree::Node parse_node) - -> SemanticsNodeBlockId; + -> SemIR::NodeBlockId; // Adds a `Branch` node branching to a new node block with a value, and // returns the ID of the new block. All paths to the branch target must go // through the current block. auto AddDominatedBlockAndBranchWithArg(ParseTree::Node parse_node, - SemanticsNodeId arg_id) - -> SemanticsNodeBlockId; + SemIR::NodeId arg_id) + -> SemIR::NodeBlockId; // Adds a `BranchIf` node branching to a new node block, and returns the ID // of the new block. All paths to the branch target must go through the // current block. auto AddDominatedBlockAndBranchIf(ParseTree::Node parse_node, - SemanticsNodeId cond_id) - -> SemanticsNodeBlockId; + SemIR::NodeId cond_id) + -> SemIR::NodeBlockId; // Adds branches from the given list of blocks to a new block, for // reconvergence of control flow, and pushes the new block onto the node // block stack. auto AddConvergenceBlockAndPush( ParseTree::Node parse_node, - std::initializer_list blocks) -> void; + std::initializer_list blocks) -> void; // Adds branches from the given list of blocks and values to a new block, for // reconvergence of control flow with a result value, and pushes the new @@ -101,8 +101,8 @@ class SemanticsContext { // value. auto AddConvergenceBlockWithArgAndPush( ParseTree::Node parse_node, - std::initializer_list> - blocks_and_args) -> SemanticsNodeId; + std::initializer_list> + blocks_and_args) -> SemIR::NodeId; // Add the current code block to the enclosing function. auto AddCurrentCodeBlockToFunction() -> void; @@ -118,24 +118,24 @@ class SemanticsContext { // future we may want to remember the right implicit conversions to do for // valid cases in order to efficiently handle generics. auto ImplicitAsForArgs( - SemanticsNodeBlockId arg_refs_id, ParseTree::Node param_parse_node, - SemanticsNodeBlockId param_refs_id, + SemIR::NodeBlockId arg_refs_id, ParseTree::Node param_parse_node, + SemIR::NodeBlockId param_refs_id, DiagnosticEmitter::DiagnosticBuilder* diagnostic) -> bool; // Runs ImplicitAsImpl for a situation where a cast is required, returning the // updated `value_id`. Prints a diagnostic and returns an Error if // unsupported. - auto ImplicitAsRequired(ParseTree::Node parse_node, SemanticsNodeId value_id, - SemanticsTypeId as_type_id) -> SemanticsNodeId; + auto ImplicitAsRequired(ParseTree::Node parse_node, SemIR::NodeId value_id, + SemIR::TypeId as_type_id) -> SemIR::NodeId; // Runs ImplicitAsRequired for a conversion to `bool`. - auto ImplicitAsBool(ParseTree::Node parse_node, SemanticsNodeId value_id) - -> SemanticsNodeId; + auto ImplicitAsBool(ParseTree::Node parse_node, SemIR::NodeId value_id) + -> SemIR::NodeId; // Canonicalizes a type which is tracked as a single node. // TODO: This should eventually return a type ID. - auto CanonicalizeType(SemanticsNodeId node_id) -> SemanticsTypeId; + auto CanonicalizeType(SemIR::NodeId node_id) -> SemIR::TypeId; // Handles canonicalization of struct types. This may create a new struct type // when it has a new structure, or reference an existing struct type when it @@ -145,36 +145,36 @@ class SemanticsContext { // name conflicts or other diagnostics during creation, which can use the // parse node. auto CanonicalizeStructType(ParseTree::Node parse_node, - SemanticsNodeBlockId refs_id) -> SemanticsTypeId; + SemIR::NodeBlockId refs_id) -> SemIR::TypeId; // Handles canonicalization of tuple types. This may create a new tuple type // if the `type_ids` doesn't match an existing tuple type. auto CanonicalizeTupleType(ParseTree::Node parse_node, - llvm::SmallVector&& type_ids) - -> SemanticsTypeId; + llvm::SmallVector&& type_ids) + -> SemIR::TypeId; // Returns a pointer type whose pointee type is `pointee_type_id`. - auto GetPointerType(ParseTree::Node parse_node, - SemanticsTypeId pointee_type_id) -> SemanticsTypeId; + auto GetPointerType(ParseTree::Node parse_node, SemIR::TypeId pointee_type_id) + -> SemIR::TypeId; // Converts an expression for use as a type. // TODO: This should eventually return a type ID. - auto ExpressionAsType(ParseTree::Node parse_node, SemanticsNodeId value_id) - -> SemanticsTypeId { + auto ExpressionAsType(ParseTree::Node parse_node, SemIR::NodeId value_id) + -> SemIR::TypeId { auto node = semantics_ir_->GetNode(value_id); - if (node.kind() == SemanticsNodeKind::StubReference) { + if (node.kind() == SemIR::NodeKind::StubReference) { value_id = node.GetAsStubReference(); CARBON_CHECK(semantics_ir_->GetNode(value_id).kind() != - SemanticsNodeKind::StubReference) + SemIR::NodeKind::StubReference) << "Stub reference should not point to another stub reference"; } return CanonicalizeType( - ImplicitAsRequired(parse_node, value_id, SemanticsTypeId::TypeType)); + ImplicitAsRequired(parse_node, value_id, SemIR::TypeId::TypeType)); } // Removes any top-level `const` qualifiers from a type. - auto GetUnqualifiedType(SemanticsTypeId type_id) -> SemanticsTypeId; + auto GetUnqualifiedType(SemIR::TypeId type_id) -> SemIR::TypeId; // Starts handling parameters or arguments. auto ParamOrArgStart() -> void; @@ -187,7 +187,7 @@ class SemanticsContext { // node_stack_ will be start_kind, and the caller should do type-specific // processing. Returns refs_id. auto ParamOrArgEnd(bool for_args, ParseNodeKind start_kind) - -> SemanticsNodeBlockId; + -> SemIR::NodeBlockId; // Saves a parameter from the top block in node_stack_ to the top block in // params_or_args_stack_. If for_args, adds a StubReference of the previous @@ -205,23 +205,21 @@ class SemanticsContext { auto parse_tree() -> const ParseTree& { return *parse_tree_; } - auto semantics_ir() -> SemanticsIR& { return *semantics_ir_; } + auto semantics_ir() -> SemIR::File& { return *semantics_ir_; } - auto node_stack() -> SemanticsNodeStack& { return node_stack_; } + auto node_stack() -> NodeStack& { return node_stack_; } - auto node_block_stack() -> SemanticsNodeBlockStack& { - return node_block_stack_; - } + auto node_block_stack() -> NodeBlockStack& { return node_block_stack_; } - auto args_type_info_stack() -> SemanticsNodeBlockStack& { + auto args_type_info_stack() -> NodeBlockStack& { return args_type_info_stack_; } - auto return_scope_stack() -> llvm::SmallVector& { + auto return_scope_stack() -> llvm::SmallVector& { return return_scope_stack_; } - auto declaration_name_stack() -> SemanticsDeclarationNameStack& { + auto declaration_name_stack() -> DeclarationNameStack& { return declaration_name_stack_; } @@ -240,20 +238,20 @@ class SemanticsContext { class TypeNode : public llvm::FastFoldingSetNode { public: explicit TypeNode(const llvm::FoldingSetNodeID& node_id, - SemanticsTypeId type_id) + SemIR::TypeId type_id) : llvm::FastFoldingSetNode(node_id), type_id_(type_id) {} - auto type_id() -> SemanticsTypeId { return type_id_; } + auto type_id() -> SemIR::TypeId { return type_id_; } private: - SemanticsTypeId type_id_; + SemIR::TypeId type_id_; }; // An entry in scope_stack_. struct ScopeStackEntry { // Names which are registered with name_lookup_, and will need to be // deregistered when the scope ends. - llvm::DenseSet names; + llvm::DenseSet names; // TODO: This likely needs to track things which need to be destructed. }; @@ -266,8 +264,8 @@ class SemanticsContext { // // If `output_value_id` is not null, then it will be set if there is a need to // cast. - auto ImplicitAsImpl(SemanticsNodeId value_id, SemanticsTypeId as_type_id, - SemanticsNodeId* output_value_id) -> ImplicitAsKind; + auto ImplicitAsImpl(SemIR::NodeId value_id, SemIR::TypeId as_type_id, + SemIR::NodeId* output_value_id) -> ImplicitAsKind; // Forms a canonical type ID for a type. This function is given two // callbacks: @@ -276,19 +274,19 @@ class SemanticsContext { // type. The ID should be distinct for all distinct type values with the same // `kind`. // - // `make_node()` is called to obtain a `SemanticsNodeId` that describes the + // `make_node()` is called to obtain a `SemIR::NodeId` that describes the // type. It is only called if the type does not already exist, so can be used - // to lazily build the `SemanticsNode`. `make_node()` is not permitted to + // to lazily build the `SemIR::Node`. `make_node()` is not permitted to // directly or indirectly canonicalize any types. auto CanonicalizeTypeImpl( - SemanticsNodeKind kind, + SemIR::NodeKind kind, llvm::function_ref profile_type, - llvm::function_ref make_node) -> SemanticsTypeId; + llvm::function_ref make_node) -> SemIR::TypeId; // Forms a canonical type ID for a type. If the type is new, adds the node to // the current block. - auto CanonicalizeTypeAndAddNodeIfNew(SemanticsNode node) -> SemanticsTypeId; + auto CanonicalizeTypeAndAddNodeIfNew(SemIR::Node node) -> SemIR::TypeId; auto current_scope() -> ScopeStackEntry& { return scope_stack_.back(); } @@ -301,39 +299,39 @@ class SemanticsContext { // The file's parse tree. const ParseTree* parse_tree_; - // The SemanticsIR being added to. - SemanticsIR* semantics_ir_; + // The SemIR::File being added to. + SemIR::File* semantics_ir_; // Whether to print verbose output. llvm::raw_ostream* vlog_stream_; // The stack during Build. Will contain file-level parse nodes on return. - SemanticsNodeStack node_stack_; + NodeStack node_stack_; // The stack of node blocks being used for general IR generation. - SemanticsNodeBlockStack node_block_stack_; + NodeBlockStack node_block_stack_; // The stack of node blocks being used for per-element tracking of nodes in // parameter and argument node blocks. Versus node_block_stack_, an element // will have 1 or more nodes in blocks in node_block_stack_, but only ever 1 // node in blocks here. - SemanticsNodeBlockStack params_or_args_stack_; + NodeBlockStack params_or_args_stack_; // The stack of node blocks being used for type information while processing // arguments. This is used in parallel with params_or_args_stack_. It's // currently only used for struct literals, where we need to track names // for a type separate from the literal arguments. - SemanticsNodeBlockStack args_type_info_stack_; + NodeBlockStack args_type_info_stack_; // A stack of return scopes; i.e., targets for `return`. Inside a function, // this will be a FunctionDeclaration. - llvm::SmallVector return_scope_stack_; + llvm::SmallVector return_scope_stack_; // A stack for scope context. llvm::SmallVector scope_stack_; // The stack used for qualified declaration name construction. - SemanticsDeclarationNameStack declaration_name_stack_; + DeclarationNameStack declaration_name_stack_; // Maps identifiers to name lookup results. Values are a stack of name lookup // results in the ancestor scopes. This offers constant-time lookup of names, @@ -341,12 +339,12 @@ class SemanticsContext { // reference. // // Names which no longer have lookup results are erased. - llvm::DenseMap> + llvm::DenseMap> name_lookup_; // Cache of the mapping from nodes to types, to avoid recomputing the folding // set ID. - llvm::DenseMap canonical_types_; + llvm::DenseMap canonical_types_; // Tracks the canonical representation of types that have been defined. llvm::FoldingSet canonical_type_nodes_; @@ -357,12 +355,10 @@ class SemanticsContext { }; // Parse node handlers. Returns false for unrecoverable errors. -#define CARBON_PARSE_NODE_KIND(Name) \ - auto SemanticsHandle##Name(SemanticsContext& context, \ - ParseTree::Node parse_node) \ - ->bool; +#define CARBON_PARSE_NODE_KIND(Name) \ + auto Handle##Name(Context& context, ParseTree::Node parse_node)->bool; #include "toolchain/parser/parse_node_kind.def" -} // namespace Carbon +} // namespace Carbon::Check #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_CONTEXT_H_ diff --git a/toolchain/semantics/semantics_declaration_name_stack.cpp b/toolchain/semantics/semantics_declaration_name_stack.cpp index 140fc2d773b1..a1e7ec7602ad 100644 --- a/toolchain/semantics/semantics_declaration_name_stack.cpp +++ b/toolchain/semantics/semantics_declaration_name_stack.cpp @@ -6,16 +6,16 @@ #include "toolchain/semantics/semantics_context.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsDeclarationNameStack::Push() -> void { +auto DeclarationNameStack::Push() -> void { declaration_name_stack_.push_back( - {.state = Context::State::New, - .target_scope_id = SemanticsNameScopeId::Invalid, - .resolved_node_id = SemanticsNodeId::Invalid}); + {.state = NameContext::State::New, + .target_scope_id = SemIR::NameScopeId::Invalid, + .resolved_node_id = SemIR::NodeId::Invalid}); } -auto SemanticsDeclarationNameStack::Pop() -> Context { +auto DeclarationNameStack::Pop() -> NameContext { if (context_->parse_tree().node_kind( context_->node_stack().PeekParseNode()) == ParseNodeKind::QualifiedDeclaration) { @@ -33,27 +33,26 @@ auto SemanticsDeclarationNameStack::Pop() -> Context { return declaration_name_stack_.pop_back_val(); } -auto SemanticsDeclarationNameStack::AddNameToLookup(Context name_context, - SemanticsNodeId target_id) - -> void { +auto DeclarationNameStack::AddNameToLookup(NameContext name_context, + SemIR::NodeId target_id) -> void { switch (name_context.state) { - case Context::State::Error: + case NameContext::State::Error: // The name is invalid and a diagnostic has already been emitted. return; - case Context::State::New: + case NameContext::State::New: CARBON_FATAL() << "Name is missing, not expected to call AddNameToLookup " "(but that may change based on error handling)."; - case Context::State::Resolved: - case Context::State::ResolvedNonScope: { + case NameContext::State::Resolved: + case NameContext::State::ResolvedNonScope: { context_->DiagnoseDuplicateName(name_context.parse_node, name_context.resolved_node_id); return; } - case Context::State::Unresolved: - if (name_context.target_scope_id == SemanticsNameScopeId::Invalid) { + case NameContext::State::Unresolved: + if (name_context.target_scope_id == SemIR::NameScopeId::Invalid) { context_->AddNameToLookup(name_context.parse_node, name_context.unresolved_name_id, target_id); } else { @@ -69,13 +68,14 @@ auto SemanticsDeclarationNameStack::AddNameToLookup(Context name_context, } } -auto SemanticsDeclarationNameStack::ApplyExpressionQualifier( - ParseTree::Node parse_node, SemanticsNodeId node_id) -> void { +auto DeclarationNameStack::ApplyExpressionQualifier(ParseTree::Node parse_node, + SemIR::NodeId node_id) + -> void { auto& name_context = declaration_name_stack_.back(); if (CanResolveQualifier(name_context, parse_node)) { - if (node_id == SemanticsNodeId::BuiltinError) { + if (node_id == SemIR::NodeId::BuiltinError) { // The input node is an error, so error the context. - name_context.state = Context::State::Error; + name_context.state = NameContext::State::Error; return; } @@ -88,8 +88,8 @@ auto SemanticsDeclarationNameStack::ApplyExpressionQualifier( } } -auto SemanticsDeclarationNameStack::ApplyNameQualifier( - ParseTree::Node parse_node, SemanticsStringId name_id) -> void { +auto DeclarationNameStack::ApplyNameQualifier(ParseTree::Node parse_node, + SemIR::StringId name_id) -> void { auto& name_context = declaration_name_stack_.back(); if (CanResolveQualifier(name_context, parse_node)) { // For identifier nodes, we need to perform a lookup on the identifier. @@ -97,9 +97,9 @@ auto SemanticsDeclarationNameStack::ApplyNameQualifier( auto resolved_node_id = context_->LookupName( name_context.parse_node, name_id, name_context.target_scope_id, /*print_diagnostics=*/false); - if (resolved_node_id == SemanticsNodeId::BuiltinError) { + if (resolved_node_id == SemIR::NodeId::BuiltinError) { // Invalid indicates an unresolved node. Store it and return. - name_context.state = Context::State::Unresolved; + name_context.state = NameContext::State::Unresolved; name_context.unresolved_name_id = name_id; return; } else { @@ -111,42 +111,43 @@ auto SemanticsDeclarationNameStack::ApplyNameQualifier( } } -auto SemanticsDeclarationNameStack::UpdateScopeIfNeeded(Context& name_context) +auto DeclarationNameStack::UpdateScopeIfNeeded(NameContext& name_context) -> void { // This will only be reached for resolved nodes. We update the target // scope based on the resolved type. auto resolved_node = context_->semantics_ir().GetNode(name_context.resolved_node_id); switch (resolved_node.kind()) { - case SemanticsNodeKind::Namespace: - name_context.state = Context::State::Resolved; + case SemIR::NodeKind::Namespace: + name_context.state = NameContext::State::Resolved; name_context.target_scope_id = resolved_node.GetAsNamespace(); break; default: - name_context.state = Context::State::ResolvedNonScope; + name_context.state = NameContext::State::ResolvedNonScope; break; } } -auto SemanticsDeclarationNameStack::CanResolveQualifier( - Context& name_context, ParseTree::Node parse_node) -> bool { +auto DeclarationNameStack::CanResolveQualifier(NameContext& name_context, + ParseTree::Node parse_node) + -> bool { switch (name_context.state) { - case Context::State::Error: + case NameContext::State::Error: // Already in an error state, so return without examining. return false; - case Context::State::Unresolved: + case NameContext::State::Unresolved: // Because more qualifiers were found, we diagnose that the earlier // qualifier failed to resolve. - name_context.state = Context::State::Error; + name_context.state = NameContext::State::Error; context_->DiagnoseNameNotFound(name_context.parse_node, name_context.unresolved_name_id); return false; - case Context::State::ResolvedNonScope: { + case NameContext::State::ResolvedNonScope: { // Because more qualifiers were found, we diagnose that the earlier // qualifier didn't resolve to a scoped entity. - name_context.state = Context::State::Error; + name_context.state = NameContext::State::Error; CARBON_DIAGNOSTIC(QualifiedDeclarationInNonScope, Error, "Declaration qualifiers are only allowed for entities " "that provide a scope."); @@ -159,12 +160,12 @@ auto SemanticsDeclarationNameStack::CanResolveQualifier( return false; } - case Context::State::New: - case Context::State::Resolved: { + case NameContext::State::New: + case NameContext::State::Resolved: { name_context.parse_node = parse_node; return true; } } } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_declaration_name_stack.h b/toolchain/semantics/semantics_declaration_name_stack.h index cd413009e695..978caffadbd1 100644 --- a/toolchain/semantics/semantics_declaration_name_stack.h +++ b/toolchain/semantics/semantics_declaration_name_stack.h @@ -9,9 +9,9 @@ #include "toolchain/parser/parse_tree.h" #include "toolchain/semantics/semantics_node.h" -namespace Carbon { +namespace Carbon::Check { -class SemanticsContext; +class Context; // Provides support and stacking for qualified declaration name handling. // @@ -48,10 +48,10 @@ class SemanticsContext; // // is forward declared in `MyType`, but is not a scope itself. // fn MyNamespace.MyType.DoSomething() { ... } // ``` -class SemanticsDeclarationNameStack { +class DeclarationNameStack { public: // Context for declaration name construction. - struct Context { + struct NameContext { enum class State { // A new context which has not processed any parts of the qualifier. New, @@ -77,7 +77,7 @@ class SemanticsDeclarationNameStack { // The scope which qualified names are added to. For unqualified names, // this will be Invalid to indicate the current scope should be used. - SemanticsNameScopeId target_scope_id = SemanticsNameScopeId::Invalid; + SemIR::NameScopeId target_scope_id = SemIR::NameScopeId::Invalid; // The last parse node used. ParseTree::Node parse_node = ParseTree::Node::Invalid; @@ -85,15 +85,14 @@ class SemanticsDeclarationNameStack { union { // The ID of a resolved qualifier, including both identifiers and // expressions. Invalid indicates resolution failed. - SemanticsNodeId resolved_node_id = SemanticsNodeId::Invalid; + SemIR::NodeId resolved_node_id = SemIR::NodeId::Invalid; // The ID of an unresolved identifier. - SemanticsStringId unresolved_name_id; + SemIR::StringId unresolved_name_id; }; }; - explicit SemanticsDeclarationNameStack(SemanticsContext* context) - : context_(context) {} + explicit DeclarationNameStack(Context* context) : context_(context) {} // Pushes processing of a new declaration name, which will be used // contextually. @@ -102,38 +101,39 @@ class SemanticsDeclarationNameStack { // Pops the current declaration name processing, returning the final context // for adding the name to lookup. This also pops the final name node from the // node stack, which will be applied to the declaration name if appropriate. - auto Pop() -> Context; + auto Pop() -> NameContext; // Applies an expression from the node stack to the top of the declaration // name stack. auto ApplyExpressionQualifier(ParseTree::Node parse_node, - SemanticsNodeId node_id) -> void; + SemIR::NodeId node_id) -> void; // Applies a Name from the node stack to the top of the declaration name // stack. - auto ApplyNameQualifier(ParseTree::Node parse_node, SemanticsStringId name_id) + auto ApplyNameQualifier(ParseTree::Node parse_node, SemIR::StringId name_id) -> void; // Adds a name to name lookup. Prints a diagnostic for name conflicts. - auto AddNameToLookup(Context name_context, SemanticsNodeId target_id) -> void; + auto AddNameToLookup(NameContext name_context, SemIR::NodeId target_id) + -> void; private: // Returns true if the context is in a state where it can resolve qualifiers. // Updates name_context as needed. - auto CanResolveQualifier(Context& name_context, ParseTree::Node parse_node) - -> bool; + auto CanResolveQualifier(NameContext& name_context, + ParseTree::Node parse_node) -> bool; // Updates the scope on name_context as needed. This is called after // resolution is complete, whether for Name or expression. - auto UpdateScopeIfNeeded(Context& name_context) -> void; + auto UpdateScopeIfNeeded(NameContext& name_context) -> void; // The linked context. - SemanticsContext* context_; + Context* context_; // Provides nesting for construction. - llvm::SmallVector declaration_name_stack_; + llvm::SmallVector declaration_name_stack_; }; -} // namespace Carbon +} // namespace Carbon::Check #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_DECLARATION_NAME_STACK_H_ diff --git a/toolchain/semantics/semantics_file_test.cpp b/toolchain/semantics/semantics_file_test.cpp index 296d72b463b8..d6f4dd187560 100644 --- a/toolchain/semantics/semantics_file_test.cpp +++ b/toolchain/semantics/semantics_file_test.cpp @@ -10,7 +10,7 @@ namespace Carbon::Testing { namespace { -class SemanticsFileTest : public DriverFileTestBase { +class CheckFileTest : public DriverFileTestBase { public: using DriverFileTestBase::DriverFileTestBase; @@ -24,6 +24,6 @@ class SemanticsFileTest : public DriverFileTestBase { } // namespace -CARBON_FILE_TEST_FACTORY(SemanticsFileTest); +CARBON_FILE_TEST_FACTORY(CheckFileTest); } // namespace Carbon::Testing diff --git a/toolchain/semantics/semantics_handle_array.cpp b/toolchain/semantics/semantics_handle_array.cpp index e9716011ab2d..6b08f1cd5153 100644 --- a/toolchain/semantics/semantics_handle_array.cpp +++ b/toolchain/semantics/semantics_handle_array.cpp @@ -7,22 +7,21 @@ #include "toolchain/semantics/semantics_node.h" #include "toolchain/semantics/semantics_node_kind.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsHandleArrayExpressionStart(SemanticsContext& /*context*/, - ParseTree::Node /*parse_node*/) - -> bool { +auto HandleArrayExpressionStart(Context& /*context*/, + ParseTree::Node /*parse_node*/) -> bool { return true; } -auto SemanticsHandleArrayExpressionSemi(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleArrayExpressionSemi(Context& context, ParseTree::Node parse_node) + -> bool { context.node_stack().Push(parse_node); return true; } -auto SemanticsHandleArrayExpression(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleArrayExpression(Context& context, ParseTree::Node parse_node) + -> bool { // TODO: Handle array type with undefined bound. if (context.parse_tree().node_kind(context.node_stack().PeekParseNode()) == ParseNodeKind::ArrayExpressionSemi) { @@ -36,22 +35,22 @@ auto SemanticsHandleArrayExpression(SemanticsContext& context, .PopAndDiscardSoloParseNode(); auto element_type_node_id = context.node_stack().PopExpression(); auto bound_node = context.semantics_ir().GetNode(bound_node_id); - if (bound_node.kind() == SemanticsNodeKind::IntegerLiteral) { + if (bound_node.kind() == SemIR::NodeKind::IntegerLiteral) { auto bound_value = context.semantics_ir().GetIntegerLiteral( bound_node.GetAsIntegerLiteral()); if (!bound_value.isNegative()) { context.AddNodeAndPush( parse_node, - SemanticsNode::ArrayType::Make( - parse_node, SemanticsTypeId::TypeType, bound_node_id, + SemIR::Node::ArrayType::Make( + parse_node, SemIR::TypeId::TypeType, bound_node_id, context.ExpressionAsType(parse_node, element_type_node_id))); return true; } } CARBON_DIAGNOSTIC(InvalidArrayExpression, Error, "Invalid array expression."); context.emitter().Emit(parse_node, InvalidArrayExpression); - context.node_stack().Push(parse_node, SemanticsNodeId::BuiltinError); + context.node_stack().Push(parse_node, SemIR::NodeId::BuiltinError); return true; } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_handle_call_expression.cpp b/toolchain/semantics/semantics_handle_call_expression.cpp index 8246ea54a929..2b60234d4579 100644 --- a/toolchain/semantics/semantics_handle_call_expression.cpp +++ b/toolchain/semantics/semantics_handle_call_expression.cpp @@ -5,10 +5,10 @@ #include "toolchain/semantics/semantics_context.h" #include "toolchain/semantics/semantics_node.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsHandleCallExpression(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleCallExpression(Context& context, ParseTree::Node parse_node) + -> bool { auto refs_id = context.ParamOrArgEnd( /*for_args=*/true, ParseNodeKind::CallExpressionStart); @@ -17,7 +17,7 @@ auto SemanticsHandleCallExpression(SemanticsContext& context, context.node_stack() .PopWithParseNode(); auto name_node = context.semantics_ir().GetNode(name_id); - if (name_node.kind() != SemanticsNodeKind::FunctionDeclaration) { + if (name_node.kind() != SemIR::NodeKind::FunctionDeclaration) { // TODO: Work on error. context.TODO(parse_node, "Not a callable name"); context.node_stack().Push(parse_node, name_id); @@ -33,7 +33,7 @@ auto SemanticsHandleCallExpression(SemanticsContext& context, if (!context.ImplicitAsForArgs(refs_id, name_node.parse_node(), callable.param_refs_id, &diagnostic)) { diagnostic.Emit(); - context.node_stack().Push(parse_node, SemanticsNodeId::BuiltinError); + context.node_stack().Push(parse_node, SemIR::NodeId::BuiltinError); return true; } @@ -42,32 +42,31 @@ auto SemanticsHandleCallExpression(SemanticsContext& context, /*diagnostic=*/nullptr)); // TODO: Propagate return types from callable. - SemanticsTypeId type_id = callable.return_type_id; + SemIR::TypeId type_id = callable.return_type_id; // For functions with an implicit return type, set the return type to empty // tuple type. - if (type_id == SemanticsTypeId::Invalid) { + if (type_id == SemIR::TypeId::Invalid) { type_id = context.CanonicalizeTupleType(call_expr_parse_node, {}); } - auto call_node_id = context.AddNode(SemanticsNode::Call::Make( + auto call_node_id = context.AddNode(SemIR::Node::Call::Make( call_expr_parse_node, type_id, refs_id, function_id)); context.node_stack().Push(parse_node, call_node_id); return true; } -auto SemanticsHandleCallExpressionComma(SemanticsContext& context, - ParseTree::Node /*parse_node*/) +auto HandleCallExpressionComma(Context& context, ParseTree::Node /*parse_node*/) -> bool { context.ParamOrArgComma(/*for_args=*/true); return true; } -auto SemanticsHandleCallExpressionStart(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleCallExpressionStart(Context& context, ParseTree::Node parse_node) + -> bool { auto name_id = context.node_stack().PopExpression(); context.node_stack().Push(parse_node, name_id); context.ParamOrArgStart(); return true; } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_handle_class.cpp b/toolchain/semantics/semantics_handle_class.cpp index 7b422f2fbdbd..7339e8a2e51d 100644 --- a/toolchain/semantics/semantics_handle_class.cpp +++ b/toolchain/semantics/semantics_handle_class.cpp @@ -4,26 +4,26 @@ #include "toolchain/semantics/semantics_context.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsHandleClassDeclaration(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleClassDeclaration(Context& context, ParseTree::Node parse_node) + -> bool { return context.TODO(parse_node, "HandleClassDeclaration"); } -auto SemanticsHandleClassDefinition(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleClassDefinition(Context& context, ParseTree::Node parse_node) + -> bool { return context.TODO(parse_node, "HandleClassDefinition"); } -auto SemanticsHandleClassDefinitionStart(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleClassDefinitionStart(Context& context, ParseTree::Node parse_node) + -> bool { return context.TODO(parse_node, "HandleClassDefinitionStart"); } -auto SemanticsHandleClassIntroducer(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleClassIntroducer(Context& context, ParseTree::Node parse_node) + -> bool { return context.TODO(parse_node, "HandleClassIntroducer"); } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_handle_codeblock.cpp b/toolchain/semantics/semantics_handle_codeblock.cpp index 6987423eb909..b693ff603dbb 100644 --- a/toolchain/semantics/semantics_handle_codeblock.cpp +++ b/toolchain/semantics/semantics_handle_codeblock.cpp @@ -4,20 +4,19 @@ #include "toolchain/semantics/semantics_context.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsHandleCodeBlockStart(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleCodeBlockStart(Context& context, ParseTree::Node parse_node) + -> bool { context.node_stack().Push(parse_node); context.PushScope(); return true; } -auto SemanticsHandleCodeBlock(SemanticsContext& context, - ParseTree::Node /*parse_node*/) -> bool { +auto HandleCodeBlock(Context& context, ParseTree::Node /*parse_node*/) -> bool { context.PopScope(); context.node_stack().PopForSoloParseNode(); return true; } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_handle_function.cpp b/toolchain/semantics/semantics_handle_function.cpp index b78c47cc10a0..13ff7e2c0678 100644 --- a/toolchain/semantics/semantics_handle_function.cpp +++ b/toolchain/semantics/semantics_handle_function.cpp @@ -4,19 +4,19 @@ #include "toolchain/semantics/semantics_context.h" -namespace Carbon { +namespace Carbon::Check { // Build a FunctionDeclaration describing the signature of a function. This // handles the common logic shared by function declaration syntax and function // definition syntax. -static auto BuildFunctionDeclaration(SemanticsContext& context) - -> std::pair { - SemanticsTypeId return_type_id = SemanticsTypeId::Invalid; +static auto BuildFunctionDeclaration(Context& context) + -> std::pair { + SemIR::TypeId return_type_id = SemIR::TypeId::Invalid; if (context.parse_tree().node_kind(context.node_stack().PeekParseNode()) == ParseNodeKind::ReturnType) { return_type_id = context.node_stack().Pop(); } - SemanticsNodeBlockId param_refs_id = + SemIR::NodeBlockId param_refs_id = context.node_stack().Pop(); auto name_context = context.declaration_name_stack().Pop(); auto fn_node = context.node_stack() @@ -27,30 +27,28 @@ static auto BuildFunctionDeclaration(SemanticsContext& context) // Add the callable. auto function_id = context.semantics_ir().AddFunction( - {.name_id = - name_context.state == - SemanticsDeclarationNameStack::Context::State::Unresolved - ? name_context.unresolved_name_id - : SemanticsStringId(SemanticsStringId::InvalidIndex), + {.name_id = name_context.state == + DeclarationNameStack::NameContext::State::Unresolved + ? name_context.unresolved_name_id + : SemIR::StringId(SemIR::StringId::InvalidIndex), .param_refs_id = param_refs_id, .return_type_id = return_type_id, .body_block_ids = {}}); auto decl_id = context.AddNode( - SemanticsNode::FunctionDeclaration::Make(fn_node, function_id)); + SemIR::Node::FunctionDeclaration::Make(fn_node, function_id)); context.declaration_name_stack().AddNameToLookup(name_context, decl_id); return {function_id, decl_id}; } -auto SemanticsHandleFunctionDeclaration(SemanticsContext& context, - ParseTree::Node /*parse_node*/) +auto HandleFunctionDeclaration(Context& context, ParseTree::Node /*parse_node*/) -> bool { BuildFunctionDeclaration(context); return true; } -auto SemanticsHandleFunctionDefinition(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { - SemanticsFunctionId function_id = +auto HandleFunctionDefinition(Context& context, ParseTree::Node parse_node) + -> bool { + SemIR::FunctionId function_id = context.node_stack().Pop(); // If the `}` of the function is reachable, reject if we need a return value @@ -64,7 +62,7 @@ auto SemanticsHandleFunctionDefinition(SemanticsContext& context, "Missing `return` at end of function with declared return type."); context.emitter().Emit(parse_node, MissingReturnStatement); } else { - context.AddNode(SemanticsNode::Return::Make(parse_node)); + context.AddNode(SemIR::Node::Return::Make(parse_node)); } } @@ -74,8 +72,7 @@ auto SemanticsHandleFunctionDefinition(SemanticsContext& context, return true; } -auto SemanticsHandleFunctionDefinitionStart(SemanticsContext& context, - ParseTree::Node parse_node) +auto HandleFunctionDefinitionStart(Context& context, ParseTree::Node parse_node) -> bool { // Process the declaration portion of the function. auto [function_id, decl_id] = BuildFunctionDeclaration(context); @@ -99,8 +96,8 @@ auto SemanticsHandleFunctionDefinitionStart(SemanticsContext& context, return true; } -auto SemanticsHandleFunctionIntroducer(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleFunctionIntroducer(Context& context, ParseTree::Node parse_node) + -> bool { // Push the bracketing node. context.node_stack().Push(parse_node); // A name should always follow. @@ -108,8 +105,7 @@ auto SemanticsHandleFunctionIntroducer(SemanticsContext& context, return true; } -auto SemanticsHandleReturnType(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleReturnType(Context& context, ParseTree::Node parse_node) -> bool { // Propagate the type expression. auto [type_parse_node, type_node_id] = context.node_stack().PopExpressionWithParseNode(); @@ -118,4 +114,4 @@ auto SemanticsHandleReturnType(SemanticsContext& context, return true; } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_handle_if_expression.cpp b/toolchain/semantics/semantics_handle_if_expression.cpp index 5c9ae5cbd928..f1bf18205029 100644 --- a/toolchain/semantics/semantics_handle_if_expression.cpp +++ b/toolchain/semantics/semantics_handle_if_expression.cpp @@ -4,10 +4,9 @@ #include "toolchain/semantics/semantics_context.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsHandleIfExpressionIf(SemanticsContext& context, - ParseTree::Node if_node) -> bool { +auto HandleIfExpressionIf(Context& context, ParseTree::Node if_node) -> bool { auto cond_value_id = context.node_stack().PopExpression(); context.node_stack().Push(if_node); @@ -26,15 +25,15 @@ auto SemanticsHandleIfExpressionIf(SemanticsContext& context, return true; } -auto SemanticsHandleIfExpressionThen(SemanticsContext& context, - ParseTree::Node then_node) -> bool { +auto HandleIfExpressionThen(Context& context, ParseTree::Node then_node) + -> bool { context.node_stack().Push(then_node, context.node_block_stack().Pop()); context.AddCurrentCodeBlockToFunction(); return true; } -auto SemanticsHandleIfExpressionElse(SemanticsContext& context, - ParseTree::Node else_node) -> bool { +auto HandleIfExpressionElse(Context& context, ParseTree::Node else_node) + -> bool { auto else_value_id = context.node_stack().PopExpression(); auto [then_node, then_end_block_id] = context.node_stack().PopWithParseNode(); @@ -61,4 +60,4 @@ auto SemanticsHandleIfExpressionElse(SemanticsContext& context, return true; } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_handle_if_statement.cpp b/toolchain/semantics/semantics_handle_if_statement.cpp index a144d0e6ca1e..659eba40a16e 100644 --- a/toolchain/semantics/semantics_handle_if_statement.cpp +++ b/toolchain/semantics/semantics_handle_if_statement.cpp @@ -5,15 +5,14 @@ #include "toolchain/semantics/semantics_context.h" #include "toolchain/semantics/semantics_node.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsHandleIfConditionStart(SemanticsContext& /*context*/, - ParseTree::Node /*parse_node*/) -> bool { +auto HandleIfConditionStart(Context& /*context*/, + ParseTree::Node /*parse_node*/) -> bool { return true; } -auto SemanticsHandleIfCondition(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleIfCondition(Context& context, ParseTree::Node parse_node) -> bool { // Convert the condition to `bool`. auto cond_value_id = context.node_stack().PopExpression(); cond_value_id = context.ImplicitAsBool(parse_node, cond_value_id); @@ -35,8 +34,8 @@ auto SemanticsHandleIfCondition(SemanticsContext& context, return true; } -auto SemanticsHandleIfStatementElse(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleIfStatementElse(Context& context, ParseTree::Node parse_node) + -> bool { context.node_stack().PopAndDiscardSoloParseNode(); // Switch to emitting the else block. @@ -46,8 +45,7 @@ auto SemanticsHandleIfStatementElse(SemanticsContext& context, return true; } -auto SemanticsHandleIfStatement(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleIfStatement(Context& context, ParseTree::Node parse_node) -> bool { // Either the then or else block, depending on whether there's an `else` node // on the top of the node stack. auto sub_block_id = context.node_block_stack().PopForAdd(); @@ -60,14 +58,14 @@ auto SemanticsHandleIfStatement(SemanticsContext& context, .PopAndDiscardSoloParseNode(); context.AddNodeToBlock( sub_block_id, - SemanticsNode::Branch::Make(parse_node, - context.node_block_stack().PeekForAdd())); + SemIR::Node::Branch::Make(parse_node, + context.node_block_stack().PeekForAdd())); break; } case ParseNodeKind::IfStatementElse: { // Branch from the then and else blocks to a new resumption block. - SemanticsNodeBlockId then_block_id = + SemIR::NodeBlockId then_block_id = context.node_stack().Pop(); context.AddConvergenceBlockAndPush(parse_node, {then_block_id, sub_block_id}); @@ -83,4 +81,4 @@ auto SemanticsHandleIfStatement(SemanticsContext& context, return true; } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_handle_index.cpp b/toolchain/semantics/semantics_handle_index.cpp index c7eb7868c8c5..a57776295174 100644 --- a/toolchain/semantics/semantics_handle_index.cpp +++ b/toolchain/semantics/semantics_handle_index.cpp @@ -7,17 +7,16 @@ #include "toolchain/semantics/semantics_node.h" #include "toolchain/semantics/semantics_node_kind.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsHandleIndexExpressionStart(SemanticsContext& /*context*/, - ParseTree::Node /*parse_node*/) - -> bool { +auto HandleIndexExpressionStart(Context& /*context*/, + ParseTree::Node /*parse_node*/) -> bool { // Leave the expression on the stack for IndexExpression. return true; } -auto SemanticsHandleIndexExpression(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleIndexExpression(Context& context, ParseTree::Node parse_node) + -> bool { CARBON_DIAGNOSTIC(OutOfBoundsAccess, Error, "Index `{0}` is past the end of `{1}`.", llvm::APSInt, std::string); @@ -30,9 +29,9 @@ auto SemanticsHandleIndexExpression(SemanticsContext& context, context.semantics_ir().GetTypeAllowBuiltinTypes(name_node.type_id()); auto name_type_node = context.semantics_ir().GetNode(name_type_id); - if (name_type_node.kind() == SemanticsNodeKind::ArrayType) { + if (name_type_node.kind() == SemIR::NodeKind::ArrayType) { auto [bound_id, type_id] = name_type_node.GetAsArrayType(); - if (index_node.kind() == SemanticsNodeKind::IntegerLiteral) { + if (index_node.kind() == SemIR::NodeKind::IntegerLiteral) { const auto& index_val = context.semantics_ir().GetIntegerLiteral( index_node.GetAsIntegerLiteral()); if (index_val.uge(context.semantics_ir().GetArrayBoundValue(bound_id))) { @@ -42,22 +41,22 @@ auto SemanticsHandleIndexExpression(SemanticsContext& context, context.semantics_ir().StringifyType(name_node.type_id())); } else { context.AddNodeAndPush( - parse_node, SemanticsNode::ArrayIndex::Make( + parse_node, SemIR::Node::ArrayIndex::Make( parse_node, type_id, name_node_id, index_node_id)); return true; } } else if (context.ImplicitAsRequired( index_node.parse_node(), index_node_id, context.CanonicalizeType( - SemanticsNodeId::BuiltinIntegerType)) != - SemanticsNodeId::BuiltinError) { + SemIR::NodeId::BuiltinIntegerType)) != + SemIR::NodeId::BuiltinError) { context.AddNodeAndPush( - parse_node, SemanticsNode::ArrayIndex::Make( + parse_node, SemIR::Node::ArrayIndex::Make( parse_node, type_id, name_node_id, index_node_id)); return true; } - } else if (name_type_node.kind() == SemanticsNodeKind::TupleType) { - if (index_node.kind() == SemanticsNodeKind::IntegerLiteral) { + } else if (name_type_node.kind() == SemIR::NodeKind::TupleType) { + if (index_node.kind() == SemIR::NodeKind::IntegerLiteral) { const auto& index_val = context.semantics_ir().GetIntegerLiteral( index_node.GetAsIntegerLiteral()); auto type_block = @@ -70,7 +69,7 @@ auto SemanticsHandleIndexExpression(SemanticsContext& context, context.semantics_ir().StringifyType(name_node.type_id())); } else { context.AddNodeAndPush( - parse_node, SemanticsNode::TupleIndex::Make( + parse_node, SemIR::Node::TupleIndex::Make( parse_node, type_block[index_val.getZExtValue()], name_node_id, index_node_id)); return true; @@ -80,14 +79,14 @@ auto SemanticsHandleIndexExpression(SemanticsContext& context, "Type cannot be determined at compile time."); context.emitter().Emit(parse_node, NondeterministicType); } - } else if (name_type_id != SemanticsNodeId::BuiltinError) { + } else if (name_type_id != SemIR::NodeId::BuiltinError) { CARBON_DIAGNOSTIC(InvalidIndexExpression, Error, "Invalid index expression."); context.emitter().Emit(parse_node, InvalidIndexExpression); } - context.node_stack().Push(parse_node, SemanticsNodeId::BuiltinError); + context.node_stack().Push(parse_node, SemIR::NodeId::BuiltinError); return true; } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_handle_interface.cpp b/toolchain/semantics/semantics_handle_interface.cpp index bca7b51a746b..20022740a514 100644 --- a/toolchain/semantics/semantics_handle_interface.cpp +++ b/toolchain/semantics/semantics_handle_interface.cpp @@ -4,27 +4,26 @@ #include "toolchain/semantics/semantics_context.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsHandleInterfaceDeclaration(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleInterfaceDeclaration(Context& context, ParseTree::Node parse_node) + -> bool { return context.TODO(parse_node, "HandleInterfaceDeclaration"); } -auto SemanticsHandleInterfaceDefinition(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleInterfaceDefinition(Context& context, ParseTree::Node parse_node) + -> bool { return context.TODO(parse_node, "HandleInterfaceDefinition"); } -auto SemanticsHandleInterfaceDefinitionStart(SemanticsContext& context, - ParseTree::Node parse_node) - -> bool { +auto HandleInterfaceDefinitionStart(Context& context, + ParseTree::Node parse_node) -> bool { return context.TODO(parse_node, "HandleInterfaceDefinitionStart"); } -auto SemanticsHandleInterfaceIntroducer(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleInterfaceIntroducer(Context& context, ParseTree::Node parse_node) + -> bool { return context.TODO(parse_node, "HandleInterfaceIntroducer"); } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_handle_literal.cpp b/toolchain/semantics/semantics_handle_literal.cpp index e8ce58fdd465..e764fb7fcad0 100644 --- a/toolchain/semantics/semantics_handle_literal.cpp +++ b/toolchain/semantics/semantics_handle_literal.cpp @@ -4,21 +4,20 @@ #include "toolchain/semantics/semantics_context.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsHandleLiteral(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleLiteral(Context& context, ParseTree::Node parse_node) -> bool { auto token = context.parse_tree().node_token(parse_node); switch (auto token_kind = context.tokens().GetKind(token)) { case TokenKind::False: case TokenKind::True: { context.AddNodeAndPush( parse_node, - SemanticsNode::BoolLiteral::Make( + SemIR::Node::BoolLiteral::Make( parse_node, - context.CanonicalizeType(SemanticsNodeId::BuiltinBoolType), - token_kind == TokenKind::True ? SemanticsBoolValue::True - : SemanticsBoolValue::False)); + context.CanonicalizeType(SemIR::NodeId::BuiltinBoolType), + token_kind == TokenKind::True ? SemIR::BoolValue::True + : SemIR::BoolValue::False)); break; } case TokenKind::IntegerLiteral: { @@ -26,10 +25,9 @@ auto SemanticsHandleLiteral(SemanticsContext& context, context.tokens().GetIntegerLiteral(token)); context.AddNodeAndPush( parse_node, - SemanticsNode::IntegerLiteral::Make( + SemIR::Node::IntegerLiteral::Make( parse_node, - context.CanonicalizeType(SemanticsNodeId::BuiltinIntegerType), - id)); + context.CanonicalizeType(SemIR::NodeId::BuiltinIntegerType), id)); break; } case TokenKind::RealLiteral: { @@ -38,12 +36,12 @@ auto SemanticsHandleLiteral(SemanticsContext& context, {.mantissa = token_value.Mantissa(), .exponent = token_value.Exponent(), .is_decimal = token_value.IsDecimal()}); - context.AddNodeAndPush(parse_node, - SemanticsNode::RealLiteral::Make( - parse_node, - context.CanonicalizeType( - SemanticsNodeId::BuiltinFloatingPointType), - id)); + context.AddNodeAndPush( + parse_node, + SemIR::Node::RealLiteral::Make( + parse_node, + context.CanonicalizeType(SemIR::NodeId::BuiltinFloatingPointType), + id)); break; } case TokenKind::StringLiteral: { @@ -51,18 +49,17 @@ auto SemanticsHandleLiteral(SemanticsContext& context, context.tokens().GetStringLiteral(token)); context.AddNodeAndPush( parse_node, - SemanticsNode::StringLiteral::Make( + SemIR::Node::StringLiteral::Make( parse_node, - context.CanonicalizeType(SemanticsNodeId::BuiltinStringType), - id)); + context.CanonicalizeType(SemIR::NodeId::BuiltinStringType), id)); break; } case TokenKind::Type: { - context.node_stack().Push(parse_node, SemanticsNodeId::BuiltinTypeType); + context.node_stack().Push(parse_node, SemIR::NodeId::BuiltinTypeType); break; } case TokenKind::Bool: { - context.node_stack().Push(parse_node, SemanticsNodeId::BuiltinBoolType); + context.node_stack().Push(parse_node, SemIR::NodeId::BuiltinBoolType); break; } case TokenKind::IntegerTypeLiteral: { @@ -70,8 +67,7 @@ auto SemanticsHandleLiteral(SemanticsContext& context, if (text != "i32") { return context.TODO(parse_node, "Currently only i32 is allowed"); } - context.node_stack().Push(parse_node, - SemanticsNodeId::BuiltinIntegerType); + context.node_stack().Push(parse_node, SemIR::NodeId::BuiltinIntegerType); break; } case TokenKind::FloatingPointTypeLiteral: { @@ -80,11 +76,11 @@ auto SemanticsHandleLiteral(SemanticsContext& context, return context.TODO(parse_node, "Currently only f64 is allowed"); } context.node_stack().Push(parse_node, - SemanticsNodeId::BuiltinFloatingPointType); + SemIR::NodeId::BuiltinFloatingPointType); break; } case TokenKind::StringTypeLiteral: { - context.node_stack().Push(parse_node, SemanticsNodeId::BuiltinStringType); + context.node_stack().Push(parse_node, SemIR::NodeId::BuiltinStringType); break; } default: { @@ -95,4 +91,4 @@ auto SemanticsHandleLiteral(SemanticsContext& context, return true; } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_handle_loop_statement.cpp b/toolchain/semantics/semantics_handle_loop_statement.cpp index 4d5295cd1081..84e84a9790be 100644 --- a/toolchain/semantics/semantics_handle_loop_statement.cpp +++ b/toolchain/semantics/semantics_handle_loop_statement.cpp @@ -5,61 +5,58 @@ #include "toolchain/semantics/semantics_context.h" #include "toolchain/semantics/semantics_node.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsHandleBreakStatement(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleBreakStatement(Context& context, ParseTree::Node parse_node) + -> bool { return context.TODO(parse_node, "HandleBreakStatement"); } -auto SemanticsHandleBreakStatementStart(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleBreakStatementStart(Context& context, ParseTree::Node parse_node) + -> bool { return context.TODO(parse_node, "HandleBreakStatementStart"); } -auto SemanticsHandleContinueStatement(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleContinueStatement(Context& context, ParseTree::Node parse_node) + -> bool { return context.TODO(parse_node, "HandleContinueStatement"); } -auto SemanticsHandleContinueStatementStart(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleContinueStatementStart(Context& context, ParseTree::Node parse_node) + -> bool { return context.TODO(parse_node, "HandleContinueStatementStart"); } -auto SemanticsHandleForHeader(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleForHeader(Context& context, ParseTree::Node parse_node) -> bool { return context.TODO(parse_node, "HandleForHeader"); } -auto SemanticsHandleForHeaderStart(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleForHeaderStart(Context& context, ParseTree::Node parse_node) + -> bool { return context.TODO(parse_node, "HandleForHeaderStart"); } -auto SemanticsHandleForIn(SemanticsContext& context, ParseTree::Node parse_node) - -> bool { +auto HandleForIn(Context& context, ParseTree::Node parse_node) -> bool { return context.TODO(parse_node, "HandleForIn"); } -auto SemanticsHandleForStatement(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleForStatement(Context& context, ParseTree::Node parse_node) -> bool { return context.TODO(parse_node, "HandleForStatement"); } -auto SemanticsHandleWhileCondition(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleWhileCondition(Context& context, ParseTree::Node parse_node) + -> bool { return context.TODO(parse_node, "HandleWhileCondition"); } -auto SemanticsHandleWhileConditionStart(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleWhileConditionStart(Context& context, ParseTree::Node parse_node) + -> bool { return context.TODO(parse_node, "HandleWhileConditionStart"); } -auto SemanticsHandleWhileStatement(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleWhileStatement(Context& context, ParseTree::Node parse_node) + -> bool { return context.TODO(parse_node, "HandleWhileStatement"); } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_handle_name.cpp b/toolchain/semantics/semantics_handle_name.cpp index 7c2f62792fc0..0d5cbb64e4bb 100644 --- a/toolchain/semantics/semantics_handle_name.cpp +++ b/toolchain/semantics/semantics_handle_name.cpp @@ -6,15 +6,15 @@ #include "toolchain/semantics/semantics_context.h" #include "toolchain/semantics/semantics_node.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsHandleMemberAccessExpression(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { - SemanticsStringId name_id = context.node_stack().Pop(); +auto HandleMemberAccessExpression(Context& context, ParseTree::Node parse_node) + -> bool { + SemIR::StringId name_id = context.node_stack().Pop(); auto base_id = context.node_stack().PopExpression(); auto base = context.semantics_ir().GetNode(base_id); - if (base.kind() == SemanticsNodeKind::Namespace) { + if (base.kind() == SemIR::NodeKind::Namespace) { // For a namespace, just resolve the name. auto node_id = context.LookupName(parse_node, name_id, base.GetAsNamespace(), @@ -27,7 +27,7 @@ auto SemanticsHandleMemberAccessExpression(SemanticsContext& context, context.semantics_ir().GetTypeAllowBuiltinTypes(base.type_id())); switch (base_type.kind()) { - case SemanticsNodeKind::StructType: { + case SemIR::NodeKind::StructType: { auto refs = context.semantics_ir().GetNodeBlock(base_type.GetAsStructType()); // TODO: Do we need to optimize this with a lookup table for O(1)? @@ -37,8 +37,8 @@ auto SemanticsHandleMemberAccessExpression(SemanticsContext& context, name_id == field_name_id) { context.AddNodeAndPush( parse_node, - SemanticsNode::StructAccess::Make( - parse_node, field_type_id, base_id, SemanticsMemberIndex(i))); + SemIR::Node::StructAccess::Make(parse_node, field_type_id, + base_id, SemIR::MemberIndex(i))); return true; } } @@ -52,7 +52,7 @@ auto SemanticsHandleMemberAccessExpression(SemanticsContext& context, break; } default: { - if (base.type_id() != SemanticsTypeId::Error) { + if (base.type_id() != SemIR::TypeId::Error) { CARBON_DIAGNOSTIC(QualifiedExpressionUnsupported, Error, "Type `{0}` does not support qualified expressions.", std::string); @@ -65,18 +65,16 @@ auto SemanticsHandleMemberAccessExpression(SemanticsContext& context, } // Should only be reached on error. - context.node_stack().Push(parse_node, SemanticsNodeId::BuiltinError); + context.node_stack().Push(parse_node, SemIR::NodeId::BuiltinError); return true; } -auto SemanticsHandlePointerMemberAccessExpression(SemanticsContext& context, - ParseTree::Node parse_node) - -> bool { +auto HandlePointerMemberAccessExpression(Context& context, + ParseTree::Node parse_node) -> bool { return context.TODO(parse_node, "HandlePointerMemberAccessExpression"); } -auto SemanticsHandleName(SemanticsContext& context, ParseTree::Node parse_node) - -> bool { +auto HandleName(Context& context, ParseTree::Node parse_node) -> bool { auto name_str = context.parse_tree().GetNodeText(parse_node); auto name_id = context.semantics_ir().AddString(name_str); // The parent is responsible for binding the name. @@ -84,19 +82,19 @@ auto SemanticsHandleName(SemanticsContext& context, ParseTree::Node parse_node) return true; } -auto SemanticsHandleNameExpression(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleNameExpression(Context& context, ParseTree::Node parse_node) + -> bool { auto name_str = context.parse_tree().GetNodeText(parse_node); auto name_id = context.semantics_ir().AddString(name_str); context.node_stack().Push( parse_node, - context.LookupName(parse_node, name_id, SemanticsNameScopeId::Invalid, + context.LookupName(parse_node, name_id, SemIR::NameScopeId::Invalid, /*print_diagnostics=*/true)); return true; } -auto SemanticsHandleQualifiedDeclaration(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleQualifiedDeclaration(Context& context, ParseTree::Node parse_node) + -> bool { auto pop_and_apply_first_child = [&]() { if (context.parse_tree().node_kind(context.node_stack().PeekParseNode()) != ParseNodeKind::QualifiedDeclaration) { @@ -115,12 +113,11 @@ auto SemanticsHandleQualifiedDeclaration(SemanticsContext& context, ParseTree::Node parse_node2 = context.node_stack().PeekParseNode(); if (context.parse_tree().node_kind(parse_node2) == ParseNodeKind::Name) { - SemanticsStringId name_id2 = - context.node_stack().Pop(); + SemIR::StringId name_id2 = context.node_stack().Pop(); pop_and_apply_first_child(); context.declaration_name_stack().ApplyNameQualifier(parse_node2, name_id2); } else { - SemanticsNodeId node_id2 = context.node_stack().PopExpression(); + SemIR::NodeId node_id2 = context.node_stack().PopExpression(); pop_and_apply_first_child(); context.declaration_name_stack().ApplyExpressionQualifier(parse_node2, node_id2); @@ -129,14 +126,13 @@ auto SemanticsHandleQualifiedDeclaration(SemanticsContext& context, return true; } -auto SemanticsHandleSelfTypeNameExpression(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleSelfTypeNameExpression(Context& context, ParseTree::Node parse_node) + -> bool { return context.TODO(parse_node, "HandleSelfTypeNameExpression"); } -auto SemanticsHandleSelfValueName(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleSelfValueName(Context& context, ParseTree::Node parse_node) -> bool { return context.TODO(parse_node, "HandleSelfValueName"); } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_handle_named_constraint.cpp b/toolchain/semantics/semantics_handle_named_constraint.cpp index 921c7cc0d445..bc4b5dbb0e74 100644 --- a/toolchain/semantics/semantics_handle_named_constraint.cpp +++ b/toolchain/semantics/semantics_handle_named_constraint.cpp @@ -5,30 +5,26 @@ #include "toolchain/semantics/semantics_context.h" #include "toolchain/semantics/semantics_node.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsHandleNamedConstraintDeclaration(SemanticsContext& context, - ParseTree::Node parse_node) - -> bool { +auto HandleNamedConstraintDeclaration(Context& context, + ParseTree::Node parse_node) -> bool { return context.TODO(parse_node, "HandleNamedConstraintDeclaration"); } -auto SemanticsHandleNamedConstraintDefinition(SemanticsContext& context, - ParseTree::Node parse_node) - -> bool { +auto HandleNamedConstraintDefinition(Context& context, + ParseTree::Node parse_node) -> bool { return context.TODO(parse_node, "HandleNamedConstraintDefinition"); } -auto SemanticsHandleNamedConstraintDefinitionStart(SemanticsContext& context, - ParseTree::Node parse_node) - -> bool { +auto HandleNamedConstraintDefinitionStart(Context& context, + ParseTree::Node parse_node) -> bool { return context.TODO(parse_node, "HandleNamedConstraintDefinitionStart"); } -auto SemanticsHandleNamedConstraintIntroducer(SemanticsContext& context, - ParseTree::Node parse_node) - -> bool { +auto HandleNamedConstraintIntroducer(Context& context, + ParseTree::Node parse_node) -> bool { return context.TODO(parse_node, "HandleNamedConstraintIntroducer"); } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_handle_namespace.cpp b/toolchain/semantics/semantics_handle_namespace.cpp index b18f784400d4..c9e8b65410d5 100644 --- a/toolchain/semantics/semantics_handle_namespace.cpp +++ b/toolchain/semantics/semantics_handle_namespace.cpp @@ -5,21 +5,20 @@ #include "toolchain/semantics/semantics_context.h" #include "toolchain/semantics/semantics_node.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsHandleNamespaceStart(SemanticsContext& context, - ParseTree::Node /*parse_node*/) -> bool { +auto HandleNamespaceStart(Context& context, ParseTree::Node /*parse_node*/) + -> bool { context.declaration_name_stack().Push(); return true; } -auto SemanticsHandleNamespace(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleNamespace(Context& context, ParseTree::Node parse_node) -> bool { auto name_context = context.declaration_name_stack().Pop(); - auto namespace_id = context.AddNode(SemanticsNode::Namespace::Make( + auto namespace_id = context.AddNode(SemIR::Node::Namespace::Make( parse_node, context.semantics_ir().AddNameScope())); context.declaration_name_stack().AddNameToLookup(name_context, namespace_id); return true; } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_handle_noop.cpp b/toolchain/semantics/semantics_handle_noop.cpp index 82ac13314a2c..03794f40fce4 100644 --- a/toolchain/semantics/semantics_handle_noop.cpp +++ b/toolchain/semantics/semantics_handle_noop.cpp @@ -4,23 +4,22 @@ #include "toolchain/semantics/semantics_context.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsHandleEmptyDeclaration(SemanticsContext& /*context*/, - ParseTree::Node /*parse_node*/) -> bool { +auto HandleEmptyDeclaration(Context& /*context*/, + ParseTree::Node /*parse_node*/) -> bool { // Empty declarations have no actions associated. return true; } -auto SemanticsHandleFileEnd(SemanticsContext& /*context*/, - ParseTree::Node /*parse_node*/) -> bool { +auto HandleFileEnd(Context& /*context*/, ParseTree::Node /*parse_node*/) + -> bool { // Do nothing, no need to balance this node. return true; } -auto SemanticsHandleInvalidParse(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleInvalidParse(Context& context, ParseTree::Node parse_node) -> bool { return context.TODO(parse_node, "HandleInvalidParse"); } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_handle_operator.cpp b/toolchain/semantics/semantics_handle_operator.cpp index 33f42fa6c776..f936be894675 100644 --- a/toolchain/semantics/semantics_handle_operator.cpp +++ b/toolchain/semantics/semantics_handle_operator.cpp @@ -4,10 +4,9 @@ #include "toolchain/semantics/semantics_context.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsHandleInfixOperator(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleInfixOperator(Context& context, ParseTree::Node parse_node) -> bool { auto rhs_id = context.node_stack().PopExpression(); auto [lhs_node, lhs_id] = context.node_stack().PopExpressionWithParseNode(); @@ -22,7 +21,7 @@ auto SemanticsHandleInfixOperator(SemanticsContext& context, context.AddNodeAndPush( parse_node, - SemanticsNode::BinaryOperatorAdd::Make( + SemIR::Node::BinaryOperatorAdd::Make( parse_node, context.semantics_ir().GetNode(lhs_id).type_id(), lhs_id, rhs_id)); return true; @@ -39,22 +38,22 @@ auto SemanticsHandleInfixOperator(SemanticsContext& context, auto rhs_block_id = context.node_block_stack().PopForAdd(); auto resume_block_id = context.node_block_stack().PeekForAdd(); context.AddNodeToBlock(rhs_block_id, - SemanticsNode::BranchWithArg::Make( + SemIR::Node::BranchWithArg::Make( parse_node, resume_block_id, rhs_id)); context.AddCurrentCodeBlockToFunction(); // Collect the result from either the first or second operand. context.AddNodeAndPush( parse_node, - SemanticsNode::BlockArg::Make( + SemIR::Node::BlockArg::Make( parse_node, context.semantics_ir().GetNode(rhs_id).type_id(), resume_block_id)); return true; } case TokenKind::Equal: { // TODO: handle complex assignment expression such as `a += 1`. - if (GetSemanticsExpressionCategory(context.semantics_ir(), lhs_id) != - SemanticsExpressionCategory::DurableReference) { + if (SemIR::GetExpressionCategory(context.semantics_ir(), lhs_id) != + SemIR::ExpressionCategory::DurableReference) { CARBON_DIAGNOSTIC(AssignmentToNonAssignable, Error, "Expression is not assignable."); context.emitter().Emit(lhs_node, AssignmentToNonAssignable); @@ -62,7 +61,7 @@ auto SemanticsHandleInfixOperator(SemanticsContext& context, context.ImplicitAsRequired( parse_node, rhs_id, context.semantics_ir().GetNode(lhs_id).type_id()); context.AddNodeAndPush( - parse_node, SemanticsNode::Assign::Make(parse_node, lhs_id, rhs_id)); + parse_node, SemIR::Node::Assign::Make(parse_node, lhs_id, rhs_id)); return true; } default: @@ -70,8 +69,8 @@ auto SemanticsHandleInfixOperator(SemanticsContext& context, } } -auto SemanticsHandlePostfixOperator(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandlePostfixOperator(Context& context, ParseTree::Node parse_node) + -> bool { auto value_id = context.node_stack().PopExpression(); // Figure out the operator for the token. @@ -80,9 +79,8 @@ auto SemanticsHandlePostfixOperator(SemanticsContext& context, case TokenKind::Star: { auto inner_type_id = context.ExpressionAsType(parse_node, value_id); context.AddNodeAndPush( - parse_node, - SemanticsNode::PointerType::Make( - parse_node, SemanticsTypeId::TypeType, inner_type_id)); + parse_node, SemIR::Node::PointerType::Make( + parse_node, SemIR::TypeId::TypeType, inner_type_id)); return true; } @@ -91,8 +89,8 @@ auto SemanticsHandlePostfixOperator(SemanticsContext& context, } } -auto SemanticsHandlePrefixOperator(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandlePrefixOperator(Context& context, ParseTree::Node parse_node) + -> bool { auto value_id = context.node_stack().PopExpression(); // Figure out the operator for the token. @@ -100,11 +98,10 @@ auto SemanticsHandlePrefixOperator(SemanticsContext& context, switch (auto token_kind = context.tokens().GetKind(token)) { case TokenKind::Amp: { // Only durable reference expressions can have their address taken. - switch ( - GetSemanticsExpressionCategory(context.semantics_ir(), value_id)) { - case SemanticsExpressionCategory::DurableReference: + switch (SemIR::GetExpressionCategory(context.semantics_ir(), value_id)) { + case SemIR::ExpressionCategory::DurableReference: break; - case SemanticsExpressionCategory::EphemeralReference: + case SemIR::ExpressionCategory::EphemeralReference: CARBON_DIAGNOSTIC(AddressOfEphemeralReference, Error, "Cannot take the address of a temporary object."); context.emitter().Emit(parse_node, AddressOfEphemeralReference); @@ -118,7 +115,7 @@ auto SemanticsHandlePrefixOperator(SemanticsContext& context, } context.AddNodeAndPush( parse_node, - SemanticsNode::AddressOf::Make( + SemIR::Node::AddressOf::Make( parse_node, context.GetPointerType( parse_node, @@ -132,7 +129,7 @@ auto SemanticsHandlePrefixOperator(SemanticsContext& context, // TODO: Detect `const (const T)*` and suggest moving the `*` inside the // parentheses. if (context.semantics_ir().GetNode(value_id).kind() == - SemanticsNodeKind::ConstType) { + SemIR::NodeKind::ConstType) { CARBON_DIAGNOSTIC(RepeatedConst, Warning, "`const` applied repeatedly to the same type has no " "additional effect."); @@ -140,9 +137,8 @@ auto SemanticsHandlePrefixOperator(SemanticsContext& context, } auto inner_type_id = context.ExpressionAsType(parse_node, value_id); context.AddNodeAndPush( - parse_node, - SemanticsNode::ConstType::Make(parse_node, SemanticsTypeId::TypeType, - inner_type_id)); + parse_node, SemIR::Node::ConstType::Make( + parse_node, SemIR::TypeId::TypeType, inner_type_id)); return true; } @@ -150,7 +146,7 @@ auto SemanticsHandlePrefixOperator(SemanticsContext& context, value_id = context.ImplicitAsBool(parse_node, value_id); context.AddNodeAndPush( parse_node, - SemanticsNode::UnaryOperatorNot::Make( + SemIR::Node::UnaryOperatorNot::Make( parse_node, context.semantics_ir().GetNode(value_id).type_id(), value_id)); return true; @@ -160,8 +156,8 @@ auto SemanticsHandlePrefixOperator(SemanticsContext& context, context.semantics_ir().GetNode(value_id).type_id()); auto type_node = context.semantics_ir().GetNode( context.semantics_ir().GetTypeAllowBuiltinTypes(type_id)); - auto result_type_id = SemanticsTypeId::Error; - if (type_node.kind() == SemanticsNodeKind::PointerType) { + auto result_type_id = SemIR::TypeId::Error; + if (type_node.kind() == SemIR::NodeKind::PointerType) { result_type_id = type_node.GetAsPointerType(); } else { CARBON_DIAGNOSTIC( @@ -172,7 +168,7 @@ auto SemanticsHandlePrefixOperator(SemanticsContext& context, parse_node, DereferenceOfNonPointer, context.semantics_ir().StringifyType(type_id)); // TODO: Check for any facet here, rather than only a type. - if (type_id == SemanticsTypeId::TypeType) { + if (type_id == SemIR::TypeId::TypeType) { CARBON_DIAGNOSTIC( DereferenceOfType, Note, "To form a pointer type, write the `*` after the pointee type."); @@ -180,9 +176,9 @@ auto SemanticsHandlePrefixOperator(SemanticsContext& context, } builder.Emit(); } - context.AddNodeAndPush(parse_node, - SemanticsNode::Dereference::Make( - parse_node, result_type_id, value_id)); + context.AddNodeAndPush( + parse_node, + SemIR::Node::Dereference::Make(parse_node, result_type_id, value_id)); return true; } @@ -191,8 +187,8 @@ auto SemanticsHandlePrefixOperator(SemanticsContext& context, } } -auto SemanticsHandleShortCircuitOperand(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleShortCircuitOperand(Context& context, ParseTree::Node parse_node) + -> bool { // Convert the condition to `bool`. auto cond_value_id = context.node_stack().PopExpression(); cond_value_id = context.ImplicitAsBool(parse_node, cond_value_id); @@ -200,22 +196,20 @@ auto SemanticsHandleShortCircuitOperand(SemanticsContext& context, // Compute the branch value: the condition for `and`, inverted for `or`. auto token = context.parse_tree().node_token(parse_node); - SemanticsNodeId branch_value_id = SemanticsNodeId::Invalid; - auto short_circuit_result_id = SemanticsNodeId::Invalid; + SemIR::NodeId branch_value_id = SemIR::NodeId::Invalid; + auto short_circuit_result_id = SemIR::NodeId::Invalid; switch (auto token_kind = context.tokens().GetKind(token)) { case TokenKind::And: branch_value_id = cond_value_id; - short_circuit_result_id = - context.AddNode(SemanticsNode::BoolLiteral::Make( - parse_node, bool_type_id, SemanticsBoolValue::False)); + short_circuit_result_id = context.AddNode(SemIR::Node::BoolLiteral::Make( + parse_node, bool_type_id, SemIR::BoolValue::False)); break; case TokenKind::Or: - branch_value_id = context.AddNode(SemanticsNode::UnaryOperatorNot::Make( + branch_value_id = context.AddNode(SemIR::Node::UnaryOperatorNot::Make( parse_node, bool_type_id, cond_value_id)); - short_circuit_result_id = - context.AddNode(SemanticsNode::BoolLiteral::Make( - parse_node, bool_type_id, SemanticsBoolValue::True)); + short_circuit_result_id = context.AddNode(SemIR::Node::BoolLiteral::Make( + parse_node, bool_type_id, SemIR::BoolValue::True)); break; default: @@ -235,9 +229,9 @@ auto SemanticsHandleShortCircuitOperand(SemanticsContext& context, context.node_block_stack().Push(rhs_block_id); context.AddCurrentCodeBlockToFunction(); - // Put the condition back on the stack for SemanticsHandleInfixOperator. + // Put the condition back on the stack for HandleInfixOperator. context.node_stack().Push(parse_node, cond_value_id); return true; } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_handle_package.cpp b/toolchain/semantics/semantics_handle_package.cpp index 285d92565802..7b678a9c33ca 100644 --- a/toolchain/semantics/semantics_handle_package.cpp +++ b/toolchain/semantics/semantics_handle_package.cpp @@ -4,31 +4,29 @@ #include "toolchain/semantics/semantics_context.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsHandlePackageApi(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandlePackageApi(Context& context, ParseTree::Node parse_node) -> bool { return context.TODO(parse_node, "HandlePackageApi"); } -auto SemanticsHandlePackageDirective(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandlePackageDirective(Context& context, ParseTree::Node parse_node) + -> bool { return context.TODO(parse_node, "HandlePackageDirective"); } -auto SemanticsHandlePackageImpl(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandlePackageImpl(Context& context, ParseTree::Node parse_node) -> bool { return context.TODO(parse_node, "HandlePackageImpl"); } -auto SemanticsHandlePackageIntroducer(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandlePackageIntroducer(Context& context, ParseTree::Node parse_node) + -> bool { return context.TODO(parse_node, "HandlePackageIntroducer"); } -auto SemanticsHandlePackageLibrary(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandlePackageLibrary(Context& context, ParseTree::Node parse_node) + -> bool { return context.TODO(parse_node, "HandlePackageLibrary"); } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_handle_parameter_list.cpp b/toolchain/semantics/semantics_handle_parameter_list.cpp index b97b7ff82697..9141188a6488 100644 --- a/toolchain/semantics/semantics_handle_parameter_list.cpp +++ b/toolchain/semantics/semantics_handle_parameter_list.cpp @@ -4,21 +4,19 @@ #include "toolchain/semantics/semantics_context.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsHandleDeducedParameterList(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleDeducedParameterList(Context& context, ParseTree::Node parse_node) + -> bool { return context.TODO(parse_node, "HandleDeducedParameterList"); } -auto SemanticsHandleDeducedParameterListStart(SemanticsContext& context, - ParseTree::Node parse_node) - -> bool { +auto HandleDeducedParameterListStart(Context& context, + ParseTree::Node parse_node) -> bool { return context.TODO(parse_node, "HandleDeducedParameterListStart"); } -auto SemanticsHandleParameterList(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleParameterList(Context& context, ParseTree::Node parse_node) -> bool { auto refs_id = context.ParamOrArgEnd( /*for_args=*/false, ParseNodeKind::ParameterListStart); // TODO: This contains the IR block for parameters. At present, it's just @@ -36,14 +34,14 @@ auto SemanticsHandleParameterList(SemanticsContext& context, return true; } -auto SemanticsHandleParameterListComma(SemanticsContext& context, - ParseTree::Node /*parse_node*/) -> bool { +auto HandleParameterListComma(Context& context, ParseTree::Node /*parse_node*/) + -> bool { context.ParamOrArgComma(/*for_args=*/false); return true; } -auto SemanticsHandleParameterListStart(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleParameterListStart(Context& context, ParseTree::Node parse_node) + -> bool { context.PushScope(); context.node_stack().Push(parse_node); context.node_block_stack().Push(); @@ -51,4 +49,4 @@ auto SemanticsHandleParameterListStart(SemanticsContext& context, return true; } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_handle_paren.cpp b/toolchain/semantics/semantics_handle_paren.cpp index 6cec1fc0108a..12644d3caafb 100644 --- a/toolchain/semantics/semantics_handle_paren.cpp +++ b/toolchain/semantics/semantics_handle_paren.cpp @@ -6,10 +6,10 @@ #include "toolchain/semantics/semantics_context.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsHandleParenExpression(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleParenExpression(Context& context, ParseTree::Node parse_node) + -> bool { auto value_id = context.node_stack().PopExpression(); // ParamOrArgStart was called for tuple handling; clean up the ParamOrArg // support for non-tuple cases. @@ -22,21 +22,21 @@ auto SemanticsHandleParenExpression(SemanticsContext& context, return true; } -auto SemanticsHandleParenExpressionOrTupleLiteralStart( - SemanticsContext& context, ParseTree::Node parse_node) -> bool { +auto HandleParenExpressionOrTupleLiteralStart(Context& context, + ParseTree::Node parse_node) + -> bool { context.node_stack().Push(parse_node); context.ParamOrArgStart(); return true; } -auto SemanticsHandleTupleLiteralComma(SemanticsContext& context, - ParseTree::Node /*parse_node*/) -> bool { +auto HandleTupleLiteralComma(Context& context, ParseTree::Node /*parse_node*/) + -> bool { context.ParamOrArgComma(/*for_args=*/true); return true; } -auto SemanticsHandleTupleLiteral(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleTupleLiteral(Context& context, ParseTree::Node parse_node) -> bool { auto refs_id = context.ParamOrArgEnd( /*for_args=*/true, ParseNodeKind::ParenExpressionOrTupleLiteralStart); @@ -44,7 +44,7 @@ auto SemanticsHandleTupleLiteral(SemanticsContext& context, .PopAndDiscardSoloParseNode< ParseNodeKind::ParenExpressionOrTupleLiteralStart>(); const auto& node_block = context.semantics_ir().GetNodeBlock(refs_id); - llvm::SmallVector type_ids; + llvm::SmallVector type_ids; type_ids.reserve(node_block.size()); for (auto node : node_block) { type_ids.push_back(context.semantics_ir().GetNode(node).type_id()); @@ -52,9 +52,9 @@ auto SemanticsHandleTupleLiteral(SemanticsContext& context, auto type_id = context.CanonicalizeTupleType(parse_node, std::move(type_ids)); auto value_id = context.AddNode( - SemanticsNode::TupleValue::Make(parse_node, type_id, refs_id)); + SemIR::Node::TupleValue::Make(parse_node, type_id, refs_id)); context.node_stack().Push(parse_node, value_id); return true; } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_handle_pattern_binding.cpp b/toolchain/semantics/semantics_handle_pattern_binding.cpp index 0b66332ca1a0..8b693b9c8d3e 100644 --- a/toolchain/semantics/semantics_handle_pattern_binding.cpp +++ b/toolchain/semantics/semantics_handle_pattern_binding.cpp @@ -5,20 +5,19 @@ #include "toolchain/semantics/semantics_context.h" #include "toolchain/semantics/semantics_node.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsHandleAddress(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleAddress(Context& context, ParseTree::Node parse_node) -> bool { return context.TODO(parse_node, "HandleAddress"); } -auto SemanticsHandleGenericPatternBinding(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleGenericPatternBinding(Context& context, ParseTree::Node parse_node) + -> bool { return context.TODO(parse_node, "GenericPatternBinding"); } -auto SemanticsHandlePatternBinding(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandlePatternBinding(Context& context, ParseTree::Node parse_node) + -> bool { auto [type_node, parsed_type_id] = context.node_stack().PopExpressionWithParseNode(); auto cast_type_id = context.ExpressionAsType(type_node, parsed_type_id); @@ -32,11 +31,11 @@ auto SemanticsHandlePatternBinding(SemanticsContext& context, switch (auto context_parse_node_kind = context.parse_tree().node_kind( context.node_stack().PeekParseNode())) { case ParseNodeKind::VariableIntroducer: - context.AddNodeAndPush(parse_node, SemanticsNode::VarStorage::Make( + context.AddNodeAndPush(parse_node, SemIR::Node::VarStorage::Make( name_node, cast_type_id, name_id)); break; case ParseNodeKind::ParameterListStart: - context.AddNodeAndPush(parse_node, SemanticsNode::Parameter::Make( + context.AddNodeAndPush(parse_node, SemIR::Node::Parameter::Make( name_node, cast_type_id, name_id)); break; default: @@ -46,9 +45,8 @@ auto SemanticsHandlePatternBinding(SemanticsContext& context, return true; } -auto SemanticsHandleTemplate(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleTemplate(Context& context, ParseTree::Node parse_node) -> bool { return context.TODO(parse_node, "HandleTemplate"); } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_handle_statement.cpp b/toolchain/semantics/semantics_handle_statement.cpp index a8e9dc87f3e1..64182e122230 100644 --- a/toolchain/semantics/semantics_handle_statement.cpp +++ b/toolchain/semantics/semantics_handle_statement.cpp @@ -5,10 +5,9 @@ #include "toolchain/semantics/semantics_context.h" #include "toolchain/semantics/semantics_node.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsHandleExpressionStatement(SemanticsContext& context, - ParseTree::Node /*parse_node*/) +auto HandleExpressionStatement(Context& context, ParseTree::Node /*parse_node*/) -> bool { // Pop the expression without investigating its contents. // TODO: This will probably eventually need to do some "do not discard" @@ -17,8 +16,8 @@ auto SemanticsHandleExpressionStatement(SemanticsContext& context, return true; } -auto SemanticsHandleReturnStatement(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleReturnStatement(Context& context, ParseTree::Node parse_node) + -> bool { CARBON_CHECK(!context.return_scope_stack().empty()); const auto& fn_node = context.semantics_ir().GetNode(context.return_scope_stack().back()); @@ -40,7 +39,7 @@ auto SemanticsHandleReturnStatement(SemanticsContext& context, .Emit(); } - context.AddNode(SemanticsNode::Return::Make(parse_node)); + context.AddNode(SemIR::Node::Return::Make(parse_node)); } else { auto arg = context.node_stack().PopExpression(); context.node_stack() @@ -61,7 +60,7 @@ auto SemanticsHandleReturnStatement(SemanticsContext& context, context.ImplicitAsRequired(parse_node, arg, callable.return_type_id); } - context.AddNode(SemanticsNode::ReturnExpression::Make(parse_node, arg)); + context.AddNode(SemIR::Node::ReturnExpression::Make(parse_node, arg)); } // Switch to a new, unreachable, empty node block. This typically won't @@ -72,11 +71,11 @@ auto SemanticsHandleReturnStatement(SemanticsContext& context, return true; } -auto SemanticsHandleReturnStatementStart(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleReturnStatementStart(Context& context, ParseTree::Node parse_node) + -> bool { // No action, just a bracketing node. context.node_stack().Push(parse_node); return true; } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_handle_struct.cpp b/toolchain/semantics/semantics_handle_struct.cpp index 68741f030f50..e8e9b0d80bc0 100644 --- a/toolchain/semantics/semantics_handle_struct.cpp +++ b/toolchain/semantics/semantics_handle_struct.cpp @@ -4,10 +4,10 @@ #include "toolchain/semantics/semantics_context.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsHandleStructComma(SemanticsContext& context, - ParseTree::Node /*parse_node*/) -> bool { +auto HandleStructComma(Context& context, ParseTree::Node /*parse_node*/) + -> bool { context.ParamOrArgComma( /*for_args=*/context.parse_tree().node_kind( context.node_stack().PeekParseNode()) != @@ -15,9 +15,8 @@ auto SemanticsHandleStructComma(SemanticsContext& context, return true; } -auto SemanticsHandleStructFieldDesignator(SemanticsContext& context, - ParseTree::Node /*parse_node*/) - -> bool { +auto HandleStructFieldDesignator(Context& context, + ParseTree::Node /*parse_node*/) -> bool { // This leaves the designated name on top because the `.` isn't interesting. CARBON_CHECK( context.parse_tree().node_kind(context.node_stack().PeekParseNode()) == @@ -25,35 +24,35 @@ auto SemanticsHandleStructFieldDesignator(SemanticsContext& context, return true; } -auto SemanticsHandleStructFieldType(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleStructFieldType(Context& context, ParseTree::Node parse_node) + -> bool { auto [type_node, type_id] = context.node_stack().PopExpressionWithParseNode(); - SemanticsTypeId cast_type_id = context.ExpressionAsType(type_node, type_id); + SemIR::TypeId cast_type_id = context.ExpressionAsType(type_node, type_id); auto [name_node, name_id] = context.node_stack().PopWithParseNode(); - context.AddNodeAndPush(parse_node, SemanticsNode::StructTypeField::Make( + context.AddNodeAndPush(parse_node, SemIR::Node::StructTypeField::Make( name_node, name_id, cast_type_id)); return true; } -auto SemanticsHandleStructFieldUnknown(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleStructFieldUnknown(Context& context, ParseTree::Node parse_node) + -> bool { return context.TODO(parse_node, "HandleStructFieldUnknown"); } -auto SemanticsHandleStructFieldValue(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleStructFieldValue(Context& context, ParseTree::Node parse_node) + -> bool { auto [value_parse_node, value_node_id] = context.node_stack().PopExpressionWithParseNode(); - SemanticsStringId name_id = context.node_stack().Pop(); + SemIR::StringId name_id = context.node_stack().Pop(); // Store the name for the type. auto type_block_id = context.args_type_info_stack().PeekForAdd(); context.semantics_ir().AddNode( type_block_id, - SemanticsNode::StructTypeField::Make( + SemIR::Node::StructTypeField::Make( parse_node, name_id, context.semantics_ir().GetNode(value_node_id).type_id())); @@ -62,8 +61,7 @@ auto SemanticsHandleStructFieldValue(SemanticsContext& context, return true; } -auto SemanticsHandleStructLiteral(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleStructLiteral(Context& context, ParseTree::Node parse_node) -> bool { auto refs_id = context.ParamOrArgEnd( /*for_args=*/true, ParseNodeKind::StructLiteralOrStructTypeLiteralStart); @@ -76,13 +74,14 @@ auto SemanticsHandleStructLiteral(SemanticsContext& context, auto type_id = context.CanonicalizeStructType(parse_node, type_block_id); auto value_id = context.AddNode( - SemanticsNode::StructValue::Make(parse_node, type_id, refs_id)); + SemIR::Node::StructValue::Make(parse_node, type_id, refs_id)); context.node_stack().Push(parse_node, value_id); return true; } -auto SemanticsHandleStructLiteralOrStructTypeLiteralStart( - SemanticsContext& context, ParseTree::Node parse_node) -> bool { +auto HandleStructLiteralOrStructTypeLiteralStart(Context& context, + ParseTree::Node parse_node) + -> bool { context.PushScope(); context.node_stack().Push(parse_node); // At this point we aren't sure whether this will be a value or type literal, @@ -93,8 +92,8 @@ auto SemanticsHandleStructLiteralOrStructTypeLiteralStart( return true; } -auto SemanticsHandleStructTypeLiteral(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleStructTypeLiteral(Context& context, ParseTree::Node parse_node) + -> bool { auto refs_id = context.ParamOrArgEnd( /*for_args=*/false, ParseNodeKind::StructLiteralOrStructTypeLiteralStart); @@ -105,13 +104,13 @@ auto SemanticsHandleStructTypeLiteral(SemanticsContext& context, // This is only used for value literals. context.args_type_info_stack().Pop(); - CARBON_CHECK(refs_id != SemanticsNodeBlockId::Empty) + CARBON_CHECK(refs_id != SemIR::NodeBlockId::Empty) << "{} is handled by StructLiteral."; context.AddNodeAndPush(parse_node, - SemanticsNode::StructType::Make( - parse_node, SemanticsTypeId::TypeType, refs_id)); + SemIR::Node::StructType::Make( + parse_node, SemIR::TypeId::TypeType, refs_id)); return true; } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_handle_variable.cpp b/toolchain/semantics/semantics_handle_variable.cpp index d530a4fee064..a3144d9ae1b4 100644 --- a/toolchain/semantics/semantics_handle_variable.cpp +++ b/toolchain/semantics/semantics_handle_variable.cpp @@ -5,12 +5,12 @@ #include "toolchain/semantics/semantics_context.h" #include "toolchain/semantics/semantics_node.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsHandleVariableDeclaration(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleVariableDeclaration(Context& context, ParseTree::Node parse_node) + -> bool { // Handle the optional initializer. - auto expr_node_id = SemanticsNodeId::Invalid; + auto expr_node_id = SemIR::NodeId::Invalid; bool has_init = context.parse_tree().node_kind(context.node_stack().PeekParseNode()) != ParseNodeKind::PatternBinding; @@ -21,7 +21,7 @@ auto SemanticsHandleVariableDeclaration(SemanticsContext& context, } // Get the storage and add it to name lookup. - SemanticsNodeId var_id = + SemIR::NodeId var_id = context.node_stack().Pop(); auto var = context.semantics_ir().GetNode(var_id); auto name_id = var.GetAsVarStorage(); @@ -31,7 +31,7 @@ auto SemanticsHandleVariableDeclaration(SemanticsContext& context, auto cast_value_id = context.ImplicitAsRequired(parse_node, expr_node_id, var.type_id()); context.AddNode( - SemanticsNode::Assign::Make(parse_node, var_id, cast_value_id)); + SemIR::Node::Assign::Make(parse_node, var_id, cast_value_id)); } context.node_stack() @@ -40,18 +40,18 @@ auto SemanticsHandleVariableDeclaration(SemanticsContext& context, return true; } -auto SemanticsHandleVariableIntroducer(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleVariableIntroducer(Context& context, ParseTree::Node parse_node) + -> bool { // No action, just a bracketing node. context.node_stack().Push(parse_node); return true; } -auto SemanticsHandleVariableInitializer(SemanticsContext& context, - ParseTree::Node parse_node) -> bool { +auto HandleVariableInitializer(Context& context, ParseTree::Node parse_node) + -> bool { // No action, just a bracketing node. context.node_stack().Push(parse_node); return true; } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_ir.cpp b/toolchain/semantics/semantics_ir.cpp index 1668d9d57d8e..33a3d12dc0b7 100644 --- a/toolchain/semantics/semantics_ir.cpp +++ b/toolchain/semantics/semantics_ir.cpp @@ -14,57 +14,55 @@ #include "toolchain/semantics/semantics_node.h" #include "toolchain/semantics/semantics_node_kind.h" -namespace Carbon { +namespace Carbon::SemIR { -auto SemanticsIR::MakeBuiltinIR() -> SemanticsIR { - SemanticsIR semantics_ir(/*builtin_ir=*/nullptr); - semantics_ir.nodes_.reserve(SemanticsBuiltinKind::ValidCount); +auto File::MakeBuiltinIR() -> File { + File semantics_ir(/*builtin_ir=*/nullptr); + semantics_ir.nodes_.reserve(BuiltinKind::ValidCount); // Error uses a self-referential type so that it's not accidentally treated as // a normal type. Every other builtin is a type, including the // self-referential TypeType. -#define CARBON_SEMANTICS_BUILTIN_KIND(Name, ...) \ - semantics_ir.nodes_.push_back(SemanticsNode::Builtin::Make( \ - SemanticsBuiltinKind::Name, \ - SemanticsBuiltinKind::Name == SemanticsBuiltinKind::Error \ - ? SemanticsTypeId::Error \ - : SemanticsTypeId::TypeType)); +#define CARBON_SEMANTICS_BUILTIN_KIND(Name, ...) \ + semantics_ir.nodes_.push_back(Node::Builtin::Make( \ + BuiltinKind::Name, BuiltinKind::Name == BuiltinKind::Error \ + ? TypeId::Error \ + : TypeId::TypeType)); #include "toolchain/semantics/semantics_builtin_kind.def" CARBON_CHECK(semantics_ir.node_blocks_.size() == 1) << "BuildBuiltins should only have the empty block, actual: " << semantics_ir.node_blocks_.size(); - CARBON_CHECK(semantics_ir.nodes_.size() == SemanticsBuiltinKind::ValidCount) - << "BuildBuiltins should produce " << SemanticsBuiltinKind::ValidCount + CARBON_CHECK(semantics_ir.nodes_.size() == BuiltinKind::ValidCount) + << "BuildBuiltins should produce " << BuiltinKind::ValidCount << " nodes, actual: " << semantics_ir.nodes_.size(); return semantics_ir; } -auto SemanticsIR::MakeFromParseTree(const SemanticsIR& builtin_ir, - const TokenizedBuffer& tokens, - const ParseTree& parse_tree, - DiagnosticConsumer& consumer, - llvm::raw_ostream* vlog_stream) - -> SemanticsIR { - SemanticsIR semantics_ir(&builtin_ir); +auto File::MakeFromParseTree(const File& builtin_ir, + const TokenizedBuffer& tokens, + const ParseTree& parse_tree, + DiagnosticConsumer& consumer, + llvm::raw_ostream* vlog_stream) -> File { + File semantics_ir(&builtin_ir); // Copy builtins over. - semantics_ir.nodes_.resize_for_overwrite(SemanticsBuiltinKind::ValidCount); - static constexpr auto BuiltinIR = SemanticsCrossReferenceIRId(0); - for (int i : llvm::seq(SemanticsBuiltinKind::ValidCount)) { + semantics_ir.nodes_.resize_for_overwrite(BuiltinKind::ValidCount); + static constexpr auto BuiltinIR = CrossReferenceIRId(0); + for (int i : llvm::seq(BuiltinKind::ValidCount)) { // We can reuse the type node ID because the offsets of cross-references // will be the same in this IR. auto type = builtin_ir.nodes_[i].type_id(); - semantics_ir.nodes_[i] = SemanticsNode::CrossReference::Make( - type, BuiltinIR, SemanticsNodeId(i)); + semantics_ir.nodes_[i] = + Node::CrossReference::Make(type, BuiltinIR, NodeId(i)); } ParseTreeNodeLocationTranslator translator(&tokens, &parse_tree); ErrorTrackingDiagnosticConsumer err_tracker(consumer); DiagnosticEmitter emitter(translator, err_tracker); - SemanticsContext context(tokens, emitter, parse_tree, semantics_ir, - vlog_stream); + Check::Context context(tokens, emitter, parse_tree, semantics_ir, + vlog_stream); PrettyStackTraceFunction context_dumper( [&](llvm::raw_ostream& output) { context.PrintForStackDump(output); }); @@ -76,13 +74,13 @@ auto SemanticsIR::MakeFromParseTree(const SemanticsIR& builtin_ir, // for example if an unrecoverable state is encountered. for (auto parse_node : parse_tree.postorder()) { switch (auto parse_kind = parse_tree.node_kind(parse_node)) { -#define CARBON_PARSE_NODE_KIND(Name) \ - case ParseNodeKind::Name: { \ - if (!SemanticsHandle##Name(context, parse_node)) { \ - semantics_ir.has_errors_ = true; \ - return semantics_ir; \ - } \ - break; \ +#define CARBON_PARSE_NODE_KIND(Name) \ + case ParseNodeKind::Name: { \ + if (!Check::Handle##Name(context, parse_node)) { \ + semantics_ir.has_errors_ = true; \ + return semantics_ir; \ + } \ + break; \ } #include "toolchain/parser/parse_node_kind.def" } @@ -106,7 +104,7 @@ auto SemanticsIR::MakeFromParseTree(const SemanticsIR& builtin_ir, return semantics_ir; } -auto SemanticsIR::Verify() const -> ErrorOr { +auto File::Verify() const -> ErrorOr { // Invariants don't necessarily hold for invalid IR. if (has_errors_) { return Success(); @@ -114,14 +112,12 @@ auto SemanticsIR::Verify() const -> ErrorOr { // Check that every code block has a terminator sequence that appears at the // end of the block. - for (const SemanticsFunction& function : functions_) { - for (SemanticsNodeBlockId block_id : function.body_block_ids) { - SemanticsTerminatorKind prior_kind = - SemanticsTerminatorKind::NotTerminator; - for (SemanticsNodeId node_id : GetNodeBlock(block_id)) { - SemanticsTerminatorKind node_kind = - GetNode(node_id).kind().terminator_kind(); - if (prior_kind == SemanticsTerminatorKind::Terminator) { + for (const Function& function : functions_) { + for (NodeBlockId block_id : function.body_block_ids) { + TerminatorKind prior_kind = TerminatorKind::NotTerminator; + for (NodeId node_id : GetNodeBlock(block_id)) { + TerminatorKind node_kind = GetNode(node_id).kind().terminator_kind(); + if (prior_kind == TerminatorKind::Terminator) { return Error(llvm::formatv("Node {0} in block {1} follows terminator", node_id, block_id)); } @@ -133,7 +129,7 @@ auto SemanticsIR::Verify() const -> ErrorOr { } prior_kind = node_kind; } - if (prior_kind != SemanticsTerminatorKind::Terminator) { + if (prior_kind != TerminatorKind::Terminator) { return Error(llvm::formatv("No terminator in block {0}", block_id)); } } @@ -175,8 +171,7 @@ static auto PrintBlock(llvm::raw_ostream& out, llvm::StringLiteral block_name, out << "]\n"; } -auto SemanticsIR::Print(llvm::raw_ostream& out, bool include_builtins) const - -> void { +auto File::Print(llvm::raw_ostream& out, bool include_builtins) const -> void { out << "cross_reference_irs_size: " << cross_reference_irs_.size() << "\n"; PrintList(out, "functions", functions_); @@ -188,7 +183,7 @@ auto SemanticsIR::Print(llvm::raw_ostream& out, bool include_builtins) const PrintBlock(out, "type_blocks", type_blocks_); out << "nodes: [\n"; - for (int i = include_builtins ? 0 : SemanticsBuiltinKind::ValidCount; + for (int i = include_builtins ? 0 : BuiltinKind::ValidCount; i < static_cast(nodes_.size()); ++i) { const auto& element = nodes_[i]; out.indent(Indent); @@ -202,65 +197,65 @@ auto SemanticsIR::Print(llvm::raw_ostream& out, bool include_builtins) const // Map a node kind representing a type into an integer describing the // precedence of that type's syntax. Higher numbers correspond to higher // precedence. -static auto GetTypePrecedence(SemanticsNodeKind kind) -> int { +static auto GetTypePrecedence(NodeKind kind) -> int { switch (kind) { - case SemanticsNodeKind::ArrayType: - case SemanticsNodeKind::Builtin: - case SemanticsNodeKind::StructType: - case SemanticsNodeKind::TupleType: + case NodeKind::ArrayType: + case NodeKind::Builtin: + case NodeKind::StructType: + case NodeKind::TupleType: return 0; - case SemanticsNodeKind::ConstType: + case NodeKind::ConstType: return -1; - case SemanticsNodeKind::PointerType: + case NodeKind::PointerType: return -2; - case SemanticsNodeKind::CrossReference: + case NodeKind::CrossReference: // TODO: Once we support stringification of cross-references, we'll need // to determine the precedence of the target of the cross-reference. For // now, all cross-references refer to builtin types from the prelude. return 0; - case SemanticsNodeKind::AddressOf: - case SemanticsNodeKind::ArrayIndex: - case SemanticsNodeKind::ArrayValue: - case SemanticsNodeKind::Assign: - case SemanticsNodeKind::BinaryOperatorAdd: - case SemanticsNodeKind::BlockArg: - case SemanticsNodeKind::BoolLiteral: - case SemanticsNodeKind::Branch: - case SemanticsNodeKind::BranchIf: - case SemanticsNodeKind::BranchWithArg: - case SemanticsNodeKind::Call: - case SemanticsNodeKind::Dereference: - case SemanticsNodeKind::FunctionDeclaration: - case SemanticsNodeKind::IntegerLiteral: - case SemanticsNodeKind::Invalid: - case SemanticsNodeKind::Namespace: - case SemanticsNodeKind::Parameter: - case SemanticsNodeKind::RealLiteral: - case SemanticsNodeKind::Return: - case SemanticsNodeKind::ReturnExpression: - case SemanticsNodeKind::StringLiteral: - case SemanticsNodeKind::StructAccess: - case SemanticsNodeKind::StructTypeField: - case SemanticsNodeKind::StructValue: - case SemanticsNodeKind::StubReference: - case SemanticsNodeKind::TupleIndex: - case SemanticsNodeKind::TupleValue: - case SemanticsNodeKind::UnaryOperatorNot: - case SemanticsNodeKind::VarStorage: + case NodeKind::AddressOf: + case NodeKind::ArrayIndex: + case NodeKind::ArrayValue: + case NodeKind::Assign: + case NodeKind::BinaryOperatorAdd: + case NodeKind::BlockArg: + case NodeKind::BoolLiteral: + case NodeKind::Branch: + case NodeKind::BranchIf: + case NodeKind::BranchWithArg: + case NodeKind::Call: + case NodeKind::Dereference: + case NodeKind::FunctionDeclaration: + case NodeKind::IntegerLiteral: + case NodeKind::Invalid: + case NodeKind::Namespace: + case NodeKind::Parameter: + case NodeKind::RealLiteral: + case NodeKind::Return: + case NodeKind::ReturnExpression: + case NodeKind::StringLiteral: + case NodeKind::StructAccess: + case NodeKind::StructTypeField: + case NodeKind::StructValue: + case NodeKind::StubReference: + case NodeKind::TupleIndex: + case NodeKind::TupleValue: + case NodeKind::UnaryOperatorNot: + case NodeKind::VarStorage: CARBON_FATAL() << "GetTypePrecedence for non-type node kind " << kind; } } -auto SemanticsIR::StringifyType(SemanticsTypeId type_id, - bool in_type_context) const -> std::string { +auto File::StringifyType(TypeId type_id, bool in_type_context) const + -> std::string { std::string str; llvm::raw_string_ostream out(str); struct Step { // The node to print. - SemanticsNodeId node_id; + NodeId node_id; // The index into node_id to print. Not used by all types. int index = 0; @@ -281,14 +276,14 @@ auto SemanticsIR::StringifyType(SemanticsTypeId type_id, } // Builtins have designated labels. - if (step.node_id.index < SemanticsBuiltinKind::ValidCount) { - out << SemanticsBuiltinKind::FromInt(step.node_id.index).label(); + if (step.node_id.index < BuiltinKind::ValidCount) { + out << BuiltinKind::FromInt(step.node_id.index).label(); continue; } auto node = GetNode(step.node_id); switch (node.kind()) { - case SemanticsNodeKind::ArrayType: { + case NodeKind::ArrayType: { auto [bound_id, type_id] = node.GetAsArrayType(); if (step.index == 0) { out << "["; @@ -299,7 +294,7 @@ auto SemanticsIR::StringifyType(SemanticsTypeId type_id, } break; } - case SemanticsNodeKind::ConstType: { + case NodeKind::ConstType: { if (step.index == 0) { out << "const "; @@ -318,7 +313,7 @@ auto SemanticsIR::StringifyType(SemanticsTypeId type_id, } break; } - case SemanticsNodeKind::PointerType: { + case NodeKind::PointerType: { if (step.index == 0) { steps.push_back(step.Next()); steps.push_back( @@ -328,7 +323,7 @@ auto SemanticsIR::StringifyType(SemanticsTypeId type_id, } break; } - case SemanticsNodeKind::StructType: { + case NodeKind::StructType: { auto refs = GetNodeBlock(node.GetAsStructType()); if (refs.empty()) { out << "{}"; @@ -346,13 +341,13 @@ auto SemanticsIR::StringifyType(SemanticsTypeId type_id, steps.push_back({.node_id = refs[step.index]}); break; } - case SemanticsNodeKind::StructTypeField: { + case NodeKind::StructTypeField: { auto [name_id, type_id] = node.GetAsStructTypeField(); out << "." << GetString(name_id) << ": "; steps.push_back({.node_id = GetTypeAllowBuiltinTypes(type_id)}); break; } - case SemanticsNodeKind::TupleType: { + case NodeKind::TupleType: { auto refs = GetTypeBlock(node.GetAsTupleType()); if (refs.empty()) { out << "()"; @@ -375,42 +370,42 @@ auto SemanticsIR::StringifyType(SemanticsTypeId type_id, {.node_id = GetTypeAllowBuiltinTypes(refs[step.index])}); break; } - case SemanticsNodeKind::AddressOf: - case SemanticsNodeKind::ArrayIndex: - case SemanticsNodeKind::ArrayValue: - case SemanticsNodeKind::Assign: - case SemanticsNodeKind::BinaryOperatorAdd: - case SemanticsNodeKind::BlockArg: - case SemanticsNodeKind::BoolLiteral: - case SemanticsNodeKind::Branch: - case SemanticsNodeKind::BranchIf: - case SemanticsNodeKind::BranchWithArg: - case SemanticsNodeKind::Builtin: - case SemanticsNodeKind::Call: - case SemanticsNodeKind::Dereference: - case SemanticsNodeKind::CrossReference: - case SemanticsNodeKind::FunctionDeclaration: - case SemanticsNodeKind::IntegerLiteral: - case SemanticsNodeKind::Namespace: - case SemanticsNodeKind::Parameter: - case SemanticsNodeKind::RealLiteral: - case SemanticsNodeKind::Return: - case SemanticsNodeKind::ReturnExpression: - case SemanticsNodeKind::StringLiteral: - case SemanticsNodeKind::StructAccess: - case SemanticsNodeKind::StructValue: - case SemanticsNodeKind::StubReference: - case SemanticsNodeKind::TupleIndex: - case SemanticsNodeKind::TupleValue: - case SemanticsNodeKind::UnaryOperatorNot: - case SemanticsNodeKind::VarStorage: + case NodeKind::AddressOf: + case NodeKind::ArrayIndex: + case NodeKind::ArrayValue: + case NodeKind::Assign: + case NodeKind::BinaryOperatorAdd: + case NodeKind::BlockArg: + case NodeKind::BoolLiteral: + case NodeKind::Branch: + case NodeKind::BranchIf: + case NodeKind::BranchWithArg: + case NodeKind::Builtin: + case NodeKind::Call: + case NodeKind::Dereference: + case NodeKind::CrossReference: + case NodeKind::FunctionDeclaration: + case NodeKind::IntegerLiteral: + case NodeKind::Namespace: + case NodeKind::Parameter: + case NodeKind::RealLiteral: + case NodeKind::Return: + case NodeKind::ReturnExpression: + case NodeKind::StringLiteral: + case NodeKind::StructAccess: + case NodeKind::StructValue: + case NodeKind::StubReference: + case NodeKind::TupleIndex: + case NodeKind::TupleValue: + case NodeKind::UnaryOperatorNot: + case NodeKind::VarStorage: // We don't need to handle stringification for nodes that don't show up // in errors, but make it clear what's going on so that it's clearer // when stringification is needed. out << ""; break; - case SemanticsNodeKind::Invalid: - llvm_unreachable("SemanticsNodeKind::Invalid is never used."); + case NodeKind::Invalid: + llvm_unreachable("NodeKind::Invalid is never used."); } } @@ -418,8 +413,8 @@ auto SemanticsIR::StringifyType(SemanticsTypeId type_id, // conversion to type `type` if it's not implied by the context. if (!in_type_context) { auto outer_node = GetNode(outer_node_id); - if (outer_node.kind() == SemanticsNodeKind::TupleType || - (outer_node.kind() == SemanticsNodeKind::StructType && + if (outer_node.kind() == NodeKind::TupleType || + (outer_node.kind() == NodeKind::StructType && GetNodeBlock(outer_node.GetAsStructType()).empty())) { out << " as type"; } @@ -428,90 +423,89 @@ auto SemanticsIR::StringifyType(SemanticsTypeId type_id, return str; } -auto GetSemanticsExpressionCategory(const SemanticsIR& semantics_ir, - SemanticsNodeId node_id) - -> SemanticsExpressionCategory { - const SemanticsIR* ir = &semantics_ir; +auto GetExpressionCategory(const File& semantics_ir, NodeId node_id) + -> ExpressionCategory { + const File* ir = &semantics_ir; while (true) { auto node = ir->GetNode(node_id); switch (node.kind()) { - case SemanticsNodeKind::Invalid: - case SemanticsNodeKind::Assign: - case SemanticsNodeKind::Branch: - case SemanticsNodeKind::BranchIf: - case SemanticsNodeKind::BranchWithArg: - case SemanticsNodeKind::FunctionDeclaration: - case SemanticsNodeKind::Namespace: - case SemanticsNodeKind::Return: - case SemanticsNodeKind::ReturnExpression: - case SemanticsNodeKind::StructTypeField: - return SemanticsExpressionCategory::NotExpression; + case NodeKind::Invalid: + case NodeKind::Assign: + case NodeKind::Branch: + case NodeKind::BranchIf: + case NodeKind::BranchWithArg: + case NodeKind::FunctionDeclaration: + case NodeKind::Namespace: + case NodeKind::Return: + case NodeKind::ReturnExpression: + case NodeKind::StructTypeField: + return ExpressionCategory::NotExpression; - case SemanticsNodeKind::CrossReference: { + case NodeKind::CrossReference: { auto [xref_id, xref_node_id] = node.GetAsCrossReference(); ir = &semantics_ir.GetCrossReferenceIR(xref_id); node_id = xref_node_id; continue; } - case SemanticsNodeKind::Call: + case NodeKind::Call: // TODO: This should eventually be Initializing. - return SemanticsExpressionCategory::Value; + return ExpressionCategory::Value; - case SemanticsNodeKind::AddressOf: - case SemanticsNodeKind::ArrayType: - case SemanticsNodeKind::BinaryOperatorAdd: - case SemanticsNodeKind::BlockArg: - case SemanticsNodeKind::BoolLiteral: - case SemanticsNodeKind::Builtin: - case SemanticsNodeKind::ConstType: - case SemanticsNodeKind::IntegerLiteral: - case SemanticsNodeKind::Parameter: - case SemanticsNodeKind::PointerType: - case SemanticsNodeKind::RealLiteral: - case SemanticsNodeKind::StringLiteral: - case SemanticsNodeKind::StructType: - case SemanticsNodeKind::TupleType: - case SemanticsNodeKind::UnaryOperatorNot: - return SemanticsExpressionCategory::Value; + case NodeKind::AddressOf: + case NodeKind::ArrayType: + case NodeKind::BinaryOperatorAdd: + case NodeKind::BlockArg: + case NodeKind::BoolLiteral: + case NodeKind::Builtin: + case NodeKind::ConstType: + case NodeKind::IntegerLiteral: + case NodeKind::Parameter: + case NodeKind::PointerType: + case NodeKind::RealLiteral: + case NodeKind::StringLiteral: + case NodeKind::StructType: + case NodeKind::TupleType: + case NodeKind::UnaryOperatorNot: + return ExpressionCategory::Value; - case SemanticsNodeKind::ArrayIndex: { + case NodeKind::ArrayIndex: { auto [base_id, index_id] = node.GetAsArrayIndex(); node_id = base_id; continue; } - case SemanticsNodeKind::StructAccess: { + case NodeKind::StructAccess: { auto [base_id, member_index] = node.GetAsStructAccess(); node_id = base_id; continue; } - case SemanticsNodeKind::TupleIndex: { + case NodeKind::TupleIndex: { auto [base_id, index_id] = node.GetAsTupleIndex(); node_id = base_id; continue; } - case SemanticsNodeKind::StubReference: { + case NodeKind::StubReference: { node_id = node.GetAsStubReference(); continue; } - case SemanticsNodeKind::ArrayValue: - case SemanticsNodeKind::StructValue: - case SemanticsNodeKind::TupleValue: + case NodeKind::ArrayValue: + case NodeKind::StructValue: + case NodeKind::TupleValue: // TODO: Eventually these will depend on the context in which the value // is used, and could be either Value or Initializing. We may want // different node kinds for a struct/tuple initializer versus a // struct/tuple value construction. - return SemanticsExpressionCategory::Value; + return ExpressionCategory::Value; - case SemanticsNodeKind::Dereference: - case SemanticsNodeKind::VarStorage: - return SemanticsExpressionCategory::DurableReference; + case NodeKind::Dereference: + case NodeKind::VarStorage: + return ExpressionCategory::DurableReference; } } } -} // namespace Carbon +} // namespace Carbon::SemIR diff --git a/toolchain/semantics/semantics_ir.h b/toolchain/semantics/semantics_ir.h index d4aad6d85022..f732a705f5f1 100644 --- a/toolchain/semantics/semantics_ir.h +++ b/toolchain/semantics/semantics_ir.h @@ -12,10 +12,10 @@ #include "toolchain/parser/parse_tree.h" #include "toolchain/semantics/semantics_node.h" -namespace Carbon { +namespace Carbon::SemIR { // A function. -struct SemanticsFunction { +struct Function { auto Print(llvm::raw_ostream& out) const -> void { out << "{name: " << name_id << ", " << "param_refs: " << param_refs_id; @@ -29,24 +29,26 @@ struct SemanticsFunction { } out << "}"; } + LLVM_DUMP_METHOD void Dump() const { llvm::errs() << *this; } // The function name. - SemanticsStringId name_id; + StringId name_id; // A block containing a single reference node per parameter. - SemanticsNodeBlockId param_refs_id; + NodeBlockId param_refs_id; // The return type. This will be invalid if the return type wasn't specified. - SemanticsTypeId return_type_id; + TypeId return_type_id; // A list of the statically reachable code blocks in the body of the // function, in lexical order. The first block is the entry block. This will // be empty for declarations that don't have a visible definition. - llvm::SmallVector body_block_ids; + llvm::SmallVector body_block_ids; }; -struct SemanticsRealLiteral { +struct RealLiteral { auto Print(llvm::raw_ostream& out) const -> void { out << "{mantissa: " << mantissa << ", exponent: " << exponent << ", is_decimal: " << is_decimal << "}"; } + LLVM_DUMP_METHOD void Dump() const { llvm::errs() << *this; } llvm::APInt mantissa; llvm::APInt exponent; @@ -57,17 +59,17 @@ struct SemanticsRealLiteral { }; // Provides semantic analysis on a ParseTree. -class SemanticsIR { +class File { public: // Produces the builtins. - static auto MakeBuiltinIR() -> SemanticsIR; + static auto MakeBuiltinIR() -> File; // Adds the IR for the provided ParseTree. - static auto MakeFromParseTree(const SemanticsIR& builtin_ir, + static auto MakeFromParseTree(const File& builtin_ir, const TokenizedBuffer& tokens, const ParseTree& parse_tree, DiagnosticConsumer& consumer, - llvm::raw_ostream* vlog_stream) -> SemanticsIR; + llvm::raw_ostream* vlog_stream) -> File; // Verifies that invariants of the semantics IR hold. auto Verify() const -> ErrorOr; @@ -77,131 +79,121 @@ class SemanticsIR { // TODO: In the future, the things to print may change, for example by adding // preludes. We may then want the ability to omit other things similar to // builtins. + auto Print(llvm::raw_ostream& out, bool include_builtins) const -> void; + auto Print(llvm::raw_ostream& out) const -> void { Print(out, /*include_builtins=*/false); } - auto Print(llvm::raw_ostream& out, bool include_builtins) const -> void; // Returns array bound value from the bound node. - auto GetArrayBoundValue(SemanticsNodeId bound_id) const -> uint64_t { + auto GetArrayBoundValue(NodeId bound_id) const -> uint64_t { return GetIntegerLiteral(GetNode(bound_id).GetAsIntegerLiteral()) .getZExtValue(); } // Returns the requested IR. - auto GetCrossReferenceIR(SemanticsCrossReferenceIRId xref_id) const - -> const SemanticsIR& { + auto GetCrossReferenceIR(CrossReferenceIRId xref_id) const -> const File& { return *cross_reference_irs_[xref_id.index]; } // Adds a callable, returning an ID to reference it. - auto AddFunction(SemanticsFunction function) -> SemanticsFunctionId { - SemanticsFunctionId id(functions_.size()); + auto AddFunction(Function function) -> FunctionId { + FunctionId id(functions_.size()); functions_.push_back(function); return id; } // Returns the requested callable. - auto GetFunction(SemanticsFunctionId function_id) const - -> const SemanticsFunction& { + auto GetFunction(FunctionId function_id) const -> const Function& { return functions_[function_id.index]; } // Returns the requested callable. - auto GetFunction(SemanticsFunctionId function_id) -> SemanticsFunction& { + auto GetFunction(FunctionId function_id) -> Function& { return functions_[function_id.index]; } // Adds an integer literal, returning an ID to reference it. - auto AddIntegerLiteral(llvm::APInt integer_literal) - -> SemanticsIntegerLiteralId { - SemanticsIntegerLiteralId id(integer_literals_.size()); + auto AddIntegerLiteral(llvm::APInt integer_literal) -> IntegerLiteralId { + IntegerLiteralId id(integer_literals_.size()); integer_literals_.push_back(integer_literal); return id; } // Returns the requested integer literal. - auto GetIntegerLiteral(SemanticsIntegerLiteralId int_id) const - -> const llvm::APInt& { + auto GetIntegerLiteral(IntegerLiteralId int_id) const -> const llvm::APInt& { return integer_literals_[int_id.index]; } // Adds a name scope, returning an ID to reference it. - auto AddNameScope() -> SemanticsNameScopeId { - SemanticsNameScopeId name_scopes_id(name_scopes_.size()); + auto AddNameScope() -> NameScopeId { + NameScopeId name_scopes_id(name_scopes_.size()); name_scopes_.resize(name_scopes_id.index + 1); return name_scopes_id; } // Adds an entry to a name scope. Returns true on success, false on // duplicates. - auto AddNameScopeEntry(SemanticsNameScopeId scope_id, - SemanticsStringId name_id, SemanticsNodeId target_id) - -> bool { + auto AddNameScopeEntry(NameScopeId scope_id, StringId name_id, + NodeId target_id) -> bool { return name_scopes_[scope_id.index].insert({name_id, target_id}).second; } // Returns the requested name scope. - auto GetNameScope(SemanticsNameScopeId scope_id) const - -> const llvm::DenseMap& { + auto GetNameScope(NameScopeId scope_id) const + -> const llvm::DenseMap& { return name_scopes_[scope_id.index]; } // Adds a node to a specified block, returning an ID to reference the node. - auto AddNode(SemanticsNodeBlockId block_id, SemanticsNode node) - -> SemanticsNodeId { - SemanticsNodeId node_id(nodes_.size()); + auto AddNode(NodeBlockId block_id, Node node) -> NodeId { + NodeId node_id(nodes_.size()); nodes_.push_back(node); - if (block_id != SemanticsNodeBlockId::Unreachable) { + if (block_id != NodeBlockId::Unreachable) { node_blocks_[block_id.index].push_back(node_id); } return node_id; } // Returns the requested node. - auto GetNode(SemanticsNodeId node_id) const -> SemanticsNode { - return nodes_[node_id.index]; - } + auto GetNode(NodeId node_id) const -> Node { return nodes_[node_id.index]; } // Adds an empty node block, returning an ID to reference it. - auto AddNodeBlock() -> SemanticsNodeBlockId { - SemanticsNodeBlockId id(node_blocks_.size()); + auto AddNodeBlock() -> NodeBlockId { + NodeBlockId id(node_blocks_.size()); node_blocks_.push_back({}); return id; } // Returns the requested node block. - auto GetNodeBlock(SemanticsNodeBlockId block_id) const - -> const llvm::SmallVector& { - CARBON_CHECK(block_id != SemanticsNodeBlockId::Unreachable); + auto GetNodeBlock(NodeBlockId block_id) const + -> const llvm::SmallVector& { + CARBON_CHECK(block_id != NodeBlockId::Unreachable); return node_blocks_[block_id.index]; } // Returns the requested node block. - auto GetNodeBlock(SemanticsNodeBlockId block_id) - -> llvm::SmallVector& { - CARBON_CHECK(block_id != SemanticsNodeBlockId::Unreachable); + auto GetNodeBlock(NodeBlockId block_id) -> llvm::SmallVector& { + CARBON_CHECK(block_id != NodeBlockId::Unreachable); return node_blocks_[block_id.index]; } // Adds a real literal, returning an ID to reference it. - auto AddRealLiteral(SemanticsRealLiteral real_literal) - -> SemanticsRealLiteralId { - SemanticsRealLiteralId id(real_literals_.size()); + auto AddRealLiteral(RealLiteral real_literal) -> RealLiteralId { + RealLiteralId id(real_literals_.size()); real_literals_.push_back(real_literal); return id; } // Returns the requested real literal. - auto GetRealLiteral(SemanticsRealLiteralId int_id) const - -> const SemanticsRealLiteral& { + auto GetRealLiteral(RealLiteralId int_id) const -> const RealLiteral& { return real_literals_[int_id.index]; } // Adds an string, returning an ID to reference it. - auto AddString(llvm::StringRef str) -> SemanticsStringId { + auto AddString(llvm::StringRef str) -> StringId { // Look up the string, or add it if it's new. - SemanticsStringId next_id(strings_.size()); + StringId next_id(strings_.size()); auto [it, added] = string_to_id_.insert({str, next_id}); if (added) { @@ -214,13 +206,13 @@ class SemanticsIR { } // Returns the requested string. - auto GetString(SemanticsStringId string_id) const -> llvm::StringRef { + auto GetString(StringId string_id) const -> llvm::StringRef { return strings_[string_id.index]; } // Adds a type, returning an ID to reference it. - auto AddType(SemanticsNodeId node_id) -> SemanticsTypeId { - SemanticsTypeId type_id(types_.size()); + auto AddType(NodeId node_id) -> TypeId { + TypeId type_id(types_.size()); types_.push_back(node_id); return type_id; } @@ -228,40 +220,38 @@ class SemanticsIR { // Gets the node ID for a type. This doesn't handle TypeType or InvalidType in // order to avoid a check; callers that need that should use // GetTypeAllowBuiltinTypes. - auto GetType(SemanticsTypeId type_id) const -> SemanticsNodeId { + auto GetType(TypeId type_id) const -> NodeId { // Double-check it's not called with TypeType or InvalidType. CARBON_CHECK(type_id.index >= 0) << "Invalid argument for GetType: " << type_id; return types_[type_id.index]; } - auto GetTypeAllowBuiltinTypes(SemanticsTypeId type_id) const - -> SemanticsNodeId { - if (type_id == SemanticsTypeId::TypeType) { - return SemanticsNodeId::BuiltinTypeType; - } else if (type_id == SemanticsTypeId::Error) { - return SemanticsNodeId::BuiltinError; + auto GetTypeAllowBuiltinTypes(TypeId type_id) const -> NodeId { + if (type_id == TypeId::TypeType) { + return NodeId::BuiltinTypeType; + } else if (type_id == TypeId::Error) { + return NodeId::BuiltinError; } else { return GetType(type_id); } } // Adds an empty type block, returning an ID to reference it. - auto AddTypeBlock() -> SemanticsTypeBlockId { - SemanticsTypeBlockId id(type_blocks_.size()); + auto AddTypeBlock() -> TypeBlockId { + TypeBlockId id(type_blocks_.size()); type_blocks_.push_back({}); return id; } // Returns the requested type block. - auto GetTypeBlock(SemanticsTypeBlockId block_id) const - -> const llvm::SmallVector& { + auto GetTypeBlock(TypeBlockId block_id) const + -> const llvm::SmallVector& { return type_blocks_[block_id.index]; } // Returns the requested type block. - auto GetTypeBlock(SemanticsTypeBlockId block_id) - -> llvm::SmallVector& { + auto GetTypeBlock(TypeBlockId block_id) -> llvm::SmallVector& { return type_blocks_[block_id.index]; } @@ -269,82 +259,77 @@ class SemanticsIR { // explicit conversion to type `type` will be added in cases where the type // expression would otherwise have a different type, such as a tuple or // struct type. - auto StringifyType(SemanticsTypeId type_id, - bool in_type_context = false) const -> std::string; + auto StringifyType(TypeId type_id, bool in_type_context = false) const + -> std::string; auto functions_size() const -> int { return functions_.size(); } auto nodes_size() const -> int { return nodes_.size(); } auto node_blocks_size() const -> int { return node_blocks_.size(); } - auto types() const -> const llvm::SmallVector& { - return types_; - } + auto types() const -> const llvm::SmallVector& { return types_; } // The node blocks, for direct mutation. - auto node_blocks() -> llvm::SmallVector>& { + auto node_blocks() -> llvm::SmallVector>& { return node_blocks_; } - auto top_node_block_id() const -> SemanticsNodeBlockId { - return top_node_block_id_; - } + auto top_node_block_id() const -> NodeBlockId { return top_node_block_id_; } // Returns true if there were errors creating the semantics IR. auto has_errors() const -> bool { return has_errors_; } private: - explicit SemanticsIR(const SemanticsIR* builtin_ir) + explicit File(const File* builtin_ir) : cross_reference_irs_({builtin_ir == nullptr ? this : builtin_ir}) { - // For SemanticsNodeBlockId::Empty. + // For NodeBlockId::Empty. node_blocks_.resize(1); } bool has_errors_ = false; // Storage for callable objects. - llvm::SmallVector functions_; + llvm::SmallVector functions_; // Related IRs. There will always be at least 2 entries, the builtin IR (used // for references of builtins) followed by the current IR (used for references // crossing node blocks). - llvm::SmallVector cross_reference_irs_; + llvm::SmallVector cross_reference_irs_; // Storage for integer literals. llvm::SmallVector integer_literals_; // Storage for name scopes. - llvm::SmallVector> - name_scopes_; + llvm::SmallVector> name_scopes_; // Storage for real literals. - llvm::SmallVector real_literals_; + llvm::SmallVector real_literals_; // Storage for strings. strings_ provides a list of allocated strings, while // string_to_id_ provides a mapping to identify strings. - llvm::StringMap string_to_id_; + llvm::StringMap string_to_id_; llvm::SmallVector strings_; // Nodes which correspond to in-use types. Stored separately for easy access // by lowering. - llvm::SmallVector types_; + llvm::SmallVector types_; // Storage for blocks within the IR. These reference entries in types_. - llvm::SmallVector> type_blocks_; + llvm::SmallVector> type_blocks_; // All nodes. The first entries will always be cross-references to builtins, - // at indices matching SemanticsBuiltinKind ordering. - llvm::SmallVector nodes_; + // at indices matching BuiltinKind ordering. + llvm::SmallVector nodes_; // Storage for blocks within the IR. These reference entries in nodes_. - llvm::SmallVector> node_blocks_; + llvm::SmallVector> node_blocks_; // The top node block ID. - SemanticsNodeBlockId top_node_block_id_ = SemanticsNodeBlockId::Invalid; + NodeBlockId top_node_block_id_ = NodeBlockId::Invalid; }; // The expression category of a semantics node. See /docs/design/values.md for // details. -enum class SemanticsExpressionCategory { +enum class ExpressionCategory { // This node does not correspond to an expression, and as such has no // category. NotExpression, @@ -362,10 +347,9 @@ enum class SemanticsExpressionCategory { }; // Returns the expression category for a node. -auto GetSemanticsExpressionCategory(const SemanticsIR& semantics_ir, - SemanticsNodeId node_id) - -> SemanticsExpressionCategory; +auto GetExpressionCategory(const File& semantics_ir, NodeId node_id) + -> ExpressionCategory; -} // namespace Carbon +} // namespace Carbon::SemIR #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_IR_H_ diff --git a/toolchain/semantics/semantics_ir_formatter.cpp b/toolchain/semantics/semantics_ir_formatter.cpp index e3857e9f06bd..5bfe01826634 100644 --- a/toolchain/semantics/semantics_ir_formatter.cpp +++ b/toolchain/semantics/semantics_ir_formatter.cpp @@ -10,7 +10,7 @@ #include "toolchain/lexer/tokenized_buffer.h" #include "toolchain/parser/parse_tree.h" -namespace Carbon { +namespace Carbon::SemIR { namespace { // Assigns names to nodes, blocks, and scopes in the Semantics IR. @@ -28,10 +28,10 @@ class NodeNamer { None = -1, Package = 0, }; - static_assert(sizeof(ScopeIndex) == sizeof(SemanticsFunctionId)); + static_assert(sizeof(ScopeIndex) == sizeof(FunctionId)); NodeNamer(const TokenizedBuffer& tokenized_buffer, - const ParseTree& parse_tree, const SemanticsIR& semantics_ir) + const ParseTree& parse_tree, const File& semantics_ir) : tokenized_buffer_(tokenized_buffer), parse_tree_(parse_tree), semantics_ir_(semantics_ir) { @@ -46,7 +46,7 @@ class NodeNamer { // Build each function scope. for (int i : llvm::seq(semantics_ir.functions_size())) { - auto fn_id = SemanticsFunctionId(i); + auto fn_id = FunctionId(i); auto fn_scope = GetScopeFor(fn_id); const auto& fn = semantics_ir.GetFunction(fn_id); // TODO: Provide a location for the function for use as a @@ -70,12 +70,12 @@ class NodeNamer { } // Returns the scope index corresponding to a function. - auto GetScopeFor(SemanticsFunctionId fn_id) -> ScopeIndex { + auto GetScopeFor(FunctionId fn_id) -> ScopeIndex { return static_cast(fn_id.index + 1); } // Returns the IR name to use for a function. - auto GetNameFor(SemanticsFunctionId fn_id) -> llvm::StringRef { + auto GetNameFor(FunctionId fn_id) -> llvm::StringRef { if (!fn_id.is_valid()) { return "invalid"; } @@ -83,15 +83,14 @@ class NodeNamer { } // Returns the IR name to use for a node, when referenced from a given scope. - auto GetNameFor(ScopeIndex scope_idx, SemanticsNodeId node_id) - -> std::string { + auto GetNameFor(ScopeIndex scope_idx, NodeId node_id) -> std::string { if (!node_id.is_valid()) { return "invalid"; } // Check for a builtin. - if (node_id.index < SemanticsBuiltinKind::ValidCount) { - return SemanticsBuiltinKind::FromInt(node_id.index).label().str(); + if (node_id.index < BuiltinKind::ValidCount) { + return BuiltinKind::FromInt(node_id.index).label().str(); } auto& [node_scope, node_name] = nodes[node_id.index]; @@ -106,8 +105,7 @@ class NodeNamer { } // Returns the IR name to use for a label, when referenced from a given scope. - auto GetLabelFor(ScopeIndex scope_idx, SemanticsNodeBlockId block_id) - -> std::string { + auto GetLabelFor(ScopeIndex scope_idx, NodeBlockId block_id) -> std::string { if (!block_id.is_valid()) { return "!invalid"; } @@ -243,7 +241,7 @@ class NodeNamer { return scopes[static_cast(scope_idx)]; } - auto AddBlockLabel(ScopeIndex scope_idx, SemanticsNodeBlockId block_id, + auto AddBlockLabel(ScopeIndex scope_idx, NodeBlockId block_id, std::string name = "", ParseTree::Node parse_node = ParseTree::Node::Invalid) -> void { @@ -265,19 +263,19 @@ class NodeNamer { // Finds and adds a suitable block label for the given semantics node that // represents some kind of branch. - auto AddBlockLabel(ScopeIndex scope_idx, SemanticsNodeBlockId block_id, - SemanticsNode node) -> void { + auto AddBlockLabel(ScopeIndex scope_idx, NodeBlockId block_id, Node node) + -> void { llvm::StringRef name; switch (parse_tree_.node_kind(node.parse_node())) { case ParseNodeKind::IfExpressionIf: switch (node.kind()) { - case SemanticsNodeKind::BranchIf: + case NodeKind::BranchIf: name = "if.expr.then"; break; - case SemanticsNodeKind::Branch: + case NodeKind::Branch: name = "if.expr.else"; break; - case SemanticsNodeKind::BranchWithArg: + case NodeKind::BranchWithArg: name = "if.expr.result"; break; default: @@ -287,10 +285,10 @@ class NodeNamer { case ParseNodeKind::IfCondition: switch (node.kind()) { - case SemanticsNodeKind::BranchIf: + case NodeKind::BranchIf: name = "if.then"; break; - case SemanticsNodeKind::Branch: + case NodeKind::Branch: name = "if.else"; break; default: @@ -303,7 +301,7 @@ class NodeNamer { break; case ParseNodeKind::ShortCircuitOperand: { - bool is_rhs = node.kind() == SemanticsNodeKind::BranchIf; + bool is_rhs = node.kind() == NodeKind::BranchIf; bool is_and = tokenized_buffer_.GetKind(parse_tree_.node_token( node.parse_node())) == TokenKind::And; name = is_and ? (is_rhs ? "and.rhs" : "and.result") @@ -318,8 +316,7 @@ class NodeNamer { AddBlockLabel(scope_idx, block_id, name.str(), node.parse_node()); } - auto CollectNamesInBlock(ScopeIndex scope_idx, SemanticsNodeBlockId block_id) - -> void { + auto CollectNamesInBlock(ScopeIndex scope_idx, NodeBlockId block_id) -> void { if (!block_id.is_valid()) { return; } @@ -330,22 +327,22 @@ class NodeNamer { for (auto node_id : semantics_ir_.GetNodeBlock(block_id)) { auto node = semantics_ir_.GetNode(node_id); switch (node.kind()) { - case SemanticsNodeKind::Branch: { + case NodeKind::Branch: { auto dest_id = node.GetAsBranch(); AddBlockLabel(scope_idx, dest_id, node); break; } - case SemanticsNodeKind::BranchIf: { + case NodeKind::BranchIf: { auto [dest_id, cond_id] = node.GetAsBranchIf(); AddBlockLabel(scope_idx, dest_id, node); break; } - case SemanticsNodeKind::BranchWithArg: { + case NodeKind::BranchWithArg: { auto [dest_id, arg_id] = node.GetAsBranchWithArg(); AddBlockLabel(scope_idx, dest_id, node); break; } - case SemanticsNodeKind::Parameter: { + case NodeKind::Parameter: { auto name_id = node.GetAsParameter(); nodes[node_id.index] = { scope_idx, @@ -353,7 +350,7 @@ class NodeNamer { semantics_ir_.GetString(name_id).str())}; break; } - case SemanticsNodeKind::VarStorage: { + case NodeKind::VarStorage: { // TODO: Eventually this name will be optional, and we'll want to // provide something like `var` as a default. However, that's not // possible right now so cannot be tested. @@ -366,7 +363,7 @@ class NodeNamer { } default: { // Sequentially number all remaining values. - if (node.kind().value_kind() != SemanticsNodeValueKind::None) { + if (node.kind().value_kind() != NodeValueKind::None) { nodes[node_id.index] = { scope_idx, scope.nodes.AllocateName(*this, node.parse_node())}; } @@ -378,7 +375,7 @@ class NodeNamer { const TokenizedBuffer& tokenized_buffer_; const ParseTree& parse_tree_; - const SemanticsIR& semantics_ir_; + const File& semantics_ir_; Namespace globals = {.prefix = "@"}; std::vector> nodes; @@ -388,12 +385,11 @@ class NodeNamer { } // namespace // Formatter for printing textual Semantics IR. -class SemanticsIRFormatter { +class Formatter { public: - explicit SemanticsIRFormatter(const TokenizedBuffer& tokenized_buffer, - const ParseTree& parse_tree, - const SemanticsIR& semantics_ir, - llvm::raw_ostream& out) + explicit Formatter(const TokenizedBuffer& tokenized_buffer, + const ParseTree& parse_tree, const File& semantics_ir, + llvm::raw_ostream& out) : semantics_ir_(semantics_ir), out_(out), node_namer_(tokenized_buffer, parse_tree, semantics_ir) {} @@ -414,12 +410,12 @@ class SemanticsIRFormatter { out_ << "}\n"; for (int i : llvm::seq(semantics_ir_.functions_size())) { - FormatFunction(SemanticsFunctionId(i)); + FormatFunction(FunctionId(i)); } } - auto FormatFunction(SemanticsFunctionId id) -> void { - const SemanticsFunction& fn = semantics_ir_.GetFunction(id); + auto FormatFunction(FunctionId id) -> void { + const Function& fn = semantics_ir_.GetFunction(id); out_ << "\nfn "; FormatFunctionName(id); @@ -428,8 +424,7 @@ class SemanticsIRFormatter { llvm::SaveAndRestore function_scope(scope_, node_namer_.GetScopeFor(id)); llvm::ListSeparator sep; - for (const SemanticsNodeId param_id : - semantics_ir_.GetNodeBlock(fn.param_refs_id)) { + for (const NodeId param_id : semantics_ir_.GetNodeBlock(fn.param_refs_id)) { out_ << sep; FormatNodeName(param_id); out_ << ": "; @@ -459,37 +454,37 @@ class SemanticsIRFormatter { } } - auto FormatCodeBlock(SemanticsNodeBlockId block_id) -> void { + auto FormatCodeBlock(NodeBlockId block_id) -> void { if (!block_id.is_valid()) { return; } - for (const SemanticsNodeId node_id : semantics_ir_.GetNodeBlock(block_id)) { + for (const NodeId node_id : semantics_ir_.GetNodeBlock(block_id)) { FormatInstruction(node_id); } } - auto FormatInstruction(SemanticsNodeId node_id) -> void { + auto FormatInstruction(NodeId node_id) -> void { if (!node_id.is_valid()) { - out_ << " " << SemanticsNodeKind::Invalid.ir_name() << "\n"; + out_ << " " << NodeKind::Invalid.ir_name() << "\n"; return; } FormatInstruction(node_id, semantics_ir_.GetNode(node_id)); } - auto FormatInstruction(SemanticsNodeId node_id, SemanticsNode node) -> void { + auto FormatInstruction(NodeId node_id, Node node) -> void { switch (node.kind()) { -#define CARBON_SEMANTICS_NODE_KIND(Name) \ - case SemanticsNodeKind::Name: \ - FormatInstruction(node_id, node); \ +#define CARBON_SEMANTICS_NODE_KIND(Name) \ + case NodeKind::Name: \ + FormatInstruction(node_id, node); \ break; #include "toolchain/semantics/semantics_node_kind.def" } } template - auto FormatInstruction(SemanticsNodeId node_id, SemanticsNode node) -> void { + auto FormatInstruction(NodeId node_id, Node node) -> void { out_ << " "; FormatInstructionLHS(node_id, node); out_ << node.kind().ir_name(); @@ -497,60 +492,58 @@ class SemanticsIRFormatter { out_ << "\n"; } - auto FormatInstructionLHS(SemanticsNodeId node_id, SemanticsNode node) - -> void { + auto FormatInstructionLHS(NodeId node_id, Node node) -> void { switch (node.kind().value_kind()) { - case SemanticsNodeValueKind::Typed: + case NodeValueKind::Typed: FormatNodeName(node_id); out_ << ": "; FormatType(node.type_id()); out_ << " = "; break; - case SemanticsNodeValueKind::Untyped: + case NodeValueKind::Untyped: FormatNodeName(node_id); out_ << " = "; break; - case SemanticsNodeValueKind::None: + case NodeValueKind::None: break; } } template - auto FormatInstructionRHS(SemanticsNode node) -> void { + auto FormatInstructionRHS(Node node) -> void { // By default, an instruction has a comma-separated argument list. FormatArgs(Kind::Get(node)); } template <> - auto FormatInstructionRHS(SemanticsNode node) - -> void { + auto FormatInstructionRHS(Node node) -> void { out_ << " "; FormatLabel(node.GetAsBlockArg()); } template <> - auto FormatInstruction(SemanticsNodeId /*node_id*/, - SemanticsNode node) -> void { + auto FormatInstruction(NodeId /*node_id*/, Node node) + -> void { if (!in_terminator_sequence) { out_ << " "; } auto [label_id, cond_id] = node.GetAsBranchIf(); out_ << "if "; FormatNodeName(cond_id); - out_ << " " << SemanticsNodeKind::Branch.ir_name() << " "; + out_ << " " << NodeKind::Branch.ir_name() << " "; FormatLabel(label_id); out_ << " else "; in_terminator_sequence = true; } template <> - auto FormatInstruction( - SemanticsNodeId /*node_id*/, SemanticsNode node) -> void { + auto FormatInstruction(NodeId /*node_id*/, Node node) + -> void { if (!in_terminator_sequence) { out_ << " "; } auto [label_id, arg_id] = node.GetAsBranchWithArg(); - out_ << SemanticsNodeKind::BranchWithArg.ir_name() << " "; + out_ << NodeKind::BranchWithArg.ir_name() << " "; FormatLabel(label_id); out_ << "("; FormatNodeName(arg_id); @@ -559,19 +552,18 @@ class SemanticsIRFormatter { } template <> - auto FormatInstruction(SemanticsNodeId /*node_id*/, - SemanticsNode node) -> void { + auto FormatInstruction(NodeId /*node_id*/, Node node) -> void { if (!in_terminator_sequence) { out_ << " "; } - out_ << SemanticsNodeKind::Branch.ir_name() << " "; + out_ << NodeKind::Branch.ir_name() << " "; FormatLabel(node.GetAsBranch()); out_ << "\n"; in_terminator_sequence = false; } template <> - auto FormatInstructionRHS(SemanticsNode node) -> void { + auto FormatInstructionRHS(Node node) -> void { out_ << " "; auto [args_id, callee_id] = node.GetAsCall(); FormatArg(callee_id); @@ -579,8 +571,7 @@ class SemanticsIRFormatter { } template <> - auto FormatInstructionRHS(SemanticsNode node) - -> void { + auto FormatInstructionRHS(Node node) -> void { // TODO: Figure out a way to make this meaningful. We'll need some way to // name cross-reference IRs, perhaps by the node ID of the import? auto [xref_id, node_id] = node.GetAsCrossReference(); @@ -589,12 +580,11 @@ class SemanticsIRFormatter { // StructTypeFields are formatted as part of their StructType. template <> - auto FormatInstruction( - SemanticsNodeId /*node_id*/, SemanticsNode /*node*/) -> void {} + auto FormatInstruction(NodeId /*node_id*/, + Node /*node*/) -> void {} template <> - auto FormatInstructionRHS(SemanticsNode node) - -> void { + auto FormatInstructionRHS(Node node) -> void { out_ << " {"; llvm::ListSeparator sep; for (auto field_id : semantics_ir_.GetNodeBlock(node.GetAsStructType())) { @@ -608,7 +598,7 @@ class SemanticsIRFormatter { out_ << "}"; } - auto FormatArgs(SemanticsNode::NoArgs /*unused*/) -> void {} + auto FormatArgs(Node::NoArgs /*unused*/) -> void {} template auto FormatArgs(Arg1 arg) -> void { @@ -624,24 +614,24 @@ class SemanticsIRFormatter { FormatArgs(args.second); } - auto FormatArg(SemanticsBoolValue v) -> void { out_ << v; } + auto FormatArg(BoolValue v) -> void { out_ << v; } - auto FormatArg(SemanticsBuiltinKind kind) -> void { out_ << kind.label(); } + auto FormatArg(BuiltinKind kind) -> void { out_ << kind.label(); } - auto FormatArg(SemanticsFunctionId id) -> void { FormatFunctionName(id); } + auto FormatArg(FunctionId id) -> void { FormatFunctionName(id); } - auto FormatArg(SemanticsIntegerLiteralId id) -> void { + auto FormatArg(IntegerLiteralId id) -> void { out_ << semantics_ir_.GetIntegerLiteral(id); } - auto FormatArg(SemanticsMemberIndex index) -> void { out_ << index; } + auto FormatArg(MemberIndex index) -> void { out_ << index; } // TODO: Should we be printing scopes inline, or should we have a separate // step to print them like we do for functions? - auto FormatArg(SemanticsNameScopeId id) -> void { + auto FormatArg(NameScopeId id) -> void { // Name scopes aren't kept in any particular order. Sort the entries before // we print them for stability and consistency. - std::vector> entries; + std::vector> entries; for (auto [name_id, node_id] : semantics_ir_.GetNameScope(id)) { entries.push_back({node_id, name_id}); } @@ -659,9 +649,9 @@ class SemanticsIRFormatter { out_ << '}'; } - auto FormatArg(SemanticsNodeId id) -> void { FormatNodeName(id); } + auto FormatArg(NodeId id) -> void { FormatNodeName(id); } - auto FormatArg(SemanticsNodeBlockId id) -> void { + auto FormatArg(NodeBlockId id) -> void { out_ << '('; llvm::ListSeparator sep; for (auto node_id : semantics_ir_.GetNodeBlock(id)) { @@ -671,21 +661,21 @@ class SemanticsIRFormatter { out_ << ')'; } - auto FormatArg(SemanticsRealLiteralId id) -> void { + auto FormatArg(RealLiteralId id) -> void { // TODO: Format with a `.` when the exponent is near zero. const auto& real = semantics_ir_.GetRealLiteral(id); out_ << real.mantissa << (real.is_decimal ? 'e' : 'p') << real.exponent; } - auto FormatArg(SemanticsStringId id) -> void { + auto FormatArg(StringId id) -> void { out_ << '"'; out_.write_escaped(semantics_ir_.GetString(id), /*UseHexEscapes=*/true); out_ << '"'; } - auto FormatArg(SemanticsTypeId id) -> void { FormatType(id); } + auto FormatArg(TypeId id) -> void { FormatType(id); } - auto FormatArg(SemanticsTypeBlockId id) -> void { + auto FormatArg(TypeBlockId id) -> void { out_ << '('; llvm::ListSeparator sep; for (auto type_id : semantics_ir_.GetTypeBlock(id)) { @@ -695,23 +685,23 @@ class SemanticsIRFormatter { out_ << ')'; } - auto FormatNodeName(SemanticsNodeId id) -> void { + auto FormatNodeName(NodeId id) -> void { out_ << node_namer_.GetNameFor(scope_, id); } - auto FormatLabel(SemanticsNodeBlockId id) -> void { + auto FormatLabel(NodeBlockId id) -> void { out_ << node_namer_.GetLabelFor(scope_, id); } - auto FormatString(SemanticsStringId id) -> void { + auto FormatString(StringId id) -> void { out_ << semantics_ir_.GetString(id); } - auto FormatFunctionName(SemanticsFunctionId id) -> void { + auto FormatFunctionName(FunctionId id) -> void { out_ << node_namer_.GetNameFor(id); } - auto FormatType(SemanticsTypeId id) -> void { + auto FormatType(TypeId id) -> void { if (!id.is_valid()) { out_ << "invalid"; } else { @@ -720,19 +710,17 @@ class SemanticsIRFormatter { } private: - const SemanticsIR& semantics_ir_; + const File& semantics_ir_; llvm::raw_ostream& out_; NodeNamer node_namer_; NodeNamer::ScopeIndex scope_ = NodeNamer::ScopeIndex::None; bool in_terminator_sequence = false; }; -auto FormatSemanticsIR(const TokenizedBuffer& tokenized_buffer, - const ParseTree& parse_tree, - const SemanticsIR& semantics_ir, llvm::raw_ostream& out) - -> void { - SemanticsIRFormatter(tokenized_buffer, parse_tree, semantics_ir, out) - .Format(); +auto FormatFile(const TokenizedBuffer& tokenized_buffer, + const ParseTree& parse_tree, const File& semantics_ir, + llvm::raw_ostream& out) -> void { + Formatter(tokenized_buffer, parse_tree, semantics_ir, out).Format(); } -} // namespace Carbon +} // namespace Carbon::SemIR diff --git a/toolchain/semantics/semantics_ir_formatter.h b/toolchain/semantics/semantics_ir_formatter.h index 6a0ea35818e1..c075daf05167 100644 --- a/toolchain/semantics/semantics_ir_formatter.h +++ b/toolchain/semantics/semantics_ir_formatter.h @@ -8,13 +8,12 @@ #include "llvm/Support/raw_ostream.h" #include "toolchain/semantics/semantics_ir.h" -namespace Carbon { +namespace Carbon::SemIR { -auto FormatSemanticsIR(const TokenizedBuffer& tokenized_buffer, - const ParseTree& parse_tree, - const SemanticsIR& semantics_ir, llvm::raw_ostream& out) - -> void; +auto FormatFile(const TokenizedBuffer& tokenized_buffer, + const ParseTree& parse_tree, const File& semantics_ir, + llvm::raw_ostream& out) -> void; -} // namespace Carbon +} // namespace Carbon::SemIR #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_IR_FORMATTER_H_ diff --git a/toolchain/semantics/semantics_ir_test.cpp b/toolchain/semantics/semantics_ir_test.cpp index 7e948a70500f..d6b8457bf36b 100644 --- a/toolchain/semantics/semantics_ir_test.cpp +++ b/toolchain/semantics/semantics_ir_test.cpp @@ -27,7 +27,7 @@ using ::testing::MatchesRegex; using ::testing::Pair; using ::testing::SizeIs; -TEST(SemanticsIRTest, YAML) { +TEST(SemIRTest, YAML) { llvm::vfs::InMemoryFileSystem fs; CARBON_CHECK(fs.addFile( "test.carbon", /*ModificationTime=*/0, diff --git a/toolchain/semantics/semantics_node.cpp b/toolchain/semantics/semantics_node.cpp index 75e24afc66a6..5bc5fb288883 100644 --- a/toolchain/semantics/semantics_node.cpp +++ b/toolchain/semantics/semantics_node.cpp @@ -4,10 +4,10 @@ #include "toolchain/semantics/semantics_node.h" -namespace Carbon { +namespace Carbon::SemIR { static auto PrintArgs(llvm::raw_ostream& /*out*/, - const SemanticsNode::NoArgs /*no_args*/) -> void {} + const Node::NoArgs /*no_args*/) -> void {} template static auto PrintArgs(llvm::raw_ostream& out, T arg) -> void { @@ -20,19 +20,21 @@ static auto PrintArgs(llvm::raw_ostream& out, std::pair args) -> void { out << ", arg1: " << args.second; } -auto SemanticsNode::Print(llvm::raw_ostream& out) const -> void { - out << "{kind: " << kind_; - switch (kind_) { +auto operator<<(llvm::raw_ostream& out, const Node& node) + -> llvm::raw_ostream& { + out << "{kind: " << node.kind_; + switch (node.kind_) { #define CARBON_SEMANTICS_NODE_KIND(Name) \ - case SemanticsNodeKind::Name: \ - PrintArgs(out, GetAs##Name()); \ + case NodeKind::Name: \ + PrintArgs(out, node.GetAs##Name()); \ break; #include "toolchain/semantics/semantics_node_kind.def" } - if (type_id_.is_valid()) { - out << ", type: " << type_id_; + if (node.type_id_.is_valid()) { + out << ", type: " << node.type_id_; } out << "}"; + return out; } -} // namespace Carbon +} // namespace Carbon::SemIR diff --git a/toolchain/semantics/semantics_node.h b/toolchain/semantics/semantics_node.h index 206504eefa34..3bd2c5c5faf0 100644 --- a/toolchain/semantics/semantics_node.h +++ b/toolchain/semantics/semantics_node.h @@ -14,16 +14,16 @@ #include "toolchain/semantics/semantics_builtin_kind.h" #include "toolchain/semantics/semantics_node_kind.h" -namespace Carbon { +namespace Carbon::SemIR { // The ID of a node. -struct SemanticsNodeId : public IndexBase { +struct NodeId : public IndexBase { // An explicitly invalid node ID. - static const SemanticsNodeId Invalid; + static const NodeId Invalid; // Builtin node IDs. #define CARBON_SEMANTICS_BUILTIN_KIND_NAME(Name) \ - static const SemanticsNodeId Builtin##Name; + static const NodeId Builtin##Name; #include "toolchain/semantics/semantics_builtin_kind.def" using IndexBase::IndexBase; @@ -31,28 +31,26 @@ struct SemanticsNodeId : public IndexBase { out << "node"; if (!is_valid()) { IndexBase::Print(out); - } else if (index < SemanticsBuiltinKind::ValidCount) { - out << SemanticsBuiltinKind::FromInt(index); + } else if (index < BuiltinKind::ValidCount) { + out << BuiltinKind::FromInt(index); } else { // Use the `+` as a small reminder that this is a delta, rather than an // absolute index. - out << "+" << index - SemanticsBuiltinKind::ValidCount; + out << "+" << index - BuiltinKind::ValidCount; } } }; -constexpr SemanticsNodeId SemanticsNodeId::Invalid = - SemanticsNodeId(SemanticsNodeId::InvalidIndex); +constexpr NodeId NodeId::Invalid = NodeId(NodeId::InvalidIndex); -// Uses the cross-reference node ID for a builtin. This relies on SemanticsIR +// Uses the cross-reference node ID for a builtin. This relies on File // guarantees for builtin cross-reference placement. -#define CARBON_SEMANTICS_BUILTIN_KIND_NAME(Name) \ - constexpr SemanticsNodeId SemanticsNodeId::Builtin##Name = \ - SemanticsNodeId(SemanticsBuiltinKind::Name.AsInt()); +#define CARBON_SEMANTICS_BUILTIN_KIND_NAME(Name) \ + constexpr NodeId NodeId::Builtin##Name = NodeId(BuiltinKind::Name.AsInt()); #include "toolchain/semantics/semantics_builtin_kind.def" // The ID of a function. -struct SemanticsFunctionId : public IndexBase { +struct FunctionId : public IndexBase { using IndexBase::IndexBase; auto Print(llvm::raw_ostream& out) const -> void { out << "function"; @@ -61,7 +59,7 @@ struct SemanticsFunctionId : public IndexBase { }; // The ID of a cross-referenced IR. -struct SemanticsCrossReferenceIRId : public IndexBase { +struct CrossReferenceIRId : public IndexBase { using IndexBase::IndexBase; auto Print(llvm::raw_ostream& out) const -> void { out << "ir"; @@ -70,9 +68,9 @@ struct SemanticsCrossReferenceIRId : public IndexBase { }; // A boolean value. -struct SemanticsBoolValue : public IndexBase { - static const SemanticsBoolValue False; - static const SemanticsBoolValue True; +struct BoolValue : public IndexBase { + static const BoolValue False; + static const BoolValue True; using IndexBase::IndexBase; auto Print(llvm::raw_ostream& out) const -> void { @@ -89,11 +87,11 @@ struct SemanticsBoolValue : public IndexBase { } }; -constexpr SemanticsBoolValue SemanticsBoolValue::False = SemanticsBoolValue(0); -constexpr SemanticsBoolValue SemanticsBoolValue::True = SemanticsBoolValue(1); +constexpr BoolValue BoolValue::False = BoolValue(0); +constexpr BoolValue BoolValue::True = BoolValue(1); // The ID of an integer literal. -struct SemanticsIntegerLiteralId : public IndexBase { +struct IntegerLiteralId : public IndexBase { using IndexBase::IndexBase; auto Print(llvm::raw_ostream& out) const -> void { out << "int"; @@ -102,9 +100,9 @@ struct SemanticsIntegerLiteralId : public IndexBase { }; // The ID of a name scope. -struct SemanticsNameScopeId : public IndexBase { +struct NameScopeId : public IndexBase { // An explicitly invalid ID. - static const SemanticsNameScopeId Invalid; + static const NameScopeId Invalid; using IndexBase::IndexBase; auto Print(llvm::raw_ostream& out) const -> void { @@ -113,19 +111,19 @@ struct SemanticsNameScopeId : public IndexBase { } }; -constexpr SemanticsNameScopeId SemanticsNameScopeId::Invalid = - SemanticsNameScopeId(SemanticsNameScopeId::InvalidIndex); +constexpr NameScopeId NameScopeId::Invalid = + NameScopeId(NameScopeId::InvalidIndex); // The ID of a node block. -struct SemanticsNodeBlockId : public IndexBase { - // All SemanticsIR instances must provide the 0th node block as empty. - static const SemanticsNodeBlockId Empty; +struct NodeBlockId : public IndexBase { + // All File instances must provide the 0th node block as empty. + static const NodeBlockId Empty; // An explicitly invalid ID. - static const SemanticsNodeBlockId Invalid; + static const NodeBlockId Invalid; // An ID for unreachable code. - static const SemanticsNodeBlockId Unreachable; + static const NodeBlockId Unreachable; using IndexBase::IndexBase; auto Print(llvm::raw_ostream& out) const -> void { @@ -138,15 +136,14 @@ struct SemanticsNodeBlockId : public IndexBase { } }; -constexpr SemanticsNodeBlockId SemanticsNodeBlockId::Empty = - SemanticsNodeBlockId(0); -constexpr SemanticsNodeBlockId SemanticsNodeBlockId::Invalid = - SemanticsNodeBlockId(SemanticsNodeBlockId::InvalidIndex); -constexpr SemanticsNodeBlockId SemanticsNodeBlockId::Unreachable = - SemanticsNodeBlockId(SemanticsNodeBlockId::InvalidIndex - 1); +constexpr NodeBlockId NodeBlockId::Empty = NodeBlockId(0); +constexpr NodeBlockId NodeBlockId::Invalid = + NodeBlockId(NodeBlockId::InvalidIndex); +constexpr NodeBlockId NodeBlockId::Unreachable = + NodeBlockId(NodeBlockId::InvalidIndex - 1); // The ID of a real literal. -struct SemanticsRealLiteralId : public IndexBase { +struct RealLiteralId : public IndexBase { using IndexBase::IndexBase; auto Print(llvm::raw_ostream& out) const -> void { out << "real"; @@ -155,7 +152,7 @@ struct SemanticsRealLiteralId : public IndexBase { }; // The ID of a string. -struct SemanticsStringId : public IndexBase { +struct StringId : public IndexBase { using IndexBase::IndexBase; auto Print(llvm::raw_ostream& out) const -> void { out << "str"; @@ -164,15 +161,15 @@ struct SemanticsStringId : public IndexBase { }; // The ID of a node block. -struct SemanticsTypeId : public IndexBase { +struct TypeId : public IndexBase { // The builtin TypeType. - static const SemanticsTypeId TypeType; + static const TypeId TypeType; // The builtin Error. - static const SemanticsTypeId Error; + static const TypeId Error; // An explicitly invalid ID. - static const SemanticsTypeId Invalid; + static const TypeId Invalid; using IndexBase::IndexBase; auto Print(llvm::raw_ostream& out) const -> void { @@ -187,15 +184,12 @@ struct SemanticsTypeId : public IndexBase { } }; -constexpr SemanticsTypeId SemanticsTypeId::TypeType = - SemanticsTypeId(SemanticsTypeId::InvalidIndex - 2); -constexpr SemanticsTypeId SemanticsTypeId::Error = - SemanticsTypeId(SemanticsTypeId::InvalidIndex - 1); -constexpr SemanticsTypeId SemanticsTypeId::Invalid = - SemanticsTypeId(SemanticsTypeId::InvalidIndex); +constexpr TypeId TypeId::TypeType = TypeId(TypeId::InvalidIndex - 2); +constexpr TypeId TypeId::Error = TypeId(TypeId::InvalidIndex - 1); +constexpr TypeId TypeId::Invalid = TypeId(TypeId::InvalidIndex); // The ID of a type block. -struct SemanticsTypeBlockId : public IndexBase { +struct TypeBlockId : public IndexBase { using IndexBase::IndexBase; auto Print(llvm::raw_ostream& out) const -> void { out << "typeBlock"; @@ -204,7 +198,7 @@ struct SemanticsTypeBlockId : public IndexBase { }; // An index for member access. -struct SemanticsMemberIndex : public IndexBase { +struct MemberIndex : public IndexBase { using IndexBase::IndexBase; auto Print(llvm::raw_ostream& out) const -> void { out << "member"; @@ -212,7 +206,7 @@ struct SemanticsMemberIndex : public IndexBase { } }; -// The standard structure for SemanticsNode. This is trying to provide a minimal +// The standard structure for Node. This is trying to provide a minimal // amount of information for a node: // // - parse_node for error placement. @@ -220,9 +214,9 @@ struct SemanticsMemberIndex : public IndexBase { // - type_id for quick type checking. // - Up to two Kind-specific members. // -// For each Kind in SemanticsNodeKind, a typical flow looks like: +// For each Kind in NodeKind, a typical flow looks like: // -// - Create a `SemanticsNode` using `SemanticsNode::Kind::Make()` +// - Create a `Node` using `Node::Kind::Make()` // - Access cross-Kind members using `node.type_id()` and similar. // - Access Kind-specific members using `node.GetAsKind()`, which depending on // the number of members will return one of NoArgs, a single value, or a @@ -232,7 +226,7 @@ struct SemanticsMemberIndex : public IndexBase { // // Internally, each Kind uses the `Factory*` types to provide a boilerplate // `Make` and `Get` methods. -class SemanticsNode { +class Node { public: struct NoArgs {}; @@ -242,19 +236,19 @@ class SemanticsNode { // Factory templates need to use the raw enum instead of the class wrapper. using KindTemplateEnum = Internal::SemanticsNodeKindRawEnum; - // Provides Make and Get to support 0, 1, or 2 arguments for a SemanticsNode. + // Provides Make and Get to support 0, 1, or 2 arguments for a Node. // These are protected so that child factories can opt in to what pieces they // want to use. template class FactoryBase { protected: - static auto Make(ParseTree::Node parse_node, SemanticsTypeId type_id, - ArgTypes... arg_ids) -> SemanticsNode { - return SemanticsNode(parse_node, SemanticsNodeKind::Create(Kind), type_id, - arg_ids.index...); + static auto Make(ParseTree::Node parse_node, TypeId type_id, + ArgTypes... arg_ids) -> Node { + return Node(parse_node, NodeKind::Create(Kind), type_id, + arg_ids.index...); } - static auto Get(SemanticsNode node) { + static auto Get(Node node) { struct Unused {}; return GetImpl(node); } @@ -262,17 +256,17 @@ class SemanticsNode { private: // GetImpl handles the different return types based on ArgTypes. template - static auto GetImpl(SemanticsNode node) -> std::pair { + static auto GetImpl(Node node) -> std::pair { CARBON_CHECK(node.kind() == Kind); return {Arg0Type(node.arg0_), Arg1Type(node.arg1_)}; } template - static auto GetImpl(SemanticsNode node) -> Arg0Type { + static auto GetImpl(Node node) -> Arg0Type { CARBON_CHECK(node.kind() == Kind); return Arg0Type(node.arg0_); } template - static auto GetImpl(SemanticsNode node) -> NoArgs { + static auto GetImpl(Node node) -> NoArgs { CARBON_CHECK(node.kind() == Kind); return NoArgs(); } @@ -292,92 +286,76 @@ class SemanticsNode { class FactoryNoType : public FactoryBase { public: static auto Make(ParseTree::Node parse_node, ArgTypes... args) { - return FactoryBase::Make( - parse_node, SemanticsTypeId::Invalid, args...); + return FactoryBase::Make(parse_node, TypeId::Invalid, + args...); } using FactoryBase::Get; }; public: - // Invalid is in the SemanticsNodeKind enum, but should never be used. + // Invalid is in the NodeKind enum, but should never be used. class Invalid { public: - static auto Get(SemanticsNode /*node*/) -> SemanticsNode::NoArgs { + static auto Get(Node /*node*/) -> Node::NoArgs { CARBON_FATAL() << "Invalid access"; } }; - using AddressOf = SemanticsNode::Factory; + using AddressOf = Node::Factory; using ArrayIndex = - Factory; + Factory; - using ArrayType = - SemanticsNode::Factory; + using ArrayType = Node::Factory; - using ArrayValue = Factory; + using ArrayValue = Factory; - using Assign = SemanticsNode::FactoryNoType; + using Assign = Node::FactoryNoType; - using BinaryOperatorAdd = - SemanticsNode::Factory; + using BinaryOperatorAdd = Node::Factory; - using BlockArg = - Factory; + using BlockArg = Factory; - using BoolLiteral = - Factory; + using BoolLiteral = Factory; - using Branch = FactoryNoType; + using Branch = FactoryNoType; - using BranchIf = FactoryNoType; + using BranchIf = FactoryNoType; - using BranchWithArg = FactoryNoType; + using BranchWithArg = + FactoryNoType; class Builtin { public: - static auto Make(SemanticsBuiltinKind builtin_kind, SemanticsTypeId type_id) - -> SemanticsNode { + static auto Make(BuiltinKind builtin_kind, TypeId type_id) -> Node { // Builtins won't have a ParseTree node associated, so we provide the // default invalid one. // This can't use the standard Make function because of the `AsInt()` cast // instead of `.index`. - return SemanticsNode(ParseTree::Node::Invalid, SemanticsNodeKind::Builtin, - type_id, builtin_kind.AsInt()); + return Node(ParseTree::Node::Invalid, NodeKind::Builtin, type_id, + builtin_kind.AsInt()); } - static auto Get(SemanticsNode node) -> SemanticsBuiltinKind { - return SemanticsBuiltinKind::FromInt(node.arg0_); + static auto Get(Node node) -> BuiltinKind { + return BuiltinKind::FromInt(node.arg0_); } }; - using Call = - Factory; + using Call = Factory; - using ConstType = - Factory; + using ConstType = Factory; class CrossReference - : public FactoryBase { + : public FactoryBase { public: - static auto Make(SemanticsTypeId type_id, SemanticsCrossReferenceIRId ir_id, - SemanticsNodeId node_id) -> SemanticsNode { + static auto Make(TypeId type_id, CrossReferenceIRId ir_id, NodeId node_id) + -> Node { // A node's parse tree node must refer to a node in the current parse // tree. This cannot use the cross-referenced node's parse tree node // because it will be in a different parse tree. @@ -387,96 +365,83 @@ class SemanticsNode { using FactoryBase::Get; }; - using Dereference = - Factory; + using Dereference = Factory; using FunctionDeclaration = - FactoryNoType; + FactoryNoType; - using IntegerLiteral = Factory; + using IntegerLiteral = + Factory; - using Namespace = FactoryNoType; + using Namespace = + FactoryNoType; - using Parameter = - Factory; + using Parameter = Factory; - using PointerType = - Factory; + using PointerType = Factory; - using RealLiteral = Factory; + using RealLiteral = Factory; - using Return = FactoryNoType; + using Return = FactoryNoType; - using ReturnExpression = FactoryNoType; + using ReturnExpression = + FactoryNoType; - using StringLiteral = Factory; + using StringLiteral = + Factory; - using StructAccess = - Factory; + using StructAccess = Factory; - using StructType = - Factory; + using StructType = Factory; using StructTypeField = - FactoryNoType; + FactoryNoType; - using StructValue = - Factory; + using StructValue = Factory; - using StubReference = - Factory; + using StubReference = Factory; using TupleIndex = - Factory; + Factory; - using TupleType = - Factory; + using TupleType = Factory; - using TupleValue = - Factory; + using TupleValue = Factory; - using UnaryOperatorNot = Factory; + using UnaryOperatorNot = + Factory; - using VarStorage = - Factory; + using VarStorage = Factory; - explicit SemanticsNode() - : SemanticsNode(ParseTree::Node::Invalid, SemanticsNodeKind::Invalid, - SemanticsTypeId::Invalid) {} + explicit Node() + : Node(ParseTree::Node::Invalid, NodeKind::Invalid, TypeId::Invalid) {} // Provide `node.GetAsKind()` as an instance method for all kinds, essentially - // an alias for`SemanticsNode::Kind::Get(node)`. + // an alias for`Node::Kind::Get(node)`. #define CARBON_SEMANTICS_NODE_KIND(Name) \ auto GetAs##Name() const { return Name::Get(*this); } #include "toolchain/semantics/semantics_node_kind.def" auto parse_node() const -> ParseTree::Node { return parse_node_; } - auto kind() const -> SemanticsNodeKind { return kind_; } + auto kind() const -> NodeKind { return kind_; } // Gets the type of the value produced by evaluating this node. - auto type_id() const -> SemanticsTypeId { return type_id_; } + auto type_id() const -> TypeId { return type_id_; } - auto Print(llvm::raw_ostream& out) const -> void; + friend auto operator<<(llvm::raw_ostream& out, const Node& node) + -> llvm::raw_ostream&; + LLVM_DUMP_METHOD void Dump() const { llvm::errs() << *this; } private: // Builtins have peculiar construction, so they are a friend rather than using // a factory base class. - friend struct SemanticsNodeForBuiltin; + friend struct NodeForBuiltin; - explicit SemanticsNode(ParseTree::Node parse_node, SemanticsNodeKind kind, - SemanticsTypeId type_id, - int32_t arg0 = SemanticsNodeId::InvalidIndex, - int32_t arg1 = SemanticsNodeId::InvalidIndex) + explicit Node(ParseTree::Node parse_node, NodeKind kind, TypeId type_id, + int32_t arg0 = NodeId::InvalidIndex, + int32_t arg1 = NodeId::InvalidIndex) : parse_node_(parse_node), kind_(kind), type_id_(type_id), @@ -484,8 +449,8 @@ class SemanticsNode { arg1_(arg1) {} ParseTree::Node parse_node_; - SemanticsNodeKind kind_; - SemanticsTypeId type_id_; + NodeKind kind_; + TypeId type_id_; // Use GetAsKind to access arg0 and arg1. int32_t arg0_; @@ -493,15 +458,15 @@ class SemanticsNode { }; // TODO: This is currently 20 bytes because we sometimes have 2 arguments for a -// pair of SemanticsNodes. However, SemanticsNodeKind is 1 byte; if args -// were 3.5 bytes, we could potentially shrink SemanticsNode by 4 bytes. This +// pair of Nodes. However, NodeKind is 1 byte; if args +// were 3.5 bytes, we could potentially shrink Node by 4 bytes. This // may be worth investigating further. -static_assert(sizeof(SemanticsNode) == 20, "Unexpected SemanticsNode size"); +static_assert(sizeof(Node) == 20, "Unexpected Node size"); // Provides base support for use of Id types as DenseMap/DenseSet keys. // Instantiated below. template -struct SemanticsIdMapInfo { +struct IdMapInfo { static inline auto getEmptyKey() -> Id { return Id(llvm::DenseMapInfo::getEmptyKey()); } @@ -519,17 +484,17 @@ struct SemanticsIdMapInfo { } }; -} // namespace Carbon +} // namespace Carbon::SemIR // Support use of Id types as DenseMap/DenseSet keys. template <> -struct llvm::DenseMapInfo - : public Carbon::SemanticsIdMapInfo {}; +struct llvm::DenseMapInfo + : public Carbon::SemIR::IdMapInfo {}; template <> -struct llvm::DenseMapInfo - : public Carbon::SemanticsIdMapInfo {}; +struct llvm::DenseMapInfo + : public Carbon::SemIR::IdMapInfo {}; template <> -struct llvm::DenseMapInfo - : public Carbon::SemanticsIdMapInfo {}; +struct llvm::DenseMapInfo + : public Carbon::SemIR::IdMapInfo {}; #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_NODE_H_ diff --git a/toolchain/semantics/semantics_node_block_stack.cpp b/toolchain/semantics/semantics_node_block_stack.cpp index 361d491aa941..90097bbc7ed2 100644 --- a/toolchain/semantics/semantics_node_block_stack.cpp +++ b/toolchain/semantics/semantics_node_block_stack.cpp @@ -8,16 +8,16 @@ #include "llvm/ADT/STLExtras.h" #include "toolchain/semantics/semantics_node.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsNodeBlockStack::Push(SemanticsNodeBlockId id) -> void { +auto NodeBlockStack::Push(SemIR::NodeBlockId id) -> void { CARBON_VLOG() << name_ << " Push " << stack_.size() << "\n"; CARBON_CHECK(stack_.size() < (1 << 20)) << "Excessive stack size: likely infinite loop"; stack_.push_back(id); } -auto SemanticsNodeBlockStack::PeekForAdd() -> SemanticsNodeBlockId { +auto NodeBlockStack::PeekForAdd() -> SemIR::NodeBlockId { CARBON_CHECK(!stack_.empty()) << "no current block"; auto& back = stack_.back(); if (!back.is_valid()) { @@ -28,17 +28,17 @@ auto SemanticsNodeBlockStack::PeekForAdd() -> SemanticsNodeBlockId { return back; } -auto SemanticsNodeBlockStack::Pop() -> SemanticsNodeBlockId { +auto NodeBlockStack::Pop() -> SemIR::NodeBlockId { CARBON_CHECK(!stack_.empty()) << "no current block"; auto back = stack_.pop_back_val(); CARBON_VLOG() << name_ << " Pop " << stack_.size() << ": " << back << "\n"; if (!back.is_valid()) { - return SemanticsNodeBlockId::Empty; + return SemIR::NodeBlockId::Empty; } return back; } -auto SemanticsNodeBlockStack::PrintForStackDump(llvm::raw_ostream& output) const +auto NodeBlockStack::PrintForStackDump(llvm::raw_ostream& output) const -> void { output << name_ << ":\n"; for (auto [i, entry] : llvm::enumerate(stack_)) { @@ -46,4 +46,4 @@ auto SemanticsNodeBlockStack::PrintForStackDump(llvm::raw_ostream& output) const } } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_node_block_stack.h b/toolchain/semantics/semantics_node_block_stack.h index fc972d8e7720..43daaa62a35e 100644 --- a/toolchain/semantics/semantics_node_block_stack.h +++ b/toolchain/semantics/semantics_node_block_stack.h @@ -11,58 +11,57 @@ #include "toolchain/semantics/semantics_ir.h" #include "toolchain/semantics/semantics_node.h" -namespace Carbon { +namespace Carbon::Check { -// Wraps the stack of node blocks for SemanticsParseTreeHandler. +// Wraps the stack of node blocks for Context. // // All pushes and pops will be vlogged. -class SemanticsNodeBlockStack { +class NodeBlockStack { public: - explicit SemanticsNodeBlockStack(llvm::StringLiteral name, - SemanticsIR& semantics_ir, - llvm::raw_ostream* vlog_stream) + explicit NodeBlockStack(llvm::StringLiteral name, SemIR::File& semantics_ir, + llvm::raw_ostream* vlog_stream) : name_(name), semantics_ir_(&semantics_ir), vlog_stream_(vlog_stream) {} // Pushes an existing node block. - auto Push(SemanticsNodeBlockId id) -> void; + auto Push(SemIR::NodeBlockId id) -> void; // Pushes a new node block. It will be invalid unless PeekForAdd is called in // order to support lazy allocation. - auto Push() -> void { Push(SemanticsNodeBlockId::Invalid); } + auto Push() -> void { Push(SemIR::NodeBlockId::Invalid); } // Pushes a new unreachable code block. - auto PushUnreachable() -> void { Push(SemanticsNodeBlockId::Unreachable); } + auto PushUnreachable() -> void { Push(SemIR::NodeBlockId::Unreachable); } // Allocates and pushes a new node block. - auto PushForAdd() -> SemanticsNodeBlockId { + auto PushForAdd() -> SemIR::NodeBlockId { Push(); return PeekForAdd(); } // Peeks at the top node block. This does not trigger lazy allocation, so the // returned node block may be invalid. - auto Peek() -> SemanticsNodeBlockId { + auto Peek() -> SemIR::NodeBlockId { CARBON_CHECK(!stack_.empty()) << "no current block"; return stack_.back(); } // Returns the top node block, allocating one if it's still invalid. - auto PeekForAdd() -> SemanticsNodeBlockId; + auto PeekForAdd() -> SemIR::NodeBlockId; // Pops the top node block. This will always return a valid node block; - // SemanticsNodeBlockId::Empty is returned if one wasn't allocated. - auto Pop() -> SemanticsNodeBlockId; + // SemIR::NodeBlockId::Empty is returned if one wasn't allocated. + auto Pop() -> SemIR::NodeBlockId; // Pops the top node block, ensuring that it is lazily allocated if it's // empty. For use when more nodes will be added to the block later. - auto PopForAdd() -> SemanticsNodeBlockId { + auto PopForAdd() -> SemIR::NodeBlockId { PeekForAdd(); return Pop(); } // Returns whether the current block is statically reachable. auto is_current_block_reachable() -> bool { - return Peek() != SemanticsNodeBlockId::Unreachable; + return Peek() != SemIR::NodeBlockId::Unreachable; } // Prints the stack for a stack dump. @@ -75,8 +74,8 @@ class SemanticsNodeBlockStack { // A name for debugging. llvm::StringLiteral name_; - // The underlying SemanticsIR instance. Always non-null. - SemanticsIR* semantics_ir_; + // The underlying SemIR::File instance. Always non-null. + SemIR::File* semantics_ir_; // Whether to print verbose output. llvm::raw_ostream* vlog_stream_; @@ -84,9 +83,9 @@ class SemanticsNodeBlockStack { // The actual stack. // PushEntry and PopEntry control modification in order to centralize // vlogging. - llvm::SmallVector stack_; + llvm::SmallVector stack_; }; -} // namespace Carbon +} // namespace Carbon::Check #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_NODE_BLOCK_STACK_H_ diff --git a/toolchain/semantics/semantics_node_kind.cpp b/toolchain/semantics/semantics_node_kind.cpp index 0d287d4155d8..00c5bb4d5524 100644 --- a/toolchain/semantics/semantics_node_kind.cpp +++ b/toolchain/semantics/semantics_node_kind.cpp @@ -20,19 +20,19 @@ CARBON_DEFINE_ENUM_CLASS_NAMES(SemanticsNodeKind) = { return Table[AsInt()]; } -auto SemanticsNodeKind::value_kind() const -> SemanticsNodeValueKind { - static constexpr SemanticsNodeValueKind Table[] = { -#define CARBON_SEMANTICS_NODE_KIND_WITH_VALUE_KIND(Name, ValueKind) \ - SemanticsNodeValueKind::ValueKind, +auto SemanticsNodeKind::value_kind() const -> SemIR::NodeValueKind { + static constexpr SemIR::NodeValueKind Table[] = { +#define CARBON_SEMANTICS_NODE_KIND_WITH_VALUE_KIND(Name, Kind) \ + SemIR::NodeValueKind::Kind, #include "toolchain/semantics/semantics_node_kind.def" }; return Table[AsInt()]; } -auto SemanticsNodeKind::terminator_kind() const -> SemanticsTerminatorKind { - static constexpr SemanticsTerminatorKind Table[] = { -#define CARBON_SEMANTICS_NODE_KIND_WITH_TERMINATOR_KIND(Name, TerminatorKind) \ - SemanticsTerminatorKind::TerminatorKind, +auto SemanticsNodeKind::terminator_kind() const -> SemIR::TerminatorKind { + static constexpr SemIR::TerminatorKind Table[] = { +#define CARBON_SEMANTICS_NODE_KIND_WITH_TERMINATOR_KIND(Name, Kind) \ + SemIR::TerminatorKind::Kind, #include "toolchain/semantics/semantics_node_kind.def" }; return Table[AsInt()]; diff --git a/toolchain/semantics/semantics_node_kind.h b/toolchain/semantics/semantics_node_kind.h index 8272dcbe6d8c..28994495a69c 100644 --- a/toolchain/semantics/semantics_node_kind.h +++ b/toolchain/semantics/semantics_node_kind.h @@ -10,15 +10,10 @@ #include "common/enum_base.h" #include "llvm/ADT/FoldingSet.h" -namespace Carbon { - -CARBON_DEFINE_RAW_ENUM_CLASS(SemanticsNodeKind, uint8_t) { -#define CARBON_SEMANTICS_NODE_KIND(Name) CARBON_RAW_ENUM_ENUMERATOR(Name) -#include "toolchain/semantics/semantics_node_kind.def" -}; +namespace Carbon::SemIR { // Whether a node produces or represents a value, and if so, what kind of value. -enum class SemanticsNodeValueKind { +enum class NodeValueKind { // This node doesn't produce a value, and shouldn't be referenced by other // nodes. None, @@ -33,7 +28,7 @@ enum class SemanticsNodeValueKind { // Whether a node is a terminator or part of the terminator sequence. The nodes // in a block appear in the order NotTerminator, then TerminatorSequence, then // Terminator, which is also the numerical order of these values. -enum class SemanticsTerminatorKind { +enum class TerminatorKind { // This node is not a terminator. NotTerminator, // This node is not itself a terminator, but forms part of a terminator @@ -43,6 +38,15 @@ enum class SemanticsTerminatorKind { Terminator, }; +} // namespace Carbon::SemIR + +namespace Carbon { + +CARBON_DEFINE_RAW_ENUM_CLASS(SemanticsNodeKind, uint8_t) { +#define CARBON_SEMANTICS_NODE_KIND(Name) CARBON_RAW_ENUM_ENUMERATOR(Name) +#include "toolchain/semantics/semantics_node_kind.def" +}; + class SemanticsNodeKind : public CARBON_ENUM_BASE(SemanticsNodeKind) { public: #define CARBON_SEMANTICS_NODE_KIND(Name) CARBON_ENUM_CONSTANT_DECLARATION(Name) @@ -54,14 +58,14 @@ class SemanticsNodeKind : public CARBON_ENUM_BASE(SemanticsNodeKind) { [[nodiscard]] auto ir_name() const -> llvm::StringRef; // Returns whether this kind of node is expected to produce a value. - [[nodiscard]] auto value_kind() const -> SemanticsNodeValueKind; + [[nodiscard]] auto value_kind() const -> SemIR::NodeValueKind; // Returns whether this node kind is a code block terminator, such as an // unconditional branch instruction, or part of the termination sequence, // such as a conditional branch instruction. The termination sequence of a // code block appears after all other instructions, and ends with a // terminator instruction. - [[nodiscard]] auto terminator_kind() const -> SemanticsTerminatorKind; + [[nodiscard]] auto terminator_kind() const -> SemIR::TerminatorKind; // Compute a fingerprint for this node kind, allowing its use as part of the // key in a `FoldingSet`. @@ -75,6 +79,11 @@ class SemanticsNodeKind : public CARBON_ENUM_BASE(SemanticsNodeKind) { // We expect the node kind to fit compactly into 8 bits. static_assert(sizeof(SemanticsNodeKind) == 1, "Kind objects include padding!"); +// TODO: Refactor EnumBase to remove the need for this alias. +namespace SemIR { +using NodeKind = SemanticsNodeKind; +} // namespace SemIR + } // namespace Carbon #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_NODE_KIND_H_ diff --git a/toolchain/semantics/semantics_node_stack.cpp b/toolchain/semantics/semantics_node_stack.cpp index 72b315df5200..ac13fc1b62e7 100644 --- a/toolchain/semantics/semantics_node_stack.cpp +++ b/toolchain/semantics/semantics_node_stack.cpp @@ -7,11 +7,10 @@ #include "llvm/ADT/STLExtras.h" #include "toolchain/semantics/semantics_node.h" -namespace Carbon { +namespace Carbon::Check { -auto SemanticsNodeStack::PrintForStackDump(llvm::raw_ostream& output) const - -> void { - output << "SemanticsNodeStack:\n"; +auto NodeStack::PrintForStackDump(llvm::raw_ostream& output) const -> void { + output << "NodeStack:\n"; for (auto [i, entry] : llvm::enumerate(stack_)) { auto parse_node_kind = parse_tree_->node_kind(entry.parse_node); output << "\t" << i << ".\t" << parse_node_kind; @@ -26,4 +25,4 @@ auto SemanticsNodeStack::PrintForStackDump(llvm::raw_ostream& output) const } } -} // namespace Carbon +} // namespace Carbon::Check diff --git a/toolchain/semantics/semantics_node_stack.h b/toolchain/semantics/semantics_node_stack.h index 6f3e14643253..5c6e404b83eb 100644 --- a/toolchain/semantics/semantics_node_stack.h +++ b/toolchain/semantics/semantics_node_stack.h @@ -13,9 +13,9 @@ #include "toolchain/parser/parse_tree.h" #include "toolchain/semantics/semantics_node.h" -namespace Carbon { +namespace Carbon::Check { -// Wraps the stack of nodes for SemanticsParseTreeHandler. +// Wraps the stack of nodes for Context. // // All pushes and pops will be vlogged. // @@ -28,10 +28,10 @@ namespace Carbon { // // These should be assumed API constraints unless otherwise mentioned on a // method. The main exception is PopAndIgnore, which doesn't do verification. -class SemanticsNodeStack { +class NodeStack { public: - explicit SemanticsNodeStack(const ParseTree& parse_tree, - llvm::raw_ostream* vlog_stream) + explicit NodeStack(const ParseTree& parse_tree, + llvm::raw_ostream* vlog_stream) : parse_tree_(&parse_tree), vlog_stream_(vlog_stream) {} // Pushes a solo parse tree node onto the stack. Used when there is no @@ -44,7 +44,7 @@ class SemanticsNodeStack { << parse_tree_->node_kind(parse_node) << " -> \n"; CARBON_CHECK(stack_.size() < (1 << 20)) << "Excessive stack size: likely infinite loop"; - stack_.push_back(Entry(parse_node, SemanticsNodeId::Invalid)); + stack_.push_back(Entry(parse_node, SemIR::NodeId::Invalid)); } // Pushes a parse tree node onto the stack with an ID. @@ -64,12 +64,12 @@ class SemanticsNodeStack { } // Pops the top of the stack without any verification. - auto PopAndIgnore() -> void { PopEntry(); } + auto PopAndIgnore() -> void { PopEntry(); } // Pops the top of the stack and returns the parse_node. template auto PopForSoloParseNode() -> ParseTree::Node { - Entry back = PopEntry(); + Entry back = PopEntry(); RequireIdKind(ParseNodeKind::Create(RequiredParseKind), IdKind::SoloParseNode); RequireParseKind(back.parse_node); @@ -85,8 +85,8 @@ class SemanticsNodeStack { // Pops an expression from the top of the stack and returns the parse_node and // the ID. auto PopExpressionWithParseNode() - -> std::pair { - return PopWithParseNode(); + -> std::pair { + return PopWithParseNode(); } // Pops the top of the stack and returns the parse_node and the ID. @@ -94,28 +94,28 @@ class SemanticsNodeStack { auto PopWithParseNode() -> auto { constexpr IdKind RequiredIdKind = ParseNodeKindToIdKind(ParseNodeKind::Create(RequiredParseKind)); - if constexpr (RequiredIdKind == IdKind::SemanticsNodeId) { - auto back = PopWithParseNode(); + if constexpr (RequiredIdKind == IdKind::NodeId) { + auto back = PopWithParseNode(); RequireParseKind(back.first); return back; } - if constexpr (RequiredIdKind == IdKind::SemanticsNodeBlockId) { - auto back = PopWithParseNode(); + if constexpr (RequiredIdKind == IdKind::NodeBlockId) { + auto back = PopWithParseNode(); RequireParseKind(back.first); return back; } - if constexpr (RequiredIdKind == IdKind::SemanticsFunctionId) { - auto back = PopWithParseNode(); + if constexpr (RequiredIdKind == IdKind::FunctionId) { + auto back = PopWithParseNode(); RequireParseKind(back.first); return back; } - if constexpr (RequiredIdKind == IdKind::SemanticsStringId) { - auto back = PopWithParseNode(); + if constexpr (RequiredIdKind == IdKind::StringId) { + auto back = PopWithParseNode(); RequireParseKind(back.first); return back; } - if constexpr (RequiredIdKind == IdKind::SemanticsTypeId) { - auto back = PopWithParseNode(); + if constexpr (RequiredIdKind == IdKind::TypeId) { + auto back = PopWithParseNode(); RequireParseKind(back.first); return back; } @@ -125,8 +125,8 @@ class SemanticsNodeStack { } // Pops an expression from the top of the stack and returns the ID. - // Expressions map multiple ParseNodeKinds to SemanticsNodeId always. - auto PopExpression() -> SemanticsNodeId { + // Expressions map multiple ParseNodeKinds to SemIR::NodeId always. + auto PopExpression() -> SemIR::NodeId { return PopExpressionWithParseNode().second; } @@ -146,20 +146,20 @@ class SemanticsNodeStack { RequireParseKind(back.parse_node); constexpr IdKind RequiredIdKind = ParseNodeKindToIdKind(ParseNodeKind::Create(RequiredParseKind)); - if constexpr (RequiredIdKind == IdKind::SemanticsNodeId) { - return back.id(); + if constexpr (RequiredIdKind == IdKind::NodeId) { + return back.id(); } - if constexpr (RequiredIdKind == IdKind::SemanticsNodeBlockId) { - return back.id(); + if constexpr (RequiredIdKind == IdKind::NodeBlockId) { + return back.id(); } - if constexpr (RequiredIdKind == IdKind::SemanticsFunctionId) { - return back.id(); + if constexpr (RequiredIdKind == IdKind::FunctionId) { + return back.id(); } - if constexpr (RequiredIdKind == IdKind::SemanticsStringId) { - return back.id(); + if constexpr (RequiredIdKind == IdKind::StringId) { + return back.id(); } - if constexpr (RequiredIdKind == IdKind::SemanticsTypeId) { - return back.id(); + if constexpr (RequiredIdKind == IdKind::TypeId) { + return back.id(); } CARBON_FATAL() << "Unpeekable IdKind for parse kind: " << ParseNodeKind::Create(RequiredParseKind) @@ -175,11 +175,11 @@ class SemanticsNodeStack { private: // Possible associated ID types. enum class IdKind { - SemanticsNodeId, - SemanticsNodeBlockId, - SemanticsFunctionId, - SemanticsStringId, - SemanticsTypeId, + NodeId, + NodeBlockId, + FunctionId, + StringId, + TypeId, // No associated ID type. SoloParseNode, // Not expected in the node stack. @@ -188,34 +188,33 @@ class SemanticsNodeStack { // An entry in stack_. struct Entry { - explicit Entry(ParseTree::Node parse_node, SemanticsNodeId node_id) + explicit Entry(ParseTree::Node parse_node, SemIR::NodeId node_id) : parse_node(parse_node), node_id(node_id) {} - explicit Entry(ParseTree::Node parse_node, - SemanticsNodeBlockId node_block_id) + explicit Entry(ParseTree::Node parse_node, SemIR::NodeBlockId node_block_id) : parse_node(parse_node), node_block_id(node_block_id) {} - explicit Entry(ParseTree::Node parse_node, SemanticsFunctionId function_id) + explicit Entry(ParseTree::Node parse_node, SemIR::FunctionId function_id) : parse_node(parse_node), function_id(function_id) {} - explicit Entry(ParseTree::Node parse_node, SemanticsStringId name_id) + explicit Entry(ParseTree::Node parse_node, SemIR::StringId name_id) : parse_node(parse_node), name_id(name_id) {} - explicit Entry(ParseTree::Node parse_node, SemanticsTypeId type_id) + explicit Entry(ParseTree::Node parse_node, SemIR::TypeId type_id) : parse_node(parse_node), type_id(type_id) {} // Returns the appropriate ID basaed on type. template auto id() -> T& { - if constexpr (std::is_same()) { + if constexpr (std::is_same()) { return node_id; } - if constexpr (std::is_same()) { + if constexpr (std::is_same()) { return node_block_id; } - if constexpr (std::is_same()) { + if constexpr (std::is_same()) { return function_id; } - if constexpr (std::is_same()) { + if constexpr (std::is_same()) { return name_id; } - if constexpr (std::is_same()) { + if constexpr (std::is_same()) { return type_id; } } @@ -229,11 +228,11 @@ class SemanticsNodeStack { // A discriminator isn't needed because the caller can determine which field // is used based on the ParseNodeKind. union { - SemanticsNodeId node_id; - SemanticsNodeBlockId node_block_id; - SemanticsFunctionId function_id; - SemanticsStringId name_id; - SemanticsTypeId type_id; + SemIR::NodeId node_id; + SemIR::NodeBlockId node_block_id; + SemIR::FunctionId function_id; + SemIR::StringId name_id; + SemIR::TypeId type_id; }; }; static_assert(sizeof(Entry) == 8, "Unexpected Entry size"); @@ -260,17 +259,17 @@ class SemanticsNodeStack { case ParseNodeKind::StructFieldType: case ParseNodeKind::StructTypeLiteral: case ParseNodeKind::TupleLiteral: - return IdKind::SemanticsNodeId; + return IdKind::NodeId; case ParseNodeKind::IfExpressionThen: case ParseNodeKind::IfStatementElse: case ParseNodeKind::ParameterList: - return IdKind::SemanticsNodeBlockId; + return IdKind::NodeBlockId; case ParseNodeKind::FunctionDefinitionStart: - return IdKind::SemanticsFunctionId; + return IdKind::FunctionId; case ParseNodeKind::Name: - return IdKind::SemanticsStringId; + return IdKind::StringId; case ParseNodeKind::ReturnType: - return IdKind::SemanticsTypeId; + return IdKind::TypeId; case ParseNodeKind::ArrayExpressionSemi: case ParseNodeKind::CodeBlockStart: case ParseNodeKind::FunctionIntroducer: @@ -293,20 +292,20 @@ class SemanticsNodeStack { // ParseNodeKindToIdKind. template static constexpr auto IdTypeToIdKind() -> IdKind { - if constexpr (std::is_same_v) { - return IdKind::SemanticsNodeId; + if constexpr (std::is_same_v) { + return IdKind::NodeId; } - if constexpr (std::is_same_v) { - return IdKind::SemanticsNodeBlockId; + if constexpr (std::is_same_v) { + return IdKind::NodeBlockId; } - if constexpr (std::is_same_v) { - return IdKind::SemanticsFunctionId; + if constexpr (std::is_same_v) { + return IdKind::FunctionId; } - if constexpr (std::is_same_v) { - return IdKind::SemanticsStringId; + if constexpr (std::is_same_v) { + return IdKind::StringId; } - if constexpr (std::is_same_v) { - return IdKind::SemanticsTypeId; + if constexpr (std::is_same_v) { + return IdKind::TypeId; } } @@ -356,6 +355,6 @@ class SemanticsNodeStack { llvm::SmallVector stack_; }; -} // namespace Carbon +} // namespace Carbon::Check #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_NODE_STACK_H_