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