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
//! Statement parsing for the Oxabl parser.
//!
//! Handles DEFINE VARIABLE, VAR, assignments, DO blocks (with counting loops),
//! IF/THEN/ELSE, REPEAT, FOR EACH, FIND, CASE, PROCEDURE, RUN, DISPLAY,
//! MESSAGE, LEAVE, NEXT, and RETURN statements.
use oxabl_ast::{
DisplayItem, Expression, FindType, Identifier, LockType, ParameterDirection, RunArgument,
RunTarget, Span, Statement, WhenBranch,
};
use oxabl_lexer::{Kind, is_callable_kind};
use super::{ParseError, ParseResult, Parser};
impl Parser<'_> {
pub fn parse_statement(&mut self) -> ParseResult<Statement> {
// Skip empty statements
if self.check(Kind::Period) {
self.advance();
return Ok(Statement::Empty);
}
// DO blocks
if self.check(Kind::Do) {
return self.parse_do_statement();
}
// IF statement
if self.check(Kind::KwIf) {
return self.parse_if_statement();
}
// Repeat block
if self.check(Kind::Repeat) {
return self.parse_repeat_statement();
}
// LEAVE
if self.check(Kind::Leave) {
self.advance();
self.expect_kind(Kind::Period, "Expected '.' to come after LEAVE")?;
return Ok(Statement::Leave);
}
// Next
if self.check(Kind::Next) {
self.advance();
self.expect_kind(Kind::Period, "Expected '.' to come after NEXT")?;
return Ok(Statement::Next);
}
// Return
if self.check(Kind::KwReturn) {
return self.parse_return_statement();
}
// FOR EACH
if self.check(Kind::KwFor) {
return self.parse_for_each();
}
// FIND statement
if self.check(Kind::Find) {
return self.parse_find_statement();
}
// CASE statement
if self.check(Kind::Case) {
return self.parse_case_statement();
}
// RUN statement
if self.check(Kind::Run) {
return self.parse_run_statement();
}
// PROCEDURE statement
if self.check(Kind::Procedure) {
return self.parse_procedure();
}
// RUN statement
if self.check(Kind::Run) {
return self.parse_run_statement();
}
// DISPLAY statement
if self.check(Kind::Display) {
return self.parse_display_statement();
}
// MESSAGE statement
if self.check(Kind::Message) {
return self.parse_message_statement();
}
// Check for traditional define statement
// def var name as type [no-undo] [initial value] [extent n].
if self.check(Kind::Define) {
return self.parse_define_statement();
}
// Check for new var statement
// var char name [=] [5].
if self.check(Kind::Identifier) {
let token = self.peek();
let text = &self.source[token.start..token.end];
if text.eq_ignore_ascii_case("var") {
return self.parse_var_statement();
}
}
// Parse left-hand assignment, stop before comparison operators
let left = self.parse_additive()?;
if self.check(Kind::Equals) {
self.advance(); // consume the "="
let value = self.parse_expression()?;
self.expect_kind(Kind::Period, "Expected '.' to end statement")?;
return Ok(Statement::Assignment {
target: left,
value,
});
}
// not an assignment, continue parsing as full expression
let expr = self.finish_expression(left)?;
self.expect_kind(Kind::Period, "Expected '.' to end statement")?;
Ok(Statement::ExpressionStatement(expr))
}
// parse define variable as type [no-undo] [initial]
fn parse_define_statement(&mut self) -> ParseResult<Statement> {
self.advance(); // consume DEFINE
// parse INPUT/OUTPUT parameters
if self.check(Kind::Input) || self.check(Kind::Output) || self.check(Kind::InputOutput) {
return self.parse_define_parameter();
}
// Variable
if !self.check(Kind::Identifier) {
return Err(ParseError {
message: "Expected variable name after DEFINE".to_string(),
span: Span {
start: self.peek().start as u32,
end: self.peek().end as u32,
},
});
}
let define_what = self.peek();
let define_text = &self.source[define_what.start..define_what.end];
if !define_text.eq_ignore_ascii_case("variable") && !define_text.eq_ignore_ascii_case("var")
{
return Err(ParseError {
message: "Expected VARIABLE or VAR after DEFINE".to_string(),
span: Span {
start: define_what.start as u32,
end: define_what.end as u32,
},
});
}
self.advance(); // consume VARIABLE or VAR
// Name
if !is_callable_kind(self.peek().kind) {
return Err(ParseError {
message: "Expected variable name after DEFINE VARIABLE".to_string(),
span: Span {
start: self.peek().start as u32,
end: self.peek().end as u32,
},
});
}
let name_token = self.advance().clone();
let name = Identifier {
span: Span {
start: name_token.start as u32,
end: name_token.end as u32,
},
name: self.source[name_token.start..name_token.end].to_string(),
};
// expect As
self.expect_kind(Kind::KwAs, "Expected AS after variable name")?;
// parse data type
let data_type = self.parse_data_type()?;
// parse optional no-undo, initial, and extent
let mut no_undo = false;
let mut initial_value = None;
let mut extent = None;
loop {
if self.check(Kind::NoUndo) {
self.advance();
no_undo = true;
} else if self.check(Kind::Identifier) {
let token = self.peek();
let text = &self.source[token.start..token.end];
if text.eq_ignore_ascii_case("initial") || text.eq_ignore_ascii_case("init") {
self.advance(); // Consume init
initial_value = Some(self.parse_expression()?);
} else if text.eq_ignore_ascii_case("extent") {
self.advance(); // Consume extent
// Extent can be followed by number or nothing (dynamic)
if self.check(Kind::IntegerLiteral) {
let ext_token = self.advance().clone();
if let Ok(n) = self.source[ext_token.start..ext_token.end].parse::<u32>() {
extent = Some(n);
} else {
extent = Some(0); // dynamic
}
} // extent check if it's set or dynamic
} else {
// not initial or extent
break;
}
} else {
break; // not an identifier, exit loop
}
}
self.expect_kind(Kind::Period, "Expected '.' to end statement")?;
Ok(Statement::VariableDeclaration {
name,
data_type,
initial_value,
no_undo,
extent,
})
}
/// Parse: VAR type name [= value].
fn parse_var_statement(&mut self) -> ParseResult<Statement> {
self.advance(); // consume VAR
// Parse data type
let data_type = self.parse_data_type()?;
// Parse variable name
if !is_callable_kind(self.peek().kind) {
return Err(ParseError {
message: "Expected variable name".to_string(),
span: Span {
start: self.peek().start as u32,
end: self.peek().end as u32,
},
});
}
let name_token = self.advance().clone();
let name = Identifier {
span: Span {
start: name_token.start as u32,
end: name_token.end as u32,
},
name: self.source[name_token.start..name_token.end].to_string(),
};
// Optional initial value
let initial_value = if self.check(Kind::Equals) {
self.advance();
Some(self.parse_expression()?)
} else {
None
};
self.expect_kind(Kind::Period, "Expected '.' to end statement")?;
Ok(Statement::VariableDeclaration {
name,
data_type,
initial_value,
no_undo: true, // VAR implies NO-UNDO
extent: None,
})
}
fn parse_define_parameter(&mut self) -> ParseResult<Statement> {
// Parse direction (we already know it's INPUT, OUTPUT, or INPUT-OUTPUT)
let direction = match self.peek().kind {
Kind::Input => {
self.advance();
ParameterDirection::Input
}
Kind::Output => {
self.advance();
ParameterDirection::Output
}
Kind::InputOutput => {
self.advance();
ParameterDirection::InputOutput
}
_ => unreachable!("parse_define_parameter called without INPUT/OUTPUT token"),
};
// Expect PARAMETER keyword
self.expect_kind(Kind::Parameter, "Expected PARAMETER after INPUT/OUTPUT")?;
// Parse parameter name
if !is_callable_kind(self.peek().kind) {
return Err(ParseError {
message: "Expected parameter name".to_string(),
span: Span {
start: self.peek().start as u32,
end: self.peek().end as u32,
},
});
}
let name_token = self.advance().clone();
let name = Identifier {
span: Span {
start: name_token.start as u32,
end: name_token.end as u32,
},
name: self.source[name_token.start..name_token.end].to_string(),
};
// Expect AS
self.expect_kind(Kind::KwAs, "Expected AS after parameter name")?;
// Parse data type
let data_type = self.parse_data_type()?;
// Optional NO-UNDO
let no_undo = if self.check(Kind::NoUndo) {
self.advance();
true
} else {
false
};
self.expect_kind(Kind::Period, "Expected '.' after parameter definition")?;
Ok(Statement::DefineParameter {
direction,
name,
data_type,
no_undo,
})
}
/// Continue parsing an expression after additive level has been parsed
fn finish_expression(&mut self, left: Expression) -> ParseResult<Expression> {
// Handle comparison operators (except = which we already checked)
let expr = if self.is_non_equals_comparison_operator() {
let op_kind = self.advance().kind;
let right = self.parse_additive()?;
self.make_comparison(left, op_kind, right)
} else {
left
};
// Handle AND
let mut expr = expr;
while self.check(Kind::And) {
self.advance();
let right = self.parse_comparison()?;
expr = Expression::And(Box::new(expr), Box::new(right));
}
// Handle OR
while self.check(Kind::Or) {
self.advance();
let right = self.parse_and()?;
expr = Expression::Or(Box::new(expr), Box::new(right));
}
Ok(expr)
}
fn is_non_equals_comparison_operator(&self) -> bool {
matches!(
self.peek().kind,
Kind::NotEqual
| Kind::LessThan
| Kind::LessThanOrEqual
| Kind::GreaterThan
| Kind::GreaterThanOrEqual
| Kind::Ne
| Kind::Lt
| Kind::Le
| Kind::Gt
| Kind::Ge
| Kind::Begins
| Kind::Matches
| Kind::Contains
)
}
fn make_comparison(&self, left: Expression, op: Kind, right: Expression) -> Expression {
match op {
Kind::NotEqual | Kind::Ne => Expression::NotEqual(Box::new(left), Box::new(right)),
Kind::LessThan | Kind::Lt => Expression::LessThan(Box::new(left), Box::new(right)),
Kind::LessThanOrEqual | Kind::Le => {
Expression::LessThanOrEqual(Box::new(left), Box::new(right))
}
Kind::GreaterThan | Kind::Gt => {
Expression::GreaterThan(Box::new(left), Box::new(right))
}
Kind::GreaterThanOrEqual | Kind::Ge => {
Expression::GreaterThanOrEqual(Box::new(left), Box::new(right))
}
Kind::Begins => Expression::Begins(Box::new(left), Box::new(right)),
Kind::Matches => Expression::Matches(Box::new(left), Box::new(right)),
Kind::Contains => Expression::Contains(Box::new(left), Box::new(right)),
_ => unreachable!(),
}
}
/// Parse multiple statements until we hit a terminator
pub fn parse_statements(&mut self) -> ParseResult<Vec<Statement>> {
let mut statements = Vec::new();
while !self.at_end() {
statements.push(self.parse_statement()?);
}
Ok(statements)
}
fn parse_do_statement(&mut self) -> ParseResult<Statement> {
self.advance(); // Consume DO
let mut loop_var = None;
let mut from = None;
let mut to = None;
let mut by = None;
let mut while_condition = None;
// check for loop
if is_callable_kind(self.peek().kind) {
// peek ahead to see if this is 'var = start to end'
let saved_pos = self.current;
let potential_var = self.advance().clone();
if self.check(Kind::Equals) {
// It's a counting loop
let var_name = Identifier {
span: Span {
start: potential_var.start as u32,
end: potential_var.end as u32,
},
name: self.source[potential_var.start..potential_var.end].to_string(),
};
loop_var = Some(var_name);
self.advance(); // consume =
from = Some(self.parse_expression()?);
// Expect TO, because we have a var and consumed =
self.expect_kind(Kind::To, "Expected TO in DO loop")?;
to = Some(self.parse_expression()?);
// Optional BY
if self.check(Kind::By) {
self.advance();
by = Some(self.parse_expression()?);
}
} else {
// not a counting loop
self.current = saved_pos;
}
}
// check for WHILE
if self.check(Kind::KwWhile) {
self.advance();
while_condition = Some(self.parse_expression()?);
}
self.expect_kind(Kind::Colon, "Expected ':' after DO")?;
let body = self.parse_block_body()?;
Ok(Statement::Do {
loop_var,
from,
to,
by,
while_condition,
body,
})
}
fn parse_if_statement(&mut self) -> ParseResult<Statement> {
self.advance(); // Consumes IF
// If "condition" THEN
let condition = self.parse_expression()?;
// Expect THEN
self.expect_kind(Kind::Then, "Expected THEN after IF condition")?;
// parse then branch, may be a DO block or single statement
let then_branch = if self.check(Kind::Do) {
self.parse_do_statement()?
} else {
self.parse_statement()?
};
// optional ELSE
let else_branch = if self.check(Kind::KwElse) {
self.advance();
let else_stmt = if self.check(Kind::Do) {
self.parse_do_statement()?
} else if self.check(Kind::KwIf) {
self.parse_if_statement()?
} else {
self.parse_statement()?
};
Some(Box::new(else_stmt))
} else {
None
};
Ok(Statement::If {
condition,
then_branch: Box::new(then_branch),
else_branch,
})
}
fn parse_repeat_statement(&mut self) -> ParseResult<Statement> {
self.advance(); // consume REPEAT
// Optional WHILE
let while_condition = if self.check(Kind::KwWhile) {
self.advance();
Some(self.parse_expression()?)
} else {
None
};
// Expect colon
self.expect_kind(Kind::Colon, "Expected ':' after REPEAT")?;
let body = self.parse_block_body()?;
Ok(Statement::Repeat {
while_condition,
body,
})
}
fn parse_return_statement(&mut self) -> ParseResult<Statement> {
self.advance(); // consume RETURN
// Check if there's a return value (not just a period)
let value = if !self.check(Kind::Period) {
Some(self.parse_expression()?)
} else {
None
};
self.expect_kind(Kind::Period, "Expected a '.' after RETURN")?;
Ok(Statement::Return(value))
}
fn parse_for_each(&mut self) -> ParseResult<Statement> {
self.advance(); // Consume FOR
self.expect_kind(Kind::Each, "Expected EACH after FOR")?;
// Parse buffer name
let buffer = self.parse_identifier()?;
// optional OF clause
let of_relation = if self.check(Kind::Of) {
self.advance();
Some(self.parse_identifier()?)
} else {
None
};
// optional WHERE clause
let where_clause = if self.check(Kind::KwWhere) {
self.advance();
Some(self.parse_expression()?)
} else {
None
};
// Lock type (default is SHARE-LOCK if not explicit)
let lock_type = self.parse_lock_type();
self.expect_kind(Kind::Colon, "Expected ':' after FOR EACH")?;
let body = self.parse_block_body()?;
Ok(Statement::ForEach {
buffer,
of_relation,
where_clause,
lock_type,
body,
})
}
// parse find statements
fn parse_find_statement(&mut self) -> ParseResult<Statement> {
self.advance(); // Consume FIND
// parse optional find type
let find_type = match self.peek().kind {
Kind::First => {
self.advance();
FindType::First
}
Kind::Last => {
self.advance();
FindType::Last
}
Kind::Next => {
self.advance();
FindType::Next
}
Kind::Prev => {
self.advance();
FindType::Prev
}
_ => FindType::Unique,
};
// parse buffer/table name
let buffer = self.parse_identifier()?;
// parse optional key-value (FIND customer <key> syntax,
// equivalent to find customer where customer.primary-index field eq 1)
// Key value is present if next token is NOT a clause keyword, lock type, or terminator.
let key_value = if !self.is_find_clause_start() {
Some(self.parse_expression()?)
} else {
None
};
// parse optional where clause
let where_clause = if self.check(Kind::KwWhere) {
self.advance();
Some(self.parse_expression()?)
} else {
None
};
// parse lock type, defaults to share lock if none is present
let lock_type = self.parse_lock_type();
// parse optional no error
let no_error = if self.check(Kind::NoError) {
self.advance();
true
} else {
false
};
self.expect_kind(Kind::Period, "Expected '.' after FIND statement")?;
Ok(Statement::Find {
find_type,
buffer,
key_value,
where_clause,
lock_type,
no_error,
})
}
// Parse Case statement and when clauses
fn parse_case_statement(&mut self) -> ParseResult<Statement> {
self.advance(); // consume CASE
let expression = self.parse_expression()?;
self.expect_kind(Kind::Colon, "Expected a ':' after CASE expression")?;
let mut when_branches = Vec::new();
while self.check(Kind::When) {
self.advance();
// Use parse_and() instead of parse_expression() to avoid consuming OR
// This allows WHEN "a" OR WHEN "b" syntax to work correctly
let mut values = vec![self.parse_and()?];
// handle WHEN "a" OR WHEN "b" syntax
while self.check(Kind::Or) {
self.advance();
self.expect_kind(Kind::When, "Expected WHEN after OR")?;
values.push(self.parse_and()?);
}
self.expect_kind(Kind::Then, "Expected THEN after WHEN value")?;
// parse statements until next WHEN, OTHERWISE, or END
let mut body = Vec::new();
while !self.check(Kind::When) && !self.check(Kind::Otherwise) && !self.check(Kind::End)
{
body.push(self.parse_statement()?);
}
when_branches.push(WhenBranch { values, body });
}
let otherwise = if self.check(Kind::Otherwise) {
self.advance();
let mut body = Vec::new();
while !self.check(Kind::End) {
body.push(self.parse_statement()?);
}
Some(body)
} else {
None
};
self.expect_kind(Kind::End, "Expected END")?;
self.expect_kind(Kind::Case, "Expected CASE after END")?;
self.expect_kind(Kind::Period, "Expected '.' after END CASE")?;
Ok(Statement::Case {
expression,
when_branches,
otherwise,
})
}
fn parse_procedure(&mut self) -> ParseResult<Statement> {
self.advance(); // consume PROCEDURE
let name = self.parse_identifier()?;
self.expect_kind(Kind::Colon, "Expected ':' after procedure name")?;
// parse body until END
let mut body = Vec::new();
while !self.check(Kind::End) {
body.push(self.parse_statement()?);
}
self.expect_kind(Kind::End, "Expected END at end of PROCEDURE body")?;
// END PROCEDURE or just END. both are valid.
if self.check(Kind::Procedure) {
self.advance();
}
self.expect_kind(Kind::Period, "Expected '.' after END PROCEDURE")?;
Ok(Statement::Procedure { name, body })
}
// parse RUN statements
fn parse_run_statement(&mut self) -> ParseResult<Statement> {
self.advance(); // consume RUN
// Parse target: VALUE(expr), string literal, or procedure name
let target = if self.check(Kind::Value) {
self.advance();
self.expect_kind(Kind::LeftParen, "Expected '(' after VALUE")?;
let expr = self.parse_expression()?;
self.expect_kind(Kind::RightParen, "Expected ')' after VALUE expression")?;
RunTarget::Dynamic(expr)
} else if self.check(Kind::StringLiteral) {
// String literal target: RUN "my-proc.p".
let token = self.advance().clone();
let name = self.source[token.start + 1..token.end - 1].to_string();
RunTarget::Literal(name)
} else {
// Procedure name (may contain hyphens, dots for .p/.w/.r/.i/.cls files)
let name = self.parse_procedure_name()?;
RunTarget::Literal(name)
};
// parse optional arguments
let arguments = if self.check(Kind::LeftParen) {
self.advance();
let mut args = Vec::new();
if !self.check(Kind::RightParen) {
loop {
let direction = match self.peek().kind {
Kind::Input => {
self.advance();
ParameterDirection::Input
}
Kind::Output => {
self.advance();
ParameterDirection::Output
}
Kind::InputOutput => {
self.advance();
ParameterDirection::InputOutput
}
_ => ParameterDirection::Input, // Default to INPUT
};
let expression = self.parse_expression()?;
args.push(RunArgument {
direction,
expression,
});
if !self.check(Kind::Comma) {
break;
}
self.advance(); // consume comma
}
}
self.expect_kind(Kind::RightParen, "Expected ')' after RUN arguments")?;
args
} else {
Vec::new()
};
// parse optional IN handle
let in_handle = if self.check(Kind::KwIn) {
self.advance();
Some(self.parse_expression()?)
} else {
None
};
// parse optional PERSISTENT [SET handle]
let (persistent, persistent_handle) = if self.check(Kind::Persistent) {
self.advance();
let h = if self.check(Kind::Set) {
self.advance();
Some(self.parse_expression()?)
} else {
None
};
(true, h)
} else {
(false, None)
};
// parse optional ASYNCHRONOUS [SET handle] [EVENT-PROCEDURE expr]
let (asynchronous, async_handle, event_procedure) = if self.check(Kind::Asynchronous) {
self.advance();
let h = if self.check(Kind::Set) {
self.advance();
Some(self.parse_expression()?)
} else {
None
};
let ep = if self.check(Kind::EventProcedure) {
self.advance();
Some(self.parse_expression()?)
} else {
None
};
(true, h, ep)
} else {
(false, None, None)
};
// parse optional NO-ERROR
let no_error = if self.check(Kind::NoError) {
self.advance();
true
} else {
false
};
self.expect_kind(Kind::Period, "Expected '.' after RUN statement")?;
Ok(Statement::Run {
target,
arguments,
in_handle,
persistent,
persistent_handle,
asynchronous,
async_handle,
event_procedure,
no_error,
})
}
// Parse DISPLAY statement
fn parse_display_statement(&mut self) -> ParseResult<Statement> {
self.advance(); // consume DISPLAY
let mut items = Vec::new();
let mut except = Vec::new();
let mut frame = None;
// Parse display items until WITH, EXCEPT, or period
while !self.check(Kind::With)
&& !self.check(Kind::Except)
&& !self.check(Kind::Period)
&& !self.at_end()
{
let expression = self.parse_expression()?;
// Optional per-item WHEN condition
let when_condition = if self.check(Kind::When) {
self.advance();
Some(self.parse_expression()?)
} else {
None
};
// Skip FORMAT "string" and COLUMN-LABEL "string" if present (no variable refs)
while self.check(Kind::Format) || self.check(Kind::ColumnLabel) {
self.advance();
if self.check(Kind::StringLiteral) {
self.advance();
}
}
items.push(DisplayItem {
expression,
when_condition,
});
}
// Parse optional EXCEPT clause
if self.check(Kind::Except) {
self.advance();
while !self.check(Kind::With) && !self.check(Kind::Period) && !self.at_end() {
except.push(self.parse_identifier()?);
}
}
// Parse optional WITH FRAME clause
if self.check(Kind::With) {
self.advance();
if self.check(Kind::Frame) {
self.advance();
frame = Some(self.parse_identifier()?);
// Skip remaining frame options until period
while !self.check(Kind::Period) && !self.at_end() {
self.advance();
}
} else {
// WITH without FRAME — skip to period
while !self.check(Kind::Period) && !self.at_end() {
self.advance();
}
}
}
self.expect_kind(Kind::Period, "Expected '.' after DISPLAY statement")?;
Ok(Statement::Display {
items,
except,
frame,
})
}
// Parse MESSAGE statement
fn parse_message_statement(&mut self) -> ParseResult<Statement> {
self.advance(); // consume MESSAGE
let mut items = Vec::new();
let mut set_targets = Vec::new();
// Parse message items until VIEW-AS, SET, UPDATE, or period
while !self.check(Kind::ViewAs)
&& !self.check(Kind::Set)
&& !self.check(Kind::Update)
&& !self.check(Kind::Period)
&& !self.at_end()
{
// Recognize SKIP / SKIP(n) as formatting directives — don't treat as identifiers
if self.check(Kind::Skip) {
self.advance();
// SKIP(n) — consume the parenthesized integer
if self.check(Kind::LeftParen) {
self.advance();
if self.check(Kind::IntegerLiteral) {
self.advance();
}
if self.check(Kind::RightParen) {
self.advance();
}
}
continue; // SKIP has no variable refs, skip it
}
items.push(self.parse_expression()?);
}
// Parse optional VIEW-AS ALERT-BOX clause — skip over without failing
if self.check(Kind::ViewAs) {
self.advance(); // consume VIEW-AS
// Skip tokens until we hit SET, UPDATE, or period
while !self.check(Kind::Set)
&& !self.check(Kind::Update)
&& !self.check(Kind::Period)
&& !self.at_end()
{
self.advance();
}
}
// Parse optional SET or UPDATE variable list
if self.check(Kind::Set) || self.check(Kind::Update) {
self.advance(); // consume SET or UPDATE
// Parse variable names until period or another clause
while !self.check(Kind::Period) && !self.at_end() {
// Skip FORMAT "string" if present after a variable
if self.check(Kind::Format) {
self.advance();
if self.check(Kind::StringLiteral) {
self.advance();
}
continue;
}
if is_callable_kind(self.peek().kind) {
set_targets.push(self.parse_identifier()?);
} else {
break;
}
}
}
self.expect_kind(Kind::Period, "Expected '.' after MESSAGE statement")?;
Ok(Statement::Message { items, set_targets })
}
// Parse the block body for code blocks like DO, consume till END.
fn parse_block_body(&mut self) -> ParseResult<Vec<Statement>> {
let mut statements = Vec::new();
while !self.check(Kind::End) && !self.at_end() {
statements.push(self.parse_statement()?);
}
// Consume the END
self.expect_kind(Kind::End, "Expected END to close block")?;
self.expect_kind(Kind::Period, "Expected '.' to end statement")?;
Ok(statements)
}
/// Parses an optional lock type (NO-LOCK, SHARE-LOCK, EXCLUSIVE-LOCK)
/// Returns ShareLock if no lock type is specified (ABL default)
fn parse_lock_type(&mut self) -> LockType {
match self.peek().kind {
Kind::NoLock => {
self.advance();
LockType::NoLock
}
Kind::ShareLock => {
self.advance();
LockType::ShareLock
}
Kind::ExclusiveLock => {
self.advance();
LockType::ExclusiveLock
}
_ => LockType::ShareLock, // Default in ABL
}
}
/// Parse a procedure name for RUN statements.
///
/// ABL procedure names can contain hyphens (e.g., `calculate-total`) and may have
/// file extensions (e.g., `my-proc.p`). Known ABL extensions are `.p`, `.w`, `.r`,
/// `.i`, and `.cls`. A period followed by a non-extension token is treated as the
/// statement terminator, not part of the name.
fn parse_procedure_name(&mut self) -> ParseResult<String> {
if !is_callable_kind(self.peek().kind) {
return Err(ParseError {
message: "Expected procedure name after RUN".to_string(),
span: Span {
start: self.peek().start as u32,
end: self.peek().end as u32,
},
});
}
let start = self.peek().start;
self.advance(); // consume the first identifier token
// Check for dotted extension (e.g., my-proc.p)
// Only consume the dot + extension if it's a known ABL file extension
if self.check(Kind::Period)
&& let Some(next) = self.tokens.get(self.current + 1)
&& next.kind == Kind::Identifier
{
let ext = &self.source[next.start..next.end];
if ext.eq_ignore_ascii_case("p")
|| ext.eq_ignore_ascii_case("w")
|| ext.eq_ignore_ascii_case("r")
|| ext.eq_ignore_ascii_case("i")
|| ext.eq_ignore_ascii_case("cls")
{
self.advance(); // consume the period
self.advance(); // consume the extension
}
}
let end = self.tokens[self.current - 1].end;
Ok(self.source[start..end].to_string())
}
/// Check if the current token is the start of a find clause (WHERE, lock, no-error, terminator)
fn is_find_clause_start(&self) -> bool {
matches!(
self.peek().kind,
Kind::KwWhere
| Kind::NoLock
| Kind::ShareLock
| Kind::ExclusiveLock
| Kind::NoError
| Kind::Period
)
}
}