Skip to main content

rustc_builtin_macros/
eii.rs

1use rustc_ast::token::{Delimiter, TokenKind};
2use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenStream, TokenTree};
3use rustc_ast::{
4    AttrKind, Attribute, DUMMY_NODE_ID, EiiDecl, EiiImpl, ItemKind, MetaItem, Mutability, Path,
5    StmtKind, SyntheticAttr, Visibility, ast,
6};
7use rustc_ast_pretty::pprust::path_to_string;
8use rustc_expand::base::{Annotatable, ExtCtxt};
9use rustc_session::diagnostics::feature_err;
10use rustc_span::{ErrorGuaranteed, Ident, Span, kw, sym};
11use thin_vec::{ThinVec, thin_vec};
12
13use crate::diagnostics::{
14    EiiAttributeNotSupported, EiiBothDeclAndImpl, EiiExternTargetExpectedList,
15    EiiExternTargetExpectedMacro, EiiExternTargetExpectedUnsafe, EiiMacroExpectedMaxOneArgument,
16    EiiMultipleImplementations, EiiOnlyOnce, EiiSharedMacroInStatementPosition,
17    EiiSharedMacroTarget, EiiStaticArgumentRequired, EiiStaticDefaultApple, EiiStaticMutable,
18};
19
20/// ```rust
21/// #[eii]
22/// fn panic_handler();
23///
24/// // or:
25///
26/// #[eii(panic_handler)]
27/// fn panic_handler();
28///
29/// // expansion:
30///
31/// extern "Rust" {
32///     fn panic_handler();
33/// }
34///
35/// #[rustc_builtin_macro(eii_shared_macro)]
36/// #[eii_declaration(panic_handler)]
37/// macro panic_handler() {}
38/// ```
39pub(crate) fn eii(
40    ecx: &mut ExtCtxt<'_>,
41    span: Span,
42    meta_item: &ast::MetaItem,
43    item: Annotatable,
44) -> Vec<Annotatable> {
45    eii_(ecx, span, meta_item, item, false)
46}
47
48pub(crate) fn unsafe_eii(
49    ecx: &mut ExtCtxt<'_>,
50    span: Span,
51    meta_item: &ast::MetaItem,
52    item: Annotatable,
53) -> Vec<Annotatable> {
54    eii_(ecx, span, meta_item, item, true)
55}
56
57fn eii_(
58    ecx: &mut ExtCtxt<'_>,
59    eii_attr_span: Span,
60    meta_item: &ast::MetaItem,
61    orig_item: Annotatable,
62    impl_unsafe: bool,
63) -> Vec<Annotatable> {
64    let eii_attr_span = ecx.with_def_site_ctxt(eii_attr_span);
65
66    let item = if let Annotatable::Item(item) = orig_item {
67        item
68    } else if let Annotatable::Stmt(ref stmt) = orig_item
69        && let StmtKind::Item(ref item) = stmt.kind
70        && let ItemKind::Fn(ref f) = item.kind
71    {
72        ecx.dcx().emit_err(EiiSharedMacroInStatementPosition {
73            span: eii_attr_span.to(item.span),
74            name: path_to_string(&meta_item.path),
75            item_span: f.ident.span,
76        });
77        return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [orig_item]))vec![orig_item];
78    } else {
79        ecx.dcx().emit_err(EiiSharedMacroTarget {
80            span: eii_attr_span,
81            name: path_to_string(&meta_item.path),
82        });
83        return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [orig_item]))vec![orig_item];
84    };
85
86    let ast::Item { attrs, id: _, span: _, vis, kind, tokens: _ } = item.as_ref();
87    let (item_span, foreign_item_name) = match kind {
88        ItemKind::Fn(func) => (func.sig.span, func.ident),
89        ItemKind::Static(stat) => {
90            // See https://github.com/rust-lang/rust/issues/157649
91            if let Some(expr) = &stat.expr
92                && ecx.sess.target.is_like_darwin
93            {
94                ecx.dcx().emit_err(EiiStaticDefaultApple {
95                    span: expr.span,
96                    name: path_to_string(&meta_item.path),
97                });
98                return ::alloc::vec::Vec::new()vec![];
99            }
100
101            // Statics must have an explicit name for the eii
102            if meta_item.is_word() {
103                ecx.dcx().emit_err(EiiStaticArgumentRequired {
104                    span: eii_attr_span,
105                    name: path_to_string(&meta_item.path),
106                });
107                return ::alloc::vec::Vec::new()vec![];
108            }
109
110            // Mut statics are currently not supported
111            if stat.mutability == Mutability::Mut {
112                ecx.dcx().emit_err(EiiStaticMutable {
113                    span: eii_attr_span,
114                    name: path_to_string(&meta_item.path),
115                });
116            }
117
118            (item.span, stat.ident)
119        }
120        _ => {
121            ecx.dcx().emit_err(EiiSharedMacroTarget {
122                span: eii_attr_span,
123                name: path_to_string(&meta_item.path),
124            });
125            return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Annotatable::Item(item)]))vec![Annotatable::Item(item)];
126        }
127    };
128
129    match kind {
130        ItemKind::Fn(func) => {
131            if func.eii_impl.is_some() {
132                ecx.dcx().emit_err(EiiBothDeclAndImpl { span: eii_attr_span });
133                return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Annotatable::Item(item)]))vec![Annotatable::Item(item)];
134            }
135        }
136        ItemKind::Static(stat) => {
137            if stat.eii_impl.is_some() {
138                ecx.dcx().emit_err(EiiBothDeclAndImpl { span: eii_attr_span });
139                return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Annotatable::Item(item)]))vec![Annotatable::Item(item)];
140            }
141        }
142        _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("Target was checked earlier")));
}unreachable!("Target was checked earlier"),
143    };
144
145    // only clone what we need
146    let attrs = attrs.clone();
147    let vis = vis.clone();
148
149    let attrs_from_decl =
150        filter_attrs_for_multiple_eii_attr(ecx, attrs, eii_attr_span, &meta_item.path);
151    let (macro_attrs, foreign_item_attrs) = split_attrs(ecx, item_span, attrs_from_decl);
152
153    let Ok(macro_name) = name_for_impl_macro(ecx, foreign_item_name, meta_item) else {
154        // we don't need to wrap in Annotatable::Stmt conditionally since
155        // EII can't be used on items in statement position
156        return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Annotatable::Item(item)]))vec![Annotatable::Item(item)];
157    };
158
159    let mut module_items = Vec::new();
160
161    if let Some(default_impl) = generate_default_impl(
162        ecx,
163        kind,
164        impl_unsafe,
165        macro_name,
166        eii_attr_span,
167        item_span,
168        foreign_item_name,
169    ) {
170        if !ecx.ecfg.features.extern_item_default_impls() {
171            feature_err(
172                ecx.sess,
173                sym::extern_item_default_impls,
174                eii_attr_span,
175                "eii with default impl is unstable",
176            )
177            .emit();
178        }
179
180        module_items.push(default_impl);
181    }
182
183    module_items.push(generate_foreign_item(
184        ecx,
185        eii_attr_span,
186        item_span,
187        kind,
188        vis,
189        foreign_item_attrs,
190    ));
191    module_items.push(generate_attribute_macro_to_implement(
192        ecx,
193        eii_attr_span,
194        macro_name,
195        foreign_item_name,
196        impl_unsafe,
197        macro_attrs,
198    ));
199
200    // we don't need to wrap in Annotatable::Stmt conditionally since
201    // EII can't be used on items in statement position
202    module_items.into_iter().map(Annotatable::Item).collect()
203}
204
205fn split_attrs(
206    ecx: &mut ExtCtxt<'_>,
207    span: Span,
208    attrs: ThinVec<Attribute>,
209) -> (ThinVec<Attribute>, ThinVec<Attribute>) {
210    let mut macro_attributes = ThinVec::new();
211    let mut foreign_item_attributes = ThinVec::new();
212
213    for attr in attrs {
214        match &attr.kind {
215            // Forward synthetic CfgTrace and CfgAttrTrace, these are applicable to both foreign item and macro.
216            AttrKind::Synthetic(SyntheticAttr::CfgTrace(_) | SyntheticAttr::CfgAttrTrace(_)) => {
217                foreign_item_attributes.push(attr.clone());
218                macro_attributes.push(attr);
219            }
220            // Drop the test entrypoint marker -- unclear how that would interact.
221            AttrKind::Synthetic(SyntheticAttr::TestEntrypoint) => {}
222            // Doc attributes should be forwarded to the macro and the foreign item, since those are
223            // the two items you interact with as a user.
224            // FIXME: idk yet how EIIs show up in docs, might want to customize
225            AttrKind::DocComment(_, _) => {
226                foreign_item_attributes.push(attr.clone());
227                macro_attributes.push(attr);
228            }
229            AttrKind::Normal(normal) => {
230                match normal.item.name() {
231                    // If an eii is marked a lang item, that's because we want to call its declaration, so
232                    // mark the foreign item as the lang item
233                    Some(sym::lang) => foreign_item_attributes.push(attr),
234                    // Deprecating an eii means deprecating the macro and the foreign item
235                    Some(sym::deprecated) => {
236                        foreign_item_attributes.push(attr.clone());
237                        macro_attributes.push(attr);
238                    }
239                    // The stability of an EII affects the usage of the macro and calling the foreign item
240                    Some(sym::stable) | Some(sym::unstable) => {
241                        foreign_item_attributes.push(attr.clone());
242                        macro_attributes.push(attr);
243                    }
244                    // `#[track_caller]` goes on the foreign item only: it's the symbol callers link
245                    // against, so it must carry the flag for call sites to pass the caller location.
246                    // Implementations derive it during codegen (see `EiiImpls` in `codegen_attrs.rs`),
247                    // so it must not be routed onto the default impl here.
248                    Some(sym::track_caller) => {
249                        foreign_item_attributes.push(attr);
250                    }
251                    Some(sym::eii) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("should already be filtered out")));
}unreachable!("should already be filtered out"),
252                    _ => {
253                        ecx.dcx().emit_err(EiiAttributeNotSupported { span, attr_span: attr.span });
254                    }
255                }
256            }
257            AttrKind::Generated(..) => ::core::panicking::unreachable_default_msg()unreachable!(),
258        }
259    }
260
261    (macro_attributes, foreign_item_attributes)
262}
263
264/// Decide on the name of the macro that can be used to implement the EII.
265/// This is either an explicitly given name, or the name of the item in the
266/// declaration of the EII.
267fn name_for_impl_macro(
268    ecx: &mut ExtCtxt<'_>,
269    item_ident: Ident,
270    meta_item: &MetaItem,
271) -> Result<Ident, ErrorGuaranteed> {
272    if meta_item.is_word() {
273        Ok(item_ident)
274    } else if let Some([first]) = meta_item.meta_item_list()
275        && let Some(m) = first.meta_item()
276        && m.path.segments.len() == 1
277    {
278        Ok(m.path.segments[0].ident)
279    } else {
280        Err(ecx.dcx().emit_err(EiiMacroExpectedMaxOneArgument {
281            span: meta_item.span,
282            name: path_to_string(&meta_item.path),
283        }))
284    }
285}
286
287/// Ensure that in the list of attrs, there's only a single `eii` attribute.
288fn filter_attrs_for_multiple_eii_attr(
289    ecx: &mut ExtCtxt<'_>,
290    attrs: ThinVec<Attribute>,
291    eii_attr_span: Span,
292    eii_attr_path: &Path,
293) -> ThinVec<Attribute> {
294    attrs
295        .into_iter()
296        .filter(|i| {
297            if i.has_name(sym::eii) {
298                ecx.dcx().emit_err(EiiOnlyOnce {
299                    span: i.span,
300                    first_span: eii_attr_span,
301                    name: path_to_string(eii_attr_path),
302                });
303                false
304            } else {
305                true
306            }
307        })
308        .collect()
309}
310
311fn generate_default_impl(
312    ecx: &mut ExtCtxt<'_>,
313    item_kind: &ItemKind,
314    impl_unsafe: bool,
315    macro_name: Ident,
316    eii_attr_span: Span,
317    item_span: Span,
318    foreign_item_name: Ident,
319) -> Option<Box<ast::Item>> {
320    let attrs = ThinVec::new();
321
322    match item_kind {
323        ItemKind::Fn(func) => {
324            func.body.as_ref()?;
325        }
326        ItemKind::Static(stat) => {
327            stat.expr.as_ref()?;
328        }
329        _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("Target was checked earlier")));
}unreachable!("Target was checked earlier"),
330    };
331
332    let eii_impl = Box::new(EiiImpl {
333        node_id: DUMMY_NODE_ID,
334        inner_span: macro_name.span,
335        eii_macro_path: ast::Path::from_ident(macro_name),
336        impl_safety: if impl_unsafe {
337            ast::Safety::Unsafe(eii_attr_span)
338        } else {
339            ast::Safety::Default
340        },
341        span: eii_attr_span,
342        is_default: true,
343        known_eii_macro_resolution: Some(ecx.path(
344            foreign_item_name.span,
345            // prefix self to explicitly escape the const block generated below
346            // NOTE: this is why EIIs can't be used on statements
347            &[Ident::new(kw::SelfLower, foreign_item_name.span), foreign_item_name],
348        )),
349    });
350
351    let mut item_kind = item_kind.clone();
352    match &mut item_kind {
353        ItemKind::Fn(func) => {
354            if !func.eii_impl.is_none() {
    ::core::panicking::panic("assertion failed: func.eii_impl.is_none()")
};assert!(func.eii_impl.is_none());
355            func.eii_impl = Some(eii_impl);
356        }
357        ItemKind::Static(stat) => {
358            if !stat.eii_impl.is_none() {
    ::core::panicking::panic("assertion failed: stat.eii_impl.is_none()")
};assert!(stat.eii_impl.is_none());
359            stat.eii_impl = Some(eii_impl);
360        }
361        _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("Target was checked earlier")));
}unreachable!("Target was checked earlier"),
362    };
363
364    let anon_mod = |span: Span, stmts: ThinVec<ast::Stmt>| {
365        ecx.item_const_underscore(span, ecx.block(span, stmts))
366    };
367
368    // const _: () = {
369    //     <orig item>
370    // }
371    Some(anon_mod(
372        item_span,
373        {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(ecx.stmt_item(item_span, ecx.item(item_span, attrs, item_kind)));
    vec
}thin_vec![ecx.stmt_item(item_span, ecx.item(item_span, attrs, item_kind))],
374    ))
375}
376
377/// Generates a foreign item, like
378///
379/// ```rust, ignore
380/// extern "…" { safe fn item(); }
381/// ```
382fn generate_foreign_item(
383    ecx: &mut ExtCtxt<'_>,
384    eii_attr_span: Span,
385    item_span: Span,
386    item_kind: &ItemKind,
387    vis: Visibility,
388    attrs_from_decl: ThinVec<Attribute>,
389) -> Box<ast::Item> {
390    let mut foreign_item_attrs = attrs_from_decl;
391
392    // Add the rustc_eii_foreign_item on the foreign item. Usually, foreign items are mangled.
393    // This attribute makes sure that we later know that this foreign item's symbol should not be.
394    foreign_item_attrs.push(ecx.attr_word(sym::rustc_eii_foreign_item, eii_attr_span));
395
396    // We set the abi to the default "rust" abi, which can be overridden by `generate_foreign_func`,
397    // if a specific abi was specified on the EII function
398    let mut abi = Some(ast::StrLit {
399        symbol: sym::Rust,
400        suffix: None,
401        symbol_unescaped: sym::Rust,
402        style: ast::StrStyle::Cooked,
403        span: eii_attr_span,
404    });
405    let foreign_kind = match item_kind {
406        ItemKind::Fn(func) => generate_foreign_func(func.clone(), &mut abi),
407        ItemKind::Static(stat) => generate_foreign_static(stat.clone()),
408        _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("Target was checked earlier")));
}unreachable!("Target was checked earlier"),
409    };
410
411    ecx.item(
412        eii_attr_span,
413        ThinVec::new(),
414        ast::ItemKind::ForeignMod(ast::ForeignMod {
415            extern_span: eii_attr_span,
416            safety: ast::Safety::Unsafe(eii_attr_span),
417            abi,
418            items: From::from([Box::new(ast::ForeignItem {
419                attrs: foreign_item_attrs,
420                id: ast::DUMMY_NODE_ID,
421                span: item_span,
422                vis,
423                kind: foreign_kind,
424                tokens: None,
425            })]),
426        }),
427    )
428}
429
430fn generate_foreign_func(
431    mut func: Box<ast::Fn>,
432    abi: &mut Option<ast::StrLit>,
433) -> ast::ForeignItemKind {
434    match func.sig.header.ext {
435        // extern "X" fn  =>  extern "X" {}
436        ast::Extern::Explicit(lit, _) => *abi = Some(lit),
437        // extern fn  =>  extern {}
438        ast::Extern::Implicit(_) => *abi = None,
439        // no abi was specified, so we keep the default
440        ast::Extern::None => {}
441    };
442
443    // ABI has been moved to the extern {} block, so we remove it from the fn item.
444    func.sig.header.ext = ast::Extern::None;
445    func.body = None;
446
447    // And mark safe functions explicitly as `safe fn`.
448    if func.sig.header.safety == ast::Safety::Default {
449        func.sig.header.safety = ast::Safety::Safe(func.sig.span);
450    }
451
452    ast::ForeignItemKind::Fn(func)
453}
454
455fn generate_foreign_static(mut stat: Box<ast::StaticItem>) -> ast::ForeignItemKind {
456    if stat.safety == ast::Safety::Default {
457        stat.safety = ast::Safety::Safe(stat.ident.span);
458    }
459
460    stat.expr = None;
461
462    ast::ForeignItemKind::Static(stat)
463}
464
465/// Generate a stub macro (a bit like in core) that will roughly look like:
466///
467/// ```rust, ignore, example
468/// // Since this a stub macro, the actual code that expands it lives in the compiler.
469/// // This attribute tells the compiler that
470/// #[builtin_macro(eii_shared_macro)]
471/// // the metadata to link this macro to the generated foreign item.
472/// #[eii_declaration(<related_foreign_item>)]
473/// macro macro_name { () => {} }
474/// ```
475fn generate_attribute_macro_to_implement(
476    ecx: &mut ExtCtxt<'_>,
477    span: Span,
478    macro_name: Ident,
479    foreign_item_name: Ident,
480    impl_unsafe: bool,
481    attrs_from_decl: ThinVec<Attribute>,
482) -> Box<ast::Item> {
483    let mut macro_attrs = attrs_from_decl;
484
485    // Avoid "missing stability attribute" errors for eiis in std. See #146993.
486    macro_attrs.push(ecx.attr_name_value_str(sym::rustc_macro_transparency, sym::semiopaque, span));
487
488    // #[builtin_macro(eii_shared_macro)]
489    macro_attrs.push(ecx.attr_nested_word(sym::rustc_builtin_macro, sym::eii_shared_macro, span));
490
491    // cant use ecx methods here to construct item since we need it to be public
492    Box::new(ast::Item {
493        attrs: macro_attrs,
494        id: ast::DUMMY_NODE_ID,
495        span,
496        // pub
497        vis: ast::Visibility { span, kind: ast::VisibilityKind::Public },
498        kind: ast::ItemKind::MacroDef(
499            // macro macro_name
500            macro_name,
501            ast::MacroDef {
502                // { () => {} }
503                body: Box::new(ast::DelimArgs {
504                    dspan: DelimSpan::from_single(span),
505                    delim: Delimiter::Brace,
506                    tokens: TokenStream::from_iter([
507                        TokenTree::Delimited(
508                            DelimSpan::from_single(span),
509                            DelimSpacing::new(Spacing::Alone, Spacing::Alone),
510                            Delimiter::Parenthesis,
511                            TokenStream::default(),
512                        ),
513                        TokenTree::token_alone(TokenKind::FatArrow, span),
514                        TokenTree::Delimited(
515                            DelimSpan::from_single(span),
516                            DelimSpacing::new(Spacing::Alone, Spacing::Alone),
517                            Delimiter::Brace,
518                            TokenStream::default(),
519                        ),
520                    ]),
521                }),
522                macro_rules: false,
523                // #[eii_declaration(foreign_item_ident)]
524                eii_declaration: Some(ast::EiiDecl {
525                    foreign_item: ast::Path::from_ident(foreign_item_name),
526                    impl_unsafe,
527                }),
528            },
529        ),
530        tokens: None,
531    })
532}
533
534pub(crate) fn eii_declaration(
535    ecx: &mut ExtCtxt<'_>,
536    span: Span,
537    meta_item: &ast::MetaItem,
538    mut item: Annotatable,
539) -> Vec<Annotatable> {
540    let i = if let Annotatable::Item(ref mut item) = item {
541        item
542    } else if let Annotatable::Stmt(ref mut stmt) = item
543        && let StmtKind::Item(ref mut item) = stmt.kind
544    {
545        item
546    } else {
547        ecx.dcx().emit_err(EiiExternTargetExpectedMacro { span });
548        return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [item]))vec![item];
549    };
550
551    let ItemKind::MacroDef(_, d) = &mut i.kind else {
552        ecx.dcx().emit_err(EiiExternTargetExpectedMacro { span });
553        return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [item]))vec![item];
554    };
555
556    let Some(list) = meta_item.meta_item_list() else {
557        ecx.dcx().emit_err(EiiExternTargetExpectedList { span: meta_item.span });
558        return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [item]))vec![item];
559    };
560
561    if list.len() > 2 {
562        ecx.dcx().emit_err(EiiExternTargetExpectedList { span: meta_item.span });
563        return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [item]))vec![item];
564    }
565
566    let Some(extern_item_path) = list.get(0).and_then(|i| i.meta_item()).map(|i| i.path.clone())
567    else {
568        ecx.dcx().emit_err(EiiExternTargetExpectedList { span: meta_item.span });
569        return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [item]))vec![item];
570    };
571
572    let impl_unsafe = if let Some(i) = list.get(1) {
573        if i.lit().and_then(|i| i.kind.str()).is_some_and(|i| i == kw::Unsafe) {
574            true
575        } else {
576            ecx.dcx().emit_err(EiiExternTargetExpectedUnsafe { span: i.span() });
577            return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [item]))vec![item];
578        }
579    } else {
580        false
581    };
582
583    d.eii_declaration = Some(EiiDecl { foreign_item: extern_item_path, impl_unsafe });
584
585    // Return the original item and the new methods.
586    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [item]))vec![item]
587}
588
589/// all Eiis share this function as the implementation for their attribute.
590pub(crate) fn eii_shared_macro(
591    ecx: &mut ExtCtxt<'_>,
592    span: Span,
593    meta_item: &ast::MetaItem,
594    mut item: Annotatable,
595) -> Vec<Annotatable> {
596    let i = if let Annotatable::Item(ref mut item) = item {
597        item
598    } else if let Annotatable::Stmt(ref mut stmt) = item
599        && let StmtKind::Item(ref mut item) = stmt.kind
600    {
601        item
602    } else {
603        ecx.dcx().emit_err(EiiSharedMacroTarget { span, name: path_to_string(&meta_item.path) });
604        return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [item]))vec![item];
605    };
606
607    let eii_impl = match &mut i.kind {
608        ItemKind::Fn(func) => &mut func.eii_impl,
609        ItemKind::Static(stat) => &mut stat.eii_impl,
610        _ => {
611            ecx.dcx()
612                .emit_err(EiiSharedMacroTarget { span, name: path_to_string(&meta_item.path) });
613            return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [item]))vec![item];
614        }
615    };
616
617    let is_default = if meta_item.is_word() {
618        false
619    } else if let Some([first]) = meta_item.meta_item_list()
620        && let Some(m) = first.meta_item()
621        && m.path.segments.len() == 1
622    {
623        m.path.segments[0].ident.name == kw::Default
624    } else {
625        ecx.dcx().emit_err(EiiMacroExpectedMaxOneArgument {
626            span: meta_item.span,
627            name: path_to_string(&meta_item.path),
628        });
629        return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [item]))vec![item];
630    };
631
632    if eii_impl.is_some() {
633        ecx.dcx().emit_err(EiiMultipleImplementations { span });
634    }
635    *eii_impl = Some(Box::new(EiiImpl {
636        node_id: DUMMY_NODE_ID,
637        inner_span: meta_item.path.span,
638        eii_macro_path: meta_item.path.clone(),
639        impl_safety: meta_item.unsafety,
640        span,
641        is_default,
642        known_eii_macro_resolution: None,
643    }));
644
645    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [item]))vec![item]
646}