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
//! ASN.1 schema parser and Rust code generator
//!
//! This library parses ASN.1 module definitions and generates Rust code
//! using the `synta` library's derive macros.
//!
//! # Quick start
//!
//! ```no_run
//! use synta_codegen::{parse, generate};
//!
//! let schema = r#"
//! Certificate DEFINITIONS ::= BEGIN
//! Certificate ::= SEQUENCE {
//! version INTEGER,
//! serialNumber INTEGER
//! }
//! END
//! "#;
//!
//! let module = parse(schema).unwrap();
//! let rust_code = generate(&module).unwrap();
//! println!("{}", rust_code);
//! ```
//!
//! # Configuration
//!
//! [`generate_with_config`] accepts a [`CodeGenConfig`] that controls several
//! aspects of the emitted code.
//!
//! ## Owned vs. borrowed string types
//!
//! By default all ASN.1 string and binary types (`OCTET STRING`, `BIT STRING`,
//! `UTF8String`, `PrintableString`, `IA5String`) are generated as **owned**
//! heap-allocating types (`OctetString`, `BitString`, …). This is convenient
//! when constructing structs programmatically.
//!
//! For parse-only workloads (e.g. X.509 certificate inspection) you can switch
//! to **zero-copy borrowed** types (`OctetStringRef<'a>`, `BitStringRef<'a>`,
//! …) that borrow directly from the input buffer. Structs that contain these
//! fields automatically gain a `'a` lifetime parameter.
//!
//! ```no_run
//! use synta_codegen::{parse, generate_with_config, CodeGenConfig, StringTypeMode};
//!
//! let schema = r#"
//! Msg DEFINITIONS ::= BEGIN
//! Msg ::= SEQUENCE {
//! payload OCTET STRING,
//! label UTF8String
//! }
//! END
//! "#;
//!
//! let module = parse(schema).unwrap();
//! let config = CodeGenConfig {
//! string_type_mode: StringTypeMode::Borrowed,
//! ..Default::default()
//! };
//! // Emits:
//! // pub struct Msg<'a> {
//! // pub payload: OctetStringRef<'a>,
//! // pub label: Utf8StringRef<'a>,
//! // }
//! let rust_code = generate_with_config(&module, config).unwrap();
//! println!("{}", rust_code);
//! ```
//!
//! String types that have no zero-copy variant (`TeletexString`, `BmpString`,
//! `UniversalString`, `GeneralString`, `NumericString`, `VisibleString`) are
//! always emitted as owned types regardless of [`StringTypeMode`].
//!
//! Named bit strings (`BIT STRING { flag(0), … }`) are always emitted as
//! owned `BitString` because they are decoded into a concrete bit-field type.
//!
//! ## Derive macro gating
//!
//! By default every `Asn1Sequence` / `Asn1Set` / `Asn1Choice` derive and its
//! associated `asn1(…)` helper attributes are wrapped in
//! `#[cfg_attr(feature = "derive", …)]`. This lets the consuming crate make
//! `synta-derive` an **optional** dependency controlled by a Cargo feature:
//!
//! ```toml
//! # Cargo.toml of the consuming crate (default behaviour)
//! [dependencies]
//! synta-derive = { version = "0.1", optional = true }
//!
//! [features]
//! derive = ["dep:synta-derive"]
//! ```
//!
//! Third-party crates that **always** depend on `synta-derive` and do not want
//! to expose a `derive` Cargo feature can use [`DeriveMode::Always`]:
//!
//! ```no_run
//! use synta_codegen::{parse, generate_with_config, CodeGenConfig, DeriveMode};
//!
//! let schema = r#"
//! Msg DEFINITIONS ::= BEGIN
//! Msg ::= SEQUENCE { id INTEGER }
//! END
//! "#;
//!
//! let module = parse(schema).unwrap();
//! let config = CodeGenConfig {
//! derive_mode: DeriveMode::Always,
//! ..Default::default()
//! };
//! // Emits:
//! // #[derive(Debug, Clone, PartialEq)]
//! // #[derive(Asn1Sequence)] ← no cfg_attr wrapper
//! // pub struct Msg { pub id: Integer }
//! let rust_code = generate_with_config(&module, config).unwrap();
//! println!("{}", rust_code);
//! ```
//!
//! If the crate uses a feature name other than `"derive"`, pass it via
//! [`DeriveMode::Custom`]:
//!
//! ```no_run
//! use synta_codegen::{parse, generate_with_config, CodeGenConfig, DeriveMode};
//!
//! # let schema = "Msg DEFINITIONS ::= BEGIN Msg ::= SEQUENCE { id INTEGER } END";
//! # let module = parse(schema).unwrap();
//! let config = CodeGenConfig {
//! derive_mode: DeriveMode::Custom("asn1-derive".to_string()),
//! ..Default::default()
//! };
//! // Emits:
//! // #[cfg_attr(feature = "asn1-derive", derive(Asn1Sequence))]
//! let rust_code = generate_with_config(&module, config).unwrap();
//! println!("{}", rust_code);
//! ```
//!
//! ## Import path prefix
//!
//! Use [`CodeGenConfig::with_crate_imports`], [`CodeGenConfig::with_super_imports`],
//! or [`CodeGenConfig::with_custom_prefix`] to emit `use` statements instead of
//! the default comment-only import annotations.
//!
//! ## Constrained INTEGER type selection
//!
//! When a top-level `INTEGER` type carries a value-range constraint (e.g.
//! `INTEGER (0..100)`), synta-codegen generates a newtype whose inner field is
//! the **smallest native Rust integer primitive** that covers the declared range,
//! rather than the arbitrary-precision `Integer` type:
//!
//! - Lower bound ≥ 0 → unsigned: `u8` (≤255), `u16` (≤65535), `u32` (≤4294967295), `u64`.
//! - Lower bound < 0 → signed: `i8`, `i16`, `i32`, `i64`.
//! - Unconstrained bounds (`MIN`/`MAX`, named values) → `i64`.
//!
//! Using a primitive type means the generated struct automatically derives
//! `Copy`, `PartialOrd`, and `Ord`, and avoids heap allocation. For example,
//! `Percentage ::= INTEGER (0..100)` produces:
//!
//! ```text
//! #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
//! pub struct Percentage(u8);
//!
//! impl Percentage {
//! pub fn new(value: u8) -> Result<Self, &'static str> { ... }
//! pub const fn new_unchecked(value: u8) -> Self { Percentage(value) }
//! pub const fn get(&self) -> u8 { self.0 }
//! pub fn into_inner(self) -> u8 { self.0 }
//! }
//! ```
//!
//! The equivalent C generation uses `uint8_t` / `uint16_t` / `uint32_t` /
//! `uint64_t` for non-negative ranges and `int8_t` / `int16_t` / `int32_t` /
//! `int64_t` for signed ranges.
pub use ;
pub use c_cmake_codegen::;
pub use c_codegen::;
pub use c_impl_codegen::;
pub use c_meson_codegen::;
pub use ;
pub use ;
pub use module_file_stem;
pub use ;
/// Locate the `asn1/` schema directory containing the ASN.1 schemas.
///
/// Call this from a build script (`build.rs`) to obtain the path to the shared
/// ASN.1 schema files that ship with the `synta` package. Three layouts are
/// checked in order:
///
/// 1. **Crate-local** — `<CARGO_MANIFEST_DIR>/asn1/` exists inside the calling
/// crate itself. Handles self-contained crates that bundle their own schemas.
///
/// 2. **Workspace build** — the calling crate sits one level below the
/// workspace root where `asn1/` lives. `../asn1` relative to
/// `CARGO_MANIFEST_DIR` is returned.
///
/// 3. **crates.io / registry build** — falls back to `cargo metadata` to find
/// the source location of the `synta` package and returns its `asn1/`
/// subdirectory. The `synta` package is identified by its manifest
/// directory name: `"synta"` (workspace root) or `"synta-X.Y.Z"` (crates.io
/// registry entry, recognised by `"synta-"` followed by an ASCII digit).
///
/// # Panics
///
/// Panics if none of the three layouts yields a valid `asn1/` directory.
/// Use `cargo metadata` to find the `asn1/` directory inside the `synta`
/// package source tree.
///
/// Scans every `manifest_path` value in the metadata JSON and identifies the
/// `synta` package by the name of its containing directory: `"synta"` (when
/// the workspace root happens to be in a directory named `synta`) or
/// `"synta-X.Y.Z"` (the standard crates.io registry layout).
/// Parse ASN.1 schema and generate Rust code in one step
/// Parse ASN.1 schema and generate C header in one step
/// Parse ASN.1 schema and generate C implementation in one step