2222
2323local M = {}
2424
25+ --- Internal functions to be overwritten when desired
26+ --- @type table<string , function>
27+ M .fn = {}
28+
29+ --- Assert function
30+ --- @type fun ( assertion : boolean , message : string )
31+ M .fn .assert = function (assertion , message )
32+ assert (assertion , message )
33+ end
34+
35+ --- Print error function
36+ --- @type fun ( reason : string )
37+ M .fn .error = function (reason )
38+ error (reason )
39+ end
40+
41+ --- Pretty printer function
42+ --- @type fun ( object : any ): string
43+ M .fn .pretty_print = function (object )
44+ return tostring (object )
45+ end
46+
2547-- predicates
2648
2749--- Tests if value is a string
@@ -86,7 +108,15 @@ function M.all_of(...)
86108
87109 for _ , pred in ipairs (predicates ) do
88110 if type (pred ) ~= " function" then
89- error " Spec must be a function (e.g. spec.keys for tables)"
111+ M .fn .error (
112+ string.format (
113+ " spec.lua: Spec '%s' must be a function (e.g. spec.keys for tables)" ,
114+ M .fn .pretty_print (pred )
115+ )
116+ )
117+ return function ()
118+ return false
119+ end
90120 end
91121 end
92122
@@ -109,7 +139,15 @@ function M.any_of(...)
109139
110140 for _ , pred in ipairs (predicates ) do
111141 if type (pred ) ~= " function" then
112- error " Spec must be a function (e.g. spec.keys for tables)"
142+ M .fn .error (
143+ string.format (
144+ " spec.lua: Spec '%s' must be a function (e.g. spec.keys for tables)" ,
145+ M .fn .pretty_print (pred )
146+ )
147+ )
148+ return function ()
149+ return false
150+ end
113151 end
114152 end
115153
151189--- @return boolean
152190function M .valid (spec , value )
153191 if type (spec ) ~= " function" then
154- error " Spec must be a function (e.g. spec.keys for tables)"
192+ M .fn .error (
193+ string.format (" spec.lua: Spec '%s' must be a function (e.g. spec.keys for tables)" , M .fn .pretty_print (spec ))
194+ )
195+ return false
155196 end
156197
157198 return spec (value )
176217--- @param value T
177218--- @return T
178219function M .assert (spec , value )
179- assert (M .valid (spec , value ))
220+ M .fn .assert (
221+ M .valid (spec , value ),
222+ string.format (
223+ " spec.lua: Assertion failed because '%s' doesn't conform to spec '%s'" ,
224+ M .fn .pretty_print (value ),
225+ M .fn .pretty_print (spec )
226+ )
227+ )
180228 return value
181229end
182230
0 commit comments