async_codegen/rust/
syntax.rs

1/*
2 * Copyright © 2025 Anand Beh
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use super::*;
18use crate::common::{SeparatedSeqAccept, Str};
19use crate::context::ContextProvides;
20use crate::{Output, SequenceAccept, Writable, WritableSeq};
21
22impl<O, Cond, Attr> Writable<O> for CfgAttr<Cond, Attr>
23where
24    O: Output,
25    Cond: Writable<O>,
26    Attr: Writable<O>,
27{
28    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
29        output.write("cfg_attr(").await?;
30        self.0.write_to(output).await?;
31        output.write(", ").await?;
32        self.1.write_to(output).await?;
33        output.write(")").await
34    }
35}
36
37impl<O, Cond> Writable<O> for Cfg<Cond>
38where
39    O: Output,
40    Cond: Writable<O>,
41{
42    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
43        output.write("cfg(").await?;
44        self.0.write_to(output).await?;
45        output.write(")").await
46    }
47}
48
49impl<O, Value> Writable<O> for Target<Value>
50where
51    O: Output,
52    Value: Writable<O>,
53{
54    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
55        let (kind, value) = match self {
56            Self::Os(value) => ("os", value),
57            Self::Family(value) => ("family", value),
58            Self::Arch(value) => ("arch", value),
59        };
60        output.write("target_").await?;
61        output.write(kind).await?;
62        output.write(" = \"").await?;
63        value.write_to(output).await?;
64        output.write("\"").await
65    }
66}
67
68impl<O> Writable<O> for NoMangle
69where
70    O: Output,
71    O::Ctx: ContextProvides<Edition>,
72{
73    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
74        let edition = output.get_ctx();
75        output
76            .write(if edition >= &Edition::Rust2024 {
77                "unsafe(no_mangle)"
78            } else {
79                "no_mangle"
80            })
81            .await
82    }
83}
84
85impl<O, Lints> Writable<O> for AllowLints<Lints>
86where
87    O: Output,
88    Lints: WritableSeq<O>,
89{
90    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
91        let mut acceptor = SeparatedSeqAccept::new(output, Str("allow("), Str(","));
92        self.0.for_each(&mut acceptor).await?;
93        if acceptor.wrote_any {
94            output.write(")").await?;
95        }
96        Ok(())
97    }
98}
99
100impl<O, Msg, Since> Writable<O> for Deprecated<Msg, Since>
101where
102    O: Output,
103    Msg: Writable<O>,
104    Since: Writable<O>,
105{
106    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
107        match self {
108            Self::Basic => output.write("deprecated").await,
109            Self::Message(msg) => {
110                output.write("deprecated = \"").await?;
111                msg.write_to(output).await?;
112                output.write("\"").await
113            }
114            Self::Full { since, note } => {
115                output.write("deprecated(since = \"").await?;
116                since.write_to(output).await?;
117                output.write("\", note = \"").await?;
118                note.write_to(output).await?;
119                output.write("\")").await
120            }
121        }
122    }
123}
124
125impl<O> Writable<O> for MustUse
126where
127    O: Output,
128{
129    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
130        output.write("must_use").await
131    }
132}
133
134impl<O> Writable<O> for ModPub
135where
136    O: Output,
137{
138    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
139        output.write("pub").await
140    }
141}
142
143impl<O, Abi> Writable<O> for ModUnsafeExtern<Abi>
144where
145    O: Output,
146    Abi: Writable<O>,
147{
148    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
149        output.write("unsafe extern \"").await?;
150        self.0.write_to(output).await?;
151        output.write("\"").await
152    }
153}
154
155impl<O, Attr, Abi, Body> Writable<O> for ExternBlock<Attr, Abi, Body>
156where
157    O: Output,
158    O::Ctx: ContextProvides<Edition>,
159    Attr: WritableSeq<O>,
160    Abi: Writable<O>,
161    Body: Writable<O>,
162{
163    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
164        self.attr
165            .for_each(&mut AttributesAccept::new(output))
166            .await?;
167        let edition = output.get_ctx();
168        if edition >= &Edition::Rust2024 {
169            output.write("unsafe ").await?;
170        }
171        output.write("extern \"").await?;
172        self.abi.write_to(output).await?;
173        output.write("\" {").await?;
174        self.body.write_to(output).await?;
175        output.write("}").await
176    }
177}
178
179impl<O: Output, Expr> Writable<O> for UnsafeBlock<Expr>
180where
181    Expr: Writable<O>,
182{
183    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
184        o.write("unsafe {\n").await?;
185        self.0.write_to(o).await?;
186        o.write("\n}").await?;
187        Ok(())
188    }
189}
190
191impl<O, InputVars, Expr> Writable<O> for Closure<InputVars, Expr>
192where
193    O: Output,
194    InputVars: WritableSeq<O>,
195    Expr: Writable<O>,
196{
197    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
198        o.write("|").await?;
199        self.input_vars
200            .for_each(&mut SeparatedSeqAccept::comma_separated(o))
201            .await?;
202        o.write("| {\n").await?;
203        self.inside_block.write_to(o).await?;
204        o.write("\n}").await?;
205        Ok(())
206    }
207}
208
209impl<O: Output, Recv, FuncName, Args> Writable<O> for FunctionCall<Recv, FuncName, Args>
210where
211    Recv: Writable<O>,
212    FuncName: Writable<O>,
213    Args: WritableSeq<O>,
214{
215    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
216        self.receiver.write_to(o).await?;
217        o.write(if self.is_assoc { "::" } else { "." }).await?;
218        self.function.write_to(o).await
219    }
220}
221
222impl<O: Output, Variable, Expr> Writable<O> for LetStmt<Variable, Expr>
223where
224    Variable: Writable<O>,
225    Expr: Writable<O>,
226{
227    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
228        o.write("let ").await?;
229        self.0.write_to(o).await?;
230        o.write(" = ").await?;
231        self.1.write_to(o).await?;
232        o.write(";\n").await?;
233        Ok(())
234    }
235}
236
237impl<O: Output, Cont, Item> Writable<O> for AssociatedItem<Cont, Item>
238where
239    Cont: Writable<O>,
240    Item: Writable<O>,
241{
242    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
243        self.0.write_to(o).await?;
244        o.write("::").await?;
245        self.1.write_to(o).await
246    }
247}
248
249impl<O: Output, Expr> Writable<O> for QuestionMarkAfter<Expr>
250where
251    Expr: Writable<O>,
252{
253    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
254        self.0.write_to(o).await?;
255        o.write("?").await?;
256        Ok(())
257    }
258}
259
260impl<O: Output, Expr> Writable<O> for OkResultOf<Expr>
261where
262    Expr: Writable<O>,
263{
264    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
265        o.write("Ok(").await?;
266        self.0.write_to(o).await?;
267        o.write(")").await?;
268        Ok(())
269    }
270}
271
272impl<O: Output, Type, Trait> Writable<O> for TypeAsTrait<Type, Trait>
273where
274    Type: Writable<O>,
275    Trait: Writable<O>,
276{
277    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
278        o.write("<").await?;
279        self.0.write_to(o).await?;
280        o.write(" as ").await?;
281        self.1.write_to(o).await?;
282        o.write(">").await?;
283        Ok(())
284    }
285}
286
287impl<O, Attr, Mods, Name, Args, Return, Body> Writable<O>
288    for FunctionDef<Attr, Mods, Name, Args, Return, Body>
289where
290    O: Output,
291    Attr: WritableSeq<O>,
292    Mods: WritableSeq<O>,
293    Name: Writable<O>,
294    Args: WritableSeq<O>,
295    Return: Writable<O>,
296    Body: Writable<O>,
297{
298    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
299        self.attr.for_each(&mut AttributesAccept::new(o)).await?;
300        self.mods.for_each(&mut ModsAccept(o)).await?;
301        o.write("fn ").await?;
302        self.decl.write_to(o).await?;
303        o.write(" -> ").await?;
304        self.return_type.write_to(o).await?;
305        self.body.write_to(o).await?;
306        o.write("\n").await?;
307        Ok(())
308    }
309}
310
311impl<O, Name, Args> Writable<O> for Function<Name, Args>
312where
313    O: Output,
314    Name: Writable<O>,
315    Args: WritableSeq<O>,
316{
317    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
318        self.name.write_to(output).await?;
319        output.write("(").await?;
320        self.args
321            .for_each(&mut SeparatedSeqAccept::comma_separated(output))
322            .await?;
323        output.write(")").await
324    }
325}
326
327impl<O: Output> Writable<O> for BodyDeclare {
328    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
329        output.write(";").await
330    }
331}
332
333impl<O: Output, Type, Value> Writable<O> for AssociatedTypeEquals<Type, Value>
334where
335    Type: Writable<O>,
336    Value: Writable<O>,
337{
338    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
339        self.0.write_to(o).await?;
340        o.write("=").await?;
341        self.1.write_to(o).await
342    }
343}
344
345impl<O: Output, Type> Writable<O> for DynOf<Type>
346where
347    Type: Writable<O>,
348{
349    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
350        o.write("dyn ").await?;
351        self.0.write_to(o).await
352    }
353}
354
355impl<O: Output, Type> Writable<O> for RefOf<Type>
356where
357    Type: Writable<O>,
358{
359    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
360        o.write("&").await?;
361        self.0.write_to(o).await
362    }
363}
364
365impl<O: Output, Type> Writable<O> for ImplOf<Type>
366where
367    Type: Writable<O>,
368{
369    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
370        o.write("impl ").await?;
371        self.0.write_to(o).await
372    }
373}
374
375impl<O: Output, Type> Writable<O> for LifetimedRefOf<'_, Type>
376where
377    Type: Writable<O>,
378{
379    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
380        o.write("&'").await?;
381        o.write(self.0).await?;
382        o.write(" ").await?;
383        self.1.write_to(o).await
384    }
385}
386
387impl<O: Output, VarName, Value> Writable<O> for AssociatedTypeDef<VarName, Value>
388where
389    VarName: Writable<O>,
390    Value: Writable<O>,
391{
392    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
393        o.write("\ntype ").await?;
394        self.0.write_to(o).await?;
395        o.write(" = ").await?;
396        self.1.write_to(o).await?;
397        o.write(";\n").await?;
398        Ok(())
399    }
400}
401
402impl<O, Attr, Mods, Name, TypeVars, SuperTraits, Body> Writable<O>
403    for TraitDef<Attr, Mods, Name, TypeVars, SuperTraits, Body>
404where
405    O: Output,
406    Attr: WritableSeq<O>,
407    Mods: WritableSeq<O>,
408    Name: Writable<O>,
409    TypeVars: WritableSeq<O>,
410    SuperTraits: WritableSeq<O>,
411    Body: Writable<O>,
412{
413    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
414        self.attr.for_each(&mut AttributesAccept::new(o)).await?;
415        self.mods.for_each(&mut ModsAccept(o)).await?;
416        o.write("trait ").await?;
417        self.name.write_to(o).await?;
418        TypeArgAccept::new(o)
419            .write_inside_diamond(&self.type_variables)
420            .await?;
421        self.super_traits
422            .for_each(&mut type_arg_bound_accept(o))
423            .await?;
424        o.write(" {").await?;
425        self.body.write_to(o).await?;
426        o.write("}").await?;
427        Ok(())
428    }
429}
430
431impl<O, TypeVars, Trait, Recv, Body> Writable<O> for TraitImpl<TypeVars, Trait, Recv, Body>
432where
433    O: Output,
434    TypeVars: WritableSeq<O>,
435    Trait: Writable<O>,
436    Recv: Writable<O>,
437    Body: Writable<O>,
438{
439    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
440        o.write("impl").await?;
441        TypeArgAccept::new(o)
442            .write_inside_diamond(&self.type_variables)
443            .await?;
444        o.write(" ").await?;
445        self.the_trait.write_to(o).await?;
446        o.write(" for ").await?;
447        self.receiver.write_to(o).await?;
448        o.write(" {").await?;
449        self.body.write_to(o).await?;
450        o.write("}").await?;
451        Ok(())
452    }
453}
454
455impl<O, Attr, Mods, Name, Elements> Writable<O> for StructDef<Attr, Mods, Name, Elements>
456where
457    O: Output,
458    Attr: WritableSeq<O>,
459    Mods: WritableSeq<O>,
460    Name: Writable<O>,
461    Elements: WritableSeq<O>,
462{
463    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
464        self.attr.for_each(&mut AttributesAccept::new(o)).await?;
465        self.mods.for_each(&mut ModsAccept(o)).await?;
466        o.write("struct ").await?;
467        match &self.kind {
468            StructKind::Tuple(name, elements) => {
469                NamedTuple {
470                    name,
471                    args: elements
472                }
473                .write_to(o)
474                .await?;
475                o.write(";").await
476            }
477            StructKind::NamedFields(name, elements) => {
478                StructCall {
479                    name,
480                    body: StructFields(elements),
481                }
482                .write_to(o)
483                .await
484            }
485        }
486    }
487}
488
489impl<O, Name, Body> Writable<O> for StructCall<Name, Body>
490where
491    O: Output,
492    Name: Writable<O>,
493    Body: Writable<O>,
494{
495    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
496        self.name.write_to(o).await?;
497        o.write(" { ").await?;
498        self.body.write_to(o).await?;
499        o.write(" }").await
500    }
501}
502
503impl<O, Fields> Writable<O> for StructFields<Fields>
504where
505    O: Output,
506    Fields: WritableSeq<O>,
507{
508    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
509        self.0.for_each(&mut struct_fields_accept(output)).await
510    }
511}
512
513impl<O, Name, Value> Writable<O> for DeclareField<Name, Value>
514where
515    O: Output,
516    Name: Writable<O>,
517    Value: Writable<O>,
518{
519    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
520        FunctionParam(&self.0, &self.1).write_to(o).await
521    }
522}
523
524impl<O, Name, Args> Writable<O> for NamedTuple<Name, Args>
525where
526    O: Output,
527    Name: Writable<O>,
528    Args: WritableSeq<O>,
529{
530    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
531        self.name.write_to(output).await?;
532        // Only write the parentheses if arguments is non-empty
533        let mut separator = SeparatedSeqAccept::new(output, Str("("), Str(", "));
534        self.args.for_each(&mut separator).await?;
535        if separator.wrote_any {
536            output.write(")").await?;
537        }
538        Ok(())
539    }
540}
541
542impl<O, Args> Writable<O> for AnonTuple<Args>
543where
544    O: Output,
545    Args: WritableSeq<O>,
546{
547    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
548        o.write("(").await?;
549        self.0
550            .for_each(&mut SeparatedSeqAccept::comma_separated(o))
551            .await?;
552        o.write(")").await
553    }
554}
555
556impl<O, Attr, Value> Writable<O> for WithAttributes<Attr, Value>
557where
558    O: Output,
559    Attr: WritableSeq<O>,
560    Value: Writable<O>,
561{
562    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
563        self.0.for_each(&mut AttributesAccept::new(output)).await?;
564        self.1.write_to(output).await
565    }
566}
567
568impl<O, Attr, Mods, Name, Entries> Writable<O> for EnumDef<Attr, Mods, Name, Entries>
569where
570    O: Output,
571    Attr: WritableSeq<O>,
572    Mods: WritableSeq<O>,
573    Name: Writable<O>,
574    Entries: WritableSeq<O>,
575{
576    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
577        self.attr
578            .for_each(&mut AttributesAccept::new(output))
579            .await?;
580        self.mods.for_each(&mut ModsAccept(output)).await?;
581        output.write("enum ").await?;
582        self.name.write_to(output).await?;
583        output.write(" {").await?;
584        self.entries
585            .for_each(&mut SeparatedSeqAccept::comma_separated(output))
586            .await?;
587        output.write("}").await
588    }
589}
590
591impl<O, Name, TypeArgs> Writable<O> for Parameterized<Name, TypeArgs>
592where
593    O: Output,
594    Name: Writable<O>,
595    TypeArgs: WritableSeq<O>,
596{
597    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
598        self.name.write_to(o).await?;
599        TypeArgAccept::new(o)
600            .write_inside_diamond(&self.type_args)
601            .await
602    }
603}
604
605impl<O, TypeVar, Bounds> Writable<O> for BoundedTypeVar<TypeVar, Bounds>
606where
607    O: Output,
608    TypeVar: Writable<O>,
609    Bounds: WritableSeq<O>,
610{
611    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
612        self.0.write_to(output).await?;
613        self.1.for_each(&mut type_arg_bound_accept(output)).await
614    }
615}
616
617impl<O> Writable<O> for Lifetime<'_>
618where
619    O: Output,
620{
621    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
622        output.write("'").await?;
623        output.write(self.0).await
624    }
625}
626
627impl<O, Name, Type> Writable<O> for FunctionParam<Name, Type>
628where
629    O: Output,
630    Name: Writable<O>,
631    Type: Writable<O>,
632{
633    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
634        self.0.write_to(output).await?;
635        output.write(": ").await?;
636        self.1.write_to(output).await
637    }
638}
639
640//
641// Sequence acceptors
642//
643
644struct ModsAccept<'o, O>(&'o mut O);
645
646impl<'o, O: Output> SequenceAccept<O> for ModsAccept<'o, O> {
647    async fn accept<W>(&mut self, writable: &W) -> Result<(), O::Error>
648    where
649        W: Writable<O>,
650    {
651        writable.write_to(&mut self.0).await?;
652        self.0.write(" ").await
653    }
654}
655
656struct TypeArgAccept<'o, O> {
657    inner: SeparatedSeqAccept<'o, O, Str<&'static str>, Str<&'static str>>,
658}
659
660impl<'o, O> TypeArgAccept<'o, O> {
661    fn new(output: &'o mut O) -> Self {
662        Self {
663            inner: SeparatedSeqAccept::new(output, Str("<"), Str(", ")),
664        }
665    }
666}
667
668impl<'o, O> TypeArgAccept<'o, O>
669where
670    O: Output,
671{
672    async fn write_inside_diamond<TypeArgs>(&mut self, type_args: &TypeArgs) -> Result<(), O::Error>
673    where
674        TypeArgs: WritableSeq<O>,
675    {
676        type_args.for_each(&mut self.inner).await?;
677        if self.inner.wrote_any {
678            self.inner.output.write(">").await?;
679        }
680        Ok(())
681    }
682}
683
684fn type_arg_bound_accept<'o, O>(
685    output: &'o mut O,
686) -> SeparatedSeqAccept<'o, O, Str<&'static str>, Str<&'static str>> {
687    SeparatedSeqAccept::new(output, Str(": "), Str(" + "))
688}
689
690fn struct_fields_accept<'o, O>(
691    output: &'o mut O,
692) -> SeparatedSeqAccept<'o, O, Str<&'static str>, Str<&'static str>> {
693    SeparatedSeqAccept::new(output, Str("\n"), Str(",\n"))
694}