forked from Kungsgeten/bml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbml.py
326 lines (278 loc) · 10.7 KB
/
bml.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
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
import re
import copy
from collections import defaultdict
content = []
# where we keep copies
clipboard = {}
vulnerability = '00'
seat = '0'
# meta information about the BML-file, supported:
# TITLE = the name of the system
# DESCRIPTION = a short summary of the system
# AUTHOR = the system's author(s)
# data in meta is only set once, and isn't overwritten
meta = defaultdict(str)
class Diagram:
"""A structure for deal diagrams"""
# each hand can be None or a tuple of four strings (s, h, d, c)
north = None
east = None
south = None
west = None
dealer = None # can be None or "N", "E", "S", "W"
vul = None # can be None or "ALL", "NO", "NS", "EW"
board = None # can be None or a string
lead = None # can be None or a string tuple ([shdc], [2-9TAKQJ])"
contract = None # can be None or a tuple of strings
def __init__(self, firstrow, hands):
for h in hands:
hand = h[0]
if hand == 'N':
self.north = h[1:]
elif hand == 'E':
self.east = h[1:]
elif hand == 'S':
self.south = h[1:]
elif hand == 'W':
self.west = h[1:]
dealer = re.search(r'(?:\A|\s)([NESW]),?(?:\Z|\s)', firstrow)
if dealer:
self.dealer = dealer.group(1)
vul = re.search(r'(?:\A|\s)(All|None|EW|NS),?(?:\Z|\s)', firstrow)
if vul:
self.vul = vul.group(1)
board = re.search(r'(?:\A|\s)#?(\d+),?(?:\Z|\s)', firstrow)
if board:
self.board = board.group(1)
lead = re.search(r'(?:\A|\s)([shdc])([2-9AKQJT]),?(?:\Z|\s)', firstrow)
if lead:
self.lead = lead.groups()
contract = re.search(r'(?:\A|\s)(PASS),?(?:\Z|\s)', firstrow)
if contract:
self.contract = ('P', None, None, None)
else:
contract = re.search(r'(?:\A|\s)(\d)([SHDCN])(XX?)?([NESW]),?(?:\Z|\s)', firstrow)
if contract:
self.contract = contract.groups()
class Node:
"""A node in a bidding table"""
def __init__(self, bid, desc, indentation, parent=None, desc_indentation=-1):
self.vul = '00'
self.seat = '0'
self.export = True
self.bid = bid
self.desc = desc
self.indentation = indentation
self.desc_indentation = desc_indentation
self.children = []
self.parent = parent
bid = re.sub(r'[-;]', '', bid)
bid = bid.replace('NT', 'N')
self.bidrepr = bid
bids = re.findall(r'\d[A-Za-z]+', self.bidrepr)
if bids and not '(' in self.bidrepr:
self.bidrepr = 'P'.join(bids)
def add_child(self, bid, desc, indentation, desc_indentation):
"""appends a new child Node to the node"""
child = Node(bid, desc, indentation, self, desc_indentation)
child.vul = self.vul
child.seat = self.seat
self.children.append(child)
return self.children[-1]
def get_sequence(self):
"""List with all the parent, and the current, bids"""
if self.parent.bidrepr == 'root':
return [self.bidrepr]
if self.parent:
ps = self.parent.get_sequence()
ps.append(self.bidrepr)
return ps
def set_children(self, children):
"""Used when copying from another Node"""
self.children = copy.deepcopy(children)
for c in self.children:
c.parent = self
# c.vul = self.vul
# c.seat = self.vul
def __getitem__(self, arg):
return self.children[arg]
def create_bidtree(text):
global clipboard, vulnerability, seat
root = Node('root', 'root', -1)
root.vul = vulnerability
root.seat = seat
lastnode = root
# breaks when no more CUT in bidtable
while True:
cut = re.search(r'^(\s*)#\s*CUT\s+(\S+)\s*\n(.*)#ENDCUT[ ]*\n?',
text, flags=re.DOTALL|re.MULTILINE)
if not cut:
break
value = cut.group(3).split('\n')
for i in range(len(value)):
value[i] = value[i][len(cut.group(1)):]
value = '\n'.join(value)
clipboard[cut.group(2)] = value # group2=key
text = text[:cut.start()]+text[cut.end():]
# breaks when no more COPY in bidtable
while True:
copy = re.search(r'^(\s*)#\s*COPY\s+(\S+)\s*\n(.*)#ENDCOPY[ ]*\n?',
text, flags=re.DOTALL|re.MULTILINE)
if not copy:
break
value = copy.group(3).split('\n')
for i in range(len(value)):
value[i] = value[i][len(copy.group(1)):]
value = '\n'.join(value)
clipboard[copy.group(2)] = value # group2=key
text = text[:copy.end(3)]+text[copy.end():]
text = text[:copy.start()]+text[copy.start(3):]
# breaks when no more PASTE in bidtable
while True:
paste = re.search(r'^(\s*)#\s*PASTE\s+(\S+)[^\S\n]*(.*)\n?', text, flags=re.MULTILINE)
if not paste:
break
indentation = paste.group(1)
lines = clipboard[paste.group(2)]
for r in paste.group(3).split():
target, replacement = r.split('=')
lines = lines.replace(target, replacement)
lines = lines.split('\n')
for l in range(len(lines)):
lines[l] = indentation + lines[l]
text = text[:paste.start()] + '\n'.join(lines) + '\n' + text[paste.end():]
hide = re.search(r'^\s*#\s*HIDE\s*\n', text, flags=re.MULTILINE)
if hide:
root.export = False
text = text[:hide.start()]+text[hide.end():]
text = re.sub(r'^\s*#\s*BIDTABLE\s*\n', '', text)
if text.strip() == '':
return None
for row in text.split('\n'):
original_row = row
if row.strip() == '':
continue # could perhaps be nicer by stripping spaces resulting from copy/paste
indentation = len(row) - len(row.lstrip())
# If the indentation is at the same level as the last bids
# description indentation, the description should just
# continue but with a line break
if indentation > 0 and indentation == lastnode.desc_indentation:
lastnode.desc += '\\n' + row.lstrip()
continue
row = row.strip()
bid = row.split(' ')[0]
desc = ' '.join(row.split(' ')[1:]).strip()
desc_indentation = original_row.find(desc)
# removes equal signs at the beginning of the description
new_desc = re.sub(r'^=\s*', '', desc)
desc_indentation += len(desc) - len(new_desc)
desc = new_desc
while indentation < lastnode.indentation:
lastnode = lastnode.parent
if indentation > lastnode.indentation:
lastnode = lastnode.add_child(bid, desc, indentation, desc_indentation)
elif indentation == lastnode.indentation:
lastnode = lastnode.parent.add_child(bid, desc, indentation, desc_indentation)
return root
class ContentType:
BIDTABLE = 1
PARAGRAPH = 2
H1 = 3
H2 = 4
H3 = 5
H4 = 6
LIST = 7
ENUM = 8
DIAGRAM = 9
TABLE = 10
DESCRIPTION = 11
BIDDING = 12
def get_content_type(text):
global meta, vulnerability, seat
if text.startswith('****'):
return (ContentType.H4, text[4:].lstrip())
if text.startswith('***'):
return (ContentType.H3, text[3:].lstrip())
if text.startswith('**'):
return (ContentType.H2, text[2:].lstrip())
if text.startswith('*'):
return (ContentType.H1, text[1:].lstrip())
# The first element is empty, therefore [1:]
if(re.match(r'^\s*-', text)):
if text.find(' :: ') >= 0:
return (ContentType.DESCRIPTION, re.split(r'^\s*-\s*', text, flags=re.MULTILINE)[1:])
return (ContentType.LIST, re.split(r'^\s*-\s*', text, flags=re.MULTILINE)[1:])
if(re.match(r'^\s*#VUL', text)):
vulnerability = text.split()[1]
return None
if(re.match(r'^\s*#SEAT', text)):
seat = text.split()[1]
return None
if(re.match(r'^\s*1\.', text)):
return (ContentType.ENUM, re.split(r'^\s*\d*\.\s*', text, flags=re.MULTILINE)[1:])
if(re.match(r'^\s*\(?[1-7]?[NTPDRCDHS]\)?\s+\(?[1-7]?[NTPDRCDHS]\)?\s+\(?[1-7]?[NTPDRCDHS]\)?\s+\(?[1-7]?[NTPDRCDHS]\)?\s*', text)):
table = []
for r in text.split('\n'):
if r:
table.append(r.split())
return (ContentType.BIDDING, table)
if(re.match(r'^\s*\(?\d[A-Za-z]+', text)):
bidtree = create_bidtree(text)
if bidtree:
return (ContentType.BIDTABLE, bidtree)
return None
# Tables
if(re.match(r'^\s*\|', text)):
table = []
rows = text.split('\n')
for r in rows:
table.append([c.strip() for c in re.findall(r'(?<=\|)[^\|]+', r)])
return (ContentType.TABLE, table)
# diagrams
hands = re.findall(r"""^\s*([NESW]):?\s*
([2-9AKQJTx-]+)\s+
([2-9AKQJTx-]+)\s+
([2-9AKQJTx-]+)\s+
([2-9AKQJTx-]+)""",
text, flags=re.MULTILINE|re.VERBOSE)
if hands and len(hands) + 2 >= len(text.split('\n')):
return (ContentType.DIAGRAM, Diagram(text.split('\n')[0], hands))
metamatch = re.match(r'^\s*#\+(\w+):\s*(.*)', text)
if(metamatch):
keyword = metamatch.group(1)
if keyword in meta:
return None
value = metamatch.group(2)
meta[keyword] = value
return None
if(re.match(r'^\s*#', text)):
bidtree = create_bidtree(text)
if bidtree:
return (ContentType.BIDTABLE, bidtree)
return None
if(re.search(r'\S', text)):
text = re.sub(r'\n +', '\n', text.strip())
return (ContentType.PARAGRAPH, text)
return None
def include_file(matchobj):
filename = matchobj.group(1)
text = ''
with open(filename, 'r') as f:
text = f.read()
return '\n' + text + '\n'
def content_from_file(filename):
global content
paragraphs = []
with open(filename, 'r') as f:
text = f.read()
text = re.sub(r'^\s*#\s*INCLUDE\s*(\S+)\s*\n?', include_file, text, flags=re.MULTILINE)
text = re.sub(r'^//.*\n', '', text, flags=re.MULTILINE)
text = re.sub(r'//.*', '', text)
paragraphs = re.split(r'([ ]*\n){2,}', text)
for c in paragraphs:
content_type = get_content_type(c)
if content_type:
content.append(content_type)
if __name__ == '__main__':
# print('To use BML, use the subprograms bml2html, bml2latex or bml2bss')
content_from_file('test.bml')