1
1
# Returns the given value if it is an instance of the given type, and raises an error otherwise.
2
# Optionally, if a block is given (accepting two parameters), it will be called instead of raising
3
# an error. This to enable giving the user richer feedback, or to supply a default value.
3
5
# @example how to assert type
4
6
# # assert that `$b` is a non empty `String` and assign to `$a`
5
7
# $a = assert_type(String[1], $b)
9
# @example using custom error message
10
# $a = assert_type(String[1], $b) |$expected, $actual| { fail("The name cannot be empty") }
12
# @example using a warning and a default
13
# $a = assert_type(String[1], $b) |$expected, $actual| { warning("Name is empty, using default") 'anonymous' }
7
15
# See the documentation for "The Puppet Type System" for more information about types.
9
17
Puppet::Functions.create_function(:assert_type) do
10
18
dispatch :assert_type do
11
19
param 'Type', 'type'
12
param 'Optional[Object]', 'value'
21
optional_block_param 'Callable[Type, Type]', 'block'
15
24
dispatch :assert_type_s do
16
25
param 'String', 'type_string'
17
param 'Optional[Object]', 'value'
27
optional_block_param 'Callable[Type, Type]', 'block'
20
30
# @param type [Type] the type the value must be an instance of
21
# @param value [Optional[Object]] the value to assert
31
# @param value [Object] the value to assert
23
def assert_type(type, value)
33
def assert_type(type, value, block=nil)
24
34
unless Puppet::Pops::Types::TypeCalculator.instance?(type,value)
25
35
inferred_type = Puppet::Pops::Types::TypeCalculator.infer(value)
26
# Do not give all the details - i.e. format as Integer, instead of Integer[n, n] for exact value, which
27
# is just confusing. (OTOH: may need to revisit, or provide a better "type diff" output.
29
actual = Puppet::Pops::Types::TypeCalculator.generalize!(inferred_type)
30
raise Puppet::ParseError, "assert_type(): Expected type #{type} does not match actual: #{actual}"
37
# Give the inferred type to allow richer comparisson in the given block (if generalized
38
# information is lost).
40
value = block.call(nil, type, inferred_type)
42
# Do not give all the details - i.e. format as Integer, instead of Integer[n, n] for exact value, which
43
# is just confusing. (OTOH: may need to revisit, or provide a better "type diff" output.
45
actual = Puppet::Pops::Types::TypeCalculator.generalize!(inferred_type)
46
raise Puppet::ParseError, "assert_type(): Expected type #{type} does not match actual: #{actual}"
35
52
# @param type_string [String] the type the value must be an instance of given in String form
36
# @param value [Optional[Object]] the value to assert
53
# @param value [Object] the value to assert
38
55
def assert_type_s(type_string, value)
39
56
t = Puppet::Pops::Types::TypeParser.new.parse(type_string)