summaryrefslogtreecommitdiff
path: root/macros/src/util.rs
blob: 2e12ef17c55cdc5db0c31de20218ceffa57d6dec (plain) (blame)
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
use heck::ToKebabCase;
use quote::ToTokens;

use super::*;

/// Return an error at the given item.
macro_rules! bail {
    (callsite, $fmt:literal $($tts:tt)*) => {
        return Err(syn::Error::new(
            proc_macro2::Span::call_site(),
            format!(concat!("typst: ", $fmt) $($tts)*)
        ))
    };
    ($item:expr, $fmt:literal $($tts:tt)*) => {
        return Err(syn::Error::new_spanned(
            &$item,
            format!(concat!("typst: ", $fmt) $($tts)*)
        ))
    };
}

/// For parsing attributes of the form:
/// #[attr(
///   statement;
///   statement;
///   returned_expression
/// )]
pub struct BlockWithReturn {
    pub prefix: Vec<syn::Stmt>,
    pub expr: syn::Stmt,
}

impl Parse for BlockWithReturn {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut stmts = syn::Block::parse_within(input)?;
        let Some(expr) = stmts.pop() else {
            return Err(input.error("expected at least one expression"));
        };
        Ok(Self { prefix: stmts, expr })
    }
}

/// Whether an attribute list has a specified attribute.
pub fn has_attr(attrs: &mut Vec<syn::Attribute>, target: &str) -> bool {
    take_attr(attrs, target).is_some()
}

/// Whether an attribute list has a specified attribute.
pub fn parse_attr<T: Parse>(
    attrs: &mut Vec<syn::Attribute>,
    target: &str,
) -> Result<Option<Option<T>>> {
    take_attr(attrs, target)
        .map(|attr| (!attr.tokens.is_empty()).then(|| attr.parse_args()).transpose())
        .transpose()
}

/// Whether an attribute list has a specified attribute.
pub fn take_attr(
    attrs: &mut Vec<syn::Attribute>,
    target: &str,
) -> Option<syn::Attribute> {
    attrs
        .iter()
        .position(|attr| attr.path.is_ident(target))
        .map(|i| attrs.remove(i))
}

/// Ensure that no unrecognized attributes remain.
pub fn validate_attrs(attrs: &[syn::Attribute]) -> Result<()> {
    for attr in attrs {
        if !attr.path.is_ident("doc") {
            let ident = attr.path.get_ident().unwrap();
            bail!(ident, "unrecognized attribute: {:?}", ident.to_string());
        }
    }
    Ok(())
}

/// Convert an identifier to a kebab-case string.
pub fn kebab_case(name: &Ident) -> String {
    name.to_string().to_kebab_case()
}

/// Extract documentation comments from an attribute list.
pub fn documentation(attrs: &[syn::Attribute]) -> String {
    let mut doc = String::new();

    // Parse doc comments.
    for attr in attrs {
        if let Ok(syn::Meta::NameValue(meta)) = attr.parse_meta() {
            if meta.path.is_ident("doc") {
                if let syn::Lit::Str(string) = &meta.lit {
                    let full = string.value();
                    let line = full.strip_prefix(' ').unwrap_or(&full);
                    doc.push_str(line);
                    doc.push('\n');
                }
            }
        }
    }

    doc.trim().into()
}

/// Extract a line of metadata from documentation.
pub fn meta_line<'a>(lines: &mut Vec<&'a str>, key: &str) -> Result<&'a str> {
    match lines.last().and_then(|line| line.strip_prefix(&format!("{key}:"))) {
        Some(value) => {
            lines.pop();
            Ok(value.trim())
        }
        None => bail!(callsite, "missing metadata key: {}", key),
    }
}

/// Creates a block responsible for building a `Scope`.
pub fn create_scope_builder(scope_block: Option<&BlockWithReturn>) -> TokenStream {
    if let Some(BlockWithReturn { prefix, expr }) = scope_block {
        quote! { {
            let mut scope = ::typst::eval::Scope::deduplicating();
            #(#prefix);*
            #expr
        } }
    } else {
        quote! { ::typst::eval::Scope::new() }
    }
}

/// Quotes an option literally.
pub fn quote_option<T: ToTokens>(option: &Option<T>) -> TokenStream {
    if let Some(value) = option {
        quote! { Some(#value) }
    } else {
        quote! { None }
    }
}