1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
mod gut;
mod html;
mod markdown;
mod resolve;

use crate::documentation::{Documentation, GdnativeClass, Method, Property};
use pulldown_cmark::{Alignment, CowStr, Event, LinkType, Options as MarkdownOptions, Parser, Tag};
use std::path::PathBuf;

pub(super) use gut::GutCallbacks;
pub(super) use html::HtmlCallbacks;
pub(super) use markdown::MarkdownCallbacks;
pub use resolve::Resolver;

/// Generate a callback to resolve broken links.
///
/// We have to generate a new one for each use because the lifetimes on
/// `pulldown_cmark::Parser::new_with_broken_link_callback` are not yet
/// refined enough.
macro_rules! broken_link_callback {
    ($resolver:expr) => {
        move |broken_link: ::pulldown_cmark::BrokenLink| {
            use ::pulldown_cmark::CowStr;

            let mut link = broken_link.reference;
            if link.starts_with('`') && link.ends_with('`') && link.len() > 1 {
                link = &link[1..link.len() - 1];
            }
            $resolver
                .resolve(link)
                .map(|string| (CowStr::from(string), CowStr::Borrowed("")))
        }
    };
}

/// Kind of files generated by a [`Builder`](crate::Builder).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Backend {
    Markdown {
        /// Where to output the generated files.
        output_dir: PathBuf,
    },
    Html {
        /// Where to output the generated files.
        output_dir: PathBuf,
    },
    Gut {
        /// Where to output the generated files.
        output_dir: PathBuf,
    },
}

/// Callbacks to encode markdown input in a given format.
pub trait Callbacks {
    /// File extension for the files generated by this callback.
    fn extension(&self) -> &'static str;
    /// Called before encoding each class.
    ///
    /// **Default**: does nothing
    fn start_class(&mut self, _s: &mut String, _resolver: &Resolver, _class: &GdnativeClass) {}
    /// Called before encoding each method.
    ///
    /// **Default**: does nothing
    fn start_method(&mut self, _s: &mut String, _resolver: &Resolver, _method: &Method) {}
    /// Called before encoding each property.
    ///
    /// **Default**: does nothing
    fn start_property(&mut self, _s: &mut String, _resolver: &Resolver, _property: &Property) {}
    /// Encode the stream of `events` in `s`.
    fn encode(&mut self, s: &mut String, events: Vec<Event<'_>>);
    /// Called at the end of the processing for a given file.
    ///
    /// **Default**: does nothing
    fn finish_encoding(&mut self, _s: &mut String) {}
}

impl dyn Callbacks {
    /// Default start_method implementation, implemented on `dyn Callbacks` to avoid
    /// code duplication.
    ///
    /// This will create a level 3 header that looks like (in markdown):
    /// ```text
    /// ### <a id="func-name"></a>func name(arg1: type, ...) -> type
    /// ________
    /// ```
    ///
    /// With appropriate linking.
    pub fn start_method_default(&mut self, s: &mut String, property: &Resolver, method: &Method) {
        let link = &format!("<a id=\"func-{}\"></a>", method.name);
        self.encode(
            s,
            vec![
                Event::Start(Tag::Heading(3)),
                Event::Html(CowStr::Borrowed(link)),
            ],
        );
        let mut method_header = String::from("func ");
        method_header.push_str(&method.name);
        method_header.push('(');
        for (index, (name, typ, _)) in method.parameters.iter().enumerate() {
            method_header.push_str(&name);
            method_header.push_str(": ");
            self.encode(s, vec![Event::Text(CowStr::Borrowed(&method_header))]);
            method_header.clear();
            self.encode(s, property.encode_type(typ));
            if index + 1 != method.parameters.len() {
                method_header.push_str(", ");
            }
        }
        method_header.push_str(") -> ");
        let mut last_events = vec![Event::Text(CowStr::Borrowed(&method_header))];
        last_events.extend(property.encode_type(&method.return_type));
        last_events.push(Event::End(Tag::Heading(3)));
        last_events.push(Event::Rule);
        self.encode(s, last_events);
    }

    /// Default start_property implementation, implemented on `dyn Callbacks` to avoid
    /// code duplication.
    ///
    /// This will create a level 3 header that looks like (in markdown):
    /// ```text
    /// ### <a id="property-name"></a> name: type
    /// ________
    /// ```
    ///
    /// With appropriate linking.
    pub fn start_property_default(
        &mut self,
        s: &mut String,
        resolver: &Resolver,
        property: &Property,
    ) {
        let link = &format!(
            "<a id=\"property-{}\"></a> {}: ",
            property.name, property.name
        );
        self.encode(
            s,
            vec![
                Event::Start(Tag::Heading(3)),
                Event::Html(CowStr::Borrowed(link)),
            ],
        );
        let mut last_events = resolver.encode_type(&property.typ);
        last_events.push(Event::End(Tag::Heading(3)));
        last_events.push(Event::Rule);
        self.encode(s, last_events);
    }
}

impl std::fmt::Debug for dyn Callbacks {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("Callbacks")
    }
}

/// Generate files given an encoding
#[derive(Debug)]
pub(crate) struct Generator<'a> {
    /// Used to resolve links.
    resolver: &'a Resolver,
    /// Encoding functions.
    callbacks: Box<dyn Callbacks>,
    /// Data to encode.
    documentation: &'a Documentation,
    /// Markdown options
    markdown_options: MarkdownOptions,
}

impl<'a> Generator<'a> {
    pub(crate) fn new(
        resolver: &'a Resolver,
        documentation: &'a Documentation,
        callbacks: Box<dyn Callbacks>,
        markdown_options: MarkdownOptions,
    ) -> Self {
        Self {
            resolver,
            callbacks,
            documentation,
            markdown_options,
        }
    }

    /// Generate the root documentation file of the crate.
    pub(crate) fn generate_root_file(&mut self, extension: &str) -> String {
        let mut root_file = String::new();
        let resolver = self.resolver;
        let mut broken_link_callback = broken_link_callback!(resolver);
        let class_iterator = EventIterator {
            context: resolver,
            parser: pulldown_cmark::Parser::new_with_broken_link_callback(
                &self.documentation.root_documentation,
                self.markdown_options,
                Some(&mut broken_link_callback),
            ),
        };
        let mut events: Vec<_> = class_iterator.into_iter().collect();
        events.extend(vec![
            Event::Start(Tag::Heading(1)),
            Event::Text(CowStr::Borrowed("Classes:")),
            Event::End(Tag::Heading(1)),
            Event::Start(Tag::List(None)),
        ]);
        for (class_name, _) in &self.documentation.classes {
            let link = Tag::Link(
                LinkType::Inline,
                format!("./{}.{}", class_name, extension).into(),
                CowStr::Borrowed(""),
            );
            events.extend(vec![
                Event::Start(Tag::Item),
                Event::Start(link.clone()),
                Event::Text(CowStr::Borrowed(&class_name)),
                Event::End(link.clone()),
                Event::End(Tag::Item),
            ])
        }
        events.push(Event::End(Tag::List(None)));
        self.callbacks.encode(&mut root_file, events);
        self.callbacks.finish_encoding(&mut root_file);
        root_file
    }

    /// Generate pairs of (class_name, file_content).
    pub(crate) fn generate_files(&mut self) -> Vec<(String, String)> {
        let mut results = Vec::new();
        for (name, class) in &self.documentation.classes {
            let mut class_file = String::new();
            let callbacks = &mut self.callbacks;
            let resolver = &self.resolver;

            callbacks.start_class(&mut class_file, resolver, class);
            let inherit_link = resolver.resolve(&class.inherit);

            // Name of the class + inherit
            let mut events = vec![
                Event::Start(Tag::Heading(1)),
                Event::Text(CowStr::Borrowed(&name)),
                Event::End(Tag::Heading(1)),
                Event::Start(Tag::Paragraph),
                Event::Start(Tag::Strong),
                Event::Text(CowStr::Borrowed("Inherit:")),
                Event::End(Tag::Strong),
                Event::Text(CowStr::Borrowed(" ")),
            ];
            if let Some(inherit_link) = inherit_link.as_ref() {
                events.extend(vec![
                    Event::Start(Tag::Link(
                        LinkType::Shortcut,
                        CowStr::Borrowed(&inherit_link),
                        CowStr::Borrowed(""),
                    )),
                    Event::Text(CowStr::Borrowed(&class.inherit)),
                    Event::End(Tag::Link(
                        LinkType::Shortcut,
                        CowStr::Borrowed(&inherit_link),
                        CowStr::Borrowed(""),
                    )),
                ])
            } else {
                events.push(Event::Text(CowStr::Borrowed(&class.inherit)))
            }
            events.extend(vec![
                Event::End(Tag::Paragraph),
                Event::Start(Tag::Heading(2)),
                Event::Text(CowStr::Borrowed("Description")),
                Event::End(Tag::Heading(2)),
            ]);
            callbacks.encode(&mut class_file, events);

            // Class description
            let mut broken_link_callback = broken_link_callback!(resolver);
            let class_documentation = EventIterator {
                context: resolver,
                parser: pulldown_cmark::Parser::new_with_broken_link_callback(
                    &class.documentation,
                    self.markdown_options,
                    Some(&mut broken_link_callback),
                ),
            }
            .into_iter()
            .collect();
            callbacks.encode(&mut class_file, class_documentation);

            // Properties table
            if !class.properties.is_empty() {
                callbacks.encode(
                    &mut class_file,
                    Self::properties_table(&class.properties, resolver),
                )
            }

            // Methods table
            callbacks.encode(
                &mut class_file,
                Self::methods_table(&class.methods, resolver),
            );

            // Properties descriptions
            if !class.properties.is_empty() {
                callbacks.encode(
                    &mut class_file,
                    vec![
                        Event::Start(Tag::Heading(2)),
                        Event::Text(CowStr::Borrowed("Properties Descriptions")),
                        Event::End(Tag::Heading(2)),
                    ],
                );
                for property in &class.properties {
                    callbacks.start_property(&mut class_file, resolver, property);
                    let mut broken_link_callback = broken_link_callback!(resolver);
                    let property_documentation = EventIterator {
                        context: resolver,
                        parser: pulldown_cmark::Parser::new_with_broken_link_callback(
                            &property.documentation,
                            self.markdown_options,
                            Some(&mut broken_link_callback),
                        ),
                    }
                    .into_iter()
                    .collect();
                    callbacks.encode(&mut class_file, property_documentation);
                }
            }

            // Methods descriptions
            callbacks.encode(
                &mut class_file,
                vec![
                    Event::Start(Tag::Heading(2)),
                    Event::Text(CowStr::Borrowed("Methods Descriptions")),
                    Event::End(Tag::Heading(2)),
                ],
            );
            for method in &class.methods {
                callbacks.start_method(&mut class_file, resolver, method);
                let mut broken_link_callback = broken_link_callback!(resolver);
                let method_documentation = EventIterator {
                    context: resolver,
                    parser: pulldown_cmark::Parser::new_with_broken_link_callback(
                        &method.documentation,
                        self.markdown_options,
                        Some(&mut broken_link_callback),
                    ),
                }
                .into_iter()
                .collect();
                callbacks.encode(&mut class_file, method_documentation);
            }
            callbacks.finish_encoding(&mut class_file);
            results.push((name.clone(), class_file))
        }
        results
    }

    /// Create a table summarizing the `properties`.
    fn properties_table<'ev>(
        properties: &'ev [Property],
        resolver: &'ev Resolver,
    ) -> Vec<Event<'ev>> {
        let mut events = vec![
            Event::Start(Tag::Heading(2)),
            Event::Text(CowStr::Borrowed("Properties")),
            Event::End(Tag::Heading(2)),
            Event::Start(Tag::Table(vec![Alignment::Left, Alignment::Left])),
            Event::Start(Tag::TableHead),
            Event::Start(Tag::TableCell),
            Event::Text(CowStr::Borrowed("type")),
            Event::End(Tag::TableCell),
            Event::Start(Tag::TableCell),
            Event::Text(CowStr::Borrowed("property")),
            Event::End(Tag::TableCell),
            Event::End(Tag::TableHead),
        ];

        for property in properties {
            let link = Tag::Link(
                LinkType::Reference,
                format!("#property-{}", property.name).into(),
                property.name.as_str().into(),
            );
            events.push(Event::Start(Tag::TableRow));
            events.push(Event::Start(Tag::TableCell));
            events.extend(resolver.encode_type(&property.typ));
            events.extend(vec![
                Event::End(Tag::TableCell),
                Event::Start(Tag::TableCell),
                Event::Start(link.clone()),
                Event::Text(CowStr::Borrowed(property.name.as_str())),
                Event::End(link),
                Event::End(Tag::TableCell),
                Event::End(Tag::TableRow),
            ]);
        }

        events.push(Event::End(Tag::Table(vec![
            Alignment::Left,
            Alignment::Left,
        ])));

        events
    }

    fn methods_table<'ev>(methods: &'ev [Method], resolver: &'ev Resolver) -> Vec<Event<'ev>> {
        let mut events = vec![
            Event::Start(Tag::Heading(2)),
            Event::Text(CowStr::Borrowed("Methods")),
            Event::End(Tag::Heading(2)),
            Event::Start(Tag::Table(vec![Alignment::Left, Alignment::Left])),
            Event::Start(Tag::TableHead),
            Event::Start(Tag::TableCell),
            Event::Text(CowStr::Borrowed("returns")),
            Event::End(Tag::TableCell),
            Event::Start(Tag::TableCell),
            Event::Text(CowStr::Borrowed("method")),
            Event::End(Tag::TableCell),
            Event::End(Tag::TableHead),
        ];

        for method in methods {
            let link = format!("#func-{}", method.name);
            events.push(Event::Start(Tag::TableRow));
            events.push(Event::Start(Tag::TableCell));
            events.extend(resolver.encode_type(&method.return_type));
            events.push(Event::End(Tag::TableCell));
            events.push(Event::Start(Tag::TableCell));

            let link = Tag::Link(
                LinkType::Reference,
                link.into(),
                method.name.as_str().into(),
            );
            events.extend(vec![
                Event::Start(link.clone()),
                Event::Text(CowStr::Borrowed(&method.name)),
                Event::End(link),
                Event::Text(CowStr::Borrowed("( ")),
            ]);
            for (index, (name, typ, _)) in method.parameters.iter().enumerate() {
                events.push(Event::Text(format!("{}: ", name).into()));
                events.extend(resolver.encode_type(typ));
                if index + 1 != method.parameters.len() {
                    events.push(Event::Text(CowStr::Borrowed(", ")));
                }
            }

            events.extend(vec![
                Event::Text(CowStr::Borrowed(" )")),
                Event::End(Tag::TableCell),
                Event::End(Tag::TableRow),
            ]);
        }

        events.push(Event::End(Tag::Table(vec![
            Alignment::Left,
            Alignment::Left,
        ])));

        events
    }
}

/// Iterate over [events](Event), resolving links and changing the resolved
/// broken links types.
struct EventIterator<'resolver, 'parser> {
    context: &'resolver Resolver,
    parser: Parser<'parser>,
}

impl<'resolver, 'parser> Iterator for EventIterator<'resolver, 'parser> {
    type Item = Event<'parser>;

    fn next(&mut self) -> Option<Self::Item> {
        let mut next_event = self.parser.next()?;
        next_event = match next_event {
            // matches broken reference links that have been restored by the callback
            // and replaces them by shortcut variants
            Event::Start(Tag::Link(LinkType::ShortcutUnknown, dest, title)) => {
                Event::Start(Tag::Link(LinkType::Shortcut, dest, title))
            }
            Event::End(Tag::Link(LinkType::ShortcutUnknown, dest, title)) => {
                Event::End(Tag::Link(LinkType::Shortcut, dest, title))
            }
            _ => next_event,
        };
        self.context.resolve_event(&mut next_event);
        Some(next_event)
    }
}