-
Notifications
You must be signed in to change notification settings - Fork 5
/
trigraphs.py
54 lines (50 loc) · 1.18 KB
/
trigraphs.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
"""
The one of the most beloved features of C/C++.
https://en.wikipedia.org/wiki/Digraphs_and_trigraphs#C
If trigraphs are used, like they usually are,
it is put before the character stream.
"""
trigraphs = {
"=": "#",
"/": "\\",
"(": "[",
")": "]",
"!": "|",
"<": "{",
">": "}",
"-": "~",
}
def translate(sequence):
k = 0
for ch in sequence:
if k == 0:
if ch != '?':
yield ch
else:
k = 1
continue
elif k == 1:
if ch != '?':
yield '?'
yield ch
k = 0
else:
k = 2
continue
else:
k = 0
if ch in trigraphs:
yield trigraphs[ch]
continue
elif ch == '?':
k = 2
yield '?'
else:
yield '?'
yield '?'
yield ch
for _ in xrange(k):
yield '?'
if __name__ == '__main__':
test = "// Will the next line be executed????????????????/\na++;\n/??/\n* A comment *??/\n/"
print ''.join(translate(test))