1use crate::compiler::prelude::*;
2
3fn int(value: Value) -> Resolved {
4 match value {
5 v @ Value::Integer(_) => Ok(v),
6 v => Err(format!("expected integer, got {}", v.kind()).into()),
7 }
8}
9
10#[derive(Clone, Copy, Debug)]
11pub struct Integer;
12
13impl Function for Integer {
14 fn identifier(&self) -> &'static str {
15 "int"
16 }
17
18 fn usage(&self) -> &'static str {
19 "Returns `value` if it is an integer, otherwise returns an error. This enables the type checker to guarantee that the returned value is an integer and can be used in any function that expects an integer."
20 }
21
22 fn category(&self) -> &'static str {
23 Category::Type.as_ref()
24 }
25
26 fn internal_failure_reasons(&self) -> &'static [&'static str] {
27 &["`value` is not an integer."]
28 }
29
30 fn return_kind(&self) -> u16 {
31 kind::INTEGER
32 }
33
34 fn return_rules(&self) -> &'static [&'static str] {
35 &[
36 "Returns the `value` if it's an integer.",
37 "Raises an error if not an integer.",
38 ]
39 }
40
41 fn parameters(&self) -> &'static [Parameter] {
42 const PARAMETERS: &[Parameter] = &[Parameter::required(
43 "value",
44 kind::ANY,
45 "The value to check if it is an integer.",
46 )];
47 PARAMETERS
48 }
49
50 fn examples(&self) -> &'static [Example] {
51 &[
52 example! {
53 title: "Declare an integer type",
54 source: indoc! {r#"
55 . = { "value": 42 }
56 int(.value)
57 "#},
58 result: Ok("42"),
59 },
60 example! {
61 title: "Declare an integer type (literal)",
62 source: "int(42)",
63 result: Ok("42"),
64 },
65 example! {
66 title: "Invalid integer type",
67 source: "int!(true)",
68 result: Err(
69 r#"function call error for "int" at (0:10): expected integer, got boolean"#,
70 ),
71 },
72 ]
73 }
74
75 fn compile(
76 &self,
77 _state: &state::TypeState,
78 _ctx: &mut FunctionCompileContext,
79 arguments: ArgumentList,
80 ) -> Compiled {
81 let value = arguments.required("value");
82
83 Ok(IntegerFn { value }.as_expr())
84 }
85}
86
87#[derive(Debug, Clone)]
88struct IntegerFn {
89 value: Box<dyn Expression>,
90}
91
92impl FunctionExpression for IntegerFn {
93 fn resolve(&self, ctx: &mut Context) -> Resolved {
94 int(self.value.resolve(ctx)?)
95 }
96
97 fn type_def(&self, state: &state::TypeState) -> TypeDef {
98 let non_integer = !self.value.type_def(state).is_integer();
99
100 TypeDef::integer().maybe_fallible(non_integer)
101 }
102}