aam-rs 2.0.2

A Rust implementation of the Abstract Alias Mapping (AAM) framework for aliasing and maping aam 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
//! Formatter trait for LSP integration.
//!
//! The Formatter provides an API for formatting AAML documents without requiring
//! full pipeline execution. This is critical for LSP support (document formatting,
//! range formatting, on-save hooks).

use crate::error::AamlError;
use crate::pipeline::parser::AstNode;

/// Configuration options for formatting behavior.
#[derive(Debug, Clone)]
pub struct FormattingOptions {
    /// Number of spaces per indentation level
    pub indent_size: usize,

    /// Use tabs instead of spaces
    pub use_tabs: bool,

    /// Line width for wrapping (0 = no wrapping)
    pub line_width: usize,

    /// Sort keys alphabetically
    pub sort_keys: bool,

    /// Add trailing newline
    pub trailing_newline: bool,

    /// Preserve blank lines
    pub preserve_blank_lines: bool,
}

impl Default for FormattingOptions {
    fn default() -> Self {
        Self {
            indent_size: 4,
            use_tabs: false,
            line_width: 100,
            sort_keys: false,
            trailing_newline: true,
            preserve_blank_lines: true,
        }
    }
}

/// Range for document range formatting.
#[derive(Debug, Clone, Copy)]
pub struct FormatRange {
    /// Start line (1-based)
    pub start_line: usize,
    /// End line (1-based, inclusive)
    pub end_line: usize,
}

/// Trait for formatting AAML documents.
///
/// This trait provides methods to format AST nodes, handle range-based formatting,
/// and support LSP clients that need formatting without full parsing/execution.
pub trait Formatter: Send + Sync {
    /// Formats an entire document represented by AST nodes.
    ///
    /// # Arguments
    /// - `nodes`: AST nodes to format
    /// - `options`: Formatting options
    ///
    /// # Returns
    /// Formatted document as a string
    fn format_document(
        &self,
        nodes: &[AstNode],
        options: &FormattingOptions,
    ) -> Result<String, AamlError>;

    /// Formats a specific range in a document.
    ///
    /// # Arguments
    /// - `nodes`: AST nodes to format
    /// - `range`: The range to format
    /// - `options`: Formatting options
    ///
    /// # Returns
    /// Formatted document with only the specified range modified
    fn format_range(
        &self,
        nodes: &[AstNode],
        range: FormatRange,
        options: &FormattingOptions,
    ) -> Result<String, AamlError>;

    /// Formats a single AST node.
    ///
    /// # Arguments
    /// - `node`: AST node to format
    /// - `indent_level`: Current indentation level
    /// - `options`: Formatting options
    ///
    /// # Returns
    /// Formatted node as a string
    fn format_node(
        &self,
        node: &AstNode,
        indent_level: usize,
        options: &FormattingOptions,
    ) -> Result<String, AamlError>;

    /// Normalizes comments in a document.
    ///
    /// # Arguments
    /// - `content`: Raw document content
    /// - `options`: Formatting options
    ///
    /// # Returns
    /// Document with normalized comments
    fn normalize_comments(
        &self,
        content: &str,
        options: &FormattingOptions,
    ) -> Result<String, AamlError>;

    /// Removes trailing whitespace and normalizes line endings.
    ///
    /// # Arguments
    /// - `content`: Raw document content
    ///
    /// # Returns
    /// Document with normalized whitespace
    fn normalize_whitespace(&self, content: &str) -> Result<String, AamlError>;
}

/// Default implementation of the Formatter trait.
///
/// Provides basic formatting capabilities suitable for most use cases.
pub struct DefaultFormatter;

impl DefaultFormatter {
    pub fn new() -> Self {
        Self
    }

    /// Creates indentation string based on level and options.
    fn create_indent(level: usize, options: &FormattingOptions) -> String {
        if options.use_tabs {
            "\t".repeat(level)
        } else {
            " ".repeat(level * options.indent_size)
        }
    }

    /// Formats an assignment node.
    fn format_assignment(
        key: &str,
        value: &str,
        indent_level: usize,
        options: &FormattingOptions,
    ) -> String {
        let indent = Self::create_indent(indent_level, options);
        format!("{}{} = {}", indent, key, value)
    }

    /// Formats a directive node.
    fn format_directive(
        name: &str,
        args: &str,
        indent_level: usize,
        options: &FormattingOptions,
    ) -> String {
        let indent = Self::create_indent(indent_level, options);
        if args.is_empty() {
            format!("{}@{}", indent, name)
        } else {
            format!("{}@{} {}", indent, name, args)
        }
    }

    /// Formats an inline object node.
    #[allow(dead_code)]
    fn format_inline_object(pairs: &[(String, String)], _options: &FormattingOptions) -> String {
        if pairs.is_empty() {
            "{}".to_string()
        } else {
            let formatted_pairs: Vec<String> = pairs
                .iter()
                .map(|(k, v)| format!("{} = {}", k, v))
                .collect();
            format!("{{ {} }}", formatted_pairs.join(", "))
        }
    }

    /// Formats an inline list node.
    #[allow(dead_code)]
    fn format_inline_list(items: &[String]) -> String {
        if items.is_empty() {
            "[]".to_string()
        } else {
            format!("[{}]", items.join(", "))
        }
    }
}

impl Default for DefaultFormatter {
    fn default() -> Self {
        Self::new()
    }
}

impl Formatter for DefaultFormatter {
    fn format_document(
        &self,
        nodes: &[AstNode],
        options: &FormattingOptions,
    ) -> Result<String, AamlError> {
        let mut output = Vec::new();

        for node in nodes {
            let formatted = self.format_node(node, 0, options)?;
            output.push(formatted);
        }

        let mut result = output.join("\n");

        if options.trailing_newline && !result.ends_with('\n') {
            result.push('\n');
        }

        Ok(result)
    }

    fn format_range(
        &self,
        nodes: &[AstNode],
        range: FormatRange,
        options: &FormattingOptions,
    ) -> Result<String, AamlError> {
        let mut output = Vec::new();

        for node in nodes {
            let line = node.line();
            if line >= range.start_line && line <= range.end_line {
                let formatted = self.format_node(node, 0, options)?;
                output.push(formatted);
            } else {
                // For lines outside the range, preserve original formatting
                output.push(format!("(original line {})", line));
            }
        }

        Ok(output.join("\n"))
    }

    fn format_node(
        &self,
        node: &AstNode,
        indent_level: usize,
        options: &FormattingOptions,
    ) -> Result<String, AamlError> {
        let formatted = match node {
            AstNode::Assignment { key, value, .. } => {
                Self::format_assignment(key, &value.to_string(), indent_level, options)
            }
            AstNode::Directive { name, args, .. } => {
                Self::format_directive(name, args, indent_level, options)
            }
        };

        Ok(formatted)
    }

    fn normalize_comments(
        &self,
        content: &str,
        _options: &FormattingOptions,
    ) -> Result<String, AamlError> {
        let lines: Vec<&str> = content.lines().collect();
        let normalized: Vec<String> = lines
            .iter()
            .map(|line| {
                // Normalize comment spacing (ensure space after #)
                if let Some(pos) = line.find('#') {
                    let before = &line[..pos];
                    let after = &line[pos + 1..];

                    // Only if surrounded by spaces (not hex color)
                    if pos > 0
                        && pos < line.len() - 1
                        && before.ends_with(' ')
                        && !after.starts_with('#')
                    {
                        let comment = after.trim_start();
                        return format!("{}# {}", before.trim_end(), comment);
                    }
                }

                line.to_string()
            })
            .collect();

        Ok(normalized.join("\n"))
    }

    fn normalize_whitespace(&self, content: &str) -> Result<String, AamlError> {
        let lines: Vec<&str> = content.lines().collect();
        let normalized: Vec<String> = lines
            .iter()
            .map(|line| line.trim_end().to_string())
            .collect();

        Ok(normalized.join("\n"))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_create_indent_spaces() {
        let options = FormattingOptions {
            indent_size: 4,
            use_tabs: false,
            ..Default::default()
        };
        assert_eq!(DefaultFormatter::create_indent(0, &options), "");
        assert_eq!(DefaultFormatter::create_indent(1, &options), "    ");
        assert_eq!(DefaultFormatter::create_indent(2, &options), "        ");
    }

    #[test]
    fn test_create_indent_tabs() {
        let options = FormattingOptions {
            use_tabs: true,
            ..Default::default()
        };
        assert_eq!(DefaultFormatter::create_indent(0, &options), "");
        assert_eq!(DefaultFormatter::create_indent(1, &options), "\t");
        assert_eq!(DefaultFormatter::create_indent(2, &options), "\t\t");
    }

    #[test]
    fn test_format_assignment() {
        let formatted =
            DefaultFormatter::format_assignment("key", "value", 0, &FormattingOptions::default());
        assert_eq!(formatted, "key = value");
    }

    #[test]
    fn test_format_assignment_with_indent() {
        let options = FormattingOptions {
            indent_size: 2,
            ..Default::default()
        };
        let formatted = DefaultFormatter::format_assignment("key", "value", 1, &options);
        assert_eq!(formatted, "  key = value");
    }

    #[test]
    fn test_format_directive() {
        let formatted = DefaultFormatter::format_directive(
            "import",
            "base.aam",
            0,
            &FormattingOptions::default(),
        );
        assert_eq!(formatted, "@import base.aam");
    }

    #[test]
    fn test_format_inline_object() {
        let pairs = vec![
            ("host".to_string(), "localhost".to_string()),
            ("port".to_string(), "8080".to_string()),
        ];
        let formatted =
            DefaultFormatter::format_inline_object(&pairs, &FormattingOptions::default());
        assert_eq!(formatted, "{ host = localhost, port = 8080 }");
    }

    #[test]
    fn test_format_inline_list() {
        let items = vec!["a".to_string(), "b".to_string(), "c".to_string()];
        let formatted = DefaultFormatter::format_inline_list(&items);
        assert_eq!(formatted, "[a, b, c]");
    }

    #[test]
    fn test_normalize_whitespace() {
        let formatter = DefaultFormatter::new();
        let input = "key = value   \nfoo = bar  ";
        let result = formatter.normalize_whitespace(input).unwrap();
        assert_eq!(result, "key = value\nfoo = bar");
    }

    #[test]
    fn test_format_document() {
        let formatter = DefaultFormatter::new();
        let ast = vec![AstNode::Assignment {
            key: "name".to_string().into(),
            value: crate::pipeline::parser::ValueNode::Literal("test".to_string().into()),
            line: 1,
        }];
        let result = formatter
            .format_document(&ast, &FormattingOptions::default())
            .unwrap();
        assert!(result.contains("name = test"));
    }
}