forked from gcalin/WhatTheLog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
syntax_tree.py
98 lines (76 loc) · 2.88 KB
/
syntax_tree.py
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
# -*- coding: utf-8 -*-
"""
Created on Tuesday 04/20/2021
Author: Tommaso Brandirali
Email: [email protected]
"""
#****************************************************************************************************
# Imports
#****************************************************************************************************
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# External
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
from __future__ import annotations
from dataclasses import dataclass, field
from typing import List, Union
import re
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Internal
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
from whatthelog.auto_printer import AutoPrinter
#****************************************************************************************************
# Syntax Tree
#****************************************************************************************************
@dataclass
class SyntaxTree(AutoPrinter):
"""
A data class representing the syntax tree for a system.
Instances of this class should be created using the
"""
name: str
prefix: str
isRegex: bool
__children: List[SyntaxTree] = field(default_factory=lambda: [])
def __post_init__(self):
try:
prefix = re.escape(self.prefix) if not self.isRegex else self.prefix
self.__pattern = re.compile(prefix)
except re.error:
self.print(f"ERROR: Invalid pattern given for Node '{self.name}'")
raise ValueError
#================================================================================
# Class Methods
#================================================================================
def get_children(self):
"""
Syntax tree children getter.
"""
return self.__children
def get_pattern(self):
"""
Syntax tree pattern getter.
"""
return self.__pattern
def insert(self, child: SyntaxTree) -> None:
"""
Add new child to tree.
"""
self.__children.append(child)
def search(self, input: str) -> Union[SyntaxTree, None]:
"""
Recursively search the syntax tree for Nodes matching the
:param input: the string to match
:return: the syntax tree node representing the best match, or None if no match found
"""
# Syntax match found at the beginning of the string
position = re.search(self.__pattern, input)
if position and position.start() == 0:
stem = re.sub(self.__pattern, '', input, 1)
if len(self.__children) == 0:
return self
for child in self.__children:
result = child.search(stem)
# Child match found
if result:
return result
return None