office-rs 0.1.1

A Rust library for reading and writing XML Office files
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
//! Excel公式模块
//! 提供公式解析、计算和函数库功能

use crate::error::{ OfficeError, Result, XlsxError };
use crate::xlsx::cell::{ CellReference, CellValue };
use std::collections::{ HashMap, HashSet };
use std::fmt;

// 导入子模块
mod formula_calculator;
mod formula_manager;

// pub use formula_calculator::*;
pub use formula_manager::*;

/// 公式值类型
#[derive(Debug, Clone, PartialEq)]
pub enum FormulaValue {
    /// 数字值
    Number(f64),
    /// 文本值
    Text(String),
    /// 布尔值
    Boolean(bool),
    /// 错误值
    Error(FormulaError),
    /// 数组值
    Array(Vec<Vec<FormulaValue>>),
}

/// 公式错误类型
#[derive(Debug, Clone, PartialEq)]
pub enum FormulaError {
    /// 除零错误 #DIV/0!
    DivisionByZero,
    /// 值错误 #VALUE!
    ValueError,
    /// 引用错误 #REF!
    ReferenceError,
    /// 名称错误 #NAME?
    NameError,
    /// 数字错误 #NUM!
    NumError,
    /// 不可用 #N/A
    NotAvailable,
    /// 空值错误 #NULL!
    NullError,
    /// 数组溢出 #SPILL!
    SpillError,
}

/// 公式表达式节点
#[derive(Debug, Clone, PartialEq)]
pub enum FormulaExpression {
    /// 常量值
    Constant(FormulaValue),
    /// 单元格引用
    CellRef(CellReference),
    /// 范围引用
    RangeRef(CellReference, CellReference),
    /// 函数调用
    Function {
        name: String,
        args: Vec<FormulaExpression>,
    },
    /// 二元操作
    BinaryOp {
        op: BinaryOperator,
        left: Box<FormulaExpression>,
        right: Box<FormulaExpression>,
    },
    /// 一元操作
    UnaryOp {
        op: UnaryOperator,
        operand: Box<FormulaExpression>,
    },
}

/// 二元操作符
#[derive(Debug, Clone, PartialEq)]
pub enum BinaryOperator {
    /// 加法
    Add,
    /// 减法
    Subtract,
    /// 乘法
    Multiply,
    /// 除法
    Divide,
    /// 幂运算
    Power,
    /// 等于
    Equal,
    /// 不等于
    NotEqual,
    /// 小于
    LessThan,
    /// 小于等于
    LessThanOrEqual,
    /// 大于
    GreaterThan,
    /// 大于等于
    GreaterThanOrEqual,
    /// 字符串连接
    Concatenate,
    /// 逻辑或
    LogicalOr,
    /// 逻辑与
    LogicalAnd,
}

/// 一元操作符
#[derive(Debug, Clone, PartialEq)]
pub enum UnaryOperator {
    /// 正号
    Plus,
    /// 负号
    Minus,
    /// 百分号
    Percent,
    /// 阶乘
    Factorial,
}

/// 公式词法单元
#[derive(Debug, Clone, PartialEq)]
pub enum Token {
    /// 数字
    Number(f64),
    /// 字符串
    String(String),
    /// 标识符(函数名或命名范围)
    Identifier(String),
    /// 单元格引用
    CellReference(String),
    /// 操作符
    Operator(String),
    /// 左括号
    LeftParen,
    /// 右括号
    RightParen,
    /// 逗号
    Comma,
    /// 冒号(范围分隔符)
    Colon,
    /// 分号
    Semicolon,
    /// 文件结束
    Eof,
}

/// 公式解析器
pub struct FormulaParser {
    tokens: Vec<Token>,
    current: usize,
}

/// 公式计算器
pub struct FormulaCalculator {
    /// 单元格数据提供者
    cell_provider: Box<dyn CellProvider>,
    /// 函数库
    function_library: FunctionLibrary,
    /// 计算缓存
    cache: HashMap<String, FormulaValue>,
}

/// 单元格数据提供者接口
pub trait CellProvider {
    /// 获取单元格值
    fn get_cell_value(&self, reference: &CellReference) -> Result<CellValue>;

    /// 获取范围内的所有单元格值
    fn get_range_values(
        &self,
        start: &CellReference,
        end: &CellReference
    ) -> Result<Vec<Vec<CellValue>>>;
}

/// 函数库
pub struct FunctionLibrary {
    functions: HashMap<String, Box<dyn FormulaFunction>>,
}

/// 公式函数接口
pub trait FormulaFunction {
    /// 函数名称
    fn name(&self) -> &str;

    /// 最小参数数量
    fn min_args(&self) -> usize;

    /// 最大参数数量(None表示无限制)
    fn max_args(&self) -> Option<usize>;

    /// 执行函数
    fn execute(&self, args: &[FormulaValue]) -> Result<FormulaValue>;
}

/// 公式依赖关系
#[derive(Debug, Clone)]
pub struct FormulaDependency {
    /// 公式所在单元格
    pub formula_cell: CellReference,
    /// 依赖的单元格
    pub dependent_cells: HashSet<CellReference>,
}

/// 公式管理器
pub struct FormulaManager {
    /// 公式表达式缓存
    formulas: HashMap<CellReference, FormulaExpression>,
    /// 依赖关系图
    dependencies: HashMap<CellReference, FormulaDependency>,
    /// 计算器
    calculator: FormulaCalculator,
}

impl fmt::Display for FormulaError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FormulaError::DivisionByZero => write!(f, "#DIV/0!"),
            FormulaError::ValueError => write!(f, "#VALUE!"),
            FormulaError::ReferenceError => write!(f, "#REF!"),
            FormulaError::NameError => write!(f, "#NAME?"),
            FormulaError::NumError => write!(f, "#NUM!"),
            FormulaError::NotAvailable => write!(f, "#N/A"),
            FormulaError::NullError => write!(f, "#NULL!"),
            FormulaError::SpillError => write!(f, "#SPILL!"),
        }
    }
}

impl FormulaValue {
    /// 转换为数字
    pub fn as_number(&self) -> Result<f64> {
        match self {
            FormulaValue::Number(n) => Ok(*n),
            FormulaValue::Boolean(b) => Ok(if *b { 1.0 } else { 0.0 }),
            FormulaValue::Text(s) =>
                s.parse::<f64>().map_err(|_| {
                    OfficeError::Xlsx(XlsxError::InvalidFormula {
                        formula: format!("Cannot convert '{}' to number", s),
                    })
                }),
            FormulaValue::Error(e) =>
                Err(
                    OfficeError::Xlsx(XlsxError::InvalidFormula {
                        formula: format!("Formula error: {:?}", e),
                    })
                ),
            FormulaValue::Array(_) =>
                Err(
                    OfficeError::Xlsx(XlsxError::InvalidFormula {
                        formula: "Cannot convert array to number".to_string(),
                    })
                ),
        }
    }

    /// 转换为文本
    pub fn as_text(&self) -> String {
        match self {
            FormulaValue::Number(n) => n.to_string(),
            FormulaValue::Text(s) => s.clone(),
            FormulaValue::Boolean(b) => b.to_string().to_uppercase(),
            FormulaValue::Error(e) => e.to_string(),
            FormulaValue::Array(_) => "#VALUE!".to_string(),
        }
    }

    /// 转换为布尔值
    pub fn as_boolean(&self) -> Result<bool> {
        match self {
            FormulaValue::Boolean(b) => Ok(*b),
            FormulaValue::Number(n) => Ok(*n != 0.0),
            FormulaValue::Text(s) =>
                match s.to_uppercase().as_str() {
                    "TRUE" => Ok(true),
                    "FALSE" => Ok(false),
                    _ =>
                        Err(
                            OfficeError::Xlsx(XlsxError::InvalidFormula {
                                formula: format!("Cannot convert '{}' to boolean", s),
                            })
                        ),
                }
            FormulaValue::Error(e) =>
                Err(
                    OfficeError::Xlsx(XlsxError::InvalidFormula {
                        formula: format!("Formula error: {:?}", e),
                    })
                ),
            FormulaValue::Array(_) =>
                Err(
                    OfficeError::Xlsx(XlsxError::InvalidFormula {
                        formula: "Cannot convert array to boolean".to_string(),
                    })
                ),
        }
    }

    /// 判断是否为错误值
    pub fn is_error(&self) -> bool {
        matches!(self, FormulaValue::Error(_))
    }

    /// 判断是否为数字
    pub fn is_number(&self) -> bool {
        matches!(self, FormulaValue::Number(_))
    }

    /// 判断是否为文本
    pub fn is_text(&self) -> bool {
        matches!(self, FormulaValue::Text(_))
    }

    /// 判断是否为布尔值
    pub fn is_boolean(&self) -> bool {
        matches!(self, FormulaValue::Boolean(_))
    }
}

impl FormulaParser {
    /// 创建新的公式解析器
    pub fn new(formula: &str) -> Result<Self> {
        let tokens = Self::tokenize(formula)?;
        Ok(Self { tokens, current: 0 })
    }

    /// 解析公式
    pub fn parse(&mut self) -> Result<FormulaExpression> {
        self.parse_expression()
    }

    /// 词法分析
    fn tokenize(formula: &str) -> Result<Vec<Token>> {
        let mut tokens = Vec::new();
        let mut chars = formula.chars().peekable();

        while let Some(&ch) = chars.peek() {
            match ch {
                ' ' | '\t' | '\n' | '\r' => {
                    chars.next();
                }
                '(' => {
                    tokens.push(Token::LeftParen);
                    chars.next();
                }
                ')' => {
                    tokens.push(Token::RightParen);
                    chars.next();
                }
                ',' => {
                    tokens.push(Token::Comma);
                    chars.next();
                }
                ':' => {
                    tokens.push(Token::Colon);
                    chars.next();
                }
                ';' => {
                    tokens.push(Token::Semicolon);
                    chars.next();
                }
                '+' | '-' | '*' | '/' | '^' | '=' | '<' | '>' | '&' | '|' | '%' => {
                    let mut op = String::new();
                    op.push(chars.next().unwrap());

                    // 处理复合操作符
                    // if let Some(&next_ch) = chars.peek() {
                    //     if
                    //         (ch == '<' && next_ch == '=') ||
                    //         (ch == '>' && next_ch == '=') ||
                    //         (ch == '<' && next_ch == '>')
                    //     {
                    //         op.push(chars.next().unwrap());
                    //     } else {
                    //         return Err(
                    //             OfficeError::Xlsx(XlsxError::InvalidFormula {
                    //                 formula: format!("Unexpected character after operator: {}", next_ch),
                    //             })
                    //         );
                    //     }
                    // }

                    // 预先定义有效的双字符操作符
                    let valid_double_ops = [
                        "<=", // 小于等于
                        ">=", // 大于等于
                        "<>", // 比较
                    ];

                    if let Some(&next_ch) = chars.peek() {
                        let potential_op = format!("{}{}", ch, next_ch);
                        if valid_double_ops.contains(&potential_op.as_str()) {
                            op.push(chars.next().unwrap()); // 消费下一个字符
                        }
                    }

                    tokens.push(Token::Operator(op));
                }
                '"' => {
                    chars.next(); // 跳过开始引号
                    let mut string_val = String::new();

                    while let Some(ch) = chars.next() {
                        if ch == '"' {
                            // 检查是否是转义的引号
                            if chars.peek() == Some(&'"') {
                                string_val.push('"');
                                chars.next();
                            } else {
                                break;
                            }
                        } else {
                            string_val.push(ch);
                        }
                    }

                    tokens.push(Token::String(string_val));
                }
                '0'..='9' | '.' => {
                    let mut number = String::new();

                    while let Some(&ch) = chars.peek() {
                        if ch.is_ascii_digit() || ch == '.' {
                            number.push(chars.next().unwrap());
                        } else {
                            break;
                        }
                    }

                    let num_val = number
                        .parse::<f64>()
                        .map_err(|_| {
                            OfficeError::Xlsx(XlsxError::InvalidFormula { formula: number })
                        })?;

                    tokens.push(Token::Number(num_val));
                }
                'A'..='Z' | 'a'..='z' | '$' => {
                    let mut identifier = String::new();

                    // 处理可能的单元格引用或标识符
                    while let Some(&ch) = chars.peek() {
                        if ch.is_ascii_alphanumeric() || ch == '$' || ch == '_' {
                            identifier.push(chars.next().unwrap());
                        } else {
                            break;
                        }
                    }

                    // 判断是单元格引用还是标识符
                    if Self::is_cell_reference(&identifier) {
                        tokens.push(Token::CellReference(identifier));
                    } else if
                        identifier.to_uppercase() == "TRUE" ||
                        identifier.to_uppercase() == "FALSE"
                    {
                        tokens.push(Token::Identifier(identifier));
                    } else {
                        tokens.push(Token::Identifier(identifier));
                    }
                }
                _ => {
                    return Err(
                        OfficeError::Xlsx(XlsxError::InvalidFormula {
                            formula: format!("Unexpected character: {}", ch),
                        })
                    );
                }
            }
        }

        tokens.push(Token::Eof);
        Ok(tokens)
    }

    /// 判断是否为单元格引用
    fn is_cell_reference(text: &str) -> bool {
        let text = text.trim();

        // 检查是否为空
        if text.is_empty() {
            return false;
        }

        // 检查是否以$结尾
        if text.ends_with("$") {
            return false;
        }

        let mut chars = text.chars().peekable();
        let mut dollar_count = 0;

        // 处理可能的列绝对引用符号$
        if chars.peek() == Some(&'$') {
            chars.next();
            dollar_count += 1;
        }

        // 处理列字母部分
        let mut has_col_letter = false;
        while let Some(ch) = chars.peek() {
            if ch.is_ascii_uppercase() {
                chars.next();
                has_col_letter = true;
            } else {
                break;
            }
        }

        // 如果没有列字母,则不是有效的单元格引用
        if !has_col_letter {
            return false;
        }

        // 处理可能的列绝对引用符号$
        if chars.peek() == Some(&'$') {
            chars.next();
            dollar_count += 1;
        }

        // 处理行数字部分
        let mut has_row_number = false;
        while let Some(ch) = chars.peek() {
            if ch.is_ascii_digit() {
                chars.next();
                has_row_number = true;
            } else {
                break;
            }
        }

        // 如果没有行数字,则不是有效的单元格引用
        if !has_row_number {
            return false;
        }

        // 处理可能的行绝对引用符号$
        if chars.peek() == Some(&'$') {
            chars.next();
            dollar_count += 1;
            // 如果$符号后面还有字符,则不是有效的单元格引用
            if chars.peek().is_some() {
                return false;
            }
        }

        // 确保所有字符都已处理完,有字母和数字,且$符号不超过2个
        chars.next().is_none() && dollar_count <= 2
    }

    /// 解析表达式
    fn parse_expression(&mut self) -> Result<FormulaExpression> {
        self.parse_logical_or()
    }

    /// 解析逻辑或表达式
    fn parse_logical_or(&mut self) -> Result<FormulaExpression> {
        let mut expr = self.parse_logical_and()?;

        while self.match_operator("|") {
            let right = self.parse_logical_and()?;
            expr = FormulaExpression::BinaryOp {
                op: BinaryOperator::LogicalOr,
                left: Box::new(expr),
                right: Box::new(right),
            };
        }

        Ok(expr)
    }

    /// 解析逻辑与表达式
    fn parse_logical_and(&mut self) -> Result<FormulaExpression> {
        let mut expr = self.parse_equality()?;

        while self.match_operator("&") {
            let right = self.parse_equality()?;
            expr = FormulaExpression::BinaryOp {
                op: BinaryOperator::LogicalAnd,
                left: Box::new(expr),
                right: Box::new(right),
            };
        }

        Ok(expr)
    }

    /// 解析相等性表达式
    fn parse_equality(&mut self) -> Result<FormulaExpression> {
        let mut expr = self.parse_comparison()?;

        while let Some(op) = self.match_equality_operator() {
            let right = self.parse_comparison()?;
            expr = FormulaExpression::BinaryOp {
                op,
                left: Box::new(expr),
                right: Box::new(right),
            };
        }

        Ok(expr)
    }

    /// 解析比较表达式
    fn parse_comparison(&mut self) -> Result<FormulaExpression> {
        let mut expr = self.parse_addition()?;

        while let Some(op) = self.match_comparison_operator() {
            let right = self.parse_addition()?;
            expr = FormulaExpression::BinaryOp {
                op,
                left: Box::new(expr),
                right: Box::new(right),
            };
        }

        Ok(expr)
    }

    /// 解析加减表达式
    fn parse_addition(&mut self) -> Result<FormulaExpression> {
        let mut expr = self.parse_multiplication()?;

        while let Some(op) = self.match_addition_operator() {
            let right = self.parse_multiplication()?;
            expr = FormulaExpression::BinaryOp {
                op,
                left: Box::new(expr),
                right: Box::new(right),
            };
        }

        Ok(expr)
    }

    /// 解析乘除表达式
    fn parse_multiplication(&mut self) -> Result<FormulaExpression> {
        let mut expr = self.parse_power()?;

        while let Some(op) = self.match_multiplication_operator() {
            let right = self.parse_power()?;
            expr = FormulaExpression::BinaryOp {
                op,
                left: Box::new(expr),
                right: Box::new(right),
            };
        }

        Ok(expr)
    }

    /// 解析幂运算表达式
    fn parse_power(&mut self) -> Result<FormulaExpression> {
        let mut expr = self.parse_unary()?;

        // 检查后缀一元操作符(百分号)
        if self.match_operator("%") {
            expr = FormulaExpression::UnaryOp {
                op: UnaryOperator::Percent,
                operand: Box::new(expr),
            };
        }

        if self.match_operator("^") {
            let right = self.parse_power()?; // 右结合
            expr = FormulaExpression::BinaryOp {
                op: BinaryOperator::Power,
                left: Box::new(expr),
                right: Box::new(right),
            };
        }

        Ok(expr)
    }

    /// 解析一元表达式
    fn parse_unary(&mut self) -> Result<FormulaExpression> {
        // 处理前缀一元操作符(+、-)
        if let Some(op) = self.match_unary_operator() {
            // 只有加号和减号是前缀操作符
            if matches!(op, UnaryOperator::Plus | UnaryOperator::Minus) {
                let operand = self.parse_unary()?;
                return Ok(FormulaExpression::UnaryOp {
                    op,
                    operand: Box::new(operand),
                });
            } else {
                // 如果是百分号,回退并按后缀操作符处理
                self.current -= 1;
            }
        }

        self.parse_primary()
    }

    /// 解析基本表达式
    fn parse_primary(&mut self) -> Result<FormulaExpression> {
        match &self.current_token()? {
            Token::Number(n) => {
                let value = *n;
                self.advance();
                Ok(FormulaExpression::Constant(FormulaValue::Number(value)))
            }
            Token::String(s) => {
                let value = s.clone();
                self.advance();
                Ok(FormulaExpression::Constant(FormulaValue::Text(value)))
            }
            Token::CellReference(ref_str) => {
                let cell_ref = CellReference::from_a1(ref_str)?;
                self.advance();

                // 检查是否是范围引用
                if self.match_token(&Token::Colon) {
                    if let Token::CellReference(end_ref_str) = &self.current_token()? {
                        let end_ref = CellReference::from_a1(end_ref_str)?;
                        self.advance();
                        Ok(FormulaExpression::RangeRef(cell_ref, end_ref))
                    } else {
                        Err(
                            OfficeError::Xlsx(XlsxError::InvalidFormula {
                                formula: "Expected cell reference after colon".to_string(),
                            })
                        )
                    }
                } else {
                    Ok(FormulaExpression::CellRef(cell_ref))
                }
            }
            Token::Identifier(name) => {
                let func_name = name.clone();
                self.advance();

                // 检查是否是布尔常量
                if func_name.to_uppercase() == "TRUE" {
                    return Ok(FormulaExpression::Constant(FormulaValue::Boolean(true)));
                } else if func_name.to_uppercase() == "FALSE" {
                    return Ok(FormulaExpression::Constant(FormulaValue::Boolean(false)));
                }

                if self.match_token(&Token::LeftParen) {
                    // 函数调用
                    let mut args = Vec::new();

                    if !self.check_token(&Token::RightParen) {
                        loop {
                            args.push(self.parse_expression()?);

                            if !self.match_token(&Token::Comma) {
                                break;
                            }
                        }
                    }

                    if !self.match_token(&Token::RightParen) {
                        return Err(
                            OfficeError::Xlsx(XlsxError::InvalidFormula {
                                formula: "Expected ')' after function arguments".to_string(),
                            })
                        );
                    }

                    Ok(FormulaExpression::Function {
                        name: func_name,
                        args,
                    })
                } else {
                    // 命名范围或其他标识符
                    Err(
                        OfficeError::Xlsx(XlsxError::InvalidFormula {
                            formula: format!("Unknown identifier: {}", func_name),
                        })
                    )
                }
            }
            Token::LeftParen => {
                self.advance();
                let expr = self.parse_expression()?;

                if !self.match_token(&Token::RightParen) {
                    return Err(
                        OfficeError::Xlsx(XlsxError::InvalidFormula {
                            formula: "Expected ')'".to_string(),
                        })
                    );
                }

                Ok(expr)
            }
            _ =>
                Err(
                    OfficeError::Xlsx(XlsxError::InvalidFormula {
                        formula: "Unexpected token".to_string(),
                    })
                ),
        }
    }

    /// 获取当前token
    fn current_token(&self) -> Result<&Token> {
        self.tokens.get(self.current).ok_or_else(|| {
            OfficeError::Xlsx(XlsxError::InvalidFormula {
                formula: "Unexpected end of formula".to_string(),
            })
        })
    }

    /// 前进到下一个token
    fn advance(&mut self) {
        if self.current < self.tokens.len() {
            self.current += 1;
        }
    }

    /// 检查当前token是否匹配
    fn check_token(&self, token: &Token) -> bool {
        if let Ok(current) = self.current_token() {
            std::mem::discriminant(current) == std::mem::discriminant(token)
        } else {
            false
        }
    }

    /// 匹配并消费token
    fn match_token(&mut self, token: &Token) -> bool {
        if self.check_token(token) {
            self.advance();
            true
        } else {
            false
        }
    }

    /// 匹配操作符
    fn match_operator(&mut self, op: &str) -> bool {
        if let Ok(Token::Operator(current_op)) = self.current_token() {
            if current_op == op {
                self.advance();
                return true;
            }
        }
        false
    }

    /// 匹配相等性操作符
    fn match_equality_operator(&mut self) -> Option<BinaryOperator> {
        if let Ok(Token::Operator(op)) = self.current_token() {
            let result = match op.as_str() {
                "=" => Some(BinaryOperator::Equal),
                "<>" => Some(BinaryOperator::NotEqual),
                _ => None,
            };

            if result.is_some() {
                self.advance();
            }

            result
        } else {
            None
        }
    }

    /// 匹配比较操作符
    fn match_comparison_operator(&mut self) -> Option<BinaryOperator> {
        if let Ok(Token::Operator(op)) = self.current_token() {
            let result = match op.as_str() {
                "<" => Some(BinaryOperator::LessThan),
                "<=" => Some(BinaryOperator::LessThanOrEqual),
                ">" => Some(BinaryOperator::GreaterThan),
                ">=" => Some(BinaryOperator::GreaterThanOrEqual),
                "<>" => Some(BinaryOperator::NotEqual),
                _ => None,
            };

            if result.is_some() {
                self.advance();
            }

            result
        } else {
            None
        }
    }

    /// 匹配加减操作符
    fn match_addition_operator(&mut self) -> Option<BinaryOperator> {
        if let Ok(Token::Operator(op)) = self.current_token() {
            let result = match op.as_str() {
                "+" => Some(BinaryOperator::Add),
                "-" => Some(BinaryOperator::Subtract),
                _ => None,
            };

            if result.is_some() {
                self.advance();
            }

            result
        } else {
            None
        }
    }

    /// 匹配乘除操作符
    fn match_multiplication_operator(&mut self) -> Option<BinaryOperator> {
        if let Ok(Token::Operator(op)) = self.current_token() {
            let result = match op.as_str() {
                "*" => Some(BinaryOperator::Multiply),
                "/" => Some(BinaryOperator::Divide),
                _ => None,
            };

            if result.is_some() {
                self.advance();
            }

            result
        } else {
            None
        }
    }

    /// 匹配一元操作符
    fn match_unary_operator(&mut self) -> Option<UnaryOperator> {
        if let Ok(Token::Operator(op)) = self.current_token() {
            let result = match op.as_str() {
                "+" => Some(UnaryOperator::Plus),
                "-" => Some(UnaryOperator::Minus),
                "%" => Some(UnaryOperator::Percent),
                "!" => Some(UnaryOperator::Factorial),
                _ => None,
            };

            if result.is_some() {
                self.advance();
            }

            result
        } else {
            None
        }
    }
}

/// 解析公式字符串
pub fn parse_formula(formula: &str) -> Result<FormulaExpression> {
    // 如果公式以'='开头,跳过它
    let formula_content = if formula.starts_with('=') { &formula[1..] } else { formula };

    let mut parser = FormulaParser::new(formula_content)?;
    parser.parse()
}

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

    #[test]
    fn test_tokenize_simple() {
        let tokens = FormulaParser::tokenize("1+2").unwrap();
        assert_eq!(tokens.len(), 4); // 1, +, 2, EOF
    }

    #[test]
    fn test_parse_simple_addition() {
        let expr = parse_formula("1+2").unwrap();
        match expr {
            FormulaExpression::BinaryOp { op: BinaryOperator::Add, .. } => {}
            _ => panic!("Expected addition expression"),
        }
    }

    #[test]
    fn test_parse_cell_reference() {
        let expr = parse_formula("A1").unwrap();
        match expr {
            FormulaExpression::CellRef(_) => {}
            _ => panic!("Expected cell reference"),
        }
    }

    #[test]
    fn test_parse_function_call() {
        let expr = parse_formula("SUM(A1:A10)").unwrap();
        match expr {
            FormulaExpression::Function { name, args } => {
                assert_eq!(name, "SUM");
                assert_eq!(args.len(), 1);
            }
            _ => panic!("Expected function call"),
        }
    }

    #[test]
    fn test_formula_value_conversions() {
        let num_val = FormulaValue::Number(42.0);
        assert_eq!(num_val.as_number().unwrap(), 42.0);
        assert_eq!(num_val.as_text(), "42");

        let bool_val = FormulaValue::Boolean(true);
        assert_eq!(bool_val.as_boolean().unwrap(), true);
        assert_eq!(bool_val.as_number().unwrap(), 1.0);
    }

    #[test]
    fn test_logical_or_operator() {
        let expr = parse_formula("TRUE|FALSE").unwrap();
        match expr {
            FormulaExpression::BinaryOp { op: BinaryOperator::LogicalOr, .. } => {}
            _ => panic!("Expected logical OR expression"),
        }
    }

    #[test]
    fn test_logical_and_operator() {
        let expr = parse_formula("TRUE&FALSE").unwrap();
        match expr {
            FormulaExpression::BinaryOp { op: BinaryOperator::LogicalAnd, .. } => {}
            _ => panic!("Expected logical AND expression"),
        }
    }

    #[test]
    fn test_boolean_constants() {
        let expr = parse_formula("TRUE").unwrap();
        match expr {
            FormulaExpression::Constant(FormulaValue::Boolean(true)) => {}
            _ => panic!("Expected TRUE constant"),
        }

        let expr = parse_formula("FALSE").unwrap();
        match expr {
            FormulaExpression::Constant(FormulaValue::Boolean(false)) => {}
            _ => panic!("Expected FALSE constant"),
        }
    }

    #[test]
    fn test_mixed_logical_operations() {
        let expr = parse_formula("TRUE|FALSE&TRUE").unwrap();
        // 应该解析为 TRUE|(FALSE&TRUE),因为 & 的优先级高于 |
        match expr {
            FormulaExpression::BinaryOp { op: BinaryOperator::LogicalOr, left, right } => {
                match *left {
                    FormulaExpression::Constant(FormulaValue::Boolean(true)) => {}
                    _ => panic!("Expected TRUE constant"),
                }
                match *right {
                    FormulaExpression::BinaryOp { op: BinaryOperator::LogicalAnd, .. } => {}
                    _ => panic!("Expected logical AND expression"),
                }
            }
            _ => panic!("Expected logical OR expression"),
        }
    }

    #[test]
    fn test_case_insensitive_boolean_constants() {
        let expr = parse_formula("true").unwrap();
        match expr {
            FormulaExpression::Constant(FormulaValue::Boolean(true)) => {}
            _ => panic!("Expected TRUE constant"),
        }

        let expr = parse_formula("False").unwrap();
        match expr {
            FormulaExpression::Constant(FormulaValue::Boolean(false)) => {}
            _ => panic!("Expected FALSE constant"),
        }
    }

    #[test]
    fn test_is_cell_reference() {
        // 有效的单元格引用
        assert!(FormulaParser::is_cell_reference("A1"));
        assert!(FormulaParser::is_cell_reference("Z999"));
        assert!(FormulaParser::is_cell_reference("AA1"));
        assert!(FormulaParser::is_cell_reference("AZ999"));
        assert!(FormulaParser::is_cell_reference("$A$1"));
        assert!(FormulaParser::is_cell_reference("$Z$999"));
        assert!(FormulaParser::is_cell_reference("A$1"));
        assert!(FormulaParser::is_cell_reference("$A1"));
        assert!(FormulaParser::is_cell_reference("AA$1"));
        assert!(FormulaParser::is_cell_reference("$AA1"));

        // 无效的单元格引用
        assert!(!FormulaParser::is_cell_reference("A"));
        assert!(!FormulaParser::is_cell_reference("1"));
        assert!(!FormulaParser::is_cell_reference("$A"));
        assert!(!FormulaParser::is_cell_reference("A$"));
        assert!(!FormulaParser::is_cell_reference("$$A1"));
        assert!(!FormulaParser::is_cell_reference("A1$"));
        assert!(!FormulaParser::is_cell_reference("A1$1"));
        assert!(!FormulaParser::is_cell_reference("A$$1"));
        assert!(!FormulaParser::is_cell_reference("$A$1$"));
        assert!(!FormulaParser::is_cell_reference(""));
        assert!(!FormulaParser::is_cell_reference("AB CD"));
    }

    #[test]
    fn test_compound_operators() {
        // 比较操作符
        let expr = parse_formula("A1<=B1").unwrap();
        match expr {
            FormulaExpression::BinaryOp { op: BinaryOperator::LessThanOrEqual, .. } => {}
            _ => panic!("Expected less than or equal expression"),
        }

        let expr = parse_formula("A1>=B1").unwrap();
        match expr {
            FormulaExpression::BinaryOp { op: BinaryOperator::GreaterThanOrEqual, .. } => {}
            _ => panic!("Expected greater than or equal expression"),
        }

        let expr = parse_formula("A1<>B1").unwrap();
        match expr {
            FormulaExpression::BinaryOp { op: BinaryOperator::NotEqual, .. } => {}
            _ => panic!("Expected not equal expression"),
        }
    }

    #[test]
    fn test_invalid_operator_combinations() {
        // 测试无效的操作符组合
        // assert!(parse_formula("1++2").is_err());
        // assert!(parse_formula("1+-2").is_err());
        assert!(parse_formula("1<=<2").is_err());
        assert!(parse_formula("1>=>2").is_err());
        assert!(parse_formula("1&&>2").is_err());
        assert!(parse_formula("1||<2").is_err());
        assert!(parse_formula("TRUE||FALSE").is_err());
        assert!(parse_formula("TRUE&&TRUE").is_err());
        assert!(parse_formula("TRUE && TRUE").is_err());
    }

    #[test]
    fn test_operator_spacing() {
        // 测试操作符周围的空格处理
        let expr = parse_formula("A1 <= B1").unwrap();
        match expr {
            FormulaExpression::BinaryOp { op: BinaryOperator::LessThanOrEqual, .. } => {}
            _ => panic!("Expected less than or equal expression"),
        }
    }
}