Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

@check convenience syntax for record/field-level value constraints #69

Open
jrevels opened this issue Nov 13, 2022 · 2 comments
Open

@check convenience syntax for record/field-level value constraints #69

jrevels opened this issue Nov 13, 2022 · 2 comments

Comments

@jrevels
Copy link
Member

jrevels commented Nov 13, 2022

Split out from #20. With Legolas v0.5 (ref #54), we have a much nicer disciplined stance on validation-by-construction, so the path forward for convenient record-level check constraints is much simpler.

We should define a simple helper @check that can be used in the following manner:

@version FooV1 begin
    x::String # unchecked
    @check(y::Int, y > 0)
    @check(z::Any, a_predicate(z) && another_predicate(z, x))
    @check(k::Int = clamp(k, 1, 10), 
           some_other_predicate(k))
    @check begin
        # record-level predicate(s)
    end
end

where the field-level @check expansion goes from statements like

@version FooV1 begin
    
    @check(f::T = $rhs, $predicate)
    
end

...to statements like:

f::T = $rhs
$predicate || throw(CheckConstraintError(:FooV1, :f, f, $stringified_predicate))

...where CheckConstraintError might look like:

struct CheckConstraintError <: Exception
    record_name::Symbol
    field_name::Symbol
    predicate::String
    received::Any
end

function Base.showerror(io::IO, e::CheckConstraintError)
    print(io, """
              Value received for $(e.field_name) of $(e.record_name): $(e.received)
              Violates `@check` constraint: $(e.predicate)
              """)
end
@ericphanson
Copy link
Member

Could this be done as a piece of syntax that @version understands, instead of as a new macro? To avoid clashes with ArgCheck.jl or other macros

@jrevels
Copy link
Member Author

jrevels commented Nov 14, 2022

Yup, that’s the intention, updated the title/OP to clarify

@jrevels jrevels changed the title @check convenience macro for record/field-level value constraints @check convenience syntax for record/field-level value constraints Nov 14, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants