Debian Codegraph @

gcc/rust/expand/rust-macro-builtins-asm.cc

raw
1 // Copyright (C) 2020-2025 Free Software Foundation, Inc.
2
3 // This file is part of GCC.
4
5 // GCC is free software; you can redistribute it and/or modify it under
6 // the terms of the GNU General Public License as published by the Free
7 // Software Foundation; either version 3, or (at your option) any later
8 // version.
9
10 // GCC is distributed in the hope that it will be useful, but WITHOUT ANY
11 // WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 // for more details.
14
15 // You should have received a copy of the GNU General Public License
16 // along with GCC; see the file COPYING3. If not see
17 // <http://www.gnu.org/licenses/>.
18
19 #include "expected.h"
20 #include "rust-macro-builtins-asm.h"
21 #include "rust-ast-fragment.h"
22 #include "rust-ast.h"
23 #include "rust-fmt.h"
24 #include "rust-stmt.h"
25
26 namespace Rust {
27 std::map<AST::InlineAsmOption, std::string> InlineAsmOptionMap{
28 {AST::InlineAsmOption::PURE, "pure"},
29 {AST::InlineAsmOption::NOMEM, "nomem"},
30 {AST::InlineAsmOption::READONLY, "readonly"},
31 {AST::InlineAsmOption::PRESERVES_FLAGS, "preserves_flags"},
32 {AST::InlineAsmOption::NORETURN, "noreturn"},
33 {AST::InlineAsmOption::NOSTACK, "nostack"},
34 {AST::InlineAsmOption::MAY_UNWIND, "may_unwind"},
35 {AST::InlineAsmOption::ATT_SYNTAX, "att_syntax"},
36 {AST::InlineAsmOption::RAW, "raw"},
37 };
38
39 std::set<std::string> potentially_nonpromoted_keywords
40 = {"in", "out", "lateout", "inout", "inlateout", "const", "sym", "label"};
41
42 // Helper function strips the beginning and ending double quotes from a
43 // string.
44 std::string
45 strip_double_quotes (const std::string &str)
46 {
47 std::string result = str;
48
49 rust_assert (!str.empty ());
50
51 rust_assert (str.front () == '\"');
52 rust_assert (str.back () == '\"');
53
54 // we have to special case empty strings which just contain a set of quotes
55 // so, if the string is "\"\"", just return ""
56 if (result.size () == 2)
57 return "";
58
59 rust_assert (result.size () >= 3);
60
61 result.erase (0, 1);
62 result.erase (result.size () - 1, 1);
63
64 return result;
65 }
66
67 tl::expected<InlineAsmContext, InlineAsmParseError>
68 parse_clobber_abi (InlineAsmContext inline_asm_ctx)
69 {
70 // clobber_abi := "clobber_abi(" <abi> *("," <abi>) [","] ")"
71 // PARSE EVERYTHING COMMITTEDLY IN THIS FUNCTION, WE CONFIRMED VIA clobber_abi
72 // identifier keyword
73 auto &parser = inline_asm_ctx.parser;
74 auto last_token_id = inline_asm_ctx.last_token_id;
75 auto &inline_asm = inline_asm_ctx.inline_asm;
76 auto token = parser.peek_current_token ();
77 if (!parser.skip_token (LEFT_PAREN))
78 {
79 token = parser.peek_current_token ();
80
81 // TODO: Error reporting shifted to the left 1 character, I'm not sure
82 // why.
83 if (token->get_id () == last_token_id)
84 {
85 rust_error_at (token->get_locus (),
86 "expected %<(%>, found end of macro arguments");
87 return tl::unexpected<InlineAsmParseError> (COMMITTED);
88 }
89 else
90 {
91 rust_error_at (token->get_locus (), "expected %<(%>, found %qs",
92 token->get_token_description ());
93 }
94 return tl::unexpected<InlineAsmParseError> (COMMITTED);
95 }
96
97 if (parser.skip_token (RIGHT_PAREN))
98 {
99 rust_error_at (
100 parser.peek_current_token ()->get_locus (),
101 "at least one abi must be provided as an argument to %<clobber_abi%>");
102 return tl::unexpected<InlineAsmParseError> (COMMITTED);
103 }
104
105 std::vector<AST::TupleClobber> new_abis;
106
107 token = parser.peek_current_token ();
108
109 while (token->get_id () != last_token_id && token->get_id () != RIGHT_PAREN)
110 {
111 // Check if it is a string literal or not, codename: <ABI> in ABNF
112 if (token->get_id () == STRING_LITERAL)
113 {
114 // TODO: Caring for span in here.
115 new_abis.push_back ({token->as_string (), token->get_locus ()});
116 }
117 else
118 {
119 // TODO: We encountered something that is not string literal, which
120 // should be illegal, please emit the correct error
121 // https://github.com/rust-lang/rust/blob/b92758a9aef1cef7b79e2b72c3d8ba113e547f89/compiler/rustc_builtin_macros/src/asm.rs#L387
122 rust_unreachable ();
123 }
124
125 if (parser.skip_token (RIGHT_PAREN))
126 {
127 break;
128 }
129
130 if (!parser.skip_token (COMMA))
131 {
132 // TODO: If the skip of comma is unsuccessful, which should be
133 // illegal, pleaes emit the correct error.
134 rust_unreachable ();
135 return tl::unexpected<InlineAsmParseError> (COMMITTED);
136 }
137
138 token = parser.peek_current_token ();
139 }
140
141 // Done processing the local clobber abis, push that to the main Args in
142 // argument
143
144 for (auto abi : new_abis)
145 {
146 inline_asm.clobber_abi.push_back (abi);
147 }
148
149 return inline_asm_ctx;
150 }
151
152 tl::optional<AST::InlineAsmRegOrRegClass>
153 parse_reg (InlineAsmContext &inline_asm_ctx)
154 {
155 using RegType = AST::InlineAsmRegOrRegClass::Type;
156 auto &parser = inline_asm_ctx.parser;
157
158 if (!parser.skip_token (LEFT_PAREN))
159 {
160 // TODO: we expect a left parenthesis here, please return the correct
161 // error.
162 rust_unreachable ();
163 return tl::nullopt;
164 }
165
166 // after successful left parenthesis parsing, we should return ast of
167 // InlineAsmRegOrRegClass of reg or reg class
168 auto token = parser.peek_current_token ();
169 AST::InlineAsmRegOrRegClass reg_class;
170 if (parser.skip_token (IDENTIFIER))
171 {
172 // construct a InlineAsmRegOrRegClass
173 reg_class.type = RegType::RegClass;
174 reg_class.reg_class.Symbol = token->as_string ();
175 }
176 else if (parser.skip_token (STRING_LITERAL))
177 {
178 // TODO: there is STRING_LITERAL, and BYTE_STRING_LITERAL, should we check
179 // for both?
180
181 // construct a InlineAsmRegOrRegClass
182 // parse_format_string
183 reg_class.type = RegType::Reg;
184 inline_asm_ctx.is_explicit = true;
185 reg_class.reg_class.Symbol = token->as_string ();
186 }
187 else
188 {
189 // TODO: This should emit error
190 // return
191 // Err(p.dcx().create_err(errors::ExpectedRegisterClassOrExplicitRegister
192 // {
193 // span: p.token.span,
194 // }));
195 rust_unreachable ();
196 }
197 if (!parser.skip_token (RIGHT_PAREN))
198 {
199 // TODO: we expect a left parenthesis here, please return the correct
200 // error.
201 rust_unreachable ();
202 return tl::nullopt;
203 }
204
205 return reg_class;
206 }
207
208 // From rustc
209 tl::expected<InlineAsmContext, InlineAsmParseError>
210 parse_reg_operand (InlineAsmContext inline_asm_ctx)
211 {
212 // let name = if p.token.is_ident() && p.look_ahead(1, |t| *t == token::Eq) {
213 // let (ident, _) = p.token.ident().unwrap();
214 // p.bump();
215 // p.expect(&token::Eq)?;
216 // allow_templates = false;
217 // Some(ident.name)
218 // } else {
219 // None
220 // };
221 auto &parser = inline_asm_ctx.parser;
222 auto token = parser.peek_current_token ();
223 auto iden_token = parser.peek_current_token ();
224
225 tl::optional<std::string> name = tl::nullopt;
226 if (check_identifier (parser, ""))
227 {
228 auto equal_token = parser.peek_current_token ();
229
230 if (parser.skip_token (EQUAL))
231 {
232 name = token->as_string ();
233 }
234 else
235 {
236 rust_error_at (token->get_locus (),
237 "expected operand, %s, options, or "
238 "additional template string",
239 "clobber_abi");
240 return tl::unexpected<InlineAsmParseError> (COMMITTED);
241 }
242 }
243
244 int slot = inline_asm_ctx.inline_asm.operands.size ();
245
246 // Here is all parse_reg_operand functions we're using in a for loop
247 auto parse_funcs = {parse_reg_operand_in, parse_reg_operand_out,
248 parse_reg_operand_lateout, parse_reg_operand_inout,
249 parse_reg_operand_const, parse_reg_operand_sym,
250 parse_reg_operand_unexpected};
251
252 // Loop over and execute the parsing functions, if the parser successfullly
253 // parses or if the parser fails to parse while it has committed to a token,
254 // we propogate the result.
255 tl::expected<InlineAsmContext, InlineAsmParseError> parsing_operand (
256 inline_asm_ctx);
257 for (auto &parse_func : parse_funcs)
258 {
259 auto result = parsing_operand.and_then (parse_func);
260
261 // Per rust's asm.rs's structure
262 // After we've parse successfully, we break out and do a local validation
263 // of named, positional & explicit register operands
264
265 if (result.has_value ())
266 {
267 inline_asm_ctx = *result;
268 break;
269 }
270 else if (result.error () == COMMITTED)
271 {
272 if (parse_func == parse_reg_operand_unexpected)
273 return inline_asm_ctx;
274 else
275 return result;
276 }
277 }
278
279 auto &inline_asm = inline_asm_ctx.inline_asm;
280
281 token = inline_asm_ctx.parser.peek_current_token ();
282 rust_debug_loc (token->get_locus (), "Here\n");
283 if (inline_asm_ctx.is_explicit)
284 {
285 if (name != tl::nullopt)
286 {
287 rust_error_at (token->get_locus (),
288 "explicit register arguments cannot have names");
289 return tl::unexpected<InlineAsmParseError> (COMMITTED);
290 }
291 inline_asm.reg_args.insert (slot);
292 }
293 else if (name != tl::nullopt)
294 {
295 if (inline_asm.named_args.find (name.value ())
296 != inline_asm.named_args.end ())
297 {
298 rust_error_at (token->get_locus (), "duplicate argument named %qs",
299 name.value ().c_str ());
300 return tl::unexpected<InlineAsmParseError> (COMMITTED);
301 }
302 inline_asm.named_args[name.value ()] = slot;
303 }
304 else
305 {
306 if (!inline_asm.named_args.empty () || !inline_asm.reg_args.empty ())
307 {
308 // positional arguments cannot follow named arguments or explicit
309 // register arguments
310 rust_error_at (token->get_locus (),
311 "positional arguments cannot follow named arguments "
312 "or explicit register arguments");
313 return tl::unexpected<InlineAsmParseError> (COMMITTED);
314 }
315 }
316
317 return inline_asm_ctx;
318 }
319
320 tl::expected<InlineAsmContext, InlineAsmParseError>
321 parse_reg_operand_in (InlineAsmContext inline_asm_ctx)
322 {
323 // For the keyword IN, currently we count it as a seperate keyword called
324 // Rust::IN search for #define RS_TOKEN_LIST in code base.
325 auto &parser = inline_asm_ctx.parser;
326 location_t locus = parser.peek_current_token ()->get_locus ();
327 if (!inline_asm_ctx.is_global_asm () && parser.skip_token (IN))
328 {
329 auto reg = parse_reg (inline_asm_ctx);
330
331 if (parser.skip_token (UNDERSCORE))
332 {
333 // We are sure to be failing a test here, based on asm.rs
334 // https://github.com/rust-lang/rust/blob/a330e49593ee890f9197727a3a558b6e6b37f843/compiler/rustc_builtin_macros/src/asm.rs#L112
335 rust_unreachable ();
336 // return tl::unexpected<InlineAsmParseError> (COMMITTED);
337 }
338
339 auto expr = parser.parse_expr ();
340
341 // TODO: When we've succesfully parse an expr, remember to clone_expr()
342 // instead of nullptr
343 AST::InlineAsmOperand::In in (reg, std::move (expr));
344 inline_asm_ctx.inline_asm.operands.emplace_back (in, locus);
345 return inline_asm_ctx;
346 }
347 return tl::unexpected<InlineAsmParseError> (NONCOMMITED);
348 }
349
350 tl::expected<InlineAsmContext, InlineAsmParseError>
351 parse_reg_operand_out (InlineAsmContext inline_asm_ctx)
352 {
353 auto &parser = inline_asm_ctx.parser;
354 location_t locus = parser.peek_current_token ()->get_locus ();
355 if (!inline_asm_ctx.is_global_asm () && check_identifier (parser, "out"))
356 {
357 auto reg = parse_reg (inline_asm_ctx);
358 std::unique_ptr<AST::Expr> expr = parser.parse_expr ();
359
360 rust_assert (expr != nullptr);
361
362 /*auto expr_ptr =
363 std::make_unique<AST::Expr>(AST::LiteralExpr(Literal))*/
364
365 // TODO: When we've succesfully parse an expr, remember to clone_expr()
366 // instead of nullptr
367 AST::InlineAsmOperand::Out out (reg, false, std::move (expr));
368
369 inline_asm_ctx.inline_asm.operands.emplace_back (out, locus);
370
371 return inline_asm_ctx;
372 }
373
374 return tl::unexpected<InlineAsmParseError> (NONCOMMITED);
375 }
376
377 tl::expected<InlineAsmContext, InlineAsmParseError>
378 parse_reg_operand_lateout (InlineAsmContext inline_asm_ctx)
379 {
380 auto &parser = inline_asm_ctx.parser;
381 auto token = parser.peek_current_token ();
382 if (!inline_asm_ctx.is_global_asm () && check_identifier (parser, "lateout"))
383 {
384 rust_error_at (token->get_locus (),
385 "The lateout feature is not implemented");
386 rust_unreachable ();
387 return tl::unexpected<InlineAsmParseError> (COMMITTED);
388 }
389
390 return tl::unexpected<InlineAsmParseError> (NONCOMMITED);
391 }
392
393 tl::expected<InlineAsmContext, InlineAsmParseError>
394 parse_reg_operand_inout (InlineAsmContext inline_asm_ctx)
395 {
396 auto &parser = inline_asm_ctx.parser;
397 auto token = parser.peek_current_token ();
398
399 if (!inline_asm_ctx.is_global_asm () && check_identifier (parser, "inout"))
400 {
401 auto reg = parse_reg (inline_asm_ctx);
402
403 if (parser.skip_token (UNDERSCORE))
404 {
405 // We are sure to be failing a test here, based on asm.rs
406 // https://github.com/rust-lang/rust/blob/a330e49593ee890f9197727a3a558b6e6b37f843/compiler/rustc_builtin_macros/src/asm.rs#L112
407 rust_error_at (token->get_locus (),
408 "The lateout feature is not implemented");
409 rust_unreachable ();
410 return tl::unexpected<InlineAsmParseError> (COMMITTED);
411 }
412
413 // TODO: Is error propogation our top priority, the ? in rust's asm.rs is
414 // doing a lot of work.
415 // TODO: Not sure how to use parse_expr
416 if (!check_identifier (parser, ""))
417 rust_unreachable ();
418 // auto expr = parse_format_string (inline_asm_ctx);
419
420 std::unique_ptr<AST::Expr> out_expr;
421
422 if (parser.skip_token (MATCH_ARROW))
423 {
424 if (!parser.skip_token (UNDERSCORE))
425 {
426 // auto result = parse_format_string (inline_asm_ctx);
427
428 if (!check_identifier (parser, ""))
429 rust_unreachable ();
430 // out_expr = parser.parse_expr();
431 }
432
433 // TODO: Rembmer to pass in clone_expr() instead of nullptr
434 // https://github.com/rust-lang/rust/blob/a3167859f2fd8ff2241295469876a2b687280bdc/compiler/rustc_builtin_macros/src/asm.rs#L135
435 // RUST VERSION: ast::InlineAsmOperand::SplitInOut { reg, in_expr:
436 // expr, out_expr, late: false }
437 // struct AST::InlineAsmOperand::SplitInOut split_in_out (reg,
438 // false, nullptr,
439 // nullptr);
440 // inline_asm_ctx.inline_asm.operands.push_back (split_in_out);
441
442 return inline_asm_ctx;
443 }
444 else
445 {
446 // https://github.com/rust-lang/rust/blob/a3167859f2fd8ff2241295469876a2b687280bdc/compiler/rustc_builtin_macros/src/asm.rs#L137
447 // RUST VERSION: ast::InlineAsmOperand::InOut { reg, expr, late: false
448 // }
449 // struct AST::InlineAsmOperand::InOut inout (reg, false,
450 // nullptr);
451 // inline_asm_ctx.inline_asm.operands.push_back (inout);
452 return inline_asm_ctx;
453 }
454 }
455
456 return tl::unexpected<InlineAsmParseError> (NONCOMMITED);
457 }
458
459 tl::expected<InlineAsmContext, InlineAsmParseError>
460 parse_reg_operand_const (InlineAsmContext inline_asm_ctx)
461 {
462 auto &parser = inline_asm_ctx.parser;
463 if (parser.peek_current_token ()->get_id () == CONST)
464 {
465 // TODO: Please handle const with parse_expr instead.
466 auto anon_const = parse_format_string (inline_asm_ctx);
467 rust_unreachable ();
468 return tl::unexpected<InlineAsmParseError> (COMMITTED);
469 }
470
471 return tl::unexpected<InlineAsmParseError> (NONCOMMITED);
472 }
473
474 tl::expected<InlineAsmContext, InlineAsmParseError>
475 parse_reg_operand_sym (InlineAsmContext inline_asm_ctx)
476 {
477 auto &parser = inline_asm_ctx.parser;
478
479 if (check_identifier (parser, "sym"))
480 {
481 // TODO: Please handle sym, which needs ExprKind::Path in Rust's asm.rs
482 rust_unreachable ();
483 return tl::unexpected<InlineAsmParseError> (COMMITTED);
484 }
485 return tl::unexpected<InlineAsmParseError> (NONCOMMITED);
486 }
487
488 tl::expected<InlineAsmContext, InlineAsmParseError>
489 parse_reg_operand_unexpected (InlineAsmContext inline_asm_ctx)
490 {
491 auto token = inline_asm_ctx.parser.peek_current_token ();
492 // TODO: It is weird that we can't seem to match any identifier,
493 // something must be wrong. consult compiler code in asm.rs or rust online
494 // compiler.
495 // rust_unreachable ();
496
497 // rust_error_at (token->get_locus (), "ERROR RIGHT HERE");
498 return tl::unexpected<InlineAsmParseError> (COMMITTED);
499 }
500
501 void
502 check_and_set (InlineAsmContext &inline_asm_ctx, AST::InlineAsmOption option)
503 {
504 auto &parser = inline_asm_ctx.parser;
505 auto &inline_asm = inline_asm_ctx.inline_asm;
506 if (inline_asm.options.count (option) != 0)
507 {
508 // TODO: report an error of duplication
509 rust_error_at (parser.peek_current_token ()->get_locus (),
510 "the %qs option was already provided",
511 InlineAsmOptionMap[option].c_str ());
512 return;
513 }
514 else
515 {
516 inline_asm.options.insert (option);
517 }
518 }
519 tl::expected<InlineAsmContext, InlineAsmParseError>
520 parse_options (InlineAsmContext &inline_asm_ctx)
521 {
522 auto &parser = inline_asm_ctx.parser;
523 bool is_global_asm = inline_asm_ctx.inline_asm.is_global_asm;
524 // Parse everything commitedly
525 if (!parser.skip_token (LEFT_PAREN))
526 {
527 auto local_token = parser.peek_current_token ();
528 rust_error_at (local_token->get_locus (), "expected %qs, found %qs", "(",
529 local_token->as_string ().c_str ());
530 return tl::unexpected<InlineAsmParseError> (COMMITTED);
531 }
532
533 auto token = parser.peek_current_token ();
534 while (!parser.skip_token (RIGHT_PAREN))
535 {
536 if (!is_global_asm && check_identifier (parser, "pure"))
537 {
538 check_and_set (inline_asm_ctx, AST::InlineAsmOption::PURE);
539 }
540 else if (!is_global_asm && check_identifier (parser, "nomem"))
541 {
542 check_and_set (inline_asm_ctx, AST::InlineAsmOption::NOMEM);
543 }
544 else if (!is_global_asm && check_identifier (parser, "readonly"))
545 {
546 check_and_set (inline_asm_ctx, AST::InlineAsmOption::READONLY);
547 }
548 else if (!is_global_asm && check_identifier (parser, "preserves_flags"))
549 {
550 check_and_set (inline_asm_ctx, AST::InlineAsmOption::PRESERVES_FLAGS);
551 }
552 else if (!is_global_asm && check_identifier (parser, "noreturn"))
553 {
554 check_and_set (inline_asm_ctx, AST::InlineAsmOption::NORETURN);
555 }
556 else if (!is_global_asm && check_identifier (parser, "nostack"))
557 {
558 check_and_set (inline_asm_ctx, AST::InlineAsmOption::NOSTACK);
559 }
560 else if (!is_global_asm && check_identifier (parser, "may_unwind"))
561 {
562 check_and_set (inline_asm_ctx, AST::InlineAsmOption::MAY_UNWIND);
563 }
564 else if (check_identifier (parser, "att_syntax"))
565 {
566 check_and_set (inline_asm_ctx, AST::InlineAsmOption::ATT_SYNTAX);
567 }
568 else if (check_identifier (parser, "raw"))
569 {
570 check_and_set (inline_asm_ctx, AST::InlineAsmOption::RAW);
571 }
572 else
573 {
574 rust_error_at (token->get_locus (),
575 "expected one of %qs, %qs, %qs, %qs, %qs, %qs, %qs, "
576 "%qs, %qs, or %qs, found %qs",
577 ")", "att_syntax", "may_unwind", "nomem", "noreturn",
578 "nostack", "preserves_flags", "pure", "raw",
579 "readonly", token->as_string ().c_str ());
580 return tl::unexpected<InlineAsmParseError> (COMMITTED);
581 }
582 if (parser.skip_token (RIGHT_PAREN))
583 {
584 break;
585 }
586
587 // Parse comma as optional
588 if (parser.skip_token (COMMA))
589 continue;
590 else
591 {
592 rust_unreachable ();
593 token = parser.peek_current_token ();
594 return tl::unexpected<InlineAsmParseError> (COMMITTED);
595 }
596 }
597
598 // TODO: Per rust asm.rs regarding options_spans
599 // I'm guessing this has to do with some error reporting.
600 // let new_span = span_start.to(p.prev_token.span);
601 // args.options_spans.push(new_span);
602
603 return inline_asm_ctx;
604 }
605
606 bool
607 check_identifier (Parser<MacroInvocLexer> &p, std::string ident)
608 {
609 auto token = p.peek_current_token ();
610
611 if (token->get_id () == IDENTIFIER)
612 {
613 auto str = token->as_string ();
614
615 // For non-promoted keywords, we need to also check for them.
616
617 if (str == ident)
618 {
619 p.skip_token ();
620 return true;
621 }
622 if (ident == "")
623 {
624 if (potentially_nonpromoted_keywords.find (str)
625 == potentially_nonpromoted_keywords.end ())
626 {
627 p.skip_token ();
628 return true;
629 }
630 return false;
631 }
632 }
633
634 return false;
635 }
636
637 tl::optional<std::string>
638 parse_format_string (InlineAsmContext &inline_asm_ctx)
639 {
640 auto &parser = inline_asm_ctx.parser;
641 auto last_token_id = inline_asm_ctx.last_token_id;
642 auto token = parser.peek_current_token ();
643
644 if (token->get_id () != last_token_id && token->get_id () == STRING_LITERAL)
645 {
646 // very nice, we got a supposedly formatted string.
647 parser.skip_token ();
648 return token->as_string ();
649 }
650 else
651 {
652 return tl::nullopt;
653 }
654 }
655
656 tl::optional<AST::Fragment>
657 MacroBuiltin::asm_handler (location_t invoc_locus, AST::MacroInvocData &invoc,
658 AST::InvocKind semicolon, AST::AsmKind is_global_asm)
659 {
660 return parse_asm (invoc_locus, invoc, semicolon, is_global_asm);
661 }
662
663 tl::expected<InlineAsmContext, InlineAsmParseError>
664 parse_asm_arg (InlineAsmContext inline_asm_ctx)
665 {
666 auto &parser = inline_asm_ctx.parser;
667 auto last_token_id = inline_asm_ctx.last_token_id;
668 auto token = parser.peek_current_token ();
669 tl::optional<std::string> fm_string;
670 while (token->get_id () != last_token_id)
671 {
672 token = parser.peek_current_token ();
673
674 // We accept a comma token here.
675 if (token->get_id () != COMMA
676 && inline_asm_ctx.consumed_comma_without_formatted_string)
677 {
678 // if it is not a comma, but we consumed it previously, this is fine
679 // but we have to set it to false tho.
680 inline_asm_ctx.consumed_comma_without_formatted_string = false;
681 }
682 else if (token->get_id () == COMMA
683 && !inline_asm_ctx.consumed_comma_without_formatted_string)
684 {
685 inline_asm_ctx.consumed_comma_without_formatted_string = false;
686 parser.skip_token ();
687 }
688 else if (token->get_id () == COMMA
689 && inline_asm_ctx.consumed_comma_without_formatted_string)
690 {
691 // We consumed comma, and there happens to also be a comma
692 // error should be: expected expression, found `,`
693 rust_error_at (token->get_locus (), "expected expression, found %qs",
694 ",");
695 return tl::unexpected<InlineAsmParseError> (COMMITTED);
696 break;
697 }
698
699 // And if that token comma is also the trailing comma, we break
700 token = parser.peek_current_token ();
701 if (token->get_id () == COMMA && token->get_id () == last_token_id)
702 {
703 parser.skip_token ();
704 break;
705 }
706
707 // Ok after the left paren is good, we better be parsing correctly
708 // everything in here, which is operand in ABNF
709
710 // Parse clobber abi, eat the identifier named "clobber_abi" if true
711 if (check_identifier (parser, "clobber_abi"))
712 {
713 auto expected = parse_clobber_abi (inline_asm_ctx);
714 if (expected.has_value ())
715 continue;
716 else if (expected.error () == COMMITTED)
717 return expected;
718
719 // The error type is definitely non-committed (we have checked above),
720 // we are allowed to keep on parsing
721 }
722
723 if (check_identifier (parser, "options"))
724 {
725 auto expected = parse_options (inline_asm_ctx);
726 if (expected.has_value ())
727 continue;
728 else if (expected.error () == COMMITTED)
729 return expected;
730
731 // The error type is definitely non-committed (we have checked above),
732 // we are allowed to keep on parsing
733 }
734
735 // Ok after we have check that neither clobber_abi nor options works, the
736 // only other logical choice is reg_operand
737
738 auto expected = parse_reg_operand (inline_asm_ctx);
739 if (expected.has_value ())
740 continue;
741 else if (expected.error () == COMMITTED)
742 return expected;
743
744 // Since parse_reg_operand is the last thing we've considered,
745 // The non-committed parse error type means that we have exhausted our
746 // search path
747
748 // We then should return the error of COMMITTED, even though we have not
749 // committed to anything So that the error bubbles up and we recover from
750 // this error gracefully
751 rust_error_at (token->get_locus (),
752 "expected operand, %s, options, or additional "
753 "template string",
754 "clobber_abi");
755 return tl::unexpected<InlineAsmParseError> (COMMITTED);
756 }
757 return tl::expected<InlineAsmContext, InlineAsmParseError> (inline_asm_ctx);
758 }
759
760 tl::expected<InlineAsmContext, InlineAsmParseError>
761 expand_inline_asm_strings (InlineAsmContext inline_asm_ctx)
762 {
763 auto &inline_asm = inline_asm_ctx.inline_asm;
764
765 auto str_vec = inline_asm.get_template_strs ();
766
767 decltype (str_vec) resulting_template_vec;
768 for (auto &template_str : str_vec)
769 {
770 /*std::cout << template_str.symbol << std::endl;*/
771
772 auto pieces = Fmt::Pieces::collect (template_str.symbol, false,
773 Fmt::ffi::ParseMode::InlineAsm);
774 auto pieces_vec = pieces.get_pieces ();
775
776 std::string transformed_template_str = "";
777 for (size_t i = 0; i < pieces_vec.size (); i++)
778 {
779 auto piece = pieces_vec[i];
780 if (piece.tag == Fmt::ffi::Piece::Tag::String)
781 {
782 transformed_template_str += piece.string._0.to_string ();
783 }
784 else if (piece.tag == Fmt::ffi::Piece::Tag::NextArgument)
785 {
786 /* std::cout << " " << i << ": "*/
787 /*<< piece.next_argument._0.to_string () << std::endl;*/
788
789 auto next_argument = piece.next_argument._0;
790 switch (piece.next_argument._0.position.tag)
791 {
792 case Fmt::ffi::Position::Tag::ArgumentImplicitlyIs: {
793 auto idx = next_argument.position.argument_implicitly_is._0;
794 /*auto trait = next_argument.format;*/
795 /*auto arg = arguments.at (idx);*/
796
797 /* // FIXME(Arthur): This API sucks*/
798 /* rust_assert (arg.get_kind ().kind*/
799 /*== AST::FormatArgumentKind::Kind::Normal);*/
800 /**/
801 /* args.push_back ({arg.get_expr ().clone_expr (),
802 * trait});*/
803
804 transformed_template_str += "%" + std::to_string (idx);
805 // std::cout << "argument implicitly is: " << idx <<
806 // std::endl; std::cout << "transformed template str is:"
807 // << transformed_template_str << std::endl;
808 /*std::cout << "trait: " << trait.to_string () <<
809 * std::endl;*/
810 /*std::cout << "arg: " << arg.to_string () << std::endl;*/
811 }
812 break;
813 case Fmt::ffi::Position::Tag::ArgumentIs:
814 case Fmt::ffi::Position::Tag::ArgumentNamed:
815 rust_sorry_at (inline_asm.get_locus (),
816 "unhandled argument position specifier");
817 break;
818 }
819 }
820 }
821 template_str.symbol = transformed_template_str;
822 }
823
824 inline_asm.template_strs = str_vec;
825 return inline_asm_ctx;
826 }
827
828 tl::optional<AST::Fragment>
829 parse_asm (location_t invoc_locus, AST::MacroInvocData &invoc,
830 AST::InvocKind semicolon, AST::AsmKind is_global_asm)
831 {
832 // From the rule of asm.
833 // We first parse all formatted strings. If we fail, then we return
834 // tl::nullopt
835
836 // We then parse the asm arguments. If we fail, then we return
837 // tl::nullopt
838
839 // We then validate. If we fail, then we return tl::nullopt
840
841 // Done
842 MacroInvocLexer lex (invoc.get_delim_tok_tree ().to_token_stream ());
843 Parser<MacroInvocLexer> parser (lex);
844 auto last_token_id = macro_end_token (invoc.get_delim_tok_tree (), parser);
845
846 AST::InlineAsm inline_asm (invoc_locus,
847 is_global_asm == AST::AsmKind::Global);
848 auto inline_asm_ctx = InlineAsmContext (inline_asm, parser, last_token_id);
849
850 auto resulting_context = parse_format_strings (inline_asm_ctx)
851 .and_then (parse_asm_arg)
852 .and_then (validate)
853 .and_then (expand_inline_asm_strings);
854
855 // TODO: I'm putting the validation here because the rust reference put
856 // it here Per Arthur's advice we would actually do the validation in a
857 // different stage. and visit on the InlineAsm AST instead of it's
858 // context.
859 if (resulting_context)
860 {
861 auto node = (*resulting_context).inline_asm.clone_expr_without_block ();
862
863 std::vector<AST::SingleASTNode> single_vec = {};
864
865 // If the macro invocation has a semicolon (`asm!("...");`), then we
866 // need to make it a statement. This way, it will be expanded
867 // properly.
868 if (semicolon == AST::InvocKind::Semicoloned)
869 single_vec.emplace_back (AST::SingleASTNode (
870 std::make_unique<AST::ExprStmt> (std::move (node), invoc_locus,
871 semicolon
872 == AST::InvocKind::Semicoloned)));
873 else
874 single_vec.emplace_back (AST::SingleASTNode (std::move (node)));
875
876 AST::Fragment fragment_ast
877 = AST::Fragment (single_vec,
878 std::vector<std::unique_ptr<AST::Token>> ());
879 return fragment_ast;
880 }
881 else
882 {
883 return tl::nullopt;
884 }
885 }
886
887 tl::expected<InlineAsmContext, InlineAsmParseError>
888 parse_format_strings (InlineAsmContext inline_asm_ctx)
889 {
890 // Parse the first ever formatted string, success or not, will skip 1
891 // token
892 auto &parser = inline_asm_ctx.parser;
893 auto last_token_id = inline_asm_ctx.last_token_id;
894 auto fm_string = parse_format_string (inline_asm_ctx);
895
896 auto &inline_asm = inline_asm_ctx.inline_asm;
897 auto token = parser.peek_current_token ();
898 if (fm_string == tl::nullopt)
899 {
900 rust_error_at (parser.peek_current_token ()->get_locus (),
901 "%s template must be a string literal", "asm");
902 return tl::unexpected<InlineAsmParseError> (COMMITTED);
903 }
904 else
905 {
906 auto template_str
907 = AST::TupleTemplateStr (token->get_locus (),
908 strip_double_quotes (fm_string.value ()));
909 inline_asm.template_strs.push_back (template_str);
910 }
911
912 // formatted string stream
913
914 while (parser.peek_current_token ()->get_id () != last_token_id)
915 {
916 if (!parser.skip_token (COMMA))
917 {
918 break;
919 }
920 // Ok after the comma is good, we better be parsing correctly
921 // everything in here, which is formatted string in ABNF
922 inline_asm_ctx.consumed_comma_without_formatted_string = false;
923
924 token = parser.peek_current_token ();
925 fm_string = parse_format_string (inline_asm_ctx);
926 if (fm_string == tl::nullopt)
927 {
928 inline_asm_ctx.consumed_comma_without_formatted_string = true;
929 break;
930 }
931 else
932 {
933 auto template_str
934 = AST::TupleTemplateStr (token->get_locus (),
935 strip_double_quotes (fm_string.value ()));
936 inline_asm.template_strs.push_back (template_str);
937 }
938 }
939
940 return inline_asm_ctx;
941 }
942
943 // bool
944 // is_label (const std::string &potential_label)
945 // {
946
947 // if (potential_label.empty () || potential_label.back () != ':')
948 // return false;
949
950 // // Check if all characters before the last colon are digits
951 // for (size_t i = 0; i < potential_label.length () - 1; i++)
952 // {
953 // if (potential_label[i] < '0' || potential_label[i] > '9')
954 // return false;
955 // }
956
957 // return true;
958 // }
959
960 tl::expected<InlineAsmContext, InlineAsmParseError>
961 validate (InlineAsmContext inline_asm_ctx)
962 {
963 return tl::expected<InlineAsmContext, InlineAsmParseError> (inline_asm_ctx);
964 }
965 } // namespace Rust