-
-
Notifications
You must be signed in to change notification settings - Fork 214
/
Copy pathmod.rs
383 lines (329 loc) · 12.3 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
/*
* Copyright (c) godot-rust; Bromeon and contributors.
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
// Note: some code duplication with godot-codegen crate.
use crate::class::FuncDefinition;
use crate::ParseResult;
use proc_macro2::{Delimiter, Group, Ident, Literal, TokenStream, TokenTree};
use quote::spanned::Spanned;
use quote::{format_ident, quote, ToTokens, TokenStreamExt};
use venial::Attribute;
mod kv_parser;
mod list_parser;
pub(crate) use kv_parser::KvParser;
pub(crate) use list_parser::ListParser;
pub fn ident(s: &str) -> Ident {
format_ident!("{}", s)
}
pub fn c_str(string: &str) -> Literal {
let c_string = std::ffi::CString::new(string).expect("CString::new() failed");
Literal::c_string(&c_string)
}
pub fn class_name_obj(class: &impl ToTokens) -> TokenStream {
let class = class.to_token_stream();
quote! { <#class as ::godot::obj::GodotClass>::class_name() }
}
pub fn bail_fn<R, T>(msg: impl AsRef<str>, tokens: T) -> ParseResult<R>
where
T: Spanned,
{
// TODO: using T: Spanned often only highlights the first tokens of the symbol, e.g. #[attr] in a function.
// Could use function.name; possibly our own trait to get a more meaningful span... or change upstream in venial.
Err(error_fn(msg, tokens))
}
macro_rules! bail {
($tokens:expr, $format_string:literal $($rest:tt)*) => {
$crate::util::bail_fn(format!($format_string $($rest)*), $tokens)
}
}
macro_rules! require_api_version {
($min_version:literal, $span:expr, $attribute:literal) => {
if !cfg!(since_api = $min_version) {
bail!(
$span,
"{} requires at least Godot API version {}",
$attribute,
$min_version
)
} else {
Ok(())
}
};
}
pub fn error_fn<T>(msg: impl AsRef<str>, tokens: T) -> venial::Error
where
T: Spanned,
{
venial::Error::new_at_span(tokens.__span(), msg.as_ref())
}
macro_rules! error {
($tokens:expr, $format_string:literal $($rest:tt)*) => {
$crate::util::error_fn(format!($format_string $($rest)*), $tokens)
}
}
pub(crate) use bail;
pub(crate) use error;
pub(crate) use require_api_version;
pub fn reduce_to_signature(function: &venial::Function) -> venial::Function {
let mut reduced = function.clone();
reduced.vis_marker = None; // TODO needed?
reduced.attributes.clear();
reduced.tk_semicolon = None;
reduced.body = None;
reduced
}
pub fn parse_signature(mut signature: TokenStream) -> venial::Function {
// Signature needs {} body to be parseable by venial
signature.append(TokenTree::Group(Group::new(
Delimiter::Brace,
TokenStream::new(),
)));
let function_item = venial::parse_item(signature)
.unwrap()
.as_function()
.unwrap()
.clone();
reduce_to_signature(&function_item)
}
/// Returns a type expression that can be used as a `VarcallSignatureTuple`.
pub fn make_signature_tuple_type(
ret_type: &TokenStream,
param_types: &[venial::TypeExpr],
) -> TokenStream {
quote::quote! {
(#ret_type, #(#param_types),*)
}
}
fn is_punct(tt: &TokenTree, c: char) -> bool {
match tt {
TokenTree::Punct(punct) => punct.as_char() == c,
_ => false,
}
}
fn delimiter_opening_char(delimiter: Delimiter) -> char {
match delimiter {
Delimiter::Parenthesis => '(',
Delimiter::Brace => '{',
Delimiter::Bracket => '[',
Delimiter::None => 'Ø',
}
}
// ----------------------------------------------------------------------------------------------------------------------------------------------
// Validation for trait/impl
/// Given an impl block for a trait, returns whether that is an impl for a trait with the given name.
///
/// That is, if `name` is `"MyTrait"`, then this function returns true if and only if `original_impl` is a
/// declaration of the form `impl MyTrait for SomeType`. The type `SomeType` is irrelevant in this example.
pub(crate) fn is_impl_named(original_impl: &venial::Impl, name: &str) -> bool {
let trait_name = original_impl.trait_ty.as_ref().unwrap(); // unwrap: already checked outside
extract_typename(trait_name).is_some_and(|seg| seg.ident == name)
}
/// Validates either:
/// a) the declaration is `impl Trait for SomeType`, if `expected_trait` is `Some("Trait")`
/// b) the declaration is `impl SomeType`, if `expected_trait` is `None`
pub(crate) fn validate_impl(
original_impl: &venial::Impl,
expected_trait: Option<&str>,
attr: &str,
) -> ParseResult<Ident> {
if let Some(expected_trait) = expected_trait {
// impl Trait for Self -- validate Trait
if !is_impl_named(original_impl, expected_trait) {
return bail!(
original_impl,
"#[{attr}] for trait impls requires trait to be `{expected_trait}`",
);
}
}
// impl Trait for Self -- validate Self
validate_self(original_impl, attr)
}
/// Validates that the declaration is the of the form `impl Trait for SomeType`, where the name of `Trait` begins with `I`.
///
/// Returns `(class_name, trait_path, trait_base_class)`, e.g. `(MyClass, godot::prelude::INode3D, Node3D)`.
pub(crate) fn validate_trait_impl_virtual<'a>(
original_impl: &'a venial::Impl,
attr: &str,
) -> ParseResult<(Ident, &'a venial::TypeExpr, Ident)> {
let trait_name = original_impl.trait_ty.as_ref().unwrap(); // unwrap: already checked outside
let typename = extract_typename(trait_name);
// Validate trait
let Some(base_class) = typename
.as_ref()
.and_then(|seg| seg.ident.to_string().strip_prefix('I').map(ident))
else {
return bail!(
original_impl,
"#[{attr}] for trait impls requires a virtual method trait (trait name should start with 'I')",
);
};
// Validate self
validate_self(original_impl, attr).map(|class_name| {
// let trait_name = typename.unwrap(); // unwrap: already checked in 'Validate trait'
(class_name, trait_name, base_class)
})
}
fn validate_self(original_impl: &venial::Impl, attr: &str) -> ParseResult<Ident> {
if let Some(segment) = extract_typename(&original_impl.self_ty) {
if segment.generic_args.is_none() {
Ok(segment.ident)
} else {
bail!(
original_impl,
"#[{attr}] for does currently not support generic arguments",
)
}
} else {
bail!(
original_impl,
"#[{attr}] requires Self type to be a simple path",
)
}
}
/// Gets the right-most type name in the path.
pub(crate) fn extract_typename(ty: &venial::TypeExpr) -> Option<venial::PathSegment> {
match ty.as_path() {
Some(mut path) => path.segments.pop(),
_ => None,
}
}
// ----------------------------------------------------------------------------------------------------------------------------------------------
pub(crate) fn path_is_single(path: &[TokenTree], expected: &str) -> bool {
path.len() == 1 && path[0].to_string() == expected
}
pub(crate) fn path_ends_with(path: &[TokenTree], expected: &str) -> bool {
// Could also use TypeExpr::as_path(), or fn below this one.
path.last().is_some_and(|last| last.to_string() == expected)
}
pub(crate) fn path_ends_with_complex(path: &venial::TypeExpr, expected: &str) -> bool {
path.as_path().is_some_and(|path| {
path.segments
.last()
.is_some_and(|seg| seg.ident == expected)
})
}
pub(crate) fn extract_cfg_attrs(
attrs: &[venial::Attribute],
) -> impl IntoIterator<Item = &venial::Attribute> {
attrs.iter().filter(|attr| {
let Some(attr_name) = attr.get_single_path_segment() else {
return false;
};
if attr_name == "cfg" {
return true;
}
if attr_name == "cfg_attr" && attr.value.to_token_stream().to_string().contains("cfg(") {
return true;
}
false
})
}
#[cfg(before_api = "4.3")]
pub fn make_virtual_tool_check() -> TokenStream {
quote! {
if ::godot::private::is_class_inactive(Self::__config().is_tool) {
return None;
}
}
}
#[cfg(since_api = "4.3")]
pub fn make_virtual_tool_check() -> TokenStream {
TokenStream::new()
}
// This function is duplicated in godot-codegen\src\util.rs
#[rustfmt::skip]
pub fn safe_ident(s: &str) -> Ident {
// See also: https://doc.rust-lang.org/reference/keywords.html
match s {
// Lexer
| "as" | "break" | "const" | "continue" | "crate" | "else" | "enum" | "extern" | "false" | "fn" | "for" | "if"
| "impl" | "in" | "let" | "loop" | "match" | "mod" | "move" | "mut" | "pub" | "ref" | "return" | "self" | "Self"
| "static" | "struct" | "super" | "trait" | "true" | "type" | "unsafe" | "use" | "where" | "while"
// Lexer 2018+
| "async" | "await" | "dyn"
// Reserved
| "abstract" | "become" | "box" | "do" | "final" | "macro" | "override" | "priv" | "typeof" | "unsized" | "virtual" | "yield"
// Reserved 2018+
| "try"
=> format_ident!("{}_", s),
_ => ident(s)
}
}
// ----------------------------------------------------------------------------------------------------------------------------------------------
/// Parses a `meta` TokenStream, that is, the tokens in parameter position of a proc-macro (between the braces).
/// Because venial can't actually parse a meta item directly, this is done by reconstructing the full macro attribute on top of some content and then parsing *that*.
pub fn venial_parse_meta(
meta: &TokenStream,
self_name: Ident,
content: &TokenStream,
) -> Result<venial::Item, venial::Error> {
// Hack because venial doesn't support direct meta parsing yet
let input = quote! {
#[#self_name(#meta)]
#content
};
venial::parse_item(input)
}
// ----------------------------------------------------------------------------------------------------------------------------------------------
// util functions for handling #[func]s and #[var(get=f, set=f)]
pub fn make_function_registered_name_constants(
funcs: &[FuncDefinition],
class_name: &Ident,
) -> Vec<TokenStream> {
funcs
.iter()
.map(|func| {
// the constant needs the same #[cfg] attribute(s) as the function, so that it is only active if the function is also active.
let cfg_attributes = extract_cfg_attrs(&func.external_attributes)
.into_iter()
.collect();
make_function_registered_name_constant(
class_name,
&func.signature_info.method_name,
&func.registered_name,
&cfg_attributes,
)
})
.collect()
}
/// Funcs can be renamed with `#[func(rename=new_name) fn f();`.
/// To be able to access the renamed function name at a later point, it is saved in a string constant.
/// This would create the following code for `f`:
/// ``pub const __gdext_func_{class_name}_f: &str = "new_name";``
pub fn make_function_registered_name_constant(
class_name: &Ident,
func_name: &Ident,
registered_name: &Option<String>,
attributes: &Vec<&Attribute>,
) -> TokenStream {
let const_name = format_function_registered_name_constant_name(class_name, func_name);
let const_value = match ®istered_name {
Some(renamed) => renamed.to_string(),
None => func_name.to_string(),
};
let doc_comment = format!(
"The rust function `{}` is registered with godot as `{}`.",
func_name, const_value
);
quote! {
#(#attributes)*
#[doc = #doc_comment]
#[doc(hidden)]
#[allow(non_upper_case_globals)]
pub const #const_name: &str = #const_value;
}
}
/// Returns the name of the constant that will be autogenerated.
pub fn format_function_registered_name_constant_name(
class_name: &Ident,
func_name: &Ident,
) -> Ident {
format_ident!("__gdext_func_{}_{}", class_name, func_name)
}
/// Returns the name of the dummy struct that's used as container for all function name constants.
pub fn format_function_registered_name_struct_name(class_name: &Ident) -> Ident {
format_ident!("{class_name}_Functions")
}