horkos 0.2.0

Cloud infrastructure language where insecure code won't compile
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
//! Recursive descent parser for Horkos.
//!
//! Converts a token stream into an AST.

use crate::ast::*;
use crate::errors::Diagnostic;
use crate::lexer::{Token, TokenKind};

/// Parse a token stream into an AST.
pub fn parse(tokens: Vec<Token>, source: &str, filename: &str) -> Result<Program, Vec<Diagnostic>> {
    let mut parser = Parser::new(tokens, source, filename);
    parser.parse_program()
}

/// Recursive descent parser.
struct Parser<'a> {
    tokens: Vec<Token>,
    current: usize,
    _source: &'a str,
    filename: &'a str,
    errors: Vec<Diagnostic>,
}

impl<'a> Parser<'a> {
    fn new(tokens: Vec<Token>, source: &'a str, filename: &'a str) -> Self {
        Self {
            tokens,
            current: 0,
            _source: source,
            filename,
            errors: Vec::new(),
        }
    }

    // === Main Entry Point ===

    fn parse_program(&mut self) -> Result<Program, Vec<Diagnostic>> {
        let mut statements = Vec::new();

        while !self.is_at_end() {
            match self.parse_statement() {
                Ok(stmt) => statements.push(stmt),
                Err(_) => {
                    // Error already recorded, try to synchronize
                    self.synchronize();
                }
            }
        }

        if self.errors.is_empty() {
            Ok(Program { statements })
        } else {
            Err(std::mem::take(&mut self.errors))
        }
    }

    // === Statement Parsing ===

    fn parse_statement(&mut self) -> Result<Spanned<Statement>, ()> {
        let token = self.peek();

        match &token.kind {
            TokenKind::Import => self.parse_import(),
            TokenKind::Val => self.parse_val_decl(),
            TokenKind::Module => self.parse_module(),
            TokenKind::Assert => self.parse_assert(),
            TokenKind::Hcl => self.parse_hcl_block(),
            TokenKind::Unsafe => self.parse_unsafe_stmt(),
            _ => {
                self.error(&format!("expected statement, found {}", token.kind));
                Err(())
            }
        }
    }

    fn parse_import(&mut self) -> Result<Spanned<Statement>, ()> {
        let start = self.expect(TokenKind::Import)?;

        let path = self.expect_string("import path")?;

        let alias = if self.check(&TokenKind::As) {
            self.advance();
            Some(self.expect_ident("import alias")?)
        } else {
            None
        };

        let span = start
            .span
            .merge(alias.as_ref().map(|a| a.span).unwrap_or(path.span));

        Ok(Spanned::new(
            Statement::Import(ImportStmt { path, alias }),
            span,
        ))
    }

    fn parse_val_decl(&mut self) -> Result<Spanned<Statement>, ()> {
        let start = self.expect(TokenKind::Val)?;

        let name = self.expect_ident("variable name")?;

        // Optional type annotation
        let type_ann = if self.check(&TokenKind::Colon) {
            self.advance();
            Some(self.parse_type()?)
        } else {
            None
        };

        self.expect(TokenKind::Eq)?;

        let value = self.parse_expr()?;
        let span = start.span.merge(value.span);

        Ok(Spanned::new(
            Statement::ValDecl(ValDecl {
                name,
                type_ann,
                value,
            }),
            span,
        ))
    }

    fn parse_module(&mut self) -> Result<Spanned<Statement>, ()> {
        let start = self.expect(TokenKind::Module)?;
        let name = self.expect_ident("module name")?;
        self.expect(TokenKind::LBrace)?;

        let mut body = Vec::new();
        while !self.check(&TokenKind::RBrace) && !self.is_at_end() {
            body.push(self.parse_statement()?);
        }

        let end = self.expect(TokenKind::RBrace)?;
        let span = start.span.merge(end.span);

        Ok(Spanned::new(
            Statement::Module(ModuleDecl { name, body }),
            span,
        ))
    }

    fn parse_assert(&mut self) -> Result<Spanned<Statement>, ()> {
        let start = self.expect(TokenKind::Assert)?;
        self.expect(TokenKind::LParen)?;

        let condition = self.parse_expr()?;

        self.expect(TokenKind::Comma)?;

        let message = self.expect_string("assertion message")?;

        let end = self.expect(TokenKind::RParen)?;
        let span = start.span.merge(end.span);

        Ok(Spanned::new(
            Statement::Assert(AssertStmt { condition, message }),
            span,
        ))
    }

    fn parse_hcl_block(&mut self) -> Result<Spanned<Statement>, ()> {
        let start = self.expect(TokenKind::Hcl)?;
        self.expect(TokenKind::LParen)?;
        let reason = self.expect_string("HCL block reason")?;

        // Reject empty or whitespace-only reasons
        if reason.node.trim().is_empty() {
            self.errors.push(
                Diagnostic::error_at(
                    "HCL blocks require a non-empty justification",
                    reason.span,
                    self.filename,
                )
                .with_code(crate::errors::ErrorCode::UnexpectedToken)
                .with_primary_label("justification cannot be empty")
                .with_help("provide a reason: hcl(\"DynamoDB not yet supported\") { ... }"),
            );
            return Err(());
        }

        self.expect(TokenKind::RParen)?;
        self.expect(TokenKind::LBrace)?;

        // We need to consume everything until the matching RBrace.
        // Since the lexer has already tokenized the input, we can just consume tokens
        // and reconstruct the string, or we can look at the source span.
        // For simplicity and correctness with nested braces, we'll count braces.

        let content_start = self.peek().span.start as usize;
        let mut depth = 1;

        while depth > 0 && !self.is_at_end() {
            if self.check(&TokenKind::LBrace) {
                depth += 1;
            } else if self.check(&TokenKind::RBrace) {
                depth -= 1;
                if depth == 0 {
                    break;
                }
            }
            self.advance();
        }

        let content_end = self.peek().span.start as usize;

        // Extract the raw content from the source
        let raw_content = self._source[content_start..content_end].to_string();

        let end = self.expect(TokenKind::RBrace)?;
        let span = start.span.merge(end.span);

        // Create a span for the content
        let content_span = Span::new(
            content_start as u32,
            content_end as u32,
            start.span.start_line, // Approximation
            start.span.start_col,  // Approximation
        );

        Ok(Spanned::new(
            Statement::HclBlock(HclBlock {
                reason,
                content: Spanned::new(raw_content, content_span),
            }),
            span,
        ))
    }

    fn parse_unsafe_stmt(&mut self) -> Result<Spanned<Statement>, ()> {
        let start = self.expect(TokenKind::Unsafe)?;
        self.expect(TokenKind::LParen)?;
        let reason = self.expect_string("unsafe reason")?;
        self.expect(TokenKind::RParen)?;
        self.expect(TokenKind::LBrace)?;

        let mut body = Vec::new();
        while !self.check(&TokenKind::RBrace) && !self.is_at_end() {
            body.push(self.parse_statement()?);
        }

        let end = self.expect(TokenKind::RBrace)?;
        let span = start.span.merge(end.span);

        Ok(Spanned::new(
            Statement::Unsafe(UnsafeStmt { reason, body }),
            span,
        ))
    }

    // === Type Parsing ===

    fn parse_type(&mut self) -> Result<Spanned<TypeExpr>, ()> {
        let name_token = self.expect_ident("type name")?;
        let name = name_token.node.clone();
        let mut span = name_token.span;

        // Check for generic arguments
        if self.check(&TokenKind::Lt) {
            self.advance();
            let mut args = Vec::new();

            loop {
                args.push(self.parse_type()?);

                if self.check(&TokenKind::Comma) {
                    self.advance();
                } else {
                    break;
                }
            }

            let end = self.expect(TokenKind::Gt)?;
            span = span.merge(end.span);

            Ok(Spanned::new(TypeExpr::Generic { name, args }, span))
        } else {
            Ok(Spanned::new(TypeExpr::Named(name), span))
        }
    }

    // === Expression Parsing (Pratt/Precedence Climbing) ===

    fn parse_expr(&mut self) -> Result<Spanned<Expr>, ()> {
        self.parse_expr_bp(0)
    }

    /// Parse expression with minimum binding power (precedence climbing)
    #[allow(clippy::while_let_loop)]
    fn parse_expr_bp(&mut self, min_bp: u8) -> Result<Spanned<Expr>, ()> {
        // Check for lambda: `x => expr` or `(x, y) => expr`
        if let Some(lambda) = self.try_parse_lambda()? {
            return Ok(lambda);
        }

        // Parse unary operators or primary expression
        let mut lhs = self.parse_unary_or_primary()?;

        loop {
            // Check for binary operator
            let op = match self.peek_binary_op() {
                Some(op) => op,
                None => break,
            };

            let (l_bp, r_bp) = Self::infix_binding_power(op);
            if l_bp < min_bp {
                break;
            }

            self.advance(); // consume operator

            let rhs = self.parse_expr_bp(r_bp)?;
            let span = lhs.span.merge(rhs.span);

            lhs = Spanned::new(
                Expr::Binary {
                    left: Box::new(lhs),
                    op,
                    right: Box::new(rhs),
                },
                span,
            );
        }

        Ok(lhs)
    }

    /// Try to parse a lambda expression
    fn try_parse_lambda(&mut self) -> Result<Option<Spanned<Expr>>, ()> {
        // Single param lambda: `x => expr`
        if self.peek().is_ident() {
            if let Some(next) = self.peek_next() {
                if next.kind == TokenKind::Arrow {
                    let param = self.expect_ident("lambda parameter")?;
                    let start_span = param.span;
                    self.expect(TokenKind::Arrow)?;
                    let body = self.parse_expr()?;
                    let span = start_span.merge(body.span);

                    return Ok(Some(Spanned::new(
                        Expr::Lambda {
                            params: vec![param],
                            body: Box::new(body),
                        },
                        span,
                    )));
                }
            }
        }

        // Multi-param lambda: `(x, y) => expr`
        if self.check(&TokenKind::LParen) {
            // Look ahead to see if this is a lambda
            if self.is_lambda_params() {
                let start = self.advance(); // consume '('
                let mut params = Vec::new();

                if !self.check(&TokenKind::RParen) {
                    loop {
                        params.push(self.expect_ident("lambda parameter")?);
                        if self.check(&TokenKind::Comma) {
                            self.advance();
                        } else {
                            break;
                        }
                    }
                }

                self.expect(TokenKind::RParen)?;
                self.expect(TokenKind::Arrow)?;
                let body = self.parse_expr()?;
                let span = start.span.merge(body.span);

                return Ok(Some(Spanned::new(
                    Expr::Lambda {
                        params,
                        body: Box::new(body),
                    },
                    span,
                )));
            }
        }

        Ok(None)
    }

    /// Check if current position is the start of lambda parameters
    fn is_lambda_params(&self) -> bool {
        // Look for pattern: `(` ident (`,` ident)* `)` `=>`
        let mut depth = 0;
        let mut i = self.current;

        while i < self.tokens.len() {
            match &self.tokens[i].kind {
                TokenKind::LParen => depth += 1,
                TokenKind::RParen => {
                    depth -= 1;
                    if depth == 0 {
                        // Check if next token is =>
                        if i + 1 < self.tokens.len() {
                            return self.tokens[i + 1].kind == TokenKind::Arrow;
                        }
                        return false;
                    }
                }
                TokenKind::Ident(_) | TokenKind::Comma => {}
                _ => return false, // Not a simple param list
            }
            i += 1;
        }
        false
    }

    fn parse_unary_or_primary(&mut self) -> Result<Spanned<Expr>, ()> {
        // Unary operators
        match &self.peek().kind {
            TokenKind::Bang => {
                let op_token = self.advance();
                let operand = self.parse_unary_or_primary()?;
                let span = op_token.span.merge(operand.span);
                Ok(Spanned::new(
                    Expr::Unary {
                        op: UnaryOp::Not,
                        operand: Box::new(operand),
                    },
                    span,
                ))
            }
            TokenKind::Minus => {
                let op_token = self.advance();
                let operand = self.parse_unary_or_primary()?;
                let span = op_token.span.merge(operand.span);
                Ok(Spanned::new(
                    Expr::Unary {
                        op: UnaryOp::Neg,
                        operand: Box::new(operand),
                    },
                    span,
                ))
            }
            _ => self.parse_postfix_expr(),
        }
    }

    fn parse_postfix_expr(&mut self) -> Result<Spanned<Expr>, ()> {
        let mut expr = self.parse_atom()?;

        // Handle postfix operations (member access, function calls)
        loop {
            if self.check(&TokenKind::Dot) {
                self.advance();
                let field = self.expect_ident("field name")?;
                let span = expr.span.merge(field.span);
                expr = Spanned::new(
                    Expr::MemberAccess {
                        object: Box::new(expr),
                        field,
                    },
                    span,
                );
            } else if self.check(&TokenKind::LParen) {
                expr = self.parse_call(expr)?;
            } else {
                break;
            }
        }

        Ok(expr)
    }

    fn peek_binary_op(&self) -> Option<BinaryOp> {
        match &self.peek().kind {
            TokenKind::Plus => Some(BinaryOp::Add),
            TokenKind::Minus => Some(BinaryOp::Sub),
            TokenKind::Star => Some(BinaryOp::Mul),
            TokenKind::Slash => Some(BinaryOp::Div),
            TokenKind::EqEq => Some(BinaryOp::Eq),
            TokenKind::BangEq => Some(BinaryOp::NotEq),
            TokenKind::Lt => Some(BinaryOp::Lt),
            TokenKind::LtEq => Some(BinaryOp::LtEq),
            TokenKind::Gt => Some(BinaryOp::Gt),
            TokenKind::GtEq => Some(BinaryOp::GtEq),
            TokenKind::And => Some(BinaryOp::And),
            TokenKind::Or => Some(BinaryOp::Or),
            _ => None,
        }
    }

    /// Get binding power for infix operators (left, right)
    fn infix_binding_power(op: BinaryOp) -> (u8, u8) {
        match op {
            BinaryOp::Or => (1, 2),
            BinaryOp::And => (3, 4),
            BinaryOp::Eq | BinaryOp::NotEq => (5, 6),
            BinaryOp::Lt | BinaryOp::LtEq | BinaryOp::Gt | BinaryOp::GtEq => (7, 8),
            BinaryOp::Add | BinaryOp::Sub => (9, 10),
            BinaryOp::Mul | BinaryOp::Div => (11, 12),
        }
    }

    fn parse_atom(&mut self) -> Result<Spanned<Expr>, ()> {
        let token = self.peek().clone();

        match &token.kind {
            // Unsafe expression: unsafe("reason") { expr }
            TokenKind::Unsafe => {
                let start = self.advance();
                self.expect(TokenKind::LParen)?;
                let reason = self.expect_string("unsafe reason")?;

                // Reject empty or whitespace-only reasons
                if reason.node.trim().is_empty() {
                    self.errors.push(
                        Diagnostic::error_at(
                            "unsafe blocks require a non-empty justification",
                            reason.span,
                            self.filename,
                        )
                        .with_code(crate::errors::ErrorCode::UnexpectedToken)
                        .with_primary_label("justification cannot be empty")
                        .with_help("provide a reason that explains why this security exception is needed:\n\n    unsafe(\"TICKET-123: Public website approved by security team\") { ... }"),
                    );
                    return Err(());
                }

                self.expect(TokenKind::RParen)?;
                self.expect(TokenKind::LBrace)?;

                // Check for common mistakes: val declarations or multiple statements
                if self.check(&TokenKind::Val) {
                    let val_token = self.peek().clone();
                    self.errors.push(
                        Diagnostic::error_at(
                            "unsafe blocks must contain a single expression, not statements",
                            val_token.span,
                            self.filename,
                        )
                        .with_code(crate::errors::ErrorCode::UnexpectedToken)
                        .with_primary_label("`val` declarations are not allowed inside unsafe")
                        .with_help("move the val declaration outside and wrap only the risky expression:\n\n    val x = unsafe(\"reason\") { riskyExpression }"),
                    );
                    return Err(());
                }

                let body = self.parse_expr()?;

                // Check if there's more content (multiple statements attempt)
                if !self.check(&TokenKind::RBrace) {
                    let next = self.peek().clone();
                    self.errors.push(
                        Diagnostic::error_at(
                            "unsafe blocks can only contain one expression",
                            next.span,
                            self.filename,
                        )
                        .with_code(crate::errors::ErrorCode::UnexpectedToken)
                        .with_primary_label("unexpected content after expression")
                        .with_help("each security decision needs its own unsafe block:\n\n    val a = unsafe(\"TICKET-1\") { expr1 }\n    val b = unsafe(\"TICKET-2\") { expr2 }"),
                    );
                    return Err(());
                }

                let end = self.expect(TokenKind::RBrace)?;
                let span = start.span.merge(end.span);

                Ok(Spanned::new(
                    Expr::Unsafe {
                        reason,
                        body: Box::new(body),
                    },
                    span,
                ))
            }

            // If expression: if cond then a else b
            // or block form: if cond { a } else { b }
            TokenKind::If => {
                let start = self.advance(); // consume 'if'
                let condition = self.parse_expr()?;

                // Check for block form or then keyword
                let then_branch = if self.check(&TokenKind::Then) {
                    self.advance(); // consume 'then'
                    self.parse_expr()?
                } else if self.check(&TokenKind::LBrace) {
                    self.advance(); // consume '{'
                    let body = self.parse_expr()?;
                    self.expect(TokenKind::RBrace)?;
                    body
                } else {
                    self.error("expected 'then' or '{' after if condition");
                    return Err(());
                };

                self.expect(TokenKind::Else)?;

                // Check for block form or direct expression
                let else_branch = if self.check(&TokenKind::LBrace) {
                    self.advance(); // consume '{'
                    let body = self.parse_expr()?;
                    self.expect(TokenKind::RBrace)?;
                    body
                } else {
                    self.parse_expr()?
                };

                let span = start.span.merge(else_branch.span);

                Ok(Spanned::new(
                    Expr::If {
                        condition: Box::new(condition),
                        then_branch: Box::new(then_branch),
                        else_branch: Box::new(else_branch),
                    },
                    span,
                ))
            }

            // Literals
            TokenKind::String(_) | TokenKind::Number(_) | TokenKind::True | TokenKind::False => {
                let token = self.advance();
                match &token.kind {
                    TokenKind::String(s) => Ok(Spanned::new(
                        Expr::Literal(Literal::String(s.clone())),
                        token.span,
                    )),
                    TokenKind::Number(n) => {
                        Ok(Spanned::new(Expr::Literal(Literal::Number(*n)), token.span))
                    }
                    TokenKind::True => {
                        Ok(Spanned::new(Expr::Literal(Literal::Bool(true)), token.span))
                    }
                    TokenKind::False => Ok(Spanned::new(
                        Expr::Literal(Literal::Bool(false)),
                        token.span,
                    )),
                    _ => unreachable!(),
                }
            }

            // Identifiers
            TokenKind::Ident(_) => {
                let token = self.advance();
                if let TokenKind::Ident(name) = &token.kind {
                    Ok(Spanned::new(Expr::Identifier(name.clone()), token.span))
                } else {
                    unreachable!()
                }
            }

            // List literals
            TokenKind::LBracket => {
                let token = self.advance();
                let start_span = token.span;
                let mut elements = Vec::new();

                if !self.check(&TokenKind::RBracket) {
                    loop {
                        elements.push(self.parse_expr()?);

                        if self.check(&TokenKind::Comma) {
                            self.advance();
                            // Allow trailing comma
                            if self.check(&TokenKind::RBracket) {
                                break;
                            }
                        } else {
                            break;
                        }
                    }
                }

                let end = self.expect(TokenKind::RBracket)?;
                Ok(Spanned::new(
                    Expr::List(elements),
                    start_span.merge(end.span),
                ))
            }

            // Record literals
            TokenKind::LBrace => {
                let token = self.advance();
                let start_span = token.span;
                let mut fields = Vec::new();

                if !self.check(&TokenKind::RBrace) {
                    loop {
                        let name = self.expect_ident("field name")?;
                        self.expect(TokenKind::Colon)?;
                        let value = self.parse_expr()?;

                        fields.push(RecordField { name, value });

                        if self.check(&TokenKind::Comma) {
                            self.advance();
                            if self.check(&TokenKind::RBrace) {
                                break;
                            }
                        } else {
                            break;
                        }
                    }
                }

                let end = self.expect(TokenKind::RBrace)?;
                Ok(Spanned::new(
                    Expr::Record(fields),
                    start_span.merge(end.span),
                ))
            }

            // Grouped expression
            TokenKind::LParen => {
                self.advance();
                let expr = self.parse_expr()?;
                self.expect(TokenKind::RParen)?;
                Ok(expr)
            }

            _ => {
                self.error(&format!("expected expression, found {}", token.kind));
                Err(())
            }
        }
    }

    fn parse_call(&mut self, callee: Spanned<Expr>) -> Result<Spanned<Expr>, ()> {
        self.expect(TokenKind::LParen)?;

        let mut args = Vec::new();

        if !self.check(&TokenKind::RParen) {
            loop {
                // Check for named argument
                let arg = if self.peek().is_ident()
                    && self.peek_next().is_some_and(|t| t.kind == TokenKind::Colon)
                {
                    let name = self.expect_ident("argument name")?;
                    self.expect(TokenKind::Colon)?;
                    let value = self.parse_expr()?;
                    Arg {
                        name: Some(name),
                        value,
                    }
                } else {
                    let value = self.parse_expr()?;
                    Arg { name: None, value }
                };

                args.push(arg);

                if self.check(&TokenKind::Comma) {
                    self.advance();
                    if self.check(&TokenKind::RParen) {
                        break;
                    }
                } else {
                    break;
                }
            }
        }

        let end = self.expect(TokenKind::RParen)?;
        let span = callee.span.merge(end.span);

        Ok(Spanned::new(
            Expr::FuncCall {
                callee: Box::new(callee),
                args,
            },
            span,
        ))
    }

    // === Helper Methods ===

    fn peek(&self) -> &Token {
        &self.tokens[self.current]
    }

    fn peek_next(&self) -> Option<&Token> {
        self.tokens.get(self.current + 1)
    }

    fn is_at_end(&self) -> bool {
        self.peek().kind == TokenKind::Eof
    }

    fn advance(&mut self) -> Token {
        if !self.is_at_end() {
            self.current += 1;
        }
        self.tokens[self.current - 1].clone()
    }

    fn check(&self, kind: &TokenKind) -> bool {
        if self.is_at_end() {
            false
        } else {
            std::mem::discriminant(&self.peek().kind) == std::mem::discriminant(kind)
        }
    }

    fn expect(&mut self, kind: TokenKind) -> Result<Token, ()> {
        if self.check(&kind) {
            Ok(self.advance())
        } else {
            self.error(&format!(
                "expected {}, found {}",
                kind.name(),
                self.peek().kind
            ));
            Err(())
        }
    }

    fn expect_ident(&mut self, context: &str) -> Result<Spanned<String>, ()> {
        let token = self.advance();
        match token.kind {
            TokenKind::Ident(name) => Ok(Spanned::new(name, token.span)),
            _ => {
                self.error(&format!(
                    "expected {} (identifier), found {}",
                    context, token.kind
                ));
                Err(())
            }
        }
    }

    fn expect_string(&mut self, context: &str) -> Result<Spanned<String>, ()> {
        let token = self.advance();
        match token.kind {
            TokenKind::String(s) => Ok(Spanned::new(s, token.span)),
            _ => {
                self.error(&format!(
                    "expected {} (string), found {}",
                    context, token.kind
                ));
                Err(())
            }
        }
    }

    fn error(&mut self, message: &str) {
        let token = self.peek();
        self.errors.push(Diagnostic::error_at(
            message.to_string(),
            token.span,
            self.filename.to_string(),
        ));
    }

    fn synchronize(&mut self) {
        self.advance();

        while !self.is_at_end() {
            // Synchronize on statement boundaries
            match self.peek().kind {
                TokenKind::Val
                | TokenKind::Import
                | TokenKind::Unsafe
                | TokenKind::Module
                | TokenKind::Assert => return,
                _ => {
                    self.advance();
                }
            }
        }
    }
}

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

    fn parse_str(source: &str) -> Result<Program, Vec<Diagnostic>> {
        let tokens = tokenize(source, "test.hk").unwrap();
        parse(tokens, source, "test.hk")
    }

    #[test]
    fn test_parse_val_decl() {
        let program = parse_str("val x = 42").unwrap();
        assert_eq!(program.statements.len(), 1);
        match &program.statements[0].node {
            Statement::ValDecl(v) => {
                assert_eq!(v.name.node, "x");
            }
            _ => panic!("expected ValDecl"),
        }
    }

    #[test]
    fn test_parse_import() {
        let program = parse_str(r#"import "legacy.tf" as legacy"#).unwrap();
        assert_eq!(program.statements.len(), 1);
        match &program.statements[0].node {
            Statement::Import(i) => {
                assert_eq!(i.path.node, "legacy.tf");
                assert_eq!(i.alias.as_ref().unwrap().node, "legacy");
            }
            _ => panic!("expected Import"),
        }
    }

    #[test]
    fn test_parse_member_access() {
        let program = parse_str("val bucket = S3.createBucket(\"data\")").unwrap();
        assert_eq!(program.statements.len(), 1);
    }

    #[test]
    fn test_parse_unsafe_expr() {
        let source = r#"val x = unsafe("ticket #123") { legacy.bucket }"#;
        let program = parse_str(source).unwrap();
        assert_eq!(program.statements.len(), 1);
        match &program.statements[0].node {
            Statement::ValDecl(decl) => match &decl.value.node {
                Expr::Unsafe { reason, .. } => {
                    assert_eq!(reason.node, "ticket #123");
                }
                _ => panic!("expected Unsafe expression"),
            },
            _ => panic!("expected ValDecl"),
        }
    }

    #[test]
    fn test_parse_list() {
        let program = parse_str(r#"val zones = ["a", "b", "c"]"#).unwrap();
        assert_eq!(program.statements.len(), 1);
    }

    #[test]
    fn test_parse_lambda() {
        let source = r#"val f = x => x + 1"#;
        let program = parse_str(source).unwrap();
        match &program.statements[0].node {
            Statement::ValDecl(decl) => match &decl.value.node {
                Expr::Lambda { params, .. } => {
                    assert_eq!(params.len(), 1);
                    assert_eq!(params[0].node, "x");
                }
                _ => panic!("expected Lambda"),
            },
            _ => panic!("expected ValDecl"),
        }
    }

    #[test]
    fn test_parse_lambda_in_call() {
        let source = r#"val subnets = zones.map(z => Network.createSubnet(zone: z))"#;
        let program = parse_str(source).unwrap();
        assert_eq!(program.statements.len(), 1);
        // Should parse as: zones.map(<lambda>)
        match &program.statements[0].node {
            Statement::ValDecl(decl) => match &decl.value.node {
                Expr::FuncCall { args, .. } => {
                    assert_eq!(args.len(), 1);
                    match &args[0].value.node {
                        Expr::Lambda { params, .. } => {
                            assert_eq!(params[0].node, "z");
                        }
                        _ => panic!("expected Lambda argument"),
                    }
                }
                _ => panic!("expected FuncCall"),
            },
            _ => panic!("expected ValDecl"),
        }
    }

    #[test]
    fn test_parse_binary_expr() {
        let source = "val x = 1 + 2 * 3";
        let program = parse_str(source).unwrap();
        match &program.statements[0].node {
            Statement::ValDecl(decl) => {
                // Should parse as 1 + (2 * 3) due to precedence
                match &decl.value.node {
                    Expr::Binary { op, .. } => {
                        assert_eq!(*op, BinaryOp::Add);
                    }
                    _ => panic!("expected Binary"),
                }
            }
            _ => panic!("expected ValDecl"),
        }
    }

    #[test]
    fn test_parse_comparison() {
        let source = "val cond = x == 5 && y < 10";
        let program = parse_str(source).unwrap();
        assert_eq!(program.statements.len(), 1);
    }

    #[test]
    fn test_parse_unary() {
        let source = "val neg = -x";
        let program = parse_str(source).unwrap();
        match &program.statements[0].node {
            Statement::ValDecl(decl) => match &decl.value.node {
                Expr::Unary { op, .. } => {
                    assert_eq!(*op, UnaryOp::Neg);
                }
                _ => panic!("expected Unary"),
            },
            _ => panic!("expected ValDecl"),
        }
    }

    #[test]
    fn test_parse_filter_with_lambda() {
        let source = r#"val public = buckets.filter(b => b.isPublic)"#;
        let program = parse_str(source).unwrap();
        assert_eq!(program.statements.len(), 1);
    }

    #[test]
    fn test_parse_multi_param_lambda() {
        let source = r#"val sum = (a, b) => a + b"#;
        let program = parse_str(source).unwrap();
        match &program.statements[0].node {
            Statement::ValDecl(decl) => match &decl.value.node {
                Expr::Lambda { params, .. } => {
                    assert_eq!(params.len(), 2);
                    assert_eq!(params[0].node, "a");
                    assert_eq!(params[1].node, "b");
                }
                _ => panic!("expected Lambda"),
            },
            _ => panic!("expected ValDecl"),
        }
    }
    #[test]
    fn test_parse_hcl_block() {
        let source = r#"hcl("legacy") { resource "foo" "bar" {} }"#;
        let program = parse_str(source).unwrap();
        match &program.statements[0].node {
            Statement::HclBlock(hcl) => {
                assert_eq!(hcl.reason.node, "legacy");
                assert!(hcl.content.node.contains("resource \"foo\" \"bar\""));
            }
            _ => panic!("expected HclBlock"),
        }
    }

    #[test]
    fn test_parse_unsafe_stmt() {
        let source = r#"unsafe("bypass") { hcl("inner") { } }"#;
        let program = parse_str(source).unwrap();
        match &program.statements[0].node {
            Statement::Unsafe(u) => {
                assert_eq!(u.reason.node, "bypass");
                assert_eq!(u.body.len(), 1);
                match &u.body[0].node {
                    Statement::HclBlock(hcl) => {
                        assert_eq!(hcl.reason.node, "inner");
                    }
                    _ => panic!("expected HclBlock inside Unsafe"),
                }
            }
            _ => panic!("expected Unsafe statement"),
        }
    }
}