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, Variable, Expr> Writable<O> for LetStmt<Variable, Expr>
232where
233    Variable: Writable<O>,
234    Expr: Writable<O>,
235{
236    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
237        o.write("let ").await?;
238        AssignStmt(&self.0, &self.1).write_to(o).await
239    }
240}
241
242impl<O: Output, Variable, Expr> Writable<O> for AssignStmt<Variable, Expr> where Variable: Writable<O>, Expr: Writable<O> {
243    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
244        self.0.write_to(o).await?;
245        o.write(" = ").await?;
246        self.1.write_to(o).await?;
247        o.write(";\n").await?;
248        Ok(())
249    }
250}
251
252impl<O: Output, Cont, Item> Writable<O> for AssociatedItem<Cont, Item>
253where
254    Cont: Writable<O>,
255    Item: Writable<O>,
256{
257    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
258        self.0.write_to(o).await?;
259        o.write("::").await?;
260        self.1.write_to(o).await
261    }
262}
263
264impl<O: Output, Expr> Writable<O> for QuestionMarkAfter<Expr>
265where
266    Expr: Writable<O>,
267{
268    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
269        self.0.write_to(o).await?;
270        o.write("?").await?;
271        Ok(())
272    }
273}
274
275impl<O: Output, Expr> Writable<O> for OkResultOf<Expr>
276where
277    Expr: Writable<O>,
278{
279    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
280        o.write("Ok(").await?;
281        self.0.write_to(o).await?;
282        o.write(")").await?;
283        Ok(())
284    }
285}
286
287impl<O: Output, Type, Trait> Writable<O> for TypeAsTrait<Type, Trait>
288where
289    Type: Writable<O>,
290    Trait: Writable<O>,
291{
292    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
293        o.write("<").await?;
294        self.0.write_to(o).await?;
295        o.write(" as ").await?;
296        self.1.write_to(o).await?;
297        o.write(">").await?;
298        Ok(())
299    }
300}
301
302impl<O, Mods, Name, Args, Return, Where, Body> Writable<O>
303    for FunctionDef<Mods, Name, Args, Return, Where, Body>
304where
305    O: Output,
306    Mods: WritableSeq<O>,
307    Name: Writable<O>,
308    Args: WritableSeq<O>,
309    Return: Writable<O>,
310    Where: WritableSeq<O>,
311    Body: Writable<O>,
312{
313    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
314        self.mods.for_each(&mut ModsAccept(o)).await?;
315        o.write("fn ").await?;
316        self.name.write_to(o).await?;
317        AnonTuple(&self.args).write_to(o).await?;
318        o.write(" -> ").await?;
319        self.return_type.write_to(o).await?;
320        self.where_conds.for_each(&mut where_cond_accept(o)).await?;
321        self.body.write_to(o).await?;
322        o.write("\n").await?;
323        Ok(())
324    }
325}
326
327impl<O: Output> Writable<O> for FunctionBodyDeclare {
328    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
329        output.write(";").await
330    }
331}
332
333impl<O: Output, Inner> Writable<O> for FunctionBodyImplement<Inner>
334where
335    Inner: Writable<O>,
336{
337    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
338        output.write("{\n").await?;
339        self.0.write_to(output).await?;
340        output.write("\n}").await
341    }
342}
343
344impl<O, Args, Return> Writable<O> for FunctionPtr<Args, Return>
345where
346    O: Output,
347    Args: WritableSeq<O>,
348    Return: Writable<O>,
349{
350    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
351        let kind = match self.kind {
352            FunctionPtrKind::FnPtr => "fn",
353            FunctionPtrKind::Fn => "Fn",
354            FunctionPtrKind::FnMut => "FnMut",
355            FunctionPtrKind::FnOnce => "FnOnce",
356        };
357        output.write(kind).await?;
358        AnonTuple(&self.args).write_to(output).await?;
359        output.write(" -> ").await?;
360        self.return_type.write_to(output).await
361    }
362}
363
364impl<O: Output, Type, Value> Writable<O> for AssociatedTypeEquals<Type, Value>
365where
366    Type: Writable<O>,
367    Value: Writable<O>,
368{
369    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
370        self.0.write_to(o).await?;
371        o.write("=").await?;
372        self.1.write_to(o).await
373    }
374}
375
376impl<O: Output, Type> Writable<O> for DynOf<Type>
377where
378    Type: Writable<O>,
379{
380    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
381        o.write("dyn ").await?;
382        self.0.write_to(o).await
383    }
384}
385
386impl<O: Output, Type> Writable<O> for RefOf<Type>
387where
388    Type: Writable<O>,
389{
390    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
391        o.write("&").await?;
392        self.0.write_to(o).await
393    }
394}
395
396impl<O: Output, Type> Writable<O> for ImplOf<Type>
397where
398    Type: Writable<O>,
399{
400    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
401        o.write("impl ").await?;
402        self.0.write_to(o).await
403    }
404}
405
406impl<O: Output, Type> Writable<O> for LifetimedRefOf<'_, Type>
407where
408    Type: Writable<O>,
409{
410    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
411        o.write("&'").await?;
412        o.write(self.0).await?;
413        o.write(" ").await?;
414        self.1.write_to(o).await
415    }
416}
417
418impl<O: Output, VarName, Value> Writable<O> for AssociatedTypeDef<VarName, Value>
419where
420    VarName: Writable<O>,
421    Value: Writable<O>,
422{
423    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
424        o.write("\ntype ").await?;
425        self.0.write_to(o).await?;
426        o.write(" = ").await?;
427        self.1.write_to(o).await?;
428        o.write(";\n").await?;
429        Ok(())
430    }
431}
432
433impl<O, Mods, Name, TypeVars, SuperTraits, Body> Writable<O>
434    for TraitDef<Mods, Name, TypeVars, SuperTraits, Body>
435where
436    O: Output,
437    Mods: WritableSeq<O>,
438    Name: Writable<O>,
439    TypeVars: WritableSeq<O>,
440    SuperTraits: WritableSeq<O>,
441    Body: Writable<O>,
442{
443    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
444        self.mods.for_each(&mut ModsAccept(o)).await?;
445        o.write("trait ").await?;
446        self.name.write_to(o).await?;
447        TypeArgAccept::new(o)
448            .write_inside_diamond(&self.type_variables)
449            .await?;
450        self.super_traits
451            .for_each(&mut type_arg_bound_accept(o))
452            .await?;
453        o.write(" {").await?;
454        self.body.write_to(o).await?;
455        o.write("}").await?;
456        Ok(())
457    }
458}
459
460impl<O, TypeVars, Trait, Recv, Where, Body> Writable<O>
461    for TraitImpl<TypeVars, Trait, Recv, Where, Body>
462where
463    O: Output,
464    TypeVars: WritableSeq<O>,
465    Trait: Writable<O>,
466    Recv: Writable<O>,
467    Where: WritableSeq<O>,
468    Body: Writable<O>,
469{
470    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
471        o.write("impl").await?;
472        TypeArgAccept::new(o)
473            .write_inside_diamond(&self.type_variables)
474            .await?;
475        o.write(" ").await?;
476        self.the_trait.write_to(o).await?;
477        o.write(" for ").await?;
478        self.receiver.write_to(o).await?;
479        self.where_conds.for_each(&mut where_cond_accept(o)).await?;
480        o.write(" {").await?;
481        self.body.write_to(o).await?;
482        o.write("}").await?;
483        Ok(())
484    }
485}
486
487impl<O, Mods, Name, Elements> Writable<O> for StructDef<Mods, Name, Elements>
488where
489    O: Output,
490    Mods: WritableSeq<O>,
491    Name: Writable<O>,
492    Elements: WritableSeq<O>,
493{
494    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
495        self.mods.for_each(&mut ModsAccept(o)).await?;
496        o.write("struct ").await?;
497        match &self.kind {
498            StructKind::Tuple(name, elements) => {
499                NamedTuple {
500                    name,
501                    args: elements,
502                }
503                .write_to(o)
504                .await?;
505                o.write(";").await
506            }
507            StructKind::NamedFields(name, elements) => {
508                StructCall {
509                    name,
510                    body: StructFields(elements),
511                }
512                .write_to(o)
513                .await
514            }
515        }
516    }
517}
518
519impl<O, Name, Body> Writable<O> for StructCall<Name, Body>
520where
521    O: Output,
522    Name: Writable<O>,
523    Body: Writable<O>,
524{
525    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
526        self.name.write_to(o).await?;
527        o.write(" { ").await?;
528        self.body.write_to(o).await?;
529        o.write(" }").await
530    }
531}
532
533impl<O, Fields> Writable<O> for StructFields<Fields>
534where
535    O: Output,
536    Fields: WritableSeq<O>,
537{
538    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
539        self.0.for_each(&mut struct_fields_accept(output)).await
540    }
541}
542
543impl<O, Name, Value> Writable<O> for DeclareField<Name, Value>
544where
545    O: Output,
546    Name: Writable<O>,
547    Value: Writable<O>,
548{
549    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
550        FunctionParam(&self.0, &self.1).write_to(o).await
551    }
552}
553
554impl<O, Name, Args> Writable<O> for NamedTuple<Name, Args>
555where
556    O: Output,
557    Name: Writable<O>,
558    Args: WritableSeq<O>,
559{
560    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
561        self.name.write_to(output).await?;
562        // Only write the parentheses if arguments is non-empty
563        let mut separator = SeparatedSeqAccept::new(output, Str("("), Str(", "));
564        self.args.for_each(&mut separator).await?;
565        if separator.wrote_any {
566            output.write(")").await?;
567        }
568        Ok(())
569    }
570}
571
572impl<O, Args> Writable<O> for AnonTuple<Args>
573where
574    O: Output,
575    Args: WritableSeq<O>,
576{
577    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
578        o.write("(").await?;
579        self.0
580            .for_each(&mut SeparatedSeqAccept::comma_separated(o))
581            .await?;
582        o.write(")").await
583    }
584}
585
586impl<O, Attr, Value> Writable<O> for WithAttributes<Attr, Value>
587where
588    O: Output,
589    Attr: WritableSeq<O>,
590    Value: Writable<O>,
591{
592    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
593        self.attr
594            .for_each(&mut AttributesAccept::with_separator(
595                output,
596                self.separator,
597            ))
598            .await?;
599        self.value.write_to(output).await
600    }
601}
602
603impl<O, Mods, Name, Entries> Writable<O> for EnumDef<Mods, Name, Entries>
604where
605    O: Output,
606    Mods: WritableSeq<O>,
607    Name: Writable<O>,
608    Entries: WritableSeq<O>,
609{
610    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
611        self.mods.for_each(&mut ModsAccept(output)).await?;
612        output.write("enum ").await?;
613        self.name.write_to(output).await?;
614        output.write(" {").await?;
615        self.entries
616            .for_each(&mut SeparatedSeqAccept::comma_separated(output))
617            .await?;
618        output.write("}").await
619    }
620}
621
622impl<O, Name, TypeArgs> Writable<O> for Parameterized<Name, TypeArgs>
623where
624    O: Output,
625    Name: Writable<O>,
626    TypeArgs: WritableSeq<O>,
627{
628    async fn write_to(&self, o: &mut O) -> Result<(), O::Error> {
629        self.name.write_to(o).await?;
630        TypeArgAccept::new(o)
631            .write_inside_diamond(&self.type_args)
632            .await
633    }
634}
635
636impl<O, TypeVar, Bounds> Writable<O> for BoundedTypeVar<TypeVar, Bounds>
637where
638    O: Output,
639    TypeVar: Writable<O>,
640    Bounds: WritableSeq<O>,
641{
642    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
643        self.0.write_to(output).await?;
644        self.1.for_each(&mut type_arg_bound_accept(output)).await
645    }
646}
647
648impl<O> Writable<O> for Lifetime<'_>
649where
650    O: Output,
651{
652    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
653        output.write("'").await?;
654        output.write(self.0).await
655    }
656}
657
658impl<O, Name, Type> Writable<O> for FunctionParam<Name, Type>
659where
660    O: Output,
661    Name: Writable<O>,
662    Type: Writable<O>,
663{
664    async fn write_to(&self, output: &mut O) -> Result<(), O::Error> {
665        self.0.write_to(output).await?;
666        output.write(": ").await?;
667        self.1.write_to(output).await
668    }
669}
670
671//
672// Sequence acceptors
673//
674
675struct ModsAccept<'o, O>(&'o mut O);
676
677impl<'o, O: Output> SequenceAccept<O> for ModsAccept<'o, O> {
678    async fn accept<W>(&mut self, writable: &W) -> Result<(), O::Error>
679    where
680        W: Writable<O>,
681    {
682        writable.write_to(&mut self.0).await?;
683        self.0.write(" ").await
684    }
685}
686
687struct TypeArgAccept<'o, O> {
688    inner: SeparatedSeqAccept<'o, O, Str<&'static str>, Str<&'static str>>,
689}
690
691impl<'o, O> TypeArgAccept<'o, O> {
692    fn new(output: &'o mut O) -> Self {
693        Self {
694            inner: SeparatedSeqAccept::new(output, Str("<"), Str(", ")),
695        }
696    }
697}
698
699impl<'o, O> TypeArgAccept<'o, O>
700where
701    O: Output,
702{
703    async fn write_inside_diamond<TypeArgs>(&mut self, type_args: &TypeArgs) -> Result<(), O::Error>
704    where
705        TypeArgs: WritableSeq<O>,
706    {
707        type_args.for_each(&mut self.inner).await?;
708        if self.inner.wrote_any {
709            self.inner.output.write(">").await?;
710        }
711        Ok(())
712    }
713}
714
715fn type_arg_bound_accept<'o, O>(
716    output: &'o mut O,
717) -> SeparatedSeqAccept<'o, O, Str<&'static str>, Str<&'static str>> {
718    SeparatedSeqAccept::new(output, Str(": "), Str(" + "))
719}
720
721fn struct_fields_accept<'o, O>(
722    output: &'o mut O,
723) -> SeparatedSeqAccept<'o, O, Str<&'static str>, Str<&'static str>> {
724    SeparatedSeqAccept::new(output, Str("\n"), Str(",\n"))
725}
726
727fn where_cond_accept<'o, O>(
728    output: &'o mut O,
729) -> SeparatedSeqAccept<'o, O, Str<&'static str>, Str<&'static str>> {
730    SeparatedSeqAccept::new(output, Str(" where "), Str(", "))
731}