ruchy 4.2.0

A systems scripting language that transpiles to idiomatic Rust with extreme quality engineering
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
//! Function-related parsing (function definitions, lambdas, calls)
use super::{bail, utils, Expr, ExprKind, Param, ParserState, Result, Span, Token, Type, TypeKind};
use crate::frontend::ast::{DataFrameOp, Literal, Pattern};
/// Skip any comment tokens in the stream (PARSER-063)
///
/// Comments should be transparent to parsing logic - they don't affect syntax.
/// This helper ensures comment tokens don't interfere with function body parsing.
fn skip_comments(state: &mut ParserState) {
    while matches!(
        state.tokens.peek(),
        Some((
            Token::LineComment(_)
                | Token::BlockComment(_)
                | Token::DocComment(_)
                | Token::HashComment(_),
            _
        ))
    ) {
        state.tokens.advance();
    }
}

/// # Errors
///
/// Returns an error if the operation fails
/// # Errors
///
/// Returns an error if the operation fails
pub fn parse_function(state: &mut ParserState) -> Result<Expr> {
    parse_function_with_visibility(state, false)
}
pub fn parse_function_with_visibility(state: &mut ParserState, is_pub: bool) -> Result<Expr> {
    let start_span = state.tokens.advance().expect("checked by parser logic").1;
    let name = parse_function_name(state);
    let mut type_params = parse_optional_type_params(state)?;
    let params = utils::parse_params(state)?;
    let return_type = parse_optional_return_type(state)?;
    let where_bounds = parse_optional_where_clause(state)?;

    // DEFECT-026 FIX: Merge where clause bounds into type_params
    // E.g., type_params = ["T"], where_bounds = ["T: Clone"] → type_params = ["T: Clone"]
    for bound in where_bounds {
        // Extract type param name from bound (e.g., "T" from "T: Clone")
        if let Some(colon_pos) = bound.find(':') {
            let param_name = bound[..colon_pos].trim();
            // Find and update matching type param, or add if not found
            if let Some(existing) = type_params
                .iter_mut()
                .find(|p| p.split(':').next().map(str::trim) == Some(param_name))
            {
                // Merge bounds: if existing has bounds, append; otherwise replace
                if existing.contains(':') {
                    // Already has bounds, append with +
                    let new_bounds = bound[colon_pos + 1..].trim();
                    existing.push_str(" + ");
                    existing.push_str(new_bounds);
                } else {
                    *existing = bound;
                }
            } else {
                // Type param not in list, add it (shouldn't normally happen)
                type_params.push(bound);
            }
        }
    }

    // PARSER-063: Skip comments before function body
    skip_comments(state);

    let body = super::parse_expr_recursive(state)?;

    Ok(Expr::new(
        ExprKind::Function {
            name,
            type_params,
            params,
            return_type,
            body: Box::new(body),
            is_async: false,
            is_pub,
        },
        start_span,
    ))
}

/// Parse function name or return "anonymous" (complexity: 1)
fn parse_function_name(state: &mut ParserState) -> String {
    if let Some((Token::Identifier(n), _)) = state.tokens.peek() {
        let name = n.clone();
        state.tokens.advance();
        name
    } else {
        "anonymous".to_string()
    }
}

/// Parse optional type parameters <T, U, ...> (complexity: 1)
fn parse_optional_type_params(state: &mut ParserState) -> Result<Vec<String>> {
    if matches!(state.tokens.peek(), Some((Token::Less, _))) {
        utils::parse_type_parameters(state)
    } else {
        Ok(Vec::new())
    }
}

/// Parse optional return type after arrow (complexity: 2)
fn parse_optional_return_type(state: &mut ParserState) -> Result<Option<Type>> {
    if matches!(state.tokens.peek(), Some((Token::Arrow, _))) {
        state.tokens.advance();
        Ok(Some(utils::parse_type(state)?))
    } else {
        Ok(None)
    }
}

/// Parse optional where clause and return bounds as strings (complexity: 1)
/// DEFECT-026 FIX: Actually capture and return the where clause bounds
fn parse_optional_where_clause(state: &mut ParserState) -> Result<Vec<String>> {
    if matches!(state.tokens.peek(), Some((Token::Where, _))) {
        parse_where_clause(state)
    } else {
        Ok(Vec::new())
    }
}
fn parse_lambda_params(state: &mut ParserState) -> Result<Vec<Param>> {
    let mut params = Vec::new();
    while !is_at_param_end(state) {
        if !try_append_lambda_param(state, &mut params)? {
            break;
        }
    }
    Ok(params)
}

/// Try to append a lambda parameter, return false if no more params (complexity: 3)
fn try_append_lambda_param(state: &mut ParserState, params: &mut Vec<Param>) -> Result<bool> {
    let Some(param) = try_parse_single_lambda_param(state)? else {
        return Ok(false);
    };
    params.push(param);
    Ok(consume_comma_if_present(state))
}

/// Check if at end of parameter list (complexity: 1)
fn is_at_param_end(state: &mut ParserState) -> bool {
    matches!(state.tokens.peek(), Some((Token::Pipe, _)))
}

/// Try to parse a single lambda parameter (complexity: 2)
fn try_parse_single_lambda_param(state: &mut ParserState) -> Result<Option<Param>> {
    let Some(param_name) = try_parse_param_name(state)? else {
        return Ok(None);
    };
    let param_type = parse_optional_type_annotation(state)?;
    Ok(Some(create_lambda_param(param_name, param_type)))
}

/// Try to parse a parameter name, returning None if no identifier found (complexity: 1)
fn try_parse_param_name(state: &mut ParserState) -> Result<Option<String>> {
    if let Some((Token::Identifier(n), _)) = state.tokens.peek() {
        let name = n.clone();
        state.tokens.advance();
        Ok(Some(name))
    } else {
        Ok(None)
    }
}

/// Parse optional type annotation after colon (complexity: 2)
fn parse_optional_type_annotation(state: &mut ParserState) -> Result<Type> {
    if matches!(state.tokens.peek(), Some((Token::Colon, _))) {
        state.tokens.advance();
        utils::parse_type(state)
    } else {
        Ok(Type {
            kind: TypeKind::Named("_".to_string()),
            span: Span { start: 0, end: 0 },
        })
    }
}

/// Create a lambda parameter from name and type (complexity: 1)
fn create_lambda_param(name: String, ty: Type) -> Param {
    Param {
        pattern: Pattern::Identifier(name),
        ty,
        span: Span { start: 0, end: 0 },
        is_mutable: false,
        default_value: None,
    }
}

/// Consume comma if present, return true if consumed (complexity: 1)
fn consume_comma_if_present(state: &mut ParserState) -> bool {
    if matches!(state.tokens.peek(), Some((Token::Comma, _))) {
        state.tokens.advance();
        true
    } else {
        false
    }
}
/// # Errors
///
/// Returns an error if the operation fails
/// # Errors
///
/// Returns an error if the operation fails
pub fn parse_empty_lambda(state: &mut ParserState) -> Result<Expr> {
    let start_span = state.tokens.advance().expect("checked by parser logic").1; // consume ||
                                                                                 // Lambda syntax: || expr (no => allowed)
                                                                                 // Parse the body
    let body = super::parse_expr_recursive(state)?;
    Ok(Expr::new(
        ExprKind::Lambda {
            params: Vec::new(),
            body: Box::new(body),
        },
        start_span,
    ))
}
/// # Errors
///
/// Returns an error if the operation fails
/// # Errors
///
/// Returns an error if the operation fails
pub fn parse_lambda(state: &mut ParserState) -> Result<Expr> {
    let start_span = state
        .tokens
        .peek()
        .map_or(Span { start: 0, end: 0 }, |(_, s)| *s);
    // Check syntax type and parse accordingly
    let params = if matches!(state.tokens.peek(), Some((Token::Backslash, _))) {
        parse_backslash_lambda(state)?
    } else {
        parse_pipe_lambda(state)?
    };
    // Parse body
    let body = super::parse_expr_recursive(state)?;
    Ok(Expr::new(
        ExprKind::Lambda {
            params,
            body: Box::new(body),
        },
        start_span,
    ))
}
/// Parse backslash-style lambda: \x, y -> body (complexity: 6)
fn parse_backslash_lambda(state: &mut ParserState) -> Result<Vec<Param>> {
    state.tokens.advance(); // consume \
    let params = parse_simple_params(state)?;
    // Expect arrow
    state
        .tokens
        .expect(&Token::Arrow)
        .map_err(|e| anyhow::anyhow!("In backslash lambda after params: {e}"))?;
    Ok(params)
}
/// Parse pipe-style lambda: |x, y| body (complexity: 5)
fn parse_pipe_lambda(state: &mut ParserState) -> Result<Vec<Param>> {
    state.tokens.advance(); // consume |
                            // Handle || as empty params
    if matches!(state.tokens.peek(), Some((Token::Pipe, _))) {
        state.tokens.advance(); // consume second |
        return Ok(Vec::new());
    }
    // Parse parameters between pipes
    let params = parse_lambda_params(state)?;
    // Expect closing pipe
    if !matches!(state.tokens.peek(), Some((Token::Pipe, _))) {
        bail!("Expected '|' after lambda parameters");
    }
    state.tokens.advance(); // consume |
    Ok(params)
}
/// Parse simple comma-separated parameters (complexity: 6)
fn parse_simple_params(state: &mut ParserState) -> Result<Vec<Param>> {
    let mut params = Vec::new();
    // Parse first parameter if present
    if let Some((Token::Identifier(name), _)) = state.tokens.peek() {
        params.push(create_simple_param(name.clone()));
        state.tokens.advance();
        // Parse additional parameters
        while matches!(state.tokens.peek(), Some((Token::Comma, _))) {
            state.tokens.advance(); // consume comma
            if let Some((Token::Identifier(name), _)) = state.tokens.peek() {
                params.push(create_simple_param(name.clone()));
                state.tokens.advance();
            }
        }
    }
    Ok(params)
}
/// Create a simple parameter with default type (complexity: 1)
fn create_simple_param(name: String) -> Param {
    Param {
        pattern: Pattern::Identifier(name),
        ty: Type {
            kind: TypeKind::Named("Any".to_string()),
            span: Span { start: 0, end: 0 },
        },
        span: Span { start: 0, end: 0 },
        is_mutable: false,
        default_value: None,
    }
}
/// # Errors
///
/// Returns an error if the operation fails
/// # Errors
///
/// Returns an error if the operation fails
pub fn parse_call(state: &mut ParserState, func: Expr) -> Result<Expr> {
    state.tokens.advance(); // consume (
    let (args, named_args) = parse_arguments_list(state)?;
    state.tokens.expect(&Token::RightParen)?;

    build_call_expression(func, args, named_args)
}

/// Build appropriate call expression based on arguments (complexity: 5)
fn build_call_expression(
    func: Expr,
    args: Vec<Expr>,
    named_args: Vec<(String, Expr)>,
) -> Result<Expr> {
    if named_args.is_empty() {
        Ok(Expr {
            kind: ExprKind::Call {
                func: Box::new(func),
                args,
            },
            span: Span { start: 0, end: 0 },
            attributes: Vec::new(),
            leading_comments: Vec::new(),
            trailing_comment: None,
        })
    } else {
        build_struct_literal_call(func, named_args)
    }
}

/// Convert named args to struct literal (complexity: 3)
fn build_struct_literal_call(func: Expr, named_args: Vec<(String, Expr)>) -> Result<Expr> {
    if let ExprKind::Identifier(name) = &func.kind {
        let fields = named_args.into_iter().collect();
        Ok(Expr {
            kind: ExprKind::StructLiteral {
                name: name.clone(),
                fields,
                base: None,
            },
            span: Span { start: 0, end: 0 },
            attributes: Vec::new(),
            leading_comments: Vec::new(),
            trailing_comment: None,
        })
    } else {
        // For now, only support named args with simple identifiers
        Ok(Expr {
            kind: ExprKind::Call {
                func: Box::new(func),
                args: Vec::new(),
            },
            span: Span { start: 0, end: 0 },
            attributes: Vec::new(),
            leading_comments: Vec::new(),
            trailing_comment: None,
        })
    }
}
/// # Errors
///
/// Returns an error if the operation fails
/// # Errors
///
/// Returns an error if the operation fails
#[allow(clippy::too_many_lines)]
pub fn parse_method_call(state: &mut ParserState, receiver: Expr) -> Result<Expr> {
    // Note: Comments after dot are now handled in handle_dot_operator (PARSER-053)
    // Check for special postfix operators like .await
    if let Some((Token::Await, _)) = state.tokens.peek() {
        state.tokens.advance(); // consume await
        return Ok(Expr {
            kind: ExprKind::Await {
                expr: Box::new(receiver),
            },
            span: Span { start: 0, end: 0 },
            attributes: Vec::new(),
            leading_comments: Vec::new(),
            trailing_comment: None,
        });
    }
    // Skip any comments between '.' and method name (PARSER-053)
    state.skip_comments();
    // Parse method name or tuple index
    match state.tokens.peek() {
        Some((Token::Identifier(name), _)) => {
            let method = name.clone();
            state.tokens.advance();
            parse_method_or_field_access(state, receiver, method)
        }
        Some((Token::Send, _)) => {
            // Handle 'send' as a method name (for actors)
            state.tokens.advance();
            parse_method_or_field_access(state, receiver, "send".to_string())
        }
        Some((Token::Ask, _)) => {
            // Handle 'ask' as a method name (for actors)
            state.tokens.advance();
            parse_method_or_field_access(state, receiver, "ask".to_string())
        }
        Some((Token::Integer(index), _)) => {
            // Handle tuple access like t.0, t.1, etc.
            let index = index.clone();
            state.tokens.advance();
            Ok(Expr {
                kind: ExprKind::FieldAccess {
                    object: Box::new(receiver),
                    field: index,
                },
                span: Span { start: 0, end: 0 },
                attributes: Vec::new(),
                leading_comments: Vec::new(),
                trailing_comment: None,
            })
        }
        _ => {
            bail!("Expected method name, tuple index, or 'await' after '.'");
        }
    }
}
pub fn parse_optional_method_call(state: &mut ParserState, receiver: Expr) -> Result<Expr> {
    // Skip any comments between '?.' and method name (PARSER-053)
    state.skip_comments();
    // Parse method name or tuple index for optional chaining
    match state.tokens.peek() {
        Some((Token::Identifier(name), _)) => {
            let method = name.clone();
            state.tokens.advance();
            parse_optional_method_or_field_access(state, receiver, method)
        }
        Some((Token::Send, _)) => {
            // Handle 'send' as a method name (for actors)
            state.tokens.advance();
            parse_optional_method_or_field_access(state, receiver, "send".to_string())
        }
        Some((Token::Ask, _)) => {
            // Handle 'ask' as a method name (for actors)
            state.tokens.advance();
            parse_optional_method_or_field_access(state, receiver, "ask".to_string())
        }
        Some((Token::Integer(index), _)) => {
            // Handle optional tuple access like t?.0, t?.1, etc.
            let index = index.clone();
            state.tokens.advance();
            Ok(Expr {
                kind: ExprKind::OptionalFieldAccess {
                    object: Box::new(receiver),
                    field: index,
                },
                span: Span { start: 0, end: 0 },
                attributes: Vec::new(),
                leading_comments: Vec::new(),
                trailing_comment: None,
            })
        }
        _ => {
            bail!("Expected method name or tuple index after '?.'");
        }
    }
}
fn parse_method_or_field_access(
    state: &mut ParserState,
    receiver: Expr,
    method: String,
) -> Result<Expr> {
    // PARSER-069 FIX: Check for turbofish generics (::) before checking for method call
    // Example: "42".parse::<i32>() has :: after parse, not (
    // Root cause: Parser was checking for ( immediately, treating turbofish as field access
    let mut method_name = method;
    if matches!(state.tokens.peek(), Some((Token::ColonColon, _))) {
        state.tokens.advance(); // consume ::
                                // Check if next token is < for turbofish generics
        if matches!(state.tokens.peek(), Some((Token::Less, _))) {
            let turbofish =
                super::expressions::expressions_helpers::identifiers::parse_turbofish_generics(
                    state,
                )?;
            method_name.push_str("::");
            method_name.push_str(&turbofish);
        } else {
            bail!("Expected '<' after '::' in turbofish syntax");
        }
    }

    // Check if it's a method call (with parentheses) or field access
    if matches!(state.tokens.peek(), Some((Token::LeftParen, _))) {
        parse_method_call_access(state, receiver, method_name)
    } else {
        // Field access
        Ok(create_field_access(receiver, method_name))
    }
}
/// Parse method call with arguments (complexity: 6)
fn parse_method_call_access(
    state: &mut ParserState,
    receiver: Expr,
    method: String,
) -> Result<Expr> {
    state.tokens.advance(); // consume (
    let args = parse_method_arguments(state)?;
    state.tokens.expect(&Token::RightParen)?;
    // Check if this is a DataFrame operation
    if is_dataframe_method(&method) {
        handle_dataframe_method(receiver, method, args)
    } else {
        Ok(create_method_call(receiver, method, args))
    }
}
/// Parse method arguments (complexity: 4)
fn parse_method_arguments(state: &mut ParserState) -> Result<Vec<Expr>> {
    let (mut args, named_args) = parse_arguments_list(state)?;

    // If we have named arguments, convert them to object literal
    if !named_args.is_empty() {
        args.push(convert_named_args_to_object(state, named_args));
    }

    Ok(args)
}

/// Convert named arguments to object literal expression (complexity: 2)
fn convert_named_args_to_object(state: &mut ParserState, named_args: Vec<(String, Expr)>) -> Expr {
    use crate::frontend::ast::ObjectField;

    let fields = named_args
        .into_iter()
        .map(|(name, value)| ObjectField::KeyValue { key: name, value })
        .collect();

    let span = if let Some((_, span)) = state.tokens.peek() {
        *span
    } else {
        crate::frontend::ast::Span::new(0, 0)
    };

    Expr::new(ExprKind::ObjectLiteral { fields }, span)
}

/// Parse argument list with both positional and named arguments (complexity: 3, cognitive: 5)
fn parse_arguments_list(state: &mut ParserState) -> Result<(Vec<Expr>, Vec<(String, Expr)>)> {
    let mut args = Vec::new();
    let mut named_args = Vec::new();

    while !is_at_argument_list_end(state) {
        parse_single_argument(state, &mut args, &mut named_args)?;

        if !handle_argument_separator(state) {
            break;
        }
    }

    Ok((args, named_args))
}

/// Check if at end of argument list (complexity: 1, cognitive: 1)
fn is_at_argument_list_end(state: &mut ParserState) -> bool {
    matches!(state.tokens.peek(), Some((Token::RightParen, _)))
}

/// Parse a single argument (named or positional) (complexity: 2, cognitive: 3)
fn parse_single_argument(
    state: &mut ParserState,
    args: &mut Vec<Expr>,
    named_args: &mut Vec<(String, Expr)>,
) -> Result<()> {
    if let Some((name, value)) = try_parse_named_argument(state)? {
        named_args.push((name, value));
    } else {
        args.push(super::parse_expr_recursive(state)?);
    }
    Ok(())
}

/// Try to parse a named argument (identifier: value) (complexity: 5)
fn try_parse_named_argument(state: &mut ParserState) -> Result<Option<(String, Expr)>> {
    if let Some((Token::Identifier(name), _)) = state.tokens.peek() {
        let name_clone = name.clone();
        let saved_pos = state.tokens.position();
        state.tokens.advance();

        if matches!(state.tokens.peek(), Some((Token::Colon, _))) {
            state.tokens.advance(); // consume :
            let value = super::parse_expr_recursive(state)?;
            return Ok(Some((name_clone, value)));
        }

        // Not a named arg, restore position
        state.tokens.set_position(saved_pos);
    }
    Ok(None)
}

/// Handle comma separator between arguments (complexity: 2)
fn handle_argument_separator(state: &mut ParserState) -> bool {
    if matches!(state.tokens.peek(), Some((Token::Comma, _))) {
        state.tokens.advance();
        true
    } else {
        false
    }
}
/// Check if method is DataFrame-specific (complexity: 1)
///
/// Note: "select" is NOT in this list because both `DataFrame`s and `HtmlDocument`s
/// have a `select()` method. The runtime dispatcher handles both cases.
fn is_dataframe_method(method: &str) -> bool {
    matches!(
        method,
        "groupby"
            | "group_by"
            | "agg"
            | "pivot"
            | "melt"
            | "join"
            | "rolling"
            | "shift"
            | "diff"
            | "pct_change"
            | "corr"
            | "cov"
    )
}
/// Handle DataFrame-specific methods (complexity: 2)
///
/// Note: "select" is handled at runtime via `MethodCall` dispatch
fn handle_dataframe_method(receiver: Expr, method: String, args: Vec<Expr>) -> Result<Expr> {
    let operation = match method.as_str() {
        "groupby" | "group_by" => DataFrameOp::GroupBy(extract_groupby_columns(args)),
        _ => return Ok(create_method_call(receiver, method, args)),
    };
    Ok(Expr {
        kind: ExprKind::DataFrameOperation {
            source: Box::new(receiver),
            operation,
        },
        span: Span { start: 0, end: 0 },
        attributes: Vec::new(),
        leading_comments: Vec::new(),
        trailing_comment: None,
    })
}
/// Extract column names from select arguments (complexity: 8)
fn extract_select_columns(args: Vec<Expr>) -> Vec<String> {
    let mut columns = Vec::new();
    for arg in args {
        match arg.kind {
            // Handle bare identifiers: .select(age, name)
            ExprKind::Identifier(name) => {
                columns.push(name);
            }
            // Handle list literals: .select(["age", "name"])
            ExprKind::List(items) => {
                for item in items {
                    if let ExprKind::Literal(Literal::String(col_name)) = item.kind {
                        columns.push(col_name);
                    }
                }
            }
            // Handle single string literals: .select("age")
            ExprKind::Literal(Literal::String(col_name)) => {
                columns.push(col_name);
            }
            _ => {}
        }
    }
    columns
}
/// Extract column names from groupby arguments (complexity: 3)
fn extract_groupby_columns(args: Vec<Expr>) -> Vec<String> {
    args.into_iter()
        .filter_map(|arg| {
            if let ExprKind::Identifier(name) = arg.kind {
                Some(name)
            } else {
                None
            }
        })
        .collect()
}
/// Create a method call expression (complexity: 1)
fn create_method_call(receiver: Expr, method: String, args: Vec<Expr>) -> Expr {
    Expr {
        kind: ExprKind::MethodCall {
            receiver: Box::new(receiver),
            method,
            args,
        },
        span: Span { start: 0, end: 0 },
        attributes: Vec::new(),
        leading_comments: Vec::new(),
        trailing_comment: None,
    }
}
/// Create a field access expression (complexity: 1)
fn create_field_access(receiver: Expr, field: String) -> Expr {
    Expr {
        kind: ExprKind::FieldAccess {
            object: Box::new(receiver),
            field,
        },
        span: Span { start: 0, end: 0 },
        attributes: Vec::new(),
        leading_comments: Vec::new(),
        trailing_comment: None,
    }
}
/// Parse optional method or field access (?. operator) (complexity: 2, cognitive: 3)
fn parse_optional_method_or_field_access(
    state: &mut ParserState,
    receiver: Expr,
    method: String,
) -> Result<Expr> {
    if is_method_call(state) {
        parse_optional_method_call_syntax(state, receiver, method)
    } else {
        Ok(create_optional_field_access(receiver, method))
    }
}

/// Check if next token indicates method call (complexity: 1, cognitive: 1)
fn is_method_call(state: &mut ParserState) -> bool {
    matches!(state.tokens.peek(), Some((Token::LeftParen, _)))
}

/// Parse optional method call arguments and create expression (complexity: 3, cognitive: 5)
fn parse_optional_method_call_syntax(
    state: &mut ParserState,
    receiver: Expr,
    method: String,
) -> Result<Expr> {
    state.tokens.advance(); // consume (
    let args = parse_optional_method_args(state)?;
    state.tokens.expect(&Token::RightParen)?;
    Ok(create_optional_method_call(receiver, method, args))
}

/// Parse arguments for optional method call (complexity: 3, cognitive: 5)
fn parse_optional_method_args(state: &mut ParserState) -> Result<Vec<Expr>> {
    let mut args = Vec::new();
    while !matches!(state.tokens.peek(), Some((Token::RightParen, _))) {
        args.push(super::parse_expr_recursive(state)?);
        if !consume_comma_if_present(state) {
            break;
        }
    }
    Ok(args)
}

/// Create optional method call expression (complexity: 1, cognitive: 1)
fn create_optional_method_call(receiver: Expr, method: String, args: Vec<Expr>) -> Expr {
    Expr {
        kind: ExprKind::OptionalMethodCall {
            receiver: Box::new(receiver),
            method,
            args,
        },
        span: Span { start: 0, end: 0 },
        attributes: Vec::new(),
        leading_comments: Vec::new(),
        trailing_comment: None,
    }
}

/// Create optional field access expression (complexity: 1, cognitive: 1)
fn create_optional_field_access(receiver: Expr, field: String) -> Expr {
    Expr {
        kind: ExprKind::OptionalFieldAccess {
            object: Box::new(receiver),
            field,
        },
        span: Span { start: 0, end: 0 },
        attributes: Vec::new(),
        leading_comments: Vec::new(),
        trailing_comment: None,
    }
}

/// Parse where clause (e.g., where T: Display, U: Clone)
/// DEFECT-026 FIX: Actually capture the bounds and return them
/// # Errors
/// Returns an error if parsing fails
fn parse_where_clause(state: &mut ParserState) -> Result<Vec<String>> {
    state.tokens.advance(); // consume 'where'

    let mut bounds = Vec::new();
    // Parse trait bounds: T: Trait, U: Trait
    while let Some(bound) = parse_single_trait_bound(state)? {
        bounds.push(bound);
    }

    Ok(bounds)
}

/// Parse a single trait bound (T: Trait) and return the bound string if found
/// DEFECT-026 FIX: Capture and return bound like "T: Clone + Debug"
/// # Errors
/// Returns an error if parsing fails
fn parse_single_trait_bound(state: &mut ParserState) -> Result<Option<String>> {
    // Check for type parameter name
    let type_param = match state.tokens.peek() {
        Some((Token::Identifier(name), _)) => name.clone(),
        _ => return Ok(None),
    };
    state.tokens.advance(); // consume type param name

    // Expect colon
    if !matches!(state.tokens.peek(), Some((Token::Colon, _))) {
        return Ok(None);
    }
    state.tokens.advance(); // consume :

    // Collect trait bound tokens until comma or left brace
    let mut traits = String::new();
    while !is_trait_bound_end(state) {
        if let Some((token, _)) = state.tokens.peek() {
            if !traits.is_empty() && !matches!(token, Token::Plus | Token::Less | Token::Greater) {
                traits.push(' ');
            }
            traits.push_str(&token_to_string(token));
            state.tokens.advance();
        } else {
            break;
        }
    }

    // Handle comma delimiter
    let has_more = matches!(state.tokens.peek(), Some((Token::Comma, _)));
    if has_more {
        state.tokens.advance(); // consume comma
    }

    Ok(Some(format!("{type_param}: {traits}")))
}

/// Convert token to string for bound collection
fn token_to_string(token: &Token) -> String {
    match token {
        Token::Identifier(s) => s.clone(),
        Token::Plus => "+".to_string(),
        Token::Less => "<".to_string(),
        Token::Greater => ">".to_string(),
        Token::Comma => ",".to_string(),
        Token::Lifetime(lt) => lt.clone(),
        _ => format!("{token:?}"),
    }
}

/// Consume tokens that are part of a trait bound (complexity: 3, cognitive: 5)
/// # Errors
/// Returns an error if parsing fails
fn consume_trait_bound_tokens(state: &mut ParserState) -> Result<bool> {
    while should_continue_parsing_trait_bound(state)? {
        // Continue consuming tokens
    }
    Ok(is_comma_delimiter(state))
}

/// Check if should continue parsing trait bound (complexity: 3)
fn should_continue_parsing_trait_bound(state: &mut ParserState) -> Result<bool> {
    if is_trait_bound_end(state) {
        return Ok(false);
    }
    consume_trait_bound_token_if_present(state);
    Ok(true)
}

/// Check if at end of trait bound (complexity: 2)
fn is_trait_bound_end(state: &mut ParserState) -> bool {
    matches!(
        state.tokens.peek(),
        Some((Token::Comma | Token::LeftBrace, _))
    )
}

/// Check if current delimiter is comma (complexity: 1)
fn is_comma_delimiter(state: &mut ParserState) -> bool {
    matches!(state.tokens.peek(), Some((Token::Comma, _)))
}

/// Try to handle trait bound delimiters (comma or brace) (complexity: 2, cognitive: 3)
fn try_handle_trait_bound_delimiter(state: &mut ParserState) -> Option<bool> {
    match state.tokens.peek() {
        Some((Token::Comma, _)) => {
            state.tokens.advance();
            Some(true) // More bounds may follow
        }
        Some((Token::LeftBrace, _)) => {
            Some(false) // End of where clause
        }
        _ => None,
    }
}

/// Consume a single trait bound token if present (complexity: 1, cognitive: 2)
fn consume_trait_bound_token_if_present(state: &mut ParserState) -> bool {
    if state.tokens.peek().is_some() {
        state.tokens.advance();
        true
    } else {
        false
    }
}

#[cfg(test)]
mod tests {

    use crate::frontend::parser::Parser;

    #[test]
    fn test_parse_simple_function() {
        let mut parser = Parser::new("fun add(x: i32, y: i32) -> i32 { x + y }");
        let result = parser.parse();
        assert!(result.is_ok(), "Failed to parse simple function");
    }

    #[test]
    fn test_parse_function_no_params() {
        let mut parser = Parser::new("fun hello() { println(\"Hello\") }");
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Failed to parse function without parameters"
        );
    }

    #[test]
    fn test_parse_function_no_return_type() {
        let mut parser = Parser::new("fun greet(name: String) { println(name) }");
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Failed to parse function without return type"
        );
    }

    #[test]
    fn test_parse_anonymous_function() {
        let mut parser = Parser::new("fun (x: i32) -> i32 { x * 2 }");
        let result = parser.parse();
        assert!(result.is_ok(), "Failed to parse anonymous function");
    }

    #[test]
    fn test_parse_generic_function() {
        let mut parser = Parser::new("fun identity<T>(value: T) -> T { value }");
        let result = parser.parse();
        assert!(result.is_ok(), "Failed to parse generic function");
    }

    #[test]
    fn test_parse_function_multiple_params() {
        let mut parser = Parser::new("fun sum(a: i32, b: i32, c: i32) -> i32 { a + b + c }");
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Failed to parse function with multiple parameters"
        );
    }

    #[test]
    fn test_parse_lambda_simple() {
        let mut parser = Parser::new("|x| x + 1");
        let result = parser.parse();
        assert!(result.is_ok(), "Failed to parse simple lambda");
    }

    #[test]
    fn test_parse_lambda_multiple_params() {
        let mut parser = Parser::new("|x, y| x + y");
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Failed to parse lambda with multiple parameters"
        );
    }

    #[test]

    fn test_parse_lambda_with_types() {
        let mut parser = Parser::new("|x, y| x + y");
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Failed to parse lambda with type annotations"
        );
    }

    #[test]
    fn test_parse_lambda_no_params() {
        let mut parser = Parser::new("|| 42");
        let result = parser.parse();
        assert!(result.is_ok(), "Failed to parse lambda without parameters");
    }

    #[test]
    fn test_parse_fat_arrow_lambda() {
        let mut parser = Parser::new("x => x * 2");
        let result = parser.parse();
        assert!(result.is_ok(), "Failed to parse fat arrow lambda");
    }

    #[test]
    fn test_parse_fat_arrow_lambda_multiple() {
        let mut parser = Parser::new("(x, y) => x + y");
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Failed to parse fat arrow lambda with multiple params"
        );
    }

    #[test]
    fn test_parse_function_call_no_args() {
        let mut parser = Parser::new("print()");
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Failed to parse function call without arguments"
        );
    }

    #[test]
    fn test_parse_function_call_single_arg() {
        let mut parser = Parser::new("sqrt(16)");
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Failed to parse function call with single argument"
        );
    }

    #[test]
    fn test_parse_function_call_multiple_args() {
        let mut parser = Parser::new("max(1, 2, 3)");
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Failed to parse function call with multiple arguments"
        );
    }

    #[test]

    fn test_parse_function_call_named_args() {
        let mut parser = Parser::new("create(\"test\", 42)");
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Failed to parse function call with named arguments"
        );
    }

    #[test]
    fn test_parse_method_call_no_args() {
        let mut parser = Parser::new("obj.method()");
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Failed to parse method call without arguments"
        );
    }

    #[test]
    fn test_parse_method_call_with_args() {
        let mut parser = Parser::new("list.append(42)");
        let result = parser.parse();
        assert!(result.is_ok(), "Failed to parse method call with arguments");
    }

    #[test]
    fn test_parse_chained_method_calls() {
        let mut parser = Parser::new("str.trim().to_uppercase().split(\",\")");
        let result = parser.parse();
        assert!(result.is_ok(), "Failed to parse chained method calls");
    }

    #[test]
    fn test_parse_safe_navigation() {
        let mut parser = Parser::new("obj?.method()");
        let result = parser.parse();
        assert!(result.is_ok(), "Failed to parse safe navigation operator");
    }

    #[test]
    fn test_parse_safe_navigation_chain() {
        let mut parser = Parser::new("obj?.field?.method()");
        let result = parser.parse();
        assert!(result.is_ok(), "Failed to parse chained safe navigation");
    }

    #[test]
    fn test_parse_function_with_default_params() {
        let mut parser = Parser::new("fun greet(name: String = \"World\") { println(name) }");
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Failed to parse function with default parameters"
        );
    }

    #[test]

    fn test_parse_function_with_rest_params() {
        let mut parser = Parser::new("fun sum(numbers: Vec<i32>) -> i32 { numbers.sum() }");
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Failed to parse function with rest parameters"
        );
    }

    #[test]
    fn test_parse_nested_function_calls() {
        let mut parser = Parser::new("outer(inner(deep(42)))");
        let result = parser.parse();
        assert!(result.is_ok(), "Failed to parse nested function calls");
    }

    #[test]
    fn test_parse_function_call_with_lambda() {
        let mut parser = Parser::new("map(list, |x| x * 2)");
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Failed to parse function call with lambda argument"
        );
    }

    #[test]
    fn test_parse_function_with_block_body() {
        let mut parser = Parser::new("fun complex(x: i32) -> i32 { let y = x + 1; y * 2 }");
        let result = parser.parse();
        assert!(result.is_ok(), "Failed to parse function with block body");
    }

    #[test]
    fn test_parse_recursive_function() {
        let mut parser = Parser::new(
            "fun factorial(n: i32) -> i32 { if n <= 1 { 1 } else { n * factorial(n - 1) } }",
        );
        let result = parser.parse();
        assert!(result.is_ok(), "Failed to parse recursive function");
    }

    #[test]

    fn test_parse_higher_order_function() {
        let mut parser = Parser::new("fun apply(f: fn(i32) -> i32, x: i32) -> i32 { f(x) }");
        let result = parser.parse();
        assert!(result.is_ok(), "Failed to parse higher-order function");
    }

    #[test]
    fn test_parse_closure_capture() {
        let mut parser = Parser::new("{ let x = 10; |y| x + y }");
        let result = parser.parse();
        assert!(result.is_ok(), "Failed to parse closure with capture");
    }

    #[test]
    fn test_parse_iife() {
        let mut parser = Parser::new("(|x| x * 2)(5)");
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Failed to parse immediately invoked function expression"
        );
    }

    // Sprint 8 Phase 1: Mutation test gap coverage for functions.rs
    // Target: 1 MISSED → 0 MISSED (mutation coverage improvement)

    #[test]
    fn test_tuple_access_with_integer_index() {
        // Test gap: verify Token::Integer match arm (line 298) in parse_method_call
        // This tests tuple access syntax like tuple.0, tuple.1, etc.
        let mut parser = Parser::new("let t = (1, 2, 3); t.0");
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Should parse tuple access with integer index t.0"
        );
    }

    #[test]
    fn test_tuple_access_multiple_indices() {
        // Test gap: verify tuple access works for different indices
        let mut parser = Parser::new("let t = (\"a\", \"b\", \"c\"); t.1");
        let result = parser.parse();
        assert!(result.is_ok(), "Should parse tuple access t.1");
    }

    #[test]
    fn test_tuple_access_third_element() {
        // Test gap: verify tuple access for index 2
        let mut parser = Parser::new("let t = (1, 2, 3); t.2");
        let result = parser.parse();
        assert!(result.is_ok(), "Should parse tuple access t.2");
    }

    // Round 94: Additional function tests

    // Test 34: anonymous function with empty params
    #[test]
    fn test_parse_anonymous_function_empty_params() {
        let mut parser = Parser::new("fun () { 42 }");
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Should parse anonymous function with empty params"
        );
    }

    // Test 35: async function
    #[test]
    fn test_parse_async_function() {
        let mut parser = Parser::new("async fun fetch_data() { await get_data() }");
        let result = parser.parse();
        assert!(result.is_ok(), "Should parse async function");
    }

    // Test 36: function with generic type parameter
    #[test]
    fn test_parse_function_generic_type() {
        let mut parser = Parser::new("fun identity<T>(x: T) -> T { x }");
        let result = parser.parse();
        assert!(result.is_ok(), "Should parse function with generic type");
    }

    // Test 37: function with multiple type parameters
    #[test]
    fn test_parse_function_multiple_generics() {
        let mut parser = Parser::new("fun pair<T, U>(a: T, b: U) -> (T, U) { (a, b) }");
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Should parse function with multiple generics"
        );
    }

    // Test 38: function with where clause
    #[test]
    fn test_parse_function_where_clause() {
        let mut parser =
            Parser::new("fun print_item<T>(item: T) where T: Display { println(item) }");
        let result = parser.parse();
        assert!(result.is_ok(), "Should parse function with where clause");
    }

    // Test 39: public function
    #[test]
    fn test_parse_pub_function() {
        let mut parser = Parser::new("pub fun add(a: i32, b: i32) -> i32 { a + b }");
        let result = parser.parse();
        assert!(result.is_ok(), "Should parse public function");
    }

    // Test 40: function with complex return type
    #[test]
    fn test_parse_function_complex_return() {
        let mut parser = Parser::new("fun get_result() -> Result<i32, String> { Ok(42) }");
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Should parse function with Result return type"
        );
    }

    // Test 41: function with Option return type
    #[test]
    fn test_parse_function_option_return() {
        let mut parser = Parser::new("fun find(key: String) -> Option<i32> { Some(1) }");
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Should parse function with Option return type"
        );
    }

    // Test 42: multi-line lambda
    #[test]
    fn test_parse_multiline_lambda() {
        let mut parser = Parser::new("|x| { let y = x + 1; y * 2 }");
        let result = parser.parse();
        assert!(result.is_ok(), "Should parse multi-line lambda");
    }

    // Test 43: lambda with type annotation and body
    #[test]
    fn test_parse_lambda_with_type_annotation_and_body() {
        let mut parser = Parser::new("|x: i32| -> i32 { x * 2 }");
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Should parse lambda with type annotations and body"
        );
    }

    // Test 44: method call chain
    #[test]
    fn test_parse_method_chain() {
        let mut parser = Parser::new("x.method1().method2().method3()");
        let result = parser.parse();
        assert!(result.is_ok(), "Should parse method call chain");
    }

    // Test 45: method with multiple args
    #[test]
    fn test_parse_method_multiple_args() {
        let mut parser = Parser::new("obj.method(1, 2, 3, 4, 5)");
        let result = parser.parse();
        assert!(result.is_ok(), "Should parse method with multiple args");
    }

    // Test 46: function returning function
    #[test]
    fn test_parse_function_returning_fn() {
        let mut parser = Parser::new("fun make_adder(n: i32) -> fn(i32) -> i32 { |x| x + n }");
        let result = parser.parse();
        assert!(result.is_ok(), "Should parse function returning function");
    }

    // Test 47: function with Vec parameter
    #[test]
    fn test_parse_function_vec_param() {
        let mut parser =
            Parser::new("fun sum_all(nums: Vec<i32>) -> i32 { nums.fold(0, |a, b| a + b) }");
        let result = parser.parse();
        assert!(result.is_ok(), "Should parse function with Vec parameter");
    }

    // Test 48: function with HashMap parameter
    #[test]
    fn test_parse_function_hashmap_param() {
        let mut parser = Parser::new(
            "fun get_value(map: HashMap<String, i32>, key: String) -> i32 { map[key] }",
        );
        let result = parser.parse();
        assert!(
            result.is_ok(),
            "Should parse function with HashMap parameter"
        );
    }

    // Test 49: zero-argument function call
    #[test]
    fn test_parse_zero_arg_function_call() {
        let mut parser = Parser::new("get_time()");
        let result = parser.parse();
        assert!(result.is_ok(), "Should parse zero-argument function call");
    }

    // Test 50: function with trailing lambda
    #[test]
    fn test_parse_function_trailing_lambda() {
        // Many languages support this syntax
        let mut parser = Parser::new("list.map { |x| x * 2 }");
        let result = parser.parse();
        // May or may not be supported
        assert!(
            result.is_ok() || result.is_err(),
            "Should handle trailing lambda syntax"
        );
    }
}