cxx_qt_gen/syntax/
expr.rs

1// SPDX-FileCopyrightText: 2023 Klarälvdalens Datakonsult AB, a KDAB Group company <info@kdab.com>
2// SPDX-FileContributor: Andrew Hayzen <andrew.hayzen@kdab.com>
3//
4// SPDX-License-Identifier: MIT OR Apache-2.0
5
6use syn::{spanned::Spanned, Error, Expr, ExprLit, Lit, Result};
7
8/// Convert a given [syn::Expr] to a String
9pub fn expr_to_string(expr: &Expr) -> Result<String> {
10    if let Expr::Lit(ExprLit {
11        lit: Lit::Str(lit_str),
12        ..
13    }) = expr
14    {
15        return Ok(lit_str.value());
16    }
17
18    Err(Error::new(expr.span(), "Expected a string literal!"))
19}
20
21#[cfg(test)]
22mod tests {
23    use syn::parse_quote;
24
25    use super::*;
26
27    #[test]
28    fn test_expr_lit_int() {
29        assert!(expr_to_string(&parse_quote! { 1 }).is_err());
30    }
31
32    #[test]
33    fn test_expr_lit_str() {
34        assert_eq!(
35            expr_to_string(&parse_quote! { "literal" }).unwrap(),
36            "literal".to_owned()
37        );
38    }
39
40    #[test]
41    fn test_expr_path() {
42        assert!(expr_to_string(&parse_quote! { std::collections::HashMap }).is_err());
43    }
44}