mirror of
https://github.com/carbon-language/carbon-lang.git
synced 2026-11-10 12:28:25 +00:00
Initial support for fn expressions. (#7893)
Support for `fn` expressions with the same feature set as `fn` declarations. In particular, there is no support for captures, positional parameters, `=>` bodies, or `auto` return types. Note that this results in two parse nodes for each `=>` token. That's a bug, but it matches the behavior of function declarations, and will be fixed in a follow-up change. Assisted-by: Gemini via Antigravity
This commit is contained in:
1 parent
66bf1415ac
commit
1b0a5709e6
24 files changed
+2015
-308
No files matched your search
@@ -7,6 +7,7 @@
|
||||
#include "common/find.h"
|
||||
#include "toolchain/base/kind_switch.h"
|
||||
#include "toolchain/check/action.h"
|
||||
#include "toolchain/check/control_flow.h"
|
||||
#include "toolchain/check/convert.h"
|
||||
#include "toolchain/check/eval.h"
|
||||
#include "toolchain/check/generic.h"
|
||||
@@ -14,6 +15,7 @@
|
||||
#include "toolchain/check/merge.h"
|
||||
#include "toolchain/check/pattern.h"
|
||||
#include "toolchain/check/pattern_match.h"
|
||||
#include "toolchain/check/return.h"
|
||||
#include "toolchain/check/scope_stack.h"
|
||||
#include "toolchain/check/type.h"
|
||||
#include "toolchain/check/type_completion.h"
|
||||
@@ -454,6 +456,170 @@ auto MakeFunctionDecl(Context& context, SemIR::LocId loc_id,
|
||||
return {decl_id, function_decl.function_id};
|
||||
}
|
||||
|
||||
// Diagnoses when positional params aren't supported. Reassigns the pattern
|
||||
// block if needed.
|
||||
static auto DiagnosePositionalParams(Context& context,
|
||||
SemIR::Function& function_info) -> void {
|
||||
if (function_info.param_patterns_id.has_value()) {
|
||||
return;
|
||||
}
|
||||
|
||||
context.TODO(function_info.latest_decl_id(),
|
||||
"function with positional parameters");
|
||||
function_info.param_patterns_id = SemIR::InstBlockId::Empty;
|
||||
}
|
||||
|
||||
// For the top-level parameter patterns list, and for any level of nested tuple
|
||||
// patterns, ensure that if a subpattern provides a default value, all
|
||||
// subsequent patterns at that level of nesting must provide a default value as
|
||||
// well. Returns the number of default values provided at the top level of the
|
||||
// function parameter, useful for efficient arity checking in callers later on.
|
||||
//
|
||||
// TODO: per https://github.com/carbon-language/carbon-lang/issues/7529, this
|
||||
// should also consider automatically supplied defaults for fully-specified
|
||||
// tuple subpatterns, and consider them as having a default for the purposes
|
||||
// of the out-of-order detection. It will also need to detect the error
|
||||
// condition when a default is also specified for those fully-specified tuple
|
||||
// subpatterns.
|
||||
static auto CheckDefaults(Context& context, SemIR::Function& function)
|
||||
-> int32_t {
|
||||
if (!function.param_patterns_id.has_value()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
struct PatternLevelState {
|
||||
// The inst ids of the subpatterns on this level of tuple subpattern
|
||||
// nesting, treated as a work list, so in reverse order of declaration.
|
||||
llvm::SmallVector<SemIR::InstId> subpattern_ids;
|
||||
|
||||
// If patterns at this level of nesting have default values, this refers
|
||||
// to the first instruction to specify a default, useful for diagnostics.
|
||||
SemIR::InstId first_pattern_with_default = SemIR::InstId::None;
|
||||
|
||||
// If we encounter a tuple-pattern during processing, we suspend processing
|
||||
// of this pattern level, in the middle of processing a single pattern from
|
||||
// root to leaves. So we record the current state of processing of a single
|
||||
// pattern to return to it after processing any tuple subpatterns.
|
||||
|
||||
// True if the current pattern being processed has a default value
|
||||
// specified.
|
||||
bool current_pattern_has_default = false;
|
||||
|
||||
// The current pattern we are processing, stored separately since it's been
|
||||
// popped from the `pattern_work_list` and already processed, just may need
|
||||
// subsequent processing.
|
||||
SemIR::InstId current_id = SemIR::InstId::None;
|
||||
|
||||
// A work list of patterns to be processed at this level of nesting.
|
||||
llvm::SmallVector<SemIR::InstId> pattern_work_list;
|
||||
|
||||
// A list of subpatterns missing required defaults, to coalesce error
|
||||
// reporting into a single diagnostic.
|
||||
llvm::SmallVector<SemIR::InstId> patterns_missing_defaults;
|
||||
|
||||
// A count of the number of patterns on this level that have defaults.
|
||||
int32_t default_count = 0;
|
||||
};
|
||||
|
||||
llvm::SmallVector<PatternLevelState> level_state_stack;
|
||||
size_t default_count = 0;
|
||||
level_state_stack.push_back({});
|
||||
llvm::append_range(
|
||||
level_state_stack.back().subpattern_ids,
|
||||
llvm::reverse(context.inst_blocks().Get(function.param_patterns_id)));
|
||||
|
||||
while (!level_state_stack.empty()) {
|
||||
PatternLevelState* state = &level_state_stack.back();
|
||||
while (!state->subpattern_ids.empty() ||
|
||||
!state->pattern_work_list.empty() || state->current_id.has_value()) {
|
||||
// If we're not resuming processing a pattern from a nested state, start
|
||||
// processing the next subpattern.
|
||||
if (!state->current_id.has_value()) {
|
||||
state->pattern_work_list.push_back(
|
||||
state->subpattern_ids.pop_back_val());
|
||||
state->current_pattern_has_default = false;
|
||||
}
|
||||
while (!state->pattern_work_list.empty()) {
|
||||
state->current_id = state->pattern_work_list.pop_back_val();
|
||||
auto inst = context.insts().Get(state->current_id);
|
||||
CARBON_KIND_SWITCH(inst) {
|
||||
case CARBON_KIND(SemIR::DefaultValuePattern default_value_pattern): {
|
||||
state->current_pattern_has_default = true;
|
||||
state->default_count += 1;
|
||||
state->pattern_work_list.push_back(
|
||||
default_value_pattern.subpattern_id);
|
||||
break;
|
||||
}
|
||||
case CARBON_KIND(
|
||||
SemIR::WrapperBindingPattern wrapper_binding_pattern): {
|
||||
state->pattern_work_list.push_back(
|
||||
wrapper_binding_pattern.subpattern_id);
|
||||
break;
|
||||
}
|
||||
case CARBON_KIND(SemIR::TuplePattern tuple_pattern): {
|
||||
auto elements =
|
||||
context.inst_blocks().Get(tuple_pattern.elements_id);
|
||||
if (!elements.empty()) {
|
||||
// Start a new state for the nested tuple pattern elements.
|
||||
level_state_stack.push_back({});
|
||||
state = &level_state_stack.back();
|
||||
llvm::append_range(state->subpattern_ids,
|
||||
llvm::reverse(elements));
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
// We only process patterns containing subpatterns, so this is an
|
||||
// intentional no-op.
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Finished processing this subpattern, detect a missing default if
|
||||
// required.
|
||||
if (state->current_pattern_has_default &&
|
||||
!state->first_pattern_with_default.has_value()) {
|
||||
state->first_pattern_with_default = state->current_id;
|
||||
} else if (!state->current_pattern_has_default &&
|
||||
state->first_pattern_with_default.has_value()) {
|
||||
state->patterns_missing_defaults.push_back(state->current_id);
|
||||
}
|
||||
state->current_id = SemIR::InstId::None;
|
||||
}
|
||||
// Finished processing this tuple-pattern, emit diagnostics if any.
|
||||
if (!state->patterns_missing_defaults.empty()) {
|
||||
CARBON_DIAGNOSTIC(RequiredPatternDefaultValueMissing, Error,
|
||||
"this pattern is missing a required default value.");
|
||||
CARBON_DIAGNOSTIC(RequiredPatternDefaultValueFirstDefault, Note,
|
||||
"all patterns to the right of this first pattern with "
|
||||
"a default value must also specify a default value.");
|
||||
CARBON_DIAGNOSTIC(
|
||||
RequiredPatternDefaultValueMissingAdditional, Note,
|
||||
"this pattern is also missing a required default value.");
|
||||
auto inst_ref = llvm::ArrayRef(state->patterns_missing_defaults);
|
||||
auto builder = context.emitter().Build(
|
||||
inst_ref.consume_front(), RequiredPatternDefaultValueMissing);
|
||||
for (auto inst_id : inst_ref) {
|
||||
builder.Note(inst_id, RequiredPatternDefaultValueMissingAdditional);
|
||||
}
|
||||
builder.Note(state->first_pattern_with_default,
|
||||
RequiredPatternDefaultValueFirstDefault);
|
||||
builder.Emit();
|
||||
}
|
||||
|
||||
// Extract the count from the level we just completed, overwriting any
|
||||
// nested level value extracted previously.
|
||||
default_count = level_state_stack.back().default_count;
|
||||
level_state_stack.pop_back();
|
||||
}
|
||||
|
||||
return default_count;
|
||||
}
|
||||
|
||||
auto CheckFunctionParams(Context& context, SemIR::Function& function) -> void {
|
||||
function.default_value_arity = CheckDefaults(context, function);
|
||||
DiagnosePositionalParams(context, function);
|
||||
}
|
||||
|
||||
auto StartFunctionDefinition(Context& context, SemIR::InstId decl_id,
|
||||
SemIR::FunctionId function_id) -> void {
|
||||
// Create the function scope and the entry block.
|
||||
@@ -467,6 +633,23 @@ auto StartFunctionDefinition(Context& context, SemIR::InstId decl_id,
|
||||
CheckFunctionDefinitionSignature(context, function_id);
|
||||
}
|
||||
|
||||
auto CheckFunctionReturnOnFinish(Context& context, Parse::NodeId node_id,
|
||||
SemIR::FunctionId function_id) -> void {
|
||||
// If the `}` of the function is reachable, reject if we need a return value
|
||||
// and otherwise add an implicit `return;`.
|
||||
if (IsCurrentPositionReachable(context)) {
|
||||
if (context.functions().Get(function_id).return_form_inst_id.has_value()) {
|
||||
CARBON_DIAGNOSTIC(
|
||||
MissingReturnStatement, Error,
|
||||
"missing `return` at end of function with declared return type");
|
||||
context.emitter().Emit(LocIdForDiagnostics::TokenOnly(node_id),
|
||||
MissingReturnStatement);
|
||||
} else {
|
||||
AddReturnInstWithCleanups(context, node_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
auto FinishFunctionDefinition(Context& context, SemIR::FunctionId function_id)
|
||||
-> void {
|
||||
context.inst_block_stack().Pop();
|
||||
|
||||
@@ -125,12 +125,21 @@ auto MakeFunctionDecl(Context& context, SemIR::LocId loc_id,
|
||||
bool is_definition, SemIR::Function function)
|
||||
-> std::pair<SemIR::InstId, SemIR::FunctionId>;
|
||||
|
||||
// Checks that a function's parameter patterns have valid default values and
|
||||
// diagnoses unsupported positional parameters.
|
||||
auto CheckFunctionParams(Context& context, SemIR::Function& function) -> void;
|
||||
|
||||
// Starts a function definition. Handles necessary stack setup, creating the
|
||||
// function scope and entry block, and definition validation. This is used for
|
||||
// both generated functions/thunks and user-declared functions.
|
||||
auto StartFunctionDefinition(Context& context, SemIR::InstId decl_id,
|
||||
SemIR::FunctionId function_id) -> void;
|
||||
|
||||
// Checks that a function definition has a `return` at the end if required, or
|
||||
// adds an implicit `return;` if reachable.
|
||||
auto CheckFunctionReturnOnFinish(Context& context, Parse::NodeId node_id,
|
||||
SemIR::FunctionId function_id) -> void;
|
||||
|
||||
// Finishes definitions started by `StartFunctionDefinition`.
|
||||
auto FinishFunctionDefinition(Context& context, SemIR::FunctionId function_id)
|
||||
-> void;
|
||||
|
||||
@@ -360,165 +360,6 @@ static auto RequestVtableIfVirtual(
|
||||
context.vtable_stack().AddInstId(decl_id);
|
||||
}
|
||||
|
||||
// Diagnoses when positional params aren't supported. Reassigns the pattern
|
||||
// block if needed.
|
||||
static auto DiagnosePositionalParams(Context& context,
|
||||
SemIR::Function& function_info) -> void {
|
||||
if (function_info.param_patterns_id.has_value()) {
|
||||
return;
|
||||
}
|
||||
|
||||
context.TODO(function_info.latest_decl_id(),
|
||||
"function with positional parameters");
|
||||
function_info.param_patterns_id = SemIR::InstBlockId::Empty;
|
||||
}
|
||||
|
||||
// For the top-level parameter patterns list, and for any level of nested tuple
|
||||
// patterns, ensure that if a subpattern provides a default value, all
|
||||
// subsequent patterns at that level of nesting must provide a default value as
|
||||
// well. Returns the number of default values provided at the top level of the
|
||||
// function parameter, useful for efficient arity checking in callers later on.
|
||||
//
|
||||
// TODO: per https://github.com/carbon-language/carbon-lang/issues/7529, this
|
||||
// should also consider automatically supplied defaults for fully-specified
|
||||
// tuple subpatterns, and consider them as having a default for the purposes
|
||||
// of the out-of-order detection. It will also need to detect the error
|
||||
// condition when a default is also specified for those fully-specified tuple
|
||||
// subpatterns.
|
||||
static auto CheckDefaults(Context& context, SemIR::Function& function)
|
||||
-> int32_t {
|
||||
if (!function.param_patterns_id.has_value()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
struct PatternLevelState {
|
||||
// The inst ids of the subpatterns on this level of tuple subpattern
|
||||
// nesting, treated as a work list, so in reverse order of declaration.
|
||||
llvm::SmallVector<SemIR::InstId> subpattern_ids;
|
||||
|
||||
// If patterns at this level of nesting have default values, this refers
|
||||
// to the first instruction to specify a default, useful for diagnostics.
|
||||
SemIR::InstId first_pattern_with_default = SemIR::InstId::None;
|
||||
|
||||
// If we encounter a tuple-pattern during processing, we suspend processing
|
||||
// of this pattern level, in the middle of processing a single pattern from
|
||||
// root to leaves. So we record the current state of processing of a single
|
||||
// pattern to return to it after processing any tuple subpatterns.
|
||||
|
||||
// True if the current pattern being processed has a default value
|
||||
// specified.
|
||||
bool current_pattern_has_default = false;
|
||||
|
||||
// The current pattern we are processing, stored separately since it's been
|
||||
// popped from the `pattern_work_list` and already processed, just may need
|
||||
// subsequent processing.
|
||||
SemIR::InstId current_id = SemIR::InstId::None;
|
||||
|
||||
// A work list of patterns to be processed at this level of nesting.
|
||||
llvm::SmallVector<SemIR::InstId> pattern_work_list;
|
||||
|
||||
// A list of subpatterns missing required defaults, to coalesce error
|
||||
// reporting into a single diagnostic.
|
||||
llvm::SmallVector<SemIR::InstId> patterns_missing_defaults;
|
||||
|
||||
// A count of the number of patterns on this level that have defaults.
|
||||
int32_t default_count = 0;
|
||||
};
|
||||
|
||||
llvm::SmallVector<PatternLevelState> level_state_stack;
|
||||
size_t default_count = 0;
|
||||
level_state_stack.push_back({});
|
||||
llvm::append_range(
|
||||
level_state_stack.back().subpattern_ids,
|
||||
llvm::reverse(context.inst_blocks().Get(function.param_patterns_id)));
|
||||
|
||||
while (!level_state_stack.empty()) {
|
||||
PatternLevelState* state = &level_state_stack.back();
|
||||
while (!state->subpattern_ids.empty() ||
|
||||
!state->pattern_work_list.empty() || state->current_id.has_value()) {
|
||||
// If we're not resuming processing a pattern from a nested state, start
|
||||
// processing the next subpattern.
|
||||
if (!state->current_id.has_value()) {
|
||||
state->pattern_work_list.push_back(
|
||||
state->subpattern_ids.pop_back_val());
|
||||
state->current_pattern_has_default = false;
|
||||
}
|
||||
while (!state->pattern_work_list.empty()) {
|
||||
state->current_id = state->pattern_work_list.pop_back_val();
|
||||
auto inst = context.insts().Get(state->current_id);
|
||||
CARBON_KIND_SWITCH(inst) {
|
||||
case CARBON_KIND(SemIR::DefaultValuePattern default_value_pattern): {
|
||||
state->current_pattern_has_default = true;
|
||||
state->default_count += 1;
|
||||
state->pattern_work_list.push_back(
|
||||
default_value_pattern.subpattern_id);
|
||||
break;
|
||||
}
|
||||
case CARBON_KIND(
|
||||
SemIR::WrapperBindingPattern wrapper_binding_pattern): {
|
||||
state->pattern_work_list.push_back(
|
||||
wrapper_binding_pattern.subpattern_id);
|
||||
break;
|
||||
}
|
||||
case CARBON_KIND(SemIR::TuplePattern tuple_pattern): {
|
||||
auto elements =
|
||||
context.inst_blocks().Get(tuple_pattern.elements_id);
|
||||
if (!elements.empty()) {
|
||||
// Start a new state for the nested tuple pattern elements.
|
||||
level_state_stack.push_back({});
|
||||
state = &level_state_stack.back();
|
||||
llvm::append_range(state->subpattern_ids,
|
||||
llvm::reverse(elements));
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
// We only process patterns containing subpatterns, so this is an
|
||||
// intentional no-op.
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Finished processing this subpattern, detect a missing default if
|
||||
// required.
|
||||
if (state->current_pattern_has_default &&
|
||||
!state->first_pattern_with_default.has_value()) {
|
||||
state->first_pattern_with_default = state->current_id;
|
||||
} else if (!state->current_pattern_has_default &&
|
||||
state->first_pattern_with_default.has_value()) {
|
||||
state->patterns_missing_defaults.push_back(state->current_id);
|
||||
}
|
||||
state->current_id = SemIR::InstId::None;
|
||||
}
|
||||
// Finished processing this tuple-pattern, emit diagnostics if any.
|
||||
if (!state->patterns_missing_defaults.empty()) {
|
||||
CARBON_DIAGNOSTIC(RequiredPatternDefaultValueMissing, Error,
|
||||
"this pattern is missing a required default value.");
|
||||
CARBON_DIAGNOSTIC(RequiredPatternDefaultValueFirstDefault, Note,
|
||||
"all patterns to the right of this first pattern with "
|
||||
"a default value must also specify a default value.");
|
||||
CARBON_DIAGNOSTIC(
|
||||
RequiredPatternDefaultValueMissingAdditional, Note,
|
||||
"this pattern is also missing a required default value.");
|
||||
auto inst_ref = llvm::ArrayRef(state->patterns_missing_defaults);
|
||||
auto builder = context.emitter().Build(
|
||||
inst_ref.consume_front(), RequiredPatternDefaultValueMissing);
|
||||
for (auto inst_id : inst_ref) {
|
||||
builder.Note(inst_id, RequiredPatternDefaultValueMissingAdditional);
|
||||
}
|
||||
builder.Note(state->first_pattern_with_default,
|
||||
RequiredPatternDefaultValueFirstDefault);
|
||||
builder.Emit();
|
||||
}
|
||||
|
||||
// Extract the count from the level we just completed, overwriting any
|
||||
// nested level value extracted previously.
|
||||
default_count = level_state_stack.back().default_count;
|
||||
level_state_stack.pop_back();
|
||||
}
|
||||
|
||||
return default_count;
|
||||
}
|
||||
|
||||
// Build a FunctionDecl describing the signature of a function. This
|
||||
// handles the common logic shared by function declaration syntax and function
|
||||
// definition syntax.
|
||||
@@ -601,9 +442,7 @@ static auto BuildFunctionDecl(Context& context,
|
||||
function_info.definition_id = decl_id;
|
||||
}
|
||||
|
||||
function_info.default_value_arity = CheckDefaults(context, function_info);
|
||||
|
||||
DiagnosePositionalParams(context, function_info);
|
||||
CheckFunctionParams(context, function_info);
|
||||
|
||||
TryMergeRedecl(
|
||||
context, name_context, std::nullopt,
|
||||
@@ -778,20 +617,7 @@ auto HandleParseNode(Context& context, Parse::FunctionDefinitionId node_id)
|
||||
SemIR::FunctionId function_id =
|
||||
context.node_stack().Pop<Parse::NodeKind::FunctionDefinitionStart>();
|
||||
|
||||
// If the `}` of the function is reachable, reject if we need a return value
|
||||
// and otherwise add an implicit `return;`.
|
||||
if (IsCurrentPositionReachable(context)) {
|
||||
if (context.functions().Get(function_id).return_form_inst_id.has_value()) {
|
||||
CARBON_DIAGNOSTIC(
|
||||
MissingReturnStatement, Error,
|
||||
"missing `return` at end of function with declared return type");
|
||||
context.emitter().Emit(LocIdForDiagnostics::TokenOnly(node_id),
|
||||
MissingReturnStatement);
|
||||
} else {
|
||||
AddReturnInstWithCleanups(context, node_id);
|
||||
}
|
||||
}
|
||||
|
||||
CheckFunctionReturnOnFinish(context, node_id, function_id);
|
||||
FinishFunctionDefinition(context, function_id);
|
||||
context.decl_name_stack().PopScope(/*check_unused=*/true);
|
||||
|
||||
|
||||
@@ -3,17 +3,144 @@
|
||||
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
||||
|
||||
#include "toolchain/check/context.h"
|
||||
#include "toolchain/check/decl_introducer_state.h"
|
||||
#include "toolchain/check/function.h"
|
||||
#include "toolchain/check/generic.h"
|
||||
#include "toolchain/check/handle.h"
|
||||
#include "toolchain/check/pattern_match.h"
|
||||
#include "toolchain/lex/token_kind.h"
|
||||
#include "toolchain/parse/node_ids.h"
|
||||
#include "toolchain/sem_ir/function.h"
|
||||
#include "toolchain/sem_ir/ids.h"
|
||||
|
||||
namespace Carbon::Check {
|
||||
|
||||
auto HandleParseNode(Context& context, Parse::LambdaIntroducerId node_id)
|
||||
-> bool {
|
||||
return context.TODO(node_id, "HandleLambdaIntroducer");
|
||||
// The function expression is potentially generic.
|
||||
StartGenericDecl(context);
|
||||
StartFunctionSignature(context);
|
||||
context.node_stack().Push(node_id);
|
||||
context.decl_introducer_state_stack().Push<Lex::TokenKind::Fn>();
|
||||
return true;
|
||||
}
|
||||
|
||||
auto HandleParseNode(Context& context, Parse::LambdaDefinitionStartId node_id)
|
||||
-> bool {
|
||||
auto return_pattern_id = SemIR::InstId::None;
|
||||
auto return_type_inst_id = SemIR::TypeInstId::None;
|
||||
auto return_form_inst_id = SemIR::InstId::None;
|
||||
if (auto [return_node, maybe_return_pattern_id] =
|
||||
context.node_stack()
|
||||
.PopWithNodeIdIf<Parse::NodeCategory::ReturnDecl>();
|
||||
maybe_return_pattern_id) {
|
||||
return_pattern_id = *maybe_return_pattern_id;
|
||||
auto return_form = context.PopReturnForm();
|
||||
return_type_inst_id = return_form.type_component_inst_id;
|
||||
return_form_inst_id = return_form.form_inst_id;
|
||||
}
|
||||
|
||||
Parse::NodeId first_param_node_id = Parse::NoneNodeId();
|
||||
Parse::NodeId last_param_node_id = Parse::NoneNodeId();
|
||||
|
||||
// Explicit params.
|
||||
auto [params_node_id, param_patterns_id] =
|
||||
context.node_stack()
|
||||
.PopWithNodeIdIf<Parse::NodeKind::ExplicitParamList>();
|
||||
if (param_patterns_id) {
|
||||
first_param_node_id =
|
||||
context.node_stack()
|
||||
.PopForSoloNodeId<Parse::NodeKind::ExplicitParamListStart>();
|
||||
last_param_node_id = params_node_id;
|
||||
} else {
|
||||
param_patterns_id = SemIR::InstBlockId::None;
|
||||
}
|
||||
|
||||
// Implicit params.
|
||||
auto [implicit_params_node_id, implicit_param_patterns_id] =
|
||||
context.node_stack()
|
||||
.PopWithNodeIdIf<Parse::NodeKind::ImplicitParamList>();
|
||||
if (implicit_param_patterns_id) {
|
||||
first_param_node_id =
|
||||
context.node_stack()
|
||||
.PopForSoloNodeId<Parse::NodeKind::ImplicitParamListStart>();
|
||||
if (!last_param_node_id.has_value()) {
|
||||
last_param_node_id = implicit_params_node_id;
|
||||
}
|
||||
} else {
|
||||
implicit_param_patterns_id = SemIR::InstBlockId::None;
|
||||
}
|
||||
|
||||
auto match_results =
|
||||
CalleePatternMatch(context, *implicit_param_patterns_id,
|
||||
*param_patterns_id, return_pattern_id);
|
||||
context.full_pattern_stack().PopFullPattern();
|
||||
auto pattern_block_id = context.pattern_block_stack().Pop();
|
||||
if (!param_patterns_id->has_value() &&
|
||||
!implicit_param_patterns_id->has_value() &&
|
||||
!return_pattern_id.has_value()) {
|
||||
pattern_block_id = SemIR::InstBlockId::None;
|
||||
}
|
||||
auto decl_block_id = context.inst_block_stack().Pop();
|
||||
|
||||
context.node_stack()
|
||||
.PopAndDiscardSoloNodeId<Parse::NodeKind::LambdaIntroducer>();
|
||||
context.decl_introducer_state_stack().Pop<Lex::TokenKind::Fn>();
|
||||
|
||||
// Function expressions may not take `self` as a parameter. (`self` in the
|
||||
// implicit parameter list is already diagnosed by `SelfInImplicitParamList`.)
|
||||
if (auto self_param_id = FindSelfPattern(context, SemIR::InstBlockId::None,
|
||||
*param_patterns_id);
|
||||
self_param_id.has_value()) {
|
||||
CARBON_DIAGNOSTIC(SelfParameterInLambda, Error,
|
||||
"`self` parameter in function expression");
|
||||
context.emitter().Emit(SemIR::LocId(self_param_id), SelfParameterInLambda);
|
||||
}
|
||||
|
||||
auto [decl_id, function_id] = MakeFunctionDecl(
|
||||
context, node_id, decl_block_id, /*build_generic=*/true,
|
||||
/*is_definition=*/true,
|
||||
SemIR::Function{
|
||||
{
|
||||
.name_id = SemIR::NameId::None,
|
||||
.parent_scope_id = SemIR::NameScopeId::None,
|
||||
.generic_id = SemIR::GenericId::None,
|
||||
.first_param_node_id = first_param_node_id,
|
||||
.last_param_node_id = last_param_node_id,
|
||||
.pattern_block_id = pattern_block_id,
|
||||
.implicit_param_patterns_id = *implicit_param_patterns_id,
|
||||
.param_patterns_id = *param_patterns_id,
|
||||
.is_extern = false,
|
||||
.extern_library_id = SemIR::LibraryNameId::None,
|
||||
.non_owning_decl_id = SemIR::InstId::None,
|
||||
.first_owning_decl_id = SemIR::InstId::None,
|
||||
},
|
||||
{
|
||||
.call_param_patterns_id = match_results.call_param_patterns_id,
|
||||
.call_params_id = match_results.call_params_id,
|
||||
.call_param_ranges = match_results.param_ranges,
|
||||
.return_type_inst_id = return_type_inst_id,
|
||||
.return_form_inst_id = return_form_inst_id,
|
||||
.return_pattern_id = return_pattern_id,
|
||||
}});
|
||||
context.inst_block_stack().AddInstId(decl_id);
|
||||
|
||||
CheckFunctionParams(context, context.functions().Get(function_id));
|
||||
|
||||
StartFunctionDefinition(context, decl_id, function_id);
|
||||
context.node_stack().Push(node_id, function_id);
|
||||
return true;
|
||||
}
|
||||
|
||||
auto HandleParseNode(Context& context, Parse::LambdaId node_id) -> bool {
|
||||
return context.TODO(node_id, "HandleLambda");
|
||||
auto function_id =
|
||||
context.node_stack().Pop<Parse::NodeKind::LambdaDefinitionStart>();
|
||||
CheckFunctionReturnOnFinish(context, node_id, function_id);
|
||||
FinishFunctionDefinition(context, function_id);
|
||||
context.scope_stack().Pop(/*check_unused=*/true);
|
||||
context.node_stack().Push(
|
||||
node_id, context.functions().Get(function_id).first_owning_decl_id);
|
||||
return true;
|
||||
}
|
||||
|
||||
auto HandleParseNode(Context& context, Parse::TerseBodyArrowId node_id)
|
||||
|
||||
@@ -67,7 +67,11 @@ static auto BranchAndStartLoopBody(Context& context, Parse::NodeId node_id,
|
||||
{.break_target = loop_exit_id,
|
||||
.break_depth = context.scope_stack().cleanup_scope_depth(),
|
||||
.continue_target = loop_header_id,
|
||||
.continue_depth = continue_depth});
|
||||
.continue_depth = continue_depth,
|
||||
.return_scope_decl_id =
|
||||
context.scope_stack().IsInFunctionScope()
|
||||
? context.scope_stack().GetReturnScopeDeclId()
|
||||
: SemIR::InstId::None});
|
||||
}
|
||||
|
||||
// Finishes emitting the body for a `while`-like loop. Adds a back-edge to the
|
||||
@@ -276,7 +280,9 @@ auto HandleParseNode(Context& context, Parse::ForStatementId node_id) -> bool {
|
||||
auto HandleParseNode(Context& context, Parse::BreakStatementStartId node_id)
|
||||
-> bool {
|
||||
auto& stack = context.break_continue_stack();
|
||||
if (stack.empty()) {
|
||||
if (stack.empty() || !context.scope_stack().IsInFunctionScope() ||
|
||||
stack.back().return_scope_decl_id !=
|
||||
context.scope_stack().GetReturnScopeDeclId()) {
|
||||
CARBON_DIAGNOSTIC(BreakOutsideLoop, Error,
|
||||
"`break` can only be used in a loop");
|
||||
context.emitter().Emit(node_id, BreakOutsideLoop);
|
||||
@@ -301,7 +307,9 @@ auto HandleParseNode(Context& /*context*/, Parse::BreakStatementId /*node_id*/)
|
||||
auto HandleParseNode(Context& context, Parse::ContinueStatementStartId node_id)
|
||||
-> bool {
|
||||
auto& stack = context.break_continue_stack();
|
||||
if (stack.empty()) {
|
||||
if (stack.empty() || !context.scope_stack().IsInFunctionScope() ||
|
||||
stack.back().return_scope_decl_id !=
|
||||
context.scope_stack().GetReturnScopeDeclId()) {
|
||||
CARBON_DIAGNOSTIC(ContinueOutsideLoop, Error,
|
||||
"`continue` can only be used in a loop");
|
||||
context.emitter().Emit(node_id, ContinueOutsideLoop);
|
||||
|
||||
@@ -431,6 +431,7 @@ class NodeStack {
|
||||
return Id::KindFor<SemIR::InstBlockId>();
|
||||
case Parse::NodeKind::FunctionDefinitionStart:
|
||||
case Parse::NodeKind::BuiltinFunctionDefinitionStart:
|
||||
case Parse::NodeKind::LambdaDefinitionStart:
|
||||
return Id::KindFor<SemIR::FunctionId>();
|
||||
case Parse::NodeKind::ChoiceDefinitionStart:
|
||||
// TODO: Should we have a separate SemIR::ChoiceId?
|
||||
|
||||
@@ -56,6 +56,7 @@ class ScopeStack {
|
||||
CleanupScopeDepth break_depth;
|
||||
SemIR::InstBlockId continue_target;
|
||||
CleanupScopeDepth continue_depth;
|
||||
SemIR::InstId return_scope_decl_id;
|
||||
};
|
||||
|
||||
// A non-lexical scope in which unqualified lookup may be required.
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
|
||||
// Exceptions. See /LICENSE for license information.
|
||||
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
||||
//
|
||||
// INCLUDE-FILE: toolchain/testing/testdata/min_prelude/primitives.carbon
|
||||
//
|
||||
// AUTOUPDATE
|
||||
// TIP: To test this file alone, run:
|
||||
// TIP: bazel test //toolchain/testing:file_test --test_arg=--file_tests=toolchain/check/testdata/function/capture/uncaptured_locals.carbon
|
||||
// TIP: To dump output, run:
|
||||
// TIP: bazel run //toolchain/testing:file_test -- --dump_output --file_tests=toolchain/check/testdata/function/capture/uncaptured_locals.carbon
|
||||
|
||||
// --- fail_todo_reference_uncaptured.carbon
|
||||
library "[[@TEST_NAME]]";
|
||||
|
||||
class X {}
|
||||
|
||||
fn Test() {
|
||||
let x: X = {};
|
||||
fn Inner() {
|
||||
// TODO: This should fail. We can't reference `x` from here.
|
||||
let unused y: X = x;
|
||||
}
|
||||
}
|
||||
|
||||
// Intentionally include an error here so we skip dominance checking, which CHECK-fails for the above example.
|
||||
// CHECK:STDERR: fail_todo_reference_uncaptured.carbon:[[@LINE+4]]:14: error: name `error` not found [NameNotFound]
|
||||
// CHECK:STDERR: fn Error() { error; }
|
||||
// CHECK:STDERR: ^~~~~
|
||||
// CHECK:STDERR:
|
||||
fn Error() { error; }
|
||||
|
||||
// --- fail_todo_reference_uncaptured_lambda.carbon
|
||||
library "[[@TEST_NAME]]";
|
||||
|
||||
class X {}
|
||||
|
||||
fn Test() {
|
||||
let x: X = {};
|
||||
(fn() {
|
||||
// TODO: This should fail. We can't reference `x` from here.
|
||||
let unused y: X = x;
|
||||
});
|
||||
}
|
||||
|
||||
// Intentionally include an error here so we skip dominance checking, which CHECK-fails for the above example.
|
||||
// CHECK:STDERR: fail_todo_reference_uncaptured_lambda.carbon:[[@LINE+4]]:14: error: name `error` not found [NameNotFound]
|
||||
// CHECK:STDERR: fn Error() { error; }
|
||||
// CHECK:STDERR: ^~~~~
|
||||
// CHECK:STDERR:
|
||||
fn Error() { error; }
|
||||
+1308
File diff suppressed because it is too large.
Load diff
@@ -637,6 +637,9 @@ CARBON_DIAGNOSTIC_KIND(UnusedModifierWithoutDefinition)
|
||||
CARBON_DIAGNOSTIC_KIND(UnusedPatternNoBindings)
|
||||
CARBON_DIAGNOSTIC_KIND(UnusedBinding)
|
||||
|
||||
// Function expression diagnostics.
|
||||
CARBON_DIAGNOSTIC_KIND(SelfParameterInLambda)
|
||||
|
||||
// ============================================================================
|
||||
// CodeGen diagnostics
|
||||
// ============================================================================
|
||||
|
||||
@@ -116,7 +116,7 @@ auto FileContext::LowerDefinitions() -> void {
|
||||
LowerGlobalVariables(sem_ir().top_inst_block_id());
|
||||
|
||||
// Lower static class variable definitions.
|
||||
for (auto class_info : sem_ir().classes().values()) {
|
||||
for (const auto& class_info : sem_ir().classes().values()) {
|
||||
auto inst_block_id = class_info.body_block_id;
|
||||
if (inst_block_id.has_value()) {
|
||||
LowerGlobalVariables(inst_block_id);
|
||||
@@ -699,14 +699,18 @@ auto FileContext::BuildDISubprogram(const SemIR::Function& function,
|
||||
if (!context().di_compile_unit()) {
|
||||
return nullptr;
|
||||
}
|
||||
auto name = sem_ir().names().GetAsStringIfIdentifier(function.name_id);
|
||||
CARBON_CHECK(name, "Unexpected special name for function: {0}",
|
||||
function.name_id);
|
||||
llvm::StringRef name = "";
|
||||
if (function.name_id.has_value()) {
|
||||
auto maybe_name =
|
||||
sem_ir().names().GetAsStringIfIdentifier(function.name_id);
|
||||
CARBON_CHECK(maybe_name, "Unexpected special name for function: {0}",
|
||||
function.name_id);
|
||||
name = *maybe_name;
|
||||
}
|
||||
auto loc = GetLocForDI(function.definition_id);
|
||||
llvm::DISubroutineType* subroutine_type = function_info.di_type;
|
||||
auto* subprogram = context().di_builder().createFunction(
|
||||
context().di_compile_unit(), *name,
|
||||
function_info.llvm_function->getName(),
|
||||
context().di_compile_unit(), name, function_info.llvm_function->getName(),
|
||||
/*File=*/context().di_builder().createFile(loc.filename, ""),
|
||||
/*LineNo=*/loc.line_number, subroutine_type,
|
||||
/*ScopeLine=*/0, llvm::DINode::FlagZero,
|
||||
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
|
||||
// Exceptions. See /LICENSE for license information.
|
||||
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
||||
//
|
||||
// INCLUDE-FILE: toolchain/testing/testdata/min_prelude/int.carbon
|
||||
//
|
||||
// AUTOUPDATE
|
||||
// TIP: To test this file alone, run:
|
||||
// TIP: bazel test //toolchain/testing:file_test --test_arg=--file_tests=toolchain/lower/testdata/lambda/lambda.carbon
|
||||
// TIP: To dump output, run:
|
||||
// TIP: bazel run //toolchain/testing:file_test -- --dump_output --file_tests=toolchain/lower/testdata/lambda/lambda.carbon
|
||||
|
||||
// --- lib.carbon
|
||||
library "[[@TEST_NAME]]";
|
||||
|
||||
alias Imported = fn (x: i32) -> i32 { return x; };
|
||||
|
||||
// --- main.carbon
|
||||
library "[[@TEST_NAME]]";
|
||||
|
||||
import library "lib";
|
||||
|
||||
fn Test() -> i32 {
|
||||
alias f = fn (x: i32) -> i32 {
|
||||
return x;
|
||||
};
|
||||
return (fn (y: i32) -> i32 { return y; })(f(Imported(1)));
|
||||
}
|
||||
|
||||
// CHECK:STDOUT: ; ---
|
||||
// CHECK:STDOUT: ; ModuleID = 'lib.carbon'
|
||||
// CHECK:STDOUT: source_filename = "lib.carbon"
|
||||
// CHECK:STDOUT:
|
||||
// CHECK:STDOUT: ; Function Attrs: nounwind
|
||||
// CHECK:STDOUT: define i32 @"_Cfn:enclosed.3c14c8ca6559e7d0"(i32 %x) #0 !dbg !23 {
|
||||
// CHECK:STDOUT: entry:
|
||||
// CHECK:STDOUT: ret i32 %x, !dbg !29
|
||||
// CHECK:STDOUT: }
|
||||
// CHECK:STDOUT:
|
||||
// CHECK:STDOUT: attributes #0 = { nounwind }
|
||||
// CHECK:STDOUT:
|
||||
// CHECK:STDOUT: !llvm.dbg.cu = !{!19}
|
||||
// CHECK:STDOUT: !llvm.module.flags = !{!2, !3}
|
||||
// CHECK:STDOUT:
|
||||
// CHECK:STDOUT: !2 = !{i32 7, !"Dwarf Version", i32 5}
|
||||
// CHECK:STDOUT: !3 = !{i32 2, !"Debug Info Version", i32 3}
|
||||
// CHECK:STDOUT: !18 = !DIFile(filename: "lib.carbon", directory: "")
|
||||
// CHECK:STDOUT: !19 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !18, producer: "carbon", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug)
|
||||
// CHECK:STDOUT: !20 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
|
||||
// CHECK:STDOUT: !21 = !{!20, !20}
|
||||
// CHECK:STDOUT: !22 = !DISubroutineType(types: !21)
|
||||
// CHECK:STDOUT: !23 = distinct !DISubprogram(linkageName: "_Cfn:enclosed.3c14c8ca6559e7d0", scope: null, file: !18, line: 3, type: !22, spFlags: DISPFlagDefinition, unit: !19, retainedNodes: !30)
|
||||
// CHECK:STDOUT: !24 = !DILocalVariable(arg: 1, scope: !23, type: !20)
|
||||
// CHECK:STDOUT: !29 = !DILocation(line: 3, column: 39, scope: !23)
|
||||
// CHECK:STDOUT: !30 = !{!24}
|
||||
// CHECK:STDOUT:
|
||||
// CHECK:STDOUT: ; ---
|
||||
// CHECK:STDOUT: ; ModuleID = 'main.carbon'
|
||||
// CHECK:STDOUT: source_filename = "main.carbon"
|
||||
// CHECK:STDOUT:
|
||||
// CHECK:STDOUT: ; Function Attrs: nounwind
|
||||
// CHECK:STDOUT: define i32 @_CTest.Main() #0 !dbg !35 {
|
||||
// CHECK:STDOUT: entry:
|
||||
// CHECK:STDOUT: %fn.call.loc9_57 = call i32 @"_Cfn:enclosed.3c14c8ca6559e7d0"(i32 1), !dbg !38
|
||||
// CHECK:STDOUT: %fn.call.loc9_58 = call i32 @"_Cfn:enclosed.4f93545957a800ba"(i32 %fn.call.loc9_57), !dbg !39
|
||||
// CHECK:STDOUT: %fn.call.loc9_59 = call i32 @"_Cfn:enclosed.1e20c3b8ac0c9b5a"(i32 %fn.call.loc9_58), !dbg !40
|
||||
// CHECK:STDOUT: ret i32 %fn.call.loc9_59, !dbg !41
|
||||
// CHECK:STDOUT: }
|
||||
// CHECK:STDOUT:
|
||||
// CHECK:STDOUT: ; Function Attrs: nounwind
|
||||
// CHECK:STDOUT: define i32 @"_Cfn:enclosed.4f93545957a800ba"(i32 %x) #0 !dbg !42 {
|
||||
// CHECK:STDOUT: entry:
|
||||
// CHECK:STDOUT: ret i32 %x, !dbg !48
|
||||
// CHECK:STDOUT: }
|
||||
// CHECK:STDOUT:
|
||||
// CHECK:STDOUT: ; Function Attrs: nounwind
|
||||
// CHECK:STDOUT: define i32 @"_Cfn:enclosed.1e20c3b8ac0c9b5a"(i32 %y) #0 !dbg !50 {
|
||||
// CHECK:STDOUT: entry:
|
||||
// CHECK:STDOUT: ret i32 %y, !dbg !56
|
||||
// CHECK:STDOUT: }
|
||||
// CHECK:STDOUT:
|
||||
// CHECK:STDOUT: declare i32 @"_Cfn:enclosed.3c14c8ca6559e7d0"(i32)
|
||||
// CHECK:STDOUT:
|
||||
// CHECK:STDOUT: attributes #0 = { nounwind }
|
||||
// CHECK:STDOUT:
|
||||
// CHECK:STDOUT: !llvm.dbg.cu = !{!32}
|
||||
// CHECK:STDOUT: !llvm.module.flags = !{!2, !3}
|
||||
// CHECK:STDOUT:
|
||||
// CHECK:STDOUT: !2 = !{i32 7, !"Dwarf Version", i32 5}
|
||||
// CHECK:STDOUT: !3 = !{i32 2, !"Debug Info Version", i32 3}
|
||||
// CHECK:STDOUT: !20 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
|
||||
// CHECK:STDOUT: !21 = !{!20, !20}
|
||||
// CHECK:STDOUT: !22 = !DISubroutineType(types: !21)
|
||||
// CHECK:STDOUT: !31 = !DIFile(filename: "main.carbon", directory: "")
|
||||
// CHECK:STDOUT: !32 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !31, producer: "carbon", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug)
|
||||
// CHECK:STDOUT: !33 = !{!20}
|
||||
// CHECK:STDOUT: !34 = !DISubroutineType(types: !33)
|
||||
// CHECK:STDOUT: !35 = distinct !DISubprogram(name: "Test", linkageName: "_CTest.Main", scope: null, file: !31, line: 5, type: !34, spFlags: DISPFlagDefinition, unit: !32)
|
||||
// CHECK:STDOUT: !38 = !DILocation(line: 9, column: 47, scope: !35)
|
||||
// CHECK:STDOUT: !39 = !DILocation(line: 9, column: 45, scope: !35)
|
||||
// CHECK:STDOUT: !40 = !DILocation(line: 9, column: 10, scope: !35)
|
||||
// CHECK:STDOUT: !41 = !DILocation(line: 9, column: 3, scope: !35)
|
||||
// CHECK:STDOUT: !42 = distinct !DISubprogram(linkageName: "_Cfn:enclosed.4f93545957a800ba", scope: null, file: !31, line: 6, type: !22, spFlags: DISPFlagDefinition, unit: !32, retainedNodes: !49)
|
||||
// CHECK:STDOUT: !43 = !DILocalVariable(arg: 1, scope: !42, type: !20)
|
||||
// CHECK:STDOUT: !48 = !DILocation(line: 7, column: 5, scope: !42)
|
||||
// CHECK:STDOUT: !49 = !{!43}
|
||||
// CHECK:STDOUT: !50 = distinct !DISubprogram(linkageName: "_Cfn:enclosed.1e20c3b8ac0c9b5a", scope: null, file: !31, line: 9, type: !22, spFlags: DISPFlagDefinition, unit: !32, retainedNodes: !57)
|
||||
// CHECK:STDOUT: !51 = !DILocalVariable(arg: 1, scope: !50, type: !20)
|
||||
// CHECK:STDOUT: !56 = !DILocation(line: 9, column: 32, scope: !50)
|
||||
// CHECK:STDOUT: !57 = !{!51}
|
||||
// CHECK:STDOUT:
|
||||
@@ -18,7 +18,8 @@ auto HandleLambdaAfterIntroducer(Context& context) -> void {
|
||||
|
||||
if (context.PositionIs(Lex::TokenKind::OpenSquareBracket)) {
|
||||
context.PushState(state, StateKind::LambdaAfterImplicitParams);
|
||||
context.PushState(StateKind::PatternListAsImplicit);
|
||||
context.PushState(StateKind::PatternListAsImplicit, *context.position(),
|
||||
BindingContext::DeducedParam);
|
||||
} else if (context.PositionIs(Lex::TokenKind::OpenParen)) {
|
||||
context.PushState(state, StateKind::LambdaAfterParams);
|
||||
context.PushState(StateKind::PatternListAsExplicit);
|
||||
@@ -40,6 +41,44 @@ auto HandleLambdaAfterImplicitParams(Context& context) -> void {
|
||||
}
|
||||
}
|
||||
|
||||
static auto ParseLambdaBody(Context& context, Context::State state,
|
||||
bool has_return_type) -> void {
|
||||
if (context.PositionIs(Lex::TokenKind::EqualGreater)) {
|
||||
// Terse body `=> expr`
|
||||
auto arrow_token = context.Consume();
|
||||
context.AddNode(NodeKind::LambdaDefinitionStart, arrow_token,
|
||||
state.has_error);
|
||||
state.has_error = false;
|
||||
context.AddLeafNode(NodeKind::TerseBodyArrow, arrow_token);
|
||||
context.PushState(state, StateKind::LambdaBodyFinish);
|
||||
context.PushStateForExpr(PrecedenceGroup::ForTopLevelExpr());
|
||||
} else if (context.PositionIs(Lex::TokenKind::OpenCurlyBrace)) {
|
||||
// Block body `{ ... }`
|
||||
context.PushState(StateKind::LambdaBodyFinish);
|
||||
context.AddNode(NodeKind::LambdaDefinitionStart, context.Consume(),
|
||||
state.has_error);
|
||||
context.PushState(StateKind::StatementScopeLoop);
|
||||
} else {
|
||||
if (has_return_type) {
|
||||
CARBON_DIAGNOSTIC(ExpectedLambdaBodyAfterReturnType, Error,
|
||||
"expected `=>` or `{{` after return type");
|
||||
context.emitter().Emit(*context.position(),
|
||||
ExpectedLambdaBodyAfterReturnType);
|
||||
} else {
|
||||
CARBON_DIAGNOSTIC(ExpectedLambdaBody, Error,
|
||||
"expected `->`, `=>`, or `{{`");
|
||||
context.emitter().Emit(*context.position(), ExpectedLambdaBody);
|
||||
}
|
||||
|
||||
// Bundle everything into a complete lambda node for error recovery --
|
||||
// otherwise the orphaned `LambdaIntroducer` would be left where an
|
||||
// expression is required, for example in `(fn)`.
|
||||
context.AddNode(NodeKind::LambdaDefinitionStart, *context.position(),
|
||||
/*has_error=*/true);
|
||||
context.AddNode(NodeKind::Lambda, state.token, /*has_error=*/true);
|
||||
}
|
||||
}
|
||||
|
||||
auto HandleLambdaAfterParams(Context& context) -> void {
|
||||
auto state = context.PopState();
|
||||
|
||||
@@ -49,68 +88,29 @@ auto HandleLambdaAfterParams(Context& context) -> void {
|
||||
context.PushState(StateKind::FunctionReturnTypeFinish);
|
||||
context.ConsumeAndDiscard();
|
||||
context.PushStateForExpr(PrecedenceGroup::ForType());
|
||||
} else if (context.PositionIs(Lex::TokenKind::EqualGreater)) {
|
||||
// Terse body `=> expr`
|
||||
context.AddLeafNode(NodeKind::TerseBodyArrow, context.Consume());
|
||||
context.PushState(state, StateKind::LambdaBodyFinish);
|
||||
context.PushStateForExpr(PrecedenceGroup::ForTopLevelExpr());
|
||||
} else if (context.PositionIs(Lex::TokenKind::OpenCurlyBrace)) {
|
||||
// Block body `{ ... }`
|
||||
context.PushState(state, StateKind::LambdaBodyFinish);
|
||||
context.PushState(StateKind::CodeBlock);
|
||||
} else if (context.PositionIs(Lex::TokenKind::MinusGreaterQuestion)) {
|
||||
// Has return form.
|
||||
context.PushState(state, StateKind::LambdaBody);
|
||||
context.PushState(StateKind::FunctionReturnFormFinish);
|
||||
context.ConsumeAndDiscard();
|
||||
context.PushStateForExpr(PrecedenceGroup::ForType());
|
||||
} else {
|
||||
CARBON_DIAGNOSTIC(ExpectedLambdaBody, Error,
|
||||
"expected `->`, `=>`, or `{{`");
|
||||
context.emitter().Emit(*context.position(), ExpectedLambdaBody);
|
||||
|
||||
// Add a dummy node for the missing body without consuming the current
|
||||
// token, then bundle everything into a complete lambda node. This keeps the
|
||||
// lambda a valid expression for error recovery -- otherwise the orphaned
|
||||
// `LambdaIntroducer` would be left where an expression is required, for
|
||||
// example in `(fn)`.
|
||||
context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
|
||||
/*has_error=*/true);
|
||||
|
||||
state.has_error = true;
|
||||
context.PushState(state, StateKind::LambdaBodyFinish);
|
||||
ParseLambdaBody(context, state, /*has_return_type=*/false);
|
||||
}
|
||||
}
|
||||
|
||||
auto HandleLambdaBody(Context& context) -> void {
|
||||
auto state = context.PopState();
|
||||
|
||||
// We arrive here after parsing return type.
|
||||
// So we look for `=>` or `{`.
|
||||
|
||||
if (context.PositionIs(Lex::TokenKind::EqualGreater)) {
|
||||
// Terse body `=> expr`
|
||||
context.AddLeafNode(NodeKind::TerseBodyArrow, context.Consume());
|
||||
context.PushState(state, StateKind::LambdaBodyFinish);
|
||||
context.PushStateForExpr(PrecedenceGroup::ForTopLevelExpr());
|
||||
} else if (context.PositionIs(Lex::TokenKind::OpenCurlyBrace)) {
|
||||
// Block body `{ ... }`
|
||||
context.PushState(state, StateKind::LambdaBodyFinish);
|
||||
context.PushState(StateKind::CodeBlock);
|
||||
} else {
|
||||
CARBON_DIAGNOSTIC(ExpectedLambdaBodyAfterReturnType, Error,
|
||||
"expected `=>` or `{{` after return type");
|
||||
context.emitter().Emit(*context.position(),
|
||||
ExpectedLambdaBodyAfterReturnType);
|
||||
|
||||
// Add a dummy node for the missing body without consuming the current
|
||||
// token.
|
||||
context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
|
||||
/*has_error=*/true);
|
||||
|
||||
state.has_error = true;
|
||||
// Bundle all nodes into a complete lambda node.
|
||||
context.PushState(state, StateKind::LambdaBodyFinish);
|
||||
}
|
||||
ParseLambdaBody(context, state, /*has_return_type=*/true);
|
||||
}
|
||||
|
||||
auto HandleLambdaBodyFinish(Context& context) -> void {
|
||||
auto state = context.PopState();
|
||||
context.AddNode(NodeKind::Lambda, state.token, state.has_error);
|
||||
if (context.tokens().GetKind(state.token) == Lex::TokenKind::OpenCurlyBrace) {
|
||||
context.AddNode(NodeKind::Lambda, context.Consume(), state.has_error);
|
||||
} else {
|
||||
context.AddNode(NodeKind::Lambda, state.token, state.has_error);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Carbon::Parse
|
||||
@@ -175,8 +175,9 @@ using AnyClassDeclId =
|
||||
// class, so they are a form of class decls. This avoids
|
||||
// duplicating all of SemIR::ClassDecl.
|
||||
ChoiceDefinitionStartId>;
|
||||
using AnyFunctionDeclId = NodeIdOneOf<FunctionDeclId, FunctionDefinitionStartId,
|
||||
BuiltinFunctionDefinitionStartId>;
|
||||
using AnyFunctionDeclId =
|
||||
NodeIdOneOf<FunctionDeclId, FunctionDefinitionStartId,
|
||||
BuiltinFunctionDefinitionStartId, LambdaDefinitionStartId>;
|
||||
using AnyFunctionDefinitionId =
|
||||
NodeIdOneOf<FunctionDefinitionId, FunctionTerseDefinitionId,
|
||||
BuiltinFunctionDefinitionId>;
|
||||
|
||||
@@ -201,6 +201,7 @@ CARBON_PARSE_NODE_KIND_DECLARATION(FunctionDefinitionStart)
|
||||
CARBON_PARSE_NODE_KIND_DECLARATION(FunctionDefinition)
|
||||
CARBON_PARSE_NODE_KIND_DECLARATION(FunctionTerseDefinition)
|
||||
CARBON_PARSE_NODE_KIND_DECLARATION(FunctionDecl)
|
||||
CARBON_PARSE_NODE_KIND_DECLARATION(LambdaDefinitionStart)
|
||||
CARBON_PARSE_NODE_KIND_DECLARATION(Lambda)
|
||||
CARBON_PARSE_NODE_KIND_DECLARATION(TerseBodyArrow)
|
||||
CARBON_PARSE_NODE_KIND_DECLARATION(BuiltinFunctionDefinitionStart)
|
||||
|
||||
@@ -815,7 +815,12 @@ CARBON_PARSE_STATE(LambdaAfterImplicitParams)
|
||||
//
|
||||
// fn <...> -> <...>
|
||||
// ^
|
||||
// 1. FunctionReturnTypeFinish (Reused)
|
||||
// 1. FunctionReturnTypeFinish
|
||||
// 2. LambdaBody
|
||||
//
|
||||
// fn <...> ->? <...>
|
||||
// ^
|
||||
// 1. FunctionReturnFormFinish
|
||||
// 2. LambdaBody
|
||||
//
|
||||
// fn <...> => <...>
|
||||
|
||||
+11
-10
@@ -75,16 +75,17 @@ var b: auto = fn (x: i32 = 0) => x;
|
||||
// CHECK:STDOUT: │ │ ╭─VarBindingPattern ':'
|
||||
// CHECK:STDOUT: │ ├─VariablePattern 'var'
|
||||
// CHECK:STDOUT: │ ├─VariableInitializer '='
|
||||
// CHECK:STDOUT: │ │ ╭─LambdaIntroducer 'fn'
|
||||
// CHECK:STDOUT: │ │ │ ╭─ExplicitParamListStart '('
|
||||
// CHECK:STDOUT: │ │ │ │ ╭─IdentifierNameNotBeforeSignature 'x'
|
||||
// CHECK:STDOUT: │ │ │ │ ├─BindingPatternTypeStart ':'
|
||||
// CHECK:STDOUT: │ │ │ │ ├─IntTypeLiteral 'i32'
|
||||
// CHECK:STDOUT: │ │ │ │ ╭─LetBindingPattern ':'
|
||||
// CHECK:STDOUT: │ │ │ │ ├─DefaultValueExprStart '='
|
||||
// CHECK:STDOUT: │ │ │ │ ├─IntLiteral '0'
|
||||
// CHECK:STDOUT: │ │ │ ├─DefaultValuePattern '='
|
||||
// CHECK:STDOUT: │ │ ├─ExplicitParamList ')'
|
||||
// CHECK:STDOUT: │ │ ╭─LambdaIntroducer 'fn'
|
||||
// CHECK:STDOUT: │ │ │ ╭─ExplicitParamListStart '('
|
||||
// CHECK:STDOUT: │ │ │ │ ╭─IdentifierNameNotBeforeSignature 'x'
|
||||
// CHECK:STDOUT: │ │ │ │ ├─BindingPatternTypeStart ':'
|
||||
// CHECK:STDOUT: │ │ │ │ ├─IntTypeLiteral 'i32'
|
||||
// CHECK:STDOUT: │ │ │ │ ╭─LetBindingPattern ':'
|
||||
// CHECK:STDOUT: │ │ │ │ ├─DefaultValueExprStart '='
|
||||
// CHECK:STDOUT: │ │ │ │ ├─IntLiteral '0'
|
||||
// CHECK:STDOUT: │ │ │ ├─DefaultValuePattern '='
|
||||
// CHECK:STDOUT: │ │ ├─ExplicitParamList ')'
|
||||
// CHECK:STDOUT: │ │ ╭─LambdaDefinitionStart '=>'
|
||||
// CHECK:STDOUT: │ │ ├─TerseBodyArrow '=>'
|
||||
// CHECK:STDOUT: │ │ ├─IdentifierNameExpr 'x'
|
||||
// CHECK:STDOUT: │ ├─Lambda 'fn'
|
||||
|
||||
+68
-44
@@ -13,6 +13,7 @@
|
||||
var a: auto = fn [T: type] (x: T) -> T { return x; };
|
||||
var b: auto = fn (x: i32) => x;
|
||||
var c: auto = fn { };
|
||||
var d: auto = fn (ref x: i32) ->? ref i32 { return x; };
|
||||
|
||||
// --- fail_unconsumed_lambda_introducer.carbon
|
||||
|
||||
@@ -74,27 +75,26 @@ fn G() {
|
||||
// CHECK:STDOUT: │ │ ╭─VarBindingPattern ':'
|
||||
// CHECK:STDOUT: │ ├─VariablePattern 'var'
|
||||
// CHECK:STDOUT: │ ├─VariableInitializer '='
|
||||
// CHECK:STDOUT: │ │ ╭─LambdaIntroducer 'fn'
|
||||
// CHECK:STDOUT: │ │ │ ╭─ImplicitParamListStart '['
|
||||
// CHECK:STDOUT: │ │ │ │ ╭─IdentifierNameNotBeforeSignature 'T'
|
||||
// CHECK:STDOUT: │ │ │ │ ├─BindingPatternTypeStart ':'
|
||||
// CHECK:STDOUT: │ │ │ │ ├─TypeTypeLiteral 'type'
|
||||
// CHECK:STDOUT: │ │ │ ├─LetBindingPattern ':'
|
||||
// CHECK:STDOUT: │ │ ├─ImplicitParamList ']'
|
||||
// CHECK:STDOUT: │ │ │ ╭─ExplicitParamListStart '('
|
||||
// CHECK:STDOUT: │ │ │ │ ╭─IdentifierNameNotBeforeSignature 'x'
|
||||
// CHECK:STDOUT: │ │ │ │ ├─BindingPatternTypeStart ':'
|
||||
// CHECK:STDOUT: │ │ │ │ ├─IdentifierNameExpr 'T'
|
||||
// CHECK:STDOUT: │ │ │ ├─LetBindingPattern ':'
|
||||
// CHECK:STDOUT: │ │ ├─ExplicitParamList ')'
|
||||
// CHECK:STDOUT: │ │ │ ╭─IdentifierNameExpr 'T'
|
||||
// CHECK:STDOUT: │ │ ├─ReturnType '->'
|
||||
// CHECK:STDOUT: │ │ │ ╭─CodeBlockStart '{'
|
||||
// CHECK:STDOUT: │ │ │ │ ╭─ReturnStatementStart 'return'
|
||||
// CHECK:STDOUT: │ │ │ │ ├─IdentifierNameExpr 'x'
|
||||
// CHECK:STDOUT: │ │ │ ├─ReturnStatement ';'
|
||||
// CHECK:STDOUT: │ │ ├─CodeBlock '}'
|
||||
// CHECK:STDOUT: │ ├─Lambda 'fn'
|
||||
// CHECK:STDOUT: │ │ ╭─LambdaIntroducer 'fn'
|
||||
// CHECK:STDOUT: │ │ │ ╭─ImplicitParamListStart '['
|
||||
// CHECK:STDOUT: │ │ │ │ ╭─IdentifierNameNotBeforeSignature 'T'
|
||||
// CHECK:STDOUT: │ │ │ │ ├─CompileTimeBindingPatternTypeStart ':'
|
||||
// CHECK:STDOUT: │ │ │ │ ├─TypeTypeLiteral 'type'
|
||||
// CHECK:STDOUT: │ │ │ ├─CompileTimeBindingPattern ':'
|
||||
// CHECK:STDOUT: │ │ ├─ImplicitParamList ']'
|
||||
// CHECK:STDOUT: │ │ │ ╭─ExplicitParamListStart '('
|
||||
// CHECK:STDOUT: │ │ │ │ ╭─IdentifierNameNotBeforeSignature 'x'
|
||||
// CHECK:STDOUT: │ │ │ │ ├─BindingPatternTypeStart ':'
|
||||
// CHECK:STDOUT: │ │ │ │ ├─IdentifierNameExpr 'T'
|
||||
// CHECK:STDOUT: │ │ │ ├─LetBindingPattern ':'
|
||||
// CHECK:STDOUT: │ │ ├─ExplicitParamList ')'
|
||||
// CHECK:STDOUT: │ │ │ ╭─IdentifierNameExpr 'T'
|
||||
// CHECK:STDOUT: │ │ ├─ReturnType '->'
|
||||
// CHECK:STDOUT: │ │ ╭─LambdaDefinitionStart '{'
|
||||
// CHECK:STDOUT: │ │ │ ╭─ReturnStatementStart 'return'
|
||||
// CHECK:STDOUT: │ │ │ ├─IdentifierNameExpr 'x'
|
||||
// CHECK:STDOUT: │ │ ├─ReturnStatement ';'
|
||||
// CHECK:STDOUT: │ ├─Lambda '}'
|
||||
// CHECK:STDOUT: ├─VariableDecl ';'
|
||||
// CHECK:STDOUT: │ ╭─VariableIntroducer 'var'
|
||||
// CHECK:STDOUT: │ │ ╭─IdentifierNameNotBeforeSignature 'b'
|
||||
@@ -103,13 +103,14 @@ fn G() {
|
||||
// CHECK:STDOUT: │ │ ╭─VarBindingPattern ':'
|
||||
// CHECK:STDOUT: │ ├─VariablePattern 'var'
|
||||
// CHECK:STDOUT: │ ├─VariableInitializer '='
|
||||
// CHECK:STDOUT: │ │ ╭─LambdaIntroducer 'fn'
|
||||
// CHECK:STDOUT: │ │ │ ╭─ExplicitParamListStart '('
|
||||
// CHECK:STDOUT: │ │ │ │ ╭─IdentifierNameNotBeforeSignature 'x'
|
||||
// CHECK:STDOUT: │ │ │ │ ├─BindingPatternTypeStart ':'
|
||||
// CHECK:STDOUT: │ │ │ │ ├─IntTypeLiteral 'i32'
|
||||
// CHECK:STDOUT: │ │ │ ├─LetBindingPattern ':'
|
||||
// CHECK:STDOUT: │ │ ├─ExplicitParamList ')'
|
||||
// CHECK:STDOUT: │ │ ╭─LambdaIntroducer 'fn'
|
||||
// CHECK:STDOUT: │ │ │ ╭─ExplicitParamListStart '('
|
||||
// CHECK:STDOUT: │ │ │ │ ╭─IdentifierNameNotBeforeSignature 'x'
|
||||
// CHECK:STDOUT: │ │ │ │ ├─BindingPatternTypeStart ':'
|
||||
// CHECK:STDOUT: │ │ │ │ ├─IntTypeLiteral 'i32'
|
||||
// CHECK:STDOUT: │ │ │ ├─LetBindingPattern ':'
|
||||
// CHECK:STDOUT: │ │ ├─ExplicitParamList ')'
|
||||
// CHECK:STDOUT: │ │ ╭─LambdaDefinitionStart '=>'
|
||||
// CHECK:STDOUT: │ │ ├─TerseBodyArrow '=>'
|
||||
// CHECK:STDOUT: │ │ ├─IdentifierNameExpr 'x'
|
||||
// CHECK:STDOUT: │ ├─Lambda 'fn'
|
||||
@@ -121,10 +122,33 @@ fn G() {
|
||||
// CHECK:STDOUT: │ │ ╭─VarBindingPattern ':'
|
||||
// CHECK:STDOUT: │ ├─VariablePattern 'var'
|
||||
// CHECK:STDOUT: │ ├─VariableInitializer '='
|
||||
// CHECK:STDOUT: │ │ ╭─LambdaIntroducer 'fn'
|
||||
// CHECK:STDOUT: │ │ │ ╭─CodeBlockStart '{'
|
||||
// CHECK:STDOUT: │ │ ├─CodeBlock '}'
|
||||
// CHECK:STDOUT: │ ├─Lambda 'fn'
|
||||
// CHECK:STDOUT: │ │ ╭─LambdaIntroducer 'fn'
|
||||
// CHECK:STDOUT: │ │ ╭─LambdaDefinitionStart '{'
|
||||
// CHECK:STDOUT: │ ├─Lambda '}'
|
||||
// CHECK:STDOUT: ├─VariableDecl ';'
|
||||
// CHECK:STDOUT: │ ╭─VariableIntroducer 'var'
|
||||
// CHECK:STDOUT: │ │ ╭─IdentifierNameNotBeforeSignature 'd'
|
||||
// CHECK:STDOUT: │ │ ├─BindingPatternTypeStart ':'
|
||||
// CHECK:STDOUT: │ │ ├─AutoTypeLiteral 'auto'
|
||||
// CHECK:STDOUT: │ │ ╭─VarBindingPattern ':'
|
||||
// CHECK:STDOUT: │ ├─VariablePattern 'var'
|
||||
// CHECK:STDOUT: │ ├─VariableInitializer '='
|
||||
// CHECK:STDOUT: │ │ ╭─LambdaIntroducer 'fn'
|
||||
// CHECK:STDOUT: │ │ │ ╭─ExplicitParamListStart '('
|
||||
// CHECK:STDOUT: │ │ │ │ ╭─IdentifierNameNotBeforeSignature 'x'
|
||||
// CHECK:STDOUT: │ │ │ │ ╭─RefBindingName 'ref'
|
||||
// CHECK:STDOUT: │ │ │ │ ├─BindingPatternTypeStart ':'
|
||||
// CHECK:STDOUT: │ │ │ │ ├─IntTypeLiteral 'i32'
|
||||
// CHECK:STDOUT: │ │ │ ├─LetBindingPattern ':'
|
||||
// CHECK:STDOUT: │ │ ├─ExplicitParamList ')'
|
||||
// CHECK:STDOUT: │ │ │ ╭─IntTypeLiteral 'i32'
|
||||
// CHECK:STDOUT: │ │ │ ╭─PrefixOperatorRef 'ref'
|
||||
// CHECK:STDOUT: │ │ ├─ReturnForm '->?'
|
||||
// CHECK:STDOUT: │ │ ╭─LambdaDefinitionStart '{'
|
||||
// CHECK:STDOUT: │ │ │ ╭─ReturnStatementStart 'return'
|
||||
// CHECK:STDOUT: │ │ │ ├─IdentifierNameExpr 'x'
|
||||
// CHECK:STDOUT: │ │ ├─ReturnStatement ';'
|
||||
// CHECK:STDOUT: │ ├─Lambda '}'
|
||||
// CHECK:STDOUT: ├─VariableDecl ';'
|
||||
// CHECK:STDOUT: ├─FileEnd ''
|
||||
// CHECK:STDOUT: (root)
|
||||
@@ -132,12 +156,12 @@ fn G() {
|
||||
// CHECK:STDOUT: ╭─FileStart ''
|
||||
// CHECK:STDOUT: │ ╭─RequireIntroducer 'require'
|
||||
// CHECK:STDOUT: │ │ ╭─IdentifierNameExpr 'j'
|
||||
// CHECK:STDOUT: │ │ │ ╭─LambdaIntroducer 'fn'
|
||||
// CHECK:STDOUT: │ │ │ │ ╭─InvalidParse '>' has_error
|
||||
// CHECK:STDOUT: │ │ │ │ ├─InvalidParse '' has_error
|
||||
// CHECK:STDOUT: │ │ │ │ ╭─InfixOperatorGreater '>' has_error
|
||||
// CHECK:STDOUT: │ │ │ ├─ReturnType '->'
|
||||
// CHECK:STDOUT: │ │ │ ├─InvalidParse '' has_error
|
||||
// CHECK:STDOUT: │ │ │ ╭─LambdaIntroducer 'fn'
|
||||
// CHECK:STDOUT: │ │ │ │ ╭─InvalidParse '>' has_error
|
||||
// CHECK:STDOUT: │ │ │ │ ├─InvalidParse '' has_error
|
||||
// CHECK:STDOUT: │ │ │ │ ╭─InfixOperatorGreater '>' has_error
|
||||
// CHECK:STDOUT: │ │ │ ├─ReturnType '->'
|
||||
// CHECK:STDOUT: │ │ │ ╭─LambdaDefinitionStart '' has_error
|
||||
// CHECK:STDOUT: │ │ │ ╭─Lambda 'fn' has_error
|
||||
// CHECK:STDOUT: │ │ ├─PrefixOperatorMinus '-'
|
||||
// CHECK:STDOUT: │ ├─InfixOperatorPercent '%'
|
||||
@@ -158,8 +182,8 @@ fn G() {
|
||||
// CHECK:STDOUT: │ │ │ ╭─VarBindingPattern ':'
|
||||
// CHECK:STDOUT: │ │ ├─VariablePattern 'var'
|
||||
// CHECK:STDOUT: │ │ ├─VariableInitializer '='
|
||||
// CHECK:STDOUT: │ │ │ ╭─LambdaIntroducer 'fn'
|
||||
// CHECK:STDOUT: │ │ │ ├─InvalidParse ';' has_error
|
||||
// CHECK:STDOUT: │ │ │ ╭─LambdaIntroducer 'fn'
|
||||
// CHECK:STDOUT: │ │ │ ╭─LambdaDefinitionStart ';' has_error
|
||||
// CHECK:STDOUT: │ │ ├─Lambda 'fn' has_error
|
||||
// CHECK:STDOUT: │ ├─VariableDecl ';'
|
||||
// CHECK:STDOUT: ├─FunctionDefinition '}'
|
||||
@@ -179,10 +203,10 @@ fn G() {
|
||||
// CHECK:STDOUT: │ │ │ ╭─VarBindingPattern ':'
|
||||
// CHECK:STDOUT: │ │ ├─VariablePattern 'var'
|
||||
// CHECK:STDOUT: │ │ ├─VariableInitializer '='
|
||||
// CHECK:STDOUT: │ │ │ ╭─LambdaIntroducer 'fn'
|
||||
// CHECK:STDOUT: │ │ │ │ ╭─IntTypeLiteral 'i32'
|
||||
// CHECK:STDOUT: │ │ │ ├─ReturnType '->'
|
||||
// CHECK:STDOUT: │ │ │ ├─InvalidParse ';' has_error
|
||||
// CHECK:STDOUT: │ │ │ ╭─LambdaIntroducer 'fn'
|
||||
// CHECK:STDOUT: │ │ │ │ ╭─IntTypeLiteral 'i32'
|
||||
// CHECK:STDOUT: │ │ │ ├─ReturnType '->'
|
||||
// CHECK:STDOUT: │ │ │ ╭─LambdaDefinitionStart ';' has_error
|
||||
// CHECK:STDOUT: │ │ ├─Lambda 'fn' has_error
|
||||
// CHECK:STDOUT: │ ├─VariableDecl ';'
|
||||
// CHECK:STDOUT: ├─FunctionDefinition '}'
|
||||
|
||||
@@ -792,18 +792,27 @@ struct CodeBlock {
|
||||
using LambdaIntroducer =
|
||||
LeafNode<NodeKind::LambdaIntroducer, Lex::FnTokenIndex>;
|
||||
|
||||
struct Lambda {
|
||||
static constexpr auto Kind = NodeKind::Lambda.Define(
|
||||
{.category = NodeCategory::Expr, .bracketed_by = LambdaIntroducer::Kind});
|
||||
struct LambdaDefinitionStart {
|
||||
static constexpr auto Kind = NodeKind::LambdaDefinitionStart.Define(
|
||||
{.bracketed_by = LambdaIntroducer::Kind});
|
||||
|
||||
LambdaIntroducerId introducer;
|
||||
std::optional<ImplicitParamListId> implicit_params;
|
||||
std::optional<ExplicitParamListId> explicit_params;
|
||||
std::optional<ReturnTypeId> return_type;
|
||||
std::optional<AnyReturnDeclId> return_type;
|
||||
Lex::TokenIndex token;
|
||||
};
|
||||
|
||||
struct Lambda {
|
||||
static constexpr auto Kind =
|
||||
NodeKind::Lambda.Define({.category = NodeCategory::Expr,
|
||||
.bracketed_by = LambdaDefinitionStart::Kind});
|
||||
|
||||
LambdaDefinitionStartId signature;
|
||||
std::optional<TerseBodyArrowId> arrow;
|
||||
NodeId body;
|
||||
// Use a generic token index because the token might be `}` or part of an
|
||||
// expression.
|
||||
std::optional<AnyExprId> terse_body;
|
||||
llvm::SmallVector<AnyStatementId> body;
|
||||
// Use a generic token index because the token might be `}` or `fn`.
|
||||
Lex::TokenIndex token;
|
||||
};
|
||||
|
||||
|
||||
@@ -171,6 +171,7 @@ static auto IsDefinitionStart(Parse::NodeKind node_kind) -> bool {
|
||||
case Parse::NodeKind::FunctionDefinitionStart:
|
||||
case Parse::NodeKind::ImplDefinitionStart:
|
||||
case Parse::NodeKind::InterfaceDefinitionStart:
|
||||
case Parse::NodeKind::LambdaDefinitionStart:
|
||||
case Parse::NodeKind::NamedConstraintDefinitionStart:
|
||||
return true;
|
||||
default:
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
#include "toolchain/sem_ir/dump.h"
|
||||
#include "toolchain/sem_ir/entity_with_params_base.h"
|
||||
#include "toolchain/sem_ir/ids.h"
|
||||
#include "toolchain/sem_ir/import_ir.h"
|
||||
#include "toolchain/sem_ir/name_scope.h"
|
||||
#include "toolchain/sem_ir/typed_insts.h"
|
||||
|
||||
@@ -421,7 +422,19 @@ struct Worklist {
|
||||
}
|
||||
|
||||
auto Add(FunctionId function_id) -> void {
|
||||
AddEntity(sem_ir->functions().Get(function_id));
|
||||
const auto& function = sem_ir->functions().Get(function_id);
|
||||
if (!function.name_id.has_value()) {
|
||||
auto [canonical_ir, canonical_decl_id] =
|
||||
GetCanonicalFileAndInstId(sem_ir, function.first_decl_id());
|
||||
llvm::SaveAndRestore in_file(sem_ir, canonical_ir);
|
||||
AddPackage(NameScopeId::Package);
|
||||
AddLibrary(canonical_ir);
|
||||
// TODO: Find a more stable way to assign fingerprints to unnamed
|
||||
// functions.
|
||||
AddInteger(canonical_decl_id.index);
|
||||
return;
|
||||
}
|
||||
AddEntity(function);
|
||||
}
|
||||
|
||||
auto Add(CppOverloadSetId cpp_overload_set_id) -> void {
|
||||
|
||||
@@ -634,7 +634,9 @@ auto InstNamer::PushEntity(FunctionId function_id, ScopeId scope_id,
|
||||
scope.name = globals_.AllocateName(
|
||||
*this, fn_loc,
|
||||
llvm::formatv("{0}{1}{2}", scope_prefix, scope_prefix.empty() ? "" : ".",
|
||||
sem_ir_->names().GetIRBaseName(fn.name_id)));
|
||||
fn.name_id.has_value()
|
||||
? sem_ir_->names().GetIRBaseName(fn.name_id)
|
||||
: "fn"));
|
||||
if (!fn.body_block_ids.empty()) {
|
||||
AddBlockLabel(scope_id, fn.body_block_ids.front(), "entry", fn_loc);
|
||||
}
|
||||
|
||||
@@ -211,7 +211,11 @@ auto Mangler::MangleImpl(SemIR::FunctionId function_id,
|
||||
|
||||
os << "_C";
|
||||
|
||||
MangleNameId(os, function.name_id);
|
||||
if (function.name_id.has_value()) {
|
||||
MangleNameId(os, function.name_id);
|
||||
} else {
|
||||
os << "fn";
|
||||
}
|
||||
char separator = '.';
|
||||
|
||||
// For a special function, add a marker to disambiguate.
|
||||
@@ -275,7 +279,8 @@ auto Mangler::MangleImpl(SemIR::FunctionId function_id,
|
||||
MangleInverseQualifiedNameScope(os, function.parent_scope_id,
|
||||
SemIR::SpecificId::None, separator);
|
||||
|
||||
if (sem_ir().name_scopes().IsPrivateToLibrary(function.name_id,
|
||||
if (!function.name_id.has_value() ||
|
||||
sem_ir().name_scopes().IsPrivateToLibrary(function.name_id,
|
||||
function.parent_scope_id)) {
|
||||
os << ".";
|
||||
MangleFingerprint(os, &sem_ir(), function.first_decl_id());
|
||||
|
||||
@@ -158,6 +158,10 @@ class StepStack {
|
||||
|
||||
// Pushes all components of a qualified name (`A.B.C`) onto the stack.
|
||||
auto PushQualifiedName(NameScopeId name_scope_id, NameId name_id) -> void {
|
||||
if (!name_id.has_value()) {
|
||||
PushString("<unnamed>");
|
||||
return;
|
||||
}
|
||||
PushNameId(name_id);
|
||||
if (!qualified_names_) {
|
||||
return;
|
||||
@@ -671,8 +675,17 @@ class Stringifier {
|
||||
*out_ << "<C++ type " << clang_type.getAsString() << ">";
|
||||
}
|
||||
|
||||
auto StringifyInst(InstId /*inst_id*/, FunctionDecl inst) -> void {
|
||||
const auto& fn = sem_ir_->functions().Get(inst.function_id);
|
||||
step_stack_->PushQualifiedName(fn.parent_scope_id, fn.name_id);
|
||||
}
|
||||
|
||||
auto StringifyInst(InstId /*inst_id*/, FunctionType inst) -> void {
|
||||
const auto& fn = sem_ir_->functions().Get(inst.function_id);
|
||||
if (!fn.name_id.has_value()) {
|
||||
*out_ << "<type of function expression>";
|
||||
return;
|
||||
}
|
||||
*out_ << "<type of ";
|
||||
step_stack_->Push(
|
||||
StepStack::QualifiedNameItem{fn.parent_scope_id, fn.name_id}, ">");
|
||||
|
||||
Reference in new issue
Block a user