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