conjure_codegen/lib.rs
1// Copyright 2018 Palantir Technologies, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//! Code generation for Conjure definitions.
15//!
16//! # Examples
17//!
18//! Code generation via a build script, assuming we have a `service-api.conjure.json` file in the crate root:
19//!
20//! build.rs:
21//!
22//! ```no_run
23//! use std::env;
24//! use std::path::Path;
25//!
26//! fn main() {
27//! let input = "service-api.conjure.json";
28//! let output = Path::new(&env::var_os("OUT_DIR").unwrap()).join("service_api");
29//!
30//! println!("cargo:rerun-if-changed={}", input);
31//! conjure_codegen::Config::new()
32//! .run_rustfmt(false)
33//! .strip_prefix("com.foobar.service".to_string())
34//! .generate_files(input, output)
35//! .unwrap();
36//! }
37//! ```
38//!
39//! src/lib.rs:
40//!
41//! ```ignore
42//! mod service_api {
43//! include!(concat!(env!("OUT_DIR"), "/service_api/mod.rs"));
44//! }
45//! ```
46//!
47//! # Types
48//!
49//! ## Builtin
50//!
51//! Builtin types map directly to existing Rust types:
52//!
53//! | Conjure | Rust |
54//! | ------------- | ------------------------------------ |
55//! | `string` | `String` |
56//! | `datetime` | `chrono::DateTime<Utc>` |
57//! | `integer` | `i32` |
58//! | `double` | `f64` |
59//! | `safelong` | `conjure_object::SafeLong` |
60//! | `binary` | `bytes::Bytes` |
61//! | `any` | `conjure_object::Any` |
62//! | `boolean` | `bool` |
63//! | `uuid` | `uuid::Uuid` |
64//! | `rid` | `conjure_object::ResourceIdentifier` |
65//! | `bearertoken` | `conjure_object::BearerToken` |
66//! | `optional<T>` | `Option<T>` |
67//! | `list<T>` | `Vec<T>` |
68//! | `set<T>` | `BTreeSet<T>` |
69//! | `map<K, V>` | `BTreeMap<K, V>` |
70//!
71//! Many of these are exposed by the `conjure-object` crate, which is a required dependency of crates containing the
72//! generated code.
73//!
74//! ### `double`
75//!
76//! Rust's `f64` type does not implement `Ord`, `Eq`, or `Hash`, which requires some special casing. Sets and maps keyed
77//! directly by `double` are represented as `BTreeSet<DoubleKey>` and `BTreeMap<DoubleKey, T>`, where the
78//! [`DoubleKey`](conjure_object::DoubleKey) type wraps `f64` and implements those traits by ordering `NaN` greater
79//! than all other values and equal to itself.
80//!
81//! Conjure aliases, objects, and unions wrapping `double` types have trait implementations which use the same logic.
82//!
83//! ## Objects
84//!
85//! Conjure objects turn into Rust structs along with builders used to construct them:
86//!
87//! ```
88//! # use conjure_codegen::example_types::product::{ManyFieldExample, StringAliasExample};
89//! let object = ManyFieldExample::builder()
90//! .string("foo")
91//! .integer(123)
92//! .double_value(3.14)
93//! .alias(StringAliasExample("foobar".to_string()))
94//! .optional_item("bar".to_string())
95//! .items(vec!["hello".to_string(), "world".to_string()])
96//! .build();
97//!
98//! assert_eq!(object.string(), "foo");
99//! assert_eq!(object.optional_item(), Some("bar"));
100//! ```
101//!
102//! The builder types are by-value and infallible - the compiler will prevent code from compiling if all required
103//! fields are not set. The API requires that all required fields be set first strictly in declaration order,
104//! after which optional fields can be set in any order.
105//!
106//! Objects with 3 or fewer required fields also have an explicit constructor:
107//!
108//! ```rust
109//! # use conjure_codegen::example_types::product::BooleanExample;
110//! let object = BooleanExample::new(true);
111//!
112//! assert_eq!(object.coin(), true);
113//! ```
114//!
115//! The generated structs implement `Debug`, `Clone`, `PartialEq`, Eq, `PartialOrd`, `Ord`, `Hash`, `Serialize`, and
116//! `Deserialize`. They implement `Copy` if they consist entirely of copyable primitive types.
117//!
118//! ## Unions
119//!
120//! Conjure unions turn into Rust enums. By default, unions are *extensible* through an additional `Unknown` variant.
121//! This allows unions to be forward-compatible by allowing clients to deserialize variants they don't yet know about
122//! and reserialize them properly:
123//!
124//! ```
125//! # use conjure_codegen::example_types::product::UnionTypeExample;
126//! # let union_value = UnionTypeExample::If(0);
127//! match union_value {
128//! UnionTypeExample::StringExample(string) => {
129//! // ...
130//! }
131//! UnionTypeExample::Set(set) => {
132//! // ...
133//! }
134//! // ...
135//! UnionTypeExample::Unknown(unknown) => {
136//! println!("got unknown variant: {}", unknown.type_());
137//! }
138//! # _ => {}
139//! }
140//! ```
141//!
142//! The generated enums implement `Debug`, `Clone`, `PartialEq`, `Eq`, `PartialOrd`, `Ord`, `Hash`, `Serialize`, and
143//! `Deserialize`. Union variants which are themselves unions are boxed in the generated enum to avoid self-referential
144//! type definitions.
145//!
146//! ## Enums
147//!
148//! Conjure enums turn into Rust enums. By default, enums are *extensible*. This allows enums to be forward-compatible
149//! by allowing clients to deserialize variants they don't yet know about and reserialize them properly:
150//!
151//! ```
152//! # use conjure_codegen::example_types::product::EnumExample;
153//! # let enum_value = EnumExample::One;
154//! match enum_value {
155//! EnumExample::One => println!("found one"),
156//! EnumExample::Two => println!("found two"),
157//! EnumExample::Unknown(unknown) => println!("got unknown variant: {}", unknown),
158//! }
159//! ```
160//!
161//! The generated enums implement `Debug`, `Clone`, `PartialEq`, `Eq`, `PartialOrd`, `Ord`, `Hash`, `Display`,
162//! `Serialize`, and `Deserialize`.
163//!
164//! ## Aliases
165//!
166//! Conjure aliases turn into Rust newtype structs that act like their inner value:
167//!
168//! ```
169//! # use conjure_codegen::example_types::product::StringAliasExample;
170//! let alias_value = StringAliasExample("hello world".to_string());
171//! assert!(alias_value.starts_with("hello"));
172//! ```
173//!
174//! The generated structs implement `Deref`, `DerefMut`, `Debug`, `Clone`, `PartialEq`, `Eq`, `PartialOrd`, `Ord`,
175//! `Hash`, `Serialize`, and `Deserialize`. They implement `Copy` if they wrap a copyable primitive type, `Default`
176//! if they wrap a type implementing `Default`, `FromIterator` if they wrap a type implementing `FromIterator`, and
177//! `Display` if they wrap a type implementing `Display`. They also implement `From<T>`, where `T` is the fully
178//! de-aliased inner type.
179//!
180//! ## Errors
181//!
182//! Conjure errors turn into Rust structs storing the error's parameters as if it were a Conjure object. The struct
183//! additionally implements the `conjure_error::ErrorType` trait which encodes the extra error metadata:
184//!
185//! ```
186//! # use conjure_codegen::example_types::product::InvalidServiceDefinition;
187//! # let (name, definition) = ("", "");
188//! use conjure_error::{ErrorType, ErrorCode};
189//!
190//! let error = InvalidServiceDefinition::new(name, definition);
191//!
192//! assert_eq!(error.code(), ErrorCode::InvalidArgument);
193//! assert_eq!(error.name(), "Conjure:InvalidServiceDefinition");
194//! ```
195//!
196//! ## Services
197//!
198//! Conjure services turn into client- and server-side interfaces:
199//!
200//! ### Clients
201//!
202//! The client object wraps a raw HTTP client and provides methods to interact with the service's endpoints. Both
203//! synchronous and asynchronous clients are provided:
204//!
205//! Synchronous:
206//! ```
207//! use conjure_http::client::Service;
208//! # use conjure_codegen::example_types::another::TestServiceClient;
209//! # fn foo<T: conjure_http::client::Client>(http_client: T) -> Result<(), conjure_error::Error> {
210//! # let auth_token = "foobar".parse().unwrap();
211//! let client = TestServiceClient::new(http_client);
212//! let file_systems = client.get_file_systems(&auth_token)?;
213//! # Ok(())
214//! # }
215//! ```
216//!
217//! Asynchronous:
218//! ```
219//! use conjure_http::client::AsyncService;
220//! # use conjure_codegen::example_types::another::TestServiceAsyncClient;
221//! # async fn foo<T: conjure_http::client::AsyncClient>(http_client: T) -> Result<(), conjure_error::Error> {
222//! # let auth_token = "foobar".parse().unwrap();
223//! let client = TestServiceAsyncClient::new(http_client);
224//! let file_systems = client.get_file_systems(&auth_token).await?;
225//! # Ok(())
226//! # }
227//! ```
228//!
229//! ### Servers
230//!
231//! Conjure generates a trait and accompanying wrapper resource which are used to implement the service's endpoints.
232//! Both synchronous and asynchronous servers are supported:
233//!
234//! Synchronous:
235//! ```ignore
236//! struct TestServiceHandler;
237//!
238//! impl<T> TestService<T> for TestServiceHandler
239//! where
240//! T: Read
241//! {
242//! fn get_file_systems(
243//! &self,
244//! auth: AuthToken,
245//! ) -> Result<BTreeMap<String, BackingFileSystem>, Error> {
246//! // ...
247//! }
248//!
249//! // ...
250//! }
251//!
252//! let resource = TestServiceResource::new(TestServiceHandler);
253//! http_server.register(resource);
254//! ```
255//!
256//! Asynchronous:
257//! ```ignore
258//! struct TestServiceHandler;
259//!
260//! impl<T> AsyncTestService<T> for TestServiceHandler
261//! where
262//! T: AsyncRead + 'static + Send
263//! {
264//! async fn get_file_systems(
265//! &self,
266//! auth: AuthToken,
267//! ) -> Result<BTreeMap<String, BackingFileSystem>, Error> {
268//! // ...
269//! }
270//!
271//! // ...
272//! }
273//!
274//! let resource = TestServiceResource::new(TestServiceHandler);
275//! http_server.register(resource);
276//! ```
277//!
278//! ### Endpoint Tags
279//!
280//! * `server-request-context` - The generated server trait method will have an additional
281//! `RequestContext` argument providing lower level access to request and response information.
282#![warn(clippy::all, missing_docs)]
283#![allow(clippy::needless_doctest_main)]
284#![recursion_limit = "256"]
285
286use crate::context::Context;
287use crate::types::{ConjureDefinition, TypeDefinition};
288use anyhow::{bail, Context as _, Error};
289use proc_macro2::TokenStream;
290use quote::quote;
291use std::collections::BTreeMap;
292use std::env;
293use std::ffi::OsStr;
294use std::fs;
295use std::path::Path;
296
297mod aliases;
298mod cargo_toml;
299mod clients;
300mod context;
301mod enums;
302mod errors;
303mod http_paths;
304mod objects;
305mod servers;
306#[allow(dead_code, clippy::all)]
307#[rustfmt::skip]
308mod types;
309mod human_size;
310mod unions;
311
312/// Examples of generated Conjure code.
313///
314/// This module is only intended to be present in documentation; it shouldn't be relied on by any library code.
315#[cfg(feature = "example-types")]
316#[allow(warnings)]
317#[rustfmt::skip]
318pub mod example_types;
319
320struct CrateInfo {
321 name: String,
322 version: String,
323}
324
325/// Codegen configuration.
326pub struct Config {
327 exhaustive: bool,
328 serialize_empty_collections: bool,
329 strip_prefix: Option<String>,
330 version: Option<String>,
331 build_crate: Option<CrateInfo>,
332}
333
334impl Default for Config {
335 fn default() -> Config {
336 Config::new()
337 }
338}
339
340impl Config {
341 /// Creates a new `Config` with default settings.
342 pub fn new() -> Config {
343 Config {
344 exhaustive: false,
345 serialize_empty_collections: false,
346 strip_prefix: None,
347 version: None,
348 build_crate: None,
349 }
350 }
351
352 /// Controls exhaustive matchability of unions and enums.
353 ///
354 /// Non-exhaustive unions and enums have the ability to deserialize and reserialize unknown variants. This enables
355 /// clients to be more forward-compatible with changes made by newer servers.
356 ///
357 /// Defaults to `false`.
358 pub fn exhaustive(&mut self, exhaustive: bool) -> &mut Config {
359 self.exhaustive = exhaustive;
360 self
361 }
362
363 /// Controls serialization of empty collection fields in objects.
364 ///
365 /// Some Conjure implementations don't properly handle deserialization of objects when empty collections are
366 /// omitted. Enabling this option will cause empty optional, set, list, and map fields to be included in the
367 /// serialized output.
368 pub fn serialize_empty_collections(
369 &mut self,
370 serialize_empty_collections: bool,
371 ) -> &mut Config {
372 self.serialize_empty_collections = serialize_empty_collections;
373 self
374 }
375
376 /// No longer used.
377 #[deprecated(note = "no longer used", since = "1.2.0")]
378 pub fn run_rustfmt(&mut self, _run_rustfmt: bool) -> &mut Config {
379 self
380 }
381
382 /// No longer used.
383 #[deprecated(note = "no longer used", since = "1.2.0")]
384 pub fn rustfmt<T>(&mut self, _rustfmt: T) -> &mut Config
385 where
386 T: AsRef<OsStr>,
387 {
388 self
389 }
390
391 /// Sets a prefix that will be stripped from package names.
392 ///
393 /// Defaults to `None`.
394 pub fn strip_prefix<T>(&mut self, strip_prefix: T) -> &mut Config
395 where
396 T: Into<Option<String>>,
397 {
398 self.strip_prefix = strip_prefix.into();
399 self
400 }
401
402 /// Sets the version included in endpoint metadata for generated client bindings.
403 ///
404 /// Defaults to the version passed to [`Self::build_crate`], or `None` otherwise.
405 pub fn version<T>(&mut self, version: T) -> &mut Config
406 where
407 T: Into<Option<String>>,
408 {
409 self.version = version.into();
410 self
411 }
412
413 /// Switches generation to create a full crate.
414 ///
415 /// Defaults to just generating a single module.
416 pub fn build_crate(&mut self, name: &str, version: &str) -> &mut Config {
417 self.build_crate = Some(CrateInfo {
418 name: name.to_string(),
419 version: version.to_string(),
420 });
421 self
422 }
423
424 /// Generates Rust source files from a JSON-encoded Conjure IR file.
425 pub fn generate_files<P, Q>(&self, ir_file: P, out_dir: Q) -> Result<(), Error>
426 where
427 P: AsRef<Path>,
428 Q: AsRef<Path>,
429 {
430 self.generate_files_inner(ir_file.as_ref(), out_dir.as_ref())
431 }
432
433 fn generate_files_inner(&self, ir_file: &Path, out_dir: &Path) -> Result<(), Error> {
434 let defs = self.parse_ir(ir_file)?;
435
436 if defs.version() != 1 {
437 bail!("unsupported IR version {}", defs.version());
438 }
439
440 let modules = self.create_modules(&defs);
441 let (src_dir, lib_root) = if self.build_crate.is_some() {
442 (out_dir.join("src"), true)
443 } else {
444 (out_dir.to_path_buf(), false)
445 };
446
447 if let Some(info) = &self.build_crate {
448 self.write_cargo_toml(out_dir, info, &defs)?;
449 self.write_rustfmt_toml(out_dir)?;
450 }
451
452 modules.render(&src_dir, lib_root)?;
453
454 Ok(())
455 }
456
457 fn parse_ir(&self, ir_file: &Path) -> Result<ConjureDefinition, Error> {
458 let ir = fs::read_to_string(ir_file)
459 .with_context(|| format!("error reading file {}", ir_file.display()))?;
460
461 let defs = conjure_serde::json::client_from_str(&ir)
462 .with_context(|| format!("error parsing Conjure IR file {}", ir_file.display()))?;
463
464 Ok(defs)
465 }
466
467 fn create_modules(&self, defs: &ConjureDefinition) -> ModuleTrie {
468 let context = Context::new(
469 defs,
470 self.exhaustive,
471 self.serialize_empty_collections,
472 self.strip_prefix.as_deref(),
473 self.version
474 .as_deref()
475 .or_else(|| self.build_crate.as_ref().map(|v| &*v.version)),
476 );
477
478 let mut root = ModuleTrie::new();
479
480 for def in defs.types() {
481 let (type_name, contents) = match def {
482 TypeDefinition::Enum(def) => (def.type_name(), enums::generate(&context, def)),
483 TypeDefinition::Alias(def) => (def.type_name(), aliases::generate(&context, def)),
484 TypeDefinition::Union(def) => (def.type_name(), unions::generate(&context, def)),
485 TypeDefinition::Object(def) => (def.type_name(), objects::generate(&context, def)),
486 };
487
488 let type_ = Type {
489 module_name: context.module_name(type_name),
490 type_names: vec![context.type_name(type_name.name()).to_string()],
491 contents,
492 };
493 root.insert(&context.module_path(type_name), type_);
494 }
495
496 for def in defs.errors() {
497 let type_ = Type {
498 module_name: context.module_name(def.error_name()),
499 type_names: vec![context.type_name(def.error_name().name()).to_string()],
500 contents: errors::generate(&context, def),
501 };
502 root.insert(&context.module_path(def.error_name()), type_);
503 }
504
505 for def in defs.services() {
506 let client = clients::generate(&context, def);
507 let server = servers::generate(&context, def);
508
509 let contents = quote! {
510 #client
511 #server
512 };
513 let type_ = Type {
514 module_name: context.module_name(def.service_name()),
515 type_names: vec![
516 format!("{}Client", def.service_name().name()),
517 format!("{}AsyncClient", def.service_name().name()),
518 context.type_name(def.service_name().name()).to_string(),
519 format!("Async{}", def.service_name().name()),
520 format!("{}Endpoints", def.service_name().name()),
521 format!("Async{}Endpoints", def.service_name().name()),
522 ],
523 contents,
524 };
525 root.insert(&context.module_path(def.service_name()), type_);
526 }
527
528 root
529 }
530
531 fn write_cargo_toml(
532 &self,
533 dir: &Path,
534 info: &CrateInfo,
535 def: &ConjureDefinition,
536 ) -> Result<(), Error> {
537 fs::create_dir_all(dir)
538 .with_context(|| format!("error creating directory {}", dir.display()))?;
539
540 let metadata = def
541 .extensions()
542 .get("recommended-product-dependencies")
543 .map(|deps| cargo_toml::Metadata {
544 sls: cargo_toml::Sls {
545 recommended_product_dependencies: deps,
546 },
547 });
548
549 let mut needs_object = false;
550 let mut needs_error = false;
551 let mut needs_http = false;
552
553 if !def.types().is_empty() {
554 needs_object = true;
555 }
556
557 if !def.errors().is_empty() {
558 needs_object = true;
559 needs_error = true;
560 }
561
562 if !def.services().is_empty() {
563 needs_http = true;
564 needs_object = true;
565 }
566
567 let conjure_version = env!("CARGO_PKG_VERSION");
568 let mut dependencies = BTreeMap::new();
569 if needs_object {
570 dependencies.insert("conjure-object", conjure_version);
571 }
572 if needs_error {
573 dependencies.insert("conjure-error", conjure_version);
574 }
575 if needs_http {
576 dependencies.insert("conjure-http", conjure_version);
577 }
578
579 let manifest = cargo_toml::Manifest {
580 package: cargo_toml::Package {
581 name: &info.name,
582 version: &info.version,
583 edition: "2018",
584 metadata,
585 },
586 dependencies,
587 };
588
589 let manifest = toml::to_string_pretty(&manifest).unwrap();
590
591 let file = dir.join("Cargo.toml");
592
593 fs::write(&file, manifest)
594 .with_context(|| format!("error writing manifest file {}", file.display()))?;
595
596 Ok(())
597 }
598
599 fn write_rustfmt_toml(&self, dir: &Path) -> Result<(), Error> {
600 let contents = "\
601disable_all_formatting = true
602";
603
604 let file = dir.join("rustfmt.toml");
605
606 fs::write(file, contents).with_context(|| "error writing rustfmt.toml")?;
607
608 Ok(())
609 }
610}
611
612struct Type {
613 module_name: String,
614 type_names: Vec<String>,
615 contents: TokenStream,
616}
617
618struct ModuleTrie {
619 submodules: BTreeMap<String, ModuleTrie>,
620 types: Vec<Type>,
621}
622
623impl ModuleTrie {
624 fn new() -> ModuleTrie {
625 ModuleTrie {
626 submodules: BTreeMap::new(),
627 types: vec![],
628 }
629 }
630
631 fn insert(&mut self, module_path: &[String], type_: Type) {
632 match module_path.split_first() {
633 Some((first, rest)) => self
634 .submodules
635 .entry(first.clone())
636 .or_insert_with(ModuleTrie::new)
637 .insert(rest, type_),
638 None => self.types.push(type_),
639 }
640 }
641
642 fn render(&self, dir: &Path, lib_root: bool) -> Result<(), Error> {
643 fs::create_dir_all(dir)
644 .with_context(|| format!("error creating directory {}", dir.display()))?;
645
646 for type_ in &self.types {
647 self.write_module(
648 &dir.join(format!("{}.rs", type_.module_name)),
649 &type_.contents,
650 )?;
651 }
652
653 for (name, module) in &self.submodules {
654 module.render(&dir.join(name), false)?;
655 }
656
657 let root = self.create_root_module(lib_root);
658 let file_name = if lib_root { "lib.rs" } else { "mod.rs" };
659 self.write_module(&dir.join(file_name), &root)?;
660
661 Ok(())
662 }
663
664 fn write_module(&self, path: &Path, contents: &TokenStream) -> Result<(), Error> {
665 let file = syn::parse2(contents.clone())?;
666 let formatted = prettyplease::unparse(&file);
667
668 fs::write(path, formatted)
669 .with_context(|| format!("error writing module {}", path.display()))?;
670 Ok(())
671 }
672
673 fn create_root_module(&self, lib_root: bool) -> TokenStream {
674 let attrs = if lib_root {
675 quote! {
676 #![allow(warnings)]
677 }
678 } else {
679 quote! {}
680 };
681
682 let uses = self.types.iter().map(|m| {
683 let module_name = m.module_name.parse::<TokenStream>().unwrap();
684 let type_names = m
685 .type_names
686 .iter()
687 .map(|n| n.parse::<TokenStream>().unwrap());
688 quote! {
689 #[doc(inline)]
690 pub use self::#module_name::{#(#type_names),*};
691 }
692 });
693
694 let type_mods = self.types.iter().map(|m| {
695 let module_name = m.module_name.parse::<TokenStream>().unwrap();
696 quote! {
697 pub mod #module_name;
698 }
699 });
700
701 let sub_mods = self.submodules.keys().map(|v| {
702 let module_name = v.parse::<TokenStream>().unwrap();
703 quote! {
704 pub mod #module_name;
705 }
706 });
707
708 quote! {
709 #attrs
710 #(#uses)*
711
712 #(#type_mods)*
713 #(#sub_mods)*
714 }
715 }
716}