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
// Copyright 2025 Oxibase Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use super::ast::{AssignmentStatement, BlockStatement, IfStatement, PlSqlStatement};
use crate::core::{Error, Result};
use crate::parser::lexer::Lexer;
use crate::parser::precedence::Precedence;
use crate::parser::token::{Token, TokenType};
pub struct PlSqlParser {
code: String,
lexer: Lexer,
cur_token: Token,
peek_token: Token,
errors: Vec<String>,
}
impl PlSqlParser {
pub fn new(code: &str) -> Self {
let mut lexer = Lexer::new(code);
let cur_token = lexer.next_token();
let peek_token = lexer.next_token();
Self {
code: code.to_string(),
lexer,
cur_token,
peek_token,
errors: Vec::new(),
}
}
fn next_token(&mut self) {
self.cur_token = self.peek_token.clone();
self.peek_token = self.lexer.next_token();
}
#[allow(dead_code)]
fn expect_peek(&mut self, t: TokenType) -> bool {
if self.peek_token.token_type == t {
self.next_token();
true
} else {
self.errors.push(format!(
"Expected next token to be {:?}, got {:?} instead",
t, self.peek_token.token_type
));
false
}
}
fn peek_is_keyword(&self, keyword: &str) -> bool {
self.peek_token.token_type == TokenType::Keyword
&& self.peek_token.literal.eq_ignore_ascii_case(keyword)
}
fn expect_keyword(&mut self, keyword: &str) -> bool {
if self.peek_is_keyword(keyword) {
self.next_token();
true
} else {
self.errors.push(format!(
"Expected keyword {}, got {}",
keyword, self.peek_token.literal
));
false
}
}
pub fn parse(&mut self) -> Result<BlockStatement> {
let mut statements = Vec::new();
// Skip DECLARE for now, assume BEGIN is the start of executable section
if self.cur_token.token_type == TokenType::Keyword
&& self.cur_token.literal.eq_ignore_ascii_case("DECLARE")
{
if let Some(declare_stmt) = self.parse_declare_statement() {
statements.push(declare_stmt);
}
}
if self.cur_token.token_type == TokenType::Keyword
&& self.cur_token.literal.eq_ignore_ascii_case("BEGIN")
{
self.next_token();
while !(self.cur_token.token_type == TokenType::Keyword
&& self.cur_token.literal.eq_ignore_ascii_case("END"))
{
if self.cur_token.token_type == TokenType::Eof {
return Err(Error::parse("Unexpected EOF waiting for END"));
}
if let Some(stmt) = self.parse_statement() {
statements.push(stmt);
} else {
// We must NOT blindly consume tokens if parse_statement failed
// Or actually, if it returned None because it wasn't a statement, we can advance
// But if it consumed tokens and failed, we are in trouble.
// Wait, parse_assignment_statement consumes tokens and returns Some.
// Does it consume the semicolon? Yes.
self.next_token();
}
}
} else {
// Just parse statements directly if no BEGIN
while self.cur_token.token_type != TokenType::Eof {
if let Some(stmt) = self.parse_statement() {
statements.push(stmt);
}
self.next_token();
}
}
if !self.errors.is_empty() {
return Err(Error::parse(self.errors.join("\n")));
}
Ok(BlockStatement {
token: self.cur_token.clone(),
statements,
})
}
fn parse_declare_statement(&mut self) -> Option<PlSqlStatement> {
let token = self.cur_token.clone();
self.next_token(); // Move past DECLARE
let mut declarations = Vec::new();
while !(self.cur_token.token_type == TokenType::Keyword
&& self.cur_token.literal.eq_ignore_ascii_case("BEGIN"))
{
if self.cur_token.token_type == TokenType::Eof {
self.errors
.push("Unexpected EOF in DECLARE block".to_string());
return None;
}
if self.cur_token.token_type == TokenType::Identifier {
let name = self.cur_token.literal.clone();
self.next_token(); // Move to type
let data_type = self.cur_token.literal.clone();
self.next_token(); // Move past type
let mut default_value = None;
if self.cur_token.literal == ":" && self.peek_token.literal == "=" {
self.next_token(); // move to =
self.next_token(); // move to expression start
let mut sql_parser =
crate::parser::Parser::new(&self.code[self.cur_token.position.offset..]);
if let Some(expr) = sql_parser.parse_expression(Precedence::Lowest) {
default_value = Some(expr);
}
// Advance our lexer until semicolon
while self.cur_token.literal != ";"
&& self.cur_token.token_type != TokenType::Eof
{
self.next_token();
}
} else if self.cur_token.literal == ":="
|| self.cur_token.literal.eq_ignore_ascii_case("DEFAULT")
{
self.next_token(); // Move past := or DEFAULT
let mut sql_parser =
crate::parser::Parser::new(&self.code[self.cur_token.position.offset..]);
if let Some(expr) = sql_parser.parse_expression(Precedence::Lowest) {
default_value = Some(expr);
}
// Advance our lexer until semicolon
while self.cur_token.literal != ";"
&& self.cur_token.token_type != TokenType::Eof
{
self.next_token();
}
}
if self.cur_token.literal == ";" {
self.next_token(); // Move past semicolon
}
declarations.push(super::ast::VariableDeclaration {
name,
data_type,
default_value,
});
} else {
// If it is an empty line or something else, advance. But actually, could be a comment.
self.next_token(); // skip unrecognized token
}
}
Some(PlSqlStatement::Declare(super::ast::DeclareStatement {
token,
declarations,
}))
}
fn parse_while_statement(&mut self) -> Option<PlSqlStatement> {
let token = self.cur_token.clone();
self.next_token(); // Move past WHILE
// Collect tokens until LOOP for the condition
let mut sql_parser =
crate::parser::Parser::new(&self.code[self.cur_token.position.offset..]);
let condition = sql_parser.parse_expression(Precedence::Lowest)?;
// Advance our lexer to LOOP
while !(self.cur_token.token_type == TokenType::Keyword
&& self.cur_token.literal.eq_ignore_ascii_case("LOOP"))
{
if self.cur_token.token_type == TokenType::Eof {
self.errors
.push("Expected LOOP after WHILE condition".to_string());
return None;
}
self.next_token();
}
self.next_token(); // Move past LOOP
let mut block = Vec::new();
// Parse LOOP block
while !(self.cur_token.token_type == TokenType::Keyword
&& self.cur_token.literal.eq_ignore_ascii_case("END"))
{
if self.cur_token.token_type == TokenType::Eof {
self.errors.push("Expected END LOOP".to_string());
return None;
}
if let Some(stmt) = self.parse_statement() {
block.push(stmt);
} else {
self.next_token();
}
}
// Expect END LOOP
if self.cur_token.token_type == TokenType::Keyword
&& self.cur_token.literal.eq_ignore_ascii_case("END")
&& self.expect_keyword("LOOP")
{
if self.peek_token.literal == ";" {
self.next_token(); // Consume semicolon
}
return Some(PlSqlStatement::While(super::ast::WhileStatement {
token,
condition,
block,
}));
}
None
}
fn parse_statement(&mut self) -> Option<PlSqlStatement> {
// Skip comments
while self.cur_token.token_type == TokenType::Comment {
self.next_token();
}
match self.cur_token.token_type {
TokenType::Keyword => {
let kw = self.cur_token.literal.to_uppercase();
match kw.as_str() {
"IF" => self.parse_if_statement(),
"WHILE" => self.parse_while_statement(),
"RETURN" => {
let stmt = PlSqlStatement::Return(self.cur_token.clone());
if self.peek_token.literal == ";" {
self.next_token();
}
Some(stmt)
}
"COMMIT" => {
let stmt = PlSqlStatement::Commit(self.cur_token.clone());
if self.peek_token.literal == ";" {
self.next_token();
}
Some(stmt)
}
"ROLLBACK" => {
let stmt = PlSqlStatement::Rollback(self.cur_token.clone());
if self.peek_token.literal == ";" {
self.next_token();
}
Some(stmt)
}
"BEGIN" => {
let stmt = PlSqlStatement::BeginTransaction(self.cur_token.clone());
if self.peek_token.literal == ";" {
self.next_token();
}
Some(stmt)
}
_ => {
// Try assignment first
if let Some(stmt) = self.parse_assignment_statement() {
return Some(stmt);
}
// Fallback to standard SQL parser
self.parse_sql_statement()
}
}
}
TokenType::Identifier => {
// Try assignment first
if let Some(stmt) = self.parse_assignment_statement() {
return Some(stmt);
}
// Fallback to standard SQL parser
self.parse_sql_statement()
}
_ => self.parse_sql_statement(),
}
}
fn parse_sql_statement(&mut self) -> Option<PlSqlStatement> {
let mut sql_parser =
crate::parser::Parser::new(&self.code[self.cur_token.position.offset..]);
// parse_statement only parses one statement
let stmt_opt = sql_parser.parse_statement();
if let Some(stmt) = stmt_opt {
while self.cur_token.literal != ";" && self.cur_token.token_type != TokenType::Eof {
self.next_token();
}
if self.cur_token.literal == ";" {
self.next_token();
}
return Some(PlSqlStatement::Sql(Box::new(stmt)));
}
None
}
fn parse_assignment_statement(&mut self) -> Option<PlSqlStatement> {
let variable = self.cur_token.literal.clone();
// Expect := or = or :
if self.peek_token.literal == "=" {
self.next_token(); // Move to =
self.next_token(); // Move to expression start
} else if self.peek_token.literal == ":" {
self.next_token(); // Move to :
if self.peek_token.literal == "=" {
self.next_token(); // Move to =
self.next_token(); // Move to expression start
} else {
return None;
}
} else if self.peek_token.literal == ":=" {
self.next_token(); // Move to :=
self.next_token(); // Move to expression start
} else {
return None;
}
// This is a hacky way to re-use the standard SQL expression parser
// We'll create a new parser just for the expression part
let mut sql_parser =
crate::parser::Parser::new(&self.code[self.cur_token.position.offset..]);
// Advance our lexer until semicolon
let mut expr_tokens = Vec::new();
while self.cur_token.literal != ";" && self.cur_token.token_type != TokenType::Eof {
expr_tokens.push(self.cur_token.clone());
self.next_token();
}
// If we hit EOF before semicolon, it's an error
if self.cur_token.token_type == TokenType::Eof && expr_tokens.is_empty() {
self.errors
.push("Expected expression after assignment".to_string());
return None;
}
println!("Tokens for assignment to {}: {:?}", variable, expr_tokens);
// Now parse the expression using the standard parser
// The problem is sql_parser reads the expression but our main lexer has skipped ahead to the semicolon.
// Let's make sure sql_parser successfully parsed it.
if let Some(expr) = sql_parser.parse_expression(Precedence::Lowest) {
let stmt = PlSqlStatement::Assignment(AssignmentStatement {
token: self.cur_token.clone(),
variable,
expression: expr,
});
// Consume semicolon if present
if self.cur_token.literal == ";" {
self.next_token();
}
// println!("Parsed assignment: {:?}", stmt);
Some(stmt)
} else {
self.errors.push(format!(
"Failed to parse expression in assignment for {}: {:?}",
variable,
sql_parser.errors()
));
None
}
}
fn parse_if_statement(&mut self) -> Option<PlSqlStatement> {
self.next_token(); // Move past IF
// Collect tokens until THEN for the condition
let mut sql_parser =
crate::parser::Parser::new(&self.code[self.cur_token.position.offset..]);
let condition = sql_parser.parse_expression(Precedence::Lowest)?;
// Advance our lexer to THEN
while !(self.cur_token.token_type == TokenType::Keyword
&& self.cur_token.literal.eq_ignore_ascii_case("THEN"))
{
if self.cur_token.token_type == TokenType::Eof {
self.errors
.push("Expected THEN after IF condition".to_string());
return None;
}
self.next_token();
}
self.next_token(); // Move past THEN
let mut then_block = Vec::new();
let mut else_block = None;
// Parse THEN block
while !(self.cur_token.token_type == TokenType::Keyword
&& (self.cur_token.literal.eq_ignore_ascii_case("ELSE")
|| self.cur_token.literal.eq_ignore_ascii_case("END")))
{
// Debug parsing statements
println!("Parsing stmt inside THEN block: {:?}", self.cur_token);
// println!("IF block token: {:?}", self.cur_token);
if self.cur_token.token_type == TokenType::Eof {
self.errors.push("Expected END IF".to_string());
return None;
}
if let Some(stmt) = self.parse_statement() {
then_block.push(stmt);
} else {
self.next_token();
}
}
// Parse optional ELSE block
if self.cur_token.token_type == TokenType::Keyword
&& self.cur_token.literal.eq_ignore_ascii_case("ELSE")
{
self.next_token(); // Move past ELSE
let mut block = Vec::new();
while !(self.cur_token.token_type == TokenType::Keyword
&& self.cur_token.literal.eq_ignore_ascii_case("END"))
{
if self.cur_token.token_type == TokenType::Eof {
self.errors.push("Expected END IF".to_string());
return None;
}
if let Some(stmt) = self.parse_statement() {
block.push(stmt);
} else {
self.next_token();
}
}
else_block = Some(block);
}
// Expect END IF
if self.cur_token.token_type == TokenType::Keyword
&& self.cur_token.literal.eq_ignore_ascii_case("END")
&& self.expect_keyword("IF")
{
if self.peek_token.literal == ";" {
self.next_token(); // Consume semicolon
}
return Some(PlSqlStatement::If(IfStatement {
token: self.cur_token.clone(),
condition,
then_block,
else_block,
}));
}
None
}
}