Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type name collision fix #601

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions typify-impl/src/defaults.rs
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,17 @@ impl TypeEntry {
(format!("defaults::{}", fn_name), Some(def))
}
}

pub(crate) fn rename(&mut self, new_name: String) {
match &mut self.details {
TypeEntryDetails::Enum(TypeEntryEnum { name, .. })
| TypeEntryDetails::Struct(TypeEntryStruct { name, .. })
| TypeEntryDetails::Newtype(TypeEntryNewtype { name, .. }) => {
*name = new_name;
}
_ => {}
}
}
}

pub(crate) fn validate_default_for_external_enum(
Expand Down
14 changes: 12 additions & 2 deletions typify-impl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

#![deny(missing_docs)]

use std::collections::{BTreeMap, BTreeSet};
use std::collections::{BTreeMap, BTreeSet, HashSet};

use conversions::SchemaCache;
use log::info;
Expand Down Expand Up @@ -205,6 +205,8 @@ pub struct TypeSpace {

cache: SchemaCache,

names: HashSet<String>,

// Shared functions for generating default values
defaults: BTreeSet<DefaultImpl>,
}
Expand All @@ -224,6 +226,7 @@ impl Default for TypeSpace {
uses_regress: Default::default(),
settings: Default::default(),
cache: Default::default(),
names: Default::default(),
defaults: Default::default(),
}
}
Expand Down Expand Up @@ -562,14 +565,15 @@ impl TypeSpace {
} else {
Name::Unknown
};
self.convert_ref_type(type_name, schema, type_id)?
self.convert_ref_type(type_name, schema, type_id)?;
}

Some(replace_type) => {
let type_entry = TypeEntry::new_native(
replace_type.replace_type.clone(),
&replace_type.impls.clone(),
);

self.id_to_entry.insert(type_id, type_entry);
}
}
Expand All @@ -584,6 +588,9 @@ impl TypeSpace {
let type_id = TypeId(index);
let mut type_entry = self.id_to_entry.get(&type_id).unwrap().clone();
type_entry.finalize(self)?;
// I think we should do it this, because in this place we're iterating over all
// created types.
type_entry.ensure_unique_name(self);
self.id_to_entry.insert(type_id, type_entry);
}

Expand Down Expand Up @@ -679,6 +686,9 @@ impl TypeSpace {
let type_id = TypeId(index);
let mut type_entry = self.id_to_entry.get(&type_id).unwrap().clone();
type_entry.finalize(self)?;
// I think we should do it this, because in this place we're iterating over all
// created types.
type_entry.ensure_unique_name(self);
self.id_to_entry.insert(type_id, type_entry);
}

Expand Down
15 changes: 15 additions & 0 deletions typify-impl/src/type_entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,21 @@ impl TypeEntry {
self.check_defaults(type_space)
}

// Ensures that the name is unique within the provided `TypeSpace`.
//
// This function checks if the current object's name already exists in the `TypeSpace`. If it does,
// the function modifies the name by appending "Alias" until a unique name is found. The unique name
// is then inserted into the `TypeSpace` and the object's name is updated accordingly.
pub(crate) fn ensure_unique_name(&mut self, type_space: &mut TypeSpace) {
if let Some(mut name) = self.name().cloned() {
while type_space.names.contains(&name) {
name = format!("{name}Alias");
}
type_space.names.insert(name.clone());
self.rename(name);
}
}

pub(crate) fn name(&self) -> Option<&String> {
match &self.details {
TypeEntryDetails::Enum(TypeEntryEnum { name, .. })
Expand Down
26 changes: 26 additions & 0 deletions typify/tests/schemas/property-name-collision.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"$schema": "http:https://json-schema.org/draft-04/schema#",
"definitions": {
"Foo": {
"properties": {
"Bar": {
"oneOf": [
{
"$ref": "#/definitions/FooBar"
},
{
"$ref": "#/definitions/Baz"
}
]
}
},
"type": "object"
},
"FooBar": {
"type": "string"
},
"Baz": {
"type": "string"
}
}
}
225 changes: 225 additions & 0 deletions typify/tests/schemas/property-name-collision.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
#[allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[doc = r" Error types."]
pub mod error {
#[doc = r" Error from a TryFrom or FromStr implementation."]
pub struct ConversionError(std::borrow::Cow<'static, str>);
impl std::error::Error for ConversionError {}
impl std::fmt::Display for ConversionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
std::fmt::Display::fmt(&self.0, f)
}
}
impl std::fmt::Debug for ConversionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
std::fmt::Debug::fmt(&self.0, f)
}
}
impl From<&'static str> for ConversionError {
fn from(value: &'static str) -> Self {
Self(value.into())
}
}
impl From<String> for ConversionError {
fn from(value: String) -> Self {
Self(value.into())
}
}
}
#[doc = "Baz"]
#[doc = r""]
#[doc = r" <details><summary>JSON schema</summary>"]
#[doc = r""]
#[doc = r" ```json"]
#[doc = "{"]
#[doc = " \"type\": \"string\""]
#[doc = "}"]
#[doc = r" ```"]
#[doc = r" </details>"]
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct Baz(pub String);
impl std::ops::Deref for Baz {
type Target = String;
fn deref(&self) -> &String {
&self.0
}
}
impl From<Baz> for String {
fn from(value: Baz) -> Self {
value.0
}
}
impl From<&Baz> for Baz {
fn from(value: &Baz) -> Self {
value.clone()
}
}
impl From<String> for Baz {
fn from(value: String) -> Self {
Self(value)
}
}
impl std::str::FromStr for Baz {
type Err = std::convert::Infallible;
fn from_str(value: &str) -> Result<Self, Self::Err> {
Ok(Self(value.to_string()))
}
}
impl ToString for Baz {
fn to_string(&self) -> String {
self.0.to_string()
}
}
#[doc = "Foo"]
#[doc = r""]
#[doc = r" <details><summary>JSON schema</summary>"]
#[doc = r""]
#[doc = r" ```json"]
#[doc = "{"]
#[doc = " \"type\": \"object\","]
#[doc = " \"properties\": {"]
#[doc = " \"Bar\": {"]
#[doc = " \"oneOf\": ["]
#[doc = " {"]
#[doc = " \"$ref\": \"#/definitions/FooBar\""]
#[doc = " },"]
#[doc = " {"]
#[doc = " \"$ref\": \"#/definitions/Baz\""]
#[doc = " }"]
#[doc = " ]"]
#[doc = " }"]
#[doc = " }"]
#[doc = "}"]
#[doc = r" ```"]
#[doc = r" </details>"]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Foo {
#[serde(rename = "Bar", default, skip_serializing_if = "Option::is_none")]
pub bar: Option<FooBarAlias>,
}
impl From<&Foo> for Foo {
fn from(value: &Foo) -> Self {
value.clone()
}
}
#[doc = "FooBar"]
#[doc = r""]
#[doc = r" <details><summary>JSON schema</summary>"]
#[doc = r""]
#[doc = r" ```json"]
#[doc = "{"]
#[doc = " \"type\": \"string\""]
#[doc = "}"]
#[doc = r" ```"]
#[doc = r" </details>"]
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct FooBar(pub String);
impl std::ops::Deref for FooBar {
type Target = String;
fn deref(&self) -> &String {
&self.0
}
}
impl From<FooBar> for String {
fn from(value: FooBar) -> Self {
value.0
}
}
impl From<&FooBar> for FooBar {
fn from(value: &FooBar) -> Self {
value.clone()
}
}
impl From<String> for FooBar {
fn from(value: String) -> Self {
Self(value)
}
}
impl std::str::FromStr for FooBar {
type Err = std::convert::Infallible;
fn from_str(value: &str) -> Result<Self, Self::Err> {
Ok(Self(value.to_string()))
}
}
impl ToString for FooBar {
fn to_string(&self) -> String {
self.0.to_string()
}
}
#[doc = "FooBarAlias"]
#[doc = r""]
#[doc = r" <details><summary>JSON schema</summary>"]
#[doc = r""]
#[doc = r" ```json"]
#[doc = "{"]
#[doc = " \"oneOf\": ["]
#[doc = " {"]
#[doc = " \"$ref\": \"#/definitions/FooBar\""]
#[doc = " },"]
#[doc = " {"]
#[doc = " \"$ref\": \"#/definitions/Baz\""]
#[doc = " }"]
#[doc = " ]"]
#[doc = "}"]
#[doc = r" ```"]
#[doc = r" </details>"]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum FooBarAlias {
FooBar(FooBar),
Baz(Baz),
}
impl From<&FooBarAlias> for FooBarAlias {
fn from(value: &FooBarAlias) -> Self {
value.clone()
}
}
impl std::str::FromStr for FooBarAlias {
type Err = self::error::ConversionError;
fn from_str(value: &str) -> Result<Self, self::error::ConversionError> {
if let Ok(v) = value.parse() {
Ok(Self::FooBar(v))
} else if let Ok(v) = value.parse() {
Ok(Self::Baz(v))
} else {
Err("string conversion failed for all variants".into())
}
}
}
impl std::convert::TryFrom<&str> for FooBarAlias {
type Error = self::error::ConversionError;
fn try_from(value: &str) -> Result<Self, self::error::ConversionError> {
value.parse()
}
}
impl std::convert::TryFrom<&String> for FooBarAlias {
type Error = self::error::ConversionError;
fn try_from(value: &String) -> Result<Self, self::error::ConversionError> {
value.parse()
}
}
impl std::convert::TryFrom<String> for FooBarAlias {
type Error = self::error::ConversionError;
fn try_from(value: String) -> Result<Self, self::error::ConversionError> {
value.parse()
}
}
impl ToString for FooBarAlias {
fn to_string(&self) -> String {
match self {
Self::FooBar(x) => x.to_string(),
Self::Baz(x) => x.to_string(),
}
}
}
impl From<FooBar> for FooBarAlias {
fn from(value: FooBar) -> Self {
Self::FooBar(value)
}
}
impl From<Baz> for FooBarAlias {
fn from(value: Baz) -> Self {
Self::Baz(value)
}
}
fn main() {}
Loading