]> git.lizzy.rs Git - rust.git/blob - src/librustc_builtin_macros/asm.rs
asm: When pretty-printing, don't escape characters twice
[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     template: 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_span: Option<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 template = p.parse_expr()?;
56     let mut args = AsmArgs {
57         template,
58         operands: vec![],
59         named_args: FxHashMap::default(),
60         reg_args: FxHashSet::default(),
61         options: ast::InlineAsmOptions::empty(),
62         options_span: None,
63     };
64
65     let mut first = true;
66     while p.token != token::Eof {
67         if !p.eat(&token::Comma) {
68             if first {
69                 // After `asm!(""` 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         first = false;
80         if p.token == token::Eof {
81             break;
82         } // accept trailing commas
83
84         // Parse options
85         if p.eat(&token::Ident(sym::options, false)) {
86             parse_options(&mut p, &mut args)?;
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             Some(ident.name)
98         } else {
99             None
100         };
101
102         let mut explicit_reg = false;
103         let op = if p.eat(&token::Ident(kw::In, false)) {
104             let reg = parse_reg(&mut p, &mut explicit_reg)?;
105             let expr = p.parse_expr()?;
106             ast::InlineAsmOperand::In { reg, expr }
107         } else if p.eat(&token::Ident(sym::out, false)) {
108             let reg = parse_reg(&mut p, &mut explicit_reg)?;
109             let expr = if p.eat_keyword(kw::Underscore) { None } else { Some(p.parse_expr()?) };
110             ast::InlineAsmOperand::Out { reg, expr, late: false }
111         } else if p.eat(&token::Ident(sym::lateout, false)) {
112             let reg = parse_reg(&mut p, &mut explicit_reg)?;
113             let expr = if p.eat_keyword(kw::Underscore) { None } else { Some(p.parse_expr()?) };
114             ast::InlineAsmOperand::Out { reg, expr, late: true }
115         } else if p.eat(&token::Ident(sym::inout, false)) {
116             let reg = parse_reg(&mut p, &mut explicit_reg)?;
117             let expr = p.parse_expr()?;
118             if p.eat(&token::FatArrow) {
119                 let out_expr =
120                     if p.eat_keyword(kw::Underscore) { None } else { Some(p.parse_expr()?) };
121                 ast::InlineAsmOperand::SplitInOut { reg, in_expr: expr, out_expr, late: false }
122             } else {
123                 ast::InlineAsmOperand::InOut { reg, expr, late: false }
124             }
125         } else if p.eat(&token::Ident(sym::inlateout, false)) {
126             let reg = parse_reg(&mut p, &mut explicit_reg)?;
127             let expr = p.parse_expr()?;
128             if p.eat(&token::FatArrow) {
129                 let out_expr =
130                     if p.eat_keyword(kw::Underscore) { None } else { Some(p.parse_expr()?) };
131                 ast::InlineAsmOperand::SplitInOut { reg, in_expr: expr, out_expr, late: true }
132             } else {
133                 ast::InlineAsmOperand::InOut { reg, expr, late: true }
134             }
135         } else if p.eat(&token::Ident(kw::Const, false)) {
136             let expr = p.parse_expr()?;
137             ast::InlineAsmOperand::Const { expr }
138         } else if p.eat(&token::Ident(sym::sym, false)) {
139             let expr = p.parse_expr()?;
140             match expr.kind {
141                 ast::ExprKind::Path(..) => {}
142                 _ => {
143                     let err = ecx
144                         .struct_span_err(expr.span, "argument to `sym` must be a path expression");
145                     return Err(err);
146                 }
147             }
148             ast::InlineAsmOperand::Sym { expr }
149         } else {
150             return Err(p.expect_one_of(&[], &[]).unwrap_err());
151         };
152
153         let span = span_start.to(p.prev_token.span);
154         let slot = args.operands.len();
155         args.operands.push((op, span));
156
157         // Validate the order of named, positional & explicit register operands and options. We do
158         // this at the end once we have the full span of the argument available.
159         if let Some(options_span) = args.options_span {
160             ecx.struct_span_err(span, "arguments are not allowed after options")
161                 .span_label(options_span, "previous options")
162                 .span_label(span, "argument")
163                 .emit();
164         }
165         if explicit_reg {
166             if name.is_some() {
167                 ecx.struct_span_err(span, "explicit register arguments cannot have names").emit();
168             }
169             args.reg_args.insert(slot);
170         } else if let Some(name) = name {
171             if let Some(&prev) = args.named_args.get(&name) {
172                 ecx.struct_span_err(span, &format!("duplicate argument named `{}`", name))
173                     .span_label(args.operands[prev].1, "previously here")
174                     .span_label(span, "duplicate argument")
175                     .emit();
176                 continue;
177             }
178             if !args.reg_args.is_empty() {
179                 let mut err = ecx.struct_span_err(
180                     span,
181                     "named arguments cannot follow explicit register arguments",
182                 );
183                 err.span_label(span, "named argument");
184                 for pos in &args.reg_args {
185                     err.span_label(args.operands[*pos].1, "explicit register argument");
186                 }
187                 err.emit();
188             }
189             args.named_args.insert(name, slot);
190         } else {
191             if !args.named_args.is_empty() || !args.reg_args.is_empty() {
192                 let mut err = ecx.struct_span_err(
193                     span,
194                     "positional arguments cannot follow named arguments \
195                      or explicit register arguments",
196                 );
197                 err.span_label(span, "positional argument");
198                 for pos in args.named_args.values() {
199                     err.span_label(args.operands[*pos].1, "named argument");
200                 }
201                 for pos in &args.reg_args {
202                     err.span_label(args.operands[*pos].1, "explicit register argument");
203                 }
204                 err.emit();
205             }
206         }
207     }
208
209     if args.options.contains(ast::InlineAsmOptions::NOMEM)
210         && args.options.contains(ast::InlineAsmOptions::READONLY)
211     {
212         let span = args.options_span.unwrap();
213         ecx.struct_span_err(span, "the `nomem` and `readonly` options are mutually exclusive")
214             .emit();
215     }
216     if args.options.contains(ast::InlineAsmOptions::PURE)
217         && args.options.contains(ast::InlineAsmOptions::NORETURN)
218     {
219         let span = args.options_span.unwrap();
220         ecx.struct_span_err(span, "the `pure` and `noreturn` options are mutually exclusive")
221             .emit();
222     }
223     if args.options.contains(ast::InlineAsmOptions::PURE)
224         && !args.options.intersects(ast::InlineAsmOptions::NOMEM | ast::InlineAsmOptions::READONLY)
225     {
226         let span = args.options_span.unwrap();
227         ecx.struct_span_err(
228             span,
229             "the `pure` option must be combined with either `nomem` or `readonly`",
230         )
231         .emit();
232     }
233
234     let mut have_real_output = false;
235     let mut outputs_sp = vec![];
236     for (op, op_sp) in &args.operands {
237         match op {
238             ast::InlineAsmOperand::Out { expr, .. }
239             | ast::InlineAsmOperand::SplitInOut { out_expr: expr, .. } => {
240                 outputs_sp.push(*op_sp);
241                 have_real_output |= expr.is_some();
242             }
243             ast::InlineAsmOperand::InOut { .. } => {
244                 outputs_sp.push(*op_sp);
245                 have_real_output = true;
246             }
247             _ => {}
248         }
249     }
250     if args.options.contains(ast::InlineAsmOptions::PURE) && !have_real_output {
251         ecx.struct_span_err(
252             args.options_span.unwrap(),
253             "asm with `pure` option must have at least one output",
254         )
255         .emit();
256     }
257     if args.options.contains(ast::InlineAsmOptions::NORETURN) && !outputs_sp.is_empty() {
258         let err = ecx
259             .struct_span_err(outputs_sp, "asm outputs are not allowed with the `noreturn` option");
260
261         // Bail out now since this is likely to confuse MIR
262         return Err(err);
263     }
264
265     Ok(args)
266 }
267
268 fn parse_options<'a>(p: &mut Parser<'a>, args: &mut AsmArgs) -> Result<(), DiagnosticBuilder<'a>> {
269     let span_start = p.prev_token.span;
270
271     p.expect(&token::OpenDelim(token::DelimToken::Paren))?;
272
273     while !p.eat(&token::CloseDelim(token::DelimToken::Paren)) {
274         if p.eat(&token::Ident(sym::pure, false)) {
275             args.options |= ast::InlineAsmOptions::PURE;
276         } else if p.eat(&token::Ident(sym::nomem, false)) {
277             args.options |= ast::InlineAsmOptions::NOMEM;
278         } else if p.eat(&token::Ident(sym::readonly, false)) {
279             args.options |= ast::InlineAsmOptions::READONLY;
280         } else if p.eat(&token::Ident(sym::preserves_flags, false)) {
281             args.options |= ast::InlineAsmOptions::PRESERVES_FLAGS;
282         } else if p.eat(&token::Ident(sym::noreturn, false)) {
283             args.options |= ast::InlineAsmOptions::NORETURN;
284         } else if p.eat(&token::Ident(sym::nostack, false)) {
285             args.options |= ast::InlineAsmOptions::NOSTACK;
286         } else {
287             p.expect(&token::Ident(sym::att_syntax, false))?;
288             args.options |= ast::InlineAsmOptions::ATT_SYNTAX;
289         }
290
291         // Allow trailing commas
292         if p.eat(&token::CloseDelim(token::DelimToken::Paren)) {
293             break;
294         }
295         p.expect(&token::Comma)?;
296     }
297
298     let new_span = span_start.to(p.prev_token.span);
299     if let Some(options_span) = args.options_span {
300         p.struct_span_err(new_span, "asm options cannot be specified multiple times")
301             .span_label(options_span, "previously here")
302             .span_label(new_span, "duplicate options")
303             .emit();
304     } else {
305         args.options_span = Some(new_span);
306     }
307
308     Ok(())
309 }
310
311 fn parse_reg<'a>(
312     p: &mut Parser<'a>,
313     explicit_reg: &mut bool,
314 ) -> Result<ast::InlineAsmRegOrRegClass, DiagnosticBuilder<'a>> {
315     p.expect(&token::OpenDelim(token::DelimToken::Paren))?;
316     let result = match p.token.kind {
317         token::Ident(name, false) => ast::InlineAsmRegOrRegClass::RegClass(name),
318         token::Literal(token::Lit { kind: token::LitKind::Str, symbol, suffix: _ }) => {
319             *explicit_reg = true;
320             ast::InlineAsmRegOrRegClass::Reg(symbol)
321         }
322         _ => {
323             return Err(
324                 p.struct_span_err(p.token.span, "expected register class or explicit register")
325             );
326         }
327     };
328     p.bump();
329     p.expect(&token::CloseDelim(token::DelimToken::Paren))?;
330     Ok(result)
331 }
332
333 fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, sp: Span, args: AsmArgs) -> P<ast::Expr> {
334     let msg = "asm template must be a string literal";
335     let template_sp = args.template.span;
336     let (template_str, template_style, template_span) =
337         match expr_to_spanned_string(ecx, args.template, msg) {
338             Ok(template) => template,
339             Err(err) => {
340                 if let Some(mut err) = err {
341                     err.emit();
342                 }
343                 return DummyResult::raw_expr(sp, true);
344             }
345         };
346
347     let str_style = match template_style {
348         ast::StrStyle::Cooked => None,
349         ast::StrStyle::Raw(raw) => Some(raw as usize),
350     };
351
352     let template_str = &template_str.as_str();
353     let template_snippet = ecx.source_map().span_to_snippet(template_sp).ok();
354     let mut parser = parse::Parser::new(
355         template_str,
356         str_style,
357         template_snippet,
358         false,
359         parse::ParseMode::InlineAsm,
360     );
361
362     let mut unverified_pieces = Vec::new();
363     while let Some(piece) = parser.next() {
364         if !parser.errors.is_empty() {
365             break;
366         } else {
367             unverified_pieces.push(piece);
368         }
369     }
370
371     if !parser.errors.is_empty() {
372         let err = parser.errors.remove(0);
373         let err_sp = template_span.from_inner(err.span);
374         let mut e = ecx
375             .struct_span_err(err_sp, &format!("invalid asm template string: {}", err.description));
376         e.span_label(err_sp, err.label + " in asm template string");
377         if let Some(note) = err.note {
378             e.note(&note);
379         }
380         if let Some((label, span)) = err.secondary_label {
381             let err_sp = template_span.from_inner(span);
382             e.span_label(err_sp, label);
383         }
384         e.emit();
385         return DummyResult::raw_expr(sp, true);
386     }
387
388     // Register operands are implicitly used since they are not allowed to be
389     // referenced in the template string.
390     let mut used = vec![false; args.operands.len()];
391     for pos in &args.reg_args {
392         used[*pos] = true;
393     }
394
395     let named_pos: FxHashMap<usize, Symbol> =
396         args.named_args.iter().map(|(&sym, &idx)| (idx, sym)).collect();
397     let mut arg_spans = parser.arg_places.iter().map(|span| template_span.from_inner(*span));
398     let mut template = vec![];
399     for piece in unverified_pieces {
400         match piece {
401             parse::Piece::String(s) => {
402                 template.push(ast::InlineAsmTemplatePiece::String(s.to_string()))
403             }
404             parse::Piece::NextArgument(arg) => {
405                 let span = arg_spans.next().unwrap_or(template_sp);
406
407                 let operand_idx = match arg.position {
408                     parse::ArgumentIs(idx) | parse::ArgumentImplicitlyIs(idx) => {
409                         if idx >= args.operands.len()
410                             || named_pos.contains_key(&idx)
411                             || args.reg_args.contains(&idx)
412                         {
413                             let msg = format!("invalid reference to argument at index {}", idx);
414                             let mut err = ecx.struct_span_err(span, &msg);
415                             err.span_label(span, "from here");
416
417                             let positional_args =
418                                 args.operands.len() - args.named_args.len() - args.reg_args.len();
419                             let positional = if positional_args != args.operands.len() {
420                                 "positional "
421                             } else {
422                                 ""
423                             };
424                             let msg = match positional_args {
425                                 0 => format!("no {}arguments were given", positional),
426                                 1 => format!("there is 1 {}argument", positional),
427                                 x => format!("there are {} {}arguments", x, positional),
428                             };
429                             err.note(&msg);
430
431                             if named_pos.contains_key(&idx) {
432                                 err.span_label(args.operands[idx].1, "named argument");
433                                 err.span_note(
434                                     args.operands[idx].1,
435                                     "named arguments cannot be referenced by position",
436                                 );
437                             } else if args.reg_args.contains(&idx) {
438                                 err.span_label(args.operands[idx].1, "explicit register argument");
439                                 err.span_note(
440                                     args.operands[idx].1,
441                                     "explicit register arguments cannot be used in the asm template",
442                                 );
443                             }
444                             err.emit();
445                             None
446                         } else {
447                             Some(idx)
448                         }
449                     }
450                     parse::ArgumentNamed(name) => match args.named_args.get(&name) {
451                         Some(&idx) => Some(idx),
452                         None => {
453                             let msg = format!("there is no argument named `{}`", name);
454                             ecx.struct_span_err(span, &msg[..]).emit();
455                             None
456                         }
457                     },
458                 };
459
460                 let mut chars = arg.format.ty.chars();
461                 let mut modifier = chars.next();
462                 if chars.next().is_some() {
463                     let span = arg
464                         .format
465                         .ty_span
466                         .map(|sp| template_sp.from_inner(sp))
467                         .unwrap_or(template_sp);
468                     ecx.struct_span_err(span, "asm template modifier must be a single character")
469                         .emit();
470                     modifier = None;
471                 }
472
473                 if let Some(operand_idx) = operand_idx {
474                     used[operand_idx] = true;
475                     template.push(ast::InlineAsmTemplatePiece::Placeholder {
476                         operand_idx,
477                         modifier,
478                         span,
479                     });
480                 }
481             }
482         }
483     }
484
485     let mut unused_operands = vec![];
486     let mut help_str = String::new();
487     for (idx, used) in used.into_iter().enumerate() {
488         if !used {
489             let msg = if let Some(sym) = named_pos.get(&idx) {
490                 help_str.push_str(&format!(" {{{}}}", sym));
491                 "named argument never used"
492             } else {
493                 help_str.push_str(&format!(" {{{}}}", idx));
494                 "argument never used"
495             };
496             unused_operands.push((args.operands[idx].1, msg));
497         }
498     }
499     match unused_operands.len() {
500         0 => {}
501         1 => {
502             let (sp, msg) = unused_operands.into_iter().next().unwrap();
503             let mut err = ecx.struct_span_err(sp, msg);
504             err.span_label(sp, msg);
505             err.help(&format!(
506                 "if this argument is intentionally unused, \
507                  consider using it in an asm comment: `\"/*{} */\"`",
508                 help_str
509             ));
510             err.emit();
511         }
512         _ => {
513             let mut err = ecx.struct_span_err(
514                 unused_operands.iter().map(|&(sp, _)| sp).collect::<Vec<Span>>(),
515                 "multiple unused asm arguments",
516             );
517             for (sp, msg) in unused_operands {
518                 err.span_label(sp, msg);
519             }
520             err.help(&format!(
521                 "if these arguments are intentionally unused, \
522                  consider using them in an asm comment: `\"/*{} */\"`",
523                 help_str
524             ));
525             err.emit();
526         }
527     }
528
529     let line_spans = if parser.line_spans.is_empty() {
530         vec![template_sp]
531     } else {
532         parser.line_spans.iter().map(|span| template_span.from_inner(*span)).collect()
533     };
534
535     let inline_asm =
536         ast::InlineAsm { template, operands: args.operands, options: args.options, line_spans };
537     P(ast::Expr {
538         id: ast::DUMMY_NODE_ID,
539         kind: ast::ExprKind::InlineAsm(P(inline_asm)),
540         span: sp,
541         attrs: ast::AttrVec::new(),
542         tokens: None,
543     })
544 }
545
546 pub fn expand_asm<'cx>(
547     ecx: &'cx mut ExtCtxt<'_>,
548     sp: Span,
549     tts: TokenStream,
550 ) -> Box<dyn base::MacResult + 'cx> {
551     match parse_args(ecx, sp, tts) {
552         Ok(args) => MacEager::expr(expand_preparsed_asm(ecx, sp, args)),
553         Err(mut err) => {
554             err.emit();
555             DummyResult::any(sp)
556         }
557     }
558 }