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