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