ctb_formats_pan/
procedure_parser.rs

1/* SPDX-License-Identifier: MIT */
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7Permission is hereby granted, free of charge, to any person obtaining a copy of
8this software and associated documentation files (the “Software”), to deal in
9the Software without restriction, including without limitation the rights to
10use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11the Software, and to permit persons to whom the Software is furnished to do so,
12subject to the following conditions:
13
14The above copyright notice and this permission notice shall be included in all
15copies or substantial portions of the Software.
16
17THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23SOFTWARE.
24*/
25
26//! AST definitions and parser for Panorama procedure and macro code.
27//!
28//! Provides lexing, parsing, and structured AST representations for
29//! Panorama procedures, including variable declarations, assignments,
30//! control flow constructs, commands, function calls, and expressions.
31
32#[allow(
33    unused_imports,
34    clippy::wildcard_imports,
35    reason = "Standard workspace module prelude"
36)]
37use crate::utilities::*;
38
39use serde::{Deserialize, Serialize};
40
41/// Scope of a declared variable in Panorama procedures.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
43pub enum PanVariableScope {
44    Local,
45    Global,
46    FileGlobal,
47    WindowGlobal,
48    Permanent,
49}
50
51/// Unary operators in Panorama expressions.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
53pub enum PanUnaryOp {
54    Not,
55    Negate,
56}
57
58/// Binary operators in Panorama expressions.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
60pub enum PanBinaryOp {
61    Add,
62    Subtract,
63    Multiply,
64    Divide,
65    Equal,
66    NotEqual,
67    LessThan,
68    LessThanOrEqual,
69    GreaterThan,
70    GreaterThanOrEqual,
71    Contains,
72    BeginsWith,
73    EndsWith,
74    Matches,
75    And,
76    Or,
77    Xor,
78}
79
80/// Expression node in a Panorama procedure.
81#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
82pub enum PanExpr {
83    StringLiteral(String),
84    IntegerLiteral(i64),
85    FloatLiteral(f64),
86    Pilcrow,
87    Identifier(String),
88    FunctionCall {
89        name: String,
90        arguments: Vec<PanExpr>,
91    },
92    UnaryOp {
93        op: PanUnaryOp,
94        operand: Box<PanExpr>,
95    },
96    BinaryOp {
97        op: PanBinaryOp,
98        left: Box<PanExpr>,
99        right: Box<PanExpr>,
100    },
101    Conditional {
102        condition: Box<PanExpr>,
103        true_value: Box<PanExpr>,
104        false_value: Box<PanExpr>,
105    },
106}
107
108/// Loop variant in Panorama procedures.
109#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
110pub enum PanLoopKind {
111    Infinite,
112    While(PanExpr),
113    Until(PanExpr),
114    Repeat(PanExpr),
115}
116
117/// Statement node in a Panorama procedure AST.
118#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
119pub enum PanStatement {
120    /// Variable declarations: `local x, y`, `global a`, etc.
121    VariableDeclaration {
122        scope: PanVariableScope,
123        names: Vec<String>,
124    },
125    /// Assignment statement: `target = value`
126    Assignment { target: String, value: PanExpr },
127    /// If-then-else construct
128    If {
129        condition: PanExpr,
130        then_branch: Vec<PanStatement>,
131        else_branch: Option<Vec<PanStatement>>,
132    },
133    /// Case / switch block
134    Case {
135        cases: Vec<(PanExpr, Vec<PanStatement>)>,
136        default_branch: Option<Vec<PanStatement>>,
137    },
138    /// Loop block
139    Loop {
140        kind: PanLoopKind,
141        body: Vec<PanStatement>,
142    },
143    /// Procedure invocation: `call <name> [, <args>]`
144    Call {
145        procedure_name: String,
146        arguments: Vec<PanExpr>,
147    },
148    /// Generic or built-in command: `openform "Detail"`, `beep`, etc.
149    Command {
150        name: String,
151        arguments: Vec<PanExpr>,
152    },
153    /// Comment text
154    Comment(String),
155}
156
157/// Abstract Syntax Tree representing a parsed Panorama procedure.
158#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
159pub struct PanProcedureAst {
160    pub statements: Vec<PanStatement>,
161}
162
163/// Parse procedure source code into a structured AST.
164pub fn parse_procedure(code: &str) -> anyhow::Result<PanProcedureAst> {
165    let tokens = tokenize(code)?;
166    let mut parser = ProcedureParser::new(tokens);
167    let statements = parser.parse_statements()?;
168    Ok(PanProcedureAst { statements })
169}
170
171#[derive(Debug, Clone, PartialEq)]
172enum Token {
173    Identifier(String),
174    StringLit(String),
175    IntLit(i64),
176    FloatLit(f64),
177    Pilcrow,
178    Equals,
179    NotEquals,
180    LessThan,
181    LessThanOrEqual,
182    GreaterThan,
183    GreaterThanOrEqual,
184    Plus,
185    Minus,
186    Star,
187    Slash,
188    Question,
189    Comma,
190    OpenParen,
191    CloseParen,
192    OpenBrace,
193    CloseBrace,
194    Newline,
195    Comment(String),
196}
197
198fn tokenize(input: &str) -> anyhow::Result<Vec<Token>> {
199    let mut tokens = Vec::new();
200    let chars: Vec<char> = input.chars().collect();
201    let mut idx = 0usize;
202
203    while idx < chars.len() {
204        let c = match chars.get(idx) {
205            Some(&ch) => ch,
206            None => break,
207        };
208
209        // Semicolon line comment
210        if c == ';' {
211            let start = idx;
212            idx = idx.saturating_add(1);
213            while idx < chars.len() && chars.get(idx).copied() != Some('\n') {
214                idx = idx.saturating_add(1);
215            }
216            if let Some(slice) = chars.get(start..idx) {
217                let comment_text: String = slice.iter().collect();
218                tokens.push(Token::Comment(comment_text));
219            }
220            continue;
221        }
222
223        // Line comment `//`
224        if c == '/' && chars.get(idx.saturating_add(1)).copied() == Some('/') {
225            let start = idx;
226            idx = idx.saturating_add(2);
227            while idx < chars.len() && chars.get(idx).copied() != Some('\n') {
228                idx = idx.saturating_add(1);
229            }
230            if let Some(slice) = chars.get(start..idx) {
231                let comment_text: String = slice.iter().collect();
232                tokens.push(Token::Comment(comment_text));
233            }
234            continue;
235        }
236
237        // Block comment `/* ... */`
238        if c == '/' && chars.get(idx.saturating_add(1)).copied() == Some('*') {
239            let start = idx;
240            idx = idx.saturating_add(2);
241            while idx < chars.len() {
242                if chars.get(idx).copied() == Some('*')
243                    && chars.get(idx.saturating_add(1)).copied() == Some('/')
244                {
245                    idx = idx.saturating_add(2);
246                    break;
247                }
248                idx = idx.saturating_add(1);
249            }
250            if let Some(slice) = chars.get(start..idx) {
251                let comment_text: String = slice.iter().collect();
252                tokens.push(Token::Comment(comment_text));
253            }
254            continue;
255        }
256
257        // Whitespace (except newlines)
258        if c.is_whitespace() && c != '\n' && c != '\r' {
259            idx = idx.saturating_add(1);
260            continue;
261        }
262
263        // Newline
264        if c == '\n' || c == '\r' {
265            if c == '\r'
266                && chars.get(idx.saturating_add(1)).copied() == Some('\n')
267            {
268                idx = idx.saturating_add(1);
269            }
270            if !tokens.last().is_some_and(|t| matches!(t, Token::Newline)) {
271                tokens.push(Token::Newline);
272            }
273            idx = idx.saturating_add(1);
274            continue;
275        }
276
277        // Pilcrow symbol
278        if c == '¶' {
279            tokens.push(Token::Pilcrow);
280            idx = idx.saturating_add(1);
281            continue;
282        }
283
284        // String literal in double quotes
285        if c == '"' {
286            idx = idx.saturating_add(1);
287            let mut s = String::new();
288            while idx < chars.len() {
289                let sc = match chars.get(idx) {
290                    Some(&ch) => ch,
291                    None => break,
292                };
293                if sc == '"' {
294                    if chars.get(idx.saturating_add(1)).copied() == Some('"') {
295                        s.push('"');
296                        idx = idx.saturating_add(2);
297                        continue;
298                    }
299                    idx = idx.saturating_add(1);
300                    break;
301                }
302                s.push(sc);
303                idx = idx.saturating_add(1);
304            }
305            tokens.push(Token::StringLit(s));
306            continue;
307        }
308
309        // String literal / block in curly braces
310        if c == '{' {
311            idx = idx.saturating_add(1);
312            let mut s = String::new();
313            let mut depth = 1usize;
314            while idx < chars.len() {
315                let sc = match chars.get(idx) {
316                    Some(&ch) => ch,
317                    None => break,
318                };
319                if sc == '{' {
320                    depth = depth.saturating_add(1);
321                } else if sc == '}' {
322                    depth = depth.saturating_sub(1);
323                    if depth == 0 {
324                        idx = idx.saturating_add(1);
325                        break;
326                    }
327                }
328                s.push(sc);
329                idx = idx.saturating_add(1);
330            }
331            tokens.push(Token::StringLit(s));
332            continue;
333        }
334
335        // Multi-char operators
336        if c == '<' {
337            let next = chars.get(idx.saturating_add(1)).copied();
338            if next == Some('>') {
339                tokens.push(Token::NotEquals);
340                idx = idx.saturating_add(2);
341                continue;
342            } else if next == Some('=') {
343                tokens.push(Token::LessThanOrEqual);
344                idx = idx.saturating_add(2);
345                continue;
346            }
347            tokens.push(Token::LessThan);
348            idx = idx.saturating_add(1);
349            continue;
350        }
351        if c == '>' {
352            let next = chars.get(idx.saturating_add(1)).copied();
353            if next == Some('=') {
354                tokens.push(Token::GreaterThanOrEqual);
355                idx = idx.saturating_add(2);
356                continue;
357            }
358            tokens.push(Token::GreaterThan);
359            idx = idx.saturating_add(1);
360            continue;
361        }
362        if c == '!' && chars.get(idx.saturating_add(1)).copied() == Some('=') {
363            tokens.push(Token::NotEquals);
364            idx = idx.saturating_add(2);
365            continue;
366        }
367        if c == '≠' || c == '€' {
368            tokens.push(Token::NotEquals);
369            idx = idx.saturating_add(1);
370            continue;
371        }
372        if c == '=' {
373            tokens.push(Token::Equals);
374            idx = idx.saturating_add(1);
375            continue;
376        }
377        if c == '+' {
378            tokens.push(Token::Plus);
379            idx = idx.saturating_add(1);
380            continue;
381        }
382        if c == '-' {
383            tokens.push(Token::Minus);
384            idx = idx.saturating_add(1);
385            continue;
386        }
387        if c == '*' {
388            tokens.push(Token::Star);
389            idx = idx.saturating_add(1);
390            continue;
391        }
392        if c == '/' {
393            tokens.push(Token::Slash);
394            idx = idx.saturating_add(1);
395            continue;
396        }
397        if c == '?' {
398            tokens.push(Token::Question);
399            idx = idx.saturating_add(1);
400            continue;
401        }
402        if c == ',' {
403            tokens.push(Token::Comma);
404            idx = idx.saturating_add(1);
405            continue;
406        }
407        if c == '(' {
408            tokens.push(Token::OpenParen);
409            idx = idx.saturating_add(1);
410            continue;
411        }
412        if c == ')' {
413            tokens.push(Token::CloseParen);
414            idx = idx.saturating_add(1);
415            continue;
416        }
417        if c == '}' {
418            tokens.push(Token::CloseBrace);
419            idx = idx.saturating_add(1);
420            continue;
421        }
422
423        // Numeric literal
424        if c.is_ascii_digit() {
425            let start = idx;
426            let mut is_float = false;
427            while idx < chars.len() {
428                let nc = match chars.get(idx) {
429                    Some(&ch) => ch,
430                    None => break,
431                };
432                if nc.is_ascii_digit() {
433                    idx = idx.saturating_add(1);
434                } else if nc == '.' && !is_float {
435                    is_float = true;
436                    idx = idx.saturating_add(1);
437                } else {
438                    break;
439                }
440            }
441            if let Some(slice) = chars.get(start..idx) {
442                let num_str: String = slice.iter().collect();
443                if is_float {
444                    if let Ok(f) = num_str.parse::<f64>() {
445                        tokens.push(Token::FloatLit(f));
446                    }
447                } else if let Ok(i) = num_str.parse::<i64>() {
448                    tokens.push(Token::IntLit(i));
449                }
450            }
451            continue;
452        }
453
454        // Identifier or keyword
455        if c.is_ascii_alphabetic() || c == '_' || c == '.' {
456            let start = idx;
457            while idx < chars.len() {
458                let nc = match chars.get(idx) {
459                    Some(&ch) => ch,
460                    None => break,
461                };
462                if nc.is_ascii_alphanumeric() || nc == '_' || nc == '.' {
463                    idx = idx.saturating_add(1);
464                } else {
465                    break;
466                }
467            }
468            if let Some(slice) = chars.get(start..idx) {
469                let ident_str: String = slice.iter().collect();
470                tokens.push(Token::Identifier(ident_str));
471            }
472            continue;
473        }
474
475        idx = idx.saturating_add(1);
476    }
477
478    Ok(tokens)
479}
480
481struct ProcedureParser {
482    tokens: Vec<Token>,
483    pos: usize,
484}
485
486impl ProcedureParser {
487    fn new(tokens: Vec<Token>) -> Self {
488        Self { tokens, pos: 0 }
489    }
490
491    fn peek(&self) -> Option<&Token> {
492        self.tokens.get(self.pos)
493    }
494
495    fn advance(&mut self) -> Option<&Token> {
496        let tok = self.tokens.get(self.pos);
497        if tok.is_some() {
498            self.pos = self.pos.saturating_add(1);
499        }
500        tok
501    }
502
503    fn skip_newlines(&mut self) {
504        while let Some(Token::Newline) = self.peek() {
505            self.advance();
506        }
507    }
508
509    fn parse_statements(&mut self) -> anyhow::Result<Vec<PanStatement>> {
510        let mut stmts = Vec::new();
511        while self.pos < self.tokens.len() {
512            self.skip_newlines();
513            if self.pos >= self.tokens.len() {
514                break;
515            }
516
517            if let Some(tok) = self.peek() {
518                if let Token::Identifier(ident) = tok {
519                    let lower = ident.to_ascii_lowercase();
520                    if lower == "endif"
521                        || lower == "endcase"
522                        || lower == "else"
523                        || lower == "until"
524                        || lower == "endloop"
525                    {
526                        break;
527                    }
528                }
529            }
530
531            if let Some(stmt) = self.parse_statement()? {
532                stmts.push(stmt);
533            }
534        }
535        Ok(stmts)
536    }
537
538    fn parse_statement(&mut self) -> anyhow::Result<Option<PanStatement>> {
539        self.skip_newlines();
540        let tok = match self.peek() {
541            Some(t) => t.clone(),
542            None => return Ok(None),
543        };
544
545        match tok {
546            Token::Comment(c) => {
547                self.advance();
548                Ok(Some(PanStatement::Comment(c)))
549            }
550            Token::Identifier(ident) => {
551                let lower = ident.to_ascii_lowercase();
552                match lower.as_str() {
553                    "local" => {
554                        self.advance();
555                        let names = self.parse_identifier_list()?;
556                        Ok(Some(PanStatement::VariableDeclaration {
557                            scope: PanVariableScope::Local,
558                            names,
559                        }))
560                    }
561                    "global" => {
562                        self.advance();
563                        let names = self.parse_identifier_list()?;
564                        Ok(Some(PanStatement::VariableDeclaration {
565                            scope: PanVariableScope::Global,
566                            names,
567                        }))
568                    }
569                    "fileglobal" => {
570                        self.advance();
571                        let names = self.parse_identifier_list()?;
572                        Ok(Some(PanStatement::VariableDeclaration {
573                            scope: PanVariableScope::FileGlobal,
574                            names,
575                        }))
576                    }
577                    "windowglobal" => {
578                        self.advance();
579                        let names = self.parse_identifier_list()?;
580                        Ok(Some(PanStatement::VariableDeclaration {
581                            scope: PanVariableScope::WindowGlobal,
582                            names,
583                        }))
584                    }
585                    "permanent" => {
586                        self.advance();
587                        let names = self.parse_identifier_list()?;
588                        Ok(Some(PanStatement::VariableDeclaration {
589                            scope: PanVariableScope::Permanent,
590                            names,
591                        }))
592                    }
593                    "if" => {
594                        self.advance();
595                        let condition = self.parse_expression()?;
596                        let mut then_branch = Vec::new();
597                        let mut else_branch = None;
598
599                        while self.pos < self.tokens.len() {
600                            self.skip_newlines();
601                            if let Some(Token::Identifier(kw)) = self.peek() {
602                                let kw_lower = kw.to_ascii_lowercase();
603                                if kw_lower == "endif" {
604                                    self.advance();
605                                    break;
606                                }
607                                if kw_lower == "else" {
608                                    self.advance();
609                                    let mut else_stmts = Vec::new();
610                                    while self.pos < self.tokens.len() {
611                                        self.skip_newlines();
612                                        if let Some(Token::Identifier(k)) =
613                                            self.peek()
614                                        {
615                                            if k.eq_ignore_ascii_case("endif") {
616                                                self.advance();
617                                                break;
618                                            }
619                                        }
620                                        if let Some(s) =
621                                            self.parse_statement()?
622                                        {
623                                            else_stmts.push(s);
624                                        }
625                                    }
626                                    else_branch = Some(else_stmts);
627                                    break;
628                                }
629                            }
630                            if let Some(s) = self.parse_statement()? {
631                                then_branch.push(s);
632                            }
633                        }
634
635                        Ok(Some(PanStatement::If {
636                            condition,
637                            then_branch,
638                            else_branch,
639                        }))
640                    }
641                    "case" => {
642                        self.advance();
643                        let mut cases = Vec::new();
644                        let mut default_branch = None;
645
646                        let cond = self.parse_expression()?;
647                        let mut case_stmts = Vec::new();
648                        while self.pos < self.tokens.len() {
649                            self.skip_newlines();
650                            if let Some(Token::Identifier(k)) = self.peek() {
651                                let k_lower = k.to_ascii_lowercase();
652                                if k_lower == "case" || k_lower == "endcase" {
653                                    break;
654                                }
655                            }
656                            if let Some(s) = self.parse_statement()? {
657                                case_stmts.push(s);
658                            }
659                        }
660                        cases.push((cond, case_stmts));
661
662                        while let Some(Token::Identifier(k)) = self.peek() {
663                            if k.eq_ignore_ascii_case("case") {
664                                self.advance();
665                                let next_cond = self.parse_expression()?;
666                                let mut next_stmts = Vec::new();
667                                while self.pos < self.tokens.len() {
668                                    self.skip_newlines();
669                                    if let Some(Token::Identifier(k2)) =
670                                        self.peek()
671                                    {
672                                        let k2_lower = k2.to_ascii_lowercase();
673                                        if k2_lower == "case"
674                                            || k2_lower == "endcase"
675                                            || k2_lower == "default"
676                                        {
677                                            break;
678                                        }
679                                    }
680                                    if let Some(s) = self.parse_statement()? {
681                                        next_stmts.push(s);
682                                    }
683                                }
684                                cases.push((next_cond, next_stmts));
685                            } else if k.eq_ignore_ascii_case("default") {
686                                self.advance();
687                                let mut def_stmts = Vec::new();
688                                while self.pos < self.tokens.len() {
689                                    self.skip_newlines();
690                                    if let Some(Token::Identifier(k2)) =
691                                        self.peek()
692                                    {
693                                        if k2.eq_ignore_ascii_case("endcase") {
694                                            break;
695                                        }
696                                    }
697                                    if let Some(s) = self.parse_statement()? {
698                                        def_stmts.push(s);
699                                    }
700                                }
701                                default_branch = Some(def_stmts);
702                                break;
703                            } else {
704                                break;
705                            }
706                        }
707
708                        if let Some(Token::Identifier(k)) = self.peek() {
709                            if k.eq_ignore_ascii_case("endcase") {
710                                self.advance();
711                            }
712                        }
713
714                        Ok(Some(PanStatement::Case {
715                            cases,
716                            default_branch,
717                        }))
718                    }
719                    "loop" => {
720                        self.advance();
721                        let mut body = Vec::new();
722                        let mut loop_kind = PanLoopKind::Infinite;
723
724                        while self.pos < self.tokens.len() {
725                            self.skip_newlines();
726                            if let Some(Token::Identifier(k)) = self.peek() {
727                                let k_lower = k.to_ascii_lowercase();
728                                if k_lower == "until" {
729                                    self.advance();
730                                    let until_expr = self.parse_expression()?;
731                                    loop_kind = PanLoopKind::Until(until_expr);
732                                    break;
733                                }
734                                if k_lower == "endloop" {
735                                    self.advance();
736                                    break;
737                                }
738                            }
739                            if let Some(s) = self.parse_statement()? {
740                                body.push(s);
741                            }
742                        }
743
744                        Ok(Some(PanStatement::Loop {
745                            kind: loop_kind,
746                            body,
747                        }))
748                    }
749                    "call" => {
750                        self.advance();
751                        let proc_name =
752                            if let Some(Token::Identifier(p)) = self.peek() {
753                                let name = p.clone();
754                                self.advance();
755                                name
756                            } else {
757                                String::new()
758                            };
759                        let mut args = Vec::new();
760                        while let Some(Token::Comma) = self.peek() {
761                            self.advance();
762                            args.push(self.parse_expression()?);
763                        }
764                        Ok(Some(PanStatement::Call {
765                            procedure_name: proc_name,
766                            arguments: args,
767                        }))
768                    }
769                    _ => {
770                        if let Some(Token::Equals) =
771                            self.tokens.get(self.pos.saturating_add(1))
772                        {
773                            self.advance(); // consume ident
774                            self.advance(); // consume '='
775                            let value = self.parse_expression()?;
776                            Ok(Some(PanStatement::Assignment {
777                                target: ident,
778                                value,
779                            }))
780                        } else {
781                            // Command invocation
782                            self.advance();
783                            let mut args = Vec::new();
784                            while self.pos < self.tokens.len() {
785                                if let Some(Token::Newline) = self.peek() {
786                                    break;
787                                }
788                                if let Some(Token::Identifier(kw)) = self.peek()
789                                {
790                                    let kw_lower = kw.to_ascii_lowercase();
791                                    if kw_lower == "endif"
792                                        || kw_lower == "else"
793                                        || kw_lower == "until"
794                                        || kw_lower == "endloop"
795                                    {
796                                        break;
797                                    }
798                                }
799                                let expr = self.parse_expression()?;
800                                args.push(expr);
801                                if let Some(Token::Comma) = self.peek() {
802                                    self.advance();
803                                } else {
804                                    break;
805                                }
806                            }
807                            Ok(Some(PanStatement::Command {
808                                name: ident,
809                                arguments: args,
810                            }))
811                        }
812                    }
813                }
814            }
815            _ => {
816                self.advance();
817                Ok(None)
818            }
819        }
820    }
821
822    fn parse_identifier_list(&mut self) -> anyhow::Result<Vec<String>> {
823        let mut idents = Vec::new();
824        while self.pos < self.tokens.len() {
825            if let Some(Token::Identifier(id)) = self.peek() {
826                idents.push(id.clone());
827                self.advance();
828                if let Some(Token::Comma) = self.peek() {
829                    self.advance();
830                } else {
831                    break;
832                }
833            } else {
834                break;
835            }
836        }
837        Ok(idents)
838    }
839
840    fn parse_expression(&mut self) -> anyhow::Result<PanExpr> {
841        self.parse_logical_or()
842    }
843
844    fn parse_logical_or(&mut self) -> anyhow::Result<PanExpr> {
845        let mut left = self.parse_logical_and()?;
846        while let Some(Token::Identifier(id)) = self.peek() {
847            if id.eq_ignore_ascii_case("or") {
848                self.advance();
849                let right = self.parse_logical_and()?;
850                left = PanExpr::BinaryOp {
851                    op: PanBinaryOp::Or,
852                    left: Box::new(left),
853                    right: Box::new(right),
854                };
855            } else if id.eq_ignore_ascii_case("xor") {
856                self.advance();
857                let right = self.parse_logical_and()?;
858                left = PanExpr::BinaryOp {
859                    op: PanBinaryOp::Xor,
860                    left: Box::new(left),
861                    right: Box::new(right),
862                };
863            } else {
864                break;
865            }
866        }
867        Ok(left)
868    }
869
870    fn parse_logical_and(&mut self) -> anyhow::Result<PanExpr> {
871        let mut left = self.parse_comparison()?;
872        while let Some(Token::Identifier(id)) = self.peek() {
873            if id.eq_ignore_ascii_case("and") {
874                self.advance();
875                let right = self.parse_comparison()?;
876                left = PanExpr::BinaryOp {
877                    op: PanBinaryOp::And,
878                    left: Box::new(left),
879                    right: Box::new(right),
880                };
881            } else {
882                break;
883            }
884        }
885        Ok(left)
886    }
887
888    fn parse_comparison(&mut self) -> anyhow::Result<PanExpr> {
889        let mut left = self.parse_additive()?;
890        while let Some(tok) = self.peek() {
891            let op = match tok {
892                Token::Equals => Some(PanBinaryOp::Equal),
893                Token::NotEquals => Some(PanBinaryOp::NotEqual),
894                Token::LessThan => Some(PanBinaryOp::LessThan),
895                Token::LessThanOrEqual => Some(PanBinaryOp::LessThanOrEqual),
896                Token::GreaterThan => Some(PanBinaryOp::GreaterThan),
897                Token::GreaterThanOrEqual => {
898                    Some(PanBinaryOp::GreaterThanOrEqual)
899                }
900                Token::Identifier(id)
901                    if id.eq_ignore_ascii_case("contains") =>
902                {
903                    Some(PanBinaryOp::Contains)
904                }
905                Token::Identifier(id)
906                    if id.eq_ignore_ascii_case("beginswith") =>
907                {
908                    Some(PanBinaryOp::BeginsWith)
909                }
910                Token::Identifier(id)
911                    if id.eq_ignore_ascii_case("endswith") =>
912                {
913                    Some(PanBinaryOp::EndsWith)
914                }
915                Token::Identifier(id) if id.eq_ignore_ascii_case("matches") => {
916                    Some(PanBinaryOp::Matches)
917                }
918                _ => None,
919            };
920
921            if let Some(binary_op) = op {
922                self.advance();
923                let right = self.parse_additive()?;
924                left = PanExpr::BinaryOp {
925                    op: binary_op,
926                    left: Box::new(left),
927                    right: Box::new(right),
928                };
929            } else {
930                break;
931            }
932        }
933        Ok(left)
934    }
935
936    fn parse_additive(&mut self) -> anyhow::Result<PanExpr> {
937        let mut left = self.parse_multiplicative()?;
938        while let Some(tok) = self.peek() {
939            let op = match tok {
940                Token::Plus => Some(PanBinaryOp::Add),
941                Token::Minus => Some(PanBinaryOp::Subtract),
942                _ => None,
943            };
944            if let Some(binary_op) = op {
945                self.advance();
946                let right = self.parse_multiplicative()?;
947                left = PanExpr::BinaryOp {
948                    op: binary_op,
949                    left: Box::new(left),
950                    right: Box::new(right),
951                };
952            } else {
953                break;
954            }
955        }
956        Ok(left)
957    }
958
959    fn parse_multiplicative(&mut self) -> anyhow::Result<PanExpr> {
960        let mut left = self.parse_unary()?;
961        while let Some(tok) = self.peek() {
962            let op = match tok {
963                Token::Star => Some(PanBinaryOp::Multiply),
964                Token::Slash => Some(PanBinaryOp::Divide),
965                _ => None,
966            };
967            if let Some(binary_op) = op {
968                self.advance();
969                let right = self.parse_unary()?;
970                left = PanExpr::BinaryOp {
971                    op: binary_op,
972                    left: Box::new(left),
973                    right: Box::new(right),
974                };
975            } else {
976                break;
977            }
978        }
979        Ok(left)
980    }
981
982    fn parse_unary(&mut self) -> anyhow::Result<PanExpr> {
983        if let Some(tok) = self.peek() {
984            if let Token::Minus = tok {
985                self.advance();
986                let operand = self.parse_primary()?;
987                return Ok(PanExpr::UnaryOp {
988                    op: PanUnaryOp::Negate,
989                    operand: Box::new(operand),
990                });
991            }
992            if let Token::Identifier(id) = tok {
993                if id.eq_ignore_ascii_case("not") {
994                    self.advance();
995                    let operand = self.parse_primary()?;
996                    return Ok(PanExpr::UnaryOp {
997                        op: PanUnaryOp::Not,
998                        operand: Box::new(operand),
999                    });
1000                }
1001            }
1002        }
1003        self.parse_primary()
1004    }
1005
1006    fn parse_primary(&mut self) -> anyhow::Result<PanExpr> {
1007        let tok = match self.advance() {
1008            Some(t) => t.clone(),
1009            None => return Ok(PanExpr::StringLiteral(String::new())),
1010        };
1011
1012        match tok {
1013            Token::StringLit(s) => Ok(PanExpr::StringLiteral(s)),
1014            Token::IntLit(i) => Ok(PanExpr::IntegerLiteral(i)),
1015            Token::FloatLit(f) => Ok(PanExpr::FloatLiteral(f)),
1016            Token::Pilcrow => Ok(PanExpr::Pilcrow),
1017            Token::Question => {
1018                if let Some(Token::OpenParen) = self.peek() {
1019                    self.advance();
1020                    let cond = self.parse_expression()?;
1021                    if let Some(Token::Comma) = self.peek() {
1022                        self.advance();
1023                    }
1024                    let true_val = self.parse_expression()?;
1025                    if let Some(Token::Comma) = self.peek() {
1026                        self.advance();
1027                    }
1028                    let false_val = self.parse_expression()?;
1029                    if let Some(Token::CloseParen) = self.peek() {
1030                        self.advance();
1031                    }
1032                    Ok(PanExpr::Conditional {
1033                        condition: Box::new(cond),
1034                        true_value: Box::new(true_val),
1035                        false_value: Box::new(false_val),
1036                    })
1037                } else {
1038                    Ok(PanExpr::Identifier("?".to_string()))
1039                }
1040            }
1041            Token::OpenParen => {
1042                let expr = self.parse_expression()?;
1043                if let Some(Token::CloseParen) = self.peek() {
1044                    self.advance();
1045                }
1046                Ok(expr)
1047            }
1048            Token::Identifier(name) => {
1049                if let Some(Token::OpenParen) = self.peek() {
1050                    self.advance();
1051                    let mut args = Vec::new();
1052                    while self.pos < self.tokens.len() {
1053                        if let Some(Token::CloseParen) = self.peek() {
1054                            self.advance();
1055                            break;
1056                        }
1057                        args.push(self.parse_expression()?);
1058                        if let Some(Token::Comma) = self.peek() {
1059                            self.advance();
1060                        } else if let Some(Token::CloseParen) = self.peek() {
1061                            self.advance();
1062                            break;
1063                        } else {
1064                            break;
1065                        }
1066                    }
1067                    Ok(PanExpr::FunctionCall {
1068                        name,
1069                        arguments: args,
1070                    })
1071                } else {
1072                    Ok(PanExpr::Identifier(name))
1073                }
1074            }
1075            _ => Ok(PanExpr::StringLiteral(String::new())),
1076        }
1077    }
1078}
1079
1080#[cfg(test)]
1081#[allow(
1082    clippy::panic,
1083    clippy::expect_used,
1084    clippy::unwrap_used,
1085    clippy::unwrap_in_result,
1086    clippy::panic_in_result_fn,
1087    clippy::indexing_slicing,
1088    clippy::arithmetic_side_effects,
1089    reason = "Standard repository test boilerplate"
1090)]
1091mod tests {
1092    use ctb_utilities::anyhow::ensure;
1093
1094    use super::*;
1095
1096    #[crate::ctb_test]
1097    fn test_parse_fibonacci_sequence_generator() -> anyhow::Result<()> {
1098        let code = r#"
1099/* Synthetic Test: Fibonacci sequence generator with iterative accumulation */
1100// Initialize variables for iteration bounds and current values
1101local count, prevVal, currVal, nextVal, sequenceOutput
1102count = 20
1103prevVal = 0
1104currVal = 1
1105sequenceOutput = str(prevVal) + ", " + str(currVal)
1106
1107loop
1108    nextVal = prevVal + currVal
1109    sequenceOutput = sequenceOutput + ", " + str(nextVal)
1110    prevVal = currVal
1111    currVal = nextVal
1112    count = count - 1
1113until count <= 2
1114
1115message "Computed Fibonacci Sequence: " + sequenceOutput
1116"#;
1117        let ast = parse_procedure(code)?;
1118        ensure!(
1119            !ast.statements.is_empty(),
1120            "AST statements should not be empty"
1121        );
1122
1123        // Verify variable declaration
1124        let has_decl = ast.statements.iter().any(|s| {
1125            matches!(
1126                s,
1127                PanStatement::VariableDeclaration {
1128                    scope: PanVariableScope::Local,
1129                    names,
1130                } if names.len() == 5 && names[0] == "count"
1131            )
1132        });
1133        ensure!(
1134            has_decl,
1135            "Expected local variable declaration for fibonacci"
1136        );
1137
1138        // Verify loop with until condition
1139        let has_loop = ast.statements.iter().any(|s| {
1140            matches!(
1141                s,
1142                PanStatement::Loop {
1143                    kind: PanLoopKind::Until(PanExpr::BinaryOp {
1144                        op: PanBinaryOp::LessThanOrEqual,
1145                        ..
1146                    }),
1147                    body,
1148                } if body.len() >= 4
1149            )
1150        });
1151        ensure!(has_loop, "Expected loop statement with until condition");
1152
1153        Ok(())
1154    }
1155
1156    #[crate::ctb_test]
1157    fn test_parse_prime_sieve_and_stats_calculator() -> anyhow::Result<()> {
1158        let code = r#"
1159/* Synthetic Test: Prime factorizer and summary statistics calculator */
1160fileglobal targetNum, divisor, factorList, isPrime
1161permanent calculationLog
1162
1163targetNum = 104729
1164divisor = 2
1165factorList = ""
1166isPrime = -1
1167
1168loop
1169    if (targetNum / divisor) * divisor = targetNum
1170        factorList = factorList + ?(factorList = "", "", ", ") + str(divisor)
1171        targetNum = targetNum / divisor
1172        isPrime = 0
1173    else
1174        divisor = divisor + ?(divisor = 2, 1, 2)
1175    endif
1176until divisor * divisor > targetNum
1177
1178if targetNum > 1
1179    factorList = factorList + ?(factorList = "", "", ", ") + str(targetNum)
1180endif
1181
1182case isPrime = -1
1183    message "Number is Prime!"
1184case isPrime = 0
1185    message "Prime factors: " + factorList
1186default
1187    message "Invalid state"
1188endcase
1189"#;
1190        let ast = parse_procedure(code)?;
1191        ensure!(ast.statements.len() >= 6, "Expected at least 6 statements");
1192
1193        // Verify fileglobal and permanent declarations
1194        let has_fileglobal = ast.statements.iter().any(|s| {
1195            matches!(
1196                s,
1197                PanStatement::VariableDeclaration {
1198                    scope: PanVariableScope::FileGlobal,
1199                    names,
1200                } if names.len() == 4
1201            )
1202        });
1203        ensure!(has_fileglobal, "Expected fileglobal declaration");
1204
1205        let has_permanent = ast.statements.iter().any(|s| {
1206            matches!(
1207                s,
1208                PanStatement::VariableDeclaration {
1209                    scope: PanVariableScope::Permanent,
1210                    names,
1211                } if names == &["calculationLog"]
1212            )
1213        });
1214        ensure!(has_permanent, "Expected permanent declaration");
1215
1216        // Verify case statement
1217        let has_case = ast.statements.iter().any(|s| {
1218            matches!(
1219                s,
1220                PanStatement::Case {
1221                    cases,
1222                    default_branch: Some(_),
1223                } if cases.len() == 2
1224            )
1225        });
1226        ensure!(
1227            has_case,
1228            "Expected case statement with 2 cases and default branch"
1229        );
1230
1231        Ok(())
1232    }
1233}