regex-anre 2.0.0

Regex-anre is a full-featured, zero-dependency regular expression engine that supports both standard and ANRE regular expressions.
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
// Copyright (c) 2025 Hemashushu <hippospark@gmail.com>, All rights reserved.
//
// This Source Code Form is subject to the terms of
// the Mozilla Public License version 2.0 and additional exceptions.
// For more details, see the LICENSE, LICENSE.additional, and CONTRIBUTING files.

use crate::transition::Transition;

pub const MAIN_ROUTE_INDEX: usize = 0;

// The `Map` structure:
//
// ```diagram
// Map
// |
// |-- Main route --\
// |                |-- node 0 --\
// |                |            |- path --> points to the next node
// |                |            |- path --> points to the next node
// |                |            |- ...
// |                |            \- path --> points to the next node
// |                |-- node 1
// |                |-- ...
// |                |-- node N
// |
// |-- Sub route (generated by lookaround assertions)
// |-- Sub route (generated by lookaround assertions)
// ```

// The `Map` represents the result of compilation.
//
// One regular expression generates one map.
#[derive(Debug)]
pub struct Map {
    // Generally, one regular expression consists of a series of nodes, which forming a "route."
    // However, "lookahead assertions" and "lookbehind assertions" in the regular expression
    // generate sub-routes. Therefore, one map may contains multiple routes,
    // in which the first route is the main route, and others are sub-routes.
    pub routes: Vec<Route>,

    // The capture groups with optional names.
    //
    // All capture groups have a unique index, and some of them may have a name.
    // This vector is used to store the names of capture groups, where
    // the index of the name corresponds to the capture group index.
    pub capture_groups: Vec<Option<String>>,
}

// A `Route` represents a series of nodes.
#[derive(Debug)]
pub struct Route {
    // A route consists of multiple nodes.
    // Each node contains multiple transitions (or character patterns),
    // which are conceptually similar to functions in programming languages.
    pub nodes: Vec<Node>,

    // The index of the entry node in the node list.
    pub entry_node_index: usize,

    // The index of the exit node in the node list.
    pub exit_node_index: usize,

    // True if the expression starts with the line begin boundary assertion `^`,
    // meaning that if a route match fails,
    // the process will not move the beginning point forward (one character) and try matching again.
    // This is also true for "lookahead assertions" and "lookbehind assertions" sub-routes,
    // thus the lookbehind assertion can only match a fixed number of characters in ANRE.
    pub is_fixed_matching_begin_point: bool,
}

// A route consists of multiple nodes.
// Each node has one or more paths to the next node,
// except for the `exit node`, which is the end of the route and has no path.
#[derive(Debug)]
pub struct Node {
    // exit transitions target the next node.
    pub path: Vec<Path>,
}

// Represents a transition item and the index of the next node to go to when the transition executes successfully.
#[derive(Debug)]
pub struct Path {
    // The transition object.
    // A transition represents a condition to be satisfied for the route to continue to the next node.
    // It is similar to the condition in an `if` statement in programming languages.
    pub transition: Transition,

    // The index of the next node to go to when the transition executes successfully.
    pub target_node_index: usize,
}

impl Map {
    pub fn new() -> Self {
        Map {
            routes: vec![],
            capture_groups: vec![],
        }
    }

    // Creates a route object and returns its index.
    pub fn create_route(&mut self) -> usize {
        let route = Route {
            nodes: vec![],
            entry_node_index: 0,
            exit_node_index: 0,
            is_fixed_matching_begin_point: false,
        };

        let idx = self.routes.len();
        self.routes.push(route);
        idx
    }

    // Creates a capture group object and returns its index.
    pub fn create_capture_group(&mut self, name: Option<String>) -> usize {
        let idx = self.capture_groups.len();
        self.capture_groups.push(name);
        idx
    }

    // Retrieves the index of a capture group by its name.
    //
    // Returns `None` if there is no capture group with the specified name.
    pub fn get_capture_group_index_by_name(&self, name: &str) -> Option<usize> {
        self.capture_groups.iter().position(|item| match item {
            Some(n) => n == name,
            None => false,
        })
    }

    // Retrieves the name of a capture group by its index.
    //
    // Returns `None` if there is no capture group name with the specified index.
    pub fn get_capture_group_name_by_index(&self, index: usize) -> Option<&str> {
        let opt_name = &self.capture_groups[index];
        if let Some(name) = opt_name {
            Some(name.as_str())
        } else {
            None
        }
    }

    // For debugging: generates a textual representation of the map.
    pub fn get_debug_text(&self) -> String {
        let mut buffer = vec![];

        // Routes
        if self.routes.len() == 1 {
            buffer.push(self.routes[0].get_debug_text());
        } else {
            for (route_index, route) in self.routes.iter().enumerate() {
                buffer.push(format!("= ${}", route_index));
                buffer.push(route.get_debug_text());
            }
        }

        // Capture groups
        for (capture_group_index, opt_capture_group_name) in
            self.capture_groups.iter().enumerate()
        {
            let s = if let Some(name) = &opt_capture_group_name {
                format!("# {{{}}}, {}", capture_group_index, name)
            } else {
                format!("# {{{}}}", capture_group_index)
            };
            buffer.push(s);
        }

        buffer.join("\n")
    }
}

impl Default for Map {
    fn default() -> Self {
        Self::new()
    }
}

impl Route {
    // Creates a node object and returns its index.
    pub fn create_node(&mut self) -> usize {
        let node = Node { path: vec![] };
        let idx = self.nodes.len();
        self.nodes.push(node);

        idx
    }

    // Creates a path object and returns its index.
    pub fn create_path(
        &mut self,
        source_node_index: usize,
        target_node_index: usize,
        transition: Transition,
    ) -> usize {
        let transition_item = Path {
            transition,
            target_node_index,
        };

        let idx = self.nodes[source_node_index].path.len();

        self.nodes[source_node_index].path.push(transition_item);

        idx
    }

    // For debugging: generates a textual representation of the route.
    pub fn get_debug_text(&self) -> String {
        let mut buffer = vec![];

        for (node_index, node) in self.nodes.iter().enumerate() {
            // Node
            let prefix = if node_index == self.entry_node_index {
                '>'
            } else if node_index == self.exit_node_index {
                '<'
            } else {
                '-'
            };

            let s = format!("{} {}", prefix, node_index);
            buffer.push(s);

            // Transition items
            for transition_item in &node.path {
                let s = format!(
                    "  -> {}, {}",
                    transition_item.target_node_index, transition_item.transition
                );
                buffer.push(s);
            }
        }

        buffer.join("\n")
    }
}

// Component is a logical concept in the compiler, it is used to wrap the nodes and transitions generated by an expression,
// and provide a unified interface (an "in port" and an "out port") for connecting with other components.
//
// In the code views, a component is just a pair of `Node` objects.
//
// The following diagram illustrates the simplest case of a component, which is
// a component that contains a single literal transition.
//
// ```diagram
//   /-----------------------------\
//   |          literal            |
//   |        | transition         |
//   |        v                    |
// =====o==-------------------==o=====
//   | in node            out node |
//   |                             |
//   \----- literal component -----/
// ```
//
// Component can be nested, for example a group component can contain another group component.
//
// The following diagram illustrates a group component that wraps two components,
// and connects them with jump transitions.
//
// ```diagram
//   /-----------------------------------------------\
//   |                                               |
//   |    component        jump         component    |
//   |  /-----------\   transition    /-----------\  |
// =====o in    out o==-------------==o in    out o=====
//   |  \-----------/                 \-----------/  |
//   |                                               |
//   \--------------- group component ---------------/
// ```
//
// A regular expression is compiled into
// nodes and transitions, but in the program views, they are wrapped into components, at the
// root level, a program is a single component, and the "in port" of the component is the
// entry point of the program, and the "out port" of the component is the exit point of the program.
//
// The following diagram illustrates a program component that wraps a root expression component
// with index capture transitions.
//
// ```diagram
//   /---------------------------------------------------------\
//   |                                                         |
//   |  capture start |                     capture end |      |
//   |     transition |                      transition |      |
//   |                V    /-------------\              v      |
// =====o==-------------===o in      out o===-------------==o=====
//   |  in                 \-------------/                 out |
//   |  node               root expression                node |
//   |                        component                        |
//   |                                                         |
//   \------------------- program component--------------------/
// ```
pub struct Component {
    pub in_node_index: usize,
    pub out_node_index: usize,
}

impl Component {
    pub fn new(in_node_index: usize, out_node_index: usize) -> Self {
        Component {
            in_node_index,
            out_node_index,
        }
    }
}

#[cfg(test)]
mod tests {
    use pretty_assertions::{assert_eq, assert_str_eq};

    use crate::{
        object_file::Map,
        transition::{CharTransition, Transition},
    };

    #[test]
    fn test_object_file_create_route() {
        let mut object = Map::new();

        // Create a route
        {
            let route_index = object.create_route();
            let route = &mut object.routes[route_index];

            // Create a node
            let _idx0 = route.create_node();

            assert_str_eq!(
                route.get_debug_text(),
                "\
> 0"
            );

            // Create other nodes
            let idx1 = route.create_node();
            let _idx2 = route.create_node();
            let idx3 = route.create_node();

            route.entry_node_index = idx1;
            route.exit_node_index = idx3;

            assert_str_eq!(
                route.get_debug_text(),
                "\
- 0
> 1
- 2
< 3"
            );
        }

        // Create another route
        {
            let route_index = object.create_route();
            let route = &mut object.routes[route_index];

            // Create a node
            let _idx0 = route.create_node();

            assert_str_eq!(
                object.get_debug_text(),
                "\
= $0
- 0
> 1
- 2
< 3
= $1
> 0"
            );
        }
    }

    #[test]
    fn test_object_file_create_capture_group() {
        let mut object = Map::new();
        let route_index = object.create_route();
        let route = &mut object.routes[route_index];

        route.create_node();
        route.create_node();

        object.create_capture_group(None);
        object.create_capture_group(Some("foo".to_owned()));
        object.create_capture_group(None);

        assert_str_eq!(
            object.get_debug_text(),
            "\
> 0
- 1
# {0}
# {1}, foo
# {2}"
        );

        assert_eq!(object.get_capture_group_index_by_name("foo"), Some(1));
        assert!(object.get_capture_group_index_by_name("bar").is_none());
    }

    #[test]
    fn test_object_file_create_path() {
        let mut object = Map::new();
        let route_index = object.create_route();
        let route = &mut object.routes[route_index];

        let node_idx0 = route.create_node();
        let node_idx1 = route.create_node();
        let node_idx2 = route.create_node();
        let node_idx3 = route.create_node();

        let trans_idx0 = route.create_path(
            node_idx0,
            node_idx1,
            Transition::Char(CharTransition::new('a')),
        );

        assert_str_eq!(
            route.get_debug_text(),
            "\
> 0
  -> 1, Char 'a'
- 1
- 2
- 3"
        );

        assert_eq!(trans_idx0, 0);

        let trans_idx1 = route.create_path(
            node_idx0,
            node_idx2,
            Transition::Char(CharTransition::new('b')),
        );

        let trans_idx2 = route.create_path(
            node_idx0,
            node_idx3,
            Transition::Char(CharTransition::new('c')),
        );

        assert_str_eq!(
            route.get_debug_text(),
            "\
> 0
  -> 1, Char 'a'
  -> 2, Char 'b'
  -> 3, Char 'c'
- 1
- 2
- 3"
        );

        assert_eq!(trans_idx1, 1);
        assert_eq!(trans_idx2, 2);

        let trans_idx3 = route.create_path(
            node_idx1,
            node_idx2,
            Transition::Char(CharTransition::new('x')),
        );

        assert_str_eq!(
            route.get_debug_text(),
            "\
> 0
  -> 1, Char 'a'
  -> 2, Char 'b'
  -> 3, Char 'c'
- 1
  -> 2, Char 'x'
- 2
- 3"
        );

        assert_eq!(trans_idx3, 0);
    }
}