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
//! proc macro crate that implements the `#[spandoc::spandoc]` attribute. See
//[`spandoc`](https://docs.rs/spandoc) documentation for details.
#![doc(html_root_url = "https://docs.rs/spandoc-attribute/0.1.0")]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![warn(
    missing_docs,
    missing_doc_code_examples,
    rust_2018_idioms,
    unreachable_pub,
    bad_style,
    const_err,
    dead_code,
    improper_ctypes,
    non_shorthand_field_patterns,
    no_mangle_generic_items,
    overflowing_literals,
    path_statements,
    patterns_in_fns_without_body,
    private_in_public,
    unconditional_recursion,
    unused,
    unused_allocation,
    unused_comparisons,
    unused_parens,
    while_true
)]

use proc_macro::TokenStream;
use proc_macro2::Ident;
use quote::quote_spanned;
use syn::{
    fold::Fold, spanned::Spanned, Attribute, AttributeArgs, Block, ExprAsync, ExprAwait, ItemFn,
    Meta, Signature,
};

#[proc_macro_attribute]
/// entrypoint for spandoc attribute proc macro
pub fn spandoc(args: TokenStream, item: TokenStream) -> TokenStream {
    let input: ItemFn = syn::parse_macro_input!(item as ItemFn);
    let _args = syn::parse_macro_input!(args as AttributeArgs);

    let span = input.span();
    let ItemFn {
        attrs,
        vis,
        block,
        sig,
        ..
    } = input;

    let Signature { ref ident, .. } = sig;

    let block = SpanInstrumentedExpressions {
        ident: ident.clone(),
    }
    .fold_block(*block);

    quote_spanned!( span =>
        #(#attrs) *
        #[allow(clippy::cognitive_complexity)]
        #vis #sig
        #block
    )
    .into()
}

struct InstrumentAwaits;

impl Fold for InstrumentAwaits {
    fn fold_expr_async(&mut self, i: ExprAsync) -> ExprAsync {
        i
    }

    fn fold_expr_await(&mut self, i: ExprAwait) -> ExprAwait {
        let mut i = syn::fold::fold_expr_await(self, i);

        let span = i.span();
        let base = i.base;
        let base = quote_spanned! { span => __fancy_guard.wrap(#base) };

        let base = syn::parse2(base).unwrap();
        i.base = Box::new(base);
        i
    }
}

struct SpanInstrumentedExpressions {
    ident: Ident,
}

impl Fold for SpanInstrumentedExpressions {
    fn fold_block(&mut self, block: Block) -> Block {
        let block_span = block.span();
        let mut block = syn::fold::fold_block(self, block);

        let stmts = block.stmts;
        let mut new_stmts = proc_macro2::TokenStream::new();
        let last = stmts.len() - 1;

        for (i, mut stmt) in stmts.into_iter().enumerate() {
            let stmt_span = stmt.span();

            let as_span = |attr: Attribute| {
                let meta = attr.parse_meta().ok()?;
                let lit = match meta {
                    Meta::NameValue(syn::MetaNameValue {
                        lit: syn::Lit::Str(lit),
                        ..
                    }) => lit,
                    _ => return None,
                };

                let (lit, args) = args::split(lit)?;
                let span_name = format!("{}::comment", self.ident);

                let span = match args {
                    Some(args) => {
                        quote_spanned! { lit.span() =>
                            tracing::span!(tracing::Level::ERROR, #span_name, #args, text = %#lit)
                        }
                    }
                    None => quote_spanned! { lit.span() =>
                        tracing::span!(tracing::Level::ERROR, #span_name, text = %#lit)
                    },
                };

                Some(span)
            };

            let attrs = if let Some(attrs) = attr::from_stmt(&mut stmt) {
                attrs
            } else {
                new_stmts.extend(quote_spanned! { stmt_span => #stmt });
                continue;
            };

            let ind = if let Some(ind) = attr::find_doc_attr_ind(attrs) {
                ind
            } else {
                new_stmts.extend(quote_spanned! { stmt_span => #stmt });
                continue;
            };

            let attr = attrs[ind].clone();
            let span = as_span(attr);

            let stmt = if span.is_some() {
                attrs.remove(ind);
                InstrumentAwaits.fold_stmt(stmt)
            } else {
                stmt
            };

            let stmts = match span {
                Some(span) if i == last => {
                    quote_spanned! { stmt_span =>
                        let __dummy_span = #span;
                        let __fancy_guard = spandoc::FancyGuard::new(&__dummy_span);
                        #stmt
                    }
                }
                Some(span) => {
                    quote_spanned! { stmt_span =>
                        let __dummy_span = #span;
                        let __fancy_guard = spandoc::FancyGuard::new(&__dummy_span);
                        #stmt
                        drop(__fancy_guard);
                        drop(__dummy_span);
                    }
                }
                _ => quote_spanned! { stmt_span => #stmt },
            };

            new_stmts.extend(stmts);
        }

        let new_block = quote_spanned! { block_span =>
            {
                #new_stmts
            }
        };

        let new_block: Block = syn::parse2(new_block).unwrap();

        block.stmts = new_block.stmts;
        block
    }
}

mod attr {
    use syn::{Attribute, Expr, Stmt};

    pub(crate) fn from_stmt(stmt: &mut Stmt) -> Option<&mut Vec<Attribute>> {
        match stmt {
            syn::Stmt::Local(local) => Some(&mut local.attrs),
            syn::Stmt::Item(_) => None,
            syn::Stmt::Expr(expr) => from_expr(expr),
            syn::Stmt::Semi(expr, ..) => from_expr(expr),
        }
    }

    fn from_expr(expr: &mut Expr) -> Option<&mut Vec<Attribute>> {
        match expr {
            Expr::Array(e) => Some(&mut e.attrs),
            Expr::Assign(e) => Some(&mut e.attrs),
            Expr::AssignOp(e) => Some(&mut e.attrs),
            Expr::Async(e) => Some(&mut e.attrs),
            Expr::Await(e) => Some(&mut e.attrs),
            Expr::Binary(e) => Some(&mut e.attrs),
            Expr::Block(e) => Some(&mut e.attrs),
            Expr::Box(e) => Some(&mut e.attrs),
            Expr::Break(e) => Some(&mut e.attrs),
            Expr::Call(e) => Some(&mut e.attrs),
            Expr::Cast(e) => Some(&mut e.attrs),
            Expr::Closure(e) => Some(&mut e.attrs),
            Expr::Continue(e) => Some(&mut e.attrs),
            Expr::Field(e) => Some(&mut e.attrs),
            Expr::ForLoop(e) => Some(&mut e.attrs),
            Expr::Group(e) => Some(&mut e.attrs),
            Expr::If(e) => Some(&mut e.attrs),
            Expr::Index(e) => Some(&mut e.attrs),
            Expr::Let(e) => Some(&mut e.attrs),
            Expr::Lit(e) => Some(&mut e.attrs),
            Expr::Loop(e) => Some(&mut e.attrs),
            Expr::Macro(e) => Some(&mut e.attrs),
            Expr::Match(e) => Some(&mut e.attrs),
            Expr::MethodCall(e) => Some(&mut e.attrs),
            Expr::Paren(e) => Some(&mut e.attrs),
            Expr::Path(e) => Some(&mut e.attrs),
            Expr::Range(e) => Some(&mut e.attrs),
            Expr::Reference(e) => Some(&mut e.attrs),
            Expr::Repeat(e) => Some(&mut e.attrs),
            Expr::Return(e) => Some(&mut e.attrs),
            Expr::Struct(e) => Some(&mut e.attrs),
            Expr::Try(e) => Some(&mut e.attrs),
            Expr::TryBlock(e) => Some(&mut e.attrs),
            Expr::Tuple(e) => Some(&mut e.attrs),
            Expr::Type(e) => Some(&mut e.attrs),
            Expr::Unary(e) => Some(&mut e.attrs),
            Expr::Unsafe(e) => Some(&mut e.attrs),
            Expr::Verbatim(_) => None,
            Expr::While(e) => Some(&mut e.attrs),
            Expr::Yield(e) => Some(&mut e.attrs),
            _ => None,
            // some variants omitted
        }
    }

    pub(crate) fn find_doc_attr_ind(attrs: &mut Vec<Attribute>) -> Option<usize> {
        attrs.iter().position(|attr| attr.path.is_ident("doc"))
    }
}

mod args {
    use core::ops::Range;
    use syn::LitStr;

    pub(crate) fn split(lit: LitStr) -> Option<(LitStr, Option<proc_macro2::TokenStream>)> {
        let text = lit.value();
        let text = text.trim();
        let span = lit.span();

        let text = if !text.starts_with("SPANDOC: ") {
            return None;
        } else {
            text.trim_start_matches("SPANDOC: ")
        };

        if let Some((text_range, args_range)) = get_ranges(text) {
            let args = &text[args_range];
            let text = &text[text_range].trim();

            let lit = LitStr::new(text, span);
            let args = LitStr::new(args, span);
            let args = args.parse().unwrap();

            Some((lit, Some(args)))
        } else {
            let lit = LitStr::new(text, span);
            Some((lit, None))
        }
    }

    fn get_ranges(text: &str) -> Option<(Range<usize>, Range<usize>)> {
        let mut depth = 0;

        if !text.ends_with('}') {
            return None;
        }

        let chars = text.chars().collect::<Vec<_>>();
        let len = chars.len();

        for (ind, c) in chars.into_iter().enumerate().rev() {
            match c {
                '}' => depth += 1,
                '{' => depth -= 1,
                _ => (),
            }

            if depth == 0 {
                let end = len - 1;
                return Some((0..ind, ind + 1..end));
            }
        }

        None
    }

    #[cfg(test)]
    pub fn split_str(text: &str) -> (&str, Option<&str>) {
        match get_ranges(text) {
            Some((text_range, args_range)) => {
                let args = &text[args_range];
                let text = &text[text_range].trim();

                (text, Some(args))
            }
            _ => (text, None),
        }
    }
}

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

    #[test]
    fn no_args() {
        let input = "This doesn't have args";
        let (text, args) = args::split_str(input);
        assert_eq!(input, text);
        assert_eq!(None, args);
    }

    #[test]
    fn with_args() {
        let input = "This doesn't have args {but, this, does}";
        let (text, args) = args::split_str(input);
        assert_eq!("This doesn't have args", text);
        assert_eq!(Some("but, this, does"), args);
    }
}