This repository was archived by the owner on Feb 24, 2022. It is now read-only.
forked from facebookresearch/TransCoder
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_tokenize_cpp.py
More file actions
executable file
·284 lines (240 loc) · 7.63 KB
/
Copy pathtest_tokenize_cpp.py
File metadata and controls
executable file
·284 lines (240 loc) · 7.63 KB
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
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from preprocessing.src.code_tokenizer import tokenize_cpp, detokenize_cpp
import pytest
TESTS = []
TESTS.append((
r"""
// This is a comment
// ------- ******* -------
int main() {
std::cout << "Hello World!";
return 0;
}""",
['int', 'main', '(', ')', '{',
'std', '::', 'cout', '<<', '" Hello ▁ World ! "', ';',
'return', '0', ';', '}']
))
TESTS.append((r"""
overload((byte)1);
overload(1L);
overload(1.0f);""",
['overload', '(', '(', 'byte', ')', '1', ')', ';',
'overload', '(', '1L', ')', ';',
'overload', '(', '1.0f', ')', ';']
))
TESTS.append((r"""auto glambda = [](auto a, auto&& b) { return a < b; };""",
["auto", "glambda", "=", "[", "]", "(", "auto", "a", ",", "auto", "&&", "b", ")",
"{", "return", "a", "<", "b", ";", "}", ";"]))
# test reference, pointor
TESTS.append((r""" int a = 0;
int * b = new int(0);
int& ref = a;""",
["int", "a", "=", "0", ";",
"int", "*", "b", "=",
"new", "int", "(", "0", ")", ";",
"int", "&", "ref", "=", "a", ";"]))
# test incrementation - equality/uniquality
TESTS.append((r"""a = 0;
b = 0;
a += 10;
a ++;
a --;
a -= 100;
if (a == b) {
cout<<"yes"<<endl;
}
if (a != b) {
cout << "no" << endl;
}""",
["a", "=", "0", ";",
"b", "=", "0", ";",
"a", "+=", "10", ";",
"a", "++", ";",
"a", "--", ";",
"a", "-=", "100", ";",
'if', '(', 'a', '==', 'b', ')', '{', 'cout', '<<', '" yes "', "<<", "endl", ";", "}",
'if', '(', 'a', '!=', 'b', ')', '{', 'cout', '<<', '" no "', '<<', 'endl', ';', '}']))
TESTS.append(("std::unordered_map<MyCustomObject, std::string> hashmap;",
["std", "::", "unordered_map", "<", "MyCustomObject", ",", "std", "::", "string", ">", "hashmap", ";"]))
TESTS.append((r"""string s = "Hi I am\nMarie";""",
["string", "s", "=", '" Hi ▁ I ▁ am \\n Marie "', ';']))
TESTS_KEEP_COMMENTS = [(
r"""
// This is a comment
// ----------*****
int main() {
std::cout << "Hello World!";
return 0;
}""",
['// ▁ This ▁ is ▁ a ▁ comment ENDCOM',
'int', 'main', '(', ')', '{',
'std', '::', 'cout', '<<', '" Hello ▁ World ! "', ';',
'return', '0', ';', '}']
),
(r"""
/* This is a
multiline comment */
/*----------------this is the docstring */
/* ----*----*-*---- ====== *** */
int main() {
std::cout << "Hello World!";
return 0;
}""", ['/* ▁ This ▁ is ▁ a STRNEWLINE multiline ▁ comment ▁ */', '/* - - - - - this ▁ is ▁ the ▁ docstring ▁ */', 'int',
'main', '(', ')', '{', 'std', '::', 'cout', '<<', '" Hello ▁ World ! "', ';', 'return', '0', ';', '}'])
]
TESTS_CHARS = [(
r"""
char a = 'a';
""",
["char", "a", "=", "' a '", ";"]
)
]
TESTS_STRINGS = [(
r"""
string s = "Hello !";""",
["string", "s", "=", f'" Hello ▁ ! "', ";"]
),
]
TESTS_MULTILINE_STRINGS = [(
r"""
string s =
"First line"
"Second line";
""",
["string", "s", "=", f'" First ▁ line "', '" Second ▁ line "', ";"]
)
]
TESTS_DETOKENIZE_MULTILINE_STRINGS = [(
r"""
string s =
"First line"
"Second line";
""",
r"""string s = "First line" "Second line";
"""
)
]
DETOKENIZE_TESTS = []
DETOKENIZE_TESTS.append((
r"""
// This is a comment
int main() {
std::cout << "Hello World!";
return 0;
}""",
r"""int main ( ) {
std :: cout << "Hello World!";
return 0;
}
"""
))
DETOKENIZE_TESTS.append((
r"""int a = 0;
int * b = new int(0);
int& ref = a;""",
r"""int a = 0;
int * b = new int ( 0 );
int & ref = a;
"""
))
DETOKENIZE_TESTS.append((
r"""a = 0;
b = 0
a += 10;
a ++;
a --;
a -= 100;
if (a == b) {
cout<<"yes"<<endl;
}
if (a != b) {
cout << "no" << endl;
}
""",
r"""a = 0;
b = 0 a += 10;
a ++;
a --;
a -= 100;
if ( a == b ) {
cout << "yes" << endl;
}
if ( a != b ) {
cout << "no" << endl;
}
"""
))
@pytest.mark.skip('Helper function')
def test_tokenizer(test_examples, keep_comments):
for i, (x, y) in enumerate(test_examples):
y_ = tokenize_cpp(x, keep_comments=keep_comments)
if y_ != y:
line_diff = [j for j, (line, line_) in enumerate(
zip(y, y_)) if line != line_]
line_diff = line_diff[-1] if len(line_diff) > 0 else -1
raise Exception(
f"Difference at {line_diff}\nExpected:\n==========\n{y}\nbut found:\n==========\n{y_}")
@pytest.mark.skip('Helper function')
def test_detokenize_invertible(test_examples):
for i, (x, _) in enumerate(test_examples):
x_ = detokenize_cpp(tokenize_cpp(x, keep_comments=False))
if x_.strip() != x.strip():
raise Exception(
f"Expected:\n==========\n{x.strip()}\nbut found:\n==========\n{x_.strip()}")
@pytest.mark.skip('Helper function')
def test_detokenize_non_invertible(test_examples):
for i, (x, y) in enumerate(test_examples):
y_ = detokenize_cpp(tokenize_cpp(x, keep_comments=False))
if y_ != y:
lenght = min(len(y_), len(y))
char_message = ""
for j in range(lenght):
if y_[j] != y[j]:
char_message = f"expected character '{y[j]}' at index {j} but found '{y_[j]}'"
if char_message == "":
char_message = f"expected length {len(y)}, found {len(y_)}"
raise Exception(
f"Expected:\n==========\n{y}\nbut found:\n==========\n{y_} \n==========\n{char_message}")
@pytest.mark.skip('Helper function')
def test_tokenize_twice(test_examples, keep_comments=False):
for i, (x, _) in enumerate(test_examples):
tokenized_once = tokenize_cpp(x, keep_comments=keep_comments)
tokenized_twice = tokenize_cpp(detokenize_cpp(
tokenized_once), keep_comments=keep_comments)
if tokenized_once != tokenized_twice:
lenght = min(len(tokenized_twice), len(tokenized_once))
char_message = ""
for j in range(lenght):
if tokenized_twice[j] != tokenized_once[j]:
char_message = f"expected token '{tokenized_once[j]}' at index {j} but found '{tokenized_twice[j]}'"
if char_message == "":
char_message = f"expected length {len(tokenized_once)}, found {len(tokenized_twice)}"
raise Exception(
f"Expected:\n==========\n{tokenized_once}\nbut found:\n==========\n{tokenized_twice} \n==========\n{char_message}")
def test_cpp_tokenizer_discarding_comments():
test_tokenizer(TESTS, keep_comments=False)
def test_cpp_tokenizer_keep_comments():
test_tokenizer(TESTS_KEEP_COMMENTS, keep_comments=True)
def test_cpp_chars():
test_tokenizer(TESTS_CHARS, keep_comments=False)
def test_cpp_strings():
test_tokenizer(TESTS_STRINGS + TESTS_MULTILINE_STRINGS,
keep_comments=False)
def test_cpp_detokenize():
test_detokenize_non_invertible(DETOKENIZE_TESTS)
def test_detokenize_cpp_chars():
test_detokenize_invertible(TESTS_CHARS)
def test_detokenize_string():
test_detokenize_invertible(TESTS_STRINGS)
def test_detokenize_multiline_string():
test_detokenize_non_invertible(TESTS_DETOKENIZE_MULTILINE_STRINGS)
def test_tokenize_twice_equal_tokenize_remove_comments():
test_tokenize_twice(TESTS + TESTS_STRINGS + TESTS_CHARS)
def test_tokenize_twice_equal_tokenize_keep_comments():
test_tokenize_twice(TESTS + TESTS_STRINGS + TESTS_CHARS +
TESTS_KEEP_COMMENTS, keep_comments=True)