1use 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#[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#[derive(Debug, Clone, Default, PartialEq, Eq)]
36#[non_exhaustive]
37pub struct Dependencies {
38 pub rust: Vec<RustDependency>,
39 pub go: Vec<GoDependency>,
41}
42
43#[derive(Debug, Clone)]
46#[non_exhaustive]
47pub struct Generation {
48 pub target: Target,
51 pub files: Vec<GeneratedFile>,
52 pub diagnostics: Vec<Diagnostic>,
53 pub dependencies: Dependencies,
54}
55
56impl Generation {
57 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 pub fn has_errors(&self) -> bool {
71 self.diagnostics
72 .iter()
73 .any(|d| d.severity == Severity::Error)
74 }
75}
76
77#[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 #[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 #[error("nothing can be generated: {}", .0.iter().map(ToString::to_string).collect::<Vec<_>>().join("; "))]
120 NothingToGenerate(Vec<Diagnostic>),
121 #[error("toolchain: {0}")]
124 Toolchain(String),
125}
126
127fn 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 .find(|(_, c)| c.is_whitespace() || "<>,()[]&*;:'!=+".contains(*c))
140 .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
148fn 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 percent_decode(name)
159 .chars()
160 .flat_map(|c| {
161 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
205fn check_rust(config: &Config) -> Result<(), GenerateError> {
208 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 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 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 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 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
288fn 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
299struct 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 match config.target {
326 Target::Rust => check_rust(config)?,
327 Target::Go => check_go(config)?,
328 }
329 let mut diagnostics = document.diagnostics();
330
331 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 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 ir.suppress();
385 }
386 for (parent, note) in std::mem::take(&mut ir.union_notes) {
389 if ir.suppressed.contains(&parent) {
390 continue;
391 }
392 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, ¬e, 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
424pub 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#[derive(Debug, Clone)]
489#[non_exhaustive]
490pub struct TemplateContext {
491 pub context: serde_json::Value,
494 pub diagnostics: Vec<Diagnostic>,
495}
496
497pub 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
521fn 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 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 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
568pub 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
585pub 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 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 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}