1use offlineasm_backend::backends::{is_backend, Backend};
64use offlineasm_backend::driver::{
65 compile_all_configurations_file, compile_all_configurations_tokens, compile_file,
66 compile_tokens, CompileOptions, ConfiguredAsm, MACHO,
67};
68use offlineasm_backend::parser::{parse_file, parse_tokens, ParseSession, ParserOptions};
69use offlineasm_backend::settings::non_backend_settings;
70use proc_macro::TokenStream;
71use proc_macro2::{Span, TokenStream as TokenStream2};
72use quote::{quote, ToTokens};
73use std::collections::BTreeMap;
74use std::path::PathBuf;
75use std::sync::atomic::{AtomicUsize, Ordering};
76use syn::parse::{Parse, ParseStream};
77use syn::{braced, Ident, LitBool, LitStr, Meta, Token};
78
79static CHECK_MACRO_UID: AtomicUsize = AtomicUsize::new(0);
80
81enum Body {
82 Path(LitStr),
83 Inline(TokenStream2),
84}
85
86impl Body {
87 fn parse(input: ParseStream) -> syn::Result<Self> {
88 if input.peek(LitStr) {
89 let fork = input.fork();
90 let _: LitStr = fork.parse()?;
91 if fork.is_empty() {
92 return Ok(Body::Path(input.parse()?));
93 }
94 }
95 Ok(Body::Inline(input.parse()?))
96 }
97
98 fn tokens(&self) -> TokenStream2 {
99 match self {
100 Body::Path(lit) => lit.to_token_stream(),
101 Body::Inline(tokens) => tokens.clone(),
102 }
103 }
104}
105
106struct MacroInput {
107 settings: Vec<(Ident, Meta)>,
108 body: Body,
109}
110
111impl Parse for MacroInput {
112 fn parse(input: ParseStream) -> syn::Result<Self> {
113 let mut settings = Vec::new();
114 if input.peek(Ident) {
115 let fork = input.fork();
116 let keyword: Ident = fork.parse()?;
117 if keyword == "settings" && fork.peek(syn::token::Brace) {
118 let _: Ident = input.parse()?;
119 let content;
120 braced!(content in input);
121 while !content.is_empty() {
122 let name: Ident = content.parse()?;
123 let _: Token![=] = content.parse()?;
124 let predicate: Meta = content.parse()?;
125 settings.push((name, predicate));
126 if content.peek(Token![,]) {
127 let _: Token![,] = content.parse()?;
128 }
129 }
130 }
131 }
132 let body = Body::parse(input)?;
133 Ok(MacroInput { settings, body })
134 }
135}
136struct InnerInput {
137 include_dir: bool,
138 settings: Vec<(Ident, bool)>,
139 body: Body,
140}
141
142impl Parse for InnerInput {
143 fn parse(input: ParseStream) -> syn::Result<Self> {
144 let flag: Ident = input.parse()?;
145 let include_dir = match flag.to_string().as_str() {
146 "include" => true,
147 "no_include" => false,
148 other => {
149 return Err(syn::Error::new(
150 flag.span(),
151 format!("expected `include` or `no_include`, found `{}`", other),
152 ))
153 }
154 };
155 let keyword: Ident = input.parse()?;
156 if keyword != "settings" {
157 return Err(syn::Error::new(keyword.span(), "expected `settings`"));
158 }
159 let content;
160 braced!(content in input);
161 let mut settings = Vec::new();
162 while !content.is_empty() {
163 let name: Ident = content.parse()?;
164 let _: Token![=] = content.parse()?;
165 let value: LitBool = content.parse()?;
166 settings.push((name, value.value));
167 if content.peek(Token![,]) {
168 let _: Token![,] = content.parse()?;
169 }
170 }
171 let body = Body::parse(input)?;
172 Ok(InnerInput {
173 include_dir,
174 settings,
175 body,
176 })
177 }
178}
179
180fn resolve_path(lit: &str) -> PathBuf {
185 let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
186 let mut path = PathBuf::from(manifest_dir);
187 path.push(lit);
188 path
189}
190
191fn compile_error(msg: impl Into<String>) -> TokenStream2 {
192 let msg = msg.into();
193 quote! { ::core::compile_error!(#msg); }
194}
195
196fn expand_backend_shorthand(settings: Vec<(Ident, Meta)>) -> Result<Vec<(Ident, Meta)>, String> {
204 let mut out: Vec<(Ident, Meta)> = Vec::new();
205 let mut native = false;
206 let mut rloop = false;
207 for (name, predicate) in settings {
208 if name == "backend" {
209 match predicate {
210 Meta::Path(path) => {
211 let keyword = path
212 .get_ident()
213 .map(|ident| ident.to_string())
214 .ok_or_else(|| "`backend` expects `native` or `rloop`".to_string())?;
215 match keyword.as_str() {
216 "native" | "auto" => native = true,
217 "rloop" | "portable" => rloop = true,
218 other => {
219 return Err(format!(
220 "unknown backend `{}` (expected `native` or `rloop`)",
221 other
222 ))
223 }
224 }
225 }
226 other => {
227 return Err(format!(
228 "`backend` expects `native` or `rloop`, found `{}`",
229 other.to_token_stream()
230 ))
231 }
232 }
233 continue;
234 }
235 out.push((name, predicate));
236 }
237 let push = |out: &mut Vec<(Ident, Meta)>, name: &str, predicate: TokenStream2| {
238 let meta: Meta = syn::parse2(quote!(#predicate)).expect("well-formed cfg predicate");
239 out.push((Ident::new(name, Span::call_site()), meta));
240 };
241 if rloop {
242 push(&mut out, "RLOOP", quote!(all()));
244 }
245 if native {
246 push(&mut out, "X86_64", quote!(target_arch = "x86_64"));
247 push(&mut out, "ARM64", quote!(target_arch = "aarch64"));
248 push(&mut out, "RISCV64", quote!(target_arch = "riscv64"));
249 }
250 if !native
251 && !rloop
252 && !out
253 .iter()
254 .any(|(name, _)| is_backend(&name.to_string().to_uppercase()))
255 {
256 return Err(
257 "no backend selected: add `backend = native` or `backend = rloop` to the settings block"
258 .to_string(),
259 );
260 }
261 Ok(out)
262}
263
264enum Source {
266 File(PathBuf),
267 Tokens {
268 tokens: TokenStream2,
269 file_name: String,
270 },
271}
272
273struct Loaded {
274 source: Source,
275 parser_options: ParserOptions,
276 describe: String,
277}
278
279impl Loaded {
280 fn parse(&self) -> syn::Result<offlineasm_backend::ast::Node> {
285 let mut session = ParseSession::new(self.parser_options.clone());
286 match &self.source {
287 Source::File(path) => parse_file(path, &mut session),
288 Source::Tokens { tokens, file_name } => {
289 parse_tokens(tokens.clone(), file_name, &mut session)
290 }
291 }
292 }
293}
294
295fn inline_file_name(tokens: &TokenStream2) -> String {
296 tokens
297 .clone()
298 .into_iter()
299 .next()
300 .map(|tt| tt.span().file())
301 .filter(|f| !f.is_empty())
302 .unwrap_or_else(|| "<inline offlineasm>".to_string())
303}
304
305fn load(body: &Body, include_dir: bool) -> Result<Loaded, String> {
306 let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
307 match body {
308 Body::Path(lit) => {
309 let path = resolve_path(&lit.value());
310 let mut parser_options = ParserOptions::default();
311 if include_dir {
312 if let Some(parent) = path.parent() {
313 parser_options
314 .include_dirs
315 .push(parent.to_string_lossy().to_string());
316 }
317 }
318 Ok(Loaded {
319 describe: format!("`{}`", path.display()),
320 source: Source::File(path),
321 parser_options,
322 })
323 }
324 Body::Inline(tokens) => {
325 if tokens.is_empty() {
326 return Err("inline offlineasm input is empty".to_string());
327 }
328 let file_name = inline_file_name(tokens);
329 let mut parser_options = ParserOptions::default();
330 if include_dir {
331 parser_options.include_dirs.push(manifest_dir);
332 }
333 Ok(Loaded {
334 describe: format!("inline offlineasm in {}", file_name),
335 source: Source::Tokens {
336 tokens: tokens.clone(),
337 file_name,
338 },
339 parser_options,
340 })
341 }
342 }
343}
344
345fn split_by_object_format(
349 elf: Vec<ConfiguredAsm>,
350 macho: Vec<ConfiguredAsm>,
351) -> Vec<ConfiguredAsm> {
352 let mut out = Vec::with_capacity(elf.len() * 2);
353 for (mut elf, mut macho) in elf.into_iter().zip(macho) {
354 if elf.backend == Backend::RLoop {
355 out.push(elf);
356 continue;
357 }
358 macho.cfg_predicate = format!("all({}, target_vendor = \"apple\")", macho.cfg_predicate);
359 elf.cfg_predicate = format!("all({}, not(target_vendor = \"apple\"))", elf.cfg_predicate);
360 out.push(elf);
361 out.push(macho);
362 }
363 out
364}
365
366fn expand_all(body: &Body, include_dir: bool) -> TokenStream2 {
369 let loaded = match load(body, include_dir) {
370 Ok(loaded) => loaded,
371 Err(e) => return compile_error(format!("offlineasm!: {}", e)),
372 };
373 if let Err(e) = loaded.parse() {
378 return e.to_compile_error();
379 }
380 let compile = |binary_format: Option<String>| {
381 let options = CompileOptions {
382 binary_format,
383 ..CompileOptions::default().with_auto_rust_offsets(true)
384 };
385 match &loaded.source {
386 Source::File(path) => {
387 compile_all_configurations_file(path, &options, &loaded.parser_options)
388 }
389 Source::Tokens { tokens, file_name } => compile_all_configurations_tokens(
390 tokens.clone(),
391 file_name,
392 &options,
393 &loaded.parser_options,
394 ),
395 }
396 };
397 let configured = compile(None).and_then(|elf| Ok((elf, compile(Some(MACHO.to_string()))?)));
398 let configured = match configured {
399 Ok((elf, macho)) => split_by_object_format(elf, macho),
400 Err(e) => {
401 return compile_error(format!(
402 "offlineasm!: failed to compile {}: {}",
403 loaded.describe, e
404 ))
405 }
406 };
407 if configured.is_empty() {
408 return compile_error(format!(
409 "offlineasm!: {} produced no valid (working-backend, non-erroneous) settings configuration",
410 loaded.describe
411 ));
412 }
413 emit_items(&configured, &loaded.describe, true)
414}
415
416const MACHO_SETTING: &str = "__offlineasm_macho";
419
420fn compile_selected(loaded: &Loaded, settings: &[(Ident, bool)]) -> Result<ConfiguredAsm, String> {
422 let mut backend: Option<Backend> = None;
423 let mut requested: BTreeMap<String, bool> = BTreeMap::new();
424 let mut macho = false;
425 for (name, value) in settings {
426 if name == MACHO_SETTING {
427 macho = *value;
428 continue;
429 }
430 let name = name.to_string().to_uppercase();
432 if is_backend(&name) {
433 if *value {
434 let parsed = Backend::parse(&name)?;
435 if let Some(existing) = backend {
436 return Err(format!(
437 "multiple backends selected ({} and {}); exactly one backend setting must resolve to true",
438 existing.name(),
439 parsed.name()
440 ));
441 }
442 backend = Some(parsed);
443 }
444 } else {
445 requested.insert(name, *value);
446 }
447 }
448 let backend = backend.ok_or_else(|| {
449 "no backend setting resolved to true: add e.g. `X86_64 = target_arch = \"x86_64\"` to the settings block"
450 .to_string()
451 })?;
452
453 let ast = loaded.parse().map_err(|e| e.to_string())?;
454 let mut settings_overrides = std::collections::HashMap::new();
455 for name in non_backend_settings(&ast) {
456 let value = requested.get(&name).copied().unwrap_or(false);
457 settings_overrides.insert(name, value);
458 }
459
460 let options = CompileOptions {
461 backend: Some(backend),
462 settings_overrides,
463 binary_format: macho.then(|| MACHO.to_string()),
464 ..CompileOptions::default().with_auto_rust_offsets(true)
465 };
466 let compiled = match &loaded.source {
467 Source::File(path) => compile_file(path, &options, &loaded.parser_options),
468 Source::Tokens { tokens, file_name } => {
469 compile_tokens(tokens.clone(), file_name, &options, &loaded.parser_options)
470 }
471 }
472 .map_err(|e| format!("failed to compile {}: {}", loaded.describe, e))?;
473
474 let mut settings = std::collections::HashMap::new();
475 settings.insert(backend.name().to_string(), true);
476 for (name, value) in requested {
477 settings.insert(name, value);
478 }
479 Ok(ConfiguredAsm {
480 cfg_predicate: String::new(),
481 settings,
482 backend,
483 compiled,
484 })
485}
486
487fn expand_settings_chain(
496 settings: &[(Ident, Meta)],
497 body: &Body,
498 include_dir: bool,
499) -> TokenStream2 {
500 let mut sorted: Vec<&(Ident, Meta)> = settings.iter().collect();
501 sorted.sort_by_key(|(name, _)| name.to_string());
502 for pair in sorted.windows(2) {
503 if pair[0].0 == pair[1].0 {
504 return compile_error(format!("offlineasm!: setting `{}` listed twice", pair[0].0));
505 }
506 }
507
508 let uid = CHECK_MACRO_UID.fetch_add(1, Ordering::Relaxed);
509 let include_flag = if include_dir {
510 quote!(include)
511 } else {
512 quote!(no_include)
513 };
514 let mut next: TokenStream2 = quote!(::offlineasm::__offlineasm_inner);
515
516 let mut definitions = TokenStream2::new();
517 for (name, predicate) in sorted.iter().rev() {
518 let check = Ident::new(
519 &format!("__offlineasm_check_{}_{}", uid, name),
520 Span::call_site(),
521 );
522 let define = |value: bool, condition: TokenStream2| {
523 quote! {
524 #[cfg(#condition)]
525 #[allow(unused_macros)]
526 macro_rules! #check {
527 ( $flag:ident settings { $($acc:tt)* } $($args:tt)* ) => {
528 #next!( $flag settings { $($acc)* #name = #value } $($args)* );
529 };
530 }
531 }
532 };
533 definitions.extend(define(true, quote!(#predicate)));
534 definitions.extend(define(false, quote!(not(#predicate))));
535 next = quote!(#check);
536 }
537
538 let first = next;
539 let body_tokens = body.tokens();
540 let mut out = definitions;
541 out.extend(quote! { #first!( #include_flag settings { } #body_tokens ); });
542
543 out
544}
545
546fn emit_items(configured: &[ConfiguredAsm], describe: &str, guarded: bool) -> TokenStream2 {
548 let mut items = Vec::with_capacity(configured.len());
549 for (index, cfg) in configured.iter().enumerate() {
550 let predicate_tokens: TokenStream2 = if guarded {
551 match syn::parse_str(&cfg.cfg_predicate) {
552 Ok(t) => t,
553 Err(e) => {
554 items.push(compile_error(format!(
555 "offlineasm!: internal error: bad cfg predicate `{}`: {}",
556 cfg.cfg_predicate, e
557 )));
558 continue;
559 }
560 }
561 } else {
562 TokenStream2::new()
563 };
564 let guard = |item: TokenStream2| {
565 if guarded {
566 quote! {
567 #[cfg(#predicate_tokens)]
568 #item
569 }
570 } else {
571 item
572 }
573 };
574
575 if cfg.backend == Backend::RLoop {
576 let mod_ident = Ident::new(
577 &format!("offlineasm_rloop_config_{}", index),
578 Span::call_site(),
579 );
580 let rust_src = cfg.compiled.rust_lines.join("\n");
581 let body: TokenStream2 = match syn::parse_str(&rust_src) {
582 Ok(t) => t,
583 Err(e) => {
584 items.push(compile_error(format!(
585 "offlineasm!: RLoop output for {} (config {}) failed to parse as Rust: {}",
586 describe, index, e
587 )));
588 continue;
589 }
590 };
591 items.push(guard(quote! {
595 mod #mod_ident {
596 #[allow(unused_imports)]
599 use super::*;
600 #body
601 }
602 }));
603 } else {
604 let template = &cfg.compiled.template;
605 let mut const_arg_tokens = Vec::with_capacity(cfg.compiled.const_args.len());
606 let mut bad = false;
607 for (ident, expr) in &cfg.compiled.const_args {
608 let ident = Ident::new(ident, Span::call_site());
609 let expr_tokens: TokenStream2 = match syn::parse_str(expr) {
610 Ok(t) => t,
611 Err(e) => {
612 items.push(compile_error(format!(
613 "offlineasm!: bad const expr `{}` for {}: {}",
614 expr, describe, e
615 )));
616 bad = true;
617 break;
618 }
619 };
620 const_arg_tokens.push(quote! { , #ident = const #expr_tokens });
621 }
622 if bad {
623 continue;
624 }
625 let options = if cfg.backend == Backend::X86_64 {
629 quote! { , options(att_syntax) }
630 } else {
631 quote! {}
632 };
633 items.push(guard(quote! {
634 ::std::arch::global_asm!(#template #(#const_arg_tokens)* #options);
635 }));
636 }
637 }
638 quote! { #(#items)* }
639}
640
641fn expand(input: TokenStream, include_dir: bool) -> TokenStream {
643 let parsed = match syn::parse::<MacroInput>(input) {
644 Ok(parsed) => parsed,
645 Err(e) => return e.to_compile_error().into(),
646 };
647 if parsed.settings.is_empty() {
648 return expand_all(&parsed.body, include_dir).into();
649 }
650 let mut settings = match expand_backend_shorthand(parsed.settings) {
651 Ok(settings) => settings,
652 Err(e) => return compile_error(format!("offlineasm!: {}", e)).into(),
653 };
654 settings.push((
657 Ident::new(MACHO_SETTING, Span::call_site()),
658 syn::parse_quote!(target_vendor = "apple"),
659 ));
660 expand_settings_chain(&settings, &parsed.body, include_dir).into()
661}
662
663#[proc_macro]
669pub fn offlineasm(input: TokenStream) -> TokenStream {
670 expand(input, false)
671}
672
673#[proc_macro]
675pub fn offlineasm_include(input: TokenStream) -> TokenStream {
676 expand(input, true)
677}
678
679#[proc_macro]
680#[doc(hidden)]
681pub fn offlineasm_inner(input: TokenStream) -> TokenStream {
682 let parsed = match syn::parse::<InnerInput>(input) {
683 Ok(parsed) => parsed,
684 Err(e) => return e.to_compile_error().into(),
685 };
686 let loaded = match load(&parsed.body, parsed.include_dir) {
687 Ok(loaded) => loaded,
688 Err(e) => return compile_error(e).into(),
689 };
690
691 if let Err(e) = loaded.parse() {
692 return e.to_compile_error().into();
693 }
694 match compile_selected(&loaded, &parsed.settings) {
695 Ok(configured) => emit_items(&[configured], &loaded.describe, false).into(),
696 Err(e) => compile_error(e).into(),
697 }
698}