]> git.lizzy.rs Git - rust.git/blob - src/librustc_builtin_macros/asm.rs
Rollup merge of #74188 - estebank:tweak-ascription-typo-heuristic, r=petrochenkov
[rust.git] / src / librustc_builtin_macros / asm.rs
1 use rustc_ast::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(&token::Ident(sym::options, false)) {
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(&token::Ident(kw::In, false)) {
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(&token::Ident(sym::out, false)) {
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(&token::Ident(sym::lateout, false)) {
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(&token::Ident(sym::inout, false)) {
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(&token::Ident(sym::inlateout, false)) {
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(&token::Ident(kw::Const, false)) {
137             let expr = p.parse_expr()?;
138             ast::InlineAsmOperand::Const { expr }
139         } else if p.eat(&token::Ident(sym::sym, false)) {
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 Err(p.expect_one_of(&[], &[]).unwrap_err());
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(&token::Ident(sym::pure, false)) {
337             try_set_option(p, args, sym::pure, ast::InlineAsmOptions::PURE);
338         } else if p.eat(&token::Ident(sym::nomem, false)) {
339             try_set_option(p, args, sym::nomem, ast::InlineAsmOptions::NOMEM);
340         } else if p.eat(&token::Ident(sym::readonly, false)) {
341             try_set_option(p, args, sym::readonly, ast::InlineAsmOptions::READONLY);
342         } else if p.eat(&token::Ident(sym::preserves_flags, false)) {
343             try_set_option(p, args, sym::preserves_flags, ast::InlineAsmOptions::PRESERVES_FLAGS);
344         } else if p.eat(&token::Ident(sym::noreturn, false)) {
345             try_set_option(p, args, sym::noreturn, ast::InlineAsmOptions::NORETURN);
346         } else if p.eat(&token::Ident(sym::nostack, false)) {
347             try_set_option(p, args, sym::nostack, ast::InlineAsmOptions::NOSTACK);
348         } else {
349             p.expect(&token::Ident(sym::att_syntax, false))?;
350             try_set_option(p, args, sym::att_syntax, ast::InlineAsmOptions::ATT_SYNTAX);
351         }
352
353         // Allow trailing commas
354         if p.eat(&token::CloseDelim(token::DelimToken::Paren)) {
355             break;
356         }
357         p.expect(&token::Comma)?;
358     }
359
360     let new_span = span_start.to(p.prev_token.span);
361     args.options_spans.push(new_span);
362
363     Ok(())
364 }
365
366 fn parse_reg<'a>(
367     p: &mut Parser<'a>,
368     explicit_reg: &mut bool,
369 ) -> Result<ast::InlineAsmRegOrRegClass, DiagnosticBuilder<'a>> {
370     p.expect(&token::OpenDelim(token::DelimToken::Paren))?;
371     let result = match p.token.kind {
372         token::Ident(name, false) => ast::InlineAsmRegOrRegClass::RegClass(name),
373         token::Literal(token::Lit { kind: token::LitKind::Str, symbol, suffix: _ }) => {
374             *explicit_reg = true;
375             ast::InlineAsmRegOrRegClass::Reg(symbol)
376         }
377         _ => {
378             return Err(
379                 p.struct_span_err(p.token.span, "expected register class or explicit register")
380             );
381         }
382     };
383     p.bump();
384     p.expect(&token::CloseDelim(token::DelimToken::Paren))?;
385     Ok(result)
386 }
387
388 fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, sp: Span, args: AsmArgs) -> P<ast::Expr> {
389     let mut template = vec![];
390     // Register operands are implicitly used since they are not allowed to be
391     // referenced in the template string.
392     let mut used = vec![false; args.operands.len()];
393     for pos in &args.reg_args {
394         used[*pos] = true;
395     }
396     let named_pos: FxHashMap<usize, Symbol> =
397         args.named_args.iter().map(|(&sym, &idx)| (idx, sym)).collect();
398     let mut line_spans = Vec::with_capacity(args.templates.len());
399     let mut curarg = 0;
400
401     for template_expr in args.templates.into_iter() {
402         if !template.is_empty() {
403             template.push(ast::InlineAsmTemplatePiece::String("\n".to_string()));
404         }
405
406         let msg = "asm template must be a string literal";
407         let template_sp = template_expr.span;
408         let (template_str, template_style, template_span) =
409             match expr_to_spanned_string(ecx, template_expr, msg) {
410                 Ok(template_part) => template_part,
411                 Err(err) => {
412                     if let Some(mut err) = err {
413                         err.emit();
414                     }
415                     return DummyResult::raw_expr(sp, true);
416                 }
417             };
418
419         let str_style = match template_style {
420             ast::StrStyle::Cooked => None,
421             ast::StrStyle::Raw(raw) => Some(raw as usize),
422         };
423
424         let template_str = &template_str.as_str();
425         let template_snippet = ecx.source_map().span_to_snippet(template_sp).ok();
426         let mut parser = parse::Parser::new(
427             template_str,
428             str_style,
429             template_snippet,
430             false,
431             parse::ParseMode::InlineAsm,
432         );
433         parser.curarg = curarg;
434
435         let mut unverified_pieces = Vec::new();
436         while let Some(piece) = parser.next() {
437             if !parser.errors.is_empty() {
438                 break;
439             } else {
440                 unverified_pieces.push(piece);
441             }
442         }
443
444         if !parser.errors.is_empty() {
445             let err = parser.errors.remove(0);
446             let err_sp = template_span.from_inner(err.span);
447             let msg = &format!("invalid asm template string: {}", err.description);
448             let mut e = ecx.struct_span_err(err_sp, msg);
449             e.span_label(err_sp, err.label + " in asm template string");
450             if let Some(note) = err.note {
451                 e.note(&note);
452             }
453             if let Some((label, span)) = err.secondary_label {
454                 let err_sp = template_span.from_inner(span);
455                 e.span_label(err_sp, label);
456             }
457             e.emit();
458             return DummyResult::raw_expr(sp, true);
459         }
460
461         curarg = parser.curarg;
462
463         let mut arg_spans = parser.arg_places.iter().map(|span| template_span.from_inner(*span));
464         for piece in unverified_pieces {
465             match piece {
466                 parse::Piece::String(s) => {
467                     template.push(ast::InlineAsmTemplatePiece::String(s.to_string()))
468                 }
469                 parse::Piece::NextArgument(arg) => {
470                     let span = arg_spans.next().unwrap_or(template_sp);
471
472                     let operand_idx = match arg.position {
473                         parse::ArgumentIs(idx) | parse::ArgumentImplicitlyIs(idx) => {
474                             if idx >= args.operands.len()
475                                 || named_pos.contains_key(&idx)
476                                 || args.reg_args.contains(&idx)
477                             {
478                                 let msg = format!("invalid reference to argument at index {}", idx);
479                                 let mut err = ecx.struct_span_err(span, &msg);
480                                 err.span_label(span, "from here");
481
482                                 let positional_args = args.operands.len()
483                                     - args.named_args.len()
484                                     - args.reg_args.len();
485                                 let positional = if positional_args != args.operands.len() {
486                                     "positional "
487                                 } else {
488                                     ""
489                                 };
490                                 let msg = match positional_args {
491                                     0 => format!("no {}arguments were given", positional),
492                                     1 => format!("there is 1 {}argument", positional),
493                                     x => format!("there are {} {}arguments", x, positional),
494                                 };
495                                 err.note(&msg);
496
497                                 if named_pos.contains_key(&idx) {
498                                     err.span_label(args.operands[idx].1, "named argument");
499                                     err.span_note(
500                                         args.operands[idx].1,
501                                         "named arguments cannot be referenced by position",
502                                     );
503                                 } else if args.reg_args.contains(&idx) {
504                                     err.span_label(
505                                         args.operands[idx].1,
506                                         "explicit register argument",
507                                     );
508                                     err.span_note(
509                                         args.operands[idx].1,
510                                         "explicit register arguments cannot be used in the asm template",
511                                     );
512                                 }
513                                 err.emit();
514                                 None
515                             } else {
516                                 Some(idx)
517                             }
518                         }
519                         parse::ArgumentNamed(name) => match args.named_args.get(&name) {
520                             Some(&idx) => Some(idx),
521                             None => {
522                                 let msg = format!("there is no argument named `{}`", name);
523                                 ecx.struct_span_err(span, &msg[..]).emit();
524                                 None
525                             }
526                         },
527                     };
528
529                     let mut chars = arg.format.ty.chars();
530                     let mut modifier = chars.next();
531                     if chars.next().is_some() {
532                         let span = arg
533                             .format
534                             .ty_span
535                             .map(|sp| template_sp.from_inner(sp))
536                             .unwrap_or(template_sp);
537                         ecx.struct_span_err(
538                             span,
539                             "asm template modifier must be a single character",
540                         )
541                         .emit();
542                         modifier = None;
543                     }
544
545                     if let Some(operand_idx) = operand_idx {
546                         used[operand_idx] = true;
547                         template.push(ast::InlineAsmTemplatePiece::Placeholder {
548                             operand_idx,
549                             modifier,
550                             span,
551                         });
552                     }
553                 }
554             }
555         }
556
557         if parser.line_spans.is_empty() {
558             let template_num_lines = 1 + template_str.matches('\n').count();
559             line_spans.extend(std::iter::repeat(template_sp).take(template_num_lines));
560         } else {
561             line_spans.extend(parser.line_spans.iter().map(|span| template_span.from_inner(*span)));
562         };
563     }
564
565     let mut unused_operands = vec![];
566     let mut help_str = String::new();
567     for (idx, used) in used.into_iter().enumerate() {
568         if !used {
569             let msg = if let Some(sym) = named_pos.get(&idx) {
570                 help_str.push_str(&format!(" {{{}}}", sym));
571                 "named argument never used"
572             } else {
573                 help_str.push_str(&format!(" {{{}}}", idx));
574                 "argument never used"
575             };
576             unused_operands.push((args.operands[idx].1, msg));
577         }
578     }
579     match unused_operands.len() {
580         0 => {}
581         1 => {
582             let (sp, msg) = unused_operands.into_iter().next().unwrap();
583             let mut err = ecx.struct_span_err(sp, msg);
584             err.span_label(sp, msg);
585             err.help(&format!(
586                 "if this argument is intentionally unused, \
587                  consider using it in an asm comment: `\"/*{} */\"`",
588                 help_str
589             ));
590             err.emit();
591         }
592         _ => {
593             let mut err = ecx.struct_span_err(
594                 unused_operands.iter().map(|&(sp, _)| sp).collect::<Vec<Span>>(),
595                 "multiple unused asm arguments",
596             );
597             for (sp, msg) in unused_operands {
598                 err.span_label(sp, msg);
599             }
600             err.help(&format!(
601                 "if these arguments are intentionally unused, \
602                  consider using them in an asm comment: `\"/*{} */\"`",
603                 help_str
604             ));
605             err.emit();
606         }
607     }
608
609     let inline_asm =
610         ast::InlineAsm { template, operands: args.operands, options: args.options, line_spans };
611     P(ast::Expr {
612         id: ast::DUMMY_NODE_ID,
613         kind: ast::ExprKind::InlineAsm(P(inline_asm)),
614         span: sp,
615         attrs: ast::AttrVec::new(),
616         tokens: None,
617     })
618 }
619
620 pub fn expand_asm<'cx>(
621     ecx: &'cx mut ExtCtxt<'_>,
622     sp: Span,
623     tts: TokenStream,
624 ) -> Box<dyn base::MacResult + 'cx> {
625     match parse_args(ecx, sp, tts) {
626         Ok(args) => MacEager::expr(expand_preparsed_asm(ecx, sp, args)),
627         Err(mut err) => {
628             err.emit();
629             DummyResult::any(sp)
630         }
631     }
632 }