]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_builtin_macros/src/asm.rs
Rollup merge of #80573 - jyn514:tool-lints, r=GuillaumeGomez
[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, DiagnosticBuilder};
7 use rustc_expand::base::{self, *};
8 use rustc_parse::parser::Parser;
9 use rustc_parse_format as parse;
10 use rustc_span::symbol::{kw, sym, Symbol};
11 use rustc_span::{InnerSpan, Span};
12
13 struct AsmArgs {
14     templates: Vec<P<ast::Expr>>,
15     operands: Vec<(ast::InlineAsmOperand, Span)>,
16     named_args: FxHashMap<Symbol, usize>,
17     reg_args: FxHashSet<usize>,
18     options: ast::InlineAsmOptions,
19     options_spans: Vec<Span>,
20 }
21
22 fn parse_args<'a>(
23     ecx: &mut ExtCtxt<'a>,
24     sp: Span,
25     tts: TokenStream,
26 ) -> Result<AsmArgs, DiagnosticBuilder<'a>> {
27     let mut p = ecx.new_parser_from_tts(tts);
28
29     if p.token == token::Eof {
30         return Err(ecx.struct_span_err(sp, "requires at least a template string argument"));
31     }
32
33     // Detect use of the legacy llvm_asm! syntax (which used to be called asm!)
34     if p.look_ahead(1, |t| *t == token::Colon || *t == token::ModSep) {
35         let mut err =
36             ecx.struct_span_err(sp, "the legacy LLVM-style asm! syntax is no longer supported");
37         err.note("consider migrating to the new asm! syntax specified in RFC 2873");
38         err.note("alternatively, switch to llvm_asm! to keep your code working as it is");
39
40         // Find the span of the "asm!" so that we can offer an automatic suggestion
41         let asm_span = sp.from_inner(InnerSpan::new(0, 4));
42         if let Ok(s) = ecx.source_map().span_to_snippet(asm_span) {
43             if s == "asm!" {
44                 err.span_suggestion(
45                     asm_span,
46                     "replace with",
47                     "llvm_asm!".into(),
48                     Applicability::MachineApplicable,
49                 );
50             }
51         }
52         return Err(err);
53     }
54
55     let first_template = p.parse_expr()?;
56     let mut args = AsmArgs {
57         templates: vec![first_template],
58         operands: vec![],
59         named_args: FxHashMap::default(),
60         reg_args: FxHashSet::default(),
61         options: ast::InlineAsmOptions::empty(),
62         options_spans: vec![],
63     };
64
65     let mut allow_templates = true;
66     while p.token != token::Eof {
67         if !p.eat(&token::Comma) {
68             if allow_templates {
69                 // After a template string, we always expect *only* a comma...
70                 let mut err = ecx.struct_span_err(p.token.span, "expected token: `,`");
71                 err.span_label(p.token.span, "expected `,`");
72                 p.maybe_annotate_with_ascription(&mut err, false);
73                 return Err(err);
74             } else {
75                 // ...after that delegate to `expect` to also include the other expected tokens.
76                 return Err(p.expect(&token::Comma).err().unwrap());
77             }
78         }
79         if p.token == token::Eof {
80             break;
81         } // accept trailing commas
82
83         // Parse options
84         if p.eat_keyword(sym::options) {
85             parse_options(&mut p, &mut args)?;
86             allow_templates = false;
87             continue;
88         }
89
90         let span_start = p.token.span;
91
92         // Parse operand names
93         let name = if p.token.is_ident() && p.look_ahead(1, |t| *t == token::Eq) {
94             let (ident, _) = p.token.ident().unwrap();
95             p.bump();
96             p.expect(&token::Eq)?;
97             allow_templates = false;
98             Some(ident.name)
99         } else {
100             None
101         };
102
103         let mut explicit_reg = false;
104         let op = if p.eat_keyword(kw::In) {
105             let reg = parse_reg(&mut p, &mut explicit_reg)?;
106             let expr = p.parse_expr()?;
107             ast::InlineAsmOperand::In { reg, expr }
108         } else if p.eat_keyword(sym::out) {
109             let reg = parse_reg(&mut p, &mut explicit_reg)?;
110             let expr = if p.eat_keyword(kw::Underscore) { None } else { Some(p.parse_expr()?) };
111             ast::InlineAsmOperand::Out { reg, expr, late: false }
112         } else if p.eat_keyword(sym::lateout) {
113             let reg = parse_reg(&mut p, &mut explicit_reg)?;
114             let expr = if p.eat_keyword(kw::Underscore) { None } else { Some(p.parse_expr()?) };
115             ast::InlineAsmOperand::Out { reg, expr, late: true }
116         } else if p.eat_keyword(sym::inout) {
117             let reg = parse_reg(&mut p, &mut explicit_reg)?;
118             let expr = p.parse_expr()?;
119             if p.eat(&token::FatArrow) {
120                 let out_expr =
121                     if p.eat_keyword(kw::Underscore) { None } else { Some(p.parse_expr()?) };
122                 ast::InlineAsmOperand::SplitInOut { reg, in_expr: expr, out_expr, late: false }
123             } else {
124                 ast::InlineAsmOperand::InOut { reg, expr, late: false }
125             }
126         } else if p.eat_keyword(sym::inlateout) {
127             let reg = parse_reg(&mut p, &mut explicit_reg)?;
128             let expr = p.parse_expr()?;
129             if p.eat(&token::FatArrow) {
130                 let out_expr =
131                     if p.eat_keyword(kw::Underscore) { None } else { Some(p.parse_expr()?) };
132                 ast::InlineAsmOperand::SplitInOut { reg, in_expr: expr, out_expr, late: true }
133             } else {
134                 ast::InlineAsmOperand::InOut { reg, expr, late: true }
135             }
136         } else if p.eat_keyword(kw::Const) {
137             let expr = p.parse_expr()?;
138             ast::InlineAsmOperand::Const { expr }
139         } else if p.eat_keyword(sym::sym) {
140             let expr = p.parse_expr()?;
141             match expr.kind {
142                 ast::ExprKind::Path(..) => {}
143                 _ => {
144                     let err = ecx
145                         .struct_span_err(expr.span, "argument to `sym` must be a path expression");
146                     return Err(err);
147                 }
148             }
149             ast::InlineAsmOperand::Sym { expr }
150         } else if allow_templates {
151             let template = p.parse_expr()?;
152             // If it can't possibly expand to a string, provide diagnostics here to include other
153             // things it could have been.
154             match template.kind {
155                 ast::ExprKind::Lit(ast::Lit { kind: ast::LitKind::Str(..), .. }) => {}
156                 ast::ExprKind::MacCall(..) => {}
157                 _ => {
158                     let errstr = "expected operand, options, or additional template string";
159                     let mut err = ecx.struct_span_err(template.span, errstr);
160                     err.span_label(template.span, errstr);
161                     return Err(err);
162                 }
163             }
164             args.templates.push(template);
165             continue;
166         } else {
167             return p.unexpected();
168         };
169
170         allow_templates = false;
171         let span = span_start.to(p.prev_token.span);
172         let slot = args.operands.len();
173         args.operands.push((op, span));
174
175         // Validate the order of named, positional & explicit register operands and options. We do
176         // this at the end once we have the full span of the argument available.
177         if !args.options_spans.is_empty() {
178             ecx.struct_span_err(span, "arguments are not allowed after options")
179                 .span_labels(args.options_spans.clone(), "previous options")
180                 .span_label(span, "argument")
181                 .emit();
182         }
183         if explicit_reg {
184             if name.is_some() {
185                 ecx.struct_span_err(span, "explicit register arguments cannot have names").emit();
186             }
187             args.reg_args.insert(slot);
188         } else if let Some(name) = name {
189             if let Some(&prev) = args.named_args.get(&name) {
190                 ecx.struct_span_err(span, &format!("duplicate argument named `{}`", name))
191                     .span_label(args.operands[prev].1, "previously here")
192                     .span_label(span, "duplicate argument")
193                     .emit();
194                 continue;
195             }
196             if !args.reg_args.is_empty() {
197                 let mut err = ecx.struct_span_err(
198                     span,
199                     "named arguments cannot follow explicit register arguments",
200                 );
201                 err.span_label(span, "named argument");
202                 for pos in &args.reg_args {
203                     err.span_label(args.operands[*pos].1, "explicit register argument");
204                 }
205                 err.emit();
206             }
207             args.named_args.insert(name, slot);
208         } else {
209             if !args.named_args.is_empty() || !args.reg_args.is_empty() {
210                 let mut err = ecx.struct_span_err(
211                     span,
212                     "positional arguments cannot follow named arguments \
213                      or explicit register arguments",
214                 );
215                 err.span_label(span, "positional argument");
216                 for pos in args.named_args.values() {
217                     err.span_label(args.operands[*pos].1, "named argument");
218                 }
219                 for pos in &args.reg_args {
220                     err.span_label(args.operands[*pos].1, "explicit register argument");
221                 }
222                 err.emit();
223             }
224         }
225     }
226
227     if args.options.contains(ast::InlineAsmOptions::NOMEM)
228         && args.options.contains(ast::InlineAsmOptions::READONLY)
229     {
230         let spans = args.options_spans.clone();
231         ecx.struct_span_err(spans, "the `nomem` and `readonly` options are mutually exclusive")
232             .emit();
233     }
234     if args.options.contains(ast::InlineAsmOptions::PURE)
235         && args.options.contains(ast::InlineAsmOptions::NORETURN)
236     {
237         let spans = args.options_spans.clone();
238         ecx.struct_span_err(spans, "the `pure` and `noreturn` options are mutually exclusive")
239             .emit();
240     }
241     if args.options.contains(ast::InlineAsmOptions::PURE)
242         && !args.options.intersects(ast::InlineAsmOptions::NOMEM | ast::InlineAsmOptions::READONLY)
243     {
244         let spans = args.options_spans.clone();
245         ecx.struct_span_err(
246             spans,
247             "the `pure` option must be combined with either `nomem` or `readonly`",
248         )
249         .emit();
250     }
251
252     let mut have_real_output = false;
253     let mut outputs_sp = vec![];
254     for (op, op_sp) in &args.operands {
255         match op {
256             ast::InlineAsmOperand::Out { expr, .. }
257             | ast::InlineAsmOperand::SplitInOut { out_expr: expr, .. } => {
258                 outputs_sp.push(*op_sp);
259                 have_real_output |= expr.is_some();
260             }
261             ast::InlineAsmOperand::InOut { .. } => {
262                 outputs_sp.push(*op_sp);
263                 have_real_output = true;
264             }
265             _ => {}
266         }
267     }
268     if args.options.contains(ast::InlineAsmOptions::PURE) && !have_real_output {
269         ecx.struct_span_err(
270             args.options_spans.clone(),
271             "asm with `pure` option must have at least one output",
272         )
273         .emit();
274     }
275     if args.options.contains(ast::InlineAsmOptions::NORETURN) && !outputs_sp.is_empty() {
276         let err = ecx
277             .struct_span_err(outputs_sp, "asm outputs are not allowed with the `noreturn` option");
278
279         // Bail out now since this is likely to confuse MIR
280         return Err(err);
281     }
282
283     Ok(args)
284 }
285
286 /// Report a duplicate option error.
287 ///
288 /// This function must be called immediately after the option token is parsed.
289 /// Otherwise, the suggestion will be incorrect.
290 fn err_duplicate_option<'a>(p: &mut Parser<'a>, symbol: Symbol, span: Span) {
291     let mut err = p
292         .sess
293         .span_diagnostic
294         .struct_span_err(span, &format!("the `{}` option was already provided", symbol));
295     err.span_label(span, "this option was already provided");
296
297     // Tool-only output
298     let mut full_span = span;
299     if p.token.kind == token::Comma {
300         full_span = full_span.to(p.token.span);
301     }
302     err.tool_only_span_suggestion(
303         full_span,
304         "remove this option",
305         String::new(),
306         Applicability::MachineApplicable,
307     );
308
309     err.emit();
310 }
311
312 /// Try to set the provided option in the provided `AsmArgs`.
313 /// If it is already set, report a duplicate option error.
314 ///
315 /// This function must be called immediately after the option token is parsed.
316 /// Otherwise, the error will not point to the correct spot.
317 fn try_set_option<'a>(
318     p: &mut Parser<'a>,
319     args: &mut AsmArgs,
320     symbol: Symbol,
321     option: ast::InlineAsmOptions,
322 ) {
323     if !args.options.contains(option) {
324         args.options |= option;
325     } else {
326         err_duplicate_option(p, symbol, p.prev_token.span);
327     }
328 }
329
330 fn parse_options<'a>(p: &mut Parser<'a>, args: &mut AsmArgs) -> Result<(), DiagnosticBuilder<'a>> {
331     let span_start = p.prev_token.span;
332
333     p.expect(&token::OpenDelim(token::DelimToken::Paren))?;
334
335     while !p.eat(&token::CloseDelim(token::DelimToken::Paren)) {
336         if p.eat_keyword(sym::pure) {
337             try_set_option(p, args, sym::pure, ast::InlineAsmOptions::PURE);
338         } else if p.eat_keyword(sym::nomem) {
339             try_set_option(p, args, sym::nomem, ast::InlineAsmOptions::NOMEM);
340         } else if p.eat_keyword(sym::readonly) {
341             try_set_option(p, args, sym::readonly, ast::InlineAsmOptions::READONLY);
342         } else if p.eat_keyword(sym::preserves_flags) {
343             try_set_option(p, args, sym::preserves_flags, ast::InlineAsmOptions::PRESERVES_FLAGS);
344         } else if p.eat_keyword(sym::noreturn) {
345             try_set_option(p, args, sym::noreturn, ast::InlineAsmOptions::NORETURN);
346         } else if p.eat_keyword(sym::nostack) {
347             try_set_option(p, args, sym::nostack, ast::InlineAsmOptions::NOSTACK);
348         } else if p.eat_keyword(sym::att_syntax) {
349             try_set_option(p, args, sym::att_syntax, ast::InlineAsmOptions::ATT_SYNTAX);
350         } else {
351             return p.unexpected();
352         }
353
354         // Allow trailing commas
355         if p.eat(&token::CloseDelim(token::DelimToken::Paren)) {
356             break;
357         }
358         p.expect(&token::Comma)?;
359     }
360
361     let new_span = span_start.to(p.prev_token.span);
362     args.options_spans.push(new_span);
363
364     Ok(())
365 }
366
367 fn parse_reg<'a>(
368     p: &mut Parser<'a>,
369     explicit_reg: &mut bool,
370 ) -> Result<ast::InlineAsmRegOrRegClass, DiagnosticBuilder<'a>> {
371     p.expect(&token::OpenDelim(token::DelimToken::Paren))?;
372     let result = match p.token.uninterpolate().kind {
373         token::Ident(name, false) => ast::InlineAsmRegOrRegClass::RegClass(name),
374         token::Literal(token::Lit { kind: token::LitKind::Str, symbol, suffix: _ }) => {
375             *explicit_reg = true;
376             ast::InlineAsmRegOrRegClass::Reg(symbol)
377         }
378         _ => {
379             return Err(
380                 p.struct_span_err(p.token.span, "expected register class or explicit register")
381             );
382         }
383     };
384     p.bump();
385     p.expect(&token::CloseDelim(token::DelimToken::Paren))?;
386     Ok(result)
387 }
388
389 fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, sp: Span, args: AsmArgs) -> P<ast::Expr> {
390     let mut template = vec![];
391     // Register operands are implicitly used since they are not allowed to be
392     // referenced in the template string.
393     let mut used = vec![false; args.operands.len()];
394     for pos in &args.reg_args {
395         used[*pos] = true;
396     }
397     let named_pos: FxHashMap<usize, Symbol> =
398         args.named_args.iter().map(|(&sym, &idx)| (idx, sym)).collect();
399     let mut line_spans = Vec::with_capacity(args.templates.len());
400     let mut curarg = 0;
401
402     for template_expr in args.templates.into_iter() {
403         if !template.is_empty() {
404             template.push(ast::InlineAsmTemplatePiece::String("\n".to_string()));
405         }
406
407         let msg = "asm template must be a string literal";
408         let template_sp = template_expr.span;
409         let (template_str, template_style, template_span) =
410             match expr_to_spanned_string(ecx, template_expr, msg) {
411                 Ok(template_part) => template_part,
412                 Err(err) => {
413                     if let Some(mut err) = err {
414                         err.emit();
415                     }
416                     return DummyResult::raw_expr(sp, true);
417                 }
418             };
419
420         let str_style = match template_style {
421             ast::StrStyle::Cooked => None,
422             ast::StrStyle::Raw(raw) => Some(raw as usize),
423         };
424
425         let template_str = &template_str.as_str();
426         let template_snippet = ecx.source_map().span_to_snippet(template_sp).ok();
427         let mut parser = parse::Parser::new(
428             template_str,
429             str_style,
430             template_snippet,
431             false,
432             parse::ParseMode::InlineAsm,
433         );
434         parser.curarg = curarg;
435
436         let mut unverified_pieces = Vec::new();
437         while let Some(piece) = parser.next() {
438             if !parser.errors.is_empty() {
439                 break;
440             } else {
441                 unverified_pieces.push(piece);
442             }
443         }
444
445         if !parser.errors.is_empty() {
446             let err = parser.errors.remove(0);
447             let err_sp = template_span.from_inner(err.span);
448             let msg = &format!("invalid asm template string: {}", err.description);
449             let mut e = ecx.struct_span_err(err_sp, msg);
450             e.span_label(err_sp, err.label + " in asm template string");
451             if let Some(note) = err.note {
452                 e.note(&note);
453             }
454             if let Some((label, span)) = err.secondary_label {
455                 let err_sp = template_span.from_inner(span);
456                 e.span_label(err_sp, label);
457             }
458             e.emit();
459             return DummyResult::raw_expr(sp, true);
460         }
461
462         curarg = parser.curarg;
463
464         let mut arg_spans = parser.arg_places.iter().map(|span| template_span.from_inner(*span));
465         for piece in unverified_pieces {
466             match piece {
467                 parse::Piece::String(s) => {
468                     template.push(ast::InlineAsmTemplatePiece::String(s.to_string()))
469                 }
470                 parse::Piece::NextArgument(arg) => {
471                     let span = arg_spans.next().unwrap_or(template_sp);
472
473                     let operand_idx = match arg.position {
474                         parse::ArgumentIs(idx) | parse::ArgumentImplicitlyIs(idx) => {
475                             if idx >= args.operands.len()
476                                 || named_pos.contains_key(&idx)
477                                 || args.reg_args.contains(&idx)
478                             {
479                                 let msg = format!("invalid reference to argument at index {}", idx);
480                                 let mut err = ecx.struct_span_err(span, &msg);
481                                 err.span_label(span, "from here");
482
483                                 let positional_args = args.operands.len()
484                                     - args.named_args.len()
485                                     - args.reg_args.len();
486                                 let positional = if positional_args != args.operands.len() {
487                                     "positional "
488                                 } else {
489                                     ""
490                                 };
491                                 let msg = match positional_args {
492                                     0 => format!("no {}arguments were given", positional),
493                                     1 => format!("there is 1 {}argument", positional),
494                                     x => format!("there are {} {}arguments", x, positional),
495                                 };
496                                 err.note(&msg);
497
498                                 if named_pos.contains_key(&idx) {
499                                     err.span_label(args.operands[idx].1, "named argument");
500                                     err.span_note(
501                                         args.operands[idx].1,
502                                         "named arguments cannot be referenced by position",
503                                     );
504                                 } else if args.reg_args.contains(&idx) {
505                                     err.span_label(
506                                         args.operands[idx].1,
507                                         "explicit register argument",
508                                     );
509                                     err.span_note(
510                                         args.operands[idx].1,
511                                         "explicit register arguments cannot be used in the asm template",
512                                     );
513                                 }
514                                 err.emit();
515                                 None
516                             } else {
517                                 Some(idx)
518                             }
519                         }
520                         parse::ArgumentNamed(name) => match args.named_args.get(&name) {
521                             Some(&idx) => Some(idx),
522                             None => {
523                                 let msg = format!("there is no argument named `{}`", name);
524                                 ecx.struct_span_err(span, &msg[..]).emit();
525                                 None
526                             }
527                         },
528                     };
529
530                     let mut chars = arg.format.ty.chars();
531                     let mut modifier = chars.next();
532                     if chars.next().is_some() {
533                         let span = arg
534                             .format
535                             .ty_span
536                             .map(|sp| template_sp.from_inner(sp))
537                             .unwrap_or(template_sp);
538                         ecx.struct_span_err(
539                             span,
540                             "asm template modifier must be a single character",
541                         )
542                         .emit();
543                         modifier = None;
544                     }
545
546                     if let Some(operand_idx) = operand_idx {
547                         used[operand_idx] = true;
548                         template.push(ast::InlineAsmTemplatePiece::Placeholder {
549                             operand_idx,
550                             modifier,
551                             span,
552                         });
553                     }
554                 }
555             }
556         }
557
558         if parser.line_spans.is_empty() {
559             let template_num_lines = 1 + template_str.matches('\n').count();
560             line_spans.extend(std::iter::repeat(template_sp).take(template_num_lines));
561         } else {
562             line_spans.extend(parser.line_spans.iter().map(|span| template_span.from_inner(*span)));
563         };
564     }
565
566     let mut unused_operands = vec![];
567     let mut help_str = String::new();
568     for (idx, used) in used.into_iter().enumerate() {
569         if !used {
570             let msg = if let Some(sym) = named_pos.get(&idx) {
571                 help_str.push_str(&format!(" {{{}}}", sym));
572                 "named argument never used"
573             } else {
574                 help_str.push_str(&format!(" {{{}}}", idx));
575                 "argument never used"
576             };
577             unused_operands.push((args.operands[idx].1, msg));
578         }
579     }
580     match unused_operands.len() {
581         0 => {}
582         1 => {
583             let (sp, msg) = unused_operands.into_iter().next().unwrap();
584             let mut err = ecx.struct_span_err(sp, msg);
585             err.span_label(sp, msg);
586             err.help(&format!(
587                 "if this argument is intentionally unused, \
588                  consider using it in an asm comment: `\"/*{} */\"`",
589                 help_str
590             ));
591             err.emit();
592         }
593         _ => {
594             let mut err = ecx.struct_span_err(
595                 unused_operands.iter().map(|&(sp, _)| sp).collect::<Vec<Span>>(),
596                 "multiple unused asm arguments",
597             );
598             for (sp, msg) in unused_operands {
599                 err.span_label(sp, msg);
600             }
601             err.help(&format!(
602                 "if these arguments are intentionally unused, \
603                  consider using them in an asm comment: `\"/*{} */\"`",
604                 help_str
605             ));
606             err.emit();
607         }
608     }
609
610     let inline_asm =
611         ast::InlineAsm { template, operands: args.operands, options: args.options, line_spans };
612     P(ast::Expr {
613         id: ast::DUMMY_NODE_ID,
614         kind: ast::ExprKind::InlineAsm(P(inline_asm)),
615         span: sp,
616         attrs: ast::AttrVec::new(),
617         tokens: None,
618     })
619 }
620
621 pub fn expand_asm<'cx>(
622     ecx: &'cx mut ExtCtxt<'_>,
623     sp: Span,
624     tts: TokenStream,
625 ) -> Box<dyn base::MacResult + 'cx> {
626     match parse_args(ecx, sp, tts) {
627         Ok(args) => MacEager::expr(expand_preparsed_asm(ecx, sp, args)),
628         Err(mut err) => {
629             err.emit();
630             DummyResult::any(sp)
631         }
632     }
633 }