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