Skip to main content

roas_codegen/
generate.rs

1//! The generation entry point and its result.
2
3use crate::config::{Config, Layout, Target};
4use crate::diagnostic::{Diagnostic, DiagnosticKind, SchemaId, Severity};
5use crate::front::Translator;
6use crate::go::GoDependency;
7use crate::rust::RustDependency;
8use crate::source::{Fidelity, SourceVersion};
9use crate::validate::ValidatedSourceDocument;
10use crate::{go, lower, rust};
11use std::path::PathBuf;
12use thiserror::Error;
13
14/// One generated file, relative to the output directory the caller
15/// chooses. Generating writes no output files; [`write`](crate::write())
16/// does.
17#[derive(Debug, Clone, PartialEq, Eq)]
18#[non_exhaustive]
19pub struct GeneratedFile {
20    pub path: PathBuf,
21    pub contents: String,
22}
23
24impl GeneratedFile {
25    pub fn new(path: impl Into<PathBuf>, contents: impl Into<String>) -> Self {
26        GeneratedFile {
27            path: path.into(),
28            contents: contents.into(),
29        }
30    }
31}
32
33/// What the generated code depends on, computed from what was emitted.
34/// Nothing generated depends on `roas`.
35#[derive(Debug, Clone, Default, PartialEq, Eq)]
36#[non_exhaustive]
37pub struct Dependencies {
38    pub rust: Vec<RustDependency>,
39    /// Modules a Go file imports from beyond the standard library.
40    pub go: Vec<GoDependency>,
41}
42
43/// The result of a generation: files in memory, everything the
44/// generator had to say, and the dependency list.
45#[derive(Debug, Clone)]
46#[non_exhaustive]
47pub struct Generation {
48    /// The language the files are in; [`write`](crate::write()) names the
49    /// manifest after it.
50    pub target: Target,
51    pub files: Vec<GeneratedFile>,
52    pub diagnostics: Vec<Diagnostic>,
53    pub dependencies: Dependencies,
54}
55
56impl Generation {
57    /// A generation made of files alone, for callers that produce their
58    /// own and want [`write`](crate::write()) to manage them.
59    pub fn new(target: Target, files: Vec<GeneratedFile>) -> Self {
60        Generation {
61            target,
62            files,
63            diagnostics: Vec::new(),
64            dependencies: Dependencies::default(),
65        }
66    }
67
68    /// True when any diagnostic is an error, meaning some type was not
69    /// emitted.
70    pub fn has_errors(&self) -> bool {
71        self.diagnostics
72            .iter()
73            .any(|d| d.severity == Severity::Error)
74    }
75}
76
77/// Generation itself did not complete. Distinct from a diagnostic: a
78/// diagnostic is an answerable fact about the description, with partial
79/// output; this is about the configuration, the templates or the
80/// toolchain, and no output is meaningful.
81#[derive(Debug, Error)]
82#[non_exhaustive]
83pub enum GenerateError {
84    #[error("configuration: {0}")]
85    Config(String),
86    #[error("`{selector}` matches nothing; the description has {candidates:?}")]
87    UnknownSelector {
88        selector: String,
89        candidates: Vec<String>,
90    },
91    #[error("attribute {attr:?} on `{at}` is not valid Rust: {reason}")]
92    InvalidAttribute {
93        at: String,
94        attr: String,
95        reason: String,
96    },
97    #[error("attribute on `{at}` sets `serde({key})`, which the generator owns: {reason}")]
98    ReservedAttribute {
99        at: String,
100        key: String,
101        reason: String,
102    },
103    #[error("`exact_numbers` needs exact input: {0}")]
104    Fidelity(String),
105    #[error("template: {0}")]
106    Template(String),
107    #[error("generated `{path}` is not valid syntax, which is a generator bug: {reason}")]
108    InvalidOutput { path: String, reason: String },
109    /// The user's templates rendered `path` into something that does not
110    /// parse; [`render`](crate::render()) shows what they wrote.
111    #[error(
112        "the templates in `template_dir` rendered `{path}` into invalid syntax: {reason}; `render` (`--dump-rendered`) shows the text"
113    )]
114    TemplateOutput { path: String, reason: String },
115    #[error("not supported yet: {0}")]
116    Unsupported(String),
117    /// Nothing in the description can be generated at all, such as under
118    /// an unknown dialect; the diagnostics say why.
119    #[error("nothing can be generated: {}", .0.iter().map(ToString::to_string).collect::<Vec<_>>().join("; "))]
120    NothingToGenerate(Vec<Diagnostic>),
121    /// A tool the target needs is missing or failed: generating Go needs
122    /// `gofmt`, which is also its syntax check.
123    #[error("toolchain: {0}")]
124    Toolchain(String),
125}
126
127/// The first segment of every relative path in a Rust type, such as
128/// `chrono` twice in `Option<chrono::NaiveDate>` and `chrono::Utc`: the
129/// names a module of the same name would hide. A path starting `::` names
130/// a crate no module can hide, so it is skipped.
131fn first_path_segments(ty: &str) -> impl Iterator<Item = &str> {
132    ty.match_indices("::").filter_map(move |(at, _)| {
133        let before = &ty[..at];
134        let start = before
135            .char_indices()
136            .rev()
137            // Identifiers may hold any Unicode letter or mark; what ends
138            // one in a type is punctuation or space.
139            .find(|(_, c)| c.is_whitespace() || "<>,()[]&*;:'!=+".contains(*c))
140            // Past that whole character, however many bytes it takes.
141            .map_or(0, |(i, c)| i + c.len_utf8());
142        let segment = &before[start..];
143        let rooted = before[..start].ends_with(':');
144        (!segment.is_empty() && !rooted).then_some(segment)
145    })
146}
147
148/// How the generated header names its source: the document's file name,
149/// never its full location. Output must be identical in every checkout,
150/// and an absolute path would also leak the machine it was generated on.
151fn source_name(uri: &url::Url) -> String {
152    uri.path_segments()
153        .and_then(|mut segments| segments.next_back())
154        .filter(|name| !name.is_empty())
155        .map(|name| {
156            // A file name is free text: a decoded newline would end the
157            // doc comment it is quoted in and turn the rest into code.
158            percent_decode(name)
159                .chars()
160                .flat_map(|c| {
161                    // Bidi controls reorder what a reader sees, and rustc
162                    // refuses them in comments.
163                    if c.is_control()
164                        || matches!(
165                            c,
166                            '\u{061C}'
167                                | '\u{200E}'
168                                | '\u{200F}'
169                                | '\u{202A}'..='\u{202E}'
170                                | '\u{2066}'..='\u{2069}'
171                        )
172                    {
173                        c.escape_default().collect::<Vec<_>>()
174                    } else {
175                        vec![c]
176                    }
177                })
178                .collect()
179        })
180        .unwrap_or_else(|| match uri.scheme() {
181            "stdin" => "standard input".to_owned(),
182            _ => uri.host_str().unwrap_or("the description").to_owned(),
183        })
184}
185
186fn percent_decode(text: &str) -> String {
187    let bytes = text.as_bytes();
188    let mut out = Vec::with_capacity(bytes.len());
189    let mut i = 0;
190    while i < bytes.len() {
191        if bytes[i] == b'%'
192            && i + 2 < bytes.len()
193            && let Ok(v) = u8::from_str_radix(&text[i + 1..i + 3], 16)
194        {
195            out.push(v);
196            i += 3;
197        } else {
198            out.push(bytes[i]);
199            i += 1;
200        }
201    }
202    String::from_utf8_lossy(&out).into_owned()
203}
204
205/// What `ConfigFile::build` checked may have been changed since, as
206/// `Config`'s fields are public; and some checks need the whole of it.
207fn check_rust(config: &Config) -> Result<(), GenerateError> {
208    // The module names the file written.
209    if !crate::config::is_module_name(&config.rust.module) {
210        return Err(GenerateError::Config(format!(
211            "`rust.module = {:?}` must be a lowercase Rust module name",
212            config.rust.module
213        )));
214    }
215    // Nor may it share its name with a crate a substitution imports: the
216    // module would hide that crate in the file that declares it.
217    // Imported, or named by any path in the type (generic arguments too).
218    if let Some((key, _)) = config.substitutions.iter().find(|(_, s)| {
219        s.rust.as_ref().is_some_and(|r| {
220            r.import
221                .as_deref()
222                .is_some_and(|import| import.replace('-', "_") == config.rust.module)
223                || first_path_segments(&r.name).any(|first| first == config.rust.module)
224        })
225    }) {
226        return Err(GenerateError::Config(format!(
227            "`rust.module = {:?}` is the crate substitution `{key}` imports or names; choose another module name or label",
228            config.rust.module
229        )));
230    }
231    // The types' files go to a directory named after the module, and
232    // Cargo builds every file in `src/bin` as a program of its own.
233    if config.layout == Layout::FilePerType && config.rust.module == "bin" {
234        return Err(GenerateError::Config(
235            "`rust.module = \"bin\"` puts the types' files in a `bin` directory, and in `src/bin` Cargo builds each file as a program; choose another module name".into(),
236        ));
237    }
238    // The header heads every type's file too, which the module includes:
239    // an inner attribute or doc comment, which an included file cannot
240    // hold, is refused. Read as Rust reads it: `# ![a]`, or `#![a]` after
241    // a comment, is one too, and `//!` inside a block comment is not.
242    if config.layout == Layout::FilePerType
243        && let Some(header) = config.header.as_deref()
244        && let Ok(file) = syn::parse_file(header)
245        && (!file.attrs.is_empty() || file.shebang.is_some())
246    {
247        return Err(GenerateError::Config(
248            "`header` holds an inner doc comment or attribute (`//!`, `#![...]`), which a type's file under `layout = \"file_per_type\"` cannot hold, as the module includes it; write it as `//`, or in the module file's template".into(),
249        ));
250    }
251    if !matches!(config.rust.edition.as_str(), "2018" | "2021" | "2024") {
252        return Err(GenerateError::Config(format!(
253            "`rust.edition = {:?}` is not a supported Rust edition (expected 2018, 2021, or 2024)",
254            config.rust.edition
255        )));
256    }
257    Ok(())
258}
259
260fn check_go(config: &Config) -> Result<(), GenerateError> {
261    if !go::naming::is_package_name(&config.go.package) {
262        return Err(GenerateError::Config(format!(
263            "`go.package = {:?}` must be a lowercase Go package name",
264            config.go.package
265        )));
266    }
267    if !go::naming::is_file_stem(&config.go.file) {
268        return Err(GenerateError::Config(format!(
269            "`go.file = {:?}` must be a lowercase file stem `go build` reads as plain source",
270            config.go.file
271        )));
272    }
273    // What a dot import is used for shows in no qualifier, and Go refuses
274    // it in a file that does not use it.
275    if config.layout == Layout::FilePerType
276        && let Some(spec) = config
277            .extra_imports
278            .iter()
279            .find(|spec| spec.trim().starts_with('.'))
280    {
281        return Err(GenerateError::Config(format!(
282            "`extra_imports` entry {spec:?} is a dot import, which `layout = \"file_per_type\"` cannot place: give it a name"
283        )));
284    }
285    Ok(())
286}
287
288/// Output that does not parse is the generator's bug with its own
289/// templates, and most likely the user's with theirs.
290fn blame_templates(error: GenerateError, config: &Config) -> GenerateError {
291    match error {
292        GenerateError::InvalidOutput { path, reason } if config.template_dir.is_some() => {
293            GenerateError::TemplateOutput { path, reason }
294        }
295        other => other,
296    }
297}
298
299/// The lowered description and what was said on the way, before any
300/// backend runs. `ir` is `None` when nothing can be generated at all.
301struct Prepared {
302    ir: Option<crate::ir::Ir>,
303    diagnostics: Vec<Diagnostic>,
304    source: String,
305}
306
307fn prepare(document: &ValidatedSourceDocument, config: &Config) -> Result<Prepared, GenerateError> {
308    if config.exact_numbers {
309        if !cfg!(feature = "exact-numbers") {
310            return Err(GenerateError::Config(
311                "`exact_numbers` requires roas-codegen built with the `exact-numbers` feature"
312                    .into(),
313            ));
314        }
315        if document.fidelity() != Fidelity::Exact {
316            return Err(GenerateError::Fidelity(format!(
317                "{} was read with {:?} fidelity; only JSON text yields exact numbers",
318                document.uri(),
319                document.fidelity()
320            )));
321        }
322    }
323    // Settings the configuration accepts but this release cannot honour
324    // are refused, never silently ignored.
325    match config.target {
326        Target::Rust => check_rust(config)?,
327        Target::Go => check_go(config)?,
328    }
329    let mut diagnostics = document.diagnostics();
330
331    // The root dialect decides what every keyword means.
332    if let Some(dialect) = &document.spec().json_schema_dialect
333        && !lower::is_known_dialect(dialect)
334    {
335        diagnostics.push(Diagnostic {
336            severity: Severity::Error,
337            kind: DiagnosticKind::UnsupportedDialect { dialect: dialect.clone() },
338            schema_id: SchemaId::new(document.uri().clone(), ""),
339            pointer: "/jsonSchemaDialect".into(),
340            message: format!("`jsonSchemaDialect: {dialect}` is not a dialect this generator understands, so no schema is generated; only the OAS dialect and Draft 2020-12 are"),
341        });
342        return Ok(Prepared {
343            ir: None,
344            diagnostics,
345            source: source_name(document.uri()),
346        });
347    }
348
349    let source_pointer: fn(&str) -> String = match document.version() {
350        SourceVersion::V2 => |p| {
351            p.strip_prefix("/components/schemas/")
352                .map_or_else(|| p.to_owned(), |rest| format!("/definitions/{rest}"))
353        },
354        _ => |p| p.to_owned(),
355    };
356    let front = Translator {
357        uri: document.uri(),
358        raw: document.raw(),
359        source_pointer,
360        legacy_nullable: matches!(document.version(), SourceVersion::V2 | SourceVersion::V3_0),
361        report_lost: config.validation,
362        v3_0_source: matches!(document.version(), SourceVersion::V3_0),
363    }
364    .translate(document.spec());
365    let mut ir = lower::lower(&front, config);
366
367    // A schema the reference report refused is not generated either.
368    let refused: Vec<SchemaId> = diagnostics
369        .iter()
370        .filter(|d| d.severity == Severity::Error)
371        .map(|d| d.schema_id.clone())
372        .collect();
373    if !refused.is_empty() {
374        for id in ir.types.keys().cloned().collect::<Vec<_>>() {
375            let source_ptr = source_pointer(&crate::diagnostic::source_of(&id.pointer));
376            if refused.iter().any(|r| {
377                r.uri == id.uri
378                    && (source_ptr == r.pointer || r.pointer.starts_with(&format!("{source_ptr}/")))
379            }) {
380                ir.types.get_mut(&id).expect("present").has_error = true;
381            }
382        }
383        // Re-run suppression with the extra errors.
384        ir.suppress();
385    }
386    // What was left out of a parent's union, once it is settled whether
387    // the parent is generated at all.
388    for (parent, note) in std::mem::take(&mut ir.union_notes) {
389        if ir.suppressed.contains(&parent) {
390            continue;
391        }
392        // What the union reads the tag as now, once every pass is done.
393        let read_as = ir.types.values().find_map(|def| match &def.kind {
394            crate::ir::TypeKind::UnionTagged(u) if u.parent.as_ref() == Some(&parent) => u
395                .fallback
396                .and_then(|i| u.variants[i].suggested_name.first().cloned()),
397            _ => None,
398        });
399        ir.diagnostics
400            .push(crate::lower::union_note(&parent, &note, read_as.as_deref()));
401    }
402    point_into_source(&mut ir.diagnostics, document.version());
403    diagnostics.append(&mut ir.diagnostics);
404    if config.validation {
405        let opted_out = |def: &crate::ir::TypeDef| {
406            def.component
407                .as_ref()
408                .and_then(|name| config.types.get(name))
409                .and_then(|t| t.validation)
410                == Some(false)
411        };
412        let mut checked = crate::checks::diagnostics(&ir, &opted_out);
413        point_into_source(&mut checked, document.version());
414        diagnostics.append(&mut checked);
415    }
416
417    Ok(Prepared {
418        ir: Some(ir),
419        diagnostics,
420        source: source_name(document.uri()),
421    })
422}
423
424/// Generate from a validated document.
425pub fn generate(
426    document: &ValidatedSourceDocument,
427    config: &Config,
428) -> Result<Generation, GenerateError> {
429    let Prepared {
430        ir,
431        mut diagnostics,
432        source,
433    } = prepare(document, config)?;
434    let Some(ir) = ir else {
435        return Ok(Generation {
436            target: config.target,
437            files: Vec::new(),
438            diagnostics,
439            dependencies: Dependencies::default(),
440        });
441    };
442    let (files, dependencies, unformatted) = match config.target {
443        Target::Rust => {
444            let mut output =
445                rust::emit(&ir, config, &source).map_err(|e| blame_templates(e, config))?;
446            point_into_source(&mut output.diagnostics, document.version());
447            diagnostics.extend(output.diagnostics);
448            let dependencies = Dependencies {
449                rust: output.dependencies,
450                go: Vec::new(),
451            };
452            (output.files, dependencies, output.unformatted)
453        }
454        Target::Go => {
455            let mut output =
456                go::emit(&ir, config, &source).map_err(|e| blame_templates(e, config))?;
457            point_into_source(&mut output.diagnostics, document.version());
458            diagnostics.extend(output.diagnostics);
459            let dependencies = Dependencies {
460                rust: Vec::new(),
461                go: output.dependencies,
462            };
463            (output.files, dependencies, None)
464        }
465    };
466    if let Some(reason) = unformatted {
467        diagnostics.push(Diagnostic {
468            severity: Severity::Warning,
469            kind: DiagnosticKind::Unformatted,
470            schema_id: SchemaId::new(document.uri().clone(), ""),
471            pointer: String::new(),
472            message: format!(
473                "the output is not formatted, so it differs from a formatted run: {reason}"
474            ),
475        });
476    }
477    sort_diagnostics(&mut diagnostics);
478    Ok(Generation {
479        target: config.target,
480        files,
481        diagnostics,
482        dependencies,
483    })
484}
485
486/// The context the templates receive, and what the generator said while
487/// building it — a type an `Error` suppressed is missing from `context`.
488#[derive(Debug, Clone)]
489#[non_exhaustive]
490pub struct TemplateContext {
491    /// The view model as JSON: the contract a template directory is
492    /// written against (see [`TEMPLATE_API`](crate::TEMPLATE_API)).
493    pub context: serde_json::Value,
494    pub diagnostics: Vec<Diagnostic>,
495}
496
497/// The exact context the templates receive. For writing templates; it is
498/// what `roas openapi generate --print-context` prints.
499pub fn template_context(
500    document: &ValidatedSourceDocument,
501    config: &Config,
502) -> Result<TemplateContext, GenerateError> {
503    let prepared = prepare(document, config)?;
504    let Some(ir) = prepared.ir else {
505        return Err(GenerateError::NothingToGenerate(prepared.diagnostics));
506    };
507    let (context, mut more) = match config.target {
508        Target::Rust => rust::context(&ir, config, &prepared.source)?,
509        Target::Go => go::context(&ir, config, &prepared.source)?,
510    };
511    let mut diagnostics = prepared.diagnostics;
512    point_into_source(&mut more, document.version());
513    diagnostics.extend(more);
514    sort_diagnostics(&mut diagnostics);
515    Ok(TemplateContext {
516        context,
517        diagnostics,
518    })
519}
520
521/// Point a diagnostic into a 2.0 source as written: its schemas are read
522/// at their 3.2 home, `/components/schemas`, and sit under `/definitions`.
523///
524/// Only for what the generator found in the normalized document: the
525/// source report's pointers are into the source already.
526fn point_into_source(diagnostics: &mut [Diagnostic], version: SourceVersion) {
527    if matches!(version, SourceVersion::V2) {
528        diagnostics.iter_mut().for_each(point_into_v2_source);
529    }
530}
531
532fn point_into_v2_source(diagnostic: &mut Diagnostic) {
533    let Some(rest) = diagnostic.pointer.strip_prefix("/components/schemas/") else {
534        return;
535    };
536    let pointer = format!("/definitions/{rest}");
537    // An attribute that was not applied names its position in the message.
538    if matches!(diagnostic.kind, DiagnosticKind::IgnoredExtension { .. })
539        && let (Some(old), Some(new)) = (
540            diagnostic.pointer.strip_suffix("/x-rust-attrs"),
541            pointer.strip_suffix("/x-rust-attrs"),
542        )
543    {
544        diagnostic.message = diagnostic
545            .message
546            .replace(&format!("`{old}`"), &format!("`{new}`"));
547    }
548    diagnostic.pointer = pointer;
549}
550
551fn sort_diagnostics(diagnostics: &mut Vec<Diagnostic>) {
552    diagnostics.sort_by(|a, b| {
553        a.pointer
554            .cmp(&b.pointer)
555            .then(a.severity.cmp(&b.severity))
556            .then(a.message.cmp(&b.message))
557    });
558    // A part merged from another component is reported there too: the
559    // same finding at the same place is said once.
560    diagnostics.dedup_by(|a, b| {
561        a.pointer == b.pointer
562            && a.severity == b.severity
563            && a.kind == b.kind
564            && a.message == b.message
565    });
566}
567
568/// The files as the templates render them, before the syntax check and
569/// the formatter: what to look at when a template produces something the
570/// formatter refuses.
571pub fn render(
572    document: &ValidatedSourceDocument,
573    config: &Config,
574) -> Result<Vec<GeneratedFile>, GenerateError> {
575    let prepared = prepare(document, config)?;
576    let Some(ir) = prepared.ir else {
577        return Err(GenerateError::NothingToGenerate(prepared.diagnostics));
578    };
579    match config.target {
580        Target::Rust => rust::render(&ir, config, &prepared.source),
581        Target::Go => go::render(&ir, config, &prepared.source),
582    }
583}
584
585/// A template directory that changes nothing, to show what can be
586/// changed: for each default template rendering under `config` (by its
587/// `target`, `layout` and `validation`), and each one it includes, a template at the
588/// path an override takes, extending the default and filling every block
589/// with the default's content, plus the `roas-templates.toml` manifest.
590/// Used as `template_dir` it renders exactly what the defaults do. It
591/// describes the defaults, whatever `template_dir` says; it is what
592/// `roas openapi generate --dump-scaffold` writes.
593pub fn scaffold(config: &Config) -> Result<Vec<GeneratedFile>, GenerateError> {
594    let entries = match config.target {
595        Target::Rust => rust::entries(config),
596        Target::Go => go::entries(config),
597    };
598    // Validation renders only when it is on.
599    let unused: &[&str] = if config.validation {
600        &[]
601    } else {
602        &["rust/validate.rs.jinja", "go/validate.go.jinja"]
603    };
604    crate::templates::scaffold(&entries, unused)
605}
606
607#[cfg(test)]
608mod tests {
609    #[test]
610    fn every_relative_path_in_a_type_names_its_crate() {
611        let firsts: Vec<_> =
612            super::first_path_segments("Option<chrono::NaiveDate, ::other::X>").collect();
613        assert_eq!(firsts, vec!["chrono"]);
614        let firsts: Vec<_> = super::first_path_segments("a::b::C").collect();
615        assert_eq!(firsts, vec!["a"]);
616        // A combining mark is no alphanumeric, and takes two bytes.
617        let firsts: Vec<_> = super::first_path_segments("cafe\u{301}::Date").collect();
618        assert_eq!(firsts.len(), 1);
619    }
620
621    #[test]
622    fn bidi_controls_are_escaped_in_the_source_name() {
623        let uri = url::Url::parse("file:///specs/a%E2%80%AEb.json").unwrap();
624        let name = super::source_name(&uri);
625        assert!(!name.contains('\u{202E}'), "{name}");
626        assert!(name.contains("\\u{202e}"), "{name}");
627    }
628}