Skip to main content

tonneau_build/codegen/cel/functions/
is_ipv4.rs

1use syn::parse_quote;
2use tonneau_cel::CelValue;
3
4use super::Function;
5use crate::codegen::cel::compiler::{
6    CompileError, CompiledExpr, CompilerCtx, ConstantCompiledExpr,
7};
8use crate::codegen::cel::types::CelType;
9use crate::types::{ProtoType, ProtoValueType};
10
11#[derive(Debug, Clone, Default)]
12pub(crate) struct IsIpv4;
13
14// this.isIpv4(arg) -> arg in this
15impl Function for IsIpv4 {
16    fn name(&self) -> &'static str {
17        "isIpv4"
18    }
19
20    fn syntax(&self) -> &'static str {
21        "<this>.isIpv4()"
22    }
23
24    fn compile(&self, ctx: CompilerCtx) -> Result<CompiledExpr, CompileError> {
25        let Some(this) = &ctx.this else {
26            return Err(CompileError::syntax("missing this", self));
27        };
28
29        if !ctx.args.is_empty() {
30            return Err(CompileError::syntax("does not take any arguments", self));
31        }
32
33        let this = this.clone().into_cel()?;
34
35        match this {
36            CompiledExpr::Constant(ConstantCompiledExpr { value }) => {
37                Ok(CompiledExpr::constant(CelValue::cel_is_ipv4(value)?))
38            }
39            this => Ok(CompiledExpr::runtime(
40                CelType::Proto(ProtoType::Value(ProtoValueType::Bool)),
41                parse_quote! {{
42                    ::tonneau::__private::cel::CelValue::cel_is_ipv4(
43                        #this,
44                    )?
45                }},
46            )),
47        }
48    }
49}
50
51#[cfg(test)]
52#[cfg(feature = "prost")]
53#[cfg_attr(coverage_nightly, coverage(off))]
54mod tests {
55    use syn::parse_quote;
56    use tonneau_cel::CelValue;
57
58    use crate::codegen::cel::compiler::{CompiledExpr, Compiler, CompilerCtx};
59    use crate::codegen::cel::functions::{Function, IsIpv4};
60    use crate::codegen::cel::types::CelType;
61    use crate::extern_paths::ExternPaths;
62    use crate::path_set::PathSet;
63    use crate::types::{ProtoType, ProtoTypeRegistry, ProtoValueType};
64
65    #[test]
66    fn test_is_ipv4_syntax() {
67        let registry = ProtoTypeRegistry::new(
68            crate::Mode::Prost,
69            ExternPaths::new(crate::Mode::Prost),
70            PathSet::default(),
71        );
72        let compiler = Compiler::new(&registry);
73        insta::assert_debug_snapshot!(IsIpv4.compile(CompilerCtx::new(compiler.child(), None, &[])), @r#"
74        Err(
75            InvalidSyntax {
76                message: "missing this",
77                syntax: "<this>.isIpv4()",
78            },
79        )
80        "#);
81
82        insta::assert_debug_snapshot!(IsIpv4.compile(CompilerCtx::new(compiler.child(), Some(CompiledExpr::constant(CelValue::String("192.168.1.1".into()))), &[])), @r"
83        Ok(
84            Constant(
85                ConstantCompiledExpr {
86                    value: Bool(
87                        true,
88                    ),
89                },
90            ),
91        )
92        ");
93
94        insta::assert_debug_snapshot!(IsIpv4.compile(CompilerCtx::new(compiler.child(), Some(CompiledExpr::constant(CelValue::String("www.scuffle.cloud".into()))), &[])), @r"
95        Ok(
96            Constant(
97                ConstantCompiledExpr {
98                    value: Bool(
99                        false,
100                    ),
101                },
102            ),
103        )
104        ");
105
106        insta::assert_debug_snapshot!(IsIpv4.compile(CompilerCtx::new(compiler.child(), Some(CompiledExpr::constant(CelValue::List(Default::default()))), &[
107            cel_parser::parse("1 + 1").unwrap(), // not an ident
108        ])), @r#"
109        Err(
110            InvalidSyntax {
111                message: "does not take any arguments",
112                syntax: "<this>.isIpv4()",
113            },
114        )
115        "#);
116    }
117
118    #[test]
119    #[cfg(not(valgrind))]
120    fn test_is_ipv4_runtime() {
121        let registry = ProtoTypeRegistry::new(
122            crate::Mode::Prost,
123            ExternPaths::new(crate::Mode::Prost),
124            PathSet::default(),
125        );
126        let compiler = Compiler::new(&registry);
127
128        let string_value = CompiledExpr::runtime(
129            CelType::Proto(ProtoType::Value(ProtoValueType::String)),
130            parse_quote!(input),
131        );
132
133        let output = IsIpv4
134            .compile(CompilerCtx::new(compiler.child(), Some(string_value), &[]))
135            .unwrap();
136
137        insta::assert_snapshot!(postcompile::compile_str!(
138            postcompile::config! {
139                test: true,
140                dependencies: vec![
141                    postcompile::Dependency::path("tonneau", "../tonneau"),
142                ],
143            },
144            quote::quote! {
145                fn is_ipv4(input: &str) -> Result<bool, ::tonneau::__private::cel::CelError<'_>> {
146                    Ok(#output)
147                }
148
149                #[test]
150                fn test_is_ipv4() {
151                    assert_eq!(is_ipv4("www.scuffle.cloud").unwrap(), false);
152                    assert_eq!(is_ipv4("192.168.1.1").unwrap(), true);
153                }
154            },
155        ));
156    }
157}