8000 Configuration via trait-bound generics by rw1nkler · Pull Request #5589 · google/xls · GitHub
[go: up one dir, main page]

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

Filter by extension

Filter by extension 8000

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 104 additions & 0 deletions docs_src/dslx_reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -772,6 +772,110 @@ fn foo<N: u32>() -> u32 { Foo<N>::N_PLUS_1 }
fn test_foo32() { assert_eq(foo<u32:32>(), u32:33); }
```

#### Trait Constants

A `trait` declares a set of named constants, each with a default value. A struct
implements the trait with an `impl Trait for Struct` block, which may override
any subset of the trait's constants; the ones it does not mention keep the
trait's defaults. Traits are currently gated behind the `traits` feature.

```dslx
#![feature(traits)]

trait Cfg {
const WIDTH: u32 = u32:8;
const OFFSET: u32 = u32:1;
const TOTAL: u32 = Self::WIDTH + Self::OFFSET;
}

struct CfgDefault {}

impl Cfg for CfgDefault {}

struct CfgWide {}

impl Cfg for CfgWide {
const WIDTH = u32:32;
}

#[test]
fn test_trait_constants() {
assert_eq(CfgDefault::WIDTH, u32:8);
assert_eq(CfgWide::WIDTH, u32:32);
assert_eq(CfgWide::OFFSET, u32:1);
assert_eq(CfgWide::TOTAL, u32:33);
}
```

* Trait constants are accessed through the implementing struct's name, e.g.
`CfgWide::WIDTH`.
* Every trait constant must have a default value. Trait members are
implicitly public, so `pub` is not allowed on them.
* An overriding constant in the `impl` may omit its type annotation; its type
is taken from the trait. Overriding with a value of a different type, or
defining a constant that is not a member of the trait, is an error.
* Within a trait constant, `Self::NAME` refers to the value of `NAME` for the
implementing struct, not to the trait's default. In the example above,
`CfgWide::TOTAL` is computed from the overridden `WIDTH`. A trait constant
that uses `Self` must have an explicit type annotation.
* A public trait defined in another module can be implemented as
`impl imported::Cfg for S { ... }`.

#### Trait-Bound Generics

A struct implementing a trait can be passed as a generic type parameter
(declared as `T: type`) to a function, struct, or proc. Inside the generic
entity, the trait constants of the type are accessible as `T::NAME` and can be
used anywhere a constant expression is expected, including in types. This
allows a whole set of related configuration values to be passed as a single
parametric, with only the values that differ from the defaults restated. This
feature is gated behind the `generics` feature in addition to `traits`.

```dslx
#![feature(generics)]
#![feature(traits)]

trait Cfg {
const WIDTH: u32 = u32:8;
const OFFSET: u32 = u32:1;
}

struct CfgDefault {}

impl Cfg for CfgDefault {}

struct CfgWide {}

impl Cfg for CfgWide {
const WIDTH = u32:32;
const OFFSET = u32:4;
}

fn offset_by<T: type>(x: u8) -> uN[T::WIDTH] { x as uN[T::WIDTH] + T::OFFSET as uN[T::WIDTH] }

#[test]
fn test_offset_by() {
assert_eq(offset_by<CfgDefault>(u8:5), u8:6);
assert_eq(offset_by<CfgWide>(u8:5), u32:9);
}
```

The same applies to procs, where `T::NAME` can be used in proc-scoped
constants, channel types, and parametrics of spawned procs:

```dslx-snippet
proc Producer<T: type> {
const N = T::WIDTH + T::OFFSET;
c: chan<uN[N]> out;
...
}

spawn Producer<CfgWide>(s);
```

Referring to a constant that is not provided by the struct's trait `impl` (e.g.
`T::NONE`) results in a type error at the point of instantiation.

### Array Type

Arrays can be constructed via bracket notation. All values that make up the
Expand Down
17 changes: 13 additions & 4 deletions xls/dslx/fmt/ast_fmt.cc
Original file line number Diff line number Diff line change
Expand Up @@ -3057,7 +3057,9 @@ DocRef Formatter::FormatImplOrTrait(const T& n, Keyword keyword,
Pos last_member_pos = n.span().start();
bool last_was_func = false;
for (int i = 0; i < n.members().size(); i++) {
const ImplMember member = n.members().at(i);
// Widen a `TraitMember` to share the formatting below.
const ImplMember member = absl::visit(
[](auto* m) -> ImplMember { return m; }, n.members().at(i));
if (i > 0 && (last_was_func || std::holds_alternative<Function*>(member))) {
body_pieces.push_back(arena_.hard_line());
}
Expand Down Expand Up @@ -3092,8 +3094,15 @@ DocRef Formatter::FormatImplOrTrait(const T& n, Keyword keyword,
}

DocRef Formatter::FormatImpl(const Impl& n) {
return FormatImplOrTrait(n, Keyword::kImpl,
FormatTypeAnnotation(*n.struct_ref()));
DocRef struct_ref = FormatTypeAnnotation(*n.struct_ref());
if (n.trait_name().has_value()) {
const Expr* trait_name = n.trait_name().value();
// `impl Trait for Struct` or `impl module::Trait for Struct`
struct_ref = ConcatN(
arena_, {FormatExpr(*trait_name), arena_.space(),
arena_.Make(Keyword::kFor), arena_.space(), struct_ref});
}
return FormatImplOrTrait(n, Keyword::kImpl, struct_ref);
}

DocRef Formatter::FormatTrait(const Trait& n) {
Expand Down Expand Up @@ -3895,7 +3904,7 @@ absl::StatusOr<DocRef> Formatter::FormatModule(const Module& n) {
pieces.push_back(arena_.hard_line());
break;
case ModuleAttribute::kTraits:
pieces.push_back(arena_.MakeText("#[feature(traits)]"));
pieces.push_back(arena_.MakeText("#![feature(traits)]"));
pieces.push_back(arena_.hard_line());
break;
case ModuleAttribute::kIoObjects:
Expand Down
27 changes: 27 additions & 0 deletions xls/dslx/fmt/ast_fmt_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -4772,5 +4772,32 @@ pub fn f(x: u32, flag: bool) -> u32 {
)");
}

TEST_F(ModuleFmtTest, TraitWithConstants) {
DoFmt(R"(#![feature(traits)]

pub trait Cfg {
const W: u32 = u32:8;
const D: u32 = u32:4;
}
)");
}

TEST_F(ModuleFmtTest, ImplOfTrait) {
DoFmtWithFunctionStubs(R"(pub trait Cfg {
const W: u32 = u32:8;
const D: u32 = u32:4;
}

struct MyStruct {}

impl Cfg for MyStruct {
const W = u32:16;
}

struct Other {}

impl Cfg for Other {}
)");
}
} // namespace
} // namespace xls::dslx
67 changes: 62 additions & 5 deletions xls/dslx/frontend/ast.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2145,19 +2145,26 @@ std::string ProcDef::ToString() const {
// -- class Impl

Impl::Impl(Module* owner, Span span, TypeAnnotation* struct_ref,
const std::vector<ImplMember> members, bool is_public)
const std::vector<ImplMember> members, bool is_public,
std::optional<Expr*> trait_name, std::optional<Trait*> trait_ref)
: AstNode(owner),
span_(std::move(span)),
struct_ref_(struct_ref),
members_(members),
public_(is_public) {}
public_(is_public),
trait_name_(trait_name),
trait_ref_(trait_ref) {}

Impl::~Impl() = default;

std::string Impl::ToString() const {
std::string type_name = ToAstNode(struct_ref_)->ToString();
std::string result =
absl::StrFormat("%simpl %s {\n", public_ ? "pub " : "", type_name);
std::string trait_string =
trait_name_.has_value()
? absl::StrFormat("%s for ", (*trait_name_)->ToString())
: "";
std::string result = absl::StrFormat("%simpl %s%s {\n", public_ ? "pub " : "",
trait_string, type_name);
for (const auto& member : members_) {
if (std::holds_alternative<Function*>(member)) {
Function* func = std::get<Function*>(member);
Expand Down Expand Up @@ -2246,7 +2253,7 @@ std::optional<Function*> Impl::GetFunction(std::string_view name) const {
// -- class Trait

Trait::Trait(Module* owner, Span span, NameDef* name_def,
std::vector<Function*> members, bool is_public)
std::vector<TraitMember> members, bool is_public)
: AstNode(owner),
span_(std::move(span)),
name_def_(name_def),
Expand All @@ -2255,6 +2262,56 @@ Trait::Trait(Module* owner, Span span, NameDef* name_def,

Trait::~Trait() = default;

template <typename T>
std::vector<T> Trait::GetMembersOfType() const {
std::vector<T> results;
for (const TraitMember& member : members_) {
if (std::holds_alternative<T>(member)) {
results.push_back(std::get<T>(member));
}
}
return results;
}

std::vector<Function*> Trait::GetFunctions() const {
return GetMembersOfType<Function*>();
}

std::vector<ConstantDef*> Trait::GetConstants() const {
return GetMembersOfType<ConstantDef*>();
}

std::optional<ConstantDef*> Trait::GetConstant(std::string_view name) const {
return GetMemberOfType<ConstantDef*>(name);
}

template <typename T>
std::optional<T> Trait::GetMemberOfType(std::string_view name) const {
std::optional<TraitMember> result = GetMember(name);
if (result.has_value() && std::holds_alternative<T>(*result)) {
return std::get<T>(*result);
}
return std::nullopt;
}

static std::string TraitMemberIdentifier(const TraitMember member) {
return absl::visit(
Visitor{
[](const ConstantDef* n) { return n->name_def()->identifier(); },
[](const Function* n) { return n->name_def()->identifier(); },
},
member);
}

std::optional<TraitMember> Trait::GetMember(std::string_view name) const {
for (const auto& member : members_) {
if (TraitMemberIdentifier(member) == name) {
return member;
}
}
return std::nullopt;
}

std::string Trait::ToString() const {
std::string result =
absl::Substitute("$0trait $1 {\n", public_ ? "pub " : "", identifier());
Expand Down
52 changes: 46 additions & 6 deletions xls/dslx/frontend/ast.h
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ XLS_DSLX_AST_NODE_EACH(FORWARD_DECL)

class StructDefBase;
class StructInstanceBase;
class Trait;

using AggregateDeclaration =
std::variant<const StructDefBase*, const SumVariant*>;
Expand Down Expand Up @@ -3763,7 +3764,9 @@ using ImplMember =
class Impl : public AstNode {
public:
Impl(Module* owner, Span span, TypeAnnotation* struct_ref,
std::vector<ImplMember> members, bool is_public);
std::vector<ImplMember> members, bool is_public,
std::optional<Expr*> trait_name = std::nullopt,
std::optional<Trait*> trait_ref = std::nullopt);

~Impl() override;

Expand Down Expand Up @@ -3813,14 +3816,23 @@ class Impl : public AstNode {
// Returns the function with the given name if present.
std::optional<Function*> GetFunction(std::string_view name) const;

// Used by trait derivation to add derived members.
void AddMember(Function* member) { members_.push_back(member); }
// Used by trait derivation, and for trait defaults instantiated per impl.
void AddMember(ImplMember member) { members_.push_back(member); }

// The trait as written: a `NameRef`, or a `ColonRef` if imported.
std::optional<Expr*> trait_name() const { return trait_name_; }

// The linked trait; an imported one is linked during type inference.
std::optional<Trait*> trait_ref() const { return trait_ref_; }
void set_trait_ref(Trait* trait_ref) { trait_ref_ = trait_ref; }

private:
Span span_;
TypeAnnotation* struct_ref_;
std::vector<ImplMember> members_;
bool public_;
std::optional<Expr*> trait_name_;
std::optional<Trait*> trait_ref_;

template <typename T>
std::optional<T> GetMemberOfType(std::string_view name) const;
Expand Down Expand Up @@ -3884,10 +3896,12 @@ class Lambda : public Expr {
}
};

using TraitMember = std::variant<ConstantDef*, Function*>;

class Trait : public AstNode {
public:
Trait(Module* owner, Span span, NameDef* name_def,
std::vector<Function*> members, bool is_public);
std::vector<TraitMember> members, bool is_public);

~Trait() override;

Expand All @@ -3909,13 +3923,39 @@ class Trait : public AstNode {
const Span& span() const { return span_; }
std::optional<Span> GetSpan() const override { return span_; }

const std::vector<Function*>& members() const { return members_; }
const std::vector<TraitMember>& members() const { return members_; }

static std::string_view GetDebugTypeName() { return "trait"; }

// Returns all the constants from this trait
std::vector<ConstantDef*> GetConstants() const;
// Returns all the functions from this trait
std::vector<Function*> GetFunctions() const;

// Returns the constant with the given name if present.
std::optional<ConstantDef*> GetConstant(std::string_view name) const;

// Returns the member with the given name, if present.
std::optional<TraitMember> GetMember(std::string_view name) const;

// A hidden impl with no overrides, used to type-check the `Self` defaults.
std::optional<Impl*> default_check_impl() const {
return default_check_impl_;
}
void set_default_check_impl(Impl* impl) { default_check_impl_ = impl; }

private:
Span span_;
NameDef* name_def_;
std::vector<Function*> members_;
std::vector<TraitMember> members_;
bool public_;
std::optional<Impl*> default_check_impl_;

template <typename T>
std::optional<T> GetMemberOfType(std::string_view name) const;

template <typename T>
std::vector<T> GetMembersOfType() const;
};

// A virtual base class for nodes that directly instantiate a struct.
Expand Down
Loading
0