Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

macro_rules! versions of assert_tokens (and _ser_ and _de_) to preserve line number on failure #26

Closed
rben01 opened this issue Nov 1, 2021 · 3 comments

Comments

@rben01
Copy link

rben01 commented Nov 1, 2021

In serde_test, the family of assert_tokens functions, while useful, would be even more useful if converted to macros. During testing, the location of a failure is reported as the location where the panic occurred, which means assert_tokens failures get traced to the serde_test source file, e.g., /Users/rben01/.cargo/registry/src/github.com-1ecc6299db9ec823/serde_test-1.0.130/src/ser.rs:111:9. If these functions were replaced with macros then the failure would get traced to the correct location in the user's source file. Example, with comments labeling the line they're on:

// Line 160
#[test]
fn test_fn() {
	let test_fn = || {
		assert!(false);
		//Line 165
	};
	test_fn();
}

// Line 170
#[test]
fn test_macro() {
	macro_rules! test_macro {
		//
		// Line 175
		() => {
			assert!(false);
		};
	}
	// Line 180
	test_macro!();
}

The failure in test_fn is reported as being on line 164, where the assert!(false) is, whereas the failure in test_macro is reported as being on line 181, where the failing use of the test_macro! occurred.

In general, converting functions to macros "just because" does not make sense. But when those functions are intended to be used in a testing context, then converting them to macros does make sense because macros preserve line numbers when they fail, whereas functions do not.

@dtolnay
Copy link
Member

dtolnay commented Nov 1, 2021

A track_caller attribute would be more appropriate I think. https://doc.rust-lang.org/1.56.0/reference/attributes/codegen.html#the-track_caller-attribute

@rben01
Copy link
Author

rben01 commented Nov 1, 2021

@dtolnay TIL that exists. Would definitely be preferable to my (what I now see is a) hack.

@dtolnay
Copy link
Member

dtolnay commented Jan 23, 2022

A track_caller attribute was added in serde-rs/serde#1920.

@dtolnay dtolnay closed this as completed Jan 23, 2022
@dtolnay dtolnay transferred this issue from serde-rs/serde Aug 10, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants