-
Notifications
You must be signed in to change notification settings - Fork 6
/
lib.rs
595 lines (527 loc) · 19.2 KB
/
lib.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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
/// This is all dirty hacks. We need to reimplement it with syn and quote
use proc_macro::{Group, TokenStream, TokenTree};
enum ObjcAttr {
Optional,
MsgSend(String),
}
fn read_objc_attr(group: Group) -> Option<ObjcAttr> {
let mut iter = group.stream().into_iter();
let Some(TokenTree::Ident(ident)) = iter.next() else {
return None;
};
if !ident.to_string().eq("objc") {
return None;
}
let Some(TokenTree::Punct(p)) = iter.next() else {
return None;
};
assert_eq!(p.as_char(), ':');
let Some(TokenTree::Punct(p)) = iter.next() else {
return None;
};
assert_eq!(p.as_char(), ':');
while let Some(tt) = iter.next() {
match tt {
TokenTree::Group(v) => panic!("didnt expect group {v}"),
TokenTree::Ident(v) => {
if v.to_string().eq("optional") {
return Some(ObjcAttr::Optional);
} else if v.to_string().eq("msg_send") {
let Some(TokenTree::Group(a)) = iter.next() else {
return None;
};
let sel = a.stream().to_string().replace(' ', "").replace('\n', "");
return Some(ObjcAttr::MsgSend(sel));
}
return None;
}
TokenTree::Punct(v) => panic!("did't expect punct {v}"),
TokenTree::Literal(v) => panic!("did't expect literal {v}"),
}
}
panic!("Unexpected attribute")
}
fn sel_args_count(sel: TokenStream) -> usize {
sel.into_iter()
.filter(|t| match t {
TokenTree::Punct(v) if v.as_char() == ':' => true,
_ => false,
})
.count()
}
fn get_fn_args(group: TokenStream, class: bool, debug: bool) -> Vec<String> {
let mut prev = None;
let mut vars = Vec::with_capacity(10);
if debug {
println!("tokens {:?}", group);
}
let mut can_be_name = class;
let mut level = 0;
for t in group.into_iter() {
match t {
TokenTree::Ident(i) => {
prev = Some(i.to_string());
}
TokenTree::Punct(p) if can_be_name && level == 0 && p.as_char() == ':' => {
if let Some(id) = prev.take() {
vars.push(id)
}
can_be_name = false;
}
TokenTree::Punct(p) if p.as_char() == '<' => level += 1,
TokenTree::Punct(p) if p.as_char() == '>' => level -= 1,
TokenTree::Punct(p) if p.as_char() == ',' => can_be_name = true,
_ => prev = None,
}
}
vars
}
#[proc_macro_attribute]
pub fn rar_retain(sel: TokenStream, func: TokenStream) -> TokenStream {
gen_msg_send(sel, func, true, false, false)
}
#[proc_macro_attribute]
pub fn cls_rar_retain(sel: TokenStream, func: TokenStream) -> TokenStream {
gen_msg_send(sel, func, true, true, false)
}
#[proc_macro_attribute]
pub fn msg_send(sel: TokenStream, func: TokenStream) -> TokenStream {
gen_msg_send(sel, func, false, false, false)
}
/// Should generate static fn sel_xxx function that gets selector.
/// So user can check selector with is_reponds_to_sel
#[proc_macro_attribute]
pub fn optional(_sel: TokenStream, func: TokenStream) -> TokenStream {
let mut iter = func.clone().into_iter();
let Some(TokenTree::Punct(p)) = iter.next() else {
panic!("expect #[objc::msg_send(...)]")
};
if p.as_char() != '#' {
panic!("expect #[objc::msg_send(...)]")
}
let Some(TokenTree::Group(g)) = iter.next() else {
panic!("expect #[objc::msg_send(...)]")
};
let Some(ObjcAttr::MsgSend(extern_name)) = read_objc_attr(g) else {
panic!("expect #[objc::msg_send(...)]")
};
let mut fn_name = None;
while let Some(tt) = iter.next() {
match tt {
TokenTree::Ident(i) if i.to_string().eq("fn") => {
let Some(TokenTree::Ident(name)) = iter.next() else {
panic!("expect function name");
};
fn_name = Some(name.to_string());
}
_ => {} // panic?
}
}
let Some(fn_name) = fn_name else {
panic!("function name not found");
};
let getter: TokenStream = format!(
"
/// `@selector({extern_name})` but dynamic
/// use this function to check if object responds to selector
fn sel_{fn_name}() -> Option<&'static objc::Sel> {{
unsafe {{ Some(objc::sel_registerName(b\"{extern_name}\\0\".as_ptr())) }}
}}
"
)
.parse()
.unwrap();
let mut func = func;
func.extend(getter.into_iter());
func
}
#[proc_macro_attribute]
pub fn obj_trait(_args: TokenStream, tr: TokenStream) -> TokenStream {
let mut original_trait = tr.clone();
let mut iter = tr.into_iter();
let mut before_trait_name_tokens = vec![];
let mut after_trait_name_tokens = vec![];
let mut trait_name = "".to_string();
let mut expect_trait_name = false;
let mut is_optional = false;
let mut sel = "".to_string();
let mut fn_name; // = "".to_string();
let mut generics = Vec::new();
//let mut fn_args = Vec::new();
let mut fn_args_str; // = "".to_string();
let mut result = Vec::new();
let mut fn_body = "".to_string();
let mut impl_trait_functions = Vec::new();
let mut has_optionals = false;
let mut fn_names = vec![];
while let Some(token) = iter.next() {
let collection = if trait_name.is_empty() {
&mut before_trait_name_tokens
} else {
&mut after_trait_name_tokens
};
match &token {
TokenTree::Group(g) => {
let mut iter = g.stream().into_iter();
while let Some(token) = iter.next() {
match token {
TokenTree::Group(g) => println!("group {g}"),
TokenTree::Ident(i) => {
let str = i.to_string();
if str.eq("fn") {
let Some(TokenTree::Ident(name)) = iter.next() else {
panic!("expect fn name");
};
fn_name = name.to_string();
let args = loop {
let Some(tt) = iter.next() else {
panic!("need more tokens");
};
match tt {
TokenTree::Group(args) => break args,
_ => generics.push(tt),
}
};
fn_args_str = args.to_string();
while let Some(tt) = iter.next() {
match tt {
TokenTree::Punct(ref p) if p.as_char() == ';' => {
result.push(tt);
break;
}
TokenTree::Group(ref g) => {
fn_body = g.to_string();
break;
}
_ => result.push(tt),
}
}
let mut ext = "";
let register_sel = if sel.is_empty() {
"None".to_string()
} else {
ext = "extern \"C\" ";
fn_args_str = fn_args_str.replacen(
"(& self",
"(&self, _cmd: Option<&objc::Sel>",
1,
);
fn_args_str = fn_args_str.replacen(
"(& mut self",
"(&mut self, _cmd: Option<&objc::Sel>",
1,
);
format!("Some(unsafe {{ objc::sel_registerName(b\"{sel}\\0\".as_ptr()) }})")
};
if is_optional && !sel.is_empty() && fn_body.is_empty() {
result.pop(); // remove ;
fn_body = "{ unimplemented!() }".to_string();
}
let ret = if result.is_empty() {
"".to_string()
} else {
TokenStream::from_iter(result.clone().into_iter()).to_string()
};
let gen = if generics.is_empty() {
"".to_string()
} else {
TokenStream::from_iter(generics.clone().into_iter()).to_string()
};
fn_names.push(fn_name.clone());
let impl_fn = format!(
"
{ext}fn impl_{fn_name}{gen}{fn_args_str}{ret} {fn_body}
"
);
impl_trait_functions.push(impl_fn);
if !is_optional {
let impl_sel = format!(
"
fn sel_{fn_name}() -> Option<&'static objc::Sel> {{ {register_sel} }}
"
);
impl_trait_functions.push(impl_sel);
}
is_optional = false;
sel.clear();
fn_name.clear();
fn_body.clear();
fn_args_str.clear();
//fn_args.clear();
result.clear();
}
}
TokenTree::Punct(p) => match p.as_char() {
'#' => {
let TokenTree::Group(g) = iter.next().unwrap() else {
panic!("not a group");
};
match read_objc_attr(g) {
Some(ObjcAttr::Optional) => {
has_optionals = true;
is_optional = true;
}
Some(ObjcAttr::MsgSend(s)) => sel = s,
None => continue,
}
}
_ => panic!("other char {p}"),
},
TokenTree::Literal(l) => println!("lit {l}"),
}
}
}
TokenTree::Ident(i) => {
let str = i.to_string();
if expect_trait_name {
expect_trait_name = false;
trait_name = str;
continue;
}
collection.push(token.clone());
if str == "trait" {
expect_trait_name = true;
}
}
TokenTree::Punct(_) | TokenTree::Literal(_) => collection.push(token),
}
}
let pre = TokenStream::from_iter(before_trait_name_tokens.into_iter()).to_string();
let obj_trait_name = format!("{trait_name}Impl");
//let after = TokenStream::from_iter(after_trait_name_tokens.into_iter()).to_string();
let fns = impl_trait_functions.join("\n");
let add_methods = if has_optionals {
"fn cls_add_methods<O: objc::Obj>(cls: &objc::Class<O>);".to_string() //" { panic!(\"use #[objc::cls_builder]\") }".to_string()
} else {
add_methods_fn(&fn_names).to_string()
};
let code = format!(
"
{pre} {obj_trait_name}: {trait_name} {{
{fns}
{add_methods}
}}
// impl {trait_name} for objc::Any {{}}
"
);
let ts: TokenStream = code.parse().unwrap();
original_trait.extend(ts);
original_trait
}
fn add_methods_fn(fns: &[String]) -> TokenStream {
let mut res = "
fn cls_add_methods<O: objc::Obj>(cls: &objc::Class<O>) {
let cls: &objc::Class<objc::Id> = unsafe { std::mem::transmute(cls) };
"
.to_string();
for f in fns {
let add = format!(
"
if let Some(sel) = Self::sel_{f}() {{
unsafe {{
let imp: extern \"C\" fn() = std::mem::transmute(Self::impl_{f} as *const u8);
objc::class_addMethod(cls, sel, imp, std::ptr::null());
}}
}}
"
);
res.push_str(&add);
}
res.push_str("\n}");
res.parse().unwrap()
}
#[proc_macro_attribute]
pub fn add_methods(_args: TokenStream, tr_impl: TokenStream) -> TokenStream {
let mut tokens = vec![];
let mut iter = tr_impl.clone().into_iter();
let mut fns = vec![];
while let Some(tt) = iter.next() {
match tt {
TokenTree::Group(g) => {
let mut body = g.stream().into_iter();
while let Some(tt) = body.next() {
match tt {
TokenTree::Ident(i) if i.to_string().eq("fn") => {
let Some(TokenTree::Ident(f)) = body.next() else {
panic!("expected function name");
};
fns.push(f.to_string().replacen("impl_", "", 1));
}
_ => continue,
}
}
let imp = add_methods_fn(&fns);
let mut stream = g.stream();
stream.extend(imp);
let g = Group::new(g.delimiter(), stream);
tokens.push(TokenTree::Group(g));
}
_ => tokens.push(tt),
}
}
// println!("fns {fns:?}");
TokenStream::from_iter(tokens.into_iter())
}
#[proc_macro_attribute]
pub fn msg_send_debug(sel: TokenStream, func: TokenStream) -> TokenStream {
gen_msg_send(sel, func, false, false, true)
}
#[proc_macro_attribute]
pub fn cls_msg_send(sel: TokenStream, func: TokenStream) -> TokenStream {
gen_msg_send(sel, func, false, true, false)
}
#[proc_macro_attribute]
pub fn cls_msg_send_debug(sel: TokenStream, func: TokenStream) -> TokenStream {
gen_msg_send(sel, func, false, true, true)
}
fn gen_msg_send(
sel: TokenStream,
func: TokenStream,
retain: bool,
class: bool,
debug: bool,
) -> TokenStream {
let extern_name = sel.to_string().replace([' ', '\n'], "");
let _is_init = extern_name.starts_with("init");
let args_count = sel_args_count(sel);
let mut iter = func.into_iter();
let mut pre: Vec<String> = Vec::with_capacity(3);
while let Some(t) = iter.next() {
match t {
TokenTree::Ident(v) => {
let s = v.to_string();
if s == "fn" {
pre.push(s);
break;
} else {
pre.push(s);
}
}
_ => continue,
}
}
let Some(TokenTree::Ident(fn_name)) = iter.next() else {
panic!("foo");
};
let fn_name = fn_name.to_string();
let mut generics = Vec::new();
let args = loop {
let Some(tt) = iter.next() else {
panic!("need more tokens");
};
match tt {
TokenTree::Group(args) => break args,
_ => generics.push(tt),
}
};
let mut gen = TokenStream::from_iter(generics.into_iter()).to_string();
if fn_name.ends_with("_ar") {
if gen.is_empty() {
gen = "<'ar>".to_string();
} else {
gen = gen.replacen('<', "<'ar,", 1);
}
}
let ts = TokenStream::from_iter(iter);
let mut ret = ts.to_string();
let mut ret_full = ts.to_string();
if let Some((a, _)) = ret.split_once("where") {
ret = format!("{a};")
}
assert_eq!(ret.pop().expect(";"), ';');
assert_eq!(ret_full.pop().expect(";"), ';');
let option = ret_full.contains("-> Option");
let fn_args = args.to_string();
if debug {
println!("ret: {ret}");
println!("fn_args: {fn_args}");
}
let vars = get_fn_args(args.stream(), class, debug);
let fn_args_count = vars.len();
if !retain {
assert_eq!(
fn_args_count, args_count,
"left: fn_args_count, right: sel_args_count"
);
}
let pre = pre.join(" ");
let vars = vars.join(", ");
let (mut fn_args, mut call_args) = if fn_args_count == 0 {
let fn_args = fn_args
.replacen("( &", "(id: &", 1)
.replacen("self", "Self", 1);
(fn_args, "sig(self)".to_string())
} else {
let fn_args = fn_args
.replacen('(', "(id:", 1)
.replace("self", "Self, imp: *const std::ffi::c_void");
(fn_args, format!("sig(self, std::ptr::null(), {vars})"))
};
if class {
if fn_args_count == 0 {
fn_args = fn_args.replacen('(', "(cls: *const std::ffi::c_void", 1);
call_args = call_args.replacen(
"sig(self",
"sig(Self::cls() as *const _ as *const std::ffi::c_void",
1,
);
} else {
fn_args = fn_args.replacen(
"(id:",
"(cls: *const std::ffi::c_void, id: *const std::ffi::c_void,",
1,
);
call_args = call_args.replacen(
"sig(self",
"sig(Self::cls() as *const _ as *const std::ffi::c_void",
1,
);
}
}
let flow = if retain {
let mut self_ = "self.".to_string();
if class {
self_ = "Self::".to_string();
}
if option {
format!(
"
#[inline]
{pre} {fn_name}{gen}{args}{ret_full} {{
arc::rar_retain_option({self_}{fn_name}_ar({vars}) )
}}
"
)
} else {
format!(
"
#[inline]
{pre} {fn_name}{gen}{args}{ret_full} {{
arc::rar_retain({self_}{fn_name}_ar({vars}))
}}
"
)
}
} else {
format!(
"
#[inline]
{pre} {fn_name}{gen}{args}{ret_full} {{
extern \"C\" {{
#[link_name = \"objc_msgSend${extern_name}\"]
fn msg_send();
}}
unsafe {{
let fn_ptr = msg_send as *const std::ffi::c_void;
let sig: extern \"C\" fn{fn_args} {ret} = std::mem::transmute(fn_ptr);
{call_args}
}}
}}
"
)
};
if debug {
println!("{flow}");
}
flow.parse().unwrap()
}