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
//! SQLite parser

pub mod ast;
pub mod parse {
    #![allow(unused_braces)]
    #![allow(unused_comparisons)] // FIXME
    #![allow(clippy::collapsible_if)]
    #![allow(clippy::if_same_then_else)]
    #![allow(clippy::absurd_extreme_comparisons)] // FIXME
    #![allow(clippy::needless_return)]
    #![allow(clippy::upper_case_acronyms)]
    #![allow(clippy::manual_range_patterns)]

    include!(concat!(env!("OUT_DIR"), "/parse.rs"));
}

use crate::dialect::Token;
use ast::{Cmd, ExplainKind, Name, Stmt};

/// Parser error
#[derive(Debug, PartialEq)]
pub enum ParserError {
    /// Syntax error
    SyntaxError {
        /// token type
        token_type: &'static str,
        /// token value
        found: Option<String>,
    },
    /// Unexpected EOF
    UnexpectedEof,
    /// Custom error
    Custom(String),
}

impl std::fmt::Display for ParserError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            ParserError::SyntaxError { token_type, found } => {
                write!(f, "near {}, \"{:?}\": syntax error", token_type, found)
            }
            ParserError::UnexpectedEof => f.write_str("unexpected end of input"),
            ParserError::Custom(s) => f.write_str(s),
        }
    }
}

impl std::error::Error for ParserError {}

/// Custom error constructor
#[macro_export]
macro_rules! custom_err {
    ($msg:literal $(,)?) => {
        $crate::parser::ParserError::Custom($msg.to_owned())
    };
    ($err:expr $(,)?) => {
        $crate::parser::ParserError::Custom(format!($err))
    };
    ($fmt:expr, $($arg:tt)*) => {
        $crate::parser::ParserError::Custom(format!($fmt, $($arg)*))
    };
}

/// Parser context
pub struct Context<'input> {
    input: &'input [u8],
    explain: Option<ExplainKind>,
    stmt: Option<Stmt>,
    constraint_name: Option<Name>,      // transient
    module_arg: Option<(usize, usize)>, // Complete text of a module argument
    module_args: Option<Vec<String>>,   // CREATE VIRTUAL TABLE args
    done: bool,
    error: Option<ParserError>,
}

impl<'input> Context<'input> {
    pub fn new(input: &'input [u8]) -> Context<'input> {
        Context {
            input,
            explain: None,
            stmt: None,
            constraint_name: None,
            module_arg: None,
            module_args: None,
            done: false,
            error: None,
        }
    }

    /// Consume parsed command
    pub fn cmd(&mut self) -> Option<Cmd> {
        if let Some(stmt) = self.stmt.take() {
            match self.explain.take() {
                Some(ExplainKind::Explain) => Some(Cmd::Explain(stmt)),
                Some(ExplainKind::QueryPlan) => Some(Cmd::ExplainQueryPlan(stmt)),
                None => Some(Cmd::Stmt(stmt)),
            }
        } else {
            None
        }
    }

    fn constraint_name(&mut self) -> Option<Name> {
        self.constraint_name.take()
    }
    fn no_constraint_name(&self) -> bool {
        self.constraint_name.is_none()
    }

    fn vtab_arg_init(&mut self) {
        self.add_module_arg();
        self.module_arg = None;
    }
    fn vtab_arg_extend(&mut self, any: Token) {
        if let Some((_, ref mut n)) = self.module_arg {
            *n = any.2
        } else {
            self.module_arg = Some((any.0, any.2))
        }
    }
    fn add_module_arg(&mut self) {
        if let Some((start, end)) = self.module_arg.take() {
            if let Ok(arg) = std::str::from_utf8(&self.input[start..end]) {
                self.module_args.get_or_insert(vec![]).push(arg.to_owned());
            } // FIXME error handling
        }
    }
    fn module_args(&mut self) -> Option<Vec<String>> {
        self.add_module_arg();
        self.module_args.take()
    }

    /// This routine is called after a single SQL statement has been parsed.
    fn sqlite3_finish_coding(&mut self) {
        self.done = true;
    }

    /// Return `true` if parser completes either successfully or with an error.
    pub fn done(&self) -> bool {
        self.done || self.error.is_some()
    }

    pub fn is_ok(&self) -> bool {
        self.error.is_none()
    }

    /// Consume error generated by parser
    pub fn error(&mut self) -> Option<ParserError> {
        self.error.take()
    }

    pub fn reset(&mut self) {
        self.explain = None;
        self.stmt = None;
        self.constraint_name = None;
        self.module_arg = None;
        self.module_args = None;
        self.done = false;
        self.error = None;
    }
}