Skip to main content

aldrin_codegen/
rust.rs

1#[cfg(test)]
2mod test;
3
4pub mod names;
5
6use crate::Options;
7use crate::error::Error;
8use aldrin_parser::{LinkResolver, Parser, ResolvedLink, Schema, ast};
9use comrak::nodes::NodeValue;
10use comrak::options::BrokenLinkReference;
11use comrak::{Arena, Options as ComrakOptions, ResolvedReference};
12use diffy::Patch;
13use std::fmt::Write;
14use std::fs;
15use std::path::Path;
16use std::sync::Arc;
17
18const BOOL: &str = "::std::primitive::bool";
19const BOX: &str = "::std::boxed::Box";
20const CLONE: &str = "::std::clone::Clone";
21const DEBUG: &str = "::std::fmt::Debug";
22const DEFAULT: &str = "::std::default::Default";
23const EQ: &str = "::std::cmp::Eq";
24const F32: &str = "::std::primitive::f32";
25const F64: &str = "::std::primitive::f64";
26const HASH: &str = "::std::hash::Hash";
27const HASH_MAP: &str = "::std::collections::HashMap";
28const HASH_SET: &str = "::std::collections::HashSet";
29const I16: &str = "::std::primitive::i16";
30const I32: &str = "::std::primitive::i32";
31const I64: &str = "::std::primitive::i64";
32const I8: &str = "::std::primitive::i8";
33const OK: &str = "::std::result::Result::Ok";
34const OPTION: &str = "::std::option::Option";
35const ORD: &str = "::std::cmp::Ord";
36const PARTIAL_EQ: &str = "::std::cmp::PartialEq";
37const PARTIAL_ORD: &str = "::std::cmp::PartialOrd";
38const RESULT: &str = "::std::result::Result";
39const STR: &str = "::std::primitive::str";
40const STRING: &str = "::std::string::String";
41const U16: &str = "::std::primitive::u16";
42const U32: &str = "::std::primitive::u32";
43const U64: &str = "::std::primitive::u64";
44const U8: &str = "::std::primitive::u8";
45const VEC: &str = "::std::vec::Vec";
46
47#[derive(Debug, Clone)]
48#[non_exhaustive]
49pub struct RustOptions<'a> {
50    pub patches: Vec<&'a Path>,
51    pub introspection_if: Option<&'a str>,
52    pub krate: Option<&'a str>,
53}
54
55impl<'a> RustOptions<'a> {
56    pub fn new() -> Self {
57        RustOptions {
58            patches: Vec::new(),
59            introspection_if: None,
60            krate: None,
61        }
62    }
63
64    pub fn krate_or_default(&self) -> &'a str {
65        self.krate.unwrap_or("::aldrin")
66    }
67}
68
69impl Default for RustOptions<'_> {
70    fn default() -> Self {
71        RustOptions::new()
72    }
73}
74
75#[derive(Debug, Clone)]
76pub struct RustOutput {
77    pub module_name: String,
78    pub module_content: String,
79}
80
81pub(crate) fn generate(
82    parser: &Parser,
83    options: &Options,
84    rust_options: &RustOptions,
85) -> Result<RustOutput, Error> {
86    let schema = parser.main_schema();
87
88    let generator = RustGenerator {
89        parser,
90        schema,
91        options,
92        rust_options,
93        output: RustOutput {
94            module_name: schema.name().to_owned(),
95            module_content: String::new(),
96        },
97    };
98
99    generator.generate()
100}
101
102struct RustGenerator<'a> {
103    parser: &'a Parser,
104    schema: &'a Schema,
105    options: &'a Options,
106    rust_options: &'a RustOptions<'a>,
107    output: RustOutput,
108}
109
110macro_rules! code {
111    ($this:expr, $arg:literal) => {
112        write!($this.output.module_content, $arg).unwrap()
113    };
114}
115
116macro_rules! codeln {
117    ($this:expr) => {
118        writeln!($this.output.module_content).unwrap()
119    };
120
121    ($this:expr, $arg:literal) => {
122        writeln!($this.output.module_content, $arg).unwrap()
123    };
124}
125
126#[rustfmt::skip::macros(code, codeln)]
127impl RustGenerator<'_> {
128    fn generate(mut self) -> Result<RustOutput, Error> {
129        let (doc, _) = self.doc_string_inner(self.schema.doc(), 0);
130        if !doc.is_empty() {
131            codeln!(self, "{doc}");
132        }
133
134        for def in self.schema.definitions() {
135            self.definition(def);
136        }
137
138        if self.options.introspection {
139            let krate = self.rust_options.krate_or_default();
140            let name = names::register_introspection(self.schema.name());
141
142            if let Some(feature) = self.rust_options.introspection_if {
143                codeln!(self, "#[cfg(feature = \"{feature}\")]");
144            }
145
146            codeln!(self, "pub fn {name}(client: &{krate}::Handle) -> {RESULT}<(), {krate}::Error> {{");
147
148            for def in self.schema.definitions() {
149                self.register_introspection(def);
150            }
151
152            codeln!(self, "    {OK}(())");
153            codeln!(self, "}}");
154        }
155
156        for patch in &self.rust_options.patches {
157            self.patch(patch)?;
158        }
159
160        Ok(self.output)
161    }
162
163    fn patch(&mut self, patch: &Path) -> Result<(), Error> {
164        let patch = fs::read_to_string(patch)?;
165        let patch = Patch::from_str(&patch)?;
166        self.output.module_content = diffy::apply(&self.output.module_content, &patch)?;
167        Ok(())
168    }
169
170    fn definition(&mut self, def: &ast::Definition) {
171        match def {
172            ast::Definition::Struct(d) => self.struct_def(
173                d.name().value(),
174                d.doc(),
175                d.attributes(),
176                d.fields(),
177                d.fallback(),
178            ),
179
180            ast::Definition::Enum(e) => self.enum_def(
181                e.name().value(),
182                e.doc(),
183                e.attributes(),
184                e.variants(),
185                e.fallback(),
186            ),
187
188            ast::Definition::Service(s) => self.service_def(s),
189            ast::Definition::Const(c) => self.const_def(c),
190            ast::Definition::Newtype(n) => self.newtype_def(n),
191        }
192    }
193
194    fn struct_def(
195        &mut self,
196        name: &str,
197        doc: &[ast::DocString],
198        attrs: &[ast::Attribute],
199        fields: &[ast::StructField],
200        fallback: Option<&ast::StructFallback>,
201    ) {
202        let krate = self.rust_options.krate_or_default();
203        let ident = format!("r#{name}");
204        let attrs = RustAttributes::parse(attrs);
205        let num_required_fields = fields.iter().filter(|&f| f.required()).count();
206        let has_required_fields = num_required_fields > 0;
207        let schema_name = self.schema.name();
208        let additional_derives = attrs.additional_derives();
209
210        let (doc_comment, doc_alt) = self.doc_string(doc, 0);
211        code!(self, "{doc_comment}");
212
213        code!(self, "#[derive({DEBUG}, {CLONE}");
214
215        if !has_required_fields {
216            code!(self, ", {DEFAULT}");
217        }
218
219        code!(self, ", {krate}::Tag, {krate}::PrimaryTag, {krate}::RefType, {krate}::Serialize, {krate}::Deserialize");
220
221        if self.options.introspection && self.rust_options.introspection_if.is_none() {
222            code!(self, ", {krate}::Introspectable");
223        }
224
225        codeln!(self, "{additional_derives})]");
226
227        if self.options.introspection
228            && let Some(feature) = self.rust_options.introspection_if
229        {
230            codeln!(self, "#[cfg_attr(feature = \"{feature}\", derive({krate}::Introspectable))]");
231        }
232
233        code!(self, "#[aldrin(");
234        if let Some(krate) = self.rust_options.krate {
235            code!(self, "crate = {krate}::core, ");
236        }
237        codeln!(self, "schema = \"{schema_name}\", ref_type)]");
238
239        if doc_alt && self.options.introspection {
240            for doc in doc {
241                let doc = doc.value_inner();
242                codeln!(self, "#[aldrin(doc = \"{doc}\")]");
243            }
244        }
245
246        codeln!(self, "pub struct {ident} {{");
247        let mut first = true;
248        for field in fields {
249            let id = field.id().value();
250            let ident = format!("r#{}", field.name().value());
251            let ty = self.type_name(field.field_type());
252
253            if first {
254                first = false;
255            } else {
256                codeln!(self);
257            }
258
259            let (doc_comment, doc_alt) = self.doc_string(field.doc(), 4);
260            code!(self, "{doc_comment}");
261
262            if field.required() {
263                codeln!(self, "    #[aldrin(id = {id})]");
264            } else {
265                codeln!(self, "    #[aldrin(id = {id}, optional)]");
266            }
267
268            if doc_alt && self.options.introspection {
269                for doc in field.doc() {
270                    let doc = doc.value_inner();
271                    codeln!(self, "    #[aldrin(doc = \"{doc}\")]");
272                }
273            }
274
275            if field.required() {
276                codeln!(self, "    pub {ident}: {ty},");
277            } else {
278                codeln!(self, "    pub {ident}: {OPTION}<{ty}>,");
279            }
280        }
281        if let Some(fallback) = fallback {
282            if !first {
283                codeln!(self);
284            }
285
286            let (doc_comment, doc_alt) = self.doc_string(fallback.doc(), 4);
287            code!(self, "{doc_comment}");
288
289            codeln!(self, "    #[aldrin(fallback)]");
290
291            if doc_alt && self.options.introspection {
292                for doc in fallback.doc() {
293                    let doc = doc.value_inner();
294                    codeln!(self, "    #[aldrin(doc = \"{doc}\")]");
295                }
296            }
297
298            let ident = format!("r#{}", fallback.name().value());
299            codeln!(self, "    pub {ident}: {krate}::core::UnknownFields,");
300        }
301        codeln!(self, "}}");
302        codeln!(self);
303
304        if !has_required_fields {
305            codeln!(self, "impl {ident} {{");
306            codeln!(self, "    pub fn new() -> Self {{");
307            codeln!(self, "        <Self as {DEFAULT}>::default()");
308            codeln!(self, "    }}");
309            codeln!(self, "}}");
310            codeln!(self);
311        }
312    }
313
314    fn enum_def(
315        &mut self,
316        name: &str,
317        doc: &[ast::DocString],
318        attrs: &[ast::Attribute],
319        vars: &[ast::EnumVariant],
320        fallback: Option<&ast::EnumFallback>,
321    ) {
322        let ident = format!("r#{name}");
323        let krate = &self.rust_options.krate_or_default();
324        let schema_name = self.schema.name();
325        let attrs = RustAttributes::parse(attrs);
326        let additional_derives = attrs.additional_derives();
327
328        let (doc_comment, doc_alt) = self.doc_string(doc, 0);
329        code!(self, "{doc_comment}");
330
331        code!(self, "#[derive({DEBUG}, {CLONE}");
332        code!(self, ", {krate}::Tag, {krate}::PrimaryTag, {krate}::RefType, {krate}::Serialize, {krate}::Deserialize");
333
334        if self.options.introspection && self.rust_options.introspection_if.is_none() {
335            code!(self, ", {krate}::Introspectable");
336        }
337
338        codeln!(self, "{additional_derives})]");
339
340        if self.options.introspection
341            && let Some(feature) = self.rust_options.introspection_if
342        {
343            codeln!(self, "#[cfg_attr(feature = \"{feature}\", derive({krate}::Introspectable))]");
344        }
345
346        code!(self, "#[aldrin(");
347        if let Some(krate) = self.rust_options.krate {
348            code!(self, "crate = {krate}::core, ");
349        }
350        codeln!(self, "schema = \"{schema_name}\", ref_type)]");
351
352        if doc_alt && self.options.introspection {
353            for doc in doc {
354                let doc = doc.value_inner();
355                codeln!(self, "#[aldrin(doc = \"{doc}\")]");
356            }
357        }
358
359        codeln!(self, "pub enum {ident} {{");
360        let mut first = true;
361        for var in vars {
362            let id = var.id().value();
363            let ident = format!("r#{}", var.name().value());
364
365            if first {
366                first = false;
367            } else {
368                codeln!(self);
369            }
370
371            let (doc_comment, doc_alt) = self.doc_string(var.doc(), 4);
372            code!(self, "{doc_comment}");
373
374            codeln!(self, "    #[aldrin(id = {id})]");
375
376            if doc_alt && self.options.introspection {
377                for doc in var.doc() {
378                    let doc = doc.value_inner();
379                    codeln!(self, "    #[aldrin(doc = \"{doc}\")]");
380                }
381            }
382
383            if let Some(ty) = var.variant_type() {
384                let ty = self.type_name(ty);
385                codeln!(self, "    {ident}({ty}),");
386            } else {
387                codeln!(self, "    {ident},");
388            }
389        }
390        if let Some(fallback) = fallback {
391            if !first {
392                codeln!(self);
393            }
394
395            let (doc_comment, doc_alt) = self.doc_string(fallback.doc(), 4);
396            code!(self, "{doc_comment}");
397
398            codeln!(self, "    #[aldrin(fallback)]");
399
400            if doc_alt && self.options.introspection {
401                for doc in fallback.doc() {
402                    let doc = doc.value_inner();
403                    codeln!(self, "    #[aldrin(doc = \"{doc}\")]");
404                }
405            }
406
407            let ident = format!("r#{}", fallback.name().value());
408            codeln!(self, "    {ident}({krate}::core::UnknownVariant),");
409        }
410        codeln!(self, "}}");
411        codeln!(self);
412    }
413
414    fn service_def(&mut self, svc: &ast::ServiceDef) {
415        if !self.options.client && !self.options.server {
416            return;
417        }
418
419        let krate = self.rust_options.krate_or_default();
420        let schema = self.schema.name();
421        let svc_name = svc.name().value();
422        let ident = format!("r#{svc_name}");
423        let uuid = svc.uuid().value();
424        let version = svc.version().value();
425
426        codeln!(self, "{krate}::service! {{");
427
428        let (doc_comment, doc_alt) = self.doc_string(svc.doc(), 4);
429        code!(self, "{doc_comment}");
430
431        code!(self, "    #[aldrin(");
432
433        if let Some(krate) = self.rust_options.krate {
434            code!(self, "crate = {krate}, ");
435        }
436
437        code!(self, "schema = \"{schema}\"");
438
439        if !self.options.client {
440            code!(self, ", client = false");
441        }
442
443        if !self.options.server {
444            code!(self, ", server = false");
445        }
446
447        if self.options.introspection {
448            code!(self, ", introspection");
449        }
450
451        if let Some(feature) = self.rust_options.introspection_if {
452            code!(self, ", introspection_if = \"{feature}\"");
453        }
454
455        codeln!(self, ")]");
456
457        if doc_alt && self.options.introspection {
458            for doc in svc.doc() {
459                let doc = doc.value_inner();
460                codeln!(self, "    #[aldrin(doc = \"{doc}\")]");
461            }
462        }
463
464        codeln!(self, "    pub service {ident} {{");
465        codeln!(self, "        uuid = {krate}::core::ServiceUuid({krate}::private::uuid::uuid!(\"{uuid}\"));");
466        codeln!(self, "        version = {version};");
467
468        for item in svc.items() {
469            codeln!(self);
470
471            match item {
472                ast::ServiceItem::Function(func) => {
473                    let name = func.name().value();
474                    let ident = format!("r#{name}");
475                    let id = func.id().value();
476
477                    let (doc_comment, doc_alt) = self.doc_string(func.doc(), 8);
478                    code!(self, "{doc_comment}");
479
480                    if doc_alt && self.options.introspection {
481                        for doc in func.doc() {
482                            let doc = doc.value_inner();
483                            codeln!(self, "        #[aldrin(doc = \"{doc}\")]");
484                        }
485                    }
486
487                    code!(self, "        fn {ident} @ {id}");
488
489                    if let (None, Some(ok), None) = (func.args(), func.ok(), func.err()) {
490                        let ty = self.function_ok_type_name(svc_name, name, ok, true);
491                        codeln!(self, " = {ty};");
492                    } else if func.args().is_some() || func.ok().is_some() || func.err().is_some() {
493                        codeln!(self, " {{");
494
495                        if let Some(args) = func.args() {
496                            let ty = self.function_args_type_name(svc_name, name, args, true);
497                            codeln!(self, "            args = {ty};");
498                        }
499
500                        if let Some(ok) = func.ok() {
501                            let ty = self.function_ok_type_name(svc_name, name, ok, true);
502                            codeln!(self, "            ok = {ty};");
503                        }
504
505                        if let Some(err) = func.err() {
506                            let ty = self.function_err_type_name(svc_name, name, err, true);
507                            codeln!(self, "            err = {ty};");
508                        }
509
510                        codeln!(self, "        }}");
511                    } else {
512                        codeln!(self, ";");
513                    }
514                }
515
516                ast::ServiceItem::Event(ev) => {
517                    let name = ev.name().value();
518                    let ident = format!("r#{name}");
519                    let id = ev.id().value();
520
521                    let (doc_comment, doc_alt) = self.doc_string(ev.doc(), 8);
522                    code!(self, "{doc_comment}");
523
524                    if doc_alt && self.options.introspection {
525                        for doc in ev.doc() {
526                            let doc = doc.value_inner();
527                            codeln!(self, "        #[aldrin(doc = \"{doc}\")]");
528                        }
529                    }
530
531                    code!(self, "        event {ident} @ {id}");
532
533                    if let Some(ty) = ev.event_type() {
534                        let ty = self.event_args_type_name(svc_name, name, ty, true);
535                        code!(self, " = {ty}");
536                    }
537
538                    codeln!(self, ";");
539                }
540            }
541        }
542
543        if let Some(fallback) = svc.function_fallback() {
544            let name = fallback.name().value();
545            let ident = format!("r#{name}");
546
547            codeln!(self);
548
549            let (doc_comment, doc_alt) = self.doc_string(fallback.doc(), 8);
550            code!(self, "{doc_comment}");
551
552            if doc_alt && self.options.introspection {
553                for doc in fallback.doc() {
554                    let doc = doc.value_inner();
555                    codeln!(self, "        #[aldrin(doc = \"{doc}\")]");
556                }
557            }
558
559            codeln!(self, "        fn {ident} = {krate}::UnknownCall;");
560        }
561
562        if let Some(fallback) = svc.event_fallback() {
563            let name = fallback.name().value();
564            let ident = format!("r#{name}");
565
566            codeln!(self);
567
568            let (doc_comment, doc_alt) = self.doc_string(fallback.doc(), 8);
569            code!(self, "{doc_comment}");
570
571            if doc_alt && self.options.introspection {
572                for doc in fallback.doc() {
573                    let doc = doc.value_inner();
574                    codeln!(self, "        #[aldrin(doc = \"{doc}\")]");
575                }
576            }
577
578            codeln!(self, "        event {ident} = {krate}::UnknownEvent;");
579        }
580
581        codeln!(self, "    }}");
582        codeln!(self, "}}");
583        codeln!(self);
584
585        for item in svc.items() {
586            match item {
587                ast::ServiceItem::Function(func) => {
588                    let func_name = func.name().value();
589
590                    if let Some(args) = func.args() {
591                        match args.part_type() {
592                            ast::TypeNameOrInline::Struct(s) => self.struct_def(
593                                &self.function_args_type_name(svc_name, func_name, args, false),
594                                s.doc(),
595                                s.attributes(),
596                                s.fields(),
597                                s.fallback(),
598                            ),
599
600                            ast::TypeNameOrInline::Enum(e) => self.enum_def(
601                                &self.function_args_type_name(svc_name, func_name, args, false),
602                                e.doc(),
603                                e.attributes(),
604                                e.variants(),
605                                e.fallback(),
606                            ),
607
608                            ast::TypeNameOrInline::TypeName(_) => {}
609                        }
610                    }
611
612                    if let Some(ok) = func.ok() {
613                        match ok.part_type() {
614                            ast::TypeNameOrInline::Struct(s) => self.struct_def(
615                                &self.function_ok_type_name(svc_name, func_name, ok, false),
616                                s.doc(),
617                                s.attributes(),
618                                s.fields(),
619                                s.fallback(),
620                            ),
621
622                            ast::TypeNameOrInline::Enum(e) => self.enum_def(
623                                &self.function_ok_type_name(svc_name, func_name, ok, false),
624                                e.doc(),
625                                e.attributes(),
626                                e.variants(),
627                                e.fallback(),
628                            ),
629
630                            ast::TypeNameOrInline::TypeName(_) => {}
631                        }
632                    }
633
634                    if let Some(err) = func.err() {
635                        match err.part_type() {
636                            ast::TypeNameOrInline::Struct(s) => self.struct_def(
637                                &self.function_err_type_name(svc_name, func_name, err, false),
638                                s.doc(),
639                                s.attributes(),
640                                s.fields(),
641                                s.fallback(),
642                            ),
643
644                            ast::TypeNameOrInline::Enum(e) => self.enum_def(
645                                &self.function_err_type_name(svc_name, func_name, err, false),
646                                e.doc(),
647                                e.attributes(),
648                                e.variants(),
649                                e.fallback(),
650                            ),
651
652                            ast::TypeNameOrInline::TypeName(_) => {}
653                        }
654                    }
655                }
656
657                ast::ServiceItem::Event(ev) => {
658                    if let Some(ty) = ev.event_type() {
659                        let ev_name = ev.name().value();
660
661                        match ty {
662                            ast::TypeNameOrInline::Struct(s) => self.struct_def(
663                                &self.event_args_type_name(svc_name, ev_name, ty, false),
664                                s.doc(),
665                                s.attributes(),
666                                s.fields(),
667                                s.fallback(),
668                            ),
669
670                            ast::TypeNameOrInline::Enum(e) => self.enum_def(
671                                &self.event_args_type_name(svc_name, ev_name, ty, false),
672                                e.doc(),
673                                e.attributes(),
674                                e.variants(),
675                                e.fallback(),
676                            ),
677
678                            ast::TypeNameOrInline::TypeName(_) => {}
679                        }
680                    }
681                }
682            }
683        }
684    }
685
686    fn const_def(&mut self, const_def: &ast::ConstDef) {
687        let krate = self.rust_options.krate_or_default();
688        let name = const_def.name().value();
689
690        let (doc_comment, _) = self.doc_string(const_def.doc(), 0);
691        code!(self, "{doc_comment}");
692
693        match const_def.value() {
694            ast::ConstValue::U8(v) => {
695                let val = v.value();
696                codeln!(self, "pub const {name}: {U8} = {val};");
697            }
698
699            ast::ConstValue::I8(v) => {
700                let val = v.value();
701                codeln!(self, "pub const {name}: {I8} = {val};");
702            }
703
704            ast::ConstValue::U16(v) => {
705                let val = v.value();
706                codeln!(self, "pub const {name}: {U16} = {val};");
707            }
708
709            ast::ConstValue::I16(v) => {
710                let val = v.value();
711                codeln!(self, "pub const {name}: {I16} = {val};");
712            }
713
714            ast::ConstValue::U32(v) => {
715                let val = v.value();
716                codeln!(self, "pub const {name}: {U32} = {val};");
717            }
718
719            ast::ConstValue::I32(v) => {
720                let val = v.value();
721                codeln!(self, "pub const {name}: {I32} = {val};");
722            }
723
724            ast::ConstValue::U64(v) => {
725                let val = v.value();
726                codeln!(self, "pub const {name}: {U64} = {val};");
727            }
728
729            ast::ConstValue::I64(v) => {
730                let val = v.value();
731                codeln!(self, "pub const {name}: {I64} = {val};");
732            }
733
734            ast::ConstValue::String(v) => {
735                let val = v.value();
736                codeln!(self, "pub const {name}: &{STR} = {val};");
737            }
738
739            ast::ConstValue::Uuid(v) => {
740                let val = v.value();
741                codeln!(self, "pub const {name}: {krate}::private::uuid::Uuid = {krate}::private::uuid::uuid!(\"{val}\");");
742            }
743        }
744
745        codeln!(self);
746    }
747
748    fn newtype_def(&mut self, newtype_def: &ast::NewtypeDef) {
749        let krate = self.rust_options.krate_or_default();
750        let name = newtype_def.name().value();
751        let ident = format!("r#{name}");
752        let ty = self.type_name(newtype_def.target_type());
753        let schema_name = self.schema.name();
754        let additional_derives =
755            RustAttributes::parse(newtype_def.attributes()).additional_derives();
756        let (is_key_type, derive_default) =
757            self.newtype_properties(self.schema, newtype_def.target_type());
758
759        let (doc_comment, doc_alt) = self.doc_string(newtype_def.doc(), 0);
760        code!(self, "{doc_comment}");
761
762        code!(self, "#[derive({DEBUG}, {CLONE}");
763
764        if derive_default {
765            code!(self, ", {DEFAULT}");
766        }
767
768        if is_key_type {
769            code!(self, ", {PARTIAL_EQ}, {EQ}, {PARTIAL_ORD}, {ORD}, {HASH}");
770        }
771
772        code!(self, ", {krate}::Tag, {krate}::PrimaryTag, {krate}::RefType, {krate}::Serialize, {krate}::Deserialize");
773
774        if self.options.introspection && self.rust_options.introspection_if.is_none() {
775            code!(self, ", {krate}::Introspectable");
776        }
777
778        if is_key_type {
779            code!(self, ", {krate}::KeyTag, {krate}::PrimaryKeyTag, {krate}::SerializeKey, {krate}::DeserializeKey");
780        }
781
782        codeln!(self, "{additional_derives})]");
783
784        if self.options.introspection
785            && let Some(feature) = self.rust_options.introspection_if
786        {
787            codeln!(self, "#[cfg_attr(feature = \"{feature}\", derive({krate}::Introspectable))]");
788        }
789
790        code!(self, "#[aldrin(");
791        if let Some(krate) = self.rust_options.krate {
792            code!(self, "crate = {krate}::core, ");
793        }
794        codeln!(self, "newtype, schema = \"{schema_name}\", ref_type)]");
795
796        if doc_alt && self.options.introspection {
797            for doc in newtype_def.doc() {
798                let doc = doc.value_inner();
799                codeln!(self, "#[aldrin(doc = \"{doc}\")]");
800            }
801        }
802
803        codeln!(self, "pub struct {ident}(pub {ty});");
804        codeln!(self);
805    }
806
807    fn register_introspection(&mut self, def: &ast::Definition) {
808        match def {
809            def @ (ast::Definition::Struct(_)
810            | ast::Definition::Enum(_)
811            | ast::Definition::Newtype(_)) => {
812                let ident = format!("r#{}", def.name().value());
813                codeln!(self, "    client.register_introspection::<{ident}>()?;");
814            }
815
816            ast::Definition::Service(s) => {
817                if self.options.client || self.options.server {
818                    let ident = format!("r#{}", s.name().value());
819                    codeln!(self, "    client.register_introspection::<{ident}Introspection>()?;");
820                }
821            }
822
823            ast::Definition::Const(_) => {}
824        }
825    }
826
827    fn type_name(&self, ty: &ast::TypeName) -> String {
828        let krate = self.rust_options.krate_or_default();
829
830        match ty.kind() {
831            ast::TypeNameKind::Bool => BOOL.to_owned(),
832            ast::TypeNameKind::U8 => U8.to_owned(),
833            ast::TypeNameKind::I8 => I8.to_owned(),
834            ast::TypeNameKind::U16 => U16.to_owned(),
835            ast::TypeNameKind::I16 => I16.to_owned(),
836            ast::TypeNameKind::U32 => U32.to_owned(),
837            ast::TypeNameKind::I32 => I32.to_owned(),
838            ast::TypeNameKind::U64 => U64.to_owned(),
839            ast::TypeNameKind::I64 => I64.to_owned(),
840            ast::TypeNameKind::F32 => F32.to_owned(),
841            ast::TypeNameKind::F64 => F64.to_owned(),
842            ast::TypeNameKind::String => STRING.to_owned(),
843            ast::TypeNameKind::Uuid => format!("{krate}::private::uuid::Uuid"),
844            ast::TypeNameKind::ObjectId => format!("{krate}::core::ObjectId"),
845            ast::TypeNameKind::ServiceId => format!("{krate}::core::ServiceId"),
846            ast::TypeNameKind::Value => format!("{krate}::core::SerializedValue"),
847            ast::TypeNameKind::Option(ty) => format!("{OPTION}<{}>", self.type_name(ty)),
848            ast::TypeNameKind::Box(ty) => format!("{BOX}<{}>", self.type_name(ty)),
849
850            #[expect(clippy::wildcard_enum_match_arm)]
851            ast::TypeNameKind::Vec(ty) => match ty.kind() {
852                ast::TypeNameKind::U8 => format!("{krate}::core::Bytes"),
853                _ => format!("{VEC}<{}>", self.type_name(ty)),
854            },
855
856            ast::TypeNameKind::Bytes => format!("{krate}::core::Bytes"),
857
858            ast::TypeNameKind::Map(k, v) => {
859                format!("{HASH_MAP}<{}, {}>", self.type_name(k), self.type_name(v))
860            }
861
862            ast::TypeNameKind::Set(ty) => format!("{HASH_SET}<{}>", self.type_name(ty)),
863
864            ast::TypeNameKind::Sender(ty) => {
865                format!("{krate}::UnboundSender<{}>", self.type_name(ty))
866            }
867
868            ast::TypeNameKind::Receiver(ty) => {
869                format!("{krate}::UnboundReceiver<{}>", self.type_name(ty))
870            }
871
872            ast::TypeNameKind::Lifetime => format!("{krate}::LifetimeId"),
873            ast::TypeNameKind::Unit => "()".to_owned(),
874
875            ast::TypeNameKind::Result(ok, err) => {
876                format!("{RESULT}<{}, {}>", self.type_name(ok), self.type_name(err))
877            }
878
879            ast::TypeNameKind::Array(ty, len) => self.array_name(ty, len),
880            ast::TypeNameKind::Ref(ty) => Self::named_ref_name(ty),
881        }
882    }
883
884    fn array_name(&self, ty: &ast::TypeName, len: &ast::ArrayLen) -> String {
885        match len.value() {
886            ast::ArrayLenValue::Literal(len) => {
887                format!("[{}; {}usize]", self.type_name(ty), len.value())
888            }
889
890            ast::ArrayLenValue::Ref(named_ref) => {
891                format!(
892                    "[{}; {} as usize]",
893                    self.type_name(ty),
894                    Self::named_ref_name(named_ref)
895                )
896            }
897        }
898    }
899
900    fn named_ref_name(ty: &ast::NamedRef) -> String {
901        match ty.kind() {
902            ast::NamedRefKind::Intern(ty) => format!("r#{}", ty.value()),
903            ast::NamedRefKind::Extern(m, ty) => format!("super::r#{}::r#{}", m.value(), ty.value()),
904        }
905    }
906
907    fn function_args_type_name(
908        &self,
909        svc_name: &str,
910        func_name: &str,
911        part: &ast::FunctionPart,
912        raw: bool,
913    ) -> String {
914        match part.part_type() {
915            ast::TypeNameOrInline::TypeName(ty) => self.type_name(ty),
916
917            ast::TypeNameOrInline::Struct(_) | ast::TypeNameOrInline::Enum(_) => {
918                if raw {
919                    format!("r#{}", names::function_args(svc_name, func_name))
920                } else {
921                    names::function_args(svc_name, func_name)
922                }
923            }
924        }
925    }
926
927    fn function_ok_type_name(
928        &self,
929        svc_name: &str,
930        func_name: &str,
931        part: &ast::FunctionPart,
932        raw: bool,
933    ) -> String {
934        match part.part_type() {
935            ast::TypeNameOrInline::TypeName(ty) => self.type_name(ty),
936
937            ast::TypeNameOrInline::Struct(_) | ast::TypeNameOrInline::Enum(_) => {
938                if raw {
939                    format!("r#{}", names::function_ok(svc_name, func_name))
940                } else {
941                    names::function_ok(svc_name, func_name)
942                }
943            }
944        }
945    }
946
947    fn function_err_type_name(
948        &self,
949        svc_name: &str,
950        func_name: &str,
951        part: &ast::FunctionPart,
952        raw: bool,
953    ) -> String {
954        match part.part_type() {
955            ast::TypeNameOrInline::TypeName(ty) => self.type_name(ty),
956
957            ast::TypeNameOrInline::Struct(_) | ast::TypeNameOrInline::Enum(_) => {
958                if raw {
959                    format!("r#{}", names::function_err(svc_name, func_name))
960                } else {
961                    names::function_err(svc_name, func_name)
962                }
963            }
964        }
965    }
966
967    fn event_args_type_name(
968        &self,
969        svc_name: &str,
970        ev_name: &str,
971        ev_type: &ast::TypeNameOrInline,
972        raw: bool,
973    ) -> String {
974        match ev_type {
975            ast::TypeNameOrInline::TypeName(ty) => self.type_name(ty),
976
977            ast::TypeNameOrInline::Struct(_) | ast::TypeNameOrInline::Enum(_) => {
978                if raw {
979                    format!("r#{}", names::event_args(svc_name, ev_name))
980                } else {
981                    names::event_args(svc_name, ev_name)
982                }
983            }
984        }
985    }
986
987    fn newtype_properties(&self, schema: &Schema, ty: &ast::TypeName) -> (bool, bool) {
988        match ty.kind() {
989            ast::TypeNameKind::U8
990            | ast::TypeNameKind::I8
991            | ast::TypeNameKind::U16
992            | ast::TypeNameKind::I16
993            | ast::TypeNameKind::U32
994            | ast::TypeNameKind::I32
995            | ast::TypeNameKind::U64
996            | ast::TypeNameKind::I64
997            | ast::TypeNameKind::String
998            | ast::TypeNameKind::Uuid => (true, false),
999
1000            ast::TypeNameKind::Bool
1001            | ast::TypeNameKind::F32
1002            | ast::TypeNameKind::F64
1003            | ast::TypeNameKind::ObjectId
1004            | ast::TypeNameKind::ServiceId
1005            | ast::TypeNameKind::Value
1006            | ast::TypeNameKind::Option(_)
1007            | ast::TypeNameKind::Box(_)
1008            | ast::TypeNameKind::Vec(_)
1009            | ast::TypeNameKind::Bytes
1010            | ast::TypeNameKind::Map(_, _)
1011            | ast::TypeNameKind::Set(_)
1012            | ast::TypeNameKind::Sender(_)
1013            | ast::TypeNameKind::Receiver(_)
1014            | ast::TypeNameKind::Lifetime
1015            | ast::TypeNameKind::Unit
1016            | ast::TypeNameKind::Result(_, _)
1017            | ast::TypeNameKind::Array(_, _) => (false, false),
1018
1019            ast::TypeNameKind::Ref(ty) => {
1020                let (schema, name) = match ty.kind() {
1021                    ast::NamedRefKind::Intern(name) => (schema, name.value()),
1022
1023                    ast::NamedRefKind::Extern(schema, name) => {
1024                        if let Some(schema) = self.parser.get_schema(schema.value()) {
1025                            (schema, name.value())
1026                        } else {
1027                            return (false, false);
1028                        }
1029                    }
1030                };
1031
1032                let Some(def) = schema
1033                    .definitions()
1034                    .iter()
1035                    .find(|def| def.name().value() == name)
1036                else {
1037                    return (false, false);
1038                };
1039
1040                match def {
1041                    ast::Definition::Struct(struct_def) => {
1042                        let has_required_fields =
1043                            struct_def.fields().iter().any(ast::StructField::required);
1044
1045                        (false, !has_required_fields)
1046                    }
1047
1048                    ast::Definition::Newtype(newtype_def) => {
1049                        self.newtype_properties(schema, newtype_def.target_type())
1050                    }
1051
1052                    ast::Definition::Enum(_)
1053                    | ast::Definition::Service(_)
1054                    | ast::Definition::Const(_) => (false, false),
1055                }
1056            }
1057        }
1058    }
1059
1060    fn doc_string(&self, doc: &[ast::DocString], indent: usize) -> (String, bool) {
1061        self.doc_string_impl(doc, indent, "///")
1062    }
1063
1064    fn doc_string_inner(&self, doc: &[ast::DocString], indent: usize) -> (String, bool) {
1065        self.doc_string_impl(doc, indent, "//!")
1066    }
1067
1068    fn doc_string_impl(
1069        &self,
1070        doc: &[ast::DocString],
1071        indent: usize,
1072        style: &'static str,
1073    ) -> (String, bool) {
1074        const INDENT: &str = "        ";
1075
1076        debug_assert!(indent <= INDENT.len());
1077
1078        if doc.is_empty() {
1079            return (String::new(), false);
1080        }
1081
1082        let mut orig = String::new();
1083
1084        for doc in doc {
1085            orig.push_str(doc.value_inner());
1086            orig.push('\n');
1087        }
1088
1089        let with_links = self.rewrite_doc_links(&orig);
1090        let mut doc_string = String::new();
1091
1092        for line in with_links.lines() {
1093            doc_string.push_str(&INDENT[..indent]);
1094            doc_string.push_str(style);
1095
1096            if !line.is_empty() {
1097                doc_string.push(' ');
1098                doc_string.push_str(line);
1099            }
1100
1101            doc_string.push('\n');
1102        }
1103
1104        (doc_string, orig != with_links)
1105    }
1106
1107    fn rewrite_doc_links(&self, doc: &str) -> String {
1108        let resolver = LinkResolver::new(self.parser, self.schema);
1109
1110        let mut options = ComrakOptions::default();
1111        options.extension.footnotes = true;
1112        options.extension.strikethrough = true;
1113        options.extension.table = true;
1114        options.extension.tasklist = true;
1115        options.parse.smart = true;
1116
1117        options.parse.broken_link_callback = Some(Arc::new(move |link: BrokenLinkReference| {
1118            resolver
1119                .convert_broken_link_if_valid(link.original)
1120                .map(|link| ResolvedReference {
1121                    url: link.to_owned(),
1122                    title: String::new(),
1123                })
1124        }));
1125
1126        let arena = Arena::new();
1127        let root = comrak::parse_document(&arena, doc, &options);
1128
1129        for node in root.descendants() {
1130            let mut data = node.data.borrow_mut();
1131
1132            if let NodeValue::Link(ref mut link) = data.value
1133                && let Some(new_link) = self.rewrite_doc_link(&link.url, resolver)
1134            {
1135                link.url = new_link;
1136            }
1137        }
1138
1139        let mut doc_string = String::new();
1140        comrak::format_commonmark(root, &options, &mut doc_string).unwrap();
1141        doc_string
1142    }
1143
1144    fn rewrite_doc_link(&self, link: &str, resolver: LinkResolver<'_>) -> Option<String> {
1145        let Ok(resolved) = resolver.resolve(link) else {
1146            return None;
1147        };
1148
1149        match resolved {
1150            ResolvedLink::Foreign => None,
1151
1152            ResolvedLink::Schema(schema) => {
1153                if schema.name() == resolver.schema().name() {
1154                    Some("self".to_owned())
1155                } else {
1156                    Some(format!("super::{}", schema.name()))
1157                }
1158            }
1159
1160            ResolvedLink::Struct(schema, struct_def) => Some(Self::doc_link_components(
1161                schema,
1162                resolver,
1163                &[struct_def.name().value()],
1164            )),
1165
1166            ResolvedLink::Field(schema, struct_def, field) => Some(Self::doc_link_components(
1167                schema,
1168                resolver,
1169                &[struct_def.name().value(), field.name().value()],
1170            )),
1171
1172            ResolvedLink::FallbackField(schema, struct_def, fallback) => {
1173                Some(Self::doc_link_components(
1174                    schema,
1175                    resolver,
1176                    &[struct_def.name().value(), fallback.name().value()],
1177                ))
1178            }
1179
1180            ResolvedLink::Enum(schema, enum_def) => Some(Self::doc_link_components(
1181                schema,
1182                resolver,
1183                &[enum_def.name().value()],
1184            )),
1185
1186            ResolvedLink::Variant(schema, enum_def, var) => Some(Self::doc_link_components(
1187                schema,
1188                resolver,
1189                &[enum_def.name().value(), var.name().value()],
1190            )),
1191
1192            ResolvedLink::FallbackVariant(schema, enum_def, fallback) => {
1193                Some(Self::doc_link_components(
1194                    schema,
1195                    resolver,
1196                    &[enum_def.name().value(), fallback.name().value()],
1197                ))
1198            }
1199
1200            ResolvedLink::Service(schema, svc) => {
1201                if self.options.client {
1202                    Some(Self::doc_link_components(
1203                        schema,
1204                        resolver,
1205                        &[&names::service_proxy(svc.name().value())],
1206                    ))
1207                } else if self.options.server {
1208                    Some(Self::doc_link_components(
1209                        schema,
1210                        resolver,
1211                        &[svc.name().value()],
1212                    ))
1213                } else {
1214                    None
1215                }
1216            }
1217
1218            ResolvedLink::Function(schema, svc, func) => {
1219                if self.options.client {
1220                    Some(Self::doc_link_components(
1221                        schema,
1222                        resolver,
1223                        &[
1224                            &names::service_proxy(svc.name().value()),
1225                            func.name().value(),
1226                        ],
1227                    ))
1228                } else if self.options.server {
1229                    Some(Self::doc_link_components(
1230                        schema,
1231                        resolver,
1232                        &[
1233                            &names::service_call(svc.name().value()),
1234                            &names::function_variant(func.name().value()),
1235                        ],
1236                    ))
1237                } else {
1238                    None
1239                }
1240            }
1241
1242            ResolvedLink::FunctionArgsStruct(schema, svc, func, _, _)
1243            | ResolvedLink::FunctionArgsEnum(schema, svc, func, _, _) => {
1244                if self.options.client || self.options.server {
1245                    Some(Self::doc_link_components(
1246                        schema,
1247                        resolver,
1248                        &[&names::function_args(
1249                            svc.name().value(),
1250                            func.name().value(),
1251                        )],
1252                    ))
1253                } else {
1254                    None
1255                }
1256            }
1257
1258            ResolvedLink::FunctionArgsField(schema, svc, func, _, _, field) => {
1259                if self.options.client || self.options.server {
1260                    Some(Self::doc_link_components(
1261                        schema,
1262                        resolver,
1263                        &[
1264                            &names::function_args(svc.name().value(), func.name().value()),
1265                            field.name().value(),
1266                        ],
1267                    ))
1268                } else {
1269                    None
1270                }
1271            }
1272
1273            ResolvedLink::FunctionArgsFallbackField(schema, svc, func, _, _, fallback) => {
1274                if self.options.client || self.options.server {
1275                    Some(Self::doc_link_components(
1276                        schema,
1277                        resolver,
1278                        &[
1279                            &names::function_args(svc.name().value(), func.name().value()),
1280                            fallback.name().value(),
1281                        ],
1282                    ))
1283                } else {
1284                    None
1285                }
1286            }
1287
1288            ResolvedLink::FunctionArgsVariant(schema, svc, func, _, _, var) => {
1289                if self.options.client || self.options.server {
1290                    Some(Self::doc_link_components(
1291                        schema,
1292                        resolver,
1293                        &[
1294                            &names::function_args(svc.name().value(), func.name().value()),
1295                            var.name().value(),
1296                        ],
1297                    ))
1298                } else {
1299                    None
1300                }
1301            }
1302
1303            ResolvedLink::FunctionArgsFallbackVariant(schema, svc, func, _, _, fallback) => {
1304                if self.options.client || self.options.server {
1305                    Some(Self::doc_link_components(
1306                        schema,
1307                        resolver,
1308                        &[
1309                            &names::function_args(svc.name().value(), func.name().value()),
1310                            fallback.name().value(),
1311                        ],
1312                    ))
1313                } else {
1314                    None
1315                }
1316            }
1317
1318            ResolvedLink::FunctionOkStruct(schema, svc, func, _, _)
1319            | ResolvedLink::FunctionOkEnum(schema, svc, func, _, _) => {
1320                if self.options.client || self.options.server {
1321                    Some(Self::doc_link_components(
1322                        schema,
1323                        resolver,
1324                        &[&names::function_ok(svc.name().value(), func.name().value())],
1325                    ))
1326                } else {
1327                    None
1328                }
1329            }
1330
1331            ResolvedLink::FunctionOkField(schema, svc, func, _, _, field) => {
1332                if self.options.client || self.options.server {
1333                    Some(Self::doc_link_components(
1334                        schema,
1335                        resolver,
1336                        &[
1337                            &names::function_ok(svc.name().value(), func.name().value()),
1338                            field.name().value(),
1339                        ],
1340                    ))
1341                } else {
1342                    None
1343                }
1344            }
1345
1346            ResolvedLink::FunctionOkFallbackField(schema, svc, func, _, _, fallback) => {
1347                if self.options.client || self.options.server {
1348                    Some(Self::doc_link_components(
1349                        schema,
1350                        resolver,
1351                        &[
1352                            &names::function_ok(svc.name().value(), func.name().value()),
1353                            fallback.name().value(),
1354                        ],
1355                    ))
1356                } else {
1357                    None
1358                }
1359            }
1360
1361            ResolvedLink::FunctionOkVariant(schema, svc, func, _, _, var) => {
1362                if self.options.client || self.options.server {
1363                    Some(Self::doc_link_components(
1364                        schema,
1365                        resolver,
1366                        &[
1367                            &names::function_ok(svc.name().value(), func.name().value()),
1368                            var.name().value(),
1369                        ],
1370                    ))
1371                } else {
1372                    None
1373                }
1374            }
1375
1376            ResolvedLink::FunctionOkFallbackVariant(schema, svc, func, _, _, fallback) => {
1377                if self.options.client || self.options.server {
1378                    Some(Self::doc_link_components(
1379                        schema,
1380                        resolver,
1381                        &[
1382                            &names::function_ok(svc.name().value(), func.name().value()),
1383                            fallback.name().value(),
1384                        ],
1385                    ))
1386                } else {
1387                    None
1388                }
1389            }
1390
1391            ResolvedLink::FunctionErrStruct(schema, svc, func, _, _)
1392            | ResolvedLink::FunctionErrEnum(schema, svc, func, _, _) => {
1393                if self.options.client || self.options.server {
1394                    Some(Self::doc_link_components(
1395                        schema,
1396                        resolver,
1397                        &[&names::function_err(
1398                            svc.name().value(),
1399                            func.name().value(),
1400                        )],
1401                    ))
1402                } else {
1403                    None
1404                }
1405            }
1406
1407            ResolvedLink::FunctionErrField(schema, svc, func, _, _, field) => {
1408                if self.options.client || self.options.server {
1409                    Some(Self::doc_link_components(
1410                        schema,
1411                        resolver,
1412                        &[
1413                            &names::function_err(svc.name().value(), func.name().value()),
1414                            field.name().value(),
1415                        ],
1416                    ))
1417                } else {
1418                    None
1419                }
1420            }
1421
1422            ResolvedLink::FunctionErrFallbackField(schema, svc, func, _, _, fallback) => {
1423                if self.options.client || self.options.server {
1424                    Some(Self::doc_link_components(
1425                        schema,
1426                        resolver,
1427                        &[
1428                            &names::function_err(svc.name().value(), func.name().value()),
1429                            fallback.name().value(),
1430                        ],
1431                    ))
1432                } else {
1433                    None
1434                }
1435            }
1436
1437            ResolvedLink::FunctionErrVariant(schema, svc, func, _, _, var) => {
1438                if self.options.client || self.options.server {
1439                    Some(Self::doc_link_components(
1440                        schema,
1441                        resolver,
1442                        &[
1443                            &names::function_err(svc.name().value(), func.name().value()),
1444                            var.name().value(),
1445                        ],
1446                    ))
1447                } else {
1448                    None
1449                }
1450            }
1451
1452            ResolvedLink::FunctionErrFallbackVariant(schema, svc, func, _, _, fallback) => {
1453                if self.options.client || self.options.server {
1454                    Some(Self::doc_link_components(
1455                        schema,
1456                        resolver,
1457                        &[
1458                            &names::function_err(svc.name().value(), func.name().value()),
1459                            fallback.name().value(),
1460                        ],
1461                    ))
1462                } else {
1463                    None
1464                }
1465            }
1466
1467            ResolvedLink::FunctionFallback(schema, svc, fallback) => {
1468                if self.options.server {
1469                    Some(Self::doc_link_components(
1470                        schema,
1471                        resolver,
1472                        &[
1473                            &names::service_call(svc.name().value()),
1474                            &names::function_variant(fallback.name().value()),
1475                        ],
1476                    ))
1477                } else {
1478                    None
1479                }
1480            }
1481
1482            ResolvedLink::Event(schema, svc, ev) => {
1483                if self.options.client {
1484                    Some(Self::doc_link_components(
1485                        schema,
1486                        resolver,
1487                        &[
1488                            &names::service_event(svc.name().value()),
1489                            &names::event_variant(ev.name().value()),
1490                        ],
1491                    ))
1492                } else if self.options.server {
1493                    Some(Self::doc_link_components(
1494                        schema,
1495                        resolver,
1496                        &[svc.name().value(), ev.name().value()],
1497                    ))
1498                } else {
1499                    None
1500                }
1501            }
1502
1503            ResolvedLink::EventStruct(schema, svc, ev, _)
1504            | ResolvedLink::EventEnum(schema, svc, ev, _) => {
1505                if self.options.client || self.options.server {
1506                    Some(Self::doc_link_components(
1507                        schema,
1508                        resolver,
1509                        &[&names::event_args(svc.name().value(), ev.name().value())],
1510                    ))
1511                } else {
1512                    None
1513                }
1514            }
1515
1516            ResolvedLink::EventField(schema, svc, ev, _, field) => {
1517                if self.options.client || self.options.server {
1518                    Some(Self::doc_link_components(
1519                        schema,
1520                        resolver,
1521                        &[
1522                            &names::event_args(svc.name().value(), ev.name().value()),
1523                            field.name().value(),
1524                        ],
1525                    ))
1526                } else {
1527                    None
1528                }
1529            }
1530
1531            ResolvedLink::EventFallbackField(schema, svc, ev, _, fallback) => {
1532                if self.options.client || self.options.server {
1533                    Some(Self::doc_link_components(
1534                        schema,
1535                        resolver,
1536                        &[
1537                            &names::event_args(svc.name().value(), ev.name().value()),
1538                            fallback.name().value(),
1539                        ],
1540                    ))
1541                } else {
1542                    None
1543                }
1544            }
1545
1546            ResolvedLink::EventVariant(schema, svc, ev, _, var) => {
1547                if self.options.client || self.options.server {
1548                    Some(Self::doc_link_components(
1549                        schema,
1550                        resolver,
1551                        &[
1552                            &names::event_args(svc.name().value(), ev.name().value()),
1553                            var.name().value(),
1554                        ],
1555                    ))
1556                } else {
1557                    None
1558                }
1559            }
1560
1561            ResolvedLink::EventFallbackVariant(schema, svc, ev, _, fallback) => {
1562                if self.options.client || self.options.server {
1563                    Some(Self::doc_link_components(
1564                        schema,
1565                        resolver,
1566                        &[
1567                            &names::event_args(svc.name().value(), ev.name().value()),
1568                            fallback.name().value(),
1569                        ],
1570                    ))
1571                } else {
1572                    None
1573                }
1574            }
1575
1576            ResolvedLink::EventFallback(schema, svc, fallback) => {
1577                if self.options.client {
1578                    Some(Self::doc_link_components(
1579                        schema,
1580                        resolver,
1581                        &[
1582                            &names::service_event(svc.name().value()),
1583                            &names::event_variant(fallback.name().value()),
1584                        ],
1585                    ))
1586                } else {
1587                    None
1588                }
1589            }
1590
1591            ResolvedLink::Const(schema, const_def) => Some(Self::doc_link_components(
1592                schema,
1593                resolver,
1594                &[const_def.name().value()],
1595            )),
1596
1597            ResolvedLink::Newtype(schema, newtype) => Some(Self::doc_link_components(
1598                schema,
1599                resolver,
1600                &[newtype.name().value()],
1601            )),
1602        }
1603    }
1604
1605    fn doc_link_base(schema: &Schema, resolver: LinkResolver) -> String {
1606        if schema.name() == resolver.schema().name() {
1607            String::new()
1608        } else {
1609            format!("super::{}::", schema.name())
1610        }
1611    }
1612
1613    fn doc_link_components(schema: &Schema, resolver: LinkResolver, components: &[&str]) -> String {
1614        let mut link = Self::doc_link_base(schema, resolver);
1615
1616        for (i, component) in components.iter().enumerate() {
1617            if i > 0 {
1618                link.push_str("::");
1619            }
1620
1621            link.push_str(component);
1622        }
1623
1624        link
1625    }
1626}
1627
1628struct RustAttributes {
1629    impl_copy: bool,
1630    impl_partial_eq: bool,
1631    impl_eq: bool,
1632    impl_partial_ord: bool,
1633    impl_ord: bool,
1634    impl_hash: bool,
1635}
1636
1637impl RustAttributes {
1638    fn new() -> Self {
1639        Self {
1640            impl_copy: false,
1641            impl_partial_eq: false,
1642            impl_eq: false,
1643            impl_partial_ord: false,
1644            impl_ord: false,
1645            impl_hash: false,
1646        }
1647    }
1648
1649    fn parse(attrs: &[ast::Attribute]) -> Self {
1650        let mut res = Self::new();
1651
1652        for attr in attrs {
1653            if attr.name().value() != "rust" {
1654                continue;
1655            }
1656
1657            for opt in attr.options() {
1658                match opt.value() {
1659                    "impl_copy" => res.impl_copy = true,
1660                    "impl_partial_eq" => res.impl_partial_eq = true,
1661                    "impl_eq" => res.impl_eq = true,
1662                    "impl_partial_ord" => res.impl_partial_ord = true,
1663                    "impl_ord" => res.impl_ord = true,
1664                    "impl_hash" => res.impl_hash = true,
1665                    _ => {}
1666                }
1667            }
1668        }
1669
1670        res
1671    }
1672
1673    fn additional_derives(&self) -> String {
1674        let mut derives = String::new();
1675
1676        if self.impl_copy {
1677            derives.push_str(", ::std::marker::Copy");
1678        }
1679
1680        if self.impl_partial_eq {
1681            derives.push_str(", ");
1682            derives.push_str(PARTIAL_EQ);
1683        }
1684
1685        if self.impl_eq {
1686            derives.push_str(", ");
1687            derives.push_str(EQ);
1688        }
1689
1690        if self.impl_partial_ord {
1691            derives.push_str(", ");
1692            derives.push_str(PARTIAL_ORD);
1693        }
1694
1695        if self.impl_ord {
1696            derives.push_str(", ");
1697            derives.push_str(ORD);
1698        }
1699
1700        if self.impl_hash {
1701            derives.push_str(", ");
1702            derives.push_str(HASH);
1703        }
1704
1705        derives
1706    }
1707}