-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
glob-compiler.cc
154 lines (121 loc) · 2.69 KB
/
glob-compiler.cc
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
#include "glob-parser.h"
#include "unicode.h"
#include "std.h"
static const char special_characters[] = ".,:\"=<>[]^/\\{}|*+?";
// escape any special re2 characters in a text.
static std::string escape(const std::string& s)
{
std::string x;
for (int i = 0; i < s.length(); i++)
{
unsigned char c = s[i];
for (int j = 0; special_characters[j] != '\0'; j++)
{
if (special_characters[j] == s[i])
{
x += '\\';
}
}
x += c;
}
return x;
}
std::string node::re2(const std::string& single_mark)
{
std::string s;
if (parent == NULL) {
s = "^";
}
switch (kind)
{
case kind_pattern:
for (int i = 0; i < children.size(); i++)
{
s += children[i]->re2(single_mark);
}
break;
case kind_list:
s += "[";
if (not_)
{
s += "^";
}
s += escape(text);
s += "]";
break;
case kind_range:
s += "[";
if (not_)
{
s += "^";
}
s += lo;
s += "-";
s += hi;
s += "]";
break;
case kind_text:
s += escape(text);
break;
case kind_any:
s += single_mark + "*";
break;
case kind_super:
s += ".*";
break;
case kind_single:
s += single_mark;
break;
case kind_any_of:
s += "(";
for (int i = 0; i < children.size(); i++)
{
if (i > 0)
{
s += "|";
}
s += children[i]->re2(single_mark);
}
s += ")";
break;
default:
break;
}
if (parent == NULL)
{
s += "$";
}
return s;
}
std::string glob_translate(const char *glob, size_t n, const std::vector<std::string>& delimiters, std::string *re2)
{
lexer *l = new lexer(glob, n);
node *root = NULL;
std::string error = glob_parse(l, &root);
if (error != "")
{
delete l;
return error;
}
std::string single_mark;
if (delimiters.empty())
{
single_mark = ".";
} else {
single_mark = "[^";
for (int i = 0; i < delimiters.size(); i++)
{
int len;
if (opa_unicode_decode_utf8(delimiters[i].c_str(), 0, delimiters[i].length(), &len) < 0 || len != delimiters[i].length())
{
return "delimiter is not a single character";
}
single_mark += escape(delimiters[i]);
}
single_mark += "]";
}
*re2 = root->re2(single_mark);
delete(root);
delete(l);
return "";
}