Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions xls/dslx/tests/errors/duplicate_enum_match_arm.x
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Copyright 2026 The XLS Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

enum Example: u2 { A = 0, B = 1, C = 2 }

fn main(value: Example) -> u32 {
match value {
Example::A => u32:0,
Example::B | Example::A => u32:1,
Example::C => u32:2,
}
}
12 changes: 12 additions & 0 deletions xls/dslx/tests/errors/error_modules_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -538,6 +538,18 @@ def test_duplicate_match_arm(self):
self.assertIn('duplicate_match_arm.x:22:5-22:8', stderr)
self.assertIn('Exact-duplicate pattern match detected `FOO`', stderr)

def test_duplicate_enum_match_arm(self):
stderr = self._run(
'xls/dslx/tests/errors/duplicate_enum_match_arm.x',
)
self.assertIn('duplicate_enum_match_arm.x:19:5-19:15', stderr)
self.assertIn('duplicate_enum_match_arm.x:20:18-20:28', stderr)
self.assertIn('Exact-duplicate pattern match detected `Example::A`', stderr)
self.assertIn(
'previously @ xls/dslx/tests/errors/duplicate_enum_match_arm.x:19:5-19:15',
stderr,
)

def test_trace_fmt_empty_err(self):
stderr = self._run(
'xls/dslx/tests/errors/trace_fmt_empty.x',
Expand Down
1 change: 1 addition & 0 deletions xls/dslx/type_system_v2/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -535,6 +535,7 @@ cc_library(
"//xls/dslx:errors",
"//xls/dslx:import_data",
"//xls/dslx:import_routines",
"//xls/dslx:status_payload_utils",
"//xls/dslx/frontend:ast",
"//xls/dslx/frontend:ast_cloner",
"//xls/dslx/frontend:ast_node",
Expand Down
18 changes: 18 additions & 0 deletions xls/dslx/type_system_v2/import_utils.cc
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,24 @@ absl::StatusOr<std::optional<const EnumDef*>> GetEnumDef(
return unwrapper.GetEnumDef();
}

absl::StatusOr<std::optional<const NameDef*>> ResolveEnumMember(
const ColonRef* colon_ref, const ImportData& import_data) {
TypeRefUnwrapper unwrapper(import_data);
XLS_RETURN_IF_ERROR(ToAstNode(colon_ref->subject())->Accept(&unwrapper));

std::optional<const NameDef*> enum_member;
if (std::optional<const EnumDef*> enum_def = unwrapper.GetEnumDef();
enum_def.has_value()) {
for (const EnumMember& member : (*enum_def)->values()) {
if (member.name_def->identifier() == colon_ref->attr()) {
enum_member = member.name_def;
break;
}
}
}
return enum_member;
}

bool IsImport(const ColonRef* colon_ref) {
if (colon_ref->ResolveImportSubject().has_value()) {
return true;
Expand Down
5 changes: 5 additions & 0 deletions xls/dslx/type_system_v2/import_utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,11 @@ absl::StatusOr<std::optional<ModuleInfo*>> GetImportedModuleInfo(
absl::StatusOr<std::optional<const EnumDef*>> GetEnumDef(
const TypeAnnotation* annotation, const ImportData& import_data);

// Resolves an enum member through type aliases. Returns `nullopt` if the
// reference does not identify an enum or the enum has no matching member.
absl::StatusOr<std::optional<const NameDef*>> ResolveEnumMember(
const ColonRef* colon_ref, const ImportData& import_data);

// Returns whether `f` is a `next` function in an impl-style proc.
absl::StatusOr<bool> IsProcDefNextFunction(const Function* f,
const ImportData& import_data);
Expand Down
49 changes: 41 additions & 8 deletions xls/dslx/type_system_v2/populate_table_visitor.cc
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
#include "xls/dslx/frontend/pos.h"
#include "xls/dslx/import_data.h"
#include "xls/dslx/import_routines.h"
#include "xls/dslx/status_payload_utils.h"
#include "xls/dslx/type_system/deduce_utils.h"
#include "xls/dslx/type_system_v2/import_utils.h"
#include "xls/dslx/type_system_v2/inference_table.h"
Expand Down Expand Up @@ -594,19 +595,29 @@ class PopulateInferenceTableVisitor : public PopulateTableVisitor,
file_table_);
}

auto duplicate_pattern_error = [this](const Span& original_span,
const Span& duplicate_span,
std::string_view pattern) {
absl::Status status = absl::InvalidArgumentError(absl::StrFormat(
"TypeInferenceError: Exact-duplicate pattern match detected `%s`; "
"only the first could possibly match; previously @ %s",
pattern, original_span.ToString(file_table_)));
AddSpanToStatusPayload(status, duplicate_span, import_data_.file_table());
AddSpanToStatusPayload(status, original_span, import_data_.file_table());
return status;
};

std::vector<TypeAnnotation*> type_annotation_members;
absl::flat_hash_set<std::string> seen_patterns;
absl::flat_hash_map<std::string, const MatchArm*> seen_arms;
absl::flat_hash_map<std::string, Span> seen_patterns;
absl::flat_hash_map<const NameDef*, Span> seen_enum_members;
for (MatchArm* arm : node->arms()) {
// Identify syntactically identical match arms.
std::string patterns_string = PatternsToString(arm);
if (auto [it, inserted] = seen_patterns.insert(patterns_string);
if (auto [it, inserted] = seen_arms.try_emplace(patterns_string, arm);
!inserted) {
return TypeInferenceErrorStatus(
arm->GetPatternSpan(), nullptr,
absl::StrFormat("Exact-duplicate pattern match detected `%s`; only "
"the first could possibly match",
patterns_string),
file_table_);
return duplicate_pattern_error(it->second->GetPatternSpan(),
arm->GetPatternSpan(), patterns_string);
}

if (node->IsConst()) {
Expand All @@ -624,6 +635,28 @@ class PopulateInferenceTableVisitor : public PopulateTableVisitor,
}

for (const PatternTree& pattern : arm->patterns()) {
if (auto [it, inserted] = seen_patterns.try_emplace(
PatternToString(pattern), GetPatternSpan(pattern));
!inserted) {
return duplicate_pattern_error(it->second, GetPatternSpan(pattern),
it->first);
}

if (std::holds_alternative<ColonRef*>(pattern)) {
const ColonRef* colon_ref = std::get<ColonRef*>(pattern);
XLS_ASSIGN_OR_RETURN(std::optional<const NameDef*> enum_member,
ResolveEnumMember(colon_ref, import_data_));
if (enum_member.has_value()) {
if (auto [it, inserted] = seen_enum_members.try_emplace(
*enum_member, GetPatternSpan(pattern));
!inserted) {
return duplicate_pattern_error(it->second,
GetPatternSpan(pattern),
PatternToString(pattern));
}
}
}

XLS_RETURN_IF_ERROR(
table_.SetTypeVariable(ToAstNode(pattern), matched_var));
}
Expand Down
138 changes: 138 additions & 0 deletions xls/dslx/type_system_v2/typecheck_module_v2_control_flow_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -880,6 +880,144 @@ const Z = match X {
HasSubstr("Exact-duplicate pattern match detected `u32:1`")));
}

TEST(TypecheckV2Test, MatchEnumVariantDuplicatedAcrossAlternativeArms) {
constexpr std::string_view kProgram = R"(
enum E: u2 {
A = 0,
B = 1,
C = 2,
}

fn f(value: E) -> u32 {
match value {
E::A => u32:0,
E::B | E::A => u32:1,
E::C => u32:2,
}
}
)";

EXPECT_THAT(
kProgram,
TypecheckFailsWithPayload(
AllOf(HasSubstr("Exact-duplicate pattern match detected `E::A`"),
HasSubstr("previously @ fake.x:12:5-12:9")),
AllOf(HasSpan(11, 4, 11, 8), HasSpan(12, 11, 12, 15))));
}

// Type aliases do not create distinct enum members, even when their match
// patterns have different source spellings.
TEST(TypecheckV2Test, MatchEnumVariantDuplicatedThroughTypeAlias) {
EXPECT_THAT(
R"(
enum E: u2 { A = 0, B = 1 }
type Alias = E;

fn f(value: E) -> u32 {
match value {
E::A => u32:0,
Alias::A => u32:1,
E::B => u32:2,
}
}
)",
TypecheckFailsWithPayload(
AllOf(HasSubstr("Exact-duplicate pattern match detected `Alias::A`"),
HasSubstr("previously @ fake.x:9:5-9:9")),
AllOf(HasSpan(8, 4, 8, 8), HasSpan(9, 4, 9, 12))));
}

TEST(TypecheckV2Test, MatchEnumVariantDuplicatedThroughChainedTypeAliases) {
EXPECT_THAT(
R"(
enum E: u2 { A = 0, B = 1 }
type First = E;
type Second = First;

fn f(value: E) -> u32 {
match value {
First::A => u32:0,
Second::A => u32:1,
E::B => u32:2,
}
}
)",
TypecheckFails(
HasSubstr("Exact-duplicate pattern match detected `Second::A`")));
}

TEST(TypecheckV2Test,
MatchEnumVariantDuplicatedThroughTypeAliasInGroupedAlternatives) {
EXPECT_THAT(
R"(
enum E: u2 { A = 0, B = 1, C = 2 }
type Alias = E;

fn f(value: E) -> u32 {
match value {
E::A => u32:0,
E::B | Alias::A => u32:1,
E::C => u32:2,
}
}
)",
TypecheckFails(
HasSubstr("Exact-duplicate pattern match detected `Alias::A`")));
}

TEST(TypecheckV2Test, MatchImportedEnumVariantDuplicatedThroughTypeAlias) {
constexpr std::string_view kImported = R"(
pub enum E: u2 { A = 0, B = 1 }
pub type ImportedAlias = E;
)";
constexpr std::string_view kProgram = R"(
import imported;
type Alias = imported::ImportedAlias;

fn f(value: Alias) -> u32 {
match value {
imported::E::A => u32:0,
Alias::A => u32:1,
imported::E::B => u32:2,
}
}
)";

ImportData import_data = CreateImportDataForTest();
XLS_EXPECT_OK(TypecheckV2(kImported, "imported", &import_data));
EXPECT_THAT(
TypecheckV2(kProgram, "main", &import_data),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Exact-duplicate pattern match detected `Alias::A`")));
}

TEST(TypecheckV2Test, MatchDistinctEnumVariantsThroughTypeAliasRemainValid) {
XLS_EXPECT_OK(TypecheckV2(R"(
enum E: u2 { A = 0, B = 1, C = 2 }
type Alias = E;

fn f(value: E) -> u32 {
match value {
E::A => u32:0,
Alias::B | Alias::C => u32:1,
}
}
)"));
}

TEST(TypecheckV2Test, MatchEnumVariantAlternativesRemainValid) {
XLS_EXPECT_OK(TypecheckV2(R"(
enum E: u2 { A = 0, B = 1, C = 2 }

fn f(value: E) -> u32 {
match value {
E::A => u32:0,
E::B | E::C => u32:1,
}
}
)"));
}

TEST(TypecheckV2Test, MatchNonExhaustive) {
EXPECT_THAT(R"(
fn f(x: u1) -> u32 {
Expand Down