lynxql 0.1.1

A parser for the Lynx declarative modeling language - a statically typed language for expressing combinatorial optimization problems
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
use crate::*;
use nom::{
    branch::alt,
    bytes::complete::{tag, take_while1, take_while, take_until},
    character::complete::{char, digit1, alpha1, alphanumeric1, line_ending, not_line_ending},
    combinator::{opt, map, recognize, value, cut},
    multi::{many0, separated_list0, separated_list1},
    sequence::{delimited, preceded, tuple, pair},
    IResult, Err as NomErr,
    error::{ErrorKind, ParseError as NomParseError}
};

// Enhanced error recovery parser for LSP use
// This parser tries to recover from errors and continue parsing

#[derive(Debug, Clone)]
pub struct ResilientParseError {
    pub message: String,
    pub line: u32,
    pub column: u32,
}

#[derive(Debug, Clone)]
pub struct ParseResult {
    pub program: Program,
    pub errors: Vec<ResilientParseError>,
}

impl ParseResult {
    pub fn new() -> Self {
        Self {
            program: Program { statements: Vec::new() },
            errors: Vec::new(),
        }
    }
}

fn calculate_position(original_input: &str, current_input: &str) -> (u32, u32) {
    let consumed_bytes = original_input.len() - current_input.len();
    let consumed_text = &original_input[..consumed_bytes];
    
    let line = consumed_text.matches('\n').count() as u32;
    let column = if let Some(last_newline) = consumed_text.rfind('\n') {
        (consumed_text.len() - last_newline - 1) as u32
    } else {
        consumed_text.len() as u32
    };
    
    (line, column)
}

pub fn parse_program_resilient(input: &str) -> ParseResult {
    let mut result = ParseResult::new();
    let original_input = input;
    let mut remaining = input;
    
    // Skip initial whitespace and comments
    if let Ok((new_input, _)) = multispace_and_comments(remaining) {
        remaining = new_input;
    }
    
    // Parse statements with error recovery
    while !remaining.trim().is_empty() {
        match parse_statement_resilient(remaining) {
            Ok((new_input, statement)) => {
                result.program.statements.push(statement);
                remaining = new_input;
                
                // Skip whitespace and comments after successful parse
                if let Ok((new_input, _)) = multispace_and_comments(remaining) {
                    remaining = new_input;
                }
            }
            Err(error) => {
                let (line, column) = calculate_position(original_input, remaining);
                result.errors.push(ResilientParseError {
                    message: format!("Parse error: {}", error),
                    line,
                    column,
                });
                
                // Try to recover by skipping to next statement
                remaining = skip_to_next_statement(remaining);
                
                // If we can't make progress, break to avoid infinite loop
                if remaining.trim().is_empty() {
                    break;
                }
            }
        }
    }
    
    result
}

fn parse_statement_resilient(input: &str) -> IResult<&str, Statement> {
    // Try each statement type with error recovery
    alt((
        map(type_decl_resilient, Statement::TypeDecl),
        map(enum_decl_resilient, Statement::EnumDecl),
        map(instance_or_assignment_resilient, Statement::Assignment),
        map(solve_call_resilient, Statement::SolveCall),
    ))(input)
}

fn type_decl_resilient(input: &str) -> IResult<&str, TypeDecl> {
    let (input, _) = ws(tag("type"))(input)?;
    let (input, name) = ws(type_name)(input)?;
    let (input, _) = ws(char(':'))(input)?;
    let (input, base_type) = ws(base_type)(input)?;
    
    // Try to parse fields, but don't fail if field parsing fails
    let (input, fields) = match opt(delimited(
        ws(char('{')),
        field_decl_list_resilient,
        ws(char('}'))
    ))(input) {
        Ok((input, fields)) => (input, fields.unwrap_or_default()),
        Err(_) => {
            // If field parsing fails, try to find the closing brace and continue
            let (input, _) = skip_to_closing_brace(input)?;
            (input, Vec::new())
        }
    };
    
    Ok((input, TypeDecl {
        name: name.to_string(),
        base_type,
        fields,
    }))
}

fn enum_decl_resilient(input: &str) -> IResult<&str, EnumDecl> {
    let (input, _) = ws(tag("enum"))(input)?;
    let (input, name) = ws(type_name)(input)?;
    let (input, _) = ws(char('{'))(input)?;
    let (input, variants) = enum_variant_list_resilient(input)?;
    let (input, _) = ws(char('}'))(input)?;
    
    Ok((input, EnumDecl {
        name: name.to_string(),
        variants,
    }))
}

fn instance_or_assignment_resilient(input: &str) -> IResult<&str, Assignment> {
    // Try to parse typed assignment: TypeName instance_name = expr
    if let Ok((remaining, type_name)) = ws(type_name)(input) {
        if let Ok((remaining, instance_name)) = ws(identifier)(remaining) {
            if let Ok((remaining, _)) = ws(char('='))(remaining) {
                // This is a typed assignment with equals: TypeName name = expr
                let (input, expr) = ws(expr_resilient)(remaining)?;
                return Ok((input, Assignment {
                    type_name: type_name.to_string(),
                    name: instance_name.to_string(),
                    value: expr,
                }));
            } else if let Ok((remaining, _)) = ws(char('{'))(remaining) {
                // This is an instance declaration without equals: TypeName name { ... }
                let (input, fields) = field_assign_list_resilient(remaining)?;
                let (input, _) = ws(char('}'))(input)?;
                
                return Ok((input, Assignment {
                    type_name: type_name.to_string(),
                    name: instance_name.to_string(),
                    value: Expr::AnonymousObjectLiteral(fields),
                }));
            }
        }
    }
    
    // Try primitive type assignments: int/float/string/bool name = expr
    if let Ok((remaining, prim_type)) = ws(alt((
        tag("int"), tag("float"), tag("string"), tag("bool")
    )))(input) {
        if let Ok((remaining, var_name)) = ws(identifier)(remaining) {
            if let Ok((remaining, _)) = ws(char('='))(remaining) {
                let (input, expr) = ws(expr_resilient)(remaining)?;
                return Ok((input, Assignment {
                    type_name: prim_type.to_string(),
                    name: var_name.to_string(),
                    value: expr,
                }));
            }
        }
    }
    
    // Fall back to regular assignment (name = expr)
    assignment_resilient(input)
}

fn solve_call_resilient(input: &str) -> IResult<&str, SolveCall> {
    // Use the original solve_call parser for now
    solve_call(input)
}

fn assignment_resilient(input: &str) -> IResult<&str, Assignment> {
    let (input, name) = ws(identifier)(input)?;
    let (input, _) = ws(char('='))(input)?;
    let (input, value) = ws(expr_resilient)(input)?;
    
    Ok((input, Assignment {
        type_name: String::new(), // Empty type_name indicates regular assignment
        name: name.to_string(),
        value,
    }))
}

fn field_decl_list_resilient(input: &str) -> IResult<&str, Vec<FieldDecl>> {
    let mut fields = Vec::new();
    let mut remaining = input;
    
    // Skip initial whitespace
    if let Ok((new_input, _)) = multispace_and_comments(remaining) {
        remaining = new_input;
    }
    
    // Parse fields with error recovery
    while !remaining.is_empty() && !remaining.starts_with('}') {
        match field_decl_resilient(remaining) {
            Ok((new_input, field)) => {
                fields.push(field);
                remaining = new_input;
                
                // Try to consume optional comma
                if let Ok((new_input, _)) = opt(ws(char(',')))(remaining) {
                    remaining = new_input;
                }
            }
            Err(_) => {
                // Skip to next comma or closing brace
                remaining = skip_to_next_field_or_end(remaining);
            }
        }
    }
    
    Ok((remaining, fields))
}

fn field_decl_resilient(input: &str) -> IResult<&str, FieldDecl> {
    let (input, name) = ws(identifier)(input)?;
    let (input, _) = ws(char(':'))(input)?;
    let (input, type_ref) = ws(type_ref)(input)?;
    let (input, is_optional) = opt(ws(char('?')))(input)?;
    
    // Handle default value with resilient expression parsing
    let (input, default) = if let Ok((new_input, _)) = ws(char('='))(input) {
        match expr_resilient(new_input) {
            Ok((new_input, expr)) => (new_input, Some(expr)),
            Err(_) => {
                // If expression parsing fails, skip to next comma or end
                let skipped_input = skip_to_next_field_or_end(new_input);
                (skipped_input, None)
            }
        }
    } else {
        (input, None)
    };
    
    Ok((input, FieldDecl {
        name: name.to_string(),
        type_ref,
        is_optional: is_optional.is_some(),
        default,
    }))
}

fn field_assign_list_resilient(input: &str) -> IResult<&str, Vec<FieldAssign>> {
    let mut fields = Vec::new();
    let mut remaining = input;
    
    // Skip initial whitespace
    if let Ok((new_input, _)) = multispace_and_comments(remaining) {
        remaining = new_input;
    }
    
    // Parse field assignments with error recovery
    while !remaining.is_empty() && !remaining.starts_with('}') {
        match ws(field_assign_resilient)(remaining) {
            Ok((new_input, field)) => {
                fields.push(field);
                remaining = new_input;
                
                // Try to consume optional comma
                if let Ok((new_input, _)) = opt(ws(char(',')))(remaining) {
                    remaining = new_input;
                }
            }
            Err(_) => {
                // Skip to next comma or closing brace
                remaining = skip_to_next_field_or_end(remaining);
            }
        }
    }
    
    Ok((remaining, fields))
}

fn field_assign_resilient(input: &str) -> IResult<&str, FieldAssign> {
    let (input, name) = ws(identifier)(input)?;
    let (input, _) = ws(char(':'))(input)?;
    let (input, value) = ws(expr_resilient)(input)?;
    
    Ok((input, FieldAssign {
        name: name.to_string(),
        value,
    }))
}

fn enum_variant_list_resilient(input: &str) -> IResult<&str, Vec<EnumVariant>> {
    let mut variants = Vec::new();
    let mut remaining = input;
    
    // Skip initial whitespace
    if let Ok((new_input, _)) = multispace_and_comments(remaining) {
        remaining = new_input;
    }
    
    // Parse variants with error recovery
    while !remaining.is_empty() && !remaining.starts_with('}') {
        match ws(enum_variant)(remaining) {
            Ok((new_input, variant)) => {
                variants.push(variant);
                remaining = new_input;
                
                // Try to consume optional comma
                if let Ok((new_input, _)) = opt(ws(char(',')))(remaining) {
                    remaining = new_input;
                }
            }
            Err(_) => {
                // Skip to next comma or closing brace
                remaining = skip_to_next_field_or_end(remaining);
            }
        }
    }
    
    Ok((remaining, variants))
}

fn expr_resilient(input: &str) -> IResult<&str, Expr> {
    // Try the regular expression parser first
    match expr(input) {
        Ok(result) => Ok(result),
        Err(_) => {
            // If regular parsing fails, try to create a fallback expression
            // For now, just try to parse an identifier or literal
            alt((
                map(identifier, |s| Expr::Identifier(s.to_string())),
                map(literal, Expr::Literal),
                // Fallback: create a placeholder expression
                map(take_while1(|c: char| !c.is_whitespace() && c != ',' && c != '}'), 
                    |s: &str| Expr::Identifier(format!("__error__{}", s))),
            ))(input)
        }
    }
}

// Utility functions for error recovery

fn skip_to_next_statement(input: &str) -> &str {
    // Look for keywords that start statements: "type", "enum", identifier followed by {, etc.
    let mut chars = input.chars();
    let mut pos = 0;
    
    while let Some(ch) = chars.next() {
        if ch == '\n' {
            // Try to find a statement start after newline
            let remaining = &input[pos + ch.len_utf8()..];
            if let Ok((_, _)) = multispace_and_comments(remaining) {
                if remaining.trim_start().starts_with("type ") ||
                   remaining.trim_start().starts_with("enum ") ||
                   is_instance_decl_start(remaining.trim_start()) {
                    return remaining.trim_start();
                }
            }
        }
        pos += ch.len_utf8();
    }
    
    "" // Return empty if no next statement found
}

fn skip_to_closing_brace(input: &str) -> IResult<&str, ()> {
    let mut brace_count = 1;
    let mut pos = 0;
    
    for ch in input.chars() {
        match ch {
            '{' => brace_count += 1,
            '}' => {
                brace_count -= 1;
                if brace_count == 0 {
                    return Ok((&input[pos + 1..], ()));
                }
            }
            _ => {}
        }
        pos += ch.len_utf8();
    }
    
    Err(NomErr::Error(nom::error::Error::new(input, ErrorKind::Char)))
}

fn skip_to_next_field_or_end(input: &str) -> &str {
    // Skip to next comma or closing brace, handling nested braces and parentheses
    let mut pos = 0;
    let mut brace_depth = 0;
    let mut paren_depth = 0;
    let mut in_string = false;
    let mut escape_next = false;
    
    for ch in input.chars() {
        if escape_next {
            escape_next = false;
            pos += ch.len_utf8();
            continue;
        }
        
        match ch {
            '\\' if in_string => escape_next = true,
            '"' => in_string = !in_string,
            '{' if !in_string => brace_depth += 1,
            '}' if !in_string => {
                if brace_depth == 0 {
                    return &input[pos..];
                }
                brace_depth -= 1;
            },
            '(' if !in_string => paren_depth += 1,
            ')' if !in_string => paren_depth -= 1,
            ',' if !in_string && brace_depth == 0 && paren_depth == 0 => {
                return &input[pos..];
            },
            _ => {}
        }
        pos += ch.len_utf8();
    }
    ""
}

fn is_instance_decl_start(input: &str) -> bool {
    // Check if this looks like "TypeName instance_name {"
    if let Ok((remaining, _)) = type_name(input) {
        if let Ok((remaining, _)) = ws(identifier)(remaining) {
            if let Ok((_, _)) = ws(char('{'))(remaining) {
                return true;
            }
        }
    }
    false
}

// Re-export the original parsers we're reusing
use crate::{
    multispace_and_comments, type_name, identifier, base_type, field_decl, solve_call,
    expr, literal, enum_variant, ws
};