inator/
expr.rs

1/*
2 * This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5 */
6
7//! Allowed expressions.
8
9use proc_macro2::Span;
10
11/// Convert to a variety of source-code-related formats.
12pub trait Expression: core::fmt::Debug {
13    /// Convert `&Self -> syn::Expr`.
14    #[must_use]
15    fn to_expr(&self) -> syn::Expr;
16    /// Convert `&Self -> syn::Pat`.
17    #[must_use]
18    fn to_pattern(&self) -> syn::Pat;
19    /// Write a `syn::Type` type representing this value's type.
20    #[must_use]
21    fn to_type() -> syn::Type;
22}
23
24impl Expression for char {
25    #[inline]
26    fn to_expr(&self) -> syn::Expr {
27        syn::Expr::Lit(syn::ExprLit {
28            attrs: vec![],
29            lit: syn::Lit::Char(syn::LitChar::new(*self, Span::call_site())),
30        })
31    }
32    #[inline]
33    fn to_pattern(&self) -> syn::Pat {
34        syn::Pat::Lit(syn::ExprLit {
35            attrs: vec![],
36            lit: syn::Lit::Char(syn::LitChar::new(*self, Span::call_site())),
37        })
38    }
39    #[inline]
40    fn to_type() -> syn::Type {
41        syn::Type::Path(syn::TypePath {
42            qself: None,
43            path: syn::Path {
44                leading_colon: None,
45                segments: core::iter::once(syn::PathSegment {
46                    ident: syn::Ident::new("char", Span::call_site()),
47                    arguments: syn::PathArguments::None,
48                })
49                .collect(),
50            },
51        })
52    }
53}
54
55impl Expression for u8 {
56    #[inline]
57    fn to_expr(&self) -> syn::Expr {
58        syn::Expr::Lit(syn::ExprLit {
59            attrs: vec![],
60            lit: syn::Lit::Byte(syn::LitByte::new(*self, Span::call_site())),
61        })
62    }
63    #[inline]
64    fn to_pattern(&self) -> syn::Pat {
65        syn::Pat::Lit(syn::ExprLit {
66            attrs: vec![],
67            lit: syn::Lit::Byte(syn::LitByte::new(*self, Span::call_site())),
68        })
69    }
70    #[inline]
71    fn to_type() -> syn::Type {
72        syn::Type::Path(syn::TypePath {
73            qself: None,
74            path: syn::Path {
75                leading_colon: None,
76                segments: core::iter::once(syn::PathSegment {
77                    ident: syn::Ident::new("u8", Span::call_site()),
78                    arguments: syn::PathArguments::None,
79                })
80                .collect(),
81            },
82        })
83    }
84}