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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
//! `pdf_derive` provides a proc macro to derive the Object trait from the `pdf` crate.
//! # Usage
//! There are several ways to derive Object on a struct or enum:
//! ## 1. Struct from PDF Dictionary
//!
//! A lot of dictionary types defined in the PDF 1.7 reference have a finite amount of possible
//! fields. Each of these are usually either required or optional. The latter is achieved by using
//! a `Option<T>` or `Vec<T>` as type of a field.
//!
//! Usually, dictionary types
//! require that the entry `/Type` is some specific string. By default, `pdf_derive` assumes that
//! this should equal the name of the input struct. This can be overridden by setting the `Type`
//! attribute equal to either the expected value of the `/Type` entry, or to `false` in order to
//! omit the type check completly.
//!
//! Check similar to that of `/Type` can also be specified in the same manner. (but the `Type`
//! attribute is special because it accepts a bool).
//!
//! Examples:
//!
//! ```ignore
//! #[derive(Object)]
//! #[pdf(Type="XObject", Subtype="Image")]
//! /// A variant of XObject
//! pub struct ImageDictionary {
//!     #[pdf(key="Width")]
//!     width: i32,
//!     #[pdf(key="Height")]
//!     height: i32,
//!     // [...]
//! }
//! ```
//!
//! This enforces that the dictionary's `/Type` entry is present and equals `/XObject`, and that the
//! `/Subtype` entry is present and equals `/Image`.
//!
//! Each field in the struct needs to implement `Object`. Implementation is provided already for
//! common types like i32, f32, usize, bool, String (from Primitive::Name), Option<T> and Vec<T>.
//! The two latter are initialized to default if the entry isn't found in the input dictionary.
//! Option<T> is therefore frequently used for fields that are optional according to the PDF
//! reference. Vec<T> can also be used for optional fields that can also be arrays (there are quite
//! a few of those in the PDF specs - one or many). However, as stated, it accepts absense of the
//! entry, so **required** fields of type array aren't yet facilitated for.
//!
//! Lastly, for each field, it's possible to define a default value by setting the `default`
//! attribute to a string that can parse as Rust code.
//!
//! Example:
//!
//! ```ignore
//! #[derive(Object)]
//! #[pdf(Type = "XRef")]
//! pub struct XRefInfo {
//!     #[pdf(key = "Filter")]
//!     filter: Vec<StreamFilter>,
//!     #[pdf(key = "Size")]
//!     pub size: i32,
//!     #[pdf(key = "Index", default = "vec![0, size]")]
//!     pub index: Vec<i32>,
//!     // [...]
//! }
//! ```
//!
//!
//! ## 2. Struct from PDF Stream
//! PDF Streams consist of a stream dictionary along with the stream itself. It is assumed that all
//! structs that want to derive Object where the primitive it  converts from is a stream,
//! have a field `info: T`, where `T: Object`, and a field `data: Vec<u8>`.
//!
//! Deriving an Object that converts from Primitive::Stream, the flag `is_stream` is required in
//! the proc macro attributes.
//!
//! ## 3. Enum from PDF Name
//! Example:
//!
//! ```ignore
//! #[derive(Object, Debug)]
//! pub enum StreamFilter {
//!     ASCIIHexDecode,
//!     ASCII85Decode,
//!     LZWDecode,
//!     FlateDecode,
//!     JPXDecode,
//!     DCTDecode,
//! }
//! ```
//!
//! In this case, `StreamFilter::from_primitive(primitive)` will return Ok(_) only if the primitive
//! is `Primitive::Name` and matches one of the enum variants
#![recursion_limit="128"]

extern crate proc_macro;
extern crate syn;
#[macro_use]
extern crate quote;

use proc_macro::{TokenStream};
use proc_macro2::{TokenStream as TokenStream2, Span};
use syn::{*, punctuated::Punctuated, token::Where};
type SynStream = TokenStream2;

// Debugging:
/*
use std::fs::{OpenOptions};
use std::io::Write;
*/






#[proc_macro_derive(Object, attributes(pdf))]
pub fn object(input: TokenStream) -> TokenStream {
    let ast = parse_macro_input!(input as DeriveInput);

    // Build the impl
    impl_object(&ast)
}

#[proc_macro_derive(ObjectWrite, attributes(pdf))]
pub fn objectwrite(input: TokenStream) -> TokenStream {
    let ast = parse_macro_input!(input as DeriveInput);

    // Build the impl
    impl_objectwrite(&ast)
}

#[proc_macro_derive(DeepClone, attributes(pdf))]
pub fn deepclone(input: TokenStream) -> TokenStream {
    let ast = parse_macro_input!(input as DeriveInput);

    // Build the impl
    impl_deepclone(&ast)
}


#[derive(Default)]
struct FieldAttrs {
    key: Option<LitStr>,
    default: Option<LitStr>,
    name: Option<LitStr>,
    skip: bool,
    other: bool,
    indirect: bool,
}
impl FieldAttrs {
    fn new() -> FieldAttrs {
        FieldAttrs {
            key: None,
            default: None,
            name: None,
            skip: false,
            other: false,
            indirect: false,
        }
    }
    fn key(&self) -> &LitStr {
        self.key.as_ref().expect("no 'key' in field attributes")
    }
    fn default(&self) -> Option<Expr> {
        self.default.as_ref().map(|s| parse_str(&s.value()).expect("can't parse `default` as EXPR"))
    }
    fn parse(list: &[Attribute]) -> FieldAttrs {
        let mut attrs = FieldAttrs::new();
        for attr in list.iter().filter(|attr| attr.path.is_ident("pdf")) {
            let list = match attr.parse_meta() {
                Ok(Meta::List(list)) => list,
                Ok(_) => panic!("only #[pdf(attrs...)] is allowed"),
                Err(e) => panic!("can't parse meta attributes: {}", e)
            };
            for meta in list.nested.iter() {
                match *meta {
                    NestedMeta::Meta(Meta::NameValue(MetaNameValue { ref path, lit: Lit::Str(ref value), ..})) => {
                        if path.is_ident("key") {
                            attrs.key = Some(value.clone());
                        } else if path.is_ident("default") {
                            attrs.default = Some(value.clone());
                        } else if path.is_ident("name") {
                            attrs.name = Some(value.clone());
                        } else {
                            panic!("unsupported key {}", path.segments.iter().map(|s| s.ident.to_string()).collect::<Vec<String>>().join("::"))
                        }
                    },
                    NestedMeta::Meta(Meta::Path(ref path)) if path.is_ident("skip") => attrs.skip = true,
                    NestedMeta::Meta(Meta::Path(ref path)) if path.is_ident("other") => attrs.other = true,
                    NestedMeta::Meta(Meta::Path(ref path)) if path.is_ident("indirect") => attrs.indirect = true,
                    _ => panic!(r#"Derive error - Supported derive attributes: `key="Key"`, `default="some code", skip, other, indirect`."#)
                }
            }
        }
        attrs
    }
}


/// Just the attributes for the whole struct
#[derive(Default, Debug)]
struct GlobalAttrs {
    /// List of checks to do in the dictionary (LHS is the key, RHS is the expected value)
    checks: Vec<(String, String)>,
    type_name: Option<String>,
    type_required: bool,
    is_stream: bool
}
impl GlobalAttrs {
    /// The PDF type may be explicitly specified as an attribute with type "Type". Else, it is the name
    /// of the struct.
    fn from_ast(ast: &DeriveInput) -> GlobalAttrs {
        let mut attrs = GlobalAttrs::default();

        for attr in ast.attrs.iter().filter(|attr| attr.path.is_ident("pdf")) {
            let list = match attr.parse_meta() {
                Ok(Meta::List(list)) => list,
                Ok(_) => panic!("only #[pdf(attrs...)] is allowed"),
                Err(e) => panic!("can't parse meta attributes: {}", e)
            };

            // Loop through list of attributes
            for meta in list.nested.iter() {
                match *meta {
                    NestedMeta::Meta(Meta::NameValue(MetaNameValue { ref path, ref lit, ..})) => {
                        if path.is_ident("Type") {
                            match lit {
                                Lit::Str(ref value) => {
                                    let mut value = value.value();
                                    attrs.type_required = if value.ends_with('?') {
                                        value.pop(); // remove '?'
                                        false
                                    } else {
                                        true
                                    };
                                    attrs.type_name = Some(value);
                                },
                                _ => panic!("Value of 'Type' attribute must be a String."),
                            }
                        } else {
                            match lit {
                                Lit::Str(ref value) => attrs.checks.push((path.segments.iter().map(|s| s.ident.to_string()).collect::<Vec<String>>().join("::"), value.value())),
                                _ => panic!("Other checks must have RHS String."),
                            }
                        }
                    },
                    NestedMeta::Meta(Meta::Path(ref path)) if path.is_ident("is_stream") => attrs.is_stream = true,
                    _ => {}
                }
            }
        }

        attrs
    }
}

fn impl_object(ast: &DeriveInput) -> TokenStream {
    let attrs = GlobalAttrs::from_ast(ast);
    match (attrs.is_stream, &ast.data) {
        (true, Data::Struct(ref data)) => impl_object_for_stream(ast, &data.fields).into(),
        (false, Data::Struct(ref data)) => impl_object_for_struct(ast, &data.fields).into(),
        (true, Data::Enum(ref variants)) => impl_enum_from_stream(ast, variants, &attrs).into(),
        (false, Data::Enum(ref variants)) => impl_object_for_enum(ast, variants).into(),
        (_, _) => unimplemented!()
    }
}
fn impl_objectwrite(ast: &DeriveInput) -> TokenStream {
    let attrs = GlobalAttrs::from_ast(ast);
    match (attrs.is_stream, &ast.data) {
        (false, Data::Struct(ref data)) => impl_objectwrite_for_struct(ast, &data.fields).into(),
        (false, Data::Enum(ref variants)) => impl_objectwrite_for_enum(ast, variants).into(),
        (_, _) => unimplemented!()
    }
}
fn impl_deepclone(ast: &DeriveInput) -> TokenStream {
    let attrs = GlobalAttrs::from_ast(ast);
    match &ast.data {
        Data::Struct(ref data) => impl_deepclone_for_struct(ast, &data.fields).into(),
        Data::Enum(ref variants) => impl_deepclone_for_enum(ast, variants).into(),
        _ => unimplemented!()
    }
}

fn enum_pairs(ast: &DeriveInput, data: &DataEnum) -> (Vec<(String, TokenStream2)>, Option<TokenStream2>) {
    let id = &ast.ident;

    let mut pairs = Vec::with_capacity(data.variants.len());
    let mut other = None;

    for var in data.variants.iter() {
        let attrs = FieldAttrs::parse(&var.attrs);
        let var_ident = &var.ident;
        let name = attrs
            .name
            .map(|lit| lit.value())
            .unwrap_or_else(|| var_ident.to_string());
        if attrs.other {
            assert!(other.is_none(), "only one 'other' variant is allowed in a name enum");
            
            match &var.fields {
                Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {}
                _ => {
                    panic!(
                        "the 'other' variant in a name enum should have exactly one unnamed field",
                    );
                }
            }
            other = Some(quote! { #id::#var_ident });
        } else {
            pairs.push((name, quote! { #id::#var_ident }));
        }
    }

    (pairs, other)
}


/// Accepts Name to construct enum
fn impl_object_for_enum(ast: &DeriveInput, data: &DataEnum) -> SynStream {
    let id = &ast.ident;
    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();

    let int_count = data.variants.iter().filter(|var| var.discriminant.is_some()).count();
    if int_count > 0 {
        assert_eq!(int_count, data.variants.len(), "either none or all variants can have a descriminant");

        let parts = data.variants.iter().map(|var| {
            if let Some((_, ref expr)) = var.discriminant {
                let var_ident = &var.ident;
                let pat = Pat::Lit(PatLit { expr: Box::new(expr.clone()), attrs: vec![] });
                quote! {
                    #pat => Ok(#id::#var_ident)
                }
            } else {
                panic!()
            }
        });

        quote! {
            impl #impl_generics pdf::object::Object for #id #ty_generics #where_clause {
                fn from_primitive(p: pdf::primitive::Primitive, _resolve: &impl pdf::object::Resolve) -> pdf::error::Result<Self> {
                    match p {
                        pdf::primitive::Primitive::Integer(i) => {
                            match i {
                                #( #parts, )*
                                _ => Err(pdf::error::PdfError::UnknownVariant { id: stringify!(#id), name: i.to_string() })
                            }
                        }
                        _ => Err(pdf::error::PdfError::UnexpectedPrimitive { expected: "Integer", found: p.get_debug_name() }),
                    }
                }
            }
        }
    } else {
        let (pairs, other) = enum_pairs(ast, data);

        let mut parts: Vec<_> = pairs
            .iter()
            .map(|(name, var)| {
                quote! {
                    #name => Ok(#var)
                }
            })
            .collect();

        if let Some(other_tokens) = other {
            parts.push(quote! {
                s => Ok(#other_tokens(s.to_string()))
            });
        } else {
            parts.push(quote! {
                s => Err(pdf::error::PdfError::UnknownVariant { id: stringify!(#id), name: s.to_string() })
            });
        }

        quote! {
            impl #impl_generics pdf::object::Object for #id #ty_generics #where_clause {
                fn from_primitive(p: pdf::primitive::Primitive, _resolve: &impl pdf::object::Resolve) -> pdf::error::Result<Self> {
                    match p {
                        pdf::primitive::Primitive::Name(name) => {
                            match name.as_str() {
                                #( #parts, )*
                            }
                        }
                        _ => Err(pdf::error::PdfError::UnexpectedPrimitive { expected: "Name", found: p.get_debug_name() }),
                    }
                }
            }
        }
    }
}
/// Accepts Name to construct enum
fn impl_objectwrite_for_enum(ast: &DeriveInput, data: &DataEnum) -> SynStream {
    let id = &ast.ident;
    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();

    let int_count = data.variants.iter().filter(|var| var.discriminant.is_some()).count();
    if int_count > 0 {
        assert_eq!(int_count, data.variants.len(), "either none or all variants can have a descriminant");

        let parts = data.variants.iter().map(|var| {
            if let Some((_, ref expr)) = var.discriminant {
                let var_ident = &var.ident;
                quote! {
                    #id::#var_ident => Ok(Primitive::Integer(#expr))
                }
            } else {
                panic!()
            }
        });

        quote! {
            impl #impl_generics pdf::object::ObjectWrite for #id #ty_generics #where_clause {
                fn to_primitive(&self, update: &mut impl pdf::object::Updater) -> Result<Primitive> {
                    match *self {
                        #( #parts, )*
                    }
                }
            }
        }
    } else {
        let (pairs, other) = enum_pairs(ast, data);

        let mut ser_code: Vec<_> = pairs
            .iter()
            .map(|(name, var)| {
                quote! {
                    #var => #name
                }
            })
            .collect();

        if let Some(other_tokens) = other {
            ser_code.push(quote! {
                #other_tokens(ref name) => name.as_str()
            });
        }

        quote! {
            impl #impl_generics pdf::object::ObjectWrite for #id #ty_generics #where_clause {
                fn to_primitive(&self, update: &mut impl pdf::object::Updater) -> Result<Primitive> {
                    let name = match *self {
                        #( #ser_code, )*
                    };
                    
                    Ok(Primitive::Name(name.into()))
                }
            }
        }
    }
}
fn impl_deepclone_for_enum(ast: &DeriveInput, data: &DataEnum) -> SynStream {
    let id = &ast.ident;
    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();

    let parts = data.variants.iter().map(|var| {
        let var_ident = &var.ident;
        match var.fields {
            Fields::Unnamed(ref fields) => {
                let labels: Vec<Ident> = fields.unnamed.iter().enumerate().map(|(i, f)| {
                    Ident::new(&format!("f_{i}"), Span::mixed_site())
                }).collect();
                quote! {
                    #id::#var_ident( #( ref #labels, )* ) => Ok(#id::#var_ident( #( #labels.deep_clone(cloner)? ),* ))
                }
            }
            Fields::Named(ref fields) => {
                let names: Vec<_> = fields.named.iter().map(|f| f.ident.as_ref().unwrap()).collect();
                quote! {
                    #id::#var_ident { #( ref #names ),* } => Ok(#id::#var_ident { #( #names: #names.deep_clone(cloner)? ),* })
                }
            }
            Fields::Unit => {
                quote! {
                    #id::#var_ident => Ok(#id::#var_ident)
                }
            }
        }
    });

    quote! {
        impl #impl_generics pdf::object::DeepClone for #id #ty_generics #where_clause {
            fn deep_clone(&self, cloner: &mut impl pdf::object::Cloner) -> Result<Self> {
                match *self {
                    #( #parts, )*
                }
            }
        }
    }
}

fn impl_enum_from_stream(ast: &DeriveInput, data: &DataEnum, attrs: &GlobalAttrs) -> SynStream {
    let id = &ast.ident;
    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();

    let ty_check = match (&attrs.type_name, attrs.type_required) {
        (Some(ref ty), required) => quote! {
            stream.info.expect(stringify!(#id), "Type", #ty, #required)?;
        },
        (None, _) => quote!{}
    };

    let variants_code: Vec<_> = data.variants.iter().map(|var| {
        let attrs = FieldAttrs::parse(&var.attrs);
        let inner_ty = match var.fields {
            Fields::Unnamed(ref fields) => {
                assert_eq!(fields.unnamed.len(), 1, "all variants in a stream enum have to have exactly one unnamed field");
                fields.unnamed.first().unwrap().ty.clone()
            },
            _ => panic!("all variants in a stream enum have to have exactly one unnamed field")
        };
        let name = attrs.name.map(|lit| lit.value()).unwrap_or_else(|| var.ident.to_string());
        let variant_ident = &var.ident;
        quote! {
            #name => Ok(#id::#variant_ident ( #inner_ty::from_primitive(pdf::primitive::Primitive::Stream(stream), resolve)?))
        }
    }).collect();

    quote! {
        impl #impl_generics pdf::object::Object for #id #ty_generics #where_clause {
            fn from_primitive(p: pdf::primitive::Primitive, resolve: &impl pdf::object::Resolve) -> pdf::error::Result<Self> {
                let mut stream = PdfStream::from_primitive(p, resolve)?;
                #ty_check

                let subty = stream.info.get("Subtype")
                    .ok_or(pdf::error::PdfError::MissingEntry { typ: stringify!(#id), field: "Subtype".into()})?
                    .as_name()?;

                match subty {
                    #( #variants_code, )*
                    s => Err(pdf::error::PdfError::UnknownVariant { id: stringify!(#id), name: s.into() })
                }
            }
        }
    }
}




fn is_option(f: &Field) -> Option<Type> {
    match f.ty {
        Type::Path(ref p) => {
            let first = p.path.segments.first().unwrap();
            match first {
                PathSegment { ident, arguments: PathArguments::AngleBracketed(args) } if ident == "Option" => {
                    match args.args.first().unwrap() {
                        GenericArgument::Type(t) => Some(t.clone()),
                        _ => panic!()
                    }
                }
                _ => None
            }
        }
        _ => None
    }
}

/// Accepts Dictionary to construct a struct
fn impl_object_for_struct(ast: &DeriveInput, fields: &Fields) -> SynStream {
    let id = &ast.ident;
    let mut generics = ast.generics.clone();
    for g in generics.params.iter_mut() {
        if let GenericParam::Type(p) = g {
            p.bounds.push(
                parse_quote!(pdf::object::Object)
            );
        }
    }
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
    let attrs = GlobalAttrs::from_ast(ast);

    ///////////////////////
    let typ = id.to_string();
    let let_parts = fields.iter().map(|field| {
        
        let name = &field.ident;
        let attrs = FieldAttrs::parse(&field.attrs);
        if attrs.skip {
            return quote! {}
        }
        if attrs.other {
            return quote! {
                let #name = dict;
            };
        }

        let key = attrs.key();

        let ty = field.ty.clone();
        if let Some(ref default) = attrs.default() {
            quote! {
                let #name = {
                    let primitive: Option<pdf::primitive::Primitive>
                        = dict.remove(#key);
                    let x: #ty = match primitive {
                        Some(primitive) => <#ty as pdf::object::Object>::from_primitive(primitive, resolve).map_err(|e|
                            pdf::error::PdfError::FromPrimitive {
                                typ: #typ,
                                field: stringify!(#name),
                                source: Box::new(e)
                            })?,
                        None => #default,
                    };
                    x
                };
            }
        } else {
            quote! {
                let #name = {
                    match dict.remove(#key) {
                        Some(primitive) =>
                            match <#ty as pdf::object::Object>::from_primitive(primitive, resolve) {
                                Ok(obj) => obj,
                                Err(e) => return Err(pdf::error::PdfError::FromPrimitive {
                                    typ: stringify!(#ty),
                                    field: stringify!(#name),
                                    source: Box::new(e)
                                })
                            }
                        None =>  // Try to construct T from Primitive::Null
                            match <#ty as pdf::object::Object>::from_primitive(pdf::primitive::Primitive::Null, resolve) {
                                Ok(obj) => obj,
                                Err(_) => return Err(pdf::error::PdfError::MissingEntry {
                                    typ: stringify!(#ty),
                                    field: String::from(stringify!(#name)),
                                })
                            },
                    }
                    // ^ By using Primitive::Null when we don't find the key, we allow 'optional'
                    // types like Option and Vec to be constructed from non-existing values
                };
            }
        }
    });

    let field_parts = fields.iter().map(|field| {
        let name = &field.ident;
        quote! { #name: #name, }
    });

    let checks: Vec<_> = attrs.checks.iter().map(|(key, val)|
        quote! {
            dict.expect(#typ, #key, #val, true)?;
        }
    ).collect();

    let ty_check = match (&attrs.type_name, attrs.type_required) {
        (Some(ref ty), required) => quote! {
            dict.expect(#typ, "Type", #ty, #required)?;
        },
        (None, _) => quote!{}
    };

    quote! {
        impl #impl_generics pdf::object::FromDict for #id #ty_generics #where_clause {
            fn from_dict(mut dict: pdf::primitive::Dictionary, resolve: &impl pdf::object::Resolve) -> pdf::error::Result<Self> {
                #ty_check
                #( #checks )*
                #( #let_parts )*
                Ok(#id {
                    #( #field_parts )*
                })
            }
        }
        impl #impl_generics pdf::object::Object for #id #ty_generics #where_clause {
            fn from_primitive(p: pdf::primitive::Primitive, resolve: &impl pdf::object::Resolve) -> pdf::error::Result<Self> {
                let dict = pdf::primitive::Dictionary::from_primitive(p, resolve)?;
                <Self as pdf::object::FromDict>::from_dict(dict, resolve)
            }
        }
    }
}

fn impl_objectwrite_for_struct(ast: &DeriveInput, fields: &Fields) -> SynStream {
    let id = &ast.ident;
    let mut generics = ast.generics.clone();
    for g in generics.params.iter_mut() {
        if let GenericParam::Type(p) = g {
            p.bounds.push(
                parse_quote!(pdf::object::ObjectWrite)
            );
        }
    }
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
    let attrs = GlobalAttrs::from_ast(ast);

    let parts: Vec<_> = fields.iter()
    .map(|field| {
        (field.ident.clone(), FieldAttrs::parse(&field.attrs), is_option(field))
    }).collect();

    let fields_ser = parts.iter()
    .map( |(field, attrs, _opt)|
        if attrs.skip | attrs.other {
            quote!()
        } else {
            let key = attrs.key();
            let tr = if attrs.indirect {
                quote! {
                    match val {
                       pdf::primitive::Primitive::Reference(r) => val,
                       p => updater.create(p)?.into(),
                    }
                }
            } else {
                quote! { val }
            };

            quote! {
                let val = pdf::object::ObjectWrite::to_primitive(&self.#field, updater)?;
                if !matches!(val, pdf::primitive::Primitive::Null) {
                    let val2 = #tr;
                    dict.insert(#key, val2);
                }
            }
        }
    );
    let checks_code = attrs.checks.iter().map(|(key, val)|
        quote! {
            dict.insert(#key, pdf::primitive::Primitive::Name(#val.into()));
        }
    );
    let pdf_type = match attrs.type_name {
        Some(ref name) => quote! {
            dict.insert("Type", pdf::primitive::Primitive::Name(#name.into()));
        },
        None => quote! {}
    };

    quote! {
        impl #impl_generics pdf::object::ObjectWrite for #id #ty_generics #where_clause {
            fn to_primitive(&self, update: &mut impl pdf::object::Updater) -> Result<pdf::primitive::Primitive> {
                pdf::object::ToDict::to_dict(self, update).map(pdf::primitive::Primitive::Dictionary)
            }
        }
        impl #impl_generics pdf::object::ToDict for #id #ty_generics #where_clause {
            fn to_dict(&self, updater: &mut impl pdf::object::Updater) -> Result<pdf::primitive::Dictionary> {
                let mut dict = pdf::primitive::Dictionary::new();
                #pdf_type
                #( #checks_code )*
                #(#fields_ser)*
                Ok(dict)
            }
        }
    }
}
fn impl_deepclone_for_struct(ast: &DeriveInput, fields: &Fields) -> SynStream {
    let id = &ast.ident;
    let mut generics = ast.generics.clone();
    for g in generics.params.iter_mut() {
        if let GenericParam::Type(p) = g {
            p.bounds.push(
                parse_quote!(pdf::object::DeepClone)
            );
        }
    }
    let (impl_generics, mut ty_generics, where_clause) = generics.split_for_impl();

    let parts: Vec<_> = fields.iter()
    .map(|field| {
        (field.ident.clone(), is_option(field))
    }).collect();

    let field_parts = parts.iter()
    .map( |(field, _opt)|
        {
            quote! {
                #field: self.#field.deep_clone(cloner)?,
            }
        }
    );

    quote! {
        impl #impl_generics pdf::object::DeepClone for #id #ty_generics #where_clause {
            fn deep_clone(&self, cloner: &mut impl pdf::object::Cloner) -> Result<Self> {
                Ok(#id {
                    #( #field_parts )*
                })
            }
        }
    }
}

/// Note: must have info and dict (TODO explain in docs)
fn impl_object_for_stream(ast: &DeriveInput, fields: &Fields) -> SynStream {
    let id = &ast.ident;
    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();

    let info_ty = fields.iter()
    .filter_map(|field| {
        if let Some(ident) = field.ident.as_ref() {
            if ident == "info" {
                Some(field.ty.clone())
            } else {
                None
            }
        } else {
            None
        }
    }).next().unwrap();

    quote! {
        impl #impl_generics pdf::object::Object for #id #ty_generics #where_clause {
            fn from_primitive(p: pdf::primitive::Primitive, resolve: &impl pdf::object::Resolve) -> pdf::error::Result<Self> {
                let pdf::primitive::PdfStream {info, data}
                    = p.to_stream(resolve)?;

                Ok(#id {
                    info: <#info_ty as pdf::object::Object>::from_primitive(pdf::primitive::Primitive::Dictionary (info), resolve)?,
                    data: data,
                })
            }
        }
    }
}