elicitation 0.10.0

Conversational elicitation of strongly-typed Rust values via MCP
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! Char contract types.

use super::ValidationError;
use crate::{ElicitCommunicator, ElicitResult, Elicitation, Prompt};
use anodized::spec;
#[cfg(not(kani))]
use elicitation_macros::instrumented_impl;

// ============================================================================

/// Contract type for alphabetic char values.
///
/// Validates on construction, then can unwrap to stdlib char via `into_inner()`.
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    Hash,
    serde::Serialize,
    serde::Deserialize,
    schemars::JsonSchema,
)]
#[schemars(description = "An alphabetic character (a-z, A-Z)")]
pub struct CharAlphabetic(char);

#[cfg_attr(not(kani), instrumented_impl)]
impl CharAlphabetic {
    /// Constructs an alphabetic char.
    ///
    /// # Errors
    ///
    /// Returns `ValidationError::NotAlphabetic` if char is not alphabetic.
    #[cfg(not(kani))]
    #[spec(requires: [value.is_alphabetic()])]
    pub fn new(value: char) -> Result<Self, ValidationError> {
        if value.is_alphabetic() {
            Ok(Self(value))
        } else {
            Err(ValidationError::NotAlphabetic(value))
        }
    }

    /// Kani version: trust stdlib, verify wrapper logic.
    #[cfg(kani)]
    pub fn new(value: char) -> Result<Self, ValidationError> {
        // Symbolic boolean represents is_alphabetic() result
        // We verify our wrapper logic, not Unicode table implementation
        let is_alpha: bool = kani::any();
        if is_alpha {
            Ok(Self(value))
        } else {
            Err(ValidationError::NotAlphabetic(value))
        }
    }

    /// Gets the wrapped value.
    pub fn get(&self) -> char {
        self.0
    }

    /// Unwraps to stdlib char (trenchcoat off).
    pub fn into_inner(self) -> char {
        self.0
    }
}

crate::default_style!(CharAlphabetic => CharAlphabeticStyle);

impl Prompt for CharAlphabetic {
    fn prompt() -> Option<&'static str> {
        Some("Please enter an alphabetic character:")
    }
}

impl Elicitation for CharAlphabetic {
    type Style = CharAlphabeticStyle;

    #[tracing::instrument(skip(communicator), fields(type_name = "CharAlphabetic"))]
    async fn elicit<C: ElicitCommunicator>(communicator: &C) -> ElicitResult<Self> {
        tracing::debug!("Eliciting CharAlphabetic (alphabetic char)");

        loop {
            let value = char::elicit(communicator).await?;

            match Self::new(value) {
                Ok(alphabetic) => {
                    tracing::debug!(value = %value, "Valid CharAlphabetic constructed");
                    return Ok(alphabetic);
                }
                Err(e) => {
                    tracing::warn!(value = %value, error = %e, "Invalid CharAlphabetic, re-prompting");
                }
            }
        }
    }

    fn kani_proof() -> proc_macro2::TokenStream {
        crate::verification::proof_helpers::kani_char_alphabetic()
    }

    fn verus_proof() -> proc_macro2::TokenStream {
        crate::verification::proof_helpers::verus_char()
    }

    fn creusot_proof() -> proc_macro2::TokenStream {
        crate::verification::proof_helpers::creusot_char()
    }
}

/// Contract type for numeric char values.
///
/// Validates on construction, then can unwrap to stdlib char via `into_inner()`.
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    Hash,
    serde::Serialize,
    serde::Deserialize,
    schemars::JsonSchema,
)]
#[schemars(description = "A numeric character (0-9)")]
pub struct CharNumeric(char);

impl CharNumeric {
    /// Constructs a numeric char.
    ///
    /// # Errors
    ///
    /// Returns `ValidationError::NotNumeric` if char is not numeric.
    #[cfg(not(kani))]
    #[spec(requires: [value.is_numeric()])]
    pub fn new(value: char) -> Result<Self, ValidationError> {
        if value.is_numeric() {
            Ok(Self(value))
        } else {
            Err(ValidationError::NotNumeric(value))
        }
    }

    /// Kani version: trust stdlib, verify wrapper logic.
    #[cfg(kani)]
    pub fn new(value: char) -> Result<Self, ValidationError> {
        // Symbolic boolean represents is_numeric() result
        let is_numeric: bool = kani::any();
        if is_numeric {
            Ok(Self(value))
        } else {
            Err(ValidationError::NotNumeric(value))
        }
    }

    /// Gets the wrapped value.
    pub fn get(&self) -> char {
        self.0
    }

    /// Unwraps to stdlib char (trenchcoat off).
    pub fn into_inner(self) -> char {
        self.0
    }
}

crate::default_style!(CharNumeric => CharNumericStyle);

impl Prompt for CharNumeric {
    fn prompt() -> Option<&'static str> {
        Some("Please enter a numeric character:")
    }
}

impl Elicitation for CharNumeric {
    type Style = CharNumericStyle;

    #[tracing::instrument(skip(communicator), fields(type_name = "CharNumeric"))]
    async fn elicit<C: ElicitCommunicator>(communicator: &C) -> ElicitResult<Self> {
        tracing::debug!("Eliciting CharNumeric (numeric char)");

        loop {
            let value = char::elicit(communicator).await?;

            match Self::new(value) {
                Ok(numeric) => {
                    tracing::debug!(value = %value, "Valid CharNumeric constructed");
                    return Ok(numeric);
                }
                Err(e) => {
                    tracing::warn!(value = %value, error = %e, "Invalid CharNumeric, re-prompting");
                }
            }
        }
    }

    fn kani_proof() -> proc_macro2::TokenStream {
        crate::verification::proof_helpers::kani_char_numeric()
    }

    fn verus_proof() -> proc_macro2::TokenStream {
        crate::verification::proof_helpers::verus_char()
    }

    fn creusot_proof() -> proc_macro2::TokenStream {
        crate::verification::proof_helpers::creusot_char()
    }
}

/// Contract type for alphanumeric char values.
///
/// Validates on construction, then can unwrap to stdlib char via `into_inner()`.
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    Hash,
    serde::Serialize,
    serde::Deserialize,
    schemars::JsonSchema,
)]
#[schemars(description = "An alphanumeric character (a-z, A-Z, 0-9)")]
pub struct CharAlphanumeric(char);

#[cfg_attr(not(kani), instrumented_impl)]
impl CharAlphanumeric {
    /// Constructs an alphanumeric char.
    ///
    /// # Errors
    ///
    /// Returns `ValidationError::NotAlphanumeric` if char is not alphanumeric.
    #[spec(requires: [value.is_alphanumeric()])]
    pub fn new(value: char) -> Result<Self, ValidationError> {
        #[cfg(kani)]
        {
            // Under Kani: symbolic validation (trust stdlib char handling)
            let is_alphanumeric: bool = kani::any();
            if is_alphanumeric {
                Ok(Self(value))
            } else {
                Err(ValidationError::NotAlphanumeric(value))
            }
        }
        #[cfg(not(kani))]
        {
            // Production: actual validation
            if value.is_alphanumeric() {
                Ok(Self(value))
            } else {
                Err(ValidationError::NotAlphanumeric(value))
            }
        }
    }

    /// Gets the wrapped value.
    pub fn get(&self) -> char {
        self.0
    }

    /// Unwraps to stdlib char (trenchcoat off).
    pub fn into_inner(self) -> char {
        self.0
    }
}

crate::default_style!(CharAlphanumeric => CharAlphanumericStyle);

impl Prompt for CharAlphanumeric {
    fn prompt() -> Option<&'static str> {
        Some("Please enter an alphanumeric character:")
    }
}

impl Elicitation for CharAlphanumeric {
    type Style = CharAlphanumericStyle;

    #[tracing::instrument(skip(communicator), fields(type_name = "CharAlphanumeric"))]
    async fn elicit<C: ElicitCommunicator>(communicator: &C) -> ElicitResult<Self> {
        tracing::debug!("Eliciting CharAlphanumeric (alphanumeric char)");

        loop {
            let value = char::elicit(communicator).await?;

            match Self::new(value) {
                Ok(alphanumeric) => {
                    tracing::debug!(value = %value, "Valid CharAlphanumeric constructed");
                    return Ok(alphanumeric);
                }
                Err(e) => {
                    tracing::warn!(value = %value, error = %e, "Invalid CharAlphanumeric, re-prompting");
                }
            }
        }
    }

    fn kani_proof() -> proc_macro2::TokenStream {
        crate::verification::proof_helpers::kani_char_alphanumeric()
    }

    fn verus_proof() -> proc_macro2::TokenStream {
        crate::verification::proof_helpers::verus_char()
    }

    fn creusot_proof() -> proc_macro2::TokenStream {
        crate::verification::proof_helpers::creusot_char()
    }
}

#[cfg(test)]
mod char_alphabetic_tests {
    use super::*;

    #[test]
    fn char_alphabetic_new_valid() {
        let result = CharAlphabetic::new('a');
        assert!(result.is_ok());
        assert_eq!(result.unwrap().get(), 'a');
    }

    #[test]
    fn char_alphabetic_new_digit_invalid() {
        let result = CharAlphabetic::new('5');
        assert!(result.is_err());
    }

    #[test]
    fn char_alphabetic_into_inner() {
        let alphabetic = CharAlphabetic::new('z').unwrap();
        let value: char = alphabetic.into_inner();
        assert_eq!(value, 'z');
    }
}

#[cfg(test)]
mod char_numeric_tests {
    use super::*;

    #[test]
    fn char_numeric_new_valid() {
        let result = CharNumeric::new('5');
        assert!(result.is_ok());
        assert_eq!(result.unwrap().get(), '5');
    }

    #[test]
    fn char_numeric_new_letter_invalid() {
        let result = CharNumeric::new('a');
        assert!(result.is_err());
    }

    #[test]
    fn char_numeric_into_inner() {
        let numeric = CharNumeric::new('9').unwrap();
        let value: char = numeric.into_inner();
        assert_eq!(value, '9');
    }
}

#[cfg(test)]
mod char_alphanumeric_tests {
    use super::*;

    #[test]
    fn char_alphanumeric_new_valid_letter() {
        let result = CharAlphanumeric::new('a');
        assert!(result.is_ok());
        assert_eq!(result.unwrap().get(), 'a');
    }

    #[test]
    fn char_alphanumeric_new_valid_digit() {
        let result = CharAlphanumeric::new('5');
        assert!(result.is_ok());
        assert_eq!(result.unwrap().get(), '5');
    }

    #[test]
    fn char_alphanumeric_new_symbol_invalid() {
        let result = CharAlphanumeric::new('!');
        assert!(result.is_err());
    }

    #[test]
    fn char_alphanumeric_into_inner() {
        let alphanumeric = CharAlphanumeric::new('x').unwrap();
        let value: char = alphanumeric.into_inner();
        assert_eq!(value, 'x');
    }
}

// ── ToCodeLiteral impls ───────────────────────────────────────────────────────

mod emit_impls {
    use super::*;
    use crate::emit_code::ToCodeLiteral;
    use proc_macro2::TokenStream;

    impl ToCodeLiteral for CharAlphabetic {
        fn to_code_literal(&self) -> TokenStream {
            let c = self.get();
            quote::quote! { elicitation::CharAlphabetic::new(#c).expect("valid CharAlphabetic") }
        }
    }

    impl ToCodeLiteral for CharNumeric {
        fn to_code_literal(&self) -> TokenStream {
            let c = self.get();
            quote::quote! { elicitation::CharNumeric::new(#c).expect("valid CharNumeric") }
        }
    }

    impl ToCodeLiteral for CharAlphanumeric {
        fn to_code_literal(&self) -> TokenStream {
            let c = self.get();
            quote::quote! { elicitation::CharAlphanumeric::new(#c).expect("valid CharAlphanumeric") }
        }
    }
}

// ── ElicitIntrospect impls ────────────────────────────────────────────────────

macro_rules! impl_primitive_introspect {
    ($($ty:ty => $name:literal),+ $(,)?) => {
        $(
            impl crate::ElicitIntrospect for $ty {
                fn pattern() -> crate::ElicitationPattern {
                    crate::ElicitationPattern::Primitive
                }
                fn metadata() -> crate::TypeMetadata {
                    crate::TypeMetadata {
                        type_name: $name,
                        description: <$ty as crate::Prompt>::prompt(),
                        details: crate::PatternDetails::Primitive,
                    }
                }
            }
        )+
    };
}

impl_primitive_introspect!(
    CharAlphabetic => "CharAlphabetic",
    CharNumeric => "CharNumeric",
    CharAlphanumeric => "CharAlphanumeric",
);