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
//! # OxiLean Parser — Surface Syntax to AST
//!
//! This crate converts concrete OxiLean source syntax (text) into abstract syntax trees (ASTs)
//! that the elaborator can process into kernel-checkable terms.
//!
//! ## Quick Start
//!
//! ### Parsing an Expression
//!
//! ```ignore
//! use oxilean_parse::{Lexer, Parser, SurfaceExpr};
//!
//! let source = "fun (x : Nat) => x + 1";
//! let lexer = Lexer::new(source);
//! let tokens = lexer.tokenize()?;
//! let mut parser = Parser::new(tokens);
//! let expr = parser.parse_expr()?;
//! ```
//!
//! ### Parsing a Module
//!
//! ```ignore
//! use oxilean_parse::Module;
//!
//! let source = "def double (n : Nat) : Nat := n + n";
//! let module = Module::parse_source(source)?;
//! ```
//!
//! ## Architecture Overview
//!
//! The parser is a three-stage pipeline:
//!
//! ```text
//! Source Text (.oxilean file)
//! │
//! ▼
//! ┌──────────────────────┐
//! │ Lexer │ → Tokenizes text
//! │ (lexer.rs) │ → Handles UTF-8, comments, strings
//! └──────────────────────┘
//! │
//! ▼
//! Token Stream
//! │
//! ▼
//! ┌──────────────────────┐
//! │ Parser │ → Builds AST from tokens
//! │ (parser_impl.rs) │ → Handles precedence, associativity
//! │ + Helpers │ → Pattern, macro, tactic parsers
//! └──────────────────────┘
//! │
//! ▼
//! Abstract Syntax Tree (AST)
//! │
//! └─→ SurfaceExpr, SurfaceDecl, Module, etc.
//! └─→ Diagnostic information (errors, warnings)
//! └─→ Source mapping (for IDE integration)
//! ```
//!
//! ## Key Concepts & Terminology
//!
//! ### Tokens
//!
//! Basic lexical elements:
//! - **Identifiers**: `x`, `Nat`, `add_comm`, etc.
//! - **Keywords**: `fun`, `def`, `theorem`, `inductive`, etc.
//! - **Operators**: `+`, `-`, `:`, `=>`, `|`, etc.
//! - **Literals**: Numbers, strings, characters
//! - **Delimiters**: `(`, `)`, `[`, `]`, `{`, `}`
//!
//! ### Surface Syntax (SurfaceExpr)
//!
//! Represents OxiLean code before elaboration:
//! - **Applications**: `f x y` (function calls)
//! - **Lambda**: `fun x => body`
//! - **Pi types**: `(x : A) -> B`
//! - **Matches**: `match x with | nil => ... | cons h t => ...`
//! - **Tactics**: `by (tac1; tac2)`
//! - **Attributes**: `@[simp] def foo := ...`
//!
//! ### AST vs Kernel Expr
//!
//! - **AST (this crate)**: Surface syntax with implicit info
//! - Contains `?` (implicit args), `_` (placeholders)
//! - No type annotations required
//! - Represents user-written code
//! - **Kernel Expr (oxilean-kernel)**: Type-checked terms
//! - All types explicit
//! - All implicit args resolved
//! - Fully elaborated
//!
//! ## Module Organization
//!
//! ### Core Parsing Modules
//!
//! | Module | Purpose |
//! |--------|---------|
//! | `lexer` | Tokenization: text → tokens |
//! | `tokens` | Token and TokenKind definitions |
//! | `parser_impl` | Main parser: tokens → AST |
//! | `command` | Command parsing (`def`, `theorem`, etc.) |
//!
//! ### AST Definition
//!
//! | Module | Purpose |
//! |--------|---------|
//! | `ast_impl` | Core AST types: `SurfaceExpr`, `SurfaceDecl`, etc. |
//! | `pattern` | Pattern matching syntax |
//! | `literal` | Number and string literals |
//!
//! ### Specialized Parsers
//!
//! | Module | Purpose |
//! |--------|---------|
//! | `tactic_parser` | Tactic syntax: `intro`, `apply`, `rw`, etc. |
//! | `macro_parser` | Macro definition and expansion |
//! | `notation_system` | Operator precedence and associativity |
//!
//! ### Diagnostics & Source Mapping
//!
//! | Module | Purpose |
//! |--------|---------|
//! | `diagnostic` | Error and warning collection |
//! | `error_impl` | Parse error types and messages |
//! | `sourcemap` | Source position tracking for IDE |
//! | `span_util` | Source span utilities |
//!
//! ### Utilities
//!
//! | Module | Purpose |
//! |--------|---------|
//! | `prettyprint` | AST pretty-printing |
//! | `module` | Module system and imports |
//! | `repl_parser` | REPL command parsing |
//!
//! ## Parsing Pipeline Details
//!
//! ### Phase 1: Lexical Analysis (Lexer)
//!
//! Transforms character stream into token stream:
//! - Handles Unicode identifiers (UTF-8)
//! - Recognizes keywords vs identifiers
//! - Tracks line/column positions (for error reporting)
//! - Supports:
//! - Single-line comments: `-- comment`
//! - Multi-line comments: `/- -/`
//! - String literals: `"hello"`
//! - Number literals: `42`, `0xFF`, `3.14`
//!
//! ### Phase 2: Syntactic Analysis (Parser)
//!
//! Transforms token stream into AST:
//! - **Recursive descent**: For statements and declarations
//! - **Pratt parsing**: For expressions (handles precedence)
//! - **Lookahead(1)**: LL(1) grammar for predictive parsing
//! - **Error recovery**: Continues parsing after errors
//!
//! ### Phase 3: Post-Processing
//!
//! - **Notation expansion**: Apply infix/prefix operators
//! - **Macro expansion**: Expand syntax sugar
//! - **Span assignment**: Map AST nodes to source positions
//!
//! ## Usage Examples
//!
//! ### Example 1: Parse and Pretty-Print
//!
//! ```text
//! use oxilean_parse::{Lexer, Parser, print_expr};
//!
//! let source = "(x : Nat) -> Nat";
//! let mut parser = Parser::from_source(source)?;
//! let expr = parser.parse_expr()?;
//! println!("{}", print_expr(&expr));
//! ```
//!
//! ### Example 2: Parse a Definition
//!
//! ```text
//! use oxilean_parse::{Lexer, Parser, Decl};
//!
//! let source = "def double (n : Nat) : Nat := n + n";
//! let mut parser = Parser::from_source(source)?;
//! let decl = parser.parse_decl()?;
//! assert!(matches!(decl, Decl::Def { .. }));
//! ```
//!
//! ### Example 3: Collect Diagnostics
//!
//! ```text
//! use oxilean_parse::DiagnosticCollector;
//!
//! let mut collector = DiagnosticCollector::new();
//! // ... parse code ...
//! for diag in collector.diagnostics() {
//! println!("{:?}", diag);
//! }
//! ```
//!
//! ## Operator Precedence
//!
//! Operators are organized by precedence levels (0-100):
//! - **Level 100** (highest): Projections, applications
//! - **Level 90**: Power/exponentiation
//! - **Level 70**: Multiplication, division
//! - **Level 65**: Addition, subtraction
//! - **Level 50**: Comparison (`<`, `>`, `=`, etc.)
//! - **Level 40**: Conjunction (`and`)
//! - **Level 35**: Disjunction (`or`)
//! - **Level 25**: Implication (`->`)
//! - **Level 0** (lowest): Binders (`fun`, `:`, etc.)
//!
//! Associativity (left/right/non-associative) is per-operator.
//!
//! ## Error Handling
//!
//! Parser errors include:
//! - **Unexpected token**: Parser expected a different token
//! - **Expected `type` token**: Specific token was expected but not found
//! - **Unclosed delimiter**: Missing closing bracket/paren
//! - **Undeclared operator**: Unknown infix operator
//! - **Invalid pattern**: Malformed pattern in match/fun
//!
//! All errors carry:
//! - **Source location** (span): File, line, column
//! - **Error message**: Human-readable description
//! - **Context**: Surrounding code snippet (for IDE tooltips)
//!
//! ## Source Mapping & IDE Integration
//!
//! The parser builds a **source map** tracking:
//! - AST node → source location
//! - Hover information (for IDE hover tooltips)
//! - Semantic tokens (for syntax highlighting)
//! - Reference locations (for "go to definition")
//!
//! This enables:
//! - Accurate error reporting
//! - IDE language server protocol (LSP) support
//! - Refactoring tools
//!
//! ## Extensibility
//!
//! ### Adding New Operators
//!
//! Operators are registered in `notation_system`:
//! ```ignore
//! let notation = Notation {
//! name: "my_op",
//! kind: NotationKind::Infix,
//! level: 60,
//! associativity: Associativity::Left,
//! };
//! notation_table.insert(notation);
//! ```
//!
//! ### Adding New Keywords
//!
//! Keywords are hardcoded in `lexer::keyword_of_string()`.
//! Add new keyword, then handle in parser.
//!
//! ### Custom Macros
//!
//! Macros are parsed by `macro_parser` and expanded during parsing:
//! ```text
//! syntax "list" ["[", expr, (",", expr)*, "]"] => ...
//! macro list_to_cons : list => (...)
//! ```
//!
//! ## Integration with Other Crates
//!
//! ### With oxilean-elab
//!
//! The elaborator consumes this crate's AST:
//! ```text
//! Parser: Source → SurfaceExpr
//! Elaborator: SurfaceExpr → Kernel Expr (with type checking)
//! ```
//!
//! ### With oxilean-kernel
//!
//! Kernel types (Name, Level, Literal) are re-exported by parser for convenience.
//!
//! ## Performance Considerations
//!
//! - **Linear parsing**: O(n) where n = source length
//! - **Minimal allocations**: AST nodes are typically smaller than source
//! - **Single pass**: No tokenization+parsing phase, done in parallel
//!
//! ## Further Reading
//!
//! - [ARCHITECTURE.md](../../ARCHITECTURE.md) — System architecture
//! - [BLUEPRINT.md](../../BLUEPRINT.md) — Formal syntax specification
//! - Module documentation for specific subcomponents
// Module stubs for future implementation
// Full implementations
/// Advanced formatter with Wadler-Lindig optimal layout.
pub use SurfaceExpr as OldSurfaceExpr;
pub use ;
pub use ;
pub use ;
pub use ParseError as OldParseError;
pub use ;
pub use Lexer;
pub use ;
pub use ;
pub use ;
pub use Parser;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use *;