-
Notifications
You must be signed in to change notification settings - Fork 5
/
lib.rs
executable file
·764 lines (657 loc) · 23.8 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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
#![deny(missing_docs)]
//! **This crate is not meant to be imported directly by users**.
//! You should import [ocaml-gen](https://crates.io/crates/ocaml-gen) instead.
//!
//! ocaml-gen-derive adds a number of derives to make ocaml-gen easier to use.
//! Refer to the [ocaml-gen](https://o1-labs.github.io/ocaml-gen/ocaml_gen/index.html) documentation.
extern crate proc_macro;
use convert_case::{Case, Casing};
use proc_macro::TokenStream;
use proc_macro2::{Ident, Span};
use quote::quote;
use syn::{
punctuated::Punctuated, Fields, FnArg, GenericParam, PredicateType, ReturnType, TraitBound,
TraitBoundModifier, Type, TypeParamBound, TypePath, WherePredicate,
};
/// A macro to create OCaml bindings for a function that uses [`#[ocaml::func]`](https://docs.rs/ocaml/latest/ocaml/attr.func.html)
///
/// Note that this macro must be placed first (before `#[ocaml::func]`).
/// For example:
///
/// ```
/// #[ocaml_gen::func]
/// #[ocaml::func]
/// pub fn something(arg1: String) {
/// //...
/// }
/// ```
///
#[proc_macro_attribute]
pub fn func(_attribute: TokenStream, item: TokenStream) -> TokenStream {
let item_fn: syn::ItemFn = syn::parse(item).expect("couldn't parse item");
let rust_name = &item_fn.sig.ident;
let inputs = &item_fn.sig.inputs;
let output = &item_fn.sig.output;
let ocaml_name = rust_ident_to_ocaml(&rust_name.to_string());
let inputs: Vec<_> = inputs
.into_iter()
.filter_map(|i| match i {
FnArg::Typed(t) => Some(&t.ty),
FnArg::Receiver(_) => None,
})
.collect();
let return_value = match output {
ReturnType::Default => quote! { "unit".to_string() },
ReturnType::Type(_, t) => quote! {
<#t as ::ocaml_gen::OCamlDesc>::ocaml_desc(env, &[])
},
};
let rust_name_str = rust_name.to_string();
let fn_name = Ident::new(&format!("{rust_name}_to_ocaml"), Span::call_site());
let new_fn = quote! {
pub fn #fn_name(env: &::ocaml_gen::Env, rename: Option<&'static str>) -> String {
// function name
let ocaml_name = rename.unwrap_or(#ocaml_name);
// arguments
let mut args: Vec<String> = vec![];
#(
args.push(
<#inputs as ::ocaml_gen::OCamlDesc>::ocaml_desc(env, &[])
);
);*
let inputs = if args.len() == 0 {
"unit".to_string()
} else {
args.join(" -> ")
};
// return value
let return_value = #return_value;
if args.len() <= 5 {
format!(
"external {} : {} -> {} = \"{}\"",
ocaml_name, inputs, return_value, #rust_name_str
)
}
// !! This is not the best way to handle this case. This will break
// if ocaml-rs changes its code generator.
else {
format!(
"external {} : {} -> {} = \"{}_bytecode\" \"{}\"",
ocaml_name, inputs, return_value, #rust_name_str, #rust_name_str
)
}
// return the binding
}
};
let gen = quote! {
// don't forget to generate code that also contains the old function :)
#item_fn
#new_fn
};
gen.into()
}
//
// Enum
//
/// The Enum derive macro.
/// It generates implementations of `ToOCaml` and `OCamlBinding` on an enum type.
/// The type must implement [`ocaml::IntoValue`](https://docs.rs/ocaml/latest/ocaml/trait.IntoValue.html)
/// and [`ocaml::FromValue`](https://docs.rs/ocaml/latest/ocaml/trait.FromValue.html)
/// For example:
///
/// ```
/// use ocaml_gen::Enum;
///
/// #[Enum]
/// enum MyType {
/// // ...
/// }
/// ```
///
#[proc_macro_derive(Enum)]
pub fn derive_ocaml_enum(item: TokenStream) -> TokenStream {
let item_enum: syn::ItemEnum = syn::parse(item).expect("only enum are supported with Enum");
//
// ocaml_desc
//
let generics_ident: Vec<_> = item_enum
.generics
.params
.iter()
.filter_map(|g| match g {
GenericParam::Type(t) => Some(&t.ident),
_ => None,
})
.collect();
let name_str = item_enum.ident.to_string();
let ocaml_desc = quote! {
fn ocaml_desc(env: &::ocaml_gen::Env, generics: &[&str]) -> String {
// get type parameters
let mut generics_ocaml: Vec<String> = vec![];
#(
generics_ocaml.push(
<#generics_ident as ::ocaml_gen::OCamlDesc>::ocaml_desc(env, generics)
);
);*
// get name
let type_id = <Self as ::ocaml_gen::OCamlDesc>::unique_id();
let (name, aliased) = env.get_type(type_id, #name_str);
// return the type description in OCaml
if generics_ocaml.is_empty() || aliased {
name.to_string()
} else {
format!("({}) {}", generics_ocaml.join(", "), name)
}
}
};
//
// unique_id
//
let unique_id = quote! {
fn unique_id() -> u128 {
::ocaml_gen::const_random!(u128)
}
};
//
// ocaml_binding
//
let generics_str: Vec<String> = item_enum
.generics
.params
.iter()
.filter_map(|g| match g {
GenericParam::Type(t) => Some(t.ident.to_string().to_case(Case::Snake)),
_ => None,
})
.collect();
let body = {
// we want to resolve types at runtime (to do relocation/renaming)
// to do that, the macro builds a list of types that doesn't need to be resolved (generic types), as well as a list of types to resolve
// at runtime, both list are consumed to generate the OCaml binding
// list of variants
let mut variants: Vec<String> = vec![];
// list of types associated to each variant. It is punctured:
// an item can appear as "#" to indicate that it needs to be resolved at run-time
let mut punctured_types: Vec<Vec<String>> = vec![];
// list of types that will need to be resolved at run-time
let mut fields_to_call = vec![];
// go through each variant to build these lists
for variant in &item_enum.variants {
let name = &variant.ident;
variants.push(name.to_string());
let mut types = vec![];
match &variant.fields {
Fields::Named(_f) => panic!("named types not implemented"),
Fields::Unnamed(fields) => {
for field in &fields.unnamed {
if let Some(ty) = is_generic(&generics_str, &field.ty) {
types.push(format!("'{}", ty.to_case(Case::Snake)));
} else {
types.push("#".to_string());
fields_to_call.push(&field.ty);
}
}
}
Fields::Unit => (),
};
punctured_types.push(types);
}
fields_to_call.reverse();
quote! {
let mut generics_ocaml: Vec<String> = vec![];
let variants: Vec<&str> = vec![
#(#variants),*
];
let punctured_types: Vec<Vec<&str>> = vec![
#(
vec![
#(#punctured_types),*
]
),*
];
let mut missing_types: Vec<String> = vec![];
#(
missing_types.push(
<#fields_to_call as ::ocaml_gen::OCamlDesc>::ocaml_desc(env, &global_generics)
);
);*
for (name, types) in variants.into_iter().zip(punctured_types) {
let mut fields = vec![];
for ty in types {
if ty != "#" {
fields.push(ty.to_string());
} else {
let ty = missing_types
.pop()
.expect("number of types to call should match number of missing types");
fields.push(ty);
}
}
// example: type 'a t = Infinity | Finite of 'a
let tag = if fields.is_empty() {
name.to_string()
} else {
format!("{} of {}", name, fields.join(" * "))
};
generics_ocaml.push(tag);
}
format!("{}", generics_ocaml.join(" | "))
}
};
let ocaml_name = rust_ident_to_ocaml(&name_str);
let ocaml_binding = quote! {
fn ocaml_binding(
env: &mut ::ocaml_gen::Env,
rename: Option<&'static str>,
new_type: bool,
) -> String {
// register the new type
if new_type {
let ty_name = rename.unwrap_or(#ocaml_name);
let ty_id = <Self as ::ocaml_gen::OCamlDesc>::unique_id();
env.new_type(ty_id, ty_name);
}
let global_generics: Vec<&str> = vec![#(#generics_str),*];
let generics_ocaml = {
#body
};
let name = <Self as ::ocaml_gen::OCamlDesc>::ocaml_desc(env, &global_generics);
if new_type {
format!("type nonrec {} = {}", name, generics_ocaml)
} else {
format!("type nonrec {} = {}", rename.expect("type alias must have a name"), name)
}
}
};
//
// Implementations
//
let (impl_generics, ty_generics, _where_clause) = item_enum.generics.split_for_impl();
// add OCamlDesc bounds to the generic types
let mut extended_generics = item_enum.generics.clone();
extended_generics.make_where_clause();
let mut extended_where_clause = extended_generics.where_clause.unwrap();
let path: syn::Path = syn::parse_str("::ocaml_gen::OCamlDesc").unwrap();
let impl_ocaml_desc = TraitBound {
paren_token: None,
modifier: TraitBoundModifier::None,
lifetimes: None,
path,
};
for generic in &item_enum.generics.params {
if let GenericParam::Type(t) = generic {
let mut bounds = Punctuated::<TypeParamBound, syn::token::Add>::new();
bounds.push(TypeParamBound::Trait(impl_ocaml_desc.clone()));
let path: syn::Path = syn::parse_str(&t.ident.to_string()).unwrap();
let bounded_ty = Type::Path(TypePath { qself: None, path });
extended_where_clause
.predicates
.push(WherePredicate::Type(PredicateType {
lifetimes: None,
bounded_ty,
colon_token: syn::token::Colon {
spans: [Span::call_site()],
},
bounds,
}));
};
}
// generate implementations for OCamlDesc and OCamlBinding
let name = item_enum.ident;
let gen = quote! {
impl #impl_generics ::ocaml_gen::OCamlDesc for #name #ty_generics #extended_where_clause {
#ocaml_desc
#unique_id
}
impl #impl_generics ::ocaml_gen::OCamlBinding for #name #ty_generics #extended_where_clause {
#ocaml_binding
}
};
gen.into()
}
//
// Struct
//
/// The Struct derive macro.
/// It generates implementations of `ToOCaml` and `OCamlBinding` on a struct.
/// The type must implement [`ocaml::IntoValue`](https://docs.rs/ocaml/latest/ocaml/trait.IntoValue.html)
/// and [`ocaml::FromValue`](https://docs.rs/ocaml/latest/ocaml/trait.FromValue.html)
///
/// For example:
///
/// ```
/// #[ocaml_gen::Struct]
/// struct MyType {
/// // ...
/// }
/// ```
///
#[proc_macro_derive(Struct)]
pub fn derive_ocaml_gen(item: TokenStream) -> TokenStream {
let item_struct: syn::ItemStruct =
syn::parse(item).expect("only structs are supported with Struct");
let name = &item_struct.ident;
let generics = &item_struct.generics.params;
let fields = &item_struct.fields;
//
// ocaml_desc
//
let generics_ident: Vec<_> = generics
.iter()
.filter_map(|g| match g {
GenericParam::Type(t) => Some(&t.ident),
_ => None,
})
.collect();
let name_str = name.to_string();
let ocaml_desc = quote! {
fn ocaml_desc(env: &::ocaml_gen::Env, generics: &[&str]) -> String {
// get type parameters
let mut generics_ocaml: Vec<String> = vec![];
#(
generics_ocaml.push(
<#generics_ident as ::ocaml_gen::OCamlDesc>::ocaml_desc(env, generics)
);
);*
// get name
let type_id = <Self as ::ocaml_gen::OCamlDesc>::unique_id();
let (name, aliased) = env.get_type(type_id, #name_str);
// return the type description in OCaml
if generics_ocaml.is_empty() || aliased {
name.to_string()
} else {
format!("({}) {}", generics_ocaml.join(", "), name)
}
}
};
//
// unique_id
//
let unique_id = quote! {
fn unique_id() -> u128 {
::ocaml_gen::const_random!(u128)
}
};
//
// ocaml_binding
//
let generics_str: Vec<String> = generics
.iter()
.filter_map(|g| match g {
GenericParam::Type(t) => Some(t.ident.to_string().to_case(Case::Snake)),
_ => None,
})
.collect();
let body = match fields {
Fields::Named(fields) => {
let mut punctured_generics_name: Vec<String> = vec![];
let mut punctured_generics_type: Vec<String> = vec![];
let mut fields_to_call = vec![];
for field in &fields.named {
let name = field.ident.as_ref().expect("a named field has an ident");
punctured_generics_name.push(name.to_string());
if let Some(ty) = is_generic(&generics_str, &field.ty) {
punctured_generics_type.push(format!("'{}", ty.to_case(Case::Snake)));
} else {
punctured_generics_type.push("#".to_string());
fields_to_call.push(&field.ty);
}
}
fields_to_call.reverse();
quote! {
let mut generics_ocaml: Vec<String> = vec![];
let punctured_generics_name: Vec<&str> = vec![
#(#punctured_generics_name),*
];
let punctured_generics_type: Vec<&str> = vec![
#(#punctured_generics_type),*
];
let mut missing_types: Vec<String> = vec![];
#(
missing_types.push(
<#fields_to_call as ::ocaml_gen::OCamlDesc>::ocaml_desc(env, &global_generics)
);
);*
for (name, ty) in punctured_generics_name.into_iter().zip(punctured_generics_type) {
if ty != "#" {
generics_ocaml.push(
format!("{}: {}", name, ty.to_string())
);
} else {
let ty = missing_types
.pop()
.expect("number of types to call should match number of missing types");
generics_ocaml.push(
format!("{}: {}", name, ty)
);
}
}
// See https://v2.ocaml.org/manual/attributes.html for boxing/unboxing
if generics_ocaml.len() == 1 {
// Tell the OCaml compiler to not unbox records of size 1
format!("{{ {} }} [@@boxed]", generics_ocaml[0])
} else {
// OCaml does not unbox records with 2+ fields, so the annotation is unnecessary
format!("{{ {} }}", generics_ocaml.join("; "))
}
}
}
Fields::Unnamed(fields) => {
let mut punctured_generics: Vec<String> = vec![];
let mut fields_to_call = vec![];
for field in &fields.unnamed {
if let Some(ident) = is_generic(&generics_str, &field.ty) {
punctured_generics.push(format!("'{}", ident.to_case(Case::Snake)));
} else {
punctured_generics.push("#".to_string());
fields_to_call.push(&field.ty);
}
}
fields_to_call.reverse();
quote! {
let mut generics_ocaml: Vec<String> = vec![];
let punctured_generics: Vec<&str> = vec![
#(#punctured_generics),*
];
let mut missing_types: Vec<String> = vec![];
#(
missing_types.push(<#fields_to_call as ::ocaml_gen::OCamlDesc>::ocaml_desc(env, &global_generics));
);*
for ty in punctured_generics {
if ty != "#" {
generics_ocaml.push(ty.to_string());
} else {
let ident = missing_types
.pop()
.expect("number of types to call should match number of missing types");
generics_ocaml.push(ident);
}
}
// when there's a single element,
// this will produce something like this:
//
// ```
// type ('field) scalar_challenge = { inner: 'field } [@@boxed]
// ```
if generics_ocaml.len() == 1 {
format!("{{ inner: {} }} [@@boxed]", generics_ocaml[0])
} else {
generics_ocaml.join(" * ")
}
}
}
Fields::Unit => panic!("only named, and unnamed field supported"),
};
let ocaml_name = rust_ident_to_ocaml(&name_str);
let ocaml_binding = quote! {
fn ocaml_binding(
env: &mut ::ocaml_gen::Env,
rename: Option<&'static str>,
new_type: bool,
) -> String {
// register the new type
let ty_id = <Self as ::ocaml_gen::OCamlDesc>::unique_id();
if new_type {
let ty_name = rename.unwrap_or(#ocaml_name);
env.new_type(ty_id, ty_name);
}
let global_generics: Vec<&str> = vec![#(#generics_str),*];
let generics_ocaml = {
#body
};
let name = <Self as ::ocaml_gen::OCamlDesc>::ocaml_desc(env, &global_generics);
if new_type {
format!("type nonrec {} = {}", name, generics_ocaml)
} else {
// add the alias
let ty_name = rename.expect("bug in ocaml-gen: rename should be Some");
env.add_alias(ty_id, ty_name);
format!("type nonrec {} = {}", ty_name, name)
}
}
};
//
// Implementations
//
let (impl_generics, ty_generics, _where_clause) = item_struct.generics.split_for_impl();
// add OCamlDesc bounds to the generic types
let mut extended_generics = item_struct.generics.clone();
extended_generics.make_where_clause();
let mut extended_where_clause = extended_generics.where_clause.unwrap();
let path: syn::Path = syn::parse_str("::ocaml_gen::OCamlDesc").unwrap();
let impl_ocaml_desc = TraitBound {
paren_token: None,
modifier: TraitBoundModifier::None,
lifetimes: None,
path,
};
for generic in generics {
if let GenericParam::Type(t) = generic {
let mut bounds = Punctuated::<TypeParamBound, syn::token::Add>::new();
bounds.push(TypeParamBound::Trait(impl_ocaml_desc.clone()));
let path: syn::Path = syn::parse_str(&t.ident.to_string()).unwrap();
let bounded_ty = Type::Path(TypePath { qself: None, path });
extended_where_clause
.predicates
.push(WherePredicate::Type(PredicateType {
lifetimes: None,
bounded_ty,
colon_token: syn::token::Colon {
spans: [Span::call_site()],
},
bounds,
}));
};
}
// generate implementations for OCamlDesc and OCamlBinding
let gen = quote! {
impl #impl_generics ::ocaml_gen::OCamlDesc for #name #ty_generics #extended_where_clause {
#ocaml_desc
#unique_id
}
impl #impl_generics ::ocaml_gen::OCamlBinding for #name #ty_generics #extended_where_clause {
#ocaml_binding
}
};
gen.into()
}
//
// almost same code for custom types
//
/// Derives implementations for `OCamlDesc` and `OCamlBinding` on a custom type
/// For example:
///
/// ```
/// use ocaml_gen::CustomType;
///
/// #[CustomType]
/// struct MyCustomType {
/// // ...
/// }
/// ```
///
#[proc_macro_derive(CustomType)]
pub fn derive_ocaml_custom(item: TokenStream) -> TokenStream {
let item_struct: syn::ItemStruct =
syn::parse(item).expect("only structs are supported at the moment");
let name = &item_struct.ident;
//
// ocaml_desc
//
let name_str = name.to_string();
let ocaml_desc = quote! {
fn ocaml_desc(env: &::ocaml_gen::Env, _generics: &[&str]) -> String {
let type_id = <Self as ::ocaml_gen::OCamlDesc>::unique_id();
env.get_type(type_id, #name_str).0
}
};
//
// unique_id
//
let unique_id = quote! {
fn unique_id() -> u128 {
::ocaml_gen::const_random!(u128)
}
};
//
// ocaml_binding
//
let ocaml_name = rust_ident_to_ocaml(&name_str);
let ocaml_binding = quote! {
fn ocaml_binding(
env: &mut ::ocaml_gen::Env,
rename: Option<&'static str>,
new_type: bool,
) -> String {
// register the new type
let ty_id = <Self as ::ocaml_gen::OCamlDesc>::unique_id();
if new_type {
let ty_name = rename.unwrap_or(#ocaml_name);
env.new_type(ty_id, ty_name);
}
let name = <Self as ::ocaml_gen::OCamlDesc>::ocaml_desc(env, &[]);
if new_type {
format!("type nonrec {}", name)
} else {
// add the alias
let ty_name = rename.expect("bug in ocaml-gen: rename should be Some");
env.add_alias(ty_id, ty_name);
format!("type nonrec {} = {}", ty_name, name)
}
}
};
//
// Implementations
//
let (impl_generics, ty_generics, where_clause) = item_struct.generics.split_for_impl();
// generate implementations for OCamlDesc and OCamlBinding
let gen = quote! {
impl #impl_generics ::ocaml_gen::OCamlDesc for #name #ty_generics #where_clause {
#ocaml_desc
#unique_id
}
impl #impl_generics ::ocaml_gen::OCamlBinding for #name #ty_generics #where_clause {
#ocaml_binding
}
};
gen.into()
}
//
// helpers
//
/// OCaml identifiers are `snake_case`, whereas Rust identifiers are CamelCase
fn rust_ident_to_ocaml(ident: &str) -> String {
ident.to_case(Case::Snake)
}
/// return true if the type passed is a generic
fn is_generic(generics: &[String], ty: &Type) -> Option<String> {
if let Type::Path(p) = ty {
if let Some(ident) = p.path.get_ident() {
let ident = ident.to_string();
if generics.contains(&ident) {
return Some(ident);
}
}
}
None
}