async-codegen 0.12.1

Minimalist async-IO code generation framework.
Documentation
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
/*
 * Copyright © 2025 Anand Beh
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

//!
//! Rust syntax elements.
//!
//! Note that no checking exists to make sure the elements are used correctly, i.e. the correct
//! combination of structs. Instead, the library user is expected to have basic knowledge of how
//! Rust syntax is composed, and to combine the structs in this module likewise.
//!
//! Example:
//!
//! ```
//! # use async_codegen::common::{CombinedSeq, NoOpSeq, SingularSeq, Str};
//! # use async_codegen::{Output, Writable};
//! # use async_codegen::rust::{CanHaveAttributes, CfgAttr, Deprecated, FunctionBodyImplement, FunctionDef, FunctionParam, ModPub, MustUse, NoMangle, Parameterized};
//!
//! async fn write_function<O>(output: &mut O) -> Result<(), O::Error> where O: Output {
//!   // For more advanced usage, you can replace Str("") by other Writable implementations
//!   let function_def = FunctionDef {
//!     mods: SingularSeq(ModPub),
//!     name: Str("my_func"),
//!     args: CombinedSeq(
//!      SingularSeq(FunctionParam(Str("var1"), Str("Type"))),
//!      SingularSeq(FunctionParam(Str("var2"), Parameterized(Str("Option"), SingularSeq(Str("bool")))))
//!     ),
//!     return_type: Parameterized(Str("Box"), SingularSeq(Str("str"))),
//!     where_conds: NoOpSeq,
//!     body: FunctionBodyImplement(Str("todo!()"))
//!   };
//!   function_def.write_to(output).await
//!   // Will render as:
//!   /*
//!   pub fn my_func(var1: Type, var2: Option<bool>) -> Box<str> {
//!     todo!()
//!   }
//!    */
//! }
//! ```
//!

use crate::common::{Combined, NoOp, NoOpSeq, Str, SurroundingSeqAccept};
use crate::{Output, SequenceAccept, Writable};
use std::fmt::Debug;

mod syntax;
#[cfg(test)]
mod tests;

/// All possible Rust editions.
/// This is the only type in this module meant to be used as context, and not as a writable itself.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum Edition {
    /// This Rust edition is declared for usability purposes. However, not all [Writable]
    /// implementations are guaranteed to work with it.
    Rust2015,
    Rust2018,
    Rust2021,
    Rust2024,
}

/// Imports a single type so that it can be used later.
/// Renders as `use Type;`. Adds a new line after the semicolon.
#[derive(Clone, Debug)]
pub struct UseType<Type>(pub Type);

/// An attribute enabled conditionally, i.e. `#[cfg_attr(Cond, Attr)]`
#[derive(Clone, Debug)]
pub struct CfgAttr<Cond, Attr>(pub Cond, pub Attr);

/// A cfg attribute. Renders as `cfg(Cond)`.
#[derive(Clone, Debug)]
pub struct Cfg<Cond>(pub Cond);

/// A doc attribute on an item.
///
/// The generic argument of this enum is not used in all variants. Consider using the constructor
/// functions [Self::hidden], [Self::inline], and [Self::no_inline] if applicable
#[derive(Clone, Debug)]
pub enum Doc<Value> {
    /// The `#[doc(hidden)]` attribute
    Hidden,
    /// The `#[doc(inline)]` attribute
    Inline,
    /// The `#[doc(no_inline)]` attribute
    NoInline,
    /// Creates an alias to another item with `#[doc(alias = "Value")]`
    Alias(Value),
    /// Creates a documentation test attribute with `#[doc(test(Value))]`
    Test(Value),
}

impl Doc<NoOp> {
    /// The `#[doc(hidden)]` attribute
    pub fn hidden() -> Doc<NoOp> {
        Doc::Hidden
    }

    /// The `#[doc(inline)]` attribute
    pub fn inline() -> Doc<NoOp> {
        Doc::Inline
    }

    /// The `#[doc(no_inline)]` attribute
    pub fn no_inline() -> Doc<NoOp> {
        Doc::NoInline
    }
}

/// A cfg condition for targeting an OS, OS family, or architecture. For example:
/// ```
/// # use async_codegen::common::{NoOpSeq, SingularSeq, Str};
/// # use async_codegen::context::EmptyContext;
/// # use async_codegen::rust::{FunctionBodyDeclare, Cfg, FunctionDef, Target, CanHaveAttributes};
/// # use async_codegen::util::InMemoryOutput;
/// let function = FunctionDef {
///   mods: NoOpSeq,
///   name: Str("conditional_func"),
///   args: NoOpSeq,
///   return_type: Str("()"),
///   where_conds: NoOpSeq,
///   body: FunctionBodyDeclare
/// }.with_attributes(
///   SingularSeq(Cfg(Target::Os(Str("linux"))))
/// );
/// let string = InMemoryOutput::print_output(EmptyContext, &function);
/// assert_eq!("#[cfg(target_os = \"linux\")]\nfn conditional_func() -> ();\n\n", string);
/// ```
#[derive(Clone, Debug)]
pub enum Target<Value> {
    Os(Value),
    Family(Value),
    Arch(Value),
}

/// The link attribute.
#[derive(Clone, Debug)]
pub struct Link<Arg>(pub Arg);

/// The no mangle attribute.
///
/// Requires that the context satisfies [ContextProvides] for [Edition], because in Rust 2024 and
/// beyond, the no-mangle attribute is an unsafe attribute.
#[derive(Clone, Debug)]
pub struct NoMangle;

/// The attribute content for `allow(...)`. The tuple value must be a sequence.
#[derive(Clone, Debug)]
pub struct AllowLints<Lints>(pub Lints);

/// The deprecated attribute. The three variants of this enum correspond to the deprecated
/// attribute's multiple ways of being specified. See:
/// https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-deprecated-attribute
#[derive(Clone, Debug)]
pub enum Deprecated<Msg, Since = NoOp> {
    Basic,
    Message(Msg),
    Full { since: Since, note: Msg },
}

impl Default for Deprecated<NoOp, NoOp> {
    fn default() -> Self {
        Self::Basic
    }
}

impl Deprecated<NoOp, NoOp> {
    pub fn basic() -> Self {
        Self::Basic
    }
}

impl<Msg> Deprecated<Msg> {
    pub fn with_message(msg: Msg) -> Self {
        Self::Message(msg)
    }
}

/// The must_use attribute
#[derive(Clone, Debug)]
pub struct MustUse;

/// The public modifier
#[derive(Clone, Debug)]
pub struct ModPub;

/// The unsafe modifier
#[derive(Clone, Debug)]
pub struct ModUnsafe;

/// The extern modifier, with the ABI selected as the tuple value.
///
/// This struct includes `unsafe`. Since Rust 2024, the unsafe keyword is required for extern
/// functions, and before Rust 2024 it is optional. To make it easy to generate code targeting
/// multiple editions, we unconditionally emit the "unsafe" keyword alongside "extern".
#[derive(Clone, Debug)]
pub struct ModUnsafeExtern<Abi>(pub Abi);

/// A standalone statement. Renders the expression and adds a semicolon and a new line.
#[derive(Clone, Debug)]
pub struct Stmt<Expr>(pub Expr);

/// A let statement. This statement includes the semicolon and a new line.
#[derive(Clone, Debug)]
pub struct LetStmt<Variable, Expr>(pub Variable, pub Expr);

/// A mutable let statement.  This statement includes the semicolon and a new line.
#[derive(Clone, Debug)]
pub struct LetMutStmt<Variable, Expr>(pub Variable, pub Expr);

/// An assignation. This statement includes the semicolon and a new line.
#[derive(Clone, Debug)]
pub struct AssignStmt<Variable, Expr>(pub Variable, pub Expr);

/// An assignation, as an expression
#[derive(Clone, Debug)]
pub struct AssignExpr<Variable, Expr>(pub Variable, pub Expr);

/// A return statement. Renders as `return Expr;` with a new line at the end.
#[derive(Clone, Debug)]
pub struct ReturnStmt<Expr>(pub Expr);

/// A let expression.
/// This can be used, for example, as the condition of [IfBlock] in order to create an "if-let" block.
#[derive(Clone, Debug)]
pub struct LetExpr<Pattern, Expr>(pub Pattern, pub Expr);

/// A raw string literal expression, i.e. r#"Content"#. Example:
/// ```
/// # use async_codegen::common::Str;
/// # use async_codegen::context::EmptyContext;
/// # use async_codegen::rust::RawStringLiteral;
/// # use async_codegen::util::InMemoryOutput;
/// let string_lit = RawStringLiteral(Str("hello_world"));
///
/// assert_eq!("r#\"hello_world\"#", InMemoryOutput::print_output(EmptyContext, &string_lit));
/// ```
#[derive(Clone, Debug)]
pub struct RawStringLiteral<Content>(pub Content);

/// An array literal with predefined elements written out.
/// Renders as `[E1, E2, E3, ...]` where EX is in the element sequence.
#[derive(Clone, Debug)]
pub struct ArrayFromElements<Elements>(pub Elements);

/// An array initialization literal with a default element and size.
/// Renders as `[Default; Count]`.
#[derive(Clone, Debug)]
pub struct ArrayInit<Default, Count>(pub Default, pub Count);

/// An item attached to an associated container, via "::".
/// The output will look like `Cont::Item`.
#[derive(Clone, Debug)]
pub struct AssociatedItem<Cont, Item>(pub Cont, pub Item);

/// A question mark following another expression.
#[derive(Clone, Debug)]
pub struct QuestionMarkAfter<Expr>(pub Expr);

/// Uses the `as` expression to perform a qualified trait cast (e.g. ready for a method call).
/// This will render as `<Type as Trait>`.
#[derive(Clone, Debug)]
pub struct TypeAsTrait<Type, Trait>(pub Type, pub Trait);

/// Uses the `as` expression to coerce one type to another.
/// This will render as `<Type1 as Type2>`.
#[derive(Clone, Debug)]
pub struct TypeAsType<Type1, Type2>(pub Type1, pub Type2);

/// Declaration of an extern block, i.e. for FFI.
/// In Rust 2024 and later, the unsafe keyword must be added for extern blocks. Thus, this struct
/// requires that the context satisfies [ContextProvides] for [Edition].
#[derive(Clone, Debug)]
pub struct ExternBlock<Abi, Body> {
    /// The ABI chosen. Must be writable
    pub abi: Abi,
    /// The body of the extern block. Must be writable
    pub body: Body,
}

impl<Abi, Body> CanHaveAttributes for ExternBlock<Abi, Body> {
    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
        WithAttributes {
            attr,
            separator: AttributeSeparator::NewLine,
            value: self,
        }
    }
}

/// Declaration of a module block. Renders as `mod Name {Body}`.
#[derive(Clone, Debug)]
pub struct ModBlock<Name, Body> {
    /// The module name
    pub name: Name,
    /// The body. Must be writable
    pub body: Body,
}

/// An if block. The condition and body must both be writable.
#[derive(Clone, Debug)]
pub struct IfBlock<Cond, Body>(pub Cond, pub Body);

/// Represents "else" syntactically. Renders as `Before else After`.
///
/// This struct requires you to specify what comes before and after the else. For example:
/// ```
/// # use async_codegen::common::Str;
/// # use async_codegen::context::EmptyContext;
/// # use async_codegen::rust::{Block, Else, IfBlock};
/// # use async_codegen::util::InMemoryOutput;
///
/// let if_block = IfBlock(Str("true"), Str("log::info(\"Hello\")"));
/// let else_block = Block(Str("panic!()"));
/// let if_else = Else(if_block, else_block);
///
/// let string = InMemoryOutput::print_output(EmptyContext, &if_else);
/// assert_eq!("if true {\nlog::info(\"Hello\")\n} else {\npanic!()\n}", string)
/// ```
#[derive(Clone, Debug)]
pub struct Else<Before, After>(pub Before, pub After);

/// An unlabeled block.
/// This can be used in many contexts, including merely organizing the code.
#[derive(Clone, Debug)]
pub struct Block<Body>(pub Body);

/// Places the expression inside an unsafe block.
/// Adds new lines inside the brackets, wrapping the inner expression.
#[derive(Clone, Debug)]
pub struct UnsafeBlock<Expr>(pub Expr);

/// Writes a closure.
/// Adds new lines inside the brackets, wrapping the inner expression.
#[derive(Clone, Debug)]
pub struct Closure<InputVars, Expr> {
    /// The input variables.
    /// Should be a sequence. They will be comma separated and placed within the pipes.
    /// To use no input variables, use [NoOpSeq].
    pub input_vars: InputVars,
    /// The expression inside the closure block.
    pub inside_block: Expr,
}

/// Performs a call to a function inside code.
#[derive(Clone, Debug)]
pub struct FunctionCall<Recv, Name, Args> {
    /// The function receiver
    pub receiver: Recv,
    /// Whether the function is associated, false if it's a method
    pub is_assoc: bool,
    /// The function name
    pub name: Name,
    /// The arguments. Must be a sequence
    pub args: Args,
}

/// Provides access to the "turbofish" syntax, i.e. `Name::<Args>`.
/// The first tuple value must be writable, and the second must be a sequence.
///
/// Note that if the sequence outputs nothing, this struct will behave as if no args were
/// specified. I.e. `Turbofish(Name, NoOpSeq)` is equivalent to just `Name`.
#[derive(Clone, Debug)]
pub struct Turbofish<Name, Args>(pub Name, pub Args);

/// Accesses a member by name. Renders as `Owner.Member`.
///
/// This can be used for named fields or tuple fields. for example:
/// ```
/// # use async_codegen::common::Str;
/// # use async_codegen::context::EmptyContext;
/// # use async_codegen::rust::{MemberAccess, LetStmt, RefOf};
/// # use async_codegen::util::InMemoryOutput;
/// let string = InMemoryOutput::print_output(EmptyContext, &LetStmt(
///   Str("borrowed_field"), RefOf(MemberAccess(Str("my_var"), Str("my_field")))
/// ));
/// assert_eq!(string, "let borrowed_field = &my_var.my_field;\n");
/// ```
#[derive(Clone, Debug)]
pub struct MemberAccess<Owner, Member>(pub Owner, pub Member);

/// A function declaration
#[derive(Clone, Debug)]
pub struct FunctionDef<Mods, Name, Args, Return, Where, Body> {
    /// The modifiers. Must be a sequence.
    pub mods: Mods,
    /// The function name. Type variables can be declared here via [Parameterized]
    pub name: Name,
    /// The arguments. Must be a sequence
    pub args: Args,
    /// The return type, i.e. after the `->` arrow
    pub return_type: Return,
    /// The "where" conditions. Must be a sequence. Set to [NoOp] to disable.
    /// Will render as `where C1, C2, C3, ...` where CX is a value in the sequence.
    pub where_conds: Where,
    /// The function body.
    /// To only declare the function, this must be `;` so use [FunctionBodyDeclare]
    /// To implement the function, use [FunctionBodyImplement]
    pub body: Body,
}

impl<Mods, Name, Args, Return, Where, Body> CanHaveAttributes
    for FunctionDef<Mods, Name, Args, Return, Where, Body>
{
    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
        WithAttributes {
            attr,
            separator: AttributeSeparator::NewLine,
            value: self,
        }
    }
}

/// Declares a function body. This is equivalent to just a semicolon.
#[derive(Clone, Debug)]
pub struct FunctionBodyDeclare;

/// Implements a function body. Places the contents inside brackets
#[derive(Clone, Debug)]
pub struct FunctionBodyImplement<Inner>(pub Inner);

/// A function pointer. Can be used for `fn`, `Fn`, `FnMut`, and `FnOnce`.
///
/// Example:
/// ```
/// # use async_codegen::common::{SingularSeq, Str};
/// # use async_codegen::context::EmptyContext;
/// # use async_codegen::rust::{FunctionPtr, FunctionPtrKind};
/// # use async_codegen::util::InMemoryOutput;
/// let function_ptr = FunctionPtr {
///   kind: FunctionPtrKind::FnMut,
///   args: SingularSeq(Str("String")),
///   return_type: Str("bool")
/// };
/// let string = InMemoryOutput::print_output(EmptyContext, &function_ptr);
/// assert_eq!("FnMut(String) -> bool", string);
/// ```
#[derive(Clone, Debug)]
pub struct FunctionPtr<Args, Return> {
    /// The function pointer kind
    pub kind: FunctionPtrKind,
    /// The arguments. Must be a sequence
    pub args: Args,
    /// The return type, i.e. after the `->` arrow
    pub return_type: Return,
}

/// The kind of function type
#[derive(Clone, Debug)]
pub enum FunctionPtrKind {
    /// An `fn` pointer. E.g. `fn(String) -> bool`.
    FnPtr,
    /// Represents [Fn]
    Fn,
    /// Represents [FnMut]
    FnMut,
    /// Represents [FnOnce]
    FnOnce,
}

/// Renders as `Type=Value`. Intended to be used as a type argument, to specify associated types.
#[derive(Clone, Debug)]
pub struct AssociatedTypeEquals<Type, Value>(pub Type, pub Value);

/// Adds a "dyn " before a type expression.
#[derive(Clone, Debug)]
pub struct DynOf<Type>(pub Type);

/// Adds a "&" before a type expression
#[derive(Clone, Debug)]
pub struct RefOf<Expr>(pub Expr);

/// Adds a "&mut " before a type expression
#[derive(Clone, Debug)]
pub struct RefMutOf<Expr>(pub Expr);

/// Dereferences an expression using `*`
#[derive(Clone, Debug)]
pub struct Dereference<Expr>(pub Expr);

/// Surrounds an expression with parentheses, rendering as `(Expr)`.
/// Even if the expression is empty, the parentheses will still be rendered.
#[derive(Clone, Debug)]
pub struct ParenthesesAround<Expr>(pub Expr);

/// Adds an "impl " before a type expression
pub struct ImplOf<Type>(pub Type);

/// Adds a reference with a lifetime before a type expression, i.e. `&'<lifetime> <type>`
#[derive(Clone, Debug)]
pub struct LifetimedRefOf<'l, Type>(pub &'l str, pub Type);

/// Uses the `&raw const` syntax to get a pointer from another pointer. For example:
/// ```
/// # use async_codegen::common::Str;
/// # use async_codegen::context::EmptyContext;
/// # use async_codegen::rust::{MemberAccess, LetStmt, RawConstOf};
/// # use async_codegen::util::InMemoryOutput;
/// let pointer_var = Str("ptr");
/// let let_stmt = LetStmt(pointer_var, RawConstOf(MemberAccess(Str("packed"), Str("field1"))));
/// let string = InMemoryOutput::print_output(EmptyContext, &let_stmt);
/// assert_eq!("let ptr = &raw const packed.field1;\n", string);
/// ```
#[derive(Clone, Debug)]
pub struct RawConstOf<Expr>(pub Expr);

/// Uses the `&raw must` syntax to get a pointer from another pointer. For example:
/// ```
/// # use async_codegen::common::Str;
/// # use async_codegen::context::EmptyContext;
/// # use async_codegen::rust::{MemberAccess, LetStmt, RawMutOf};
/// # use async_codegen::util::InMemoryOutput;
/// let pointer_var = Str("ptr");
/// let let_stmt = LetStmt(pointer_var, RawMutOf(MemberAccess(Str("packed"), Str("field1"))));
/// let string = InMemoryOutput::print_output(EmptyContext, &let_stmt);
/// assert_eq!("let ptr = &raw mut packed.field1;\n", string);
/// ```
#[derive(Clone, Debug)]
pub struct RawMutOf<Expr>(pub Expr);

/// A `*const Type` for some arbitrary type
#[derive(Clone, Debug)]
pub struct ConstPtr<Type>(pub Type);

/// A `*mut Type` for some arbitrary type.
#[derive(Clone, Debug)]
pub struct MutPtr<Type>(pub Type);

/// Declares a type, rendering as `type Value;` Adds a new line after.
///
/// Can be used for multiple purposes:
/// - Creating a type alias, free-form
/// - Defining an associated type (use [FillOutField])
/// - Declaring the value of an associated type (use [AssignExpr])
///
/// Example using traits and associated types:
/// ```
/// use async_codegen::common::{Combined, NoOpSeq, SingularSeq, Str};
/// use async_codegen::context::EmptyContext;
/// use async_codegen::rust::{AssignExpr, FillOutField, Lifetime, LifetimedRefOf, Parameterized, TraitDef, TraitImpl, TypeDeclare};
/// use async_codegen::util::InMemoryOutput;
///
/// let trait_def = TraitDef {
///   mods: NoOpSeq,
///   name: Str("MyTrait"),
///   type_variables: NoOpSeq,
///   super_traits: NoOpSeq,
///   body: TypeDeclare(FillOutField(Parameterized(Str("Special"), SingularSeq(Lifetime("s"))), Str("Clone")))
/// };
/// let trait_impl = TraitImpl {
///   mods: NoOpSeq,
///   type_variables: NoOpSeq,
///   the_trait: Str("MyTrait"),
///   receiver: Str("()"),
///   where_conds: NoOpSeq,
///   body: TypeDeclare(AssignExpr(Parameterized(Str("Special"), SingularSeq(Lifetime("s"))), LifetimedRefOf("s", Str("str"))))
/// };
/// let string = InMemoryOutput::print_output(EmptyContext, &Combined(trait_def, trait_impl));
/// assert_eq!(r#"trait MyTrait {
///type Special<'s>: Clone;
///
///}
///
///impl MyTrait for () {
///type Special<'s> = &'s str;
///
///}
///
///"#, string);
/// ```
#[derive(Clone, Debug)]
pub struct TypeDeclare<Value>(pub Value);

/// The declaration of a trait
#[derive(Clone, Debug)]
pub struct TraitDef<Mods, Name, TypeVars, SuperTraits, Body> {
    /// The trait modifiers, e.g. visibility. Must be a sequence.
    pub mods: Mods,
    /// The name of the trait
    pub name: Name,
    /// The type variables. Must be a sequence
    pub type_variables: TypeVars,
    /// The super traits. Must be a sequence
    pub super_traits: SuperTraits,
    /// The trait definition's body. Use [NoOp] if none exists.
    pub body: Body,
}

impl<Mods, Name, TypeVars, SuperTraits, Body> CanHaveAttributes
    for TraitDef<Mods, Name, TypeVars, SuperTraits, Body>
{
    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
        WithAttributes {
            attr,
            separator: AttributeSeparator::NewLine,
            value: self,
        }
    }
}

/// The implementation declaration for a trait, applying to a certain receiver.
#[derive(Clone, Debug)]
pub struct TraitImpl<Mods, TypeVars, Trait, Recv, Where, Body> {
    /// The modifiers on the `impl` block.
    /// Set to [NoOpSeq] for none, or use `SingularSeq(ModUnsafe)` to generate an `unsafe impl`.
    pub mods: Mods,
    /// The type variables to use for the impl block itself. All type variables that appear later
    /// on the trait or the receiver must be declared here, per Rust language rules.
    ///
    /// This field must be a sequence.
    pub type_variables: TypeVars,
    /// The trait being implemented
    pub the_trait: Trait,
    /// The receiver for which it is implemented
    pub receiver: Recv,
    /// The "where" conditions. Must be a sequence. Set to [NoOpSeq] to disable.
    /// Will render as `where C1, C2, C3, ...` where CX is a value in the sequence.
    pub where_conds: Where,
    /// The body. Use [NoOp] if none exists.
    pub body: Body,
}

impl<Mods, TypeVars, Trait, Recv, Where, Body> CanHaveAttributes
    for TraitImpl<Mods, TypeVars, Trait, Recv, Where, Body>
{
    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
        WithAttributes {
            attr,
            separator: AttributeSeparator::NewLine,
            value: self,
        }
    }
}

/// An impl block.
///
/// For impls of a trait for a certain receiver, it is suggested to use [TraitImpl].
#[derive(Clone, Debug)]
pub struct Impl<Mods, TypeVars, Recv, Where, Body> {
    /// The modifiers on the `impl` block.
    /// Set to [NoOpSeq] for none, or use `SingularSeq(ModUnsafe)` to generate an `unsafe impl`.
    pub mods: Mods,
    /// The type variables to use for the impl block itself. All type variables that appear later
    /// on the trait or the receiver must be declared here, per Rust language rules.
    ///
    /// This field must be a sequence.
    pub type_variables: TypeVars,
    /// The receiver for which the implementation exists
    pub receiver: Recv,
    /// The "where" conditions. Must be a sequence. Set to [NoOpSeq] to disable.
    /// Will render as `where C1, C2, C3, ...` where CX is a value in the sequence.
    pub where_conds: Where,
    /// The body. Use [NoOp] if none exists.
    pub body: Body,
}

impl<Mods, TypeVars, Recv, Where, Body> CanHaveAttributes
    for Impl<Mods, TypeVars, Recv, Where, Body>
{
    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
        WithAttributes {
            attr,
            separator: AttributeSeparator::NewLine,
            value: self,
        }
    }
}

/// The declaration of a struct.
#[derive(Clone, Debug)]
pub struct StructDef<Mods, Name, Elements> {
    /// The struct modifiers. Must be a sequence.
    pub mods: Mods,
    /// The kind of the struct.
    ///
    /// It is suggested to use either a [NamedTuple] or [StructCall]. A semicolon will be
    /// automatically added afterward, as is needed for tuple structs, and this semicolon will not
    /// affect structs with named fields.
    pub kind: StructKind<Name, Elements>,
}

impl<Mods, Name, Elements> CanHaveAttributes for StructDef<Mods, Name, Elements> {
    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
        WithAttributes {
            attr,
            separator: AttributeSeparator::NewLine,
            value: self,
        }
    }
}

/// Completes the struct definition as either a named tuple or a struct with named fields.
#[derive(Clone, Debug)]
pub enum StructKind<Name, Elements> {
    /// A named tuple. This will function similarly to [NamedTuple], except a semicolon will
    /// be added afterward.
    ///
    /// `Name` must be writable, and `Elements` must be a writable sequence for the tuple arguments.
    Tuple(Name, Elements),
    /// A struct with named fields. This will function similarly to [StructCall].
    ///
    /// `Name` must be writable, and `Elements` must be writable sequence for the struct fields.
    NamedFields(Name, Elements),
}

/// The construction or deconstruction of a struct.
///
/// When rendered, will use the format `Name { Body }`. Spaces will be added automatically.
///
/// This should **not** be used for tuple structs, for that see [NamedTuple].
#[derive(Clone, Debug)]
pub struct StructCall<Name, Body> {
    /// The struct name. Must be writable.
    ///
    /// If you are declaring a struct for the first time, you can use [Parameterized] in order
    /// to declare type variables.
    pub name: Name,
    /// The body. Must be writable.
    ///
    /// It is suggested to use [StructFields] for multiple fields, or [DeclareField] or
    /// [FillOutField] for just one.
    pub body: Body,
}

/// Named struct fields. This will place every field on a new line with a comma afterward.
/// It is recommended that the sequence should pass [DeclareField] or [FillOutField] depending
/// upon whether the struct is being
///
/// If you have a single field, you can skip using a sequence and just use [DeclareField] or
/// [FillOutField] directly.
#[derive(Clone, Debug)]
pub struct StructFields<Fields>(pub Fields);

/// Declares a single field within a struct.
///
/// Does not add attributes. If you want to use attributes for declaration purposes, you can use
/// [CanHaveAttributes::with_attributes] on this field.
#[derive(Clone, Debug)]
pub struct DeclareField<Mods, Name, FieldType> {
    /// The field modifiers. Must be a sequence.
    pub mods: Mods,
    /// The name. Must be writable
    pub name: Name,
    /// The field type. Must be writable
    pub field_type: FieldType,
}

impl<Mods, Name, Value> CanHaveAttributes for DeclareField<Mods, Name, Value> {
    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
        WithAttributes {
            attr,
            separator: AttributeSeparator::NewLine,
            value: self,
        }
    }
}

/// Provides a field upon struct creation. Renders as `Name: Value`
#[derive(Clone, Debug)]
pub struct FillOutField<Name, Value>(pub Name, pub Value);

/// A named tuple type.
///
/// Renders as `Name(A1, A2, A3, ...)` where AX is part of the argument sequence.
/// If no arguments exist, will render only as `Name` (i.e., a unit struct).
#[derive(Clone, Debug)]
pub struct NamedTuple<Name, Args> {
    pub name: Name,
    pub args: Args,
}

/// An anonymous tuple type. This struct's tuple value must be a sequence.
///
/// Renders as `(A1, A2, A3, ...)` where AX is part of the argument sequence.
#[derive(Clone, Debug)]
pub struct AnonTuple<Args>(pub Args);

/// The unit type, i.e. `()`
pub type UnitType = AnonTuple<NoOpSeq>;

impl AnonTuple<NoOpSeq> {
    /// Creates
    pub fn unit() -> Self {
        Self(NoOpSeq)
    }
}

/// Adds attributes to ANY item.
///
/// The first tuple value must be a sequence. The second must be a writable value. This struct
/// is typically constructed via [CanHaveAttributes::with_attributes].
///
/// Rust attributes can be put in many places, so this enables you to add attributes to any
/// writable item. For example, adding attributes to function parameters can be done like so:
///
/// ```rust
/// # use async_codegen::common::{SingularSeq, Str};
/// # use async_codegen::context::EmptyContext;
/// # use async_codegen::rust::{Cfg, FunctionParam, MustUse, Target, WithAttributes, CanHaveAttributes};
/// # use async_codegen::util::InMemoryOutput;
///
/// let function_param = FunctionParam(Str("conditional_param"), Str("Fd")).with_attributes(
///   SingularSeq(Cfg(Target::Os(Str("linux"))))
/// );
/// let string = InMemoryOutput::print_output(EmptyContext, &function_param);
/// assert_eq!("#[cfg(target_os = \"linux\")] conditional_param: Fd", string);
/// ```
#[derive(Clone, Debug)]
pub struct WithAttributes<Attr, Value> {
    /// The attributes. Must be a sequence.
    pub attr: Attr,
    /// The separator between each attribute
    pub separator: AttributeSeparator,
    /// The value
    pub value: Value,
}

#[derive(Copy, Clone, Debug)]
pub enum AttributeSeparator {
    Space,
    NewLine,
}

/// A writable that can have attributes attached to it
pub trait CanHaveAttributes: Sized {
    /// Adds attributes to this writable
    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self>;
}

/// Defines an enum.
///
/// In order to use or refer to an enum, you can use [AssociatedItem] together with [NamedTuple]
/// or [StructCall].
#[derive(Clone, Debug)]
pub struct EnumDef<Mods, Name, Entries> {
    /// The modifiers on the type. Must be a sequence.
    pub mods: Mods,
    /// The name of the enum
    pub name: Name,
    /// The enum entries. Must be a sequence, each entry will be written on a new line with a comma
    ///
    /// As for the entries themselves, it is suggested to use [NamedTuple] or [StructCall]
    /// depending on which kind of enum entry you want to create.
    pub entries: Entries,
}

impl<Mods, Name, Entries> CanHaveAttributes for EnumDef<Mods, Name, Entries> {
    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
        WithAttributes {
            attr,
            separator: AttributeSeparator::NewLine,
            value: self,
        }
    }
}

/// A type argument-parameterized expression. Used in relation to parameterized names and their
/// arguments. Examples: `function_name<args>`, `TypeName<'lifetime, args>`, `MyType<Assoc=Value>`.
///
/// If no type args exist, [NoOpSeq] should be used. In any case, the second tuple value of this
/// struct must be a sequence. If they are empty, only `Name` will be rendered.
#[derive(Clone, Debug)]
pub struct Parameterized<Name, TypeArgs>(pub Name, pub TypeArgs);

/// A type variable with a sequence of bounds.
/// Will render as `TypeVar: B1 + B2 + ...`
#[derive(Clone, Debug)]
pub struct BoundedTypeVar<TypeVar, Bounds>(pub TypeVar, pub Bounds);

/// A standalone lifetime, intended to be used as a type argument or variable
#[derive(Clone, Debug)]
pub struct Lifetime<'l>(pub &'l str);

/// Renders an individual function parameter, `Name: Type`
#[derive(Clone, Debug)]
pub struct FunctionParam<Name, Type>(pub Name, pub Type);

impl<Name, Type> CanHaveAttributes for FunctionParam<Name, Type> {
    fn with_attributes<Attr>(self, attr: Attr) -> WithAttributes<Attr, Self> {
        WithAttributes {
            attr,
            separator: AttributeSeparator::Space,
            value: self,
        }
    }
}

/// A sequence acceptor that writes attributes. Every attribute will be surrounded with "#[]"
#[derive(Debug)]
pub struct AttributesAccept<'o, O, Sep> {
    inner: SurroundingSeqAccept<'o, O, Str<&'static str>, Combined<Str<&'static str>, Sep>>,
}

impl<'o, O, Sep> AttributesAccept<'o, O, Sep> {
    pub fn with_separator(output: &'o mut O, separator: Sep) -> Self {
        Self {
            inner: SurroundingSeqAccept::new(output, Str("#["), Combined(Str("]"), separator)),
        }
    }
}

impl<'o, O, Sep> SequenceAccept<O> for AttributesAccept<'o, O, Sep>
where
    O: Output,
    Sep: Writable<O>,
{
    async fn accept<W: Writable<O>>(&mut self, writable: &W) -> Result<(), O::Error> {
        self.inner.accept(writable).await
    }
}