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