Debian Codegraph @

src/YappsStarParser_2_0.g

raw
1 # The following two recipes produce CIF2 and STAR2 syntax.
2 #
3 #
4 # <CIF2_syntax>=
5 # Python 2/3 compatibility. We try to keep the code as
6 # portable across the 2-3 divide as we can.
7 #
8 #
9 # <Python2-3 compatibility>=
10 # To maximize python3/python2 compatibility
11 from __future__ import print_function
12 from __future__ import unicode_literals
13 from __future__ import division
14 from __future__ import absolute_import
15
16 from .StarFile import StarBlock,StarFile,StarList,StarDict
17 from . import CifSyntaxError
18 from io import StringIO
19 # Helper functions.
20 #
21 # We have a monitor function which we can call to save the last parsed
22 # value (and print, if we are debugging). We also have functions for
23 # stripping off delimiters from strings. Finally, we match up our
24 # loops after reading them in. Note that we have function stripextras,
25 # which is only for semicolon strings, and stripstring, which is for
26 # getting rid of the inverted commas.
27 #
28 #
29 # <Helper functions>=
30 # An alternative specification for the Cif Parser, based on Yapps2
31 # by Amit Patel (http://theory.stanford.edu/~amitp/Yapps)
32 #
33 # helper code: we define our match tokens
34 lastval = ''
35 def monitor(location,value):
36 global lastval
37 #print 'At %s: %s' % (location,repr(value))
38 lastval = repr(value)
39 return value
40
41 # Strip extras gets rid of leading and trailing whitespace, and
42 # semicolons.
43 def stripextras(value):
44 from .StarFile import remove_line_folding, remove_line_prefix
45 # we get rid of semicolons and leading/trailing terminators etc.
46 import re
47 jj = re.compile("[\n\r\f \t\v]*")
48 semis = re.compile("[\n\r\f \t\v]*[\n\r\f]\n*;")
49 cut = semis.match(value)
50 if cut: #we have a semicolon-delimited string
51 nv = value[cut.end():len(value)-2]
52 try:
53 if nv[-1]=='\r': nv = nv[:-1]
54 except IndexError: #empty data value
55 pass
56 # apply protocols
57 nv = remove_line_prefix(nv)
58 nv = remove_line_folding(nv)
59 return nv
60 else:
61 cut = jj.match(value)
62 if cut:
63 return stripstring(value[cut.end():])
64 return value
65
66 # helper function to get rid of inverted commas etc.
67
68 def stripstring(value):
69 if value:
70 if value[0]== '\'' and value[-1]=='\'':
71 return value[1:-1]
72 if value[0]=='"' and value[-1]=='"':
73 return value[1:-1]
74 return value
75
76 # helper function to get rid of triple quotes
77 def striptriple(value):
78 if value:
79 if value[:3] == '"""' and value[-3:] == '"""':
80 return value[3:-3]
81 if value[:3] == "'''" and value[-3:] == "'''":
82 return value[3:-3]
83 return value
84
85 # helper function to populate a StarBlock given a list of names
86 # and values .
87 #
88 # Note that there may be an empty list at the very end of our itemlists,
89 # so we remove that if necessary.
90 #
91 # charpos and context are provided so that we can emit a sensible
92 # error message.
93
94 def makeloop(target_block, loopdata, context):
95 loop_seq,itemlists = loopdata
96 if itemlists[-1] == []: itemlists.pop(-1)
97 # print('Making loop with %s' % repr(itemlists))
98 step_size = len(loop_seq)
99 for col_no in range(step_size):
100 target_block.AddItem(loop_seq[col_no], itemlists[col_no::step_size],precheck=True)
101 # now construct the loop
102 try:
103 target_block.CreateLoop(loop_seq) #will raise ValueError on problem
104 except ValueError:
105 charpos = context.scanner.get_prev_char_pos()
106 error_string = 'Incorrect number of loop values for loop containing %s' % repr(loop_seq)
107 raise CifSyntaxError(charpos=charpos, context=context, msg = error_string)
108
109 # return an object with the appropriate amount of nesting
110 def make_empty(nestlevel):
111 gd = []
112 for i in range(1,nestlevel):
113 gd = [gd]
114 return gd
115
116 # this function updates a dictionary first checking for name collisions,
117 # which imply that the CIF is invalid. We need case insensitivity for
118 # names.
119
120 # Unfortunately we cannot check loop item contents against non-loop contents
121 # in a non-messy way during parsing, as we may not have easy access to previous
122 # key value pairs in the context of our call (unlike our built-in access to all
123 # previous loops).
124 # For this reason, we don't waste time checking looped items against non-looped
125 # names during parsing of a data block. This would only match a subset of the
126 # final items. We do check against ordinary items, however.
127 #
128 # Note the following situations:
129 # (1) new_dict is empty -> we have just added a loop; do no checking
130 # (2) new_dict is not empty -> we have some new key-value pairs
131 #
132 def cif_update(old_dict,new_dict,loops):
133 old_keys = map(lambda a:a.lower(),old_dict.keys())
134 if new_dict != {}: # otherwise we have a new loop
135 #print 'Comparing %s to %s' % (repr(old_keys),repr(new_dict.keys()))
136 for new_key in new_dict.keys():
137 if new_key.lower() in old_keys:
138 raise CifError("Duplicate dataname or blockname %s in input file" % new_key)
139 old_dict[new_key] = new_dict[new_key]
140 #
141 # this takes two lines, so we couldn't fit it into a one line execution statement...
142 def order_update(order_array,new_name):
143 order_array.append(new_name)
144 return new_name
145
146 # and finally...turn a sequence into a python dict (thanks to Stackoverflow)
147 def pairwise(iterable):
148 try:
149 it = iter(iterable)
150 while 1:
151 yield next(it), next(it)
152 except StopIteration:
153 return
154 %%
155 parser StarParser:
156 # CIF 2.0 uses spaces instead of commas to separate list values so commas are allowed in data values
157 #
158 #
159 # <Regular expressions CIF2>=
160 # <STAR2-CIF2 common regular expressions block 1>=
161 # first handle whitespace and comments, keeping whitespace
162 # before a semicolon
163 ignore: r"([ \t\n\r](?!;))|[ \t]"
164 ignore: r"(#.*[\n\r](?!;))|(#.*)"
165 # now the tokens
166 token LBLOCK: "(L|l)(O|o)(O|o)(P|p)_" # loop_
167 token GLOBAL: "(G|g)(L|l)(O|o)(B|b)(A|a)(L|l)_"
168 token STOP: "(S|s)(T|t)(O|o)(P|p)_"
169 token save_heading: "(S|s)(A|a)(V|v)(E|e)_[][!%&()*+,./:<=>?@0-9A-Za-z\\\\^`{}|~\"#$';_\u00A0-\uD7FF\uE000-\uFDCF\uFDF0-\uFFFD\U00010000-\U0001FFFD\U00020000-\U0002FFFD\U00030000-\U0003FFFD\U00040000-\U0004FFFD\U00050000-\U0005FFFD\U00060000-\U0006FFFD\U00070000-\U0007FFFD\U00080000-\U0008FFFD\U00090000-\U0009FFFD\U000A0000-\U000AFFFD\U000B0000-\U000BFFFD\U000C0000-\U000CFFFD\U000D0000-\U000DFFFD\U000E0000-\U000EFFFD\U000F0000-\U000FFFFD\U00100000-\U0010FFFD-]+"
170 token save_end: "(S|s)(A|a)(V|v)(E|e)_"
171 token data_name: "_[][!%&()*+,./:<=>?@0-9A-Za-z\\\\^`{}|~\"#$';_\u00A0-\uD7FF\uE000-\uFDCF\uFDF0-\uFFFD\U00010000-\U0001FFFD\U00020000-\U0002FFFD\U00030000-\U0003FFFD\U00040000-\U0004FFFD\U00050000-\U0005FFFD\U00060000-\U0006FFFD\U00070000-\U0007FFFD\U00080000-\U0008FFFD\U00090000-\U0009FFFD\U000A0000-\U000AFFFD\U000B0000-\U000BFFFD\U000C0000-\U000CFFFD\U000D0000-\U000DFFFD\U000E0000-\U000EFFFD\U000F0000-\U000FFFFD\U00100000-\U0010FFFD-]+" #_followed by stuff
172 token data_heading: "(D|d)(A|a)(T|t)(A|a)_[][!%&()*+,./:<=>?@0-9A-Za-z\\\\^`{}|~\"#$';_\u00A0-\uD7FF\uE000-\uFDCF\uFDF0-\uFFFD\U00010000-\U0001FFFD\U00020000-\U0002FFFD\U00030000-\U0003FFFD\U00040000-\U0004FFFD\U00050000-\U0005FFFD\U00060000-\U0006FFFD\U00070000-\U0007FFFD\U00080000-\U0008FFFD\U00090000-\U0009FFFD\U000A0000-\U000AFFFD\U000B0000-\U000BFFFD\U000C0000-\U000CFFFD\U000D0000-\U000DFFFD\U000E0000-\U000EFFFD\U000F0000-\U000FFFFD\U00100000-\U0010FFFD-]+"
173 token start_sc_line: "(\n|\r\n);([^\n\r])*(\r\n|\r|\n)+"
174 token sc_line_of_text: "[^;\r\n]([^\r\n])*(\r\n|\r|\n)+"
175 token end_sc_line: ";"
176 token c_c_b: "}"
177 token o_c_b: "{"
178 token c_s_b: "]"
179 token o_s_b: r"\["
180 #token dat_val_nocomma_nosq: "([^\s\"#$,'_\(\{\[\]][^\s,\[\]]*)|'(('(?![\s,]))|([^\n\r\f']))*'+|\"((\"(?![\s,]))|([^\n\r\"]))*\"+"
181 token dat_val_internal_sq: r"\[([^\s[\]]*)\]"
182 # token dat_val_nocomma_nocurl: "([^\s\"#$,'_\(\{\[\]][^\s,}]*)|'(('(?![\s,]))|([^\n\r\f']))*'+|\"([^\n\r\"])*\"+"
183 # For tests of new DDLm syntax - no quotes or apostrophes in strings, no commas, braces or square brackets in undelimited data values
184 # This token for triple-quote delimited strings must come before single-quote delimited strings to avoid the opening quotes being
185 # interpreted as a single-quote delimited string
186 token triple_quote_data_value: "(?s)'''.*?'''|\"\"\".*?\"\"\""
187 token single_quote_data_value: r"'([^\n\r\f'])*'+|\"([^\n\r\"])*\"+"
188
189 token data_value_1: r"((?!(((S|s)(A|a)(V|v)(E|e)_[^\s]*)|((G|g)(L|l)(O|o)(B|b)(A|a)(L|l)_[^\s]*)|((S|s)(T|t)(O|o)(P|p)_[^\s]*)|((D|d)(A|a)(T|t)(A|a)_[^\s]*)))[^\s\"#$'_{}[\]][^\s{}[\]]*)"
190 # Currently just a single line but we allow a whole block just in case.
191 #
192 #
193 # <STAR2-CIF2 common regular expressions block 2>=
194 token END: '$'
195
196
197 # <Grammar specification CIF2>=
198 # CIF2 and STAR2 are almost identical in grammar
199 #
200 #
201 # <CIF2-STAR2 common grammar>=
202 # now the rules
203
204 rule input<<prepared>>: ( ((
205 dblock<<prepared>> {{allblocks = prepared; allblocks.merge_fast(dblock)}}
206 (
207 dblock<<prepared>> {{allblocks.merge_fast(dblock)}} #
208 )*
209 END
210 )
211 |
212 (
213 END {{allblocks = prepared}}
214 ))) {{allblocks.unlock(); return allblocks}}
215
216 rule dblock<<prepared>>: ( data_heading {{heading = data_heading[5:];thisbc=StarFile(characterset='unicode',standard=prepared.standard);act_heading = thisbc.NewBlock(heading,prepared.blocktype(overwrite=False));stored_block = thisbc[act_heading]}}# a data heading
217 (
218 dataseq<<stored_block>> #because merging may have changed the heading
219 |
220 save_frame<<prepared>> {{thisbc.merge_fast(save_frame,parent=stored_block)}}
221 )*
222 ) {{stored_block.setmaxnamelength(stored_block.maxnamelength);return (monitor('dblock',thisbc))}} # but may be empty
223
224 rule dataseq<<starblock>>: data<<starblock>>
225 (
226 data<<starblock>>
227 )*
228
229 rule data<<currentblock>>: top_loop {{makeloop(currentblock,top_loop,_context)}}
230 |
231 datakvpair {{currentblock.AddItem(datakvpair[0],datakvpair[1],precheck=True)}} #kv pair
232
233 rule datakvpair: data_name data_value {{return [data_name,data_value]}} # name-value
234
235 rule data_value: (data_value_1 {{thisval = data_value_1}}
236 |
237 delimited_data_value {{thisval = delimited_data_value}}
238 |
239 sc_lines_of_text {{thisval = stripextras(sc_lines_of_text)}}
240 |
241 bracket_expression {{thisval = bracket_expression}}
242 ) {{return monitor('data_value',thisval)}}
243
244 rule delimited_data_value: (triple_quote_data_value {{thisval = striptriple(triple_quote_data_value)}}
245 |
246 single_quote_data_value {{thisval = stripstring(single_quote_data_value)}}
247 ) {{return thisval}}
248
249 rule sc_lines_of_text: start_sc_line {{lines = StringIO();lines.write(start_sc_line)}}
250 (
251 sc_line_of_text {{lines.write(sc_line_of_text)}}
252 )*
253 end_sc_line {{lines.write(end_sc_line);return monitor('sc_line_of_text',lines.getvalue())}}
254
255 rule bracket_expression: square_bracket_expr {{return square_bracket_expr}}
256 |
257 curly_bracket_expr {{return curly_bracket_expr}}
258
259
260 # due to the inability of the parser to backtrack, we contruct our loops in helper functions,
261 # and simply collect data during parsing proper.
262
263 rule top_loop: LBLOCK loopfield loopvalues {{return loopfield,loopvalues}}
264
265 # OK: a loopfield is either a sequence of datanames
266
267 rule loopfield: ( {{loop_seq=[] }}
268 (
269 ( data_name ) {{loop_seq.append(data_name)}}
270 )*
271 ) {{return loop_seq}} # sequence of data names
272
273
274 rule loopvalues: (
275 (data_value ) {{dataloop=[data_value]}}
276 (
277 (data_value ) {{dataloop.append(monitor('loopval',data_value))}}
278 )*
279 ) {{return dataloop}}
280
281 rule save_frame<<prepared>>: save_heading {{savehead = save_heading[5:];savebc = StarFile(characterset='unicode');newname = savebc.NewBlock(savehead,prepared.blocktype(overwrite=False));stored_block = savebc[newname] }}
282 (
283 dataseq<<savebc[savehead]>>
284 |
285 save_frame<<prepared>> {{savebc.merge_fast(save_frame,parent=stored_block)}}
286 )*
287 save_end {{return monitor('save_frame',savebc)}}
288
289 # <CIF2-specific grammar>=
290 rule save_frame<<prepared>>: save_heading {{savehead = save_heading[5:];savebc = StarFile(characterset='unicode');newname = savebc.NewBlock(savehead,prepared.blocktype(overwrite=False));stored_block = savebc[newname] }}
291 (
292 dataseq<<savebc[savehead]>>
293 )*
294 save_end {{return monitor('save_frame',savebc)}}
295
296
297 rule square_bracket_expr: o_s_b {{this_list = []}}
298 ( data_value {{this_list.append(data_value)}}
299 (
300 data_value {{this_list.append(data_value)}}
301 ) *
302 ) *
303 c_s_b {{return StarList(this_list)}}
304
305 rule curly_bracket_expr: ( o_c_b {{table_as_list = []}}
306 ( delimited_data_value {{table_as_list = [delimited_data_value]}}
307 ":"
308 data_value {{table_as_list.append(data_value)}}
309 (
310 delimited_data_value {{table_as_list.append(delimited_data_value)}}
311 ":"
312 data_value {{table_as_list.append(data_value)}}
313 ) *
314 ) *
315 c_c_b ) {{return StarDict(pairwise(table_as_list))}}
316
317
318
319
320 %%