Skip to content

Commit

Permalink
Merge pull request #3227 from Kaiepi/enum-typing
Browse files Browse the repository at this point in the history
Document how to type enums
  • Loading branch information
JJ committed Feb 23, 2020
2 parents 25fb71d + 9d4101b commit 982e43a
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
38 changes: 38 additions & 0 deletions doc/Language/typesystem.pod6
Expand Up @@ -817,6 +817,44 @@ Firstly, we read lines from C<config> file, split every line using
C<words> method and return resulting pair for every line, thus
creating a List of Pairs.
=head3 Typing Enums
When declaring enums with an explicit scope, a type may be provided,
which will be used to typecheck the enum's values:
=for code
my Str enum Foo (foo => 'foo');
All enum pairs are typed as L<Enumeration|/type/Enumeration>. In
addition, when the enum values are typed as C<Numeric>, C<Stringy>, or a
combination of these two types, enum pairs also do the
C<NumericEnumeration>, C<StringyEnumeration>, and
C<NumericStringyEnumeration> roles respectively. These simply determine
how enum pairs get stringified with the C<Str> method.
Given that these types are roles, naturally you can provide your own
roles when declaring an enum, which allows you to give them custom
behavior and state. For example, to make it simpler to check if a number
matches a flag in a bitmask enum, you could write a
C<BitmaskEnumeration> role with an C<ACCEPTS> method to handle this via
smartmatching:
=begin code
role BitmaskEnumeration {
multi method ACCEPTS(::?CLASS:D: Int:D $value --> Bool:D) {
so $value +& self.value
}
}
enum Flags does BitmaskEnumeration (
FLAG_FOO => 0b001,
FLAG_BAR => 0b010,
FLAG_BAZ => 0b100,
);
say 0b111 ~~ FLAG_FOO & FLAG_BAR & FLAG_BAZ; # OUTPUT: «True␤»
=end code
=head3 Metaclass
To test if a given type object is an C<enum>, test the metaobject method
Expand Down
3 changes: 3 additions & 0 deletions xt/code.pws
Expand Up @@ -107,6 +107,7 @@ binarytree
bindingtype
birthdaycongrats
bisectable
BitmaskEnumeration
bitrary
bj
bloatable
Expand Down Expand Up @@ -410,6 +411,7 @@ nswp
ntop
numerichost
numericserv
NumericStringyEnumeration
numillo
numlist
obai
Expand Down Expand Up @@ -512,6 +514,7 @@ statm
stmt
strdistance
strillo
StringyEnumeration
strorarrayofstr
strs
su
Expand Down
1 change: 1 addition & 0 deletions xt/words.pws
Expand Up @@ -124,6 +124,7 @@ bindkey
bindoruse
binmode
bitbucket
bitmask
bitwise
bom
bool
Expand Down

0 comments on commit 982e43a

Please sign in to comment.