Skip to main content

tsurara_backend/
lib.rs

1//! The interface between the model and the code generator of each language (design.md 18.3).
2//! This crate depends on no language crate; `tsurara-cli` registers the built-in backends.
3//!
4//! Published for backends outside this repository, with one version for all tsurara crates,
5//! released with the CLI and moving with `semVersion`. Stable: `Backend`, `Emitted`, `Output`,
6//! `OutputFile`, `Markers`, `generate`, `manifest`, `plugin`, and the protocol types of `external`
7//! and `session`.
8
9pub mod external;
10pub mod hoist;
11pub mod manifest;
12pub mod operation_def;
13pub mod plugin;
14pub mod session;
15
16pub use manifest::Manifest;
17use tsurara_sem::{Model, Options, Warning};
18
19#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
20#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
21pub struct OutputFile {
22    /// Path relative to the output root (`/`-separated).
23    pub path: String,
24    pub contents: String,
25}
26
27/// Result of generation.
28#[derive(Debug, Clone)]
29pub struct Output {
30    /// Output files sorted by path.
31    pub files: Vec<OutputFile>,
32    pub warnings: Vec<Warning>,
33    /// What the backend generated, by name; `None` for external backends that do not return one.
34    pub manifest: Option<Manifest>,
35}
36
37/// What `Backend::example` receives: the model, the manifest `emit` returned for it, and the sample
38/// values of the operation (design.md 18.7.1).
39#[derive(Debug, Clone, Copy)]
40pub struct ExampleInput<'a> {
41    pub model: &'a Model,
42    pub opts: &'a Options,
43    pub manifest: &'a Manifest,
44    pub operation: &'a tsurara_sem::operation::Operation,
45    pub samples: &'a tsurara_sample::OperationSamples,
46}
47
48/// The base URL call examples use: the definition's first server, with its variables at their
49/// defaults, when that is an absolute URL; `https://api.example.com` (with the server's path, if
50/// it is relative) otherwise.
51pub fn example_base_url(model: &Model) -> String {
52    let Some(server) = model.servers.first() else {
53        return "https://api.example.com".into();
54    };
55    let mut url = server.url.clone();
56    for v in &server.variables {
57        url = url.replace(&format!("{{{}}}", v.name), &v.default);
58    }
59    if url.contains(['{', '"', '\\', '\'', '`']) || tsurara_sem::text::has_control(&url) {
60        return "https://api.example.com".into();
61    }
62    if url.starts_with("https://") || url.starts_with("http://") {
63        url
64    } else {
65        format!(
66            "https://api.example.com{}",
67            if url.starts_with('/') {
68                url
69            } else {
70                String::new()
71            }
72        )
73    }
74}
75
76/// A call example: `code` compiles as the file `file` (relative to the output root) next to the
77/// generated code.
78#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
79#[serde(rename_all = "camelCase")]
80pub struct Example {
81    pub file: String,
82    pub code: String,
83    /// How to use the file where placing it is not enough (a module declaration, ...).
84    #[serde(skip_serializing_if = "Option::is_none")]
85    pub note: Option<String>,
86}
87
88/// What a backend's `emit` returns.
89#[derive(Debug, Clone)]
90pub struct Emitted {
91    pub files: Vec<OutputFile>,
92    /// Warnings of the backend's own approximations; the model's are not included.
93    pub warnings: Vec<Warning>,
94    pub manifest: Option<Manifest>,
95}
96
97/// How the CLI recognizes a backend's files (design.md 18.8).
98#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
99#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
100#[serde(rename_all = "camelCase")]
101pub struct Markers {
102    /// The first line of every generated file, in the language's comment syntax. The CLI deletes stale
103    /// files that start with it and leaves other files alone.
104    pub generated: String,
105    /// Where generated code records the runtime library version range it requires.
106    #[serde(default)]
107    pub version: Option<VersionMarker>,
108    /// Extensions of files that tools keep next to generated files (`.uid` for Godot). They are deleted
109    /// together with a stale generated file.
110    #[serde(default)]
111    pub sidecars: Vec<String>,
112}
113
114#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
115#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
116pub struct VersionMarker {
117    /// Output file that holds the line, relative to the output root.
118    pub file: String,
119    /// Prefix of the line; the rest of the line is the range.
120    pub prefix: String,
121}
122
123impl Markers {
124    /// The version range recorded in `files`, if the backend records one.
125    pub fn recorded_version(&self, files: &[OutputFile]) -> Option<String> {
126        let marker = self.version.as_ref()?;
127        let file = files.iter().find(|f| f.path == marker.file)?;
128        file.contents
129            .lines()
130            .find_map(|l| l.strip_prefix(marker.prefix.as_str()))
131            .map(|r| r.trim().to_owned())
132    }
133}
134
135/// A code generator for one language.
136pub trait Backend {
137    /// `typescript`, `python`, ... Used as the `language` value in the configuration.
138    fn id(&self) -> &'static str;
139
140    /// How the CLI recognizes this backend's files.
141    fn markers(&self) -> Markers;
142
143    /// Builds the output files from the model, with the warnings of the backend's own approximations
144    /// and the manifest of what it generated.
145    fn emit(&self, model: &Model, opts: &Options) -> Result<Emitted, Error>;
146
147    /// A call example for one operation (`tsurara inspect operation`): a file that calls
148    /// the generated function with the operation's sample values and handles its Result as the
149    /// language does. `None` when the backend has no examples or the operation no function.
150    fn example(&self, _input: &ExampleInput) -> Option<Example> {
151        None
152    }
153
154    /// The options of the language as JSON, as plugins receive them (`ExtendInput::options`): what a
155    /// plugin needs to write files that match the generated code, such as TypeScript's import
156    /// extension. `null` by default.
157    fn options_json(&self) -> serde_json::Value {
158        serde_json::Value::Null
159    }
160}
161
162#[derive(Debug, thiserror::Error)]
163pub enum Error {
164    #[error(transparent)]
165    Sem(#[from] tsurara_sem::Error),
166    /// A backend program failed or answered something that does not follow the protocol.
167    #[error("{0}")]
168    External(String),
169    /// Options the backend cannot generate with.
170    #[error("{0}")]
171    Options(String),
172    #[error("plugin `{name}`: {source}")]
173    Plugin {
174        name: String,
175        #[source]
176        source: plugin::PluginError,
177    },
178}
179
180/// Builds the output files from the model with `backend`, together with the model's warnings.
181pub fn generate_from_model(
182    backend: &dyn Backend,
183    model: &Model,
184    opts: &Options,
185) -> Result<Output, Error> {
186    let Emitted {
187        files,
188        warnings: backend_warnings,
189        manifest,
190    } = backend.emit(model, opts)?;
191    let mut warnings = model.warnings.clone();
192    // Warnings of the backend's own approximations name the language (design.md 18.4.5).
193    warnings.extend(backend_warnings.into_iter().map(|w| Warning {
194        language: Some(backend.id().to_owned()),
195        ..w
196    }));
197    warnings.sort();
198    warnings.dedup();
199    Ok(Output {
200        files,
201        warnings,
202        manifest,
203    })
204}
205
206/// Builds the model from a loaded definition and generates with `backend`.
207pub fn generate(
208    backend: &dyn Backend,
209    set: &tsurara_loader::DocumentSet,
210    opts: &Options,
211) -> Result<Output, Error> {
212    let model = tsurara_sem::build_model(set, opts)?;
213    generate_from_model(backend, &model, opts)
214}
215
216pub use plugin::generate_with_plugins;
217
218/// The JSON Schemas of what tsurara exchanges with programs outside it, by file name in `spec/`
219///: the model (design.md 18.4.6), the manifest (11.1), and the messages of the plugin and
220/// external backend protocols (11, 18.11).
221#[cfg(feature = "schema")]
222pub fn json_schemas() -> Vec<(&'static str, String)> {
223    use schemars::generate::SchemaSettings;
224    let render = |schema: schemars::Schema| {
225        let mut text = serde_json::to_string_pretty(&schema).expect("schemas serialize");
226        text.push('\n');
227        text
228    };
229    let settings = || SchemaSettings::draft2020_12();
230    let model = settings()
231        .into_generator()
232        .into_root_schema_for::<tsurara_sem::Model>();
233    let manifest = settings()
234        .into_generator()
235        .into_root_schema_for::<Manifest>();
236
237    // The protocol: one definition per message, and the root accepts any of them.
238    let mut generator = settings().into_generator();
239    let messages = [
240        ("Describe", generator.subschema_for::<external::Describe>()),
241        (
242            "GenerateRequest",
243            generator.subschema_for::<external::GenerateRequest>(),
244        ),
245        (
246            "GenerateResponse",
247            generator.subschema_for::<external::GenerateResponse>(),
248        ),
249        (
250            "ExtendInput",
251            generator.subschema_for::<plugin::ExtendInput>(),
252        ),
253        ("Files", generator.subschema_for::<Vec<OutputFile>>()),
254        (
255            "SessionRequest",
256            generator.subschema_for::<session::SessionRequest>(),
257        ),
258        (
259            "SessionResponse",
260            generator.subschema_for::<session::SessionResponse>(),
261        ),
262    ];
263    let mut defs = generator.take_definitions(true);
264    // Messages that are not a definition of their own (a list of files) become one.
265    let refs: Vec<serde_json::Value> = messages
266        .into_iter()
267        .map(|(name, schema)| {
268            let value = schema.to_value();
269            if value.get("$ref").is_some() {
270                value
271            } else {
272                defs.insert(name.into(), value);
273                serde_json::json!({ "$ref": format!("#/$defs/{name}") })
274            }
275        })
276        .collect();
277    let protocol = serde_json::json!({
278        "$schema": "https://json-schema.org/draft/2020-12/schema",
279        "title": "tsurara plugin and external backend protocol",
280        "description": "`describe` answers with Describe; `generate` receives GenerateRequest and answers with GenerateResponse; the extend hook receives ExtendInput and answers with Files; transformFiles receives and answers with Files; transformModel receives and answers with the model (sem-model.schema.json). Plugin modules exchange SessionRequest and SessionResponse, one per line.",
281        "anyOf": refs,
282        "$defs": defs,
283    });
284    vec![
285        ("sem-model.schema.json", render(model)),
286        ("manifest.schema.json", render(manifest)),
287        (
288            "plugin-protocol.schema.json",
289            format!(
290                "{}\n",
291                serde_json::to_string_pretty(&protocol).expect("serializes")
292            ),
293        ),
294    ]
295}