swc_macros_common/
lib.rs

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
//! Internal crate for the swc project.

extern crate proc_macro;

use proc_macro2::{Span, TokenStream};
use quote::ToTokens;
use syn::{punctuated::Pair, *};

pub mod binder;
pub mod derive;
pub mod prelude;
mod syn_ext;

pub fn call_site() -> Span {
    Span::call_site()
}

pub fn def_site() -> Span {
    call_site()
}

/// `attr` - tokens inside `#[]`. e.g. `derive(EqIgnoreSpan)`, ast_node
pub fn print(attr: &'static str, tokens: proc_macro2::TokenStream) -> proc_macro::TokenStream {
    use std::env;

    match env::var("PRINT_GENERATED") {
        Ok(ref s) if s == "1" || attr == s => {}
        _ => return tokens.into(),
    }

    println!("\n\tOutput of #[{}]:\n\t {}", attr, tokens);
    tokens.into()
}

pub fn is_attr_name(attr: &Attribute, name: &str) -> bool {
    attr.path().is_ident(name)
}

/// Returns `None` if `attr` is not a doc attribute.
pub fn doc_str(attr: &Attribute) -> Option<String> {
    fn parse_tts(attr: &Attribute) -> String {
        match &attr.meta {
            Meta::NameValue(MetaNameValue {
                value:
                    Expr::Lit(ExprLit {
                        lit: Lit::Str(s), ..
                    }),
                ..
            }) => s.value(),
            _ => panic!("failed to parse {:?}", attr.meta),
        }
    }

    if !is_attr_name(attr, "doc") {
        return None;
    }

    Some(parse_tts(attr))
}

/// Creates a doc comment.
pub fn make_doc_attr(s: &str) -> Attribute {
    let span = Span::call_site();

    Attribute {
        style: AttrStyle::Outer,
        bracket_token: Default::default(),
        pound_token: Token![#](span),
        meta: Meta::NameValue(MetaNameValue {
            path: Path {
                leading_colon: None,
                segments: vec![Pair::End(PathSegment {
                    ident: Ident::new("doc", span),
                    arguments: Default::default(),
                })]
                .into_iter()
                .collect(),
            },
            eq_token: Token![=](span),
            value: Expr::Lit(ExprLit {
                attrs: Default::default(),
                lit: Lit::Str(LitStr::new(s, span)),
            }),
        }),
    }
}

pub fn access_field(obj: &dyn ToTokens, idx: usize, f: &Field) -> Expr {
    Expr::Field(ExprField {
        attrs: Default::default(),
        base: syn::parse2(obj.to_token_stream())
            .expect("swc_macros_common::access_field: failed to parse object"),
        dot_token: Token![.](Span::call_site()),
        member: match &f.ident {
            Some(id) => Member::Named(id.clone()),
            _ => Member::Unnamed(Index {
                index: idx as _,
                span: Span::call_site(),
            }),
        },
    })
}

pub fn join_stmts(stmts: &[Stmt]) -> TokenStream {
    let mut q = TokenStream::new();

    for s in stmts {
        s.to_tokens(&mut q);
    }

    q
}

/// fail! is a panic! with location reporting.
#[macro_export]
macro_rules! fail {
    ($($args:tt)+) => {{
        panic!("{}\n --> {}:{}:{}", format_args!($($args)*), file!(), line!(), column!());
    }};
}

#[macro_export]
macro_rules! unimplemented {
    ($($args:tt)+) => {{
        fail!("not yet implemented: {}", format_args!($($args)*));
    }};
}

#[macro_export]
macro_rules! unreachable {
    () => {{
        fail!("internal error: unreachable");
    }};
    ($($args:tt)+) => {{
        fail!("internal error: unreachable\n{}", format_args!($($args)*));
    }};
}