Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 38 additions & 58 deletions compiler/rustc_builtin_macros/src/autodiff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
//! configs (autodiff enabled or disabled), so we have to add cfg's to each import.

use std::str::FromStr;
use std::string::String;

use rustc_ast::expand::autodiff_attrs::{
DiffActivity, DiffMode, valid_input_activity, valid_ret_activity, valid_ty_for_activity,
Expand Down Expand Up @@ -42,26 +41,6 @@ fn has_ret(ty: &FnRetTy) -> bool {
FnRetTy::Default(_) => false,
}
}
fn first_ident(x: &MetaItemInner) -> rustc_span::Ident {
if let Some(l) = x.lit() {
match l.kind {
ast::LitKind::Int(val, _) => {
// get an Ident from a lit
return rustc_span::Ident::from_str(val.get().to_string().as_str());
}
_ => {}
}
}

let segments = &x.meta_item().unwrap().path.segments;
assert!(segments.len() == 1);
segments[0].ident
}

fn name(x: &MetaItemInner) -> String {
first_ident(x).name.to_string()
}

fn width(x: &MetaItemInner) -> Option<u128> {
let lit = x.lit()?;
match lit.kind {
Expand Down Expand Up @@ -113,7 +92,15 @@ fn from_ast(
let mut activities: Vec<DiffActivity> = vec![];
let mut errors = false;
for x in &meta_item[first_activity..] {
let activity_str = name(x);
let Some(ident) = x.ident() else {
dcx.emit_err(diagnostics::AutoDiffUnknownActivity {
span: x.span(),
act: rustc_ast_pretty::pprust::meta_list_item_to_string(x),
});
errors = true;
continue;
};
let activity_str = ident.name.to_string();
let res = DiffActivity::from_str(&activity_str);
match res {
Ok(x) => activities.push(x),
Expand All @@ -132,15 +119,10 @@ fn from_ast(

// If a return type exist, we need to split the last activity,
// otherwise we return None as placeholder.
let (ret_activity, input_activity) = if has_ret {
let Some((last, rest)) = activities.split_last() else {
unreachable!(
"should not be reachable because we counted the number of activities previously"
);
};
(last, rest)
} else {
(&DiffActivity::None, activities.as_slice())
// A missing return activity is reported by the count check in `gen_enzyme_decl`.
let (ret_activity, input_activity) = match activities.split_last() {
Some((last, rest)) if has_ret => (last, rest),
_ => (&DiffActivity::None, activities.as_slice()),
};

RustcAutodiff {
Expand All @@ -153,7 +135,7 @@ fn from_ast(

fn meta_item_inner_to_ts(t: &MetaItemInner, ts: &mut Vec<TokenTree>) {
let comma = Token::new(TokenKind::Comma, Span::default());
let val = first_ident(t);
let val = t.ident().expect("activities are validated in `from_ast`");
let t = Token::from_ast_ident(val);
ts.push(TokenTree::Token(t, Spacing::Joint));
ts.push(TokenTree::Token(comma, Spacing::Alone));
Expand Down Expand Up @@ -255,6 +237,18 @@ fn expand_with_mode(
return vec![item];
}

let Some(d_ident) = meta_item_vec[0].ident() else {
dcx.emit_err(diagnostics::AutoDiffInvalidName { span: meta_item_vec[0].span() });
return vec![item];
};

let x = from_ast(ecx, &meta_item_vec, has_ret, mode);
if !x.is_active() {
// We encountered an error, so we return the original item.
// This allows us to potentially parse other attributes.
return vec![item];
}

let mode_symbol = match mode {
DiffMode::Forward => sym::Forward,
DiffMode::Reverse => sym::Reverse,
Expand Down Expand Up @@ -302,32 +296,18 @@ fn expand_with_mode(
ts.pop();
let ts = TokenStream::from_iter(ts);

let x = from_ast(ecx, &meta_item_vec, has_ret, mode);
if !x.is_active() {
// We encountered an error, so we return the original item.
// This allows us to potentially parse other attributes.
return vec![item];
}
let span = ecx.with_def_site_ctxt(expand_span);

let d_sig = gen_enzyme_decl(ecx, &sig, &x, span);
let Some(d_sig) = gen_enzyme_decl(ecx, &sig, &x, span) else {
return vec![item];
};

let d_body = ecx.block(
span,
thin_vec![call_autodiff(
ecx,
primal,
first_ident(&meta_item_vec[0]),
span,
&sig,
&d_sig,
&generics,
is_impl,
)],
thin_vec![call_autodiff(ecx, primal, d_ident, span, &sig, &d_sig, &generics, is_impl)],
);

// The first element of it is the name of the function to be generated
let d_fn = ecx.item_fn(d_sig, first_ident(&meta_item_vec[0]), generics, Some(d_body));
let d_fn = ecx.item_fn(d_sig, d_ident, generics, Some(d_body));
let mut rustc_ad_attr =
Box::new(ast::NormalAttr::from_ident(Ident::with_dummy_span(sym::rustc_autodiff)));

Expand Down Expand Up @@ -588,16 +568,17 @@ fn gen_turbofish_expr(
// Each argument of the primal function (and the return type if existing) must be annotated with an
// activity.
//
// Error handling: If the user provides an invalid configuration (incorrect numbers, types, or
// both), we emit an error and return the original signature. This allows us to continue parsing.
// Error handling: If the user provides the wrong number of activities, we emit an error and
// return `None`. If the types don't fit the activities, we emit an error and return the
// original signature. This allows us to continue parsing.
// FIXME(Sa4dUs): make individual activities' span available so errors
// can point to only the activity instead of the entire attribute
fn gen_enzyme_decl(
ecx: &ExtCtxt<'_>,
sig: &ast::FnSig,
x: &RustcAutodiff,
span: Span,
) -> ast::FnSig {
) -> Option<ast::FnSig> {
let dcx = ecx.sess.dcx();
let has_ret = has_ret(&sig.decl.output);
let sig_args = sig.decl.inputs.len() + if has_ret { 1 } else { 0 };
Expand All @@ -608,8 +589,7 @@ fn gen_enzyme_decl(
expected: sig_args,
found: num_activities,
});
// This is not the right signature, but we can continue parsing.
return sig.clone();
return None;
}
assert!(sig.decl.inputs.len() == x.input_activity.len());
assert!(has_ret == x.has_ret_activity());
Expand Down Expand Up @@ -650,7 +630,7 @@ fn gen_enzyme_decl(

if errors {
// This is not the right signature, but we can continue parsing.
return sig.clone();
return Some(sig.clone());
}

let unsafe_activities = x
Expand Down Expand Up @@ -822,5 +802,5 @@ fn gen_enzyme_decl(
}
let d_sig = FnSig { header: d_header, decl: d_decl, span };
trace!("Generated signature: {:?}", d_sig);
d_sig
Some(d_sig)
}
6 changes: 6 additions & 0 deletions compiler/rustc_builtin_macros/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,12 @@ mod autodiff {
pub(crate) span: Span,
}
#[derive(Diagnostic)]
#[diag("expected an identifier for the generated function name")]
pub(crate) struct AutoDiffInvalidName {
#[primary_span]
pub(crate) span: Span,
}
#[derive(Diagnostic)]
#[diag("did not recognize Activity: `{$act}`")]
pub(crate) struct AutoDiffUnknownActivity {
#[primary_span]
Expand Down
4 changes: 0 additions & 4 deletions tests/crashes/160329.rs

This file was deleted.

38 changes: 38 additions & 0 deletions tests/ui/autodiff/invalid-macro-args.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
//! Regression test for <https://github.com/rust-lang/rust/issues/150326>,
//! <https://github.com/rust-lang/rust/issues/150327> and
//! <https://github.com/rust-lang/rust/issues/150329>.
//! Invalid arguments to the autodiff macros used to ICE during expansion.

#![feature(autodiff)]

use std::autodiff::{autodiff_forward, autodiff_reverse};

// A return type, but no activities at all.
#[autodiff_reverse(df1)]
//~^ ERROR expected 1 activities, but found 0
fn f1() -> f64 {
0.0
}

// The name has a leading `::`.
#[autodiff_forward(::df2)]
//~^ ERROR expected an identifier for the generated function name
fn f2() {}

// The name is a float literal.
#[autodiff_reverse(2.0f)]
//~^ ERROR invalid suffix `f` for float literal
//~| ERROR expected an identifier for the generated function name
fn f3() {}

// An activity that is a float literal.
#[autodiff_reverse(df4, 2.0)]
//~^ ERROR did not recognize Activity: `2.0`
fn f4(x: f64) {}

// An activity with a path.
#[autodiff_reverse(df5, ::Active)]
//~^ ERROR did not recognize Activity: `::Active`
fn f5(x: f64) {}

fn main() {}
40 changes: 40 additions & 0 deletions tests/ui/autodiff/invalid-macro-args.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
error: expected 1 activities, but found 0
--> $DIR/invalid-macro-args.rs:11:1
|
LL | #[autodiff_reverse(df1)]
| ^^^^^^^^^^^^^^^^^^^^^^^^

error: expected an identifier for the generated function name
--> $DIR/invalid-macro-args.rs:18:20
|
LL | #[autodiff_forward(::df2)]
| ^^^^^

error: invalid suffix `f` for float literal
--> $DIR/invalid-macro-args.rs:23:20
|
LL | #[autodiff_reverse(2.0f)]
| ^^^^ invalid suffix `f`
|
= help: valid suffixes are `f32` and `f64`

error: expected an identifier for the generated function name
--> $DIR/invalid-macro-args.rs:23:20
|
LL | #[autodiff_reverse(2.0f)]
| ^^^^

error: did not recognize Activity: `2.0`
--> $DIR/invalid-macro-args.rs:29:25
|
LL | #[autodiff_reverse(df4, 2.0)]
| ^^^

error: did not recognize Activity: `::Active`
--> $DIR/invalid-macro-args.rs:34:25
|
LL | #[autodiff_reverse(df5, ::Active)]
| ^^^^^^^^

error: aborting due to 6 previous errors

13 changes: 13 additions & 0 deletions tests/ui/autodiff/invalid-signature-recovery.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
//! Regression test for <https://github.com/rust-lang/rust/issues/160329>.
//! Parser recovery left the function with more parameters than activities,
//! and expansion used to ICE instead of stopping at the count error.

#![feature(autodiff)]

#[core::autodiff::autodiff_forward(fd_inner, Dual)]
//~^ ERROR expected 2 activities, but found 1
fn f(_x: struct S<B, T>) {}
//~^ ERROR expected type, found keyword `struct`
//~| ERROR expected one of `:`, `@`, or `|`, found `>`

fn main() {}
20 changes: 20 additions & 0 deletions tests/ui/autodiff/invalid-signature-recovery.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
error: expected type, found keyword `struct`
--> $DIR/invalid-signature-recovery.rs:9:10
|
LL | fn f(_x: struct S<B, T>) {}
| ^^^^^^ expected type

error: expected one of `:`, `@`, or `|`, found `>`
--> $DIR/invalid-signature-recovery.rs:9:23
|
LL | fn f(_x: struct S<B, T>) {}
| ^ expected one of `:`, `@`, or `|`

error: expected 2 activities, but found 1
--> $DIR/invalid-signature-recovery.rs:7:1
|
LL | #[core::autodiff::autodiff_forward(fd_inner, Dual)]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error: aborting due to 3 previous errors

Loading