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
//! # j1939-macros
//!
//! Procedural macros for the j1939-rs library.
//!
//! ## Note on `std` Usage
//!
//! This crate uses the standard library (`std`) and does **not** have `#![no_std]`.
//! This is intentional and correct:
//!
//! - **Proc macros run at compile time** on the developer's machine, not on the embedded target
//! - The Rust compiler **requires** proc macro crates to use `std`
//! - Dynamic allocations (Vec, String, HashMap) are used during code generation
//! - This code **never runs** on the embedded system
//!
//! The **generated code** from these macros is fully `no_std` compatible and runs on embedded
//! targets without heap allocation. See the `j1939-rs` crate documentation for details on
//! embedded system support.
use TokenStream;
use quote;
use ;
// Internal modules for macro implementation
use *;
use *;
use *;
/// Attribute macro for defining J1939 message structures with automatic marshalling/unmarshalling.
///
/// This macro transforms a struct definition into a complete J1939 message with serialization
/// and deserialization capabilities. It generates implementations of the `Marshall` and `Unmarshall`
/// traits, as well as associated constants for message metadata.
///
/// # Parameters
///
/// - `pgn`: (required) Parameter Group Number - A unique identifier for the message (0-262143)
/// - `priority`: (optional) Message priority (0-7, where 0 is highest). Default: 6
/// - `length`: (optional) Message length in bits. Default: 64 bits (8 bytes)
///
/// # Field Attributes
///
/// Each field must have a `#[j1939(...)]` attribute with the following parameters:
///
/// - `bits = start..end`: (required) Bit range for this field within the message
/// - `scale = f32`: (optional) Scaling factor for float conversion. Use with `f32` fields
/// - `offset = f32`: (optional) Offset applied to scaled values. Default: 0.0
/// - Formula: `raw = (value - offset) / scale`
/// - `encoding = "type"`: (optional) Special encoding type (e.g., "q9" for fixed-point)
/// - `unit = "string"`: (optional) Physical unit for documentation (e.g., "km/h", "°C")
/// - `reserved`: (optional flag) Marks bits as reserved/unused
///
/// ## Encoding Strategies
///
/// The encoding strategy is automatically determined based on field type and attributes:
///
/// | Field Type | Attributes | Encoding | Description |
/// |------------|-----------|----------|-------------|
/// | `u8`, `u16`, `u32` | - | UInt | Direct unsigned integer |
/// | `i8`, `i16`, `i32` | - | SInt | Signed integer with sign extension |
/// | `f32` | `scale`, `offset?` | Scaled | Linear transformation: `(raw * scale) + offset` |
/// | `f32` | `encoding = "q9"` | Q9 | Fixed-point format (10 bits: 1 sign + 9 fractional) |
/// | Custom enum | - | Enum | Type-safe enum (requires `#[repr(u8)]` and `#[j1939_enum]`) |
/// | `()` | `reserved` | Reserved | Unused bits set to zero |
///
/// ### Offset Behavior
///
/// When using `scale` with `offset`:
/// - `offset != 0.0`: Raw values treated as **unsigned** (common for temperatures, percentages)
/// - `offset == 0.0` (default): Sign extension applied for **signed** values
///
/// # Generated Items
///
/// The macro generates:
/// - Constants: `PGN`, `PRIORITY`, `LENGTH`
/// - `Marshall` trait implementation for encoding
/// - `Unmarshall` trait implementation for decoding
/// - Comprehensive documentation table with field layout
///
/// # Examples
///
/// ## Basic Message with Scaled Values
///
/// ```ignore
/// use j1939_rs::prelude::*;
///
/// #[j1939_message(pgn = 61444, priority = 3, length = 64)]
/// pub struct EngineSpeed {
/// /// Engine RPM
/// #[j1939(bits = 0..16, scale = 0.125, unit = "rpm")]
/// pub engine_speed: f32,
///
/// /// Coolant temperature with offset
/// #[j1939(bits = 16..24, scale = 1.0, offset = -40.0, unit = "°C")]
/// pub coolant_temp: f32,
///
/// /// Reserved bits
/// #[j1939(bits = 24..64, reserved)]
/// pub reserved: (),
/// }
///
/// // Usage
/// let msg = EngineSpeed {
/// engine_speed: 1850.0,
/// coolant_temp: 85.0,
/// reserved: (),
/// };
///
/// let mut j1939_msg = J1939Message::default();
/// msg.marshall(&mut j1939_msg).unwrap();
///
/// let decoded = EngineSpeed::unmarshall(&j1939_msg).unwrap();
/// assert_eq!(decoded.engine_speed, 1850.0);
/// ```
///
/// ## Message with Enums
///
/// ```ignore
/// use j1939_rs::prelude::*;
///
/// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// #[repr(u8)]
/// #[j1939_enum]
/// pub enum GearPosition {
/// Park = 0,
/// Reverse = 1,
/// Neutral = 2,
/// Drive = 3,
/// }
///
/// #[j1939_message(pgn = 12345, priority = 6)]
/// pub struct TransmissionStatus {
/// #[j1939(bits = 0..2)]
/// pub gear: GearPosition,
///
/// #[j1939(bits = 2..18, scale = 0.1, unit = "km/h")]
/// pub speed: f32,
///
/// #[j1939(bits = 18..64, reserved)]
/// pub reserved: (),
/// }
/// ```
///
/// ## Message with Q9 Fixed-Point Encoding
///
/// ```ignore
/// use j1939_rs::prelude::*;
///
/// #[j1939_message(pgn = 65400)]
/// pub struct ControlData {
/// /// High-precision control value using Q9 fixed-point
/// #[j1939(bits = 0..10, encoding = "q9")]
/// pub control_value: f32,
///
/// #[j1939(bits = 10..64, reserved)]
/// pub reserved: (),
/// }
/// ```
///
/// # Notes
///
/// - All bit ranges must be non-overlapping and within the message length
/// - Float fields require either `scale` or `encoding` attribute
/// - When `offset` is non-zero, raw values are treated as unsigned
/// - When `offset` is zero (default), sign extension is applied for negative values
/// - Reserved bits are automatically set to zero during marshalling
/// - Encoding types are inferred automatically from field types and attributes
///
/// # See Also
///
/// - [`j1939_enum`] - Attribute macro for registering enums used in messages
/// Attribute macro for registering enums used in J1939 messages.
///
/// This macro registers enum information for automatic documentation generation. When an enum
/// marked with `#[j1939_enum]` is used as a field type in a message, the generated documentation
/// will include a comprehensive table showing all enum variants, their values, and descriptions.
///
/// # Requirements
///
/// - The enum must have `#[repr(u8)]` to ensure proper memory layout
/// - Variants can have explicit discriminant values or use implicit incrementing values
/// - Each variant can have doc comments which will appear in the generated documentation
///
/// # Benefits
///
/// - Automatic documentation table generation for enum fields in J1939 messages
/// - Variant values shown in both decimal and binary format
/// - Integration with the message field layout documentation
/// - Type-safe enum encoding/decoding
///
/// # Examples
///
/// ## Basic Enum Registration
///
/// ```ignore
/// use j1939_rs::prelude::*;
///
/// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// #[repr(u8)]
/// #[j1939_enum]
/// /// Engine operating mode
/// pub enum EngineMode {
/// /// Engine is stopped
/// Stopped = 0,
/// /// Engine is starting
/// Starting = 1,
/// /// Engine running normally
/// Running = 2,
/// /// Engine has critical fault
/// Fault = 7,
/// }
/// ```
///
/// ## Enum with Implicit Values
///
/// ```ignore
/// use j1939_rs::prelude::*;
///
/// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// #[repr(u8)]
/// #[j1939_enum]
/// /// Gear selection
/// pub enum GearPosition {
/// /// Park - vehicle locked
/// Park, // = 0
/// /// Reverse gear
/// Reverse, // = 1
/// /// Neutral - no gear engaged
/// Neutral, // = 2
/// /// Drive mode
/// Drive, // = 3
/// /// Low gear for climbing
/// Low, // = 4
/// }
/// ```
///
/// ## Using Enums in Messages
///
/// ```ignore
/// use j1939_rs::prelude::*;
///
/// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// #[repr(u8)]
/// #[j1939_enum]
/// pub enum TorqueMode {
/// LowIdle = 0,
/// AcceleratorControl = 1,
/// CruiseControl = 2,
/// }
///
/// #[j1939_message(pgn = 61444, priority = 3)]
/// pub struct EngineController {
/// /// Current torque control mode
/// #[j1939(bits = 0..4)]
/// pub torque_mode: TorqueMode,
///
/// #[j1939(bits = 4..20, scale = 0.125, unit = "rpm")]
/// pub engine_speed: f32,
///
/// #[j1939(bits = 20..64, reserved)]
/// pub reserved: (),
/// }
/// ```
///
/// # Notes
///
/// - The macro preserves the original enum definition unchanged
/// - Enum information is stored in a compile-time registry for documentation generation
/// - Enums are transmitted as their underlying `u8` representation
/// - Use `#[repr(u8)]` to ensure consistent memory layout across platforms