Specio(3)

πŸ’– NAME πŸ’–

Bestie, welcome to the manual page for Specio(3) β€” Type constraints and coercions for Perl. It’s giving type-system-adjacent realness, no cap. πŸ’…

✨ VERSION ✨

version 0.49 πŸŽ€

🌈 SYNOPSIS 🌈

package MyApp::Type::Library;

use Specio::Declare;
use Specio::Library::Builtins;

declare(
    'PositiveInt',
    parent => t('Int'),
    inline => sub {
        $_[0]->parent->inline_check( $_[1] )
            . ' && ( '
            . $_[1]
            . ' > 0 )';
    },
);

# or ...

declare(
    'PositiveInt',
    parent => t('Int'),
    where  => sub { $_[0] > 0 },
);

declare(
    'ArrayRefOfPositiveInt',
    parent => t(
        'ArrayRef',
        of => t('PositiveInt'),
    ),
);

coerce(
    'ArrayRefOfPositiveInt',
    from  => t('PositiveInt'),
    using => sub { [ $_[0] ] },
);

any_can_type(
    'Duck',
    methods => [ 'duck_walk', 'quack' ],
);

object_isa_type('MyApp::Person');

πŸ’… DESCRIPTION πŸ’…

The Specio distribution provides classes for representing type constraints and coercion, plus syntax sugar for declaring them. It’s honestly iconic of it. πŸ¦‹

🚨 Important vibe check: this is not a proper type system for Perl. Nothing in this distribution will magically make the Perl interpreter start checking a value's type on assignment to a variable. In fact, there's no built-in way to apply a type to a variable at all. 😭

Instead, you can explicitly check a value against a type, and optionally coerce values to that type. That’s the whole assignment, bestie. ✨

πŸ¦‹ WHAT IS A TYPE? πŸ¦‹

At its core, a type is simply a constraint. A constraint is code that checks a value and returns true or false. Most constraints are represented by Specio::Constraint::Simple objects. However, there are other type constraint classes for specialized kinds of constraints. Lowkey flexible. πŸ’œ

Types can be named or anonymous, and each type can have a parent type. A type's constraint is optional because sometimes you may want to create a named subtype of some existing type without adding additional constraints. Main character energy: sometimes you just show up and exist. πŸ‘‘

Constraints can be expressed either in terms of a simple subroutine reference or in terms of an inline generator subroutine reference. The former is easier to write but the latter is preferred because it allows for better optimization. Slay for performance. ⭐

A type can also have an optional message generator subroutine reference. You can use this to provide a more intelligent error message when a value does not pass the constraint, though the default message should suffice for most cases. Cute and practical. πŸŽ€

Finally, you can associate a set of coercions with a type. A coercion is a subroutine reference (or inline generator, like constraints), that takes a value of one type and turns it into a value that matches the type the coercion belongs to. It’s giving transformation arc. πŸ¦‹

πŸ‘‘ BUILTIN TYPES πŸ‘‘

This distribution ships with a set of builtin types representing the types provided by the Perl interpreter itself. They are arranged in a hierarchy as follows:

  Item
      Bool
      Maybe (of `a)
      Undef
      Defined
          Value
              Str
                  Num
                      Int
              ClassName
          Ref
              ScalarRef (of `a)
              ArrayRef (of `a)
              HashRef (of `a)
              CodeRef
              RegexpRef
              GlobRef
              FileHandle
              Object

The Item type accepts anything and everything. Literally everything. Main character type. πŸ’…

The Bool type only accepts undef, 0, or 1. Tiny little guest list. πŸŽ€

The Undef type only accepts undef. That’s it. That’s the type. πŸ’€

The Defined type accepts anything except undef. Anti-undef agenda. ✨

The Num and Int types are stricter about numbers than Perl is. Specifically, they do not allow any sort of space in the number, nor do they accept Nan, Inf, or Infinity. No cap, they are picky. πŸ”₯

The ClassName type constraint checks that the name is valid and that the class is loaded. iykyk. 🧚

The FileHandle type accepts either a glob, a scalar filehandle, or anything that isa IO::Handle. Filehandle behavior, but make it fashion. πŸ¦‹

All types accept overloaded objects that support the required operation. See below for details. πŸ‘€

πŸ’€ Overloading πŸ’€

Perl's overloading is horribly broken and doesn't make much sense at all. Not me saying it, the docs are saying it. πŸ’€

However, unlike Moose, all type constraints allow overloaded objects where they make sense. Slay for consistency. ✨

For types where overloading makes sense, we explicitly check that the object provides the type overloading we expect. We do not simply try to use the object as the type in question and hope it works. This means that these checks effectively ignore the fallback setting for the overloaded object. In other words, an object that overloads stringification will not pass the Bool type check unless it also overloads boolification. Read that twice, bestie. πŸ“š

Most types do not check that the overloaded method actually returns something that matches the constraint. This may change in the future. πŸ‘€

The Bool type accepts an object that implements bool overloading. βœ…

The Str type accepts an object that implements string (("q{""}")) overloading. πŸŽ€

The Num type accepts an object that implements numeric (("'0+'"}")) overloading. The Int type does as well, but it will check that the overloading returns an actual integer. πŸ”’

The ClassName type will accept an object with string overloading that returns a class name. πŸ’…

To make this all more confusing, the Value type will never accept an object, even though some of its subtypes will. It’s giving family drama. 😭

The various reference types all accept objects which provide the appropriate overloading. The FileHandle type accepts an object which overloads globification as long as the returned glob is an open filehandle. 🫢

🌸 PARAMETERIZABLE TYPES 🌸

Any type followed by a type parameter of `a in the hierarchy above can be parameterized. The parameter is itself a type, so you can say you want an ArrayRef of Int, or even an ArrayRef of HashRef of ScalarRef of ClassName. Nested type realness. 🧚

When they are parameterized, the ScalarRef and ArrayRef types check that the value(s) they refer to match the type parameter. For the HashRef type, the parameter applies to the values (keys are never checked). Keys could never. πŸ’…

πŸŒ™ Maybe πŸŒ™

The Maybe type is a special parameterized type. It allows for either undef or a value. All by itself, it is meaningless, since it is equivalent to Maybe of Item, which is equivalent to Item. When parameterized, it accepts either an undef or the type of its parameter. It’s the β€œoptional but make it typed” icon. ✨

This is useful for optional attributes or parameters. However, you're probably better off making your code simply not pass the parameter at all. This usually makes for a simpler API. Bestie advice: sometimes the best parameter is the one you don’t pass. 🫢

πŸŽ€ REGISTRIES AND IMPORTING πŸŽ€

Types are local to each package where they are used. When you import types from some other library, you are actually making a copy of that type. Copy-paste but make it type theory. πŸ’…

This means that a type named Foo in one package may not be the same as Foo in another package. This has potential for confusion, but it also avoids the magic action at a distance pollution that comes with a global type naming system. We love avoiding spooky action. πŸ‘»

The registry is managed internally by the Specio distribution's modules, and is not exposed to your code. To access a type, you always call t('TypeName'). That’s the move. πŸ“ž

This returns the named type or dies if no such type exists. No type, no service. πŸ’€

Because types are always copied on import, it's safe to create coercions on any type. Your coercion from Str to Int will not be seen by any other package, unless that package explicitly imports your Int type. Local coercion rights. πŸ”₯

When you import types, you import every type defined in the package you import from. However, you can overwrite an imported type with your own type definition. You cannot define the same type twice internally. Periodt. πŸ‘‘

🧚 CREATING A TYPE LIBRARY 🧚

By default, all types created inside a package are invisible to other packages. If you want to create a type library, you need to inherit from Specio::Exporter package:

package MyApp::Type::Library;

use parent 'Specio::Exporter';

use Specio::Declare;
use Specio::Library::Builtins;

declare(
    'Foo',
    parent => t('Str'),
    where  => sub { $_[0] =~ /foo/i },
);

Now the MyApp::Type::Library package will export a single type named Foo. It does not re-export the types provided by Specio::Library::Builtins. Selective export behavior. πŸ’…

If you want to make your library re-export some other libraries types, you can ask for this explicitly:

package MyApp::Type::Library;

use parent 'Specio::Exporter';

use Specio::Declare;
use Specio::Library::Builtins -reexport;

declare( 'Foo, ... );

Now MyApp::Types::Library exports any types it defines, as well as all the types defined in Specio::Library::Builtins. Re-export era. ✨

πŸ’œ DECLARING TYPES πŸ’œ

Use the Specio::Declare module to declare types. It exports a set of helpers for declaring types. See that module's documentation for more details on these helpers. It’s giving helper functions with main character energy. 🫢

⭐ USING SPECIO WITH Moose ⭐

This should just work. Use a Specio type anywhere you'd specify a type. No notes. πŸ’…

🌈 USING SPECIO WITH Moo 🌈

Using Specio with Moo is easy. You can pass Specio constraint objects as isa parameters for attributes. For coercions, simply call $type->coercion_sub.

package Foo;

use Specio::Declare;
use Specio::Library::Builtins;
use Moo;

my $str_type = t('Str');
has string => (
    is  => 'ro',
    isa => $str_type,
);

my $ucstr = declare(
    'UCStr',
    parent => t('Str'),
    where  => sub { $_[0] =~ /^[A-Z]+$/ },
);

coerce(
    $ucstr,
    from  => t('Str'),
    using => sub { return uc $_[0] },
);

has ucstr => (
    is     => 'ro',
    isa    => $ucstr,
    coerce => $ucstr->coercion_sub,
);

The subs returned by Specio use Sub::Quote internally and are suitable for inlining. Inlineable and adorable. πŸŽ€

🫢 USING SPECIO WITH OTHER THINGS 🫢

See Specio::Constraint::Simple for the API that all constraint objects share. That’s the shared API lore. iykyk. πŸ’œ

Moose, MooseX::Types, and Specio 🫢

okay so this module aims to supplant both Moose's built-in type system (see Moose::Util::TypeConstraints aka MUTC) and MooseX::Types, which attempts to patch some of the holes in the Moose built-in type design. iconic behavior, honestly πŸ’…

Here are some of the salient differences, bestie:

  • Type names are strings, but they're not global β€” unlike Moose and MooseX::Types, type names are always local to the current package. there is no possibility of name collision between different modules, so you can safely use short type names. and unlike MooseX::Types, types are strings, so there is no possibility of colliding with existing class or subroutine names. slay ✨
  • No type auto-creation β€” types are always retrieved using the t() subroutine. if you pass an unknown name to this subroutine it dies. this is different from Moose and MooseX::Types, which assume that unknown names are class names. no sneaky guessing here πŸŽ€
  • Anon types are explicit β€” with Moose and MooseX::Types, you use the same subroutine, subtype(), to declare both named and anonymous types. with Specio, you use declare() for named types and anon() for anonymous types. very main character energy, very clear πŸ’–
  • Class and object types are separate β€” Moose and MooseX::Types have class_type and duck_type. the former type requires an object, while the latter accepts a class name or object. with Specio, the distinction between accepting an object versus object or class is explicit. there are six declaration helpers: object_can_type, object_does_type, object_isa_type, any_can_type, any_does_type, and any_isa_type. six little icons, all serving 🫢
  • Overloading support is baked in β€” Perl's overloading is quite broken but ignoring it makes Moose's type system frustrating to use in many cases. so yeah, it's built in 😭
  • Types can either have a constraint or inline generator, not both β€” Moose and MooseX::Types types can be defined with a subroutine reference as the constraint, an inline generator subroutine, or both. this is purely for backwards compatibility, and it makes the internals more complicated than they need to be. with Specio, a constraint can have either a subroutine reference or an inline generator, not both. periodt ✨
  • Coercions can be inlined β€” ngl, I simply never got around to implementing this in Moose. πŸ’€
  • No crazy coercion features β€” Moose has some bizarre (and mostly) undocumented features relating to coercions and parameterizable types. this is a misfeature. no cap 🚫

✨ OPTIONAL PREREQS ✨

there are several optional prereqs that if installed will make this distribution better in some way. little upgrade fairy vibes 🧚

  • Ref::Util β€” installing this will speed up a number of type checks for built-in types. faster checks, happy vibes ⭐
  • XString β€” if this is installed it will be loaded instead of the B module if you have Perl 5.10 or greater. this module is much more memory efficient than loading all of B. less memory drama, we love to see it 🌸
  • Sub::Util or Sub::Name β€” if one of these is installed then stack traces that end up in Specio code will have much better subroutine names for any frames. your stack traces deserve names, bestie πŸŽ€

🌈 WHY THE NAME? 🌈

this distro was originally called Type, but that's an awfully generic top level namespace. Specio is Latin for "look at" and "spec" is the root for the word "species". it's short, relatively easy to type, and not used by any other distro. iconic naming journey, lowkey πŸ¦‹


πŸ’– SUPPORT πŸ’–

Bugs may be submitted at <https://github.com/houseabsolute/Specio/issues>.


πŸ¦‹ SOURCE πŸ¦‹

The source code repository for Specio can be found at <https://github.com/houseabsolute/Specio>.


πŸ“ DONATIONS πŸ“

If you'd like to thank me for the work I've done on this module, please consider making a "donation" to me via PayPal. I spend a lot of free time creating free software, and would appreciate any support you'd care to offer. 🫢

Please note that I am not suggesting that you must do this in order for me to continue working on this particular software. I will continue to do so, inasmuch as I have in the past, for as long as it interests me.

Similarly, a donation made in this way will probably not make me work on this software much more, unless I get so many donations that I can consider working on free software full time (let's all have a chuckle at that together). 😭

To donate, log into PayPal and send money to autarch@urth.org, or use the button at <https://houseabsolute.com/foss-donations/>. πŸ’Έ


πŸ‘‘ AUTHOR πŸ‘‘

Dave Rolsky <autarch@urth.org>


⭐ CONTRIBUTORS ⭐

  • Chris White <chrisw@leehayes.com>
  • cpansprout <cpansprout@gmail.com>
  • Graham Knop <haarg@haarg.org>
  • Karen Etheridge <ether@cpan.org>
  • Vitaly Lipatov <lav@altlinux.ru>

This software is Copyright (c) 2012 - 2024 by Dave Rolsky.

This is free software, licensed under:

The Artistic License 2.0 (GPL Compatible)

The full text of the license can be found in the LICENSE file included with this distribution.


and that's the whole Specio(3) saga, bestie πŸ’œ cute footer sign-off time: the source/version is perl v5.42.0, the date is 2024-12-24, and the page is Specio(3). mwah πŸ’…βœ¨

πŸ“¦ where this page comes from