6666# TODO Check strings for Unicode standard for `XID_Start` and `XID_Continue`
6767# @functools.cache
6868def rust_sanitize_field_ident (value : str ) -> str :
69- """
70- Checks whether the field name is a Rust reserved world, or escapes it.
71- """
72- # value = functools.reduce(lambda s, r: re.sub(*r, s), __FIELD_NAME_REX_DICT, value)
73- # value = value.lower()
69+ """Check whether the field name is a Rust reserved world, or escape it."""
7470 if value in __RUST_RESERVED_WORDS :
7571 return f"r#{ value } "
7672 return value
@@ -79,18 +75,15 @@ def rust_sanitize_field_ident(value: str) -> str:
7975# TODO Check strings for Unicode standard for `XID_Start` and `XID_Continue`
8076@functools .cache
8177def rust_sanitize_type_ident (value : str ) -> str :
82- """
83- Converts an input string into a valid Rust type name (PascalCase).
78+ """Convert an input string into a valid Rust type name (PascalCase).
79+
8480 Results are cached for performance optimization.
8581 """
8682 return functools .reduce (lambda s , r : re .sub (r [0 ], r [1 ], s ), __TYPE_NAME_REX_DICT , value )
8783
8884
8985def rust_sanitize_doc_iter (value : Union [Sequence [str ], str ]) -> Iterator [str ]:
90- """
91- Sanitizes Markdown doc-strings by splitting lines and wrapping non-hyperlinked
92- URLs in angle brackets.
93- """
86+ """Sanitize Markdown doc-strings by splitting lines and wrapping non-hyperlinked URLs in angle brackets."""
9487 return map (
9588 lambda v : re .sub (__MD_NON_HYPERLINK_REX , lambda m : f"<{ str (m .group ())} >" , v ),
9689 itertools .chain .from_iterable (map ( # flat_map
@@ -102,8 +95,8 @@ def rust_sanitize_doc_iter(value: Union[Sequence[str], str]) -> Iterator[str]:
10295
10396@functools .cache
10497def to_rust_literal (value : Any ) -> str :
105- """
106- Convert Python values to their equivalent Rust literal representation.
98+ """Convert Python values to their equivalent Rust literal representation.
99+
107100 Results are cached for performance optimization.
108101 """
109102 if isinstance (value , bool ):
@@ -123,10 +116,7 @@ def to_rust_literal(value: Any) -> str:
123116
124117
125118def make_avro (items : MutableSequence [JsonDataType ]) -> MutableSequence [NamedSchema ]:
126- """
127- Processes a list of dictionaries to generate a list of Avro schemas.
128- """
129-
119+ """Process a list of dictionaries to generate a list of Avro schemas."""
130120 # Same as `from .utils import convert_to_dict`, which, however, is not public
131121 def convert_to_dict (j4 : Any ) -> Any :
132122 """Convert generic Mapping objects to dicts recursively."""
@@ -162,9 +152,7 @@ def convert_to_dict(j4: Any) -> Any:
162152
163153@dataclass # ASSERT: Immutable class
164154class RustLifetime :
165- """
166- Represents a Rust lifetime parameter (e.g., `'a`).
167- """
155+ """Represents a Rust lifetime parameter (e.g., `'a`)."""
168156
169157 ident : RustIdent
170158
@@ -176,26 +164,20 @@ def __str__(self) -> str:
176164
177165
178166class RustType (ABC ):
179- """
180- Abstract class for Rust types.
181- """
167+ """Abstract class for Rust types."""
182168
183169 pass
184170
185171
186172class RustMeta (ABC ):
187- """
188- Abstract class for Rust attribute metas.
189- """
173+ """Abstract class for Rust attribute metas."""
190174
191175 pass
192176
193177
194178@dataclass (unsafe_hash = True ) # ASSERT: Immutable class
195179class RustAttribute :
196- """
197- Represents a Rust attribute (e.g., `#[derive(Debug)]`).
198- """
180+ """Represents a Rust attribute (e.g., `#[derive(Debug)]`)."""
199181
200182 meta : RustMeta
201183
@@ -213,9 +195,7 @@ def __str__(self) -> str:
213195
214196@dataclass (unsafe_hash = True ) # ASSERT: Immutable class
215197class RustPathSegment :
216- """
217- Represents a segment in a Rust path with optional generics.
218- """
198+ """Represents a segment in a Rust path with optional generics."""
219199
220200 ident : RustIdent
221201 generics : RustGenerics = dataclasses .field (default_factory = tuple )
@@ -232,8 +212,8 @@ def __str__(self) -> str:
232212 @classmethod
233213 @functools .cache
234214 def from_str (cls , value : str ) -> "RustPathSegment" :
235- """
236- Parses a string into RustPathSegment class.
215+ """Parse a string into RustPathSegment class.
216+
237217 Results are cached for performance optimization.
238218 """
239219
@@ -276,9 +256,7 @@ def parse_generics_string(value_generics: str) -> RustGenerics:
276256
277257@dataclass (unsafe_hash = True ) # ASSERT: Immutable class
278258class RustPath (RustMeta ):
279- """
280- Represents a complete Rust path (e.g., `::std::vec::Vec<T>`).
281- """
259+ """Represents a complete Rust path (e.g., `::std::vec::Vec<T>`)."""
282260
283261 # ASSERT: Never initialized with an empty sequence
284262 segments : RustPathSegments
@@ -309,8 +287,8 @@ def __str__(self) -> str:
309287 @classmethod
310288 @functools .cache
311289 def from_str (cls , value : str ) -> "RustPath" :
312- """
313- Parses a string into RustPath class.
290+ """Parse a string into RustPath class.
291+
314292 Results are cached for performance optimization.
315293 """
316294 norm_value , leading_colon = (value [2 :], True ) if value .startswith ("::" ) else (value , False )
@@ -323,21 +301,10 @@ def from_str(cls, value: str) -> "RustPath":
323301 raise ValueError (f"Poorly formatted Rust path: '{ value } '" )
324302 return cls (segments = tuple (segments ), leading_colon = leading_colon )
325303
326- # def parent(self) -> "RustPath":
327- # """
328- # Returns a new RustPath containing all but the last segment.
329- # """
330- # return RustPath(
331- # segments=self.segments[:-1],
332- # leading_colon=self.leading_colon,
333- # )
334-
335304
336305@dataclass (unsafe_hash = True ) # ASSERT: Immutable class
337306class RustTypeTuple (RustType ):
338- """
339- Represents a Rust tuple type (e.g., `(T, U)`).
340- """
307+ """Represents a Rust tuple type (e.g., `(T, U)`)."""
341308
342309 # ASSERT: Never initialized with an empty sequence
343310 types : Sequence [RustPath ]
@@ -349,9 +316,7 @@ def __str__(self) -> str:
349316
350317@dataclass # ASSERT: Immutable class
351318class RustMetaList (RustMeta ):
352- """
353- Represents attribute meta list information (e.g., `derive(Debug, Clone)`)
354- """
319+ """Represents attribute meta list information (e.g., `derive(Debug, Clone)`).."""
355320
356321 path : RustPath
357322 metas : Sequence [RustMeta ] = tuple ()
@@ -366,9 +331,7 @@ def __str__(self) -> str:
366331
367332@dataclass # ASSERT: Immutable class
368333class RustMetaNameValue (RustMeta ):
369- """
370- Represents attribute meta name-value information (e.g., `key = value`)
371- """
334+ """Represents attribute meta name-value information (e.g., `key = value`)."""
372335
373336 path : RustPath
374337 value : Any = True
@@ -387,9 +350,7 @@ def __str__(self) -> str:
387350
388351@dataclass
389352class RustNamedType (ABC ): # ABC class
390- """
391- Abstract class for Rust struct and enum types.
392- """
353+ """Abstract class for Rust struct and enum types."""
393354
394355 ident : RustIdent
395356 attrs : RustAttributes = dataclasses .field (default_factory = list )
@@ -410,9 +371,7 @@ def __str__(self) -> str:
410371
411372@dataclass # ASSERT: Immutable class
412373class RustField :
413- """
414- Represents a field in a Rust struct.
415- """
374+ """Represents a field in a Rust struct."""
416375
417376 ident : RustIdent
418377 type : RustPath
@@ -435,9 +394,7 @@ def write_to(self, writer: IO[str], depth: int = 0) -> None:
435394
436395@dataclass
437396class RustStruct (RustNamedType ):
438- """
439- Represents a Rust struct definition.
440- """
397+ """Represents a Rust struct definition."""
441398
442399 fields : Optional [RustFields ] = None
443400
@@ -462,9 +419,7 @@ def write_to(self, writer: IO[str], depth: int = 0) -> None:
462419
463420@dataclass # ASSERT: Immutable class
464421class RustVariant :
465- """
466- Represents a variant in a Rust enum.
467- """
422+ """Represents a variant in a Rust enum."""
468423
469424 ident : RustIdent
470425 tuple : Optional [RustTypeTuple ] = None
@@ -507,9 +462,7 @@ def from_path(cls, path: RustPath) -> "RustVariant":
507462
508463@dataclass
509464class RustEnum (RustNamedType ):
510- """
511- Represents a Rust enum definition.
512- """
465+ """Represents a Rust enum definition."""
513466
514467 variants : RustVariants = dataclasses .field (default_factory = tuple )
515468
@@ -528,9 +481,7 @@ def write_to(self, writer: IO[str], depth: int = 0) -> None:
528481
529482# Wrapper for the RustNamedType `write_to()` method call
530483def salad_macro_write_to (ty : RustNamedType , writer : IO [str ], depth : int = 0 ) -> None :
531- """
532- Writes a RustNamedType wrapping it in the Schema Salad macro
533- """
484+ """Write a RustNamedType wrapping it in the Schema Salad macro."""
534485 indent = " " * depth
535486 writer .write (indent + "salad_core::define_type! {\n " )
536487 ty .write_to (writer , 1 )
@@ -544,9 +495,7 @@ def salad_macro_write_to(ty: RustNamedType, writer: IO[str], depth: int = 0) ->
544495
545496@dataclass
546497class RustModuleTree :
547- """
548- Represents a Rust module with submodules and named types
549- """
498+ """Represents a Rust module with submodules and named types."""
550499
551500 ident : RustIdent # ASSERT: Immutable field
552501 parent : Optional ["RustModuleTree" ] # ASSERT: Immutable field
@@ -559,9 +508,7 @@ def __hash__(self) -> int:
559508 return hash ((self .ident , self .parent ))
560509
561510 def get_rust_path (self ) -> RustPath :
562- """
563- Returns the complete Rust path from root to this module.
564- """
511+ """Return the complete Rust path from root to this module."""
565512 segments : list [RustPathSegment ] = []
566513 current : Optional ["RustModuleTree" ] = self
567514
@@ -571,9 +518,7 @@ def get_rust_path(self) -> RustPath:
571518 return RustPath (segments = tuple (reversed (segments )))
572519
573520 def add_submodule (self , path : Union [RustPath , str ]) -> "RustModuleTree" :
574- """
575- Creates a new submodule or returns an existing one with the given path.
576- """
521+ """Create a new submodule or returns an existing one with the given path."""
577522 if isinstance (path , str ):
578523 path = RustPath .from_str (path )
579524 segments = iter (path .segments )
@@ -598,25 +543,10 @@ def add_submodule(self, path: Union[RustPath, str]) -> "RustModuleTree":
598543 )
599544 return current
600545
601- # def get_submodule(self, path: Union[RustPath, str]) -> Optional["RustModuleTree"]:
602- # """
603- # Returns a submodule from this module tree by its Rust path, if any.
604- # """
605- # if isinstance(path, str):
606- # path = RustPath.from_str(path)
607- # current, last_segment_idx = self, len(path.segments) - 1
608- # for idx, segment in enumerate(path.segments):
609- # if (idx == last_segment_idx) and (current.ident == segment.ident):
610- # return current
611- # current = current.submodules.get(segment.ident)
612- # if not current:
613- # return None
614- # return None
615-
616546 def add_named_type (self , ty : RustNamedType ) -> RustPath :
617- """
618- Adds a named type to this module tree and returns its complete Rust path.
619- Raises `ValueError` if type with same name already exists
547+ """Add a named type to this module tree and returns its complete Rust path.
548+
549+ Raises `ValueError` if type with same name already exists.
620550 """
621551 module_rust_path = self .get_rust_path ()
622552 if ty .ident in self .named_types :
@@ -630,9 +560,7 @@ def add_named_type(self, ty: RustNamedType) -> RustPath:
630560 # return None
631561
632562 def write_to_fs (self , base_path : Path ) -> None :
633- """
634- Writes the module tree to the filesystem under the given base path.
635- """
563+ """Write the module tree to the filesystem under the given base path."""
636564
637565 def write_module_file (module : "RustModuleTree" , path : Path , mode : str = "wt" ) -> None :
638566 with open (path , mode = mode ) as module_rs :
@@ -715,9 +643,7 @@ def rust_type_list(rust_ty: RustPath) -> RustPath:
715643
716644
717645class RustCodeGen (CodeGenBase ):
718- """
719- Rust code generator for schema salad definitions.
720- """
646+ """Rust code generator for schema salad definitions."""
721647
722648 # Static
723649 CRATE_VERSION : ClassVar [str ] = "0.1.0" # Version of the generated crate
@@ -738,6 +664,7 @@ def __init__(
738664 salad_version : str ,
739665 target : Optional [str ] = None ,
740666 ) -> None :
667+ """Initialize the RustCodeGen class."""
741668 self .package = package
742669 self .package_version = self .__generate_crate_version (salad_version )
743670 self .output_dir = Path (target or "." ).resolve ()
@@ -1120,9 +1047,7 @@ def __get_submodule_path(self, schema: NamedSchema) -> RustPath:
11201047 return RustPath (segments = segments )
11211048
11221049 def __init_output_directory (self ) -> None :
1123- """
1124- Initialize the output directory structure.
1125- """
1050+ """Initialize the output directory structure."""
11261051 if self .output_dir .is_file ():
11271052 raise ValueError (f"Output directory cannot be a file: { self .output_dir } " )
11281053 if not self .output_dir .exists ():
0 commit comments