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
//! Property metadata tracking for Python xacro compatibility
//!
//! This module provides metadata tracking and formatting support that matches
//! Python xacro's int/float distinction and boolean literal formatting.
//!
//! Key features:
//! - Track which properties should format with .0 (floats) vs without (ints)
//! - Track pseudo-boolean properties (True/False literals) for 1.0/0.0 formatting
//! - Metadata propagation through property references
use super::EvalContext;
use crate::eval::interpreter::format_value_python_style;
use crate::eval::interpreter::remove_quotes;
/// Metadata tracked for each property to support Python-like formatting
#[cfg(feature = "compat")]
#[derive(Debug, Clone)]
pub(super) struct PropertyMetadata {
/// Whether this property should be formatted as float (keep .0 for whole numbers)
/// True if:
/// - Property value contains decimal point (e.g., "1.5", "100.0")
/// - Property comes from division expression (e.g., "${255/255}")
/// - Property references a float property (e.g., "${float_prop * 2}")
pub(super) is_float: bool,
/// Whether this property originated from a boolean literal
/// True if:
/// - Property value is "true" or "false" (case-insensitive, e.g., TRUE, False, etc.)
/// - Property references a pseudo-boolean property
///
/// When true, numeric values 1.0/0.0 should be formatted as "True"/"False"
pub(super) is_pseudo_boolean: bool,
}
impl<const MAX_SUBSTITUTION_DEPTH: usize> EvalContext<MAX_SUBSTITUTION_DEPTH> {
/// Generic helper to access a metadata field for a variable
///
/// Checks scoped metadata first (depth:name), then falls back to global metadata.
/// This avoids duplication between is_var_float and is_var_boolean.
///
/// # Arguments
/// * `var` - The variable name to look up
/// * `field_accessor` - Closure to extract the desired field from PropertyMetadata
///
/// # Returns
/// The field value, or T::default() if not found
#[cfg(feature = "compat")]
pub(super) fn get_var_metadata_field<F, T>(
&self,
var: &str,
field_accessor: F,
) -> T
where
F: Fn(&PropertyMetadata) -> T,
T: Default,
{
let metadata = self.property_metadata.borrow();
let scope_depth = self.scope_stack.borrow().len();
// Try scoped metadata first (current scope down to global)
for depth in (1..=scope_depth).rev() {
let scoped_key = format!("{}:{}", depth, var);
if let Some(meta) = metadata.get(&scoped_key) {
return field_accessor(meta);
}
}
// Fall back to checking global (no scope prefix)
metadata.get(var).map(field_accessor).unwrap_or_default()
}
/// Check if a variable has float metadata (compat feature only)
///
/// Looks up a property by name across all scopes (current to global) to determine
/// if it should be formatted as a float. Checks scoped metadata first (depth:name),
/// then falls back to global metadata (no scope prefix).
///
/// # Arguments
/// * `var` - The variable name to look up
///
/// # Returns
/// `true` if the variable has float metadata, `false` otherwise
#[cfg(feature = "compat")]
pub(super) fn is_var_float(
&self,
var: &str,
) -> bool {
self.get_var_metadata_field(var, |m| m.is_float)
}
/// Check if a variable is marked as pseudo-boolean (originated from True/False literal)
///
/// Used during formatting to determine if 1.0/0.0 should be formatted as "True"/"False".
/// Checks scoped metadata first (depth:name), then falls back to global metadata.
///
/// # Arguments
/// * `var` - The variable name to look up
///
/// # Returns
/// `true` if the variable has boolean metadata, `false` otherwise
#[cfg(feature = "compat")]
pub(super) fn is_var_boolean(
&self,
var: &str,
) -> bool {
self.get_var_metadata_field(var, |m| m.is_pseudo_boolean)
}
/// Compute float metadata for a property value (compat feature only)
///
/// Determines if a property should be formatted as float (with .0 for whole numbers)
/// based on Python xacro's int/float distinction heuristics.
///
/// Detection rules:
/// 1. Value contains decimal point → float
/// 2. Value is inf/nan → float
/// 3. Value contains division (/) → float
/// 4. Value references a float property → float (propagation)
#[cfg(feature = "compat")]
pub(super) fn compute_float_metadata(
&self,
value: &str,
) -> bool {
if !self.use_python_compat {
return false;
}
let has_decimal = value.contains('.');
let is_special = value.parse::<f64>().is_ok_and(|n| !n.is_finite());
let has_division = value.contains('/');
// Check if expression references any float properties
let refs_float_prop = if value.contains("${") {
let refs = self.extract_property_references(value);
refs.iter().any(|r| self.is_var_float(r))
} else {
false
};
has_decimal || is_special || has_division || refs_float_prop
}
#[cfg(not(feature = "compat"))]
#[allow(dead_code)]
pub(super) fn compute_float_metadata(
&self,
_value: &str,
) -> bool {
false
}
/// Compute boolean metadata for a property value (compat feature only)
///
/// Determines if a property originated from a boolean literal and should
/// format 1.0/0.0 as "True"/"False" in output.
///
/// Detection rules:
/// 1. Value is "True"/"False" (Python literals) or "true"/"false" (XML/xacro convention)
/// 2. Value references a pseudo-boolean property (propagation)
///
/// Limitation: Only works for literal definitions, not boolean expressions
/// like `${x == y}` which return 1.0/0.0 without type information.
#[cfg(feature = "compat")]
pub(super) fn compute_boolean_metadata(
&self,
value: &str,
) -> bool {
if !self.use_python_compat {
return false;
}
let trimmed = value.trim();
// Check for boolean literals (case-insensitive matching)
// Python xacro's _eval_literal() accepts any casing: true, True, TRUE, etc.
// All are formatted as "True"/"False" in output
if trimmed.eq_ignore_ascii_case("true") || trimmed.eq_ignore_ascii_case("false") {
return true;
}
// Check if expression references any boolean properties
if trimmed.contains("${") {
let refs = self.extract_property_references(trimmed);
refs.iter().any(|r| self.is_var_boolean(r))
} else {
false
}
}
#[cfg(not(feature = "compat"))]
#[allow(dead_code)]
pub(super) fn compute_boolean_metadata(
&self,
_value: &str,
) -> bool {
false
}
/// Compute property metadata for a value (compat feature only)
///
/// Combines float and boolean metadata computation to avoid duplication.
/// This is called when adding properties to scope or globally.
///
/// # Arguments
/// * `value` - The property value string to analyze
///
/// # Returns
/// PropertyMetadata with both is_float and is_pseudo_boolean computed
#[cfg(feature = "compat")]
pub(super) fn compute_property_metadata(
&self,
value: &str,
) -> PropertyMetadata {
PropertyMetadata {
is_float: self.compute_float_metadata(value),
is_pseudo_boolean: self.compute_boolean_metadata(value),
}
}
/// Check if an expression result should be formatted as float (with .0 for whole numbers)
///
/// Returns true if:
/// - Expression contains division (always produces float), OR
/// - Result has fractional part (is not a whole number), OR
/// - Expression references any float properties (metadata propagation)
///
/// # Arguments
/// * `expr` - The expression that was evaluated
/// * `result_value` - The pyisheval Value result
///
/// # Returns
/// Whether to format the result as float (with .0 for whole numbers)
#[cfg(feature = "compat")]
pub(super) fn should_format_as_float(
&self,
expr: &str,
result_value: &pyisheval::Value,
) -> bool {
// Check if expression contains division (always produces float)
if expr.contains('/') {
return true;
}
// Check if result has fractional part (always float)
if let pyisheval::Value::Number(n) = result_value {
if n.fract() != 0.0 {
return true;
}
}
// Special case: if expression is just a simple variable name (no operators),
// check its metadata directly
let trimmed = expr.trim();
if super::util::is_simple_identifier(trimmed) {
return self.is_var_float(trimmed);
}
// Complex expression: extract variables and check if any are float properties
// Note: extract_property_references expects ${...} syntax, so wrap the expression
let vars = self.extract_property_references(&format!("${{{}}}", expr));
for var in vars {
if self.is_var_float(&var) {
return true;
}
}
false
}
/// Check if an expression result should be formatted as boolean ("True"/"False")
///
/// Returns true if:
/// - Result value is exactly 1.0 or 0.0 (boolean numeric values), AND
/// - Expression is a simple variable reference with boolean metadata
///
/// Note: Complex expressions (like `1 if flag else 0`) are NOT formatted as boolean,
/// even if they reference boolean properties, because the result type is determined
/// by the expression itself, not by the properties it references.
///
/// # Arguments
/// * `expr` - The expression that was evaluated
/// * `result_value` - The pyisheval Value result
///
/// # Returns
/// `true` if the result should be formatted as "True"/"False", `false` otherwise
#[cfg(feature = "compat")]
pub(super) fn should_format_as_boolean(
&self,
expr: &str,
result_value: &pyisheval::Value,
) -> bool {
// Only boolean values (1.0 or 0.0) can be formatted as boolean
if !matches!(result_value, pyisheval::Value::Number(n) if *n == 1.0 || *n == 0.0) {
return false;
}
// Only format as boolean for simple variable references
// Complex expressions determine their own output type
let trimmed = expr.trim();
if super::util::is_simple_identifier(trimmed) {
return self.is_var_boolean(trimmed);
}
false
}
/// Format an evaluation result with Python-compatible number formatting
///
/// When compat feature is enabled, uses metadata to decide whether to format
/// numbers as float (with .0) or int. When disabled, uses default formatting.
/// Always strips quotes from string literals.
///
/// # Arguments
/// * `value` - The evaluated value to format
/// * `expr` - The original expression (used for metadata lookup)
///
/// # Returns
/// Formatted string with quotes stripped if it was a string literal
#[cfg_attr(not(feature = "compat"), allow(unused_variables))]
pub(super) fn format_evaluation_result(
&self,
value: &pyisheval::Value,
expr: &str,
) -> String {
// Format the value
let formatted = {
#[cfg(feature = "compat")]
{
if self.use_python_compat {
// Check for boolean formatting first (1.0/0.0 with boolean metadata)
if self.should_format_as_boolean(expr, value) {
// should_format_as_boolean guarantees value is Number(1.0) or Number(0.0)
if let pyisheval::Value::Number(n) = value {
if *n == 1.0 {
"True".to_string()
} else {
"False".to_string()
}
} else {
unreachable!("should_format_as_boolean validated this is a Number")
}
} else {
// Not a boolean, use float metadata
let force_float = self.should_format_as_float(expr, value);
format_value_python_style(value, force_float)
}
} else {
// Preserve old behavior: always format with .0 for whole numbers
format_value_python_style(value, true)
}
}
#[cfg(not(feature = "compat"))]
{
// Preserve old behavior: always format with .0 for whole numbers
format_value_python_style(value, true)
}
};
// Strip quotes from string literals (always done, not compat-specific)
remove_quotes(&formatted).to_string()
}
}