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
//! This library exposes a procedural macro that reads a GraphQL schema file, and generates the
//! corresponding 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 from using
//! Juniper.
//!
//! # Example
//!
//! Schema:
//!
//! ```graphql
//! schema {
//!   query: Query
//!   mutation: Mutation
//! }
//!
//! type Query {
//!   // this makes the return value `FieldResult<String>`
//!   // rather than the default `FieldResult<&String>`
//!   "#[ownership(owned)]"
//!   helloWorld(name: String!): String!
//! }
//!
//! type Mutation {
//!   noop: Boolean!
//! }
//! ```
//!
//! Rust implementation of schema:
//!
//! ```
//! #[macro_use]
//! extern crate juniper;
//!
//! use 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: &Executor<'_, Context>,
//!         name: String,
//!     ) -> FieldResult<String> {
//!         Ok(format!("Hello, {}!", name))
//!     }
//! }
//!
//! pub struct Mutation;
//!
//! impl MutationFields for Mutation {
//!     fn field_noop(&self, executor: &Executor<'_, Context>) -> 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),
//!         &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!",
//!     );
//! }
//! ```
//!
//! This expands into:
//!
//! ```
//! #[macro_use]
//! extern crate juniper;
//!
//! use juniper::*;
//!
//! pub struct Context;
//! impl juniper::Context for Context {}
//!
//! pub struct Query;
//!
//! graphql_object!(Query: Context |&self| {
//!     field hello_world(&executor, name: String) -> FieldResult<String> {
//!         <Self as QueryFields>::field_hello_world(&self, &executor, name)
//!     }
//! });
//!
//! trait QueryFields {
//!     fn field_hello_world(
//!         &self,
//!         executor: &Executor<'_, Context>,
//!         name: String,
//!     ) -> FieldResult<String>;
//! }
//!
//! impl QueryFields for Query {
//!     fn field_hello_world(
//!         &self,
//!         executor: &Executor<'_, Context>,
//!         name: String,
//!     ) -> FieldResult<String> {
//!         Ok(format!("Hello, {}!", name))
//!     }
//! }
//!
//! pub struct Mutation;
//!
//! graphql_object!(Mutation: Context |&self| {
//!     field noop(&executor) -> FieldResult<&bool> {
//!         <Self as MutationFields>::field_noop(&self, &executor)
//!     }
//! });
//!
//! trait MutationFields {
//!     fn field_noop(&self, executor: &Executor<'_, Context>) -> FieldResult<&bool>;
//! }
//!
//! impl MutationFields for Mutation {
//!     fn field_noop(&self, executor: &Executor<'_, Context>) -> 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),
//!         &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!",
//!     );
//! }
//! ```
//!
//! # 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 return owned values (such as values queried from a database) you have to
//! annotate the field in the schema with `#[ownership(owned)]`.
//!
//! 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 on non-nulls to Rust types
//! - Custom scalar types including the `ID` type
//! - Interfaces
//! - Unions
//! - Input objects
//! - Enumeration types
//!
//! Not supported yet:
//! - Default values for arguments
//! - Subscriptions (currently not supported by Juniper so we're unsure when or if this will happen)
//!
//! ## The `ID` type
//!
//! The `ID` GraphQL type will be generated as a newtype wrapper around a `String` using
//! [`juniper::graphql_scalar!`](https://docs.rs/juniper/0.11.1/juniper/macro.graphql_scalar.html). The Rust type will be called `Id`.
//!
//! Example:
//!
//! ```
//! pub struct Id(pub String);
//!
//! impl Id {
//!     // A generated convenience initializer
//!     pub fn new<T: Into<String>>(id: T) -> Self {
//!         Id(id.into())
//!     }
//! }
//! ```
//!
//! ## Custom scalar types
//!
//! Similarly to `ID`, custom scalar types get converted into newtype wrappers around `String`s. For example:
//!
//! ```graphql
//! scalar Cursor
//! ```
//!
//! Would result in
//!
//! ```
//! pub struct Cursor(pub String);
//! ```
//!
//! `Date` and `DateTime` are the two exceptions to this. `Date` gets converted into
//! [`chrono::naive::NaiveDate`](https://docs.rs/chrono/0.4.6/chrono/naive/struct.NaiveDate.html)
//! and `DateTime` into
//! [`chrono::DateTime<chrono::offset::Utc>`](https://docs.rs/chrono/0.4.6/chrono/struct.DateTime.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.
//!
//! 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, 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 {
//!         "#[ownership(owned)]"
//!         search(query: String!): [SearchResult!]!
//!     }
//!
//!     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, 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.
//!
//! 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, 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 {
//!         "#[ownership(owned)]"
//!         search(query: String!): [SearchResult!]!
//!     }
//!
//!     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, 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)
//!     }
//! }
//! ```
//!
//! Note that union types current don't work with `QueryTrail`s, meaning that it will not generate
//! methods for each field in the union. Expect that to be fixed in a future version.
//!
//! ## Input objects
//!
//! Input objects will be converted into Rust structs with public fields.
//!
//! 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 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 {
//!         "#[ownership(owned)]"
//!         createPost(input: CreatePost!): Post
//!     }
//!
//!     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, 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.
//!
//! 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 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 {
//!         "#[ownership(owned)]"
//!         allPosts(status: STATUS!): [Post!]!
//!     }
//!
//!     type Post {
//!         id: ID!
//!     }
//! }
//!
//! pub struct Query;
//!
//! impl QueryFields for Query {
//!     fn field_all_posts(
//!         &self,
//!         executor: &Executor<'_, Context>,
//!         trail: &QueryTrail<'_, Post, Walked>,
//!         status: Status,
//!     ) -> FieldResult<Vec<Post>> {
//!         match status {
//!             Status::Published => unimplemented!("find published posts"),
//!             Status::Unpublished => unimplemented!("find unpublished posts"),
//!         }
//!     }
//! }
//! ```
//!
//! # 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` -> `pub struct Id(pub String)`
//!
//! # 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 objects types (non scalar values) will also get a `QueryTrail` argument
//! besides the executor.
//!
//! [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
//!
//! ## Example
//!
//! ```
//! # #[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 {
//!         "#[ownership(owned)]"
//!         allPosts: [Post!]!
//!     }
//!
//!     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, 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, 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<'_, T, K>`. `T` is the type the current
//! field returns and `K` is either `Walked` or `NotWalked`.
//!
//! ### `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>`.
//!
//! ### `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.

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

extern crate proc_macro;
extern crate proc_macro2;

#[macro_use]
mod macros;
mod nullable_type;
mod pretty_print;
mod walk_ast;

use self::walk_ast::{
    find_interface_implementors, find_special_scalar_types, gen_juniper_code, gen_query_trails,
    Output,
};
use graphql_parser::parse_schema;
use proc_macro2::TokenStream;

/// Read a GraphQL schema file and generate corresponding Juniper macro calls.
///
/// See [the crate level docs](index.html) for an example.
#[proc_macro]
pub fn graphql_schema_from_file(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input: TokenStream = input.into();

    let file = input.to_string().replace("\"", "");
    let pwd = std::env::current_dir().unwrap();
    let path = pwd.join(file);

    match read_file(&path) {
        Ok(schema) => parse_and_gen_schema(&schema),
        Err(err) => panic!("{}", err),
    }
}

/// Write your GraphQL schema directly in your Rust code.
///
/// This is mostly useful for testing. Prefer using [`graphql_schema_from_file`][] for larger
/// schemas.
///
/// [`graphql_schema_from_file`]: macro.graphql_schema_from_file.html
///
/// # Example
///
/// ```
/// # #[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 {
///         "#[ownership(owned)]"
///         helloWorld: String!
///     }
/// }
///
/// pub struct Query;
///
/// impl QueryFields for Query {
///     fn field_hello_world(
///         &self,
///         executor: &Executor<'_, Context>,
///     ) -> FieldResult<String> {
///         Ok("Hello, World!".to_string())
///     }
/// }
/// ```
#[proc_macro]
pub fn graphql_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input: TokenStream = input.into();
    let schema = input.to_string();
    parse_and_gen_schema(&schema)
}

fn parse_and_gen_schema(schema: &str) -> proc_macro::TokenStream {
    let doc = match parse_schema(&schema) {
        Ok(doc) => doc,
        Err(parse_error) => panic!("{}", parse_error),
    };

    let special_scalars = find_special_scalar_types(&doc);
    let interface_implementors = find_interface_implementors(&doc);

    let mut output = Output::new(special_scalars, interface_implementors);

    gen_query_trails(&doc, &mut output);
    gen_juniper_code(doc, &mut output);

    let out: proc_macro::TokenStream = output.tokens().into_iter().collect::<TokenStream>().into();

    if debugging_enabled() {
        self::pretty_print::code_gen_debug(out.to_string());
    }

    out
}

fn read_file(path: &std::path::PathBuf) -> Result<String, std::io::Error> {
    use std::{fs::File, io::prelude::*};
    let mut file = File::open(path)?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    Ok(contents)
}

fn debugging_enabled() -> bool {
    if let Ok(val) = std::env::var("JUNIPER_FROM_SCHEMA_DEBUG") {
        if &val == "1" {
            return true;
        }
    }

    false
}