xacro-rs 0.2.2

A xml preprocessor for xacro files to generate URDF files
Documentation
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
//! Substitution engine for expressions and extensions
//!
//! Implements iterative substitution of ${...} expressions and $(...) extensions
//! with proper handling of nested cases, recursive evaluation, and depth limits.

use super::{truncate_snippet, EvalContext};
use crate::error::XacroError;
use crate::eval::interpreter::{build_pyisheval_context, eval_boolean, init_interpreter};
use crate::eval::lexer::{Lexer, TokenType};
use crate::extensions::extension_utils;
use core::cell::RefCell;
use std::collections::HashMap;

impl<const MAX_SUBSTITUTION_DEPTH: usize> EvalContext<MAX_SUBSTITUTION_DEPTH> {
    /// Generic iterative substitution helper
    ///
    /// Applies a processing function iteratively until no more substitutions are possible
    /// or the maximum depth is reached. This eliminates code duplication across multiple
    /// substitution methods.
    ///
    /// # Arguments
    /// * `text` - Input text to process
    /// * `should_continue` - Predicate to check if processing should continue
    /// * `process_fn` - Function to apply one processing pass
    ///
    /// # Returns
    /// Fully processed text
    fn substitute_iteratively<F, P>(
        &self,
        text: &str,
        should_continue: F,
        process_fn: P,
    ) -> Result<String, XacroError>
    where
        F: Fn(&str) -> bool,
        P: Fn(&str) -> Result<String, XacroError>,
    {
        let mut result = text.to_string();
        let mut iteration = 0;

        while should_continue(&result) && iteration < MAX_SUBSTITUTION_DEPTH {
            let next = process_fn(&result)?;

            // Short-circuit: if result didn't change, we're done
            if next == result {
                break;
            }

            result = next;
            iteration += 1;
        }

        // Check if we hit the depth limit with remaining substitutions
        if iteration >= MAX_SUBSTITUTION_DEPTH && should_continue(&result) {
            return Err(XacroError::MaxSubstitutionDepth {
                depth: MAX_SUBSTITUTION_DEPTH,
                snippet: truncate_snippet(&result),
            });
        }

        Ok(result)
    }

    /// Perform one pass of substitution with metadata-aware formatting and location context
    ///
    /// Sets current_location briefly during evaluation for print_location() support.
    ///
    /// # Arguments
    /// * `text` - The text containing ${...} to evaluate
    /// * `properties` - The property context (pre-resolved)
    /// * `loc` - Location context to set during evaluation
    ///
    /// # Returns
    /// The text with one level of ${...} expressions resolved
    fn substitute_one_pass_with_loc(
        &self,
        text: &str,
        properties: &HashMap<String, String>,
        loc: Option<&crate::eval::LocationContext>,
    ) -> Result<String, XacroError> {
        // Check if location context is already set (nested call)
        let was_set = {
            let current = self.current_location.borrow();
            current.is_some()
        };

        // Set location if not already set
        if !was_set {
            *self.current_location.borrow_mut() = loc.cloned();
        }

        // RAII guard to ensure cleanup even on error
        struct LocationGuard<'a> {
            location: &'a RefCell<Option<crate::eval::LocationContext>>,
            should_clear: bool,
        }

        impl Drop for LocationGuard<'_> {
            fn drop(&mut self) {
                if self.should_clear {
                    // Only clear if we can borrow - if we can't, it means we're in
                    // a nested panic/unwind and it's not safe to touch the RefCell
                    if let Ok(mut loc) = self.location.try_borrow_mut() {
                        *loc = None;
                    }
                }
            }
        }

        let _guard = LocationGuard {
            location: &self.current_location,
            should_clear: !was_set,
        };

        // Perform the substitution (may trigger nested calls)
        // Guard will automatically clear location on drop
        self.substitute_one_pass(text, properties)
    }

    /// Perform one pass of substitution with metadata-aware formatting
    ///
    /// This is similar to eval_text_with_interpreter but uses property metadata
    /// to determine whether to format numbers as float (with .0) or int (without .0).
    ///
    /// # Arguments
    /// * `text` - The text containing ${...} to evaluate
    /// * `properties` - The property context (pre-resolved)
    ///
    /// # Returns
    /// The text with one level of ${...} expressions resolved
    fn substitute_one_pass(
        &self,
        text: &str,
        properties: &HashMap<String, String>,
    ) -> Result<String, XacroError> {
        // Create fresh interpreter for this evaluation to prevent state leakage.
        // Using a shared interpreter caused properties defined in macro scopes to persist
        // after the scope was popped, violating Python xacro's scoping semantics.
        let mut fresh_interp = init_interpreter();

        // Build pyisheval context with the fresh interpreter
        let context = build_pyisheval_context(properties, &mut fresh_interp).map_err(|e| {
            XacroError::EvalError {
                expr: text.to_string(),
                source: e,
            }
        })?;

        // Tokenize and process
        let lexer = Lexer::new(text);
        let mut result = String::new();

        for (token_type, token_value) in lexer {
            match token_type {
                TokenType::Text => {
                    result.push_str(&token_value);
                }
                TokenType::Expr => {
                    // Evaluate expression using centralized helper with fresh interpreter
                    let value_opt = crate::eval::interpreter::evaluate_expression_impl(
                        &mut fresh_interp,
                        &token_value,
                        &context,
                        #[cfg(feature = "yaml")]
                        Some(&self.yaml_tag_handler_registry),
                        self.current_location.borrow().as_ref(),
                    )
                    .map_err(|e| XacroError::EvalError {
                        expr: token_value.clone(),
                        source: crate::eval::EvalError::PyishEval {
                            expr: token_value.clone(),
                            source: e,
                        },
                    })?;

                    // Handle result
                    match value_opt {
                        Some(value) => {
                            // Format result with compat-aware number formatting
                            let formatted = self.format_evaluation_result(&value, &token_value);
                            result.push_str(&formatted);
                        }
                        None => {
                            // Special case returned no output (e.g., xacro.print_location())
                            continue;
                        }
                    }
                }
                TokenType::Extension => {
                    // Resolve extension immediately with current location context
                    let resolved = self
                        .resolve_extension(&token_value, self.current_location.borrow().as_ref())?;
                    result.push_str(&resolved);
                }
                TokenType::DollarDollarBrace => {
                    // Preserve escape sequence: $$ → $
                    result.push('$');
                    result.push_str(&token_value);
                }
            }
        }

        Ok(result)
    }

    /// Substitute ${...} expressions in text using scope-aware resolution
    ///
    /// This is the public API for the single-pass expander. It uses the current
    /// scope stack to resolve properties, properly handling macro parameter shadowing.
    ///
    /// # Arguments
    /// * `text` - The text containing ${...} expressions to substitute
    /// * `loc` - Optional location context for error reporting
    ///
    /// # Returns
    /// The text with all ${...} expressions resolved
    pub fn substitute_text(
        &self,
        text: &str,
        loc: Option<&crate::eval::LocationContext>,
    ) -> Result<String, XacroError> {
        // Clone location once at the start to pass to substitute_one_pass
        let loc_cloned = loc.cloned();

        self.substitute_iteratively(
            text,
            |s| s.contains("${") || s.contains("$("),
            |result| {
                // Build context first (may trigger nested calls)
                let properties = self.build_eval_context(result)?;

                // Pass location to substitute_one_pass (it will set current_location briefly)
                self.substitute_one_pass_with_loc(result, &properties, loc_cloned.as_ref())
            },
        )
    }

    /// Parse and resolve an extension like `$(arg foo)`, `$(find pkg)`, `$(env VAR)`
    ///
    /// Extensions are distinct from expressions - they provide external data sources.
    /// Document-order eager evaluation prevents circular dependencies naturally.
    ///
    /// # Arguments
    /// * `content` - The extension content without `$(` and `)`, e.g., "arg foo"
    /// * `loc` - Optional location context for error reporting
    ///
    /// # Returns
    /// The resolved value from the appropriate extension handler
    ///
    /// # Errors
    /// * `InvalidExtension` - Malformed syntax (empty, missing argument, multi-word, etc.)
    /// * `UnknownExtension` - Extension type not recognized
    /// * `UndefinedArgument` - Argument not found in args map
    /// * `UnimplementedFeature` - Extension type not yet implemented (find, env)
    fn resolve_extension(
        &self,
        content: &str,
        loc: Option<&crate::eval::LocationContext>,
    ) -> Result<String, XacroError> {
        // Parse extension command and args
        // Format: "command arg1 arg2 ..."
        let mut parts_iter = content.split_whitespace();

        // Extract extension command (required)
        let command = parts_iter
            .next()
            .ok_or_else(|| XacroError::InvalidExtension {
                content: content.to_string(),
                reason: "Extension cannot be empty: $()".to_string(),
            })?;

        // Collect remaining parts as raw args string
        let args_raw = parts_iter.collect::<Vec<_>>().join(" ");

        // Fully resolve args: both ${...} expressions and nested $(...) extensions
        // This allows patterns like: $(find ${package_name}) and $(arg $(arg inner))
        // MAX_SUBSTITUTION_DEPTH in substitute_all prevents infinite recursion
        let args_evaluated = self.substitute_all(&args_raw, loc)?;

        // Handle $(arg ...) specially using self.args directly
        // This ensures arg resolution uses the shared args map that gets modified
        // by xacro:arg directives during expansion.
        //
        // IMPORTANT: This check runs BEFORE the extension handler chain, which means
        // $(arg ...) cannot be overridden by custom extensions. This is intentional
        // to guarantee correctness of argument handling and prevent shadowing of this
        // core feature. See notes/EXTENSION_IMPL_ACTUAL.md for rationale.
        if command == "arg" {
            let arg_parts =
                extension_utils::expect_args(&args_evaluated, "arg", 1).map_err(|e| {
                    XacroError::InvalidExtension {
                        content: content.to_string(),
                        reason: e.to_string(),
                    }
                })?;

            return self
                .args
                .borrow()
                .get(&arg_parts[0])
                .cloned()
                .ok_or_else(|| XacroError::UndefinedArgument {
                    name: arg_parts[0].clone(),
                });
        }

        // Try each extension handler in order
        for handler in self.extensions.iter() {
            match handler.resolve(command, &args_evaluated) {
                Ok(Some(result)) => return Ok(result),
                Ok(None) => continue, // Try next handler
                Err(e) => {
                    // Handler recognized the command but resolution failed
                    return Err(XacroError::InvalidExtension {
                        content: content.to_string(),
                        reason: e.to_string(),
                    });
                }
            }
        }

        // No handler recognized the command
        Err(XacroError::UnknownExtension {
            ext_type: command.to_string(),
        })
    }

    /// Resolve only extensions `$(...)`, preserving expressions `${...}`
    ///
    /// This is used as a helper to resolve extensions inside expressions before
    /// evaluating the expression itself. For example, `${$(arg count) * 2}` needs
    /// the `$(arg count)` resolved first before pyisheval can evaluate the arithmetic.
    ///
    /// # Arguments
    /// * `text` - Text potentially containing both `$()` and `${}`
    ///
    /// # Returns
    /// Text with `$()` resolved but `${}` preserved
    pub(super) fn substitute_extensions_only(
        &self,
        text: &str,
        loc: Option<&crate::eval::LocationContext>,
    ) -> Result<String, XacroError> {
        self.substitute_extensions_only_inner(text, 0, loc)
    }

    /// Inner recursive implementation of substitute_extensions_only with depth tracking
    ///
    /// # Arguments
    /// * `text` - Text potentially containing both `$()` and `${}`
    /// * `depth` - Current recursion depth (for overflow protection)
    /// * `loc` - Optional location context for error reporting
    ///
    /// # Returns
    /// Text with `$()` resolved but `${}` preserved
    fn substitute_extensions_only_inner(
        &self,
        text: &str,
        depth: usize,
        loc: Option<&crate::eval::LocationContext>,
    ) -> Result<String, XacroError> {
        // Prevent infinite recursion
        if depth >= MAX_SUBSTITUTION_DEPTH {
            return Err(XacroError::MaxSubstitutionDepth {
                depth: MAX_SUBSTITUTION_DEPTH,
                snippet: truncate_snippet(text),
            });
        }

        let lexer = Lexer::new(text);
        let mut result = String::new();

        for (token_type, content) in lexer {
            match token_type {
                TokenType::Text => result.push_str(&content),
                TokenType::Extension => {
                    let resolved = self.resolve_extension(&content, loc)?;
                    result.push_str(&resolved);
                }
                TokenType::Expr => {
                    // Don't evaluate expressions - just preserve them
                    // BUT: recursively resolve any $() inside the expression content
                    let content_with_extensions_resolved =
                        self.substitute_extensions_only_inner(&content, depth + 1, loc)?;
                    result.push_str("${");
                    result.push_str(&content_with_extensions_resolved);
                    result.push('}');
                }
                TokenType::DollarDollarBrace => {
                    // Preserve escape sequence
                    result.push('$');
                    result.push_str(&content);
                }
            }
        }

        Ok(result)
    }

    /// Substitute both extensions `$(...)` and expressions `${...}` iteratively
    ///
    /// This is the full substitution method that handles both args and properties.
    /// It iterates until no more substitutions are possible or max depth is reached.
    ///
    /// **Evaluation order** (critical for nested cases):
    /// 1. Resolve all extensions `$(...)` in the text
    /// 2. Evaluate all expressions `${...}` in the text
    /// 3. Repeat until no changes or max depth reached
    ///
    /// **Example**: `${$(arg count) * 2}` where count=5
    /// - Iteration 1:
    ///   - Resolve extensions: `${5 * 2}`
    ///   - Evaluate expressions: `10`
    /// - Iteration 2: No changes (done)
    ///
    /// # Arguments
    /// * `text` - The text containing ${...} and $(...) to substitute
    /// * `loc` - Optional location context for error reporting
    ///
    /// # Returns
    /// Fully resolved text with all substitutions applied
    ///
    /// # Errors
    /// * `MaxSubstitutionDepth` - Exceeded iteration limit (likely circular refs)
    /// * `UndefinedArgument` - Referenced arg not found
    /// * `EvalError` - Expression evaluation failed
    pub fn substitute_all(
        &self,
        text: &str,
        loc: Option<&crate::eval::LocationContext>,
    ) -> Result<String, XacroError> {
        self.substitute_iteratively(
            text,
            |s| s.contains("${") || s.contains("$("),
            |s| {
                // First resolve all extensions
                let with_extensions = self.substitute_extensions_only(s, loc)?;
                // Then evaluate all expressions
                self.substitute_text(&with_extensions, loc)
            },
        )
    }

    /// Evaluate a boolean expression using scope-aware resolution
    ///
    /// This is used for conditional evaluation (xacro:if, xacro:unless).
    /// It uses the current scope stack to resolve properties.
    ///
    /// # Arguments
    /// * `expr` - The expression to evaluate (e.g., "${x > 5}" or "true")
    /// * `loc` - Optional location context for error reporting
    ///
    /// # Returns
    /// * `Ok(true)` if the expression evaluates to true
    /// * `Ok(false)` if the expression evaluates to false
    /// * `Err` if the expression can't be evaluated
    pub fn eval_boolean(
        &self,
        expr: &str,
        loc: Option<&crate::eval::LocationContext>,
    ) -> Result<bool, XacroError> {
        // FIRST: Resolve any $(arg ...) extensions in the expression
        // Use substitute_extensions_only to preserve ${...} property refs for eval_boolean
        let resolved_expr = self.substitute_extensions_only(expr, loc)?;

        // THEN: Build context with properties referenced in the resolved expression
        // This is more efficient than resolving all properties upfront
        let properties = self.build_eval_context(&resolved_expr)?;

        // FINALLY: Evaluate the fully resolved boolean expression
        eval_boolean(&resolved_expr, &properties).map_err(Into::into)
    }

    /// Internal substitution helper used by property resolution
    ///
    /// Similar to substitute_text but takes an explicit property context instead
    /// of building it from the scope stack. Used during lazy property resolution
    /// to avoid recursion issues.
    ///
    /// # Arguments
    /// * `text` - Text containing ${...} expressions
    /// * `properties` - Pre-resolved property context
    ///
    /// # Returns
    /// Text with all ${...} expressions resolved
    pub(crate) fn substitute_in_text(
        &self,
        text: &str,
        properties: &HashMap<String, String>,
    ) -> Result<String, XacroError> {
        // Use location context if available for print_location() support
        let loc = self.current_location.borrow().clone();
        self.substitute_iteratively(
            text,
            |s| s.contains("${"),
            |result| self.substitute_one_pass_with_loc(result, properties, loc.as_ref()),
        )
    }
}