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
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
//! This library contains a procedural macro that reads a GraphQL schema file, and generates the
//! corresponding [Juniper](https://crates.io/crates/juniper) [macro calls]. This means you can
//! have a real schema file and be guaranteed that it matches your Rust implementation. It also
//! removes most of the boilerplate involved in using Juniper.
//!
//! [macro calls]: https://graphql-rust.github.io/types/objects/complex_fields.html
//!
//! # Table of contents
//!
//! - [Example](#example)
//! - [Example web app](#example-web-app)
//! - [Customizing ownership](#customizing-ownership)
//! - [GraphQL features](#graphql-features)
//!     - [The `ID` type](#the-id-type)
//!     - [Custom scalar types](#custom-scalar-types)
//!     - [Special case scalars](#special-case-scalars)
//!     - [Interfaces](#interfaces)
//!     - [Union types](#union-types)
//!     - [Input objects](#input-objects)
//!     - [Enumeration types](#enumeration-types)
//!     - [Default argument values](#default-argument-values)
//! - [GraphQL to Rust types](#graphql-to-rust-types)
//! - [Query trails](#query-trails)
//! - [Customizing the error type](#customizing-the-error-type)
//! - [Customizing the context type](#customizing-the-context-type)
//! - [Inspecting the generated code](#inspecting-the-generated-code)
//!
//! # Example
//!
//! Schema:
//!
//! ```graphql
//! schema {
//!   query: Query
//!   mutation: Mutation
//! }
//!
//! type Query {
//!   // The directive makes the return value `FieldResult<String>`
//!   // rather than the default `FieldResult<&String>`
//!   helloWorld(name: String!): String! @juniper(ownership: "owned")
//! }
//!
//! type Mutation {
//!   noop: Boolean!
//! }
//! ```
//!
//! How you could implement that schema:
//!
//! ```
//! #[macro_use]
//! extern crate juniper;
//!
//! use juniper_from_schema::graphql_schema_from_file;
//!
//! // This is the important line
//! graphql_schema_from_file!("tests/schemas/doc_schema.graphql");
//!
//! pub struct Context;
//! impl juniper::Context for Context {}
//!
//! pub struct Query;
//!
//! impl QueryFields for Query {
//!     fn field_hello_world(
//!         &self,
//!         executor: &juniper::Executor<'_, Context>,
//!         name: String,
//!     ) -> juniper::FieldResult<String> {
//!         Ok(format!("Hello, {}!", name))
//!     }
//! }
//!
//! pub struct Mutation;
//!
//! impl MutationFields for Mutation {
//!     fn field_noop(&self, executor: &juniper::Executor<'_, Context>) -> juniper::FieldResult<&bool> {
//!         Ok(&true)
//!     }
//! }
//!
//! fn main() {
//!     let ctx = Context;
//!
//!     let query = "query { helloWorld(name: \"Ferris\") }";
//!
//!     let (result, errors) = juniper::execute(
//!         query,
//!         None,
//!         &Schema::new(Query, Mutation),
//!         &juniper::Variables::new(),
//!         &ctx,
//!     )
//!     .unwrap();
//!
//!     assert_eq!(errors.len(), 0);
//!     assert_eq!(
//!         result
//!             .as_object_value()
//!             .unwrap()
//!             .get_field_value("helloWorld")
//!             .unwrap()
//!             .as_scalar_value::<String>()
//!             .unwrap(),
//!         "Hello, Ferris!",
//!     );
//! }
//! ```
//!
//! And with `graphql_schema_from_file!` expanded your code would look something like this:
//!
//! ```
//! #[macro_use]
//! extern crate juniper;
//!
//! pub struct Context;
//! impl juniper::Context for Context {}
//!
//! pub struct Query;
//!
//! juniper::graphql_object!(Query: Context |&self| {
//!     field hello_world(&executor, name: String) -> juniper::FieldResult<String> {
//!         <Self as QueryFields>::field_hello_world(&self, &executor, name)
//!     }
//! });
//!
//! trait QueryFields {
//!     fn field_hello_world(
//!         &self,
//!         executor: &juniper::Executor<'_, Context>,
//!         name: String,
//!     ) -> juniper::FieldResult<String>;
//! }
//!
//! impl QueryFields for Query {
//!     fn field_hello_world(
//!         &self,
//!         executor: &juniper::Executor<'_, Context>,
//!         name: String,
//!     ) -> juniper::FieldResult<String> {
//!         Ok(format!("Hello, {}!", name))
//!     }
//! }
//!
//! pub struct Mutation;
//!
//! juniper::graphql_object!(Mutation: Context |&self| {
//!     field noop(&executor) -> juniper::FieldResult<&bool> {
//!         <Self as MutationFields>::field_noop(&self, &executor)
//!     }
//! });
//!
//! trait MutationFields {
//!     fn field_noop(&self, executor: &juniper::Executor<'_, Context>) -> juniper::FieldResult<&bool>;
//! }
//!
//! impl MutationFields for Mutation {
//!     fn field_noop(&self, executor: &juniper::Executor<'_, Context>) -> juniper::FieldResult<&bool> {
//!         Ok(&true)
//!     }
//! }
//!
//! type Schema = juniper::RootNode<'static, Query, Mutation>;
//!
//! fn main() {
//!     let ctx = Context;
//!
//!     let query = "query { helloWorld(name: \"Ferris\") }";
//!
//!     let (result, errors) = juniper::execute(
//!         query,
//!         None,
//!         &Schema::new(Query, Mutation),
//!         &juniper::Variables::new(),
//!         &ctx,
//!     )
//!     .unwrap();
//!
//!     assert_eq!(errors.len(), 0);
//!     assert_eq!(
//!         result
//!             .as_object_value()
//!             .unwrap()
//!             .get_field_value("helloWorld")
//!             .unwrap()
//!             .as_scalar_value::<String>()
//!             .unwrap(),
//!         "Hello, Ferris!",
//!     );
//! }
//! ```
//!
//! # Example web app
//!
//! You can find an example of how to use this library together with [Rocket] and [Diesel] to make
//! a GraphQL web app at <https://github.com/davidpdrsn/graphql-app-example> or an example of how
//! to use this library with [Actix] and [Diesel] at
//! <https://github.com/husseinraoouf/graphql-actix-example>.
//!
//! [Rocket]: https://rocket.rs
//! [Diesel]: http://diesel.rs
//! [Actix]: https://actix.rs/
//!
//! # Customizing ownership
//!
//! By default all fields return borrowed values. Specifically the type is
//! `juniper::FieldResult<&'a T>` where `'a` is the lifetime of `self`. This works well for
//! returning data owned by `self` and avoids needless `.clone()` calls you would need if fields
//! returned owned values.
//!
//! However if you need to change the ownership you have to add the directive
//! `@juniper(ownership:)` to the field in the schema.
//!
//! It takes the following arguments:
//!
//! - `@juniper(ownership: "borrowed")`: The return type will be borrowed from `self`
//! (`FieldResult<&T>`).
//! - `@juniper(ownership: "owned")`: The return type will be owned (`FieldResult<T>`).
//! - `@juniper(ownership: "as_ref")`: Only applicable for `Option` and `Vec` return types. Changes
//! the inner type to be borrowed (`FieldResult<Option<&T>>` or `FieldResult<Vec<&T>>`).
//!
//! All field arguments will be owned.
//!
//! # GraphQL features
//!
//! The goal of this library is to support as much of GraphQL as Juniper does.
//!
//! Here is the complete list of features:
//!
//! Supported:
//! - Object types including converting lists and non-nulls to Rust types
//! - Custom scalar types including the `ID` type
//! - Interfaces
//! - Unions
//! - Input objects
//! - Enumeration types
//!
//! Not supported yet:
//! - Subscriptions (currently not supported by Juniper so we're unsure when or if this will happen)
//! - Schema directives (`@deprecated` is supported)
//! - Type extensions
//!
//! ## The `ID` type
//!
//! The `ID` GraphQL type will be generated into [`juniper::ID`].
//!
//! [`juniper::ID`]: https://docs.rs/juniper/latest/juniper/struct.ID.html
//!
//! ## Custom scalar types
//!
//! Custom scalar types will be generated into a newtype wrapper around a `String`. For example:
//!
//! ```graphql
//! scalar Cursor
//! ```
//!
//! Would result in
//!
//! ```
//! pub struct Cursor(pub String);
//! ```
//!
//! ## Special case scalars
//!
//! A couple of scalar names have special meaning. Those are:
//!
//! - `Url` becomes
//! [`url::Url`](https://docs.rs/url/2.1.0/url/struct.Url.html).
//! - `Uuid` becomes
//! [`uuid::Uuid`](https://docs.rs/uuid/0.7.4/uuid/struct.Uuid.html).
//! - `Date` becomes
//! [`chrono::naive::NaiveDate`](https://docs.rs/chrono/0.4.6/chrono/naive/struct.NaiveDate.html).
//! - `DateTime` becomes [`chrono::DateTime<chrono::offset::Utc>`] by default but if defined with
//! `scalar DateTime @juniper(with_time_zone: false)` it will become [`chrono::naive::NaiveDateTime`].
//!
//! Juniper doesn't support [`chrono::Date`](https://docs.rs/chrono/0.4.9/chrono/struct.Date.html)
//! so therefore this library cannot support that either. You can read about Juniper's supported
//! integrations [here](https://docs.rs/juniper/0.13.1/juniper/integrations/index.html).
//!
//! [`chrono::DateTime<chrono::offset::Utc>`]: https://docs.rs/chrono/0.4.9/chrono/struct.DateTime.html
//! [`chrono::naive::NaiveDateTime`]: https://docs.rs/chrono/0.4.9/chrono/naive/struct.NaiveDateTime.html
//!
//! ## Interfaces
//!
//! Juniper has several ways of representing GraphQL interfaces in Rust. They are listed
//! [here](https://graphql-rust.github.io/types/interfaces.html#enums) along with their advantages
//! and disadvantages.
//!
//! For the generated code we use the `enum` pattern because we found it to be the most flexible.
//!
//! Abbreviated example (find [complete example here](https://github.com/davidpdrsn/juniper-from-schema/blob/master/examples/interface.rs)):
//!
//! ```
//! # #[macro_use]
//! # extern crate juniper;
//! # use juniper::*;
//! # use juniper_from_schema::graphql_schema;
//! # fn main() {}
//! # pub struct Context;
//! # impl juniper::Context for Context {}
//! # pub struct Article { id: ID, text: String }
//! # impl ArticleFields for Article {
//! #     fn field_id(
//! #         &self,
//! #         executor: &Executor<'_, Context>,
//! #     ) -> FieldResult<&ID> { unimplemented!() }
//! #     fn field_text(
//! #         &self,
//! #         executor: &Executor<'_, Context>,
//! #     ) -> FieldResult<&String> { unimplemented!() }
//! # }
//! # pub struct Tweet { id: ID, text: String }
//! # impl TweetFields for Tweet {
//! #     fn field_id(
//! #         &self,
//! #         executor: &Executor<'_, Context>,
//! #     ) -> FieldResult<&ID> { unimplemented!() }
//! #     fn field_text(
//! #         &self,
//! #         executor: &Executor<'_, Context>,
//! #     ) -> FieldResult<&String> { unimplemented!() }
//! # }
//! #
//! graphql_schema! {
//!     schema {
//!         query: Query
//!     }
//!
//!     type Query {
//!         search(query: String!): [SearchResult!]! @juniper(ownership: "owned")
//!     }
//!
//!     interface SearchResult {
//!         id: ID!
//!         text: String!
//!     }
//!
//!     type Article implements SearchResult {
//!         id: ID!
//!         text: String!
//!     }
//!
//!     type Tweet implements SearchResult {
//!         id: ID!
//!         text: String!
//!     }
//! }
//!
//! pub struct Query;
//!
//! impl QueryFields for Query {
//!     fn field_search(
//!         &self,
//!         executor: &Executor<'_, Context>,
//!         trail: &QueryTrail<'_, SearchResult, juniper_from_schema::Walked>,
//!         query: String,
//!     ) -> FieldResult<Vec<SearchResult>> {
//!         let article: Article = Article { id: ID::new("1"), text: "Business".to_string() };
//!         let tweet: Tweet = Tweet { id: ID::new("2"), text: "1 weird tip".to_string() };
//!
//!         let posts = vec![
//!             SearchResult::from(article),
//!             SearchResult::from(tweet),
//!         ];
//!
//!         Ok(posts)
//!     }
//! }
//! ```
//!
//! The enum that gets generated has variants for each type that implements the interface and also
//! implements `From<T>` for each type.
//!
//! ## Union types
//!
//! Union types are basically just interfaces so they work in very much the same way.
//!
//! Abbreviated example (find [complete example here](https://github.com/davidpdrsn/juniper-from-schema/blob/master/examples/union_types.rs)):
//!
//! ```
//! # #[macro_use]
//! # extern crate juniper;
//! # use juniper::*;
//! # use juniper_from_schema::graphql_schema;
//! # fn main() {}
//! # pub struct Context;
//! # impl juniper::Context for Context {}
//! # pub struct Article { id: ID, text: String }
//! # impl ArticleFields for Article {
//! #     fn field_id(
//! #         &self,
//! #         executor: &Executor<'_, Context>,
//! #     ) -> FieldResult<&ID> { unimplemented!() }
//! #     fn field_text(
//! #         &self,
//! #         executor: &Executor<'_, Context>,
//! #     ) -> FieldResult<&String> { unimplemented!() }
//! # }
//! # pub struct Tweet { id: ID, text: String }
//! # impl TweetFields for Tweet {
//! #     fn field_id(
//! #         &self,
//! #         executor: &Executor<'_, Context>,
//! #     ) -> FieldResult<&ID> { unimplemented!() }
//! #     fn field_text(
//! #         &self,
//! #         executor: &Executor<'_, Context>,
//! #     ) -> FieldResult<&String> { unimplemented!() }
//! # }
//! #
//! graphql_schema! {
//!     schema {
//!         query: Query
//!     }
//!
//!     type Query {
//!         search(query: String!): [SearchResult!]! @juniper(ownership: "owned")
//!     }
//!
//!     union SearchResult = Article | Tweet
//!
//!     type Article {
//!         id: ID!
//!         text: String!
//!     }
//!
//!     type Tweet {
//!         id: ID!
//!         text: String!
//!     }
//! }
//!
//! pub struct Query;
//!
//! impl QueryFields for Query {
//!     fn field_search(
//!         &self,
//!         executor: &Executor<'_, Context>,
//!         trail: &QueryTrail<'_, SearchResult, juniper_from_schema::Walked>,
//!         query: String,
//!     ) -> FieldResult<Vec<SearchResult>> {
//!         let article: Article = Article { id: ID::new("1"), text: "Business".to_string() };
//!         let tweet: Tweet = Tweet { id: ID::new("2"), text: "1 weird tip".to_string() };
//!
//!         let posts = vec![
//!             SearchResult::from(article),
//!             SearchResult::from(tweet),
//!         ];
//!
//!         Ok(posts)
//!     }
//! }
//! ```
//!
//! ## Input objects
//!
//! Input objects will be converted into Rust structs with public fields.
//!
//! Abbreviated example (find [complete example here](https://github.com/davidpdrsn/juniper-from-schema/blob/master/examples/input_types.rs)):
//!
//! ```
//! # #[macro_use]
//! # extern crate juniper;
//! # use juniper::*;
//! # use juniper_from_schema::graphql_schema;
//! # fn main() {}
//! # pub struct Context;
//! # impl juniper::Context for Context {}
//! # pub struct Post { id: ID }
//! # impl PostFields for Post {
//! #     fn field_id(
//! #         &self,
//! #         executor: &Executor<'_, Context>,
//! #     ) -> FieldResult<&ID> {
//! #         unimplemented!()
//! #     }
//! #     fn field_title(
//! #         &self,
//! #         executor: &Executor<'_, Context>,
//! #     ) -> FieldResult<&String> {
//! #         unimplemented!()
//! #     }
//! # }
//! # pub struct Query;
//! # impl QueryFields for Query {
//! #     fn field_noop(
//! #         &self,
//! #         executor: &Executor<'_, Context>,
//! #     ) -> FieldResult<&bool> {
//! #         unimplemented!()
//! #     }
//! # }
//! graphql_schema! {
//!     schema {
//!         query: Query
//!         mutation: Mutation
//!     }
//!
//!     type Mutation {
//!         createPost(input: CreatePost!): Post @juniper(ownership: "owned")
//!     }
//!
//!     input CreatePost {
//!         title: String!
//!     }
//!
//!     type Post {
//!         id: ID!
//!         title: String!
//!     }
//!
//!     type Query { noop: Boolean! }
//! }
//!
//! pub struct Mutation;
//!
//! impl MutationFields for Mutation {
//!     fn field_create_post(
//!         &self,
//!         executor: &Executor<'_, Context>,
//!         trail: &QueryTrail<'_, Post, juniper_from_schema::Walked>,
//!         input: CreatePost,
//!     ) -> FieldResult<Option<Post>> {
//!         let title: String = input.title;
//!
//!         unimplemented!()
//!     }
//! }
//! ```
//!
//! From that example `CreatePost` will be defined as
//!
//! ```
//! pub struct CreatePost {
//!     pub title: String,
//! }
//! ```
//!
//! ## Enumeration types
//!
//! GraphQL enumeration types will be converted into normal Rust enums. The name of each variant
//! will be camel cased.
//!
//! Abbreviated example (find [complete example here](https://github.com/davidpdrsn/juniper-from-schema/blob/master/examples/enumeration_types.rs)):
//!
//! ```
//! # #[macro_use]
//! # extern crate juniper;
//! # use juniper::*;
//! # use juniper_from_schema::graphql_schema;
//! # fn main() {}
//! # pub struct Context;
//! # impl juniper::Context for Context {}
//! # pub struct Post { id: ID }
//! # impl PostFields for Post {
//! #     fn field_id(
//! #         &self,
//! #         executor: &Executor<'_, Context>,
//! #     ) -> FieldResult<&ID> {
//! #         Ok(&self.id)
//! #     }
//! # }
//! #
//! graphql_schema! {
//!     schema {
//!         query: Query
//!     }
//!
//!     enum Status {
//!         PUBLISHED
//!         UNPUBLISHED
//!     }
//!
//!     type Query {
//!         allPosts(status: Status!): [Post!]! @juniper(ownership: "owned")
//!     }
//!
//!     type Post {
//!         id: ID!
//!     }
//! }
//!
//! pub struct Query;
//!
//! impl QueryFields for Query {
//!     fn field_all_posts(
//!         &self,
//!         executor: &Executor<'_, Context>,
//!         trail: &QueryTrail<'_, Post, juniper_from_schema::Walked>,
//!         status: Status,
//!     ) -> FieldResult<Vec<Post>> {
//!         match status {
//!             Status::Published => unimplemented!("find published posts"),
//!             Status::Unpublished => unimplemented!("find unpublished posts"),
//!         }
//!     }
//! }
//! ```
//!
//! ## Default argument values
//!
//! In GraphQL you are able to provide default values for field arguments, provided the argument is
//! nullable.
//!
//! Arguments of the following types support default values:
//! - `Float`
//! - `Int`
//! - `String`
//! - `Boolean`
//! - Enumerations
//! - Input objects (as field arguments, see below)
//! - Lists containing some other supported type
//!
//! Abbreviated example (find [complete example here](https://github.com/davidpdrsn/juniper-from-schema/blob/master/examples/default_argument_values.rs)):
//!
//! ```
//! # #[macro_use]
//! # extern crate juniper;
//! # use juniper::*;
//! # use juniper_from_schema::graphql_schema;
//! # fn main() {}
//! # pub struct Context;
//! # impl juniper::Context for Context {}
//! # pub struct Post { id: ID }
//! # impl PostFields for Post {
//! #     fn field_id(
//! #         &self,
//! #         executor: &Executor<'_, Context>,
//! #     ) -> FieldResult<&ID> {
//! #         Ok(&self.id)
//! #     }
//! # }
//! #
//! graphql_schema! {
//!     schema {
//!         query: Query
//!     }
//!
//!     enum Status {
//!         PUBLISHED
//!         UNPUBLISHED
//!     }
//!
//!     input Pagination {
//!         pageSize: Int!
//!         cursor: ID
//!     }
//!
//!     type Query {
//!         allPosts(
//!             status: Status = PUBLISHED,
//!             pagination: Pagination = { pageSize: 20 }
//!         ): [Post!]! @juniper(ownership: "owned")
//!     }
//!
//!     type Post {
//!         id: ID!
//!     }
//! }
//!
//! pub struct Query;
//!
//! impl QueryFields for Query {
//!     fn field_all_posts(
//!         &self,
//!         executor: &Executor<'_, Context>,
//!         trail: &QueryTrail<'_, Post, juniper_from_schema::Walked>,
//!         status: Status,
//!         pagination: Pagination,
//!     ) -> FieldResult<Vec<Post>> {
//!         // `status` will be `Status::Published` if not given in the query
//!
//!         match status {
//!             Status::Published => unimplemented!("find published posts"),
//!             Status::Unpublished => unimplemented!("find unpublished posts"),
//!         }
//!     }
//! }
//! ```
//!
//! ### Input object gotchas
//!
//! Defaults for input objects are only supported as field arguments. The following is not
//! supported
//!
//! ```graphql
//! input SomeType {
//!   field: Int = 1
//! }
//! ```
//!
//! This isn't supported because [the spec is unclear about how to handle multiple nested
//! defaults](https://github.com/webonyx/graphql-php/issues/350).
//!
//! Also, defaults are only used if no arguments are passed. So given the schema
//!
//! ```graphql
//! input Input {
//!   a: String
//!   b: String
//! }
//!
//! type Query {
//!   field(arg: Input = { a: "a" }): Int!
//! }
//! ```
//!
//! and the query
//!
//! ```graphql
//! query MyQuery {
//!   field(arg: { b: "my b" })
//! }
//! ```
//!
//! The value of `arg` inside the resolver would be `Input { a: None, b: Some("my b") }`. Note that
//! even though `a` has a default value in the field doesn't get used here because we set `arg` in
//! the query.
//!
//! # GraphQL to Rust types
//!
//! This is how the standard GraphQL types will be mapped to Rust:
//!
//! - `Int` -> `i32`
//! - `Float` -> `f64`
//! - `String` -> `String`
//! - `Boolean` -> `bool`
//! - `ID` -> [`juniper::ID`](https://docs.rs/juniper/latest/juniper/struct.ID.html)
//!
//! # Query trails
//!
//! If you're not careful about preloading associations for deeply nested queries you risk getting
//! lots of [N+1 query bugs][]. Juniper provides a [look ahead api][] which lets you inspect things
//! coming up further down a query. However the API is string based, so you risk making typos and
//! checking for fields that don't exist.
//!
//! `QueryTrail` is a thin wrapper around Juniper look aheads with generated methods for each field
//! on all your types. This means the compiler will reject your code if you're checking for invalid
//! fields.
//!
//! Fields that return object types (non scalar values) will also get a `QueryTrail` argument
//! besides the executor.
//!
//! Since the `QueryTrail` type itself is defined in this crate (rather than being inserted into
//! your code) we cannot directly add methods for your GraphQL fields. Those methods have to be
//! added through ["extension traits"](http://xion.io/post/code/rust-extension-traits.html). So if
//! you see an error like
//!
//! ```text
//!    |  trail.foo();
//!    |        ^^^ method not found in `&juniper_from_schema::QueryTrail<'a, User, juniper_from_schema::Walked>`
//!    |
//!    = help: items from traits can only be used if the trait is in scope
//! help: the following trait is implemented but not in scope, perhaps add a `use` for it:
//!    |
//! 2  | use crate::graphql_schema::query_trails::QueryTrailUserExtensions;
//!    |
//! ```
//!
//! Then adding `use crate::graphql_schema::query_trails::*` to you module should fix it. This is
//! necessary because all the extention traits are generated inside a module called `query_trails`.
//! This is done so you can glob import the `QueryTrail` extension traits without glob importing
//! everything from your GraphQL schema.
//!
//! If you just want everything from the schema `use crate::graphql_schema::*` will also bring in
//! the extension traits.
//!
//! [N+1 query bugs]: https://secure.phabricator.com/book/phabcontrib/article/n_plus_one/
//! [look ahead api]: https://docs.rs/juniper/0.11.1/juniper/struct.LookAheadSelection.html
//!
//! ## Abbreviated example
//!
//! Find [complete example here](https://github.com/davidpdrsn/juniper-from-schema/blob/master/examples/query_trails.rs)
//!
//! ```
//! # #[macro_use]
//! # extern crate juniper;
//! # use juniper::*;
//! # use juniper_from_schema::graphql_schema;
//! # fn main() {}
//! # pub struct Context;
//! # impl juniper::Context for Context {}
//! #
//! graphql_schema! {
//!     schema {
//!         query: Query
//!     }
//!
//!     type Query {
//!         allPosts: [Post!]! @juniper(ownership: "owned")
//!     }
//!
//!     type Post {
//!         id: Int!
//!         author: User!
//!     }
//!
//!     type User {
//!         id: Int!
//!     }
//! }
//!
//! pub struct Query;
//!
//! impl QueryFields for Query {
//!     fn field_all_posts(
//!         &self,
//!         executor: &Executor<'_, Context>,
//!         trail: &QueryTrail<'_, Post, juniper_from_schema::Walked>,
//!     ) -> FieldResult<Vec<Post>> {
//!         // Check if the query includes the author
//!         if let Some(_) = trail.author().walk() {
//!             // Somehow preload the users to avoid N+1 query bugs
//!             // Exactly how to do this depends on your setup
//!         }
//!
//!         // Normally this would come from the database
//!         let post = Post {
//!             id: 1,
//!             author: User { id: 1 },
//!         };
//!
//!         Ok(vec![post])
//!     }
//! }
//!
//! pub struct Post {
//!     id: i32,
//!     author: User,
//! }
//!
//! impl PostFields for Post {
//!     fn field_id(&self, executor: &Executor<'_, Context>) -> FieldResult<&i32> {
//!         Ok(&self.id)
//!     }
//!
//!     fn field_author(
//!         &self,
//!         executor: &Executor<'_, Context>,
//!         trail: &QueryTrail<'_, User, juniper_from_schema::Walked>,
//!     ) -> FieldResult<&User> {
//!         Ok(&self.author)
//!     }
//! }
//!
//! pub struct User {
//!     id: i32,
//! }
//!
//! impl UserFields for User {
//!     fn field_id(
//!         &self,
//!         executor: &Executor<'_, Context>,
//!     ) -> FieldResult<&i32> {
//!         Ok(&self.id)
//!     }
//! }
//! ```
//!
//! ## Types
//!
//! A query trial has two generic parameters: `QueryTrail<'a, T, K>`. `T` is the type the current
//! field returns and `K` is either `Walked` or `NotWalked`.
//!
//! The lifetime `'a` comes from Juniper and is the lifetime of the incoming query.
//!
//! ### `T`
//!
//! The `T` allows us to implement different methods for different types. For example in the
//! example above we implement `id` and `author` for `QueryTrail<'_, Post, K>` but only `id` for
//! `QueryTrail<'_, User, K>`.
//!
//! If your field returns a `Vec<T>` or `Option<T>` the given query trail will be `QueryTrail<'_,
//! T, _>`. So `Vec` or `Option` will be removed and you'll only be given the inner most type.
//! That is because in the GraphQL query syntax it doesn't matter if you're querying a `User`
//! or `[User]`. The fields you have access to are the same.
//!
//! ### `K`
//!
//! The `Walked` and `NotWalked` types are used to check if a given trail has been checked to
//! actually be part of a query. Calling any method on a `QueryTrail<'_, T, K>` will return
//! `QueryTrail<'_, T, NotWalked>`, and to check if the trail is actually part of the query you have
//! to call `.walk()` which returns `Option<QueryTrail<'_, T, Walked>>`. If that is a `Some(_)`
//! you'll know the trail is part of the query and you can do whatever preloading is necessary.
//!
//! Example:
//!
//! ```ignore
//! if let Some(walked_trail) = trail
//!     .some_field()
//!     .some_other_field()
//!     .third_field()
//!     .walk()
//! {
//!     // preload stuff
//! }
//! ```
//!
//! You can always run `cargo doc` and inspect all the methods on `QueryTrail` and in which
//! contexts you can call them.
//!
//! ## Downcasting for interface and union `QueryTrail`s
//!
//! _This section is mostly relevant if you're using
//! [juniper-eager-loading](https://crates.io/crates/juniper-eager-loading) however it isn't
//! specific to that library._
//!
//! If you have a `QueryTrail<'a, T, Walked>` where `T` is an interface or union type you can use
//! `.downcast()` to convert that `QueryTrail` into one of the implementors of the interface or
//! union.
//!
//! Example:
//!
//! ```
//! # #[macro_use]
//! # extern crate juniper;
//! # use juniper::*;
//! # use juniper_from_schema::graphql_schema;
//! # fn main() {}
//! # pub struct Context;
//! # impl juniper::Context for Context {}
//! # pub struct Article { id: ID }
//! # impl ArticleFields for Article {
//! #     fn field_id(
//! #         &self,
//! #         executor: &Executor<'_, Context>,
//! #     ) -> FieldResult<&ID> { unimplemented!() }
//! # }
//! # pub struct Tweet { id: ID, text: String }
//! # impl TweetFields for Tweet {
//! #     fn field_id(
//! #         &self,
//! #         executor: &Executor<'_, Context>,
//! #     ) -> FieldResult<&ID> { unimplemented!() }
//! # }
//! #
//! graphql_schema! {
//!     schema {
//!         query: Query
//!     }
//!
//!     type Query {
//!         search(query: String!): [SearchResult!]!
//!     }
//!
//!     interface SearchResult {
//!         id: ID!
//!     }
//!
//!     type Article implements SearchResult {
//!         id: ID!
//!     }
//!
//!     type Tweet implements SearchResult {
//!         id: ID!
//!     }
//! }
//!
//! pub struct Query;
//!
//! impl QueryFields for Query {
//!     fn field_search(
//!         &self,
//!         executor: &Executor<'_, Context>,
//!         trail: &QueryTrail<'_, SearchResult, juniper_from_schema::Walked>,
//!         query: String,
//!     ) -> FieldResult<&Vec<SearchResult>> {
//!         let article_trail: QueryTrail<'_, Article, Walked> = trail.downcast();
//!         let tweet_trail: QueryTrail<'_, Tweet, Walked> = trail.downcast();
//!
//!         // ...
//!         # unimplemented!()
//!     }
//! }
//! ```
//!
//! ### Why is this useful?
//!
//! If you were do perform some kind of preloading of data you might have a function that inspects
//! a `QueryTrail` and loads the necessary data from a database. Such a function could look like
//! this:
//!
//! ```ignore
//! fn preload_users(
//!     mut users: Vec<User>,
//!     query_trail: &QueryTrail<'_, User, Walked>,
//!     db: &Database,
//! ) -> Vec<User> {
//!     // ...
//! }
//! ```
//!
//! This function works well when we have field that returns `[User!]!`. That field is going to get
//! a `QueryTrail<'a, User, Walked>` which is exactly what `preload_users` needs.
//!
//! However, now imagine you have a schema like this:
//!
//! ```graphql
//! type Query {
//!     search(query: String!): [SearchResult!]!
//! }
//!
//! union SearchResult = User | City | Country
//!
//! type User {
//!     id: ID!
//!     city: City!
//! }
//!
//! type City {
//!     id: ID!
//!     country: Country!
//! }
//!
//! type Country {
//!     id: ID!
//! }
//! ```
//!
//! The method `QueryFields::field_search` will receive a `QueryTrail<'a, SearchResult, Walked>`.
//! That type doesn't work with `preload_users`. So we have to convert our `QueryTrail<'a,
//! SearchResult, Walked>` into `QueryTrail<'a, User, Walked>`.
//!
//! This can be done by calling `.downcast()` which automatically gets implemented for interface and
//! union query trails. See above for an example.
//!
//! # Customizing the error type
//!
//! By default the return type of the generated field methods will be [`juniper::FieldResult<T>`].
//! That is just a type alias for `std::result::Result<T, juniper::FieldError>`. Should you want to
//! use a different error type than [`juniper::FieldError`] that can be done by passing `,
//! error_type: YourType` to [`graphql_schema_from_file!`].
//!
//! Just keep in that your custom error type must implement [`juniper::IntoFieldError`] to
//! type check.
//!
//! Example:
//!
//! ```
//! # #[macro_use]
//! # extern crate juniper;
//! # use juniper::*;
//! # use juniper_from_schema::graphql_schema_from_file;
//! # fn main() {}
//! # pub struct Context;
//! # impl juniper::Context for Context {}
//! # pub struct Mutation;
//! # impl MutationFields for Mutation {
//! #     fn field_noop(&self, executor: &Executor<'_, Context>) -> Result<&bool, MyError> {
//! #         Ok(&true)
//! #     }
//! # }
//! graphql_schema_from_file!("tests/schemas/doc_schema.graphql", error_type: MyError);
//!
//! pub struct MyError(String);
//!
//! impl juniper::IntoFieldError for MyError {
//!     fn into_field_error(self) -> juniper::FieldError {
//!         // Perform custom error handling
//!         juniper::FieldError::from(self.0)
//!     }
//! }
//!
//! pub struct Query;
//!
//! impl QueryFields for Query {
//!     fn field_hello_world(
//!         &self,
//!         executor: &Executor<'_, Context>,
//!         name: String,
//!     ) -> Result<String, MyError> {
//!         Ok(format!("Hello, {}!", name))
//!     }
//! }
//! ```
//!
//! [`graphql_schema!`] does not support changing the error type.
//!
//! [`graphql_schema!`]: macro.graphql_schema.html
//! [`graphql_schema_from_file!`]: macro.graphql_schema_from_file.html
//! [`juniper::IntoFieldError`]: https://docs.rs/juniper/0.11.1/juniper/trait.IntoFieldError.html
//! [`juniper::FieldError`]: https://docs.rs/juniper/0.11.1/juniper/struct.FieldError.html
//! [`juniper::FieldResult<T>`]: https://docs.rs/juniper/0.11.1/juniper/type.FieldResult.html
//!
//! # Customizing the context type
//!
//! By default the generate code will assume your context type is called `Context`. If that is not
//! the case you can customize it by calling [`graphql_schema_from_file!`] with `context_type: NewName`.
//!
//! Example:
//!
//! ```
//! # #[macro_use]
//! # extern crate juniper;
//! # use juniper::*;
//! # use juniper_from_schema::graphql_schema_from_file;
//! # fn main() {}
//! # pub struct Mutation;
//! # impl MutationFields for Mutation {
//! #     fn field_noop(&self, executor: &Executor<'_, MyContext>) -> juniper::FieldResult<&bool> {
//! #         Ok(&true)
//! #     }
//! # }
//! graphql_schema_from_file!("tests/schemas/doc_schema.graphql", context_type: MyContext);
//!
//! pub struct MyContext;
//! impl juniper::Context for MyContext {}
//!
//! pub struct Query;
//!
//! impl QueryFields for Query {
//!     fn field_hello_world(
//!         &self,
//!         executor: &Executor<'_, MyContext>,
//!         name: String,
//!     ) -> juniper::FieldResult<String> {
//!         Ok(format!("Hello, {}!", name))
//!     }
//! }
//! ```
//!
//! [`graphql_schema!`] does not support changing the context type.
//!
//! [`graphql_schema!`]: macro.graphql_schema.html
//! [`graphql_schema_from_file!`]: macro.graphql_schema_from_file.html
//!
//! # Inspecting the generated code
//!
//! If you wish to see exactly what code gets generated you can set the env var
//! `JUNIPER_FROM_SCHEMA_DEBUG` to `1` when compiling. For example:
//!
//! ```bash
//! JUNIPER_FROM_SCHEMA_DEBUG=1 cargo build
//! ```
//!
//! The code will not be formatted so it might be tricky to read. The easiest way to fix this is to
//! copy the printed code to a file and run it through [rustfmt].
//!
//! Alternatively you can include the [feature] called `"format-debug-output"`. This will run the
//! output through [rustfmt] before printing it. That way you don't have to do that manually.
//! Example `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! juniper-from-schema = { version = "x.y.z", features = ["format-debug-output"] }
//! ```
//!
//! Unfortunately this requires that you're using nightly, because [rustfmt requires
//! nightly](https://github.com/rust-lang/rustfmt#installing-from-source). It might also break your
//! build because [rustfmt] doesn't always compile for some reason ¯\\\_(ツ)\_/¯. If you experience
//! this just remove the `"format-debug-output"` feature and format the output manually.
//!
//! [feature]: https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#choosing-features
//! [rustfmt]: https://github.com/rust-lang/rustfmt

#![deny(
    missing_docs,
    unused_imports,
    dead_code,
    unused_variables,
    unused_must_use
)]
#![doc(html_root_url = "https://docs.rs/juniper-from-schema/0.4.0")]

use juniper::{DefaultScalarValue, LookAheadSelection};
use std::marker::PhantomData;

pub use juniper_from_schema_code_gen::{graphql_schema, graphql_schema_from_file};

/// A type used to parameterize `QueryTrail` to know that `walk` has been called.
pub struct Walked;

/// A type used to parameterize `QueryTrail` to know that `walk` has *not* been called.
pub struct NotWalked;

/// A wrapper around a `juniper::LookAheadSelection` with methods for each possible child.
pub struct QueryTrail<'a, T, K> {
    #[doc(hidden)]
    pub look_ahead: Option<&'a LookAheadSelection<'a, DefaultScalarValue>>,
    #[doc(hidden)]
    pub node_type: PhantomData<T>,
    #[doc(hidden)]
    pub walked: K,
}

impl<'a, T> QueryTrail<'a, T, NotWalked> {
    /// Check if the trail is present in the query being executed
    pub fn walk(self) -> Option<QueryTrail<'a, T, Walked>> {
        match self.look_ahead {
            Some(inner) => Some(QueryTrail {
                look_ahead: Some(inner),
                node_type: self.node_type,
                walked: Walked,
            }),
            None => None,
        }
    }
}

/// Make a `QueryTrail` from something, normally a `juniper::LookAheadSelection`.
///
/// You normally shouldn't need to worry about this trait.
pub trait MakeQueryTrail<'a> {
    #[allow(missing_docs)]
    fn make_query_trail<T>(&'a self) -> QueryTrail<'a, T, Walked>;
}

impl<'a> MakeQueryTrail<'a> for LookAheadSelection<'a, DefaultScalarValue> {
    fn make_query_trail<T>(&'a self) -> QueryTrail<'a, T, Walked> {
        QueryTrail {
            look_ahead: Some(self),
            node_type: PhantomData,
            walked: Walked,
        }
    }
}

#[cfg(test)]
mod test {
    #[allow(unused_imports)]
    use super::*;

    #[rustversion::nightly]
    #[test]
    fn test_compile_pass() {
        let t = trybuild::TestCases::new();
        t.pass("tests/compile_pass/*.rs");
        t.compile_fail("tests/compile_fail/*.rs");
    }
}