xsd_parser/generator/misc.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
use std::borrow::Cow;
use std::collections::{BTreeMap, HashSet};
use bitflags::bitflags;
use inflector::Inflector;
use proc_macro2::{Ident as Ident2, TokenStream};
use quote::{format_ident, quote};
use crate::schema::{MaxOccurs, MinOccurs, NamespaceId};
use crate::types::{Ident, Name, Type, Types};
use super::Error;
bitflags! {
/// Different flags that control what code the [`Generator`](super::Generator)
/// is generating.
#[derive(Debug, Clone, Copy)]
pub struct GenerateFlags: u32 {
/// None of the features are enabled.
///
/// # Examples
///
/// Consider the following XML schema:
/// ```xml
#[doc = include_str!("../../tests/generator/generate_flags/schema.xsd")]
/// ```
///
/// Setting none of the flags will result in the following code:
/// ```rust
#[doc = include_str!("../../tests/generator/generate_flags/expected/empty.rs")]
/// ```
const NONE = 0;
/// The generated code uses modules for the different namespaces.
///
/// # Examples
///
/// Consider the following XML schema:
/// ```xml
#[doc = include_str!("../../tests/generator/generate_flags/schema.xsd")]
/// ```
///
/// Enable the `USE_MODULES` feature only will result in the following code:
/// ```rust,ignore
#[doc = include_str!("../../tests/generator/generate_flags/expected/use_modules.rs")]
/// ```
const USE_MODULES = 1 << 0;
/// The generator flattens the content type of choice types if it does not
/// define any element attributes.
///
/// # Examples
///
/// Consider the following XML schema:
/// ```xml
#[doc = include_str!("../../tests/generator/generate_flags/schema.xsd")]
/// ```
///
/// Enable the `FLATTEN_CONTENT` feature only will result in the following code:
/// ```rust
#[doc = include_str!("../../tests/generator/generate_flags/expected/flatten_content.rs")]
/// ```
const FLATTEN_CONTENT = 1 << 1;
/// The generator will generate code to serialize the generated types using
/// the `quick_xml` crate.
const QUICK_XML_SERIALIZE = 1 << 2;
/// The generator will generate code to deserialize the generated types using
/// the `quick_xml` crate.
const QUICK_XML_DESERIALIZE = 1 << 3;
/// Combination of `QUICK_XML_SERIALIZE` and [`QUICK_XML_DESERIALIZE`].
const QUICK_XML = Self::QUICK_XML_SERIALIZE.bits() | Self::QUICK_XML_DESERIALIZE.bits();
/// Implement the [`WithNamespace`](crate::WithNamespace) trait for the generated types.
const WITH_NAMESPACE_TRAIT = 1 << 4;
}
}
bitflags! {
/// Flags to tell the [`Generator`](super::Generator) how to deal with boxed
/// types.
#[derive(Default, Debug, Clone, Copy, Eq, PartialEq)]
pub struct BoxFlags: u32 {
/// Boxed types will only be used if necessary.
///
/// # Examples
///
/// Consider the following XML schema:
/// ```xml
#[doc = include_str!("../../tests/generator/box_flags/schema.xsd")]
/// ```
///
/// Enable the `AUTO` feature only will result in the following code:
/// ```rust
#[doc = include_str!("../../tests/generator/box_flags/expected/auto.rs")]
/// ```
const AUTO = 0;
/// Elements in a `xs:choice` type will always be boxed.
///
/// # Examples
///
/// Consider the following XML schema:
/// ```xml
#[doc = include_str!("../../tests/generator/box_flags/schema.xsd")]
/// ```
///
/// Enable the `ENUM_ELEMENTS` feature only will result in the following code:
/// ```rust
#[doc = include_str!("../../tests/generator/box_flags/expected/enum_elements.rs")]
/// ```
const ENUM_ELEMENTS = 1 << 0;
/// Elements in a `xs:all` or `xs:sequence` type will always be boxed.
///
/// # Examples
///
/// Consider the following XML schema:
/// ```xml
#[doc = include_str!("../../tests/generator/box_flags/schema.xsd")]
/// ```
///
/// Enable the `STRUCT_ELEMENTS` feature only will result in the following code:
/// ```rust
#[doc = include_str!("../../tests/generator/box_flags/expected/struct_elements.rs")]
/// ```
const STRUCT_ELEMENTS = 1 << 1;
}
}
/// Tells the [`Generator`](super::Generator) what type should be generated for
/// the content of an XML element.
#[derive(Default, Debug, Clone, Copy, Eq, PartialEq)]
pub enum ContentMode {
/// The mode is selected depending on the type definition of the element.
/// `xs:choice` types will be rendered as enum, `xs:all` and `xs:sequence`
/// types will be rendered as struct.
///
/// # Examples
///
/// Consider the following XML schema:
/// ```xml
#[doc = include_str!("../../tests/generator/content_mode/schema.xsd")]
/// ```
///
/// If the content mode is set to [`ContentMode::Auto`] the following code is rendered:
/// ```rust
#[doc = include_str!("../../tests/generator/content_mode/expected/auto.rs")]
/// ```
#[default]
Auto,
/// The content of a XML element is always rendered as enum.
///
/// # Examples
///
/// Consider the following XML schema:
/// ```xml
#[doc = include_str!("../../tests/generator/content_mode/schema.xsd")]
/// ```
///
/// If the content mode is set to [`ContentMode::Enum`] the following code is rendered:
/// ```rust
#[doc = include_str!("../../tests/generator/content_mode/expected/enum.rs")]
/// ```
Enum,
/// The content of a XML element is always rendered as struct.
///
/// # Examples
///
/// Consider the following XML schema:
/// ```xml
#[doc = include_str!("../../tests/generator/content_mode/schema.xsd")]
/// ```
///
/// If the content mode is set to [`ContentMode::Struct`] the following code is rendered:
/// ```rust
#[doc = include_str!("../../tests/generator/content_mode/expected/struct.rs")]
/// ```
Struct,
}
/// Tells the [`Generator`](super::Generator) how to deal with type definitions.
#[derive(Default, Debug, Clone, Copy, Eq, PartialEq)]
pub enum TypedefMode {
/// The [`Generator`](super::Generator) will automatically detect if a
/// new type struct or a simple type definition should be used
/// for a [`Reference`](Type::Reference) type.
///
/// Detecting the correct type automatically depends basically on the
/// occurrence of the references type. If the target type is only referenced
/// exactly once, a type definition is rendered. If a different
/// occurrence is used, it is wrapped in a new type struct because usually
/// additional code needs to be implemented for such types.
///
/// # Examples
///
/// Consider the following XML schema:
/// ```xml
#[doc = include_str!("../../tests/generator/typedef_mode/schema.xsd")]
/// ```
///
/// If the typedef mode is set to [`TypedefMode::Auto`] the following code is rendered:
/// ```rust
#[doc = include_str!("../../tests/generator/typedef_mode/expected/auto.rs")]
/// ```
#[default]
Auto,
/// The [`Generator`](super::Generator) will always use a simple type definition
/// for a [`Reference`](Type::Reference) type.
///
/// # Examples
///
/// Consider the following XML schema:
/// ```xml
#[doc = include_str!("../../tests/generator/typedef_mode/schema.xsd")]
/// ```
///
/// If the typedef mode is set to [`TypedefMode::Typedef`] the following code is rendered:
/// ```rust
#[doc = include_str!("../../tests/generator/typedef_mode/expected/typedef.rs")]
/// ```
Typedef,
/// The [`Generator`](super::Generator) will always use a new type struct
/// for a [`Reference`](Type::Reference) type.
///
/// # Examples
///
/// Consider the following XML schema:
/// ```xml
#[doc = include_str!("../../tests/generator/typedef_mode/schema.xsd")]
/// ```
///
/// If the typedef mode is set to [`TypedefMode::NewType`] the following code is rendered:
/// ```rust
#[doc = include_str!("../../tests/generator/typedef_mode/expected/new_type.rs")]
/// ```
NewType,
}
/// Tells the [`Generator`](super::Generator) how to generate code for the
/// [`serde`] crate.
#[derive(Default, Debug, Clone, Copy, Eq, PartialEq)]
pub enum SerdeSupport {
/// No code for the [`serde`] crate is generated.
///
/// # Examples
///
/// Consider the following XML schema:
/// ```xml
#[doc = include_str!("../../tests/generator/serde_support/schema.xsd")]
/// ```
///
/// If the serde support mode is set to [`SerdeSupport::None`] the following code is rendered:
/// ```rust
#[doc = include_str!("../../tests/generator/serde_support/expected/none.rs")]
/// ```
#[default]
None,
/// Generates code that can be serialized and deserialized using the
/// [`serde`] create in combination with the with [`quick_xml`] crate.
///
/// # Examples
///
/// Consider the following XML schema:
/// ```xml
#[doc = include_str!("../../tests/generator/serde_support/schema.xsd")]
/// ```
///
/// If the serde support mode is set to [`SerdeSupport::QuickXml`] the following code is rendered:
/// ```rust
#[doc = include_str!("../../tests/generator/serde_support/expected/quick_xml.rs")]
/// ```
QuickXml,
/// Generates code that can be serialized and deserialized using the
/// [`serde`] create in combination with the with [`serde-xml-rs`](https://docs.rs/serde-xml-rs) crate.
///
/// # Examples
///
/// Consider the following XML schema:
/// ```xml
#[doc = include_str!("../../tests/generator/serde_support/schema.xsd")]
/// ```
///
/// If the serde support mode is set to [`SerdeSupport::SerdeXmlRs`] the following code is rendered:
/// ```rust
#[doc = include_str!("../../tests/generator/serde_support/expected/serde_xml_rs.rs")]
/// ```
SerdeXmlRs,
}
impl SerdeSupport {
/// Returns `true` if this is equal to [`SerdeSupport::None`], `false` otherwise.
#[must_use]
pub fn is_none(&self) -> bool {
matches!(self, Self::None)
}
}
/* Modules */
#[derive(Default, Debug)]
pub(super) struct Modules(pub BTreeMap<Option<NamespaceId>, Module>);
impl Modules {
pub(super) fn get_mut(&mut self, ns: Option<NamespaceId>) -> &mut Module {
self.0.entry(ns).or_default()
}
pub(super) fn add_code(&mut self, ns: Option<NamespaceId>, code: TokenStream) {
self.get_mut(ns).code.extend(code);
}
}
/* Module */
#[derive(Default, Debug)]
pub(super) struct Module {
pub code: TokenStream,
pub quick_xml_serialize: Option<TokenStream>,
pub quick_xml_deserialize: Option<TokenStream>,
}
/* PendingType */
#[derive(Debug)]
pub(super) struct PendingType<'types> {
pub ty: &'types Type,
pub ident: Ident,
}
/* TypeRef */
#[derive(Debug)]
pub(super) struct TypeRef {
pub ns: Option<NamespaceId>,
pub module_ident: Option<Ident2>,
pub type_ident: Ident2,
pub flags: StateFlags,
pub boxed_elements: HashSet<Ident>,
}
/* StateFlags */
bitflags! {
#[derive(Debug, Clone, Copy)]
pub(super) struct StateFlags: u32 {
const HAS_TYPE = 1 << 0;
const HAS_IMPL = 1 << 1;
const HAS_QUICK_XML_SERIALIZE = 1 << 2;
const HAS_QUICK_XML_DESERIALIZE = 1 << 3;
const HAS_QUICK_XML = Self::HAS_QUICK_XML_SERIALIZE.bits() | Self::HAS_QUICK_XML_DESERIALIZE.bits();
}
}
/* Occurs */
#[derive(Default, Debug, Clone, Copy, Eq, PartialEq)]
pub(super) enum Occurs {
#[default]
None,
Single,
Optional,
DynamicList,
StaticList(usize),
}
impl Occurs {
pub(super) fn from_occurs(min: MinOccurs, max: MaxOccurs) -> Self {
match (min, max) {
(0, MaxOccurs::Bounded(0)) => Self::None,
(1, MaxOccurs::Bounded(1)) => Self::Single,
(0, MaxOccurs::Bounded(1)) => Self::Optional,
(a, MaxOccurs::Bounded(b)) if a == b => Self::StaticList(a),
(_, _) => Self::DynamicList,
}
}
pub(super) fn make_type(
self,
ident: &TokenStream,
need_indirection: bool,
) -> Option<TokenStream> {
match self {
Self::None => None,
Self::Single if need_indirection => Some(quote! { Box<#ident> }),
Self::Single => Some(quote! { #ident }),
Self::Optional if need_indirection => Some(quote! { Option<Box<#ident>> }),
Self::Optional => Some(quote! { Option<#ident> }),
Self::DynamicList => Some(quote! { Vec<#ident> }),
Self::StaticList(sz) if need_indirection => Some(quote! { [Box<#ident>; #sz] }),
Self::StaticList(sz) => Some(quote! { [#ident; #sz] }),
}
}
pub(super) fn is_direct(&self) -> bool {
matches!(self, Self::Single | Self::Optional | Self::StaticList(_))
}
}
/* TypeMode */
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub(super) enum TypeMode {
All,
Choice,
Sequence,
}
/* Helper */
pub(super) fn format_field_name(name: &Name) -> Cow<'static, str> {
let ident = name
.to_type_named(false, None)
.as_str()
.unwrap()
.to_snake_case();
match KEYWORDS.binary_search_by(|(key, _)| key.cmp(&ident.as_str())) {
Ok(idx) => Cow::Borrowed(KEYWORDS[idx].1),
Err(_) => Cow::Owned(ident),
}
}
pub(super) fn format_field_ident(name: &Name) -> Ident2 {
let ident = format_field_name(name);
format_ident!("{ident}")
}
pub(super) fn format_module_ident(name: &Name) -> Ident2 {
format_field_ident(name)
}
pub(super) fn format_type_name(name: &Name) -> String {
name.to_type_named(false, None)
.as_str()
.unwrap()
.to_pascal_case()
}
pub(super) fn format_type_ident(name: &Name) -> Ident2 {
let ident = format_type_name(name);
format_ident!("{ident}")
}
pub(super) fn format_variant_ident(name: &Name) -> Ident2 {
format_type_ident(name)
}
pub(super) fn format_module(
types: &Types,
ns: Option<NamespaceId>,
) -> Result<Option<Ident2>, Error> {
let Some(ns) = ns else {
return Ok(None);
};
let module = types.modules.get(&ns).ok_or(Error::UnknownNamespace(ns))?;
Ok(Some(format_module_ident(&module.name)))
}
pub(super) fn format_type_ref(current_ns: Option<NamespaceId>, type_: &TypeRef) -> TokenStream {
format_type_ref_ex(current_ns, None, type_)
}
pub(super) fn format_type_ref_ex(
current_ns: Option<NamespaceId>,
extra: Option<&TokenStream>,
type_: &TypeRef,
) -> TokenStream {
let type_ident = &type_.type_ident;
let module_ident = match (current_ns, type_.ns) {
(Some(a), Some(b)) if a != b => Some(&type_.module_ident),
(_, _) => None,
};
if let Some(module_ident) = module_ident {
quote! {
#module_ident #extra :: #type_ident
}
} else {
quote! {
#type_ident
}
}
}
pub(super) fn make_type_name(postfixes: &[String], ty: &Type, ident: &Ident) -> Name {
match (ty, &ident.name) {
(Type::Reference(ti), Name::Unnamed { .. }) if ti.type_.name.is_named() => {
match Occurs::from_occurs(ti.min_occurs, ti.max_occurs) {
Occurs::DynamicList => return Name::new(format!("{}List", ti.type_.name)),
Occurs::Optional => return Name::new(format!("{}Opt", ti.type_.name)),
_ => (),
}
}
(_, _) => (),
};
let postfix = postfixes
.get(ident.type_ as usize)
.map_or("", |s| s.as_str());
match &ident.name {
Name::Named(s) if s.ends_with(postfix) => Name::Named(s.clone()),
Name::Named(s) => Name::Named(Cow::Owned(format!("{s}{postfix}"))),
name => name.to_type_named(false, None),
}
}
const KEYWORDS: &[(&str, &str)] = &[
("abstract", "abstract_"),
("as", "as_"),
("become", "become_"),
("box", "box_"),
("break", "break_"),
("const", "const_"),
("continue", "continue_"),
("crate", "crate_"),
("do", "do_"),
("else", "else_"),
("enum", "enum_"),
("extern", "extern_"),
("false", "false_"),
("final", "final_"),
("fn", "fn_"),
("for", "for_"),
("if", "if_"),
("impl", "impl_"),
("in", "in_"),
("let", "let_"),
("loop", "loop_"),
("macro", "macro_"),
("match", "match_"),
("mod", "mod_"),
("move", "move_"),
("mut", "mut_"),
("override", "override_"),
("priv", "priv_"),
("pub", "pub_"),
("ref", "ref_"),
("return", "return_"),
("self", "self_"),
("Self", "Self_"),
("static", "static_"),
("struct", "struct_"),
("super", "super_"),
("trait", "trait_"),
("true", "true_"),
("try", "try_"),
("type", "type_"),
("typeof", "typeof_"),
("union", "union_"),
("unsafe", "unsafe_"),
("unsized", "unsized_"),
("use", "use_"),
("virtual", "virtual_"),
("where", "where_"),
("while", "while_"),
("yield", "yield_"),
];