oak-rust 0.0.11

High-performance incremental Rust parser for the oak ecosystem with flexible configuration, emphasizing memory safety and zero-cost abstractions.
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
#![doc = include_str!("readme.md")]

use crate::{
    ast::{RustRoot, *},
    lexer::RustTokenType,
};

/// Rust Code Formatter
///
/// `RustFormatter` is responsible for converting Rust AST into formatted source code strings.
/// It follows Rust's official code style guidelines, including indentation, spacing, and line breaks.
///
/// # Examples
///
/// Basic usage:
///
/// ```rust,ignore
/// use oak_rust::formatter::RustFormatter;
///
/// let formatter = RustFormatter::new();
/// let formatted = formatter.format("fn main(){let x=42}");
/// // Output: "fn main() {\n    let x = 42;\n}"
/// ```
pub struct RustFormatter {
    /// Indentation level
    indent_level: usize,
    /// Indentation string (usually 4 spaces)
    indent_str: String,
    /// Maximum line length
    max_line_length: usize,
}

impl RustFormatter {
    /// Create a new Rust formatter
    ///
    /// # Returns
    ///
    /// Returns a new `RustFormatter` instance with default configuration.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use oak_rust::formatter::RustFormatter;
    ///
    /// let formatter = RustFormatter::new();
    /// ```
    pub fn new() -> Self {
        Self {
            indent_level: 0,
            indent_str: "    ".to_string(), // 4 spaces
            max_line_length: 100,
        }
    }

    /// Create formatter with custom configuration
    ///
    /// # Arguments
    ///
    /// * `indent_str` - Indentation string
    /// * `max_line_length` - Maximum line length
    ///
    /// # Returns
    ///
    /// Returns a configured `RustFormatter` instance.
    pub fn with_config(indent_str: String, max_line_length: usize) -> Self {
        Self { indent_level: 0, indent_str, max_line_length }
    }

    /// Format the given Rust source code string
    ///
    /// # Arguments
    ///
    /// * `source` - Rust source code to format
    ///
    /// # Returns
    ///
    /// Returns the formatted Rust source code string.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use oak_rust::formatter::RustFormatter;
    ///
    /// let formatter = RustFormatter::new();
    /// let formatted = formatter.format("fn main(){let x=42}");
    /// ```
    pub fn format(&self, source: &str) -> String {
        // TODO: Implement complete Rust code formatting
        // Currently returns basic formatting version
        self.basic_format(source)
    }

    /// Format Rust AST root node
    ///
    /// # Arguments
    ///
    /// * `root` - Rust AST root node
    ///
    /// # Returns
    ///
    /// Returns the formatted Rust source code string.
    pub fn format_ast(&self, root: &RustRoot) -> String {
        let mut result = String::new();

        for (i, item) in root.items.iter().enumerate() {
            if i > 0 {
                result.push_str("\n\n");
            }
            result.push_str(&self.format_item(item));
        }

        result
    }

    /// Format top-level items
    fn format_item(&self, item: &Item) -> String {
        match item {
            Item::Function(func) => self.format_function(func),
            Item::Struct(struct_def) => self.format_struct(struct_def),
            Item::Enum(enum_def) => self.format_enum(enum_def),
            Item::Trait(trait_def) => self.format_trait(trait_def),
            Item::Impl(impl_block) => self.format_impl(impl_block),
            Item::Module(module) => self.format_module(module),
            Item::Use(use_item) => self.format_use(use_item),
            Item::Const(const_item) => self.format_const(const_item),
            Item::Static(static_item) => self.format_static(static_item),
            Item::TypeAlias(type_alias) => self.format_type_alias(type_alias),
            Item::ExternBlock(extern_block) => self.format_extern_block(extern_block),
        }
    }

    /// Format functions
    fn format_function(&self, func: &Function) -> String {
        let mut result = String::new();

        // Function modifiers
        if func.is_async {
            result.push_str("async ");
        }
        if func.is_unsafe {
            result.push_str("unsafe ");
        }

        result.push_str("fn ");
        result.push_str(&func.name.name);

        // Parameter list
        result.push('(');
        for (i, param) in func.params.iter().enumerate() {
            if i > 0 {
                result.push_str(", ");
            }
            result.push_str(&self.format_param(param));
        }
        result.push(')');

        // Return type
        if let Some(return_type) = &func.return_type {
            result.push_str(" -> ");
            result.push_str(&self.format_type(return_type));
        }

        // Function body
        result.push(' ');
        result.push_str(&self.format_block(&func.body));

        result
    }

    /// Format parameters
    fn format_param(&self, param: &Param) -> String {
        let mut result = String::new();
        if param.is_mut {
            result.push_str("mut ");
        }
        result.push_str(&param.name.name);
        result.push_str(": ");
        result.push_str(&self.format_type(&param.ty));
        result
    }

    /// Format code blocks
    fn format_block(&self, block: &Block) -> String {
        let mut result = String::new();
        result.push_str("{\n");

        // Increase indentation
        let mut formatter = self.clone();
        formatter.indent_level += 1;

        // Format statements
        for stmt in &block.statements {
            result.push_str(&formatter.get_indent());
            result.push_str(&formatter.format_statement(stmt));
            result.push('\n');
        }

        result.push_str(&self.get_indent());
        result.push('}');
        result
    }

    /// Format statements
    fn format_statement(&self, stmt: &Statement) -> String {
        match stmt {
            Statement::Let { name, ty, expr, mutable, .. } => {
                let mut result = String::new();
                result.push_str("let ");
                if *mutable {
                    result.push_str("mut ");
                }
                result.push_str(&name.name);

                if let Some(ty) = ty {
                    result.push_str(": ");
                    result.push_str(&self.format_type(ty));
                }

                if let Some(expr) = expr {
                    result.push_str(" = ");
                    result.push_str(&self.format_expr(expr));
                }

                result.push(';');
                result
            }
            Statement::ExprStmt { expr, semi, .. } => {
                let mut result = self.format_expr(expr);
                if *semi {
                    result.push(';');
                }
                result
            }
            Statement::Return { expr, .. } => {
                let mut result = String::from("return");
                if let Some(expr) = expr {
                    result.push(' ');
                    result.push_str(&self.format_expr(expr));
                }
                result.push(';');
                result
            }
            Statement::Break { expr, .. } => {
                let mut result = String::from("break");
                if let Some(expr) = expr {
                    result.push(' ');
                    result.push_str(&self.format_expr(expr));
                }
                result.push(';');
                result
            }
            Statement::Continue { .. } => String::from("continue;"),
            Statement::Item(item) => self.format_item(item),
        }
    }

    /// Format expressions
    fn format_expr(&self, expr: &Expr) -> String {
        match expr {
            Expr::Literal { value, .. } => value.clone(),
            Expr::Bool { value, .. } => value.to_string(),
            Expr::Ident(ident) => ident.name.clone(),
            Expr::Binary { left, op, right, .. } => {
                format!("{} {} {}", self.format_expr(left), self.format_syntax_kind(op), self.format_expr(right))
            }
            Expr::Unary { op, expr, .. } => {
                format!("{}{}", self.format_syntax_kind(op), self.format_expr(expr))
            }
            Expr::Call { callee, args, .. } => {
                let mut result = self.format_expr(callee);
                result.push('(');
                for (i, arg) in args.iter().enumerate() {
                    if i > 0 {
                        result.push_str(", ");
                    }
                    result.push_str(&self.format_expr(arg));
                }
                result.push(')');
                result
            }
            Expr::Field { receiver, field, .. } => {
                format!("{}.{}", self.format_expr(receiver), field.name)
            }
            Expr::Index { receiver, index, .. } => {
                format!("{}[{}]", self.format_expr(receiver), self.format_expr(index))
            }
            Expr::Paren { expr, .. } => {
                format!("({})", self.format_expr(expr))
            }
            Expr::Block(block) => self.format_block(block),
            _ => "/* unsupported expression */".to_string(),
        }
    }

    /// Format literal expressions
    fn _format_literal_expr(&self, expr: &Expr) -> String {
        match expr {
            Expr::Literal { value, .. } => value.clone(),
            Expr::Bool { value, .. } => value.to_string(),
            _ => "".to_string(), // Returns empty string for non-literal expressions
        }
    }

    /// Format syntax types to strings
    fn format_syntax_kind(&self, kind: &RustTokenType) -> String {
        match kind {
            RustTokenType::Plus => "+".to_string(),
            RustTokenType::Minus => "-".to_string(),
            RustTokenType::Star => "*".to_string(),
            RustTokenType::Slash => "/".to_string(),
            RustTokenType::Percent => "%".to_string(),
            RustTokenType::EqEq => "==".to_string(),
            RustTokenType::Ne => "!=".to_string(),
            RustTokenType::Lt => "<".to_string(),
            RustTokenType::Le => "<=".to_string(),
            RustTokenType::Gt => ">".to_string(),
            RustTokenType::Ge => ">=".to_string(),
            RustTokenType::AndAnd => "&&".to_string(),
            RustTokenType::OrOr => "||".to_string(),
            RustTokenType::Bang => "!".to_string(),
            RustTokenType::Ampersand => "&".to_string(),
            _ => "/* unsupported operator */".to_string(),
        }
    }

    /// Get current indentation string
    fn get_indent(&self) -> String {
        self.indent_str.repeat(self.indent_level)
    }

    /// Basic formatting (simple implementation)
    fn basic_format(&self, source: &str) -> String {
        // Simple formatting: add appropriate spaces and line breaks
        source.replace("{", " {\n").replace("}", "\n}").replace(";", ";\n").lines().map(|line| line.trim()).filter(|line| !line.is_empty()).collect::<Vec<_>>().join("\n")
    }

    // Placeholder methods - these need to be implemented based on specific requirements
    fn format_struct(&self, _struct_def: &Struct) -> String {
        "/* struct formatting not implemented */".to_string()
    }

    fn format_enum(&self, _enum_def: &Enum) -> String {
        "/* enum formatting not implemented */".to_string()
    }

    fn format_trait(&self, _trait_def: &Trait) -> String {
        "/* trait formatting not implemented */".to_string()
    }

    fn format_impl(&self, _impl_block: &Impl) -> String {
        "/* impl formatting not implemented */".to_string()
    }

    fn format_module(&self, _module: &Module) -> String {
        "/* module formatting not implemented */".to_string()
    }

    fn format_use(&self, use_item: &UseItem) -> String {
        format!("use {};", use_item.path)
    }

    fn format_const(&self, const_item: &Const) -> String {
        format!("const {}: {} = {}", const_item.name.name, self.format_type(&const_item.ty), self.format_expr(&const_item.expr))
    }

    fn format_static(&self, static_item: &Static) -> String {
        let mut_keyword = if static_item.mutable { "mut " } else { "" };
        format!("static {}{}: {} = {}", mut_keyword, static_item.name.name, self.format_type(&static_item.ty), self.format_expr(&static_item.expr))
    }

    fn format_type_alias(&self, type_alias: &TypeAlias) -> String {
        format!("type {} = {}", type_alias.name.name, self.format_type(&type_alias.ty))
    }

    fn _format_macro_def(&self, _macro_def: &str) -> String {
        "/* macro definition formatting not implemented */".to_string()
    }

    fn format_extern_block(&self, _extern_block: &ExternBlock) -> String {
        // Temporarily return placeholder implementation to avoid compilation errors
        "extern {}".to_string()
    }

    fn _format_generics(&self, _generics: &str) -> String {
        "/* generics formatting not implemented */".to_string()
    }

    fn format_type(&self, _ty: &Type) -> String {
        "/* type formatting not implemented */".to_string()
    }

    fn _format_pattern(&self, _pattern: &Pattern) -> String {
        "/* pattern formatting not implemented */".to_string()
    }
}

impl Clone for RustFormatter {
    fn clone(&self) -> Self {
        Self { indent_level: self.indent_level, indent_str: self.indent_str.clone(), max_line_length: self.max_line_length }
    }
}

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