]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_builtin_macros/src/asm.rs
Auto merge of #93530 - anonion0:pthread_sigmask_fix, r=JohnTitor
[rust.git] / compiler / rustc_builtin_macros / src / asm.rs
1 use rustc_ast as ast;
2 use rustc_ast::ptr::P;
3 use rustc_ast::token;
4 use rustc_ast::tokenstream::TokenStream;
5 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
6 use rustc_errors::{Applicability, PResult};
7 use rustc_expand::base::{self, *};
8 use rustc_parse::parser::Parser;
9 use rustc_parse_format as parse;
10 use rustc_session::lint;
11 use rustc_session::parse::ParseSess;
12 use rustc_span::symbol::Ident;
13 use rustc_span::symbol::{kw, sym, Symbol};
14 use rustc_span::{InnerSpan, Span};
15 use rustc_target::asm::InlineAsmArch;
16 use smallvec::smallvec;
17
18 pub struct AsmArgs {
19     pub templates: Vec<P<ast::Expr>>,
20     pub operands: Vec<(ast::InlineAsmOperand, Span)>,
21     named_args: FxHashMap<Symbol, usize>,
22     reg_args: FxHashSet<usize>,
23     pub clobber_abis: Vec<(Symbol, Span)>,
24     options: ast::InlineAsmOptions,
25     pub options_spans: Vec<Span>,
26 }
27
28 fn parse_args<'a>(
29     ecx: &mut ExtCtxt<'a>,
30     sp: Span,
31     tts: TokenStream,
32     is_global_asm: bool,
33 ) -> PResult<'a, AsmArgs> {
34     let mut p = ecx.new_parser_from_tts(tts);
35     let sess = &ecx.sess.parse_sess;
36     parse_asm_args(&mut p, sess, sp, is_global_asm)
37 }
38
39 // Primarily public for rustfmt consumption.
40 // Internal consumers should continue to leverage `expand_asm`/`expand__global_asm`
41 pub fn parse_asm_args<'a>(
42     p: &mut Parser<'a>,
43     sess: &'a ParseSess,
44     sp: Span,
45     is_global_asm: bool,
46 ) -> PResult<'a, AsmArgs> {
47     let diag = &sess.span_diagnostic;
48
49     if p.token == token::Eof {
50         return Err(diag.struct_span_err(sp, "requires at least a template string argument"));
51     }
52
53     let first_template = p.parse_expr()?;
54     let mut args = AsmArgs {
55         templates: vec![first_template],
56         operands: vec![],
57         named_args: FxHashMap::default(),
58         reg_args: FxHashSet::default(),
59         clobber_abis: Vec::new(),
60         options: ast::InlineAsmOptions::empty(),
61         options_spans: vec![],
62     };
63
64     let mut allow_templates = true;
65     while p.token != token::Eof {
66         if !p.eat(&token::Comma) {
67             if allow_templates {
68                 // After a template string, we always expect *only* a comma...
69                 let mut err = diag.struct_span_err(p.token.span, "expected token: `,`");
70                 err.span_label(p.token.span, "expected `,`");
71                 p.maybe_annotate_with_ascription(&mut err, false);
72                 return Err(err);
73             } else {
74                 // ...after that delegate to `expect` to also include the other expected tokens.
75                 return Err(p.expect(&token::Comma).err().unwrap());
76             }
77         }
78         if p.token == token::Eof {
79             break;
80         } // accept trailing commas
81
82         // Parse clobber_abi
83         if p.eat_keyword(sym::clobber_abi) {
84             parse_clobber_abi(p, &mut args)?;
85             allow_templates = false;
86             continue;
87         }
88
89         // Parse options
90         if p.eat_keyword(sym::options) {
91             parse_options(p, &mut args, is_global_asm)?;
92             allow_templates = false;
93             continue;
94         }
95
96         let span_start = p.token.span;
97
98         // Parse operand names
99         let name = if p.token.is_ident() && p.look_ahead(1, |t| *t == token::Eq) {
100             let (ident, _) = p.token.ident().unwrap();
101             p.bump();
102             p.expect(&token::Eq)?;
103             allow_templates = false;
104             Some(ident.name)
105         } else {
106             None
107         };
108
109         let mut explicit_reg = false;
110         let op = if !is_global_asm && p.eat_keyword(kw::In) {
111             let reg = parse_reg(p, &mut explicit_reg)?;
112             if p.eat_keyword(kw::Underscore) {
113                 let err = diag.struct_span_err(p.token.span, "_ cannot be used for input operands");
114                 return Err(err);
115             }
116             let expr = p.parse_expr()?;
117             ast::InlineAsmOperand::In { reg, expr }
118         } else if !is_global_asm && p.eat_keyword(sym::out) {
119             let reg = parse_reg(p, &mut explicit_reg)?;
120             let expr = if p.eat_keyword(kw::Underscore) { None } else { Some(p.parse_expr()?) };
121             ast::InlineAsmOperand::Out { reg, expr, late: false }
122         } else if !is_global_asm && p.eat_keyword(sym::lateout) {
123             let reg = parse_reg(p, &mut explicit_reg)?;
124             let expr = if p.eat_keyword(kw::Underscore) { None } else { Some(p.parse_expr()?) };
125             ast::InlineAsmOperand::Out { reg, expr, late: true }
126         } else if !is_global_asm && p.eat_keyword(sym::inout) {
127             let reg = parse_reg(p, &mut explicit_reg)?;
128             if p.eat_keyword(kw::Underscore) {
129                 let err = diag.struct_span_err(p.token.span, "_ cannot be used for input operands");
130                 return Err(err);
131             }
132             let expr = p.parse_expr()?;
133             if p.eat(&token::FatArrow) {
134                 let out_expr =
135                     if p.eat_keyword(kw::Underscore) { None } else { Some(p.parse_expr()?) };
136                 ast::InlineAsmOperand::SplitInOut { reg, in_expr: expr, out_expr, late: false }
137             } else {
138                 ast::InlineAsmOperand::InOut { reg, expr, late: false }
139             }
140         } else if !is_global_asm && p.eat_keyword(sym::inlateout) {
141             let reg = parse_reg(p, &mut explicit_reg)?;
142             if p.eat_keyword(kw::Underscore) {
143                 let err = diag.struct_span_err(p.token.span, "_ cannot be used for input operands");
144                 return Err(err);
145             }
146             let expr = p.parse_expr()?;
147             if p.eat(&token::FatArrow) {
148                 let out_expr =
149                     if p.eat_keyword(kw::Underscore) { None } else { Some(p.parse_expr()?) };
150                 ast::InlineAsmOperand::SplitInOut { reg, in_expr: expr, out_expr, late: true }
151             } else {
152                 ast::InlineAsmOperand::InOut { reg, expr, late: true }
153             }
154         } else if p.eat_keyword(kw::Const) {
155             let anon_const = p.parse_anon_const_expr()?;
156             ast::InlineAsmOperand::Const { anon_const }
157         } else if p.eat_keyword(sym::sym) {
158             let expr = p.parse_expr()?;
159             let ast::ExprKind::Path(qself, path) = &expr.kind else {
160                 let err = diag
161                     .struct_span_err(expr.span, "expected a path for argument to `sym`");
162                 return Err(err);
163             };
164             let sym = ast::InlineAsmSym {
165                 id: ast::DUMMY_NODE_ID,
166                 qself: qself.clone(),
167                 path: path.clone(),
168             };
169             ast::InlineAsmOperand::Sym { sym }
170         } else if allow_templates {
171             let template = p.parse_expr()?;
172             // If it can't possibly expand to a string, provide diagnostics here to include other
173             // things it could have been.
174             match template.kind {
175                 ast::ExprKind::Lit(ast::Lit { kind: ast::LitKind::Str(..), .. }) => {}
176                 ast::ExprKind::MacCall(..) => {}
177                 _ => {
178                     let errstr = if is_global_asm {
179                         "expected operand, options, or additional template string"
180                     } else {
181                         "expected operand, clobber_abi, options, or additional template string"
182                     };
183                     let mut err = diag.struct_span_err(template.span, errstr);
184                     err.span_label(template.span, errstr);
185                     return Err(err);
186                 }
187             }
188             args.templates.push(template);
189             continue;
190         } else {
191             return p.unexpected();
192         };
193
194         allow_templates = false;
195         let span = span_start.to(p.prev_token.span);
196         let slot = args.operands.len();
197         args.operands.push((op, span));
198
199         // Validate the order of named, positional & explicit register operands and
200         // clobber_abi/options. We do this at the end once we have the full span
201         // of the argument available.
202         if !args.options_spans.is_empty() {
203             diag.struct_span_err(span, "arguments are not allowed after options")
204                 .span_labels(args.options_spans.clone(), "previous options")
205                 .span_label(span, "argument")
206                 .emit();
207         } else if let Some((_, abi_span)) = args.clobber_abis.last() {
208             diag.struct_span_err(span, "arguments are not allowed after clobber_abi")
209                 .span_label(*abi_span, "clobber_abi")
210                 .span_label(span, "argument")
211                 .emit();
212         }
213         if explicit_reg {
214             if name.is_some() {
215                 diag.struct_span_err(span, "explicit register arguments cannot have names").emit();
216             }
217             args.reg_args.insert(slot);
218         } else if let Some(name) = name {
219             if let Some(&prev) = args.named_args.get(&name) {
220                 diag.struct_span_err(span, &format!("duplicate argument named `{}`", name))
221                     .span_label(args.operands[prev].1, "previously here")
222                     .span_label(span, "duplicate argument")
223                     .emit();
224                 continue;
225             }
226             if !args.reg_args.is_empty() {
227                 let mut err = diag.struct_span_err(
228                     span,
229                     "named arguments cannot follow explicit register arguments",
230                 );
231                 err.span_label(span, "named argument");
232                 for pos in &args.reg_args {
233                     err.span_label(args.operands[*pos].1, "explicit register argument");
234                 }
235                 err.emit();
236             }
237             args.named_args.insert(name, slot);
238         } else {
239             if !args.named_args.is_empty() || !args.reg_args.is_empty() {
240                 let mut err = diag.struct_span_err(
241                     span,
242                     "positional arguments cannot follow named arguments \
243                      or explicit register arguments",
244                 );
245                 err.span_label(span, "positional argument");
246                 for pos in args.named_args.values() {
247                     err.span_label(args.operands[*pos].1, "named argument");
248                 }
249                 for pos in &args.reg_args {
250                     err.span_label(args.operands[*pos].1, "explicit register argument");
251                 }
252                 err.emit();
253             }
254         }
255     }
256
257     if args.options.contains(ast::InlineAsmOptions::NOMEM)
258         && args.options.contains(ast::InlineAsmOptions::READONLY)
259     {
260         let spans = args.options_spans.clone();
261         diag.struct_span_err(spans, "the `nomem` and `readonly` options are mutually exclusive")
262             .emit();
263     }
264     if args.options.contains(ast::InlineAsmOptions::PURE)
265         && args.options.contains(ast::InlineAsmOptions::NORETURN)
266     {
267         let spans = args.options_spans.clone();
268         diag.struct_span_err(spans, "the `pure` and `noreturn` options are mutually exclusive")
269             .emit();
270     }
271     if args.options.contains(ast::InlineAsmOptions::PURE)
272         && !args.options.intersects(ast::InlineAsmOptions::NOMEM | ast::InlineAsmOptions::READONLY)
273     {
274         let spans = args.options_spans.clone();
275         diag.struct_span_err(
276             spans,
277             "the `pure` option must be combined with either `nomem` or `readonly`",
278         )
279         .emit();
280     }
281
282     let mut have_real_output = false;
283     let mut outputs_sp = vec![];
284     let mut regclass_outputs = vec![];
285     for (op, op_sp) in &args.operands {
286         match op {
287             ast::InlineAsmOperand::Out { reg, expr, .. }
288             | ast::InlineAsmOperand::SplitInOut { reg, out_expr: expr, .. } => {
289                 outputs_sp.push(*op_sp);
290                 have_real_output |= expr.is_some();
291                 if let ast::InlineAsmRegOrRegClass::RegClass(_) = reg {
292                     regclass_outputs.push(*op_sp);
293                 }
294             }
295             ast::InlineAsmOperand::InOut { reg, .. } => {
296                 outputs_sp.push(*op_sp);
297                 have_real_output = true;
298                 if let ast::InlineAsmRegOrRegClass::RegClass(_) = reg {
299                     regclass_outputs.push(*op_sp);
300                 }
301             }
302             _ => {}
303         }
304     }
305     if args.options.contains(ast::InlineAsmOptions::PURE) && !have_real_output {
306         diag.struct_span_err(
307             args.options_spans.clone(),
308             "asm with the `pure` option must have at least one output",
309         )
310         .emit();
311     }
312     if args.options.contains(ast::InlineAsmOptions::NORETURN) && !outputs_sp.is_empty() {
313         let err = diag
314             .struct_span_err(outputs_sp, "asm outputs are not allowed with the `noreturn` option");
315
316         // Bail out now since this is likely to confuse MIR
317         return Err(err);
318     }
319
320     if args.clobber_abis.len() > 0 {
321         if is_global_asm {
322             let err = diag.struct_span_err(
323                 args.clobber_abis.iter().map(|(_, span)| *span).collect::<Vec<Span>>(),
324                 "`clobber_abi` cannot be used with `global_asm!`",
325             );
326
327             // Bail out now since this is likely to confuse later stages
328             return Err(err);
329         }
330         if !regclass_outputs.is_empty() {
331             diag.struct_span_err(
332                 regclass_outputs.clone(),
333                 "asm with `clobber_abi` must specify explicit registers for outputs",
334             )
335             .span_labels(
336                 args.clobber_abis.iter().map(|(_, span)| *span).collect::<Vec<Span>>(),
337                 "clobber_abi",
338             )
339             .span_labels(regclass_outputs, "generic outputs")
340             .emit();
341         }
342     }
343
344     Ok(args)
345 }
346
347 /// Report a duplicate option error.
348 ///
349 /// This function must be called immediately after the option token is parsed.
350 /// Otherwise, the suggestion will be incorrect.
351 fn err_duplicate_option<'a>(p: &mut Parser<'a>, symbol: Symbol, span: Span) {
352     let mut err = p
353         .sess
354         .span_diagnostic
355         .struct_span_err(span, &format!("the `{}` option was already provided", symbol));
356     err.span_label(span, "this option was already provided");
357
358     // Tool-only output
359     let mut full_span = span;
360     if p.token.kind == token::Comma {
361         full_span = full_span.to(p.token.span);
362     }
363     err.tool_only_span_suggestion(
364         full_span,
365         "remove this option",
366         String::new(),
367         Applicability::MachineApplicable,
368     );
369
370     err.emit();
371 }
372
373 /// Try to set the provided option in the provided `AsmArgs`.
374 /// If it is already set, report a duplicate option error.
375 ///
376 /// This function must be called immediately after the option token is parsed.
377 /// Otherwise, the error will not point to the correct spot.
378 fn try_set_option<'a>(
379     p: &mut Parser<'a>,
380     args: &mut AsmArgs,
381     symbol: Symbol,
382     option: ast::InlineAsmOptions,
383 ) {
384     if !args.options.contains(option) {
385         args.options |= option;
386     } else {
387         err_duplicate_option(p, symbol, p.prev_token.span);
388     }
389 }
390
391 fn parse_options<'a>(
392     p: &mut Parser<'a>,
393     args: &mut AsmArgs,
394     is_global_asm: bool,
395 ) -> PResult<'a, ()> {
396     let span_start = p.prev_token.span;
397
398     p.expect(&token::OpenDelim(token::DelimToken::Paren))?;
399
400     while !p.eat(&token::CloseDelim(token::DelimToken::Paren)) {
401         if !is_global_asm && p.eat_keyword(sym::pure) {
402             try_set_option(p, args, sym::pure, ast::InlineAsmOptions::PURE);
403         } else if !is_global_asm && p.eat_keyword(sym::nomem) {
404             try_set_option(p, args, sym::nomem, ast::InlineAsmOptions::NOMEM);
405         } else if !is_global_asm && p.eat_keyword(sym::readonly) {
406             try_set_option(p, args, sym::readonly, ast::InlineAsmOptions::READONLY);
407         } else if !is_global_asm && p.eat_keyword(sym::preserves_flags) {
408             try_set_option(p, args, sym::preserves_flags, ast::InlineAsmOptions::PRESERVES_FLAGS);
409         } else if !is_global_asm && p.eat_keyword(sym::noreturn) {
410             try_set_option(p, args, sym::noreturn, ast::InlineAsmOptions::NORETURN);
411         } else if !is_global_asm && p.eat_keyword(sym::nostack) {
412             try_set_option(p, args, sym::nostack, ast::InlineAsmOptions::NOSTACK);
413         } else if p.eat_keyword(sym::att_syntax) {
414             try_set_option(p, args, sym::att_syntax, ast::InlineAsmOptions::ATT_SYNTAX);
415         } else if p.eat_keyword(kw::Raw) {
416             try_set_option(p, args, kw::Raw, ast::InlineAsmOptions::RAW);
417         } else if p.eat_keyword(sym::may_unwind) {
418             try_set_option(p, args, kw::Raw, ast::InlineAsmOptions::MAY_UNWIND);
419         } else {
420             return p.unexpected();
421         }
422
423         // Allow trailing commas
424         if p.eat(&token::CloseDelim(token::DelimToken::Paren)) {
425             break;
426         }
427         p.expect(&token::Comma)?;
428     }
429
430     let new_span = span_start.to(p.prev_token.span);
431     args.options_spans.push(new_span);
432
433     Ok(())
434 }
435
436 fn parse_clobber_abi<'a>(p: &mut Parser<'a>, args: &mut AsmArgs) -> PResult<'a, ()> {
437     let span_start = p.prev_token.span;
438
439     p.expect(&token::OpenDelim(token::DelimToken::Paren))?;
440
441     if p.eat(&token::CloseDelim(token::DelimToken::Paren)) {
442         let err = p.sess.span_diagnostic.struct_span_err(
443             p.token.span,
444             "at least one abi must be provided as an argument to `clobber_abi`",
445         );
446         return Err(err);
447     }
448
449     let mut new_abis = Vec::new();
450     loop {
451         match p.parse_str_lit() {
452             Ok(str_lit) => {
453                 new_abis.push((str_lit.symbol_unescaped, str_lit.span));
454             }
455             Err(opt_lit) => {
456                 // If the non-string literal is a closing paren then it's the end of the list and is fine
457                 if p.eat(&token::CloseDelim(token::DelimToken::Paren)) {
458                     break;
459                 }
460                 let span = opt_lit.map_or(p.token.span, |lit| lit.span);
461                 let mut err =
462                     p.sess.span_diagnostic.struct_span_err(span, "expected string literal");
463                 err.span_label(span, "not a string literal");
464                 return Err(err);
465             }
466         };
467
468         // Allow trailing commas
469         if p.eat(&token::CloseDelim(token::DelimToken::Paren)) {
470             break;
471         }
472         p.expect(&token::Comma)?;
473     }
474
475     let full_span = span_start.to(p.prev_token.span);
476
477     if !args.options_spans.is_empty() {
478         let mut err = p
479             .sess
480             .span_diagnostic
481             .struct_span_err(full_span, "clobber_abi is not allowed after options");
482         err.span_labels(args.options_spans.clone(), "options");
483         return Err(err);
484     }
485
486     match &new_abis[..] {
487         // should have errored above during parsing
488         [] => unreachable!(),
489         [(abi, _span)] => args.clobber_abis.push((*abi, full_span)),
490         [abis @ ..] => {
491             for (abi, span) in abis {
492                 args.clobber_abis.push((*abi, *span));
493             }
494         }
495     }
496
497     Ok(())
498 }
499
500 fn parse_reg<'a>(
501     p: &mut Parser<'a>,
502     explicit_reg: &mut bool,
503 ) -> PResult<'a, ast::InlineAsmRegOrRegClass> {
504     p.expect(&token::OpenDelim(token::DelimToken::Paren))?;
505     let result = match p.token.uninterpolate().kind {
506         token::Ident(name, false) => ast::InlineAsmRegOrRegClass::RegClass(name),
507         token::Literal(token::Lit { kind: token::LitKind::Str, symbol, suffix: _ }) => {
508             *explicit_reg = true;
509             ast::InlineAsmRegOrRegClass::Reg(symbol)
510         }
511         _ => {
512             return Err(
513                 p.struct_span_err(p.token.span, "expected register class or explicit register")
514             );
515         }
516     };
517     p.bump();
518     p.expect(&token::CloseDelim(token::DelimToken::Paren))?;
519     Ok(result)
520 }
521
522 fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::InlineAsm> {
523     let mut template = vec![];
524     // Register operands are implicitly used since they are not allowed to be
525     // referenced in the template string.
526     let mut used = vec![false; args.operands.len()];
527     for pos in &args.reg_args {
528         used[*pos] = true;
529     }
530     let named_pos: FxHashMap<usize, Symbol> =
531         args.named_args.iter().map(|(&sym, &idx)| (idx, sym)).collect();
532     let mut line_spans = Vec::with_capacity(args.templates.len());
533     let mut curarg = 0;
534
535     let mut template_strs = Vec::with_capacity(args.templates.len());
536
537     for template_expr in args.templates.into_iter() {
538         if !template.is_empty() {
539             template.push(ast::InlineAsmTemplatePiece::String("\n".to_string()));
540         }
541
542         let msg = "asm template must be a string literal";
543         let template_sp = template_expr.span;
544         let (template_str, template_style, template_span) =
545             match expr_to_spanned_string(ecx, template_expr, msg) {
546                 Ok(template_part) => template_part,
547                 Err(err) => {
548                     if let Some((mut err, _)) = err {
549                         err.emit();
550                     }
551                     return None;
552                 }
553             };
554
555         let str_style = match template_style {
556             ast::StrStyle::Cooked => None,
557             ast::StrStyle::Raw(raw) => Some(raw as usize),
558         };
559
560         let template_snippet = ecx.source_map().span_to_snippet(template_sp).ok();
561         template_strs.push((
562             template_str,
563             template_snippet.as_ref().map(|s| Symbol::intern(s)),
564             template_sp,
565         ));
566         let template_str = template_str.as_str();
567
568         if let Some(InlineAsmArch::X86 | InlineAsmArch::X86_64) = ecx.sess.asm_arch {
569             let find_span = |needle: &str| -> Span {
570                 if let Some(snippet) = &template_snippet {
571                     if let Some(pos) = snippet.find(needle) {
572                         let end = pos
573                             + snippet[pos..]
574                                 .find(|c| matches!(c, '\n' | ';' | '\\' | '"'))
575                                 .unwrap_or(snippet[pos..].len() - 1);
576                         let inner = InnerSpan::new(pos, end);
577                         return template_sp.from_inner(inner);
578                     }
579                 }
580                 template_sp
581             };
582
583             if template_str.contains(".intel_syntax") {
584                 ecx.parse_sess().buffer_lint(
585                     lint::builtin::BAD_ASM_STYLE,
586                     find_span(".intel_syntax"),
587                     ecx.current_expansion.lint_node_id,
588                     "avoid using `.intel_syntax`, Intel syntax is the default",
589                 );
590             }
591             if template_str.contains(".att_syntax") {
592                 ecx.parse_sess().buffer_lint(
593                     lint::builtin::BAD_ASM_STYLE,
594                     find_span(".att_syntax"),
595                     ecx.current_expansion.lint_node_id,
596                     "avoid using `.att_syntax`, prefer using `options(att_syntax)` instead",
597                 );
598             }
599         }
600
601         // Don't treat raw asm as a format string.
602         if args.options.contains(ast::InlineAsmOptions::RAW) {
603             template.push(ast::InlineAsmTemplatePiece::String(template_str.to_string()));
604             let template_num_lines = 1 + template_str.matches('\n').count();
605             line_spans.extend(std::iter::repeat(template_sp).take(template_num_lines));
606             continue;
607         }
608
609         let mut parser = parse::Parser::new(
610             template_str,
611             str_style,
612             template_snippet,
613             false,
614             parse::ParseMode::InlineAsm,
615         );
616         parser.curarg = curarg;
617
618         let mut unverified_pieces = Vec::new();
619         while let Some(piece) = parser.next() {
620             if !parser.errors.is_empty() {
621                 break;
622             } else {
623                 unverified_pieces.push(piece);
624             }
625         }
626
627         if !parser.errors.is_empty() {
628             let err = parser.errors.remove(0);
629             let err_sp = template_span.from_inner(err.span);
630             let msg = &format!("invalid asm template string: {}", err.description);
631             let mut e = ecx.struct_span_err(err_sp, msg);
632             e.span_label(err_sp, err.label + " in asm template string");
633             if let Some(note) = err.note {
634                 e.note(&note);
635             }
636             if let Some((label, span)) = err.secondary_label {
637                 let err_sp = template_span.from_inner(span);
638                 e.span_label(err_sp, label);
639             }
640             e.emit();
641             return None;
642         }
643
644         curarg = parser.curarg;
645
646         let mut arg_spans = parser.arg_places.iter().map(|span| template_span.from_inner(*span));
647         for piece in unverified_pieces {
648             match piece {
649                 parse::Piece::String(s) => {
650                     template.push(ast::InlineAsmTemplatePiece::String(s.to_string()))
651                 }
652                 parse::Piece::NextArgument(arg) => {
653                     let span = arg_spans.next().unwrap_or(template_sp);
654
655                     let operand_idx = match arg.position {
656                         parse::ArgumentIs(idx) | parse::ArgumentImplicitlyIs(idx) => {
657                             if idx >= args.operands.len()
658                                 || named_pos.contains_key(&idx)
659                                 || args.reg_args.contains(&idx)
660                             {
661                                 let msg = format!("invalid reference to argument at index {}", idx);
662                                 let mut err = ecx.struct_span_err(span, &msg);
663                                 err.span_label(span, "from here");
664
665                                 let positional_args = args.operands.len()
666                                     - args.named_args.len()
667                                     - args.reg_args.len();
668                                 let positional = if positional_args != args.operands.len() {
669                                     "positional "
670                                 } else {
671                                     ""
672                                 };
673                                 let msg = match positional_args {
674                                     0 => format!("no {}arguments were given", positional),
675                                     1 => format!("there is 1 {}argument", positional),
676                                     x => format!("there are {} {}arguments", x, positional),
677                                 };
678                                 err.note(&msg);
679
680                                 if named_pos.contains_key(&idx) {
681                                     err.span_label(args.operands[idx].1, "named argument");
682                                     err.span_note(
683                                         args.operands[idx].1,
684                                         "named arguments cannot be referenced by position",
685                                     );
686                                 } else if args.reg_args.contains(&idx) {
687                                     err.span_label(
688                                         args.operands[idx].1,
689                                         "explicit register argument",
690                                     );
691                                     err.span_note(
692                                         args.operands[idx].1,
693                                         "explicit register arguments cannot be used in the asm template",
694                                     );
695                                 }
696                                 err.emit();
697                                 None
698                             } else {
699                                 Some(idx)
700                             }
701                         }
702                         parse::ArgumentNamed(name, span) => match args.named_args.get(&name) {
703                             Some(&idx) => Some(idx),
704                             None => {
705                                 let msg = format!("there is no argument named `{}`", name);
706                                 ecx.struct_span_err(template_span.from_inner(span), &msg).emit();
707                                 None
708                             }
709                         },
710                     };
711
712                     let mut chars = arg.format.ty.chars();
713                     let mut modifier = chars.next();
714                     if chars.next().is_some() {
715                         let span = arg
716                             .format
717                             .ty_span
718                             .map(|sp| template_sp.from_inner(sp))
719                             .unwrap_or(template_sp);
720                         ecx.struct_span_err(
721                             span,
722                             "asm template modifier must be a single character",
723                         )
724                         .emit();
725                         modifier = None;
726                     }
727
728                     if let Some(operand_idx) = operand_idx {
729                         used[operand_idx] = true;
730                         template.push(ast::InlineAsmTemplatePiece::Placeholder {
731                             operand_idx,
732                             modifier,
733                             span,
734                         });
735                     }
736                 }
737             }
738         }
739
740         if parser.line_spans.is_empty() {
741             let template_num_lines = 1 + template_str.matches('\n').count();
742             line_spans.extend(std::iter::repeat(template_sp).take(template_num_lines));
743         } else {
744             line_spans.extend(parser.line_spans.iter().map(|span| template_span.from_inner(*span)));
745         };
746     }
747
748     let mut unused_operands = vec![];
749     let mut help_str = String::new();
750     for (idx, used) in used.into_iter().enumerate() {
751         if !used {
752             let msg = if let Some(sym) = named_pos.get(&idx) {
753                 help_str.push_str(&format!(" {{{}}}", sym));
754                 "named argument never used"
755             } else {
756                 help_str.push_str(&format!(" {{{}}}", idx));
757                 "argument never used"
758             };
759             unused_operands.push((args.operands[idx].1, msg));
760         }
761     }
762     match unused_operands.len() {
763         0 => {}
764         1 => {
765             let (sp, msg) = unused_operands.into_iter().next().unwrap();
766             let mut err = ecx.struct_span_err(sp, msg);
767             err.span_label(sp, msg);
768             err.help(&format!(
769                 "if this argument is intentionally unused, \
770                  consider using it in an asm comment: `\"/*{} */\"`",
771                 help_str
772             ));
773             err.emit();
774         }
775         _ => {
776             let mut err = ecx.struct_span_err(
777                 unused_operands.iter().map(|&(sp, _)| sp).collect::<Vec<Span>>(),
778                 "multiple unused asm arguments",
779             );
780             for (sp, msg) in unused_operands {
781                 err.span_label(sp, msg);
782             }
783             err.help(&format!(
784                 "if these arguments are intentionally unused, \
785                  consider using them in an asm comment: `\"/*{} */\"`",
786                 help_str
787             ));
788             err.emit();
789         }
790     }
791
792     Some(ast::InlineAsm {
793         template,
794         template_strs: template_strs.into_boxed_slice(),
795         operands: args.operands,
796         clobber_abis: args.clobber_abis,
797         options: args.options,
798         line_spans,
799     })
800 }
801
802 pub(super) fn expand_asm<'cx>(
803     ecx: &'cx mut ExtCtxt<'_>,
804     sp: Span,
805     tts: TokenStream,
806 ) -> Box<dyn base::MacResult + 'cx> {
807     match parse_args(ecx, sp, tts, false) {
808         Ok(args) => {
809             let expr = if let Some(inline_asm) = expand_preparsed_asm(ecx, args) {
810                 P(ast::Expr {
811                     id: ast::DUMMY_NODE_ID,
812                     kind: ast::ExprKind::InlineAsm(P(inline_asm)),
813                     span: sp,
814                     attrs: ast::AttrVec::new(),
815                     tokens: None,
816                 })
817             } else {
818                 DummyResult::raw_expr(sp, true)
819             };
820             MacEager::expr(expr)
821         }
822         Err(mut err) => {
823             err.emit();
824             DummyResult::any(sp)
825         }
826     }
827 }
828
829 pub(super) fn expand_global_asm<'cx>(
830     ecx: &'cx mut ExtCtxt<'_>,
831     sp: Span,
832     tts: TokenStream,
833 ) -> Box<dyn base::MacResult + 'cx> {
834     match parse_args(ecx, sp, tts, true) {
835         Ok(args) => {
836             if let Some(inline_asm) = expand_preparsed_asm(ecx, args) {
837                 MacEager::items(smallvec![P(ast::Item {
838                     ident: Ident::empty(),
839                     attrs: Vec::new(),
840                     id: ast::DUMMY_NODE_ID,
841                     kind: ast::ItemKind::GlobalAsm(Box::new(inline_asm)),
842                     vis: ast::Visibility {
843                         span: sp.shrink_to_lo(),
844                         kind: ast::VisibilityKind::Inherited,
845                         tokens: None,
846                     },
847                     span: ecx.with_def_site_ctxt(sp),
848                     tokens: None,
849                 })])
850             } else {
851                 DummyResult::any(sp)
852             }
853         }
854         Err(mut err) => {
855             err.emit();
856             DummyResult::any(sp)
857         }
858     }
859 }