Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Menu
Open sidebar
Raphaël Gomès
micro-timer
Commits
011cdfa0cfa0
Commit
72233e23
authored
Feb 27, 2020
by
Raphaël Gomès
Browse files
Add better error message when using `timed` on something else than a function
parent
5138d01934e5
Changes
1
Hide whitespace changes
Inline
Side-by-side
src/lib.rs
View file @
011cdfa0
...
...
@@ -5,14 +5,22 @@
/// `extern crate` Required even for 2018 edition
extern
crate
proc_macro
;
use
proc_macro
::
TokenStream
;
use
quote
::
quote
;
type
StaticResult
<
T
>
=
::
std
::
result
::
Result
<
T
,
&
'static
str
>
;
use
quote
::{
quote
,
quote_spanned
};
use
syn
::
spanned
::
Spanned
;
/// ```compile_fail
/// use micro_timer::timed;
///
/// #[timed] // Can only be used on functions
/// struct Thing;
/// ```
#[proc_macro_attribute]
pub
fn
timed
(
_attr_ts
:
TokenStream
,
fn_ts
:
TokenStream
)
->
TokenStream
{
let
ast
=
syn
::
parse
(
fn_ts
.clone
())
.unwrap
();
let
func
=
parse_function
(
ast
)
.unwrap
();
let
func
=
match
parse_function
(
ast
)
{
Ok
(
f
)
=>
f
,
Err
(
stream
)
=>
return
stream
,
};
let
mut
outer
=
func
.clone
();
outer
.sig.ident
=
func
.sig.ident
.to_owned
();
...
...
@@ -42,9 +50,13 @@ pub fn timed(_attr_ts: TokenStream, fn_ts: TokenStream) -> TokenStream {
(
quote!
{
#
outer
})
.into
()
}
fn
parse_function
(
item
:
syn
::
Item
)
->
Static
Result
<
syn
::
ItemFn
>
{
fn
parse_function
(
item
:
syn
::
Item
)
->
Result
<
syn
::
ItemFn
,
TokenStream
>
{
match
item
{
syn
::
Item
::
Fn
(
func
)
=>
Ok
(
func
),
_
=>
Err
(
"`time_it` attribute can only be used on functions"
),
i
=>
Err
(
quote_spanned!
{
i
.span
()
=>
compile_error!
(
"`#[timed]` can only be used on functions"
);
}
.into
()),
}
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment