- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要获取每个方法的调用者的源位置。我正在尝试创建一个 proc_macro_attribute
捕获位置并打印它。
#[proc_macro_attribute]
pub fn get_location(attr: TokenStream, item: TokenStream) -> TokenStream {
// Get and print file!(), line!() of source
// Should print line no. 11
item
}
#[get_location]
fn add(x: u32, y: u32) -> u32 {
x + y
}
fn main() {
add(1, 5); // Line No. 11
}
最佳答案
TL;DR
这是一个使用 syn
的过程宏和 quote
做你所描述的:
// print_caller_location/src/lib.rs
use proc_macro::TokenStream;
use quote::quote;
use syn::spanned::Spanned;
// Create a procedural attribute macro
//
// Notably, this must be placed alone in its own crate
#[proc_macro_attribute]
pub fn print_caller_location(_attr: TokenStream, item: TokenStream) -> TokenStream {
// Parse the passed item as a function
let func = syn::parse_macro_input!(item as syn::ItemFn);
// Break the function down into its parts
let syn::ItemFn {
attrs,
vis,
sig,
block,
} = func;
// Ensure that it isn't an `async fn`
if let Some(async_token) = sig.asyncness {
// Error out if so
let error = syn::Error::new(
async_token.span(),
"async functions do not support caller tracking functionality
help: consider returning `impl Future` instead",
);
return TokenStream::from(error.to_compile_error());
}
// Wrap body in a closure only if function doesn't already have #[track_caller]
let block = if attrs.iter().any(|attr| attr.path.is_ident("track_caller")) {
quote! { #block }
} else {
quote! {
(move || #block)()
}
};
// Extract function name for prettier output
let name = format!("{}", sig.ident);
// Generate the output, adding `#[track_caller]` as well as a `println!`
let output = quote! {
#[track_caller]
#(#attrs)*
#vis #sig {
println!(
"entering `fn {}`: called from `{}`",
#name,
::core::panic::Location::caller()
);
#block
}
};
// Convert the output from a `proc_macro2::TokenStream` to a `proc_macro::TokenStream`
TokenStream::from(output)
}
Cargo.toml
:
# print_caller_location/Cargo.toml
[lib]
proc-macro = true
[dependencies]
syn = {version = "1.0.16", features = ["full"]}
quote = "1.0.3"
proc-macro2 = "1.0.9"
Short answer: to obtain the location in which your function gets called, mark it with
#[track_caller]
and usestd::panic::Location::caller
in its body.
#[track_caller]
, Location::caller
. fn foo() {
// body of foo
}
#[track_caller]
fn foo() {
println!("{}", std::panic::Location::caller());
// body of foo
}
Cargo.toml
.
// print_caller_location/src/lib.rs
use proc_macro::TokenStream;
use quote::quote;
// Create a procedural attribute macro
//
// Notably, this must be placed alone in its own crate
#[proc_macro_attribute]
pub fn print_caller_location(_attr: TokenStream, item: TokenStream) -> TokenStream {
// Parse the passed item as a function
let func = syn::parse_macro_input!(item as syn::ItemFn);
// Break the function down into its parts
let syn::ItemFn {
attrs,
vis,
sig,
block,
} = func;
// Extract function name for prettier output
let name = format!("{}", sig.ident);
// Generate the output, adding `#[track_caller]` as well as a `println!`
let output = quote! {
#[track_caller]
#(#attrs)*
#vis #sig {
println!(
"entering `fn {}`: called from `{}`",
#name,
::core::panic::Location::caller()
);
#block
}
};
// Convert the output from a `proc_macro2::TokenStream` to a `proc_macro::TokenStream`
TokenStream::from(output)
}
// example1/src/main.rs
#![feature(track_caller)]
#[print_caller_location::print_caller_location]
fn add(x: u32, y: u32) -> u32 {
x + y
}
fn main() {
add(1, 5); // entering `fn add`: called from `example1/src/main.rs:11:5`
add(1, 5); // entering `fn add`: called from `example1/src/main.rs:12:5`
}
async fn
组成年代:#[print_caller_location]
) 的位置。例如:// example2/src/main.rs
#![feature(track_caller)]
#[print_caller_location::print_caller_location]
async fn foo() {}
fn main() {
let future = foo();
// ^ oops! prints nothing
futures::executor::block_on(future);
// ^ oops! prints "entering `fn foo`: called from `example2/src/main.rs:5:1`"
let future = foo();
// ^ oops! prints nothing
futures::executor::block_on(future);
// ^ oops! prints "entering `fn foo`: called from `example2/src/main.rs:5:1`"
}
#[track_caller]
:#[print_caller_location]
的嵌套函数将打印根调用者的位置,而不是给定函数的直接调用者。例如:// example3/src/main.rs
#![feature(track_caller)]
#[print_caller_location::print_caller_location]
fn add(x: u32, y: u32) -> u32 {
x + y
}
#[print_caller_location::print_caller_location]
fn add_outer(x: u32, y: u32) -> u32 {
add(x, y)
// ^ we would expect "entering `fn add`: called from `example3/src/main.rs:12:5`"
}
fn main() {
add(1, 5);
// ^ "entering `fn add`: called from `example3/src/main.rs:17:5`"
add(1, 5);
// ^ "entering `fn add`: called from `example3/src/main.rs:19:5`"
add_outer(1, 5);
// ^ "entering `fn add_outer`: called from `example3/src/main.rs:21:5`"
// ^ oops! "entering `fn add`: called from `example3/src/main.rs:21:5`"
//
// In reality, `add` was called on line 12, from within the body of `add_outer`
add_outer(1, 5);
// ^ "entering `fn add_outer`: called from `example3/src/main.rs:26:5`"
// oops! ^ entering `fn add`: called from `example3/src/main.rs:26:5`
//
// In reality, `add` was called on line 12, from within the body of `add_outer`
}
async fn
s
async fn
解决此问题。使用
-> impl Future
,例如,如果我们想要我们的
async fn
反例要正常工作,我们可以改为:
// example4/src/main.rs
#![feature(track_caller)]
use std::future::Future;
#[print_caller_location::print_caller_location]
fn foo() -> impl Future<Output = ()> {
async move {
// body of foo
}
}
fn main() {
let future = foo();
// ^ prints "entering `fn foo`: called from `example4/src/main.rs:15:18`"
futures::executor::block_on(future);
// ^ prints nothing
let future = foo();
// ^ prints "entering `fn foo`: called from `example4/src/main.rs:19:18`"
futures::executor::block_on(future);
// ^ prints nothing
}
async fn foo()
更改为至
fn foo() -> impl Future<Output = ()>
除了影响返回的 future 可能具有的自动特征。
async fn
,则简单地发出错误。 .我们可以通过将这些行添加到我们的宏代码中来做到这一点:
// Ensure that it isn't an `async fn`
if let Some(async_token) = sig.asyncness {
// Error out if so
let error = syn::Error::new(
async_token.span(),
"async functions do not support caller tracking functionality
help: consider returning `impl Future` instead",
);
return TokenStream::from(error.to_compile_error());
}
#[print_caller_location]
的嵌套行为职能
#[track_caller]
函数,
foo
,直接调用另一个
#[track_caller]
函数,
bar
,
Location::caller
将使他们都可以访问
foo
的来电者。换句话说,
Location::caller
在嵌套
#[track_caller]
的情况下提供对根调用者的访问权限职能:
#![feature(track_caller)]
fn main() {
foo(); // prints `src/main.rs:4:5` instead of the line number in `foo`
}
#[track_caller]
fn foo() {
bar();
}
#[track_caller]
fn bar() {
println!("{}", std::panic::Location::caller());
}
#[track_caller]
的链。来电。我们可以通过隐藏对
bar
的嵌套调用来打破链条。在闭包内:
#![feature(track_caller)]
fn main() {
foo();
}
#[track_caller]
fn foo() {
(move || {
bar(); // prints `src/main.rs:10:9`
})()
}
#[track_caller]
fn bar() {
println!("{}", std::panic::Location::caller());
}
#[track_caller]
的链条了功能,我们可以解决这个问题。我们只需要确定用户是否真的用
#[track_caller]
标记了他们的功能。我们故意避免插入闭包并破坏链条。
// Wrap body in a closure only if function doesn't already have #[track_caller]
let block = if attrs.iter().any(|attr| attr.path.is_ident("track_caller")) {
quote! { #block }
} else {
quote! {
(move || #block)()
}
};
// print_caller_location/src/lib.rs
use proc_macro::TokenStream;
use quote::quote;
use syn::spanned::Spanned;
// Create a procedural attribute macro
//
// Notably, this must be placed alone in its own crate
#[proc_macro_attribute]
pub fn print_caller_location(_attr: TokenStream, item: TokenStream) -> TokenStream {
// Parse the passed item as a function
let func = syn::parse_macro_input!(item as syn::ItemFn);
// Break the function down into its parts
let syn::ItemFn {
attrs,
vis,
sig,
block,
} = func;
// Ensure that it isn't an `async fn`
if let Some(async_token) = sig.asyncness {
// Error out if so
let error = syn::Error::new(
async_token.span(),
"async functions do not support caller tracking functionality
help: consider returning `impl Future` instead",
);
return TokenStream::from(error.to_compile_error());
}
// Wrap body in a closure only if function doesn't already have #[track_caller]
let block = if attrs.iter().any(|attr| attr.path.is_ident("track_caller")) {
quote! { #block }
} else {
quote! {
(move || #block)()
}
};
// Extract function name for prettier output
let name = format!("{}", sig.ident);
// Generate the output, adding `#[track_caller]` as well as a `println!`
let output = quote! {
#[track_caller]
#(#attrs)*
#vis #sig {
println!(
"entering `fn {}`: called from `{}`",
#name,
::core::panic::Location::caller()
);
#block
}
};
// Convert the output from a `proc_macro2::TokenStream` to a `proc_macro::TokenStream`
TokenStream::from(output)
}
关于rust - 我们可以在过程宏属性中获取调用者的源代码位置吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60692131/
如何在 Excel 中编写可以在我将打开的任何 Excel 文档上工作(使用快捷方式运行)的宏? 这可能吗? 最佳答案 您需要将宏添加到 Personal.xlsb 以使它们可用于所有 excel 文
我正在研究 problem #74在4clojure.com,我的解决方案如下: (defn FPS [s] (->> (map read-string (re-seq #"[0-9]+"
我还没有完全理解Clojure 箭头宏thread-first -> 和thread-last 宏->> 之间的区别。在阅读 https://clojure.org/guides/threading_
我想将一些调试输出语句插入到大型 C 代码库中。这些调试输出语句将由编译器选项开关控制。 调试输出语句如下所示: #ifdef DEBUG_FLAG Print(someSymbol) #endif
我正在通过宏将代码注入(inject)到 C++ 类中。有没有办法根据访问修饰符的上下文来做到这一点?有点像 #if (we_are_in_public_context) INJECT_PUBLIC_
这应该与 memoize 类似,但有很大不同。虽然 memoize 应该与纯函数一起使用,但它通常对加速 IO 相关函数很有用。 我正在寻找的函数/宏应该表现得像高阶函数。它产生的功能应该: 第一次调
对于下面的代码: let services: [MyServices] = [ MyService(), #if DEBUG DebugService(), #endi
假设我有以下文本文件 name: John Doe description: My name is John Doe and I'm really good at vim! name: John Do
在创建 Excel 宏方面需要帮助。我有一个 Excel 工作表。Excel 工作表不一致。我打算使它统一和结构化。 例如。 A B C
我正在 excel 中设置一个宏,以便在更新单元格时自动发送电子邮件。是否可以在电子邮件正文中包含单元格的内容?例如,如果单元格 G7 已更新,请在电子邮件中包含单元格 B7 的内容?单元格行将是相同
我创建了一个简单的 Excel 工作表。 这是我的宏代码: Sub MyMacro() Sheets("Sheet1").Select A$ = Cells(1, 1) Msg
在 Excel 的 VB 宏中,如何删除所有出现的以某个字符串开头的单词? 例如: 字符串内容为:xxxx $AUD543.43 yyyy 我想搜索以 $AUD 开头的字符串中的任何内容并删除下一个空
我是 Excel 宏的新手.. 谁能告诉我这个宏是做什么的? Sub People_Add_Document() prow = ActiveCell.row num = Cells(p
我对 Excel 中的 VBA 和宏非常陌生。我有一个非常大的 Excel 电子表格,其中 A 列保存日期。我正在尝试删除值小于某个日期的行,这就是我到现在为止的想法。 Sub DELETEDATE(
我在 Excel 2003 中有一个 VBA 对象,当通过流数据获得某些值时,它会触发三个简单的宏。它运行良好。我想打开一个重复的工作表,但具有不同的流数据,并在各自的工作表上触发宏。它现在可以使用,
下面的宏有什么问题?我只想评估一个选项卡中的一个单元格是否大于另一个选项卡中的另一个单元格。然后消息框: Sub Comhouse() If Worksheets("(2.2) TRA works
需要一个简单的 excel 宏的帮助。我在第 1 列 X1 到 X20 中有数据。我想自动将此信息粘贴到 A 列,然后当我更新 X 列中的数字时,我想将此信息粘贴到 B 列,然后再粘贴到 C 列...
我找到了以下代码,效果很好;但是,我必须手动更改月份,以便它转到第二个工作簿的右侧工作表。由于工作表以月为单位,我怎样才能使其自动更改为当月? Sub AlarmSheet() Dim wkb As
很难说出这里问的是什么。这个问题是模棱两可的、模糊的、不完整的、过于宽泛的或修辞的,无法以目前的形式得到合理的回答。如需帮助澄清这个问题以便重新打开它,visit the help center .
我的公司只使用 MS Office 2003 产品,所以我必须坚持下去。由于我的工作性质,我需要使用很多“复制和粘贴”功能。源数据主要来自网站,我将数据粘贴到 Excel 中的单元格中。问题是剪贴板保
我是一名优秀的程序员,十分优秀!