1use crate::compiler::prelude::*;
2
3fn string(value: Value) -> Resolved {
4 match value {
5 v @ Value::Bytes(_) => Ok(v),
6 v => Err(format!("expected string, got {}", v.kind()).into()),
7 }
8}
9
10#[derive(Clone, Copy, Debug)]
11pub struct String;
12
13impl Function for String {
14 fn identifier(&self) -> &'static str {
15 "string"
16 }
17
18 fn usage(&self) -> &'static str {
19 "Returns `value` if it is a string, otherwise returns an error. This enables the type checker to guarantee that the returned value is a string and can be used in any function that expects a string."
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 a string."]
28 }
29
30 fn return_kind(&self) -> u16 {
31 kind::BYTES
32 }
33
34 fn return_rules(&self) -> &'static [&'static str] {
35 &[
36 "Returns the `value` if it's a string.",
37 "Raises an error if not a string.",
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 a string.",
46 )];
47 PARAMETERS
48 }
49
50 fn examples(&self) -> &'static [Example] {
51 &[
52 example! {
53 title: "Declare a string type",
54 source: indoc! {r#"
55 . = { "message": "{\"field\": \"value\"}" }
56 string(.message)
57 "#},
58 result: Ok(r#""{\"field\": \"value\"}""#),
59 },
60 example! {
61 title: "Invalid type",
62 source: "string!(true)",
63 result: Err(
64 r#"function call error for "string" at (0:13): expected string, got boolean"#,
65 ),
66 },
67 ]
68 }
69
70 fn compile(
71 &self,
72 _state: &state::TypeState,
73 _ctx: &mut FunctionCompileContext,
74 arguments: ArgumentList,
75 ) -> Compiled {
76 let value = arguments.required("value");
77
78 Ok(StringFn { value }.as_expr())
79 }
80}
81
82#[derive(Debug, Clone)]
83struct StringFn {
84 value: Box<dyn Expression>,
85}
86
87impl FunctionExpression for StringFn {
88 fn resolve(&self, ctx: &mut Context) -> Resolved {
89 string(self.value.resolve(ctx)?)
90 }
91
92 fn type_def(&self, state: &state::TypeState) -> TypeDef {
93 let non_bytes = !self.value.type_def(state).is_bytes();
94
95 TypeDef::bytes().maybe_fallible(non_bytes)
96 }
97}