Debian Codegraph @

src/YappsStarParser.nw

raw
1 @
2 Noweb literate programming file for Star grammar and parser specification.
3 We are using Amit Patel's excellent context-sensitive Yapps2 parser.
4 '
5 This was chosen
6 because it enables us to process long semicolon delimited strings without
7 running into Python recursion limits. In the original kjParsing implementation,
8 it was impossible to get the lexer to return a single line of text within
9 the semicolon-delimited string as that re would have matched a single line
10 of text anywhere in the file. The resulting very long match expression
11 only worked for text strings less than about 9000 characters in length.
12 For further information about Yapps2, see
13 http://theory.stanford.edu/~amitp/Yapps/
14
15 Several standards are available, of which four are implemented: 1.0,
16 1.1, CIF2 and STAR2. CIF2 differs from STAR2 in that lists have comma
17 separators and no nested save frames are allowed. Note that 1.0,1.1
18 and CIF2/STAR2 differ in their treatment of unquoted data values beginning
19 with brackets.
20
21 <<1.0_syntax>>=
22 <<Python2-3 compatibility>>
23 <<Helper functions>>
24 %%
25 parser StarParser:
26 <<Regular expressions 1.0>>
27 <<Grammar specification 1.1>>
28 %%
29
30 <<1.1_syntax>>=
31 <<Python2-3 compatibility>>
32 <<Helper functions>>
33 %%
34 parser StarParser:
35 <<Regular expressions 1.1>>
36 <<Grammar specification 1.1>>
37 %%
38 @ The following two recipes produce CIF2 and STAR2 syntax.
39
40 <<CIF2_syntax>>=
41 <<Python2-3 compatibility>>
42 <<Helper functions>>
43 %%
44 parser StarParser:
45 <<Regular expressions CIF2>>
46 <<Grammar specification CIF2>>
47 %%
48 @ The STAR2 syntax
49 <<STAR2_syntax>>=
50 <<Python2-3 compatibility>>
51 <<Helper functions>>
52 %%
53 parser StarParser:
54 <<Regular expressions STAR2>>
55 <<Grammar specification STAR2>>
56 %%
57 @ Helper functions.
58
59 We have a monitor function which we can call to save the last parsed
60 value (and print, if we are debugging). We also have functions for
61 stripping off delimiters from strings. Finally, we match up our
62 loops after reading them in. Note that we have function stripextras,
63 which is only for semicolon strings, and stripstring, which is for
64 getting rid of the inverted commas.
65
66 <<Helper functions>>=
67 # An alternative specification for the Cif Parser, based on Yapps2
68 # by Amit Patel (http://theory.stanford.edu/~amitp/Yapps)
69 #
70 # helper code: we define our match tokens
71 lastval = ''
72 def monitor(location,value):
73 global lastval
74 #print 'At %s: %s' % (location,repr(value))
75 lastval = repr(value)
76 return value
77
78 # Strip extras gets rid of leading and trailing whitespace, and
79 # semicolons.
80 def stripextras(value):
81 from .StarFile import remove_line_folding, remove_line_prefix
82 # we get rid of semicolons and leading/trailing terminators etc.
83 import re
84 jj = re.compile("[\n\r\f \t\v]*")
85 semis = re.compile("[\n\r\f \t\v]*[\n\r\f]\n*;")
86 cut = semis.match(value)
87 if cut: #we have a semicolon-delimited string
88 nv = value[cut.end():len(value)-2]
89 try:
90 if nv[-1]=='\r': nv = nv[:-1]
91 except IndexError: #empty data value
92 pass
93 # apply protocols
94 nv = remove_line_prefix(nv)
95 nv = remove_line_folding(nv)
96 return nv
97 else:
98 cut = jj.match(value)
99 if cut:
100 return stripstring(value[cut.end():])
101 return value
102
103 # helper function to get rid of inverted commas etc.
104
105 def stripstring(value):
106 if value:
107 if value[0]== '\'' and value[-1]=='\'':
108 return value[1:-1]
109 if value[0]=='"' and value[-1]=='"':
110 return value[1:-1]
111 return value
112
113 # helper function to get rid of triple quotes
114 def striptriple(value):
115 if value:
116 if value[:3] == '"""' and value[-3:] == '"""':
117 return value[3:-3]
118 if value[:3] == "'''" and value[-3:] == "'''":
119 return value[3:-3]
120 return value
121
122 # helper function to populate a StarBlock given a list of names
123 # and values .
124 #
125 # Note that there may be an empty list at the very end of our itemlists,
126 # so we remove that if necessary.
127 #
128
129 def makeloop(target_block,loopdata):
130 loop_seq,itemlists = loopdata
131 if itemlists[-1] == []: itemlists.pop(-1)
132 # print('Making loop with %s' % repr(itemlists))
133 step_size = len(loop_seq)
134 for col_no in range(step_size):
135 target_block.AddItem(loop_seq[col_no], itemlists[col_no::step_size],precheck=True)
136 # now construct the loop
137 try:
138 target_block.CreateLoop(loop_seq) #will raise ValueError on problem
139 except ValueError:
140 error_string = 'Incorrect number of loop values for loop containing %s' % repr(loop_seq)
141 print(error_string, file=sys.stderr)
142 raise ValueError(error_string)
143
144 # return an object with the appropriate amount of nesting
145 def make_empty(nestlevel):
146 gd = []
147 for i in range(1,nestlevel):
148 gd = [gd]
149 return gd
150
151 # this function updates a dictionary first checking for name collisions,
152 # which imply that the CIF is invalid. We need case insensitivity for
153 # names.
154
155 # Unfortunately we cannot check loop item contents against non-loop contents
156 # in a non-messy way during parsing, as we may not have easy access to previous
157 # key value pairs in the context of our call (unlike our built-in access to all
158 # previous loops).
159 # For this reason, we don't waste time checking looped items against non-looped
160 # names during parsing of a data block. This would only match a subset of the
161 # final items. We do check against ordinary items, however.
162 #
163 # Note the following situations:
164 # (1) new_dict is empty -> we have just added a loop; do no checking
165 # (2) new_dict is not empty -> we have some new key-value pairs
166 #
167 def cif_update(old_dict,new_dict,loops):
168 old_keys = map(lambda a:a.lower(),old_dict.keys())
169 if new_dict != {}: # otherwise we have a new loop
170 #print 'Comparing %s to %s' % (repr(old_keys),repr(new_dict.keys()))
171 for new_key in new_dict.keys():
172 if new_key.lower() in old_keys:
173 raise CifError("Duplicate dataname or blockname %s in input file" % new_key)
174 old_dict[new_key] = new_dict[new_key]
175 #
176 # this takes two lines, so we couldn't fit it into a one line execution statement...
177 def order_update(order_array,new_name):
178 order_array.append(new_name)
179 return new_name
180
181 # and finally...turn a sequence into a python dict (thanks to Stackoverflow)
182 def pairwise(iterable):
183 try:
184 it = iter(iterable)
185 while 1:
186 yield next(it), next(it)
187 except StopIteration:
188 return
189 @
190
191 We can simplify the BNC specification of Nick Spadaccini. First of
192 all, we do not have to have type I and type II strings, which are
193 distinguished by the presence or absence of a line feed directly
194 preceding them and thus by being allowed a semicolon at the front or
195 not. We take care of this by treating as whitespace all terminators
196 except for those with a following semicolon, so that a
197 carriage-return-semicolon sequence matches the start_sc_line uniquely.
198
199 We include reserved words and save frames. The other reserved words
200 have no rules defined, so will flag a syntax error. However, as yapps
201 is a context-sensitive parser, it will by default make any word found
202 starting with our reserved words into a data value if it occurs in the
203 expected position, so we explicity exclude stuff starting with our
204 words in the definition of data_value_1.
205
206 The syntax rules below correspond to the current STAR2 paper. Commas
207 are not allowed in non-delimited data values so that they can be used
208 to separate list items.
209
210 Note that we do not recognise characters outside the Unicode basic
211 multilingual plane in datanames, data headings and save headings.
212 This is due to a limitation of Python 2 unicode strings and will be
213 removed when PyCIFRW is ported to Python 3.
214
215 <<Regular expressions STAR2>>=
216 <<STAR2-CIF2 common regular expressions block 1>>
217 <<STAR2-CIF2 common regular expressions block 2>>
218 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,{}[\]]*)"
219
220 <<STAR2-CIF2 common regular expressions block 1>>=
221 # first handle whitespace and comments, keeping whitespace
222 # before a semicolon
223 ignore: r"([ \t\n\r](?!;))|[ \t]"
224 ignore: r"(#.*[\n\r](?!;))|(#.*)"
225 # now the tokens
226 token LBLOCK: "(L|l)(O|o)(O|o)(P|p)_" # loop_
227 token GLOBAL: "(G|g)(L|l)(O|o)(B|b)(A|a)(L|l)_"
228 token STOP: "(S|s)(T|t)(O|o)(P|p)_"
229 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-]+"
230 token save_end: "(S|s)(A|a)(V|v)(E|e)_"
231 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
232 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-]+"
233 token start_sc_line: "(\n|\r\n);([^\n\r])*(\r\n|\r|\n)+"
234 token sc_line_of_text: "[^;\r\n]([^\r\n])*(\r\n|\r|\n)+"
235 token end_sc_line: ";"
236 token c_c_b: "}"
237 token o_c_b: "{"
238 token c_s_b: "]"
239 token o_s_b: r"\["
240 #token dat_val_nocomma_nosq: "([^\s\"#$,'_\(\{\[\]][^\s,\[\]]*)|'(('(?![\s,]))|([^\n\r\f']))*'+|\"((\"(?![\s,]))|([^\n\r\"]))*\"+"
241 token dat_val_internal_sq: r"\[([^\s[\]]*)\]"
242 # token dat_val_nocomma_nocurl: "([^\s\"#$,'_\(\{\[\]][^\s,}]*)|'(('(?![\s,]))|([^\n\r\f']))*'+|\"([^\n\r\"])*\"+"
243 # For tests of new DDLm syntax - no quotes or apostrophes in strings, no commas, braces or square brackets in undelimited data values
244 # This token for triple-quote delimited strings must come before single-quote delimited strings to avoid the opening quotes being
245 # interpreted as a single-quote delimited string
246 token triple_quote_data_value: "(?s)'''.*?'''|\"\"\".*?\"\"\""
247 token single_quote_data_value: r"'([^\n\r\f'])*'+|\"([^\n\r\"])*\"+"
248
249 @ Currently just a single line but we allow a whole block just in case.
250
251 <<STAR2-CIF2 common regular expressions block 2>>=
252 token END: '$'
253
254 @ CIF 2.0 uses spaces instead of commas to separate list values so commas are allowed in data values
255
256 <<Regular expressions CIF2>>=
257 <<STAR2-CIF2 common regular expressions block 1>>
258 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{}[\]]*)"
259 <<STAR2-CIF2 common regular expressions block 2>>
260
261 @ CIF 1.1 does not allow unquoted data values to begin with a bracket character, but does not have bracket expressions
262 as such.
263
264 <<Regular expressions 1.1>>=
265 # first handle whitespace and comments, keeping whitespace
266 # before a semicolon
267 ignore: r"([ \t\n\r](?!;))|[ \t]"
268 ignore: r"(#.*[\n\r](?!;))|(#.*)"
269 # now the tokens
270 token LBLOCK: "(L|l)(O|o)(O|o)(P|p)_" # loop_
271 token GLOBAL: "(G|g)(L|l)(O|o)(B|b)(A|a)(L|l)_"
272 token STOP: "(S|s)(T|t)(O|o)(P|p)_"
273 token save_heading: r"(S|s)(A|a)(V|v)(E|e)_[][!%&()*+,./:<=>?@0-9A-Za-z\\\\^`{}|~\"#$';_-]+"
274 token save_end: "(S|s)(A|a)(V|v)(E|e)_"
275 token data_name: r"_[][!%&()*+,./:<=>?@0-9A-Za-z\\\\^`{}|~\"#$';_-]+" #_followed by stuff
276 token data_heading: r"(D|d)(A|a)(T|t)(A|a)_[][!%&()*+,./:<=>?@0-9A-Za-z\\\\^`{}|~\"#$';_-]+"
277 token start_sc_line: r"(\n|\r\n);([^\n\r])*(\r\n|\r|\n)+"
278 token sc_line_of_text: r"[^;\r\n]([^\r\n])*(\r\n|\r|\n)+"
279 token end_sc_line: ";"
280 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]*)|'(('(?=\S))|([^\n\r\f']))*'+|\"((\"(?=\S))|([^\n\r\"]))*\"+"
281 token END: '$'
282
283 @ The original CIF specification allowed brackets to begin data values, even if not quoted. That is the only difference.
284
285 <<Regular expressions 1.0>>=
286 # first handle whitespace and comments, keeping whitespace
287 # before a semicolon
288 ignore: r"([ \t\n\r](?!;))|[ \t]"
289 ignore: r"(#.*[\n\r](?!;))|(#.*)"
290 # now the tokens
291 token LBLOCK: "(L|l)(O|o)(O|o)(P|p)_" # loop_
292 token GLOBAL: "(G|g)(L|l)(O|o)(B|b)(A|a)(L|l)_"
293 token STOP: "(S|s)(T|t)(O|o)(P|p)_"
294 token save_heading: r"(S|s)(A|a)(V|v)(E|e)_[][!%&()*+,./:<=>?@0-9A-Za-z\\\\^`{}|~\"#$';_-]+"
295 token save_end: "(S|s)(A|a)(V|v)(E|e)_"
296 token data_name: r"_[][!%&()*+,./:<=>?@0-9A-Za-z\\\\^`{}|~\"#$';_-]+" #_followed by stuff
297 token data_heading: r"(D|d)(A|a)(T|t)(A|a)_[][!%&()*+,./:<=>?@0-9A-Za-z\\\\^`{}|~\"#$';_-]+"
298 token start_sc_line: r"(\n|\r\n);([^\n\r])*(\r\n|\r|\n)+"
299 token sc_line_of_text: r"[^;\r\n]([^\r\n])*(\r\n|\r|\n)+"
300 token end_sc_line: ";"
301 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]*)|'(('(?=\S))|([^\n\r\f']))*'+|\"((\"(?=\S))|([^\n\r\"]))*\"+"
302 token END: '$'
303
304 @
305
306 The final returned value is a StarFile, with each key a datablock name.
307 The value attached to each key is an entire dictionary for that block. We
308 bypass the standard __setitem__ methods to gain precision in checking for
309 duplicate blocknames and skipping name checks.
310
311 Note in the following grammar that we have adjusted for some yapps idiosyncracies:
312 in particular, a nested bracket expression needs to be distinguished from the
313 top-level nested bracket expression otherwise the context-sensitive parser
314 will search for all those items which could follow the top level bracket
315 expression in nested expressions. The current version produces slightly
316 incorrect error messages in that any type of close bracket is supposedly
317 OK, even though only a particular type will be accepted.
318
319 We also have to deal with Dimension-type lists, where there may be square brackets
320 as part of the value (e.g. [4[5]]). This requires catching internal square brackets
321 as well. The current grammar specification catches only this case i.e. the first
322 element of the array can be of the form xxx[yyy]. No other elements can have this
323 form, and there can be no trailing characters. This form can be allowed for other
324 elements by trivial expansion of the current description but, until further notice,
325 I do not think it is useful to allow square brackets in list values.
326
327 <<Grammar specification STAR2>>=
328 <<CIF2-STAR2 common grammar>>
329 <<STAR2-specific grammar>>
330
331 <<Grammar specification CIF2>>=
332 <<CIF2-STAR2 common grammar>>
333 <<CIF2-specific grammar>>
334
335 @ CIF2 and STAR2 are almost identical in grammar
336
337 <<CIF2-STAR2 common grammar>>=
338 # now the rules
339
340 rule input@<<prepared>>: ( ((
341 dblock@<<prepared>> {{allblocks = prepared; allblocks.merge_fast(dblock)}}
342 (
343 dblock@<<prepared>> {{allblocks.merge_fast(dblock)}} #
344 )*
345 END
346 )
347 |
348 (
349 END {{allblocks = prepared}}
350 ))) {{allblocks.unlock(); return allblocks}}
351
352 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
353 (
354 dataseq@<<stored_block>> #because merging may have changed the heading
355 |
356 save_frame@<<prepared>> {{thisbc.merge_fast(save_frame,parent=stored_block)}}
357 )*
358 ) {{stored_block.setmaxnamelength(stored_block.maxnamelength);return (monitor('dblock',thisbc))}} # but may be empty
359
360 rule dataseq@<<starblock>>: data@<<starblock>>
361 (
362 data@<<starblock>>
363 )*
364
365 rule data@<<currentblock>>: top_loop {{makeloop(currentblock,top_loop)}}
366 |
367 datakvpair {{currentblock.AddItem(datakvpair[0],datakvpair[1],precheck=True)}} #kv pair
368
369 rule datakvpair: data_name data_value {{return [data_name,data_value]}} # name-value
370
371 rule data_value: (data_value_1 {{thisval = data_value_1}}
372 |
373 delimited_data_value {{thisval = delimited_data_value}}
374 |
375 sc_lines_of_text {{thisval = stripextras(sc_lines_of_text)}}
376 |
377 bracket_expression {{thisval = bracket_expression}}
378 ) {{return monitor('data_value',thisval)}}
379
380 rule delimited_data_value: (triple_quote_data_value {{thisval = striptriple(triple_quote_data_value)}}
381 |
382 single_quote_data_value {{thisval = stripstring(single_quote_data_value)}}
383 ) {{return thisval}}
384
385 rule sc_lines_of_text: start_sc_line {{lines = StringIO();lines.write(start_sc_line)}}
386 (
387 sc_line_of_text {{lines.write(sc_line_of_text)}}
388 )*
389 end_sc_line {{lines.write(end_sc_line);return monitor('sc_line_of_text',lines.getvalue())}}
390
391 rule bracket_expression: square_bracket_expr {{return square_bracket_expr}}
392 |
393 curly_bracket_expr {{return curly_bracket_expr}}
394
395
396 # due to the inability of the parser to backtrack, we contruct our loops in helper functions,
397 # and simply collect data during parsing proper.
398
399 rule top_loop: LBLOCK loopfield loopvalues {{return loopfield,loopvalues}}
400
401 # OK: a loopfield is either a sequence of datanames
402
403 rule loopfield: ( {{loop_seq=[] }}
404 (
405 ( data_name ) {{loop_seq.append(data_name)}}
406 )*
407 ) {{return loop_seq}} # sequence of data names
408
409
410 rule loopvalues: (
411 (data_value ) {{dataloop=[data_value]}}
412 (
413 (data_value ) {{dataloop.append(monitor('loopval',data_value))}}
414 )*
415 ) {{return dataloop}}
416
417 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] }}
418 (
419 dataseq@<<savebc[savehead]>>
420 |
421 save_frame@<<prepared>> {{savebc.merge_fast(save_frame,parent=stored_block)}}
422 )*
423 save_end {{return monitor('save_frame',savebc)}}
424
425 @ STAR2 specifies nested save frames and comma-separated list and table elements,
426 whereas CIF2 has space-separated elements.
427
428 <<STAR2-specific grammar>>=
429 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] }}
430 (
431 dataseq@<<savebc[savehead]>>
432 |
433 save_frame@<<prepared>> {{savebc.merge_fast(save_frame,parent=stored_block)}}
434 )*
435 save_end {{return monitor('save_frame',savebc)}}
436
437 rule square_bracket_expr: o_s_b {{this_list = []}}
438 ( data_value {{this_list.append(data_value)}}
439 ( ","
440 data_value {{this_list.append(data_value)}}
441 ) *
442 ) *
443 c_s_b {{return StarList(this_list)}}
444
445 rule curly_bracket_expr: ( o_c_b {{table_as_list = []}}
446 ( delimited_data_value {{table_as_list = [delimited_data_value]}}
447 ":"
448 data_value {{table_as_list.append(data_value)}}
449 ( ","
450 delimited_data_value {{table_as_list.append(delimited_data_value)}}
451 ":"
452 data_value {{table_as_list.append(data_value)}}
453 ) *
454 ) *
455 c_c_b ) {{return StarDict(pairwise(table_as_list))}}
456
457
458
459 <<CIF2-specific grammar>>=
460 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] }}
461 (
462 dataseq@<<savebc[savehead]>>
463 )*
464 save_end {{return monitor('save_frame',savebc)}}
465
466
467 rule square_bracket_expr: o_s_b {{this_list = []}}
468 ( data_value {{this_list.append(data_value)}}
469 (
470 data_value {{this_list.append(data_value)}}
471 ) *
472 ) *
473 c_s_b {{return StarList(this_list)}}
474
475 rule curly_bracket_expr: ( o_c_b {{table_as_list = []}}
476 ( delimited_data_value {{table_as_list = [delimited_data_value]}}
477 ":"
478 data_value {{table_as_list.append(data_value)}}
479 (
480 delimited_data_value {{table_as_list.append(delimited_data_value)}}
481 ":"
482 data_value {{table_as_list.append(data_value)}}
483 ) *
484 ) *
485 c_c_b ) {{return StarDict(pairwise(table_as_list))}}
486
487
488
489 @ The CIF 1.1 grammar specification does not include bracket expressions, but does exclude brackets from
490 beginning unquoted data values. We pass through the argument [[prepared]] so we can deal with non-standard
491 dictionary files that contain duplicate datablocks.
492
493 <<Grammar specification 1.1>>=
494 # now the rules
495
496 rule input@<<prepared>>: ( ((
497 dblock@<<prepared>> {{allblocks = prepared;allblocks.merge_fast(dblock)}}
498 (
499 dblock@<<prepared>> {{allblocks.merge_fast(dblock)}} #
500 )*
501 END
502 )
503 |
504 (
505 END {{allblocks = prepared}}
506 ))) {{allblocks.unlock();return allblocks}}
507
508 rule dblock@<<prepared>>: ( data_heading {{heading = data_heading[5:];thisbc=StarFile(characterset='unicode',standard=prepared.standard);newname = thisbc.NewBlock(heading,prepared.blocktype(overwrite=False));act_block=thisbc[newname]}}# a data heading
509 (
510 dataseq@<<thisbc[heading]>>
511 |
512 save_frame@<<prepared>> {{thisbc.merge_fast(save_frame,parent=act_block)}}
513 )*
514 # A trick to force rechecking of all datanames, which was skipped by the precheck = True option below
515 ) {{thisbc[heading].setmaxnamelength(thisbc[heading].maxnamelength);return (monitor('dblock',thisbc))}} # but may be empty
516
517 rule dataseq@<<starblock>>: data@<<starblock>>
518 (
519 data@<<starblock>>
520 )*
521
522 rule data@<<currentblock>>: top_loop {{makeloop(currentblock,top_loop)}}
523 |
524 datakvpair {{currentblock.AddItem(datakvpair[0],datakvpair[1],precheck=True)}} #kv pair
525
526 rule datakvpair: data_name data_value {{return [data_name,data_value]}} # name-value
527
528 rule data_value: (data_value_1 {{thisval = stripstring(data_value_1)}}
529 |
530 sc_lines_of_text {{thisval = stripextras(sc_lines_of_text)}}
531 ) {{return monitor('data_value',thisval)}}
532
533 rule sc_lines_of_text: start_sc_line {{lines = StringIO();lines.write(start_sc_line)}}
534 (
535 sc_line_of_text {{lines.write(sc_line_of_text)}}
536 )*
537 end_sc_line {{lines.write(end_sc_line);return monitor('sc_line_of_text',lines.getvalue())}}
538
539 # due to the inability of the parser to backtrack, we contruct our loops in helper functions,
540 # and simply collect data during parsing proper.
541
542 rule top_loop: LBLOCK loopfield loopvalues {{return loopfield,loopvalues}}
543
544 # OK: a loopfield is either a sequence of dataname*,loopfield with stop
545 # or else dataname,loopfield without stop
546
547 rule loopfield: ( {{toploop=[]}}
548 (
549 ( data_name ) {{toploop.append(data_name)}}
550 )*
551 ) {{return toploop}} # sequence of data names
552
553
554 rule loopvalues: (
555 (data_value ) {{dataloop=[data_value]}}
556 (
557 (data_value ) {{dataloop.append(monitor('loopval',data_value))}}
558 )*
559 ) {{return dataloop}}
560
561 rule save_frame@<<prepared>>: save_heading {{savehead = save_heading[5:];savebc = StarFile();newname=savebc.NewBlock(savehead,prepared.blocktype(overwrite=False));act_block=savebc[newname] }}
562 (
563 dataseq@<<savebc[savehead]>>
564 |
565 save_frame@<<prepared>> {{savebc.merge_fast(save_frame,parent=act_block)}}
566 )*
567 save_end {{return monitor('save_frame',savebc)}}
568
569
570 @ Python 2/3 compatibility. We try to keep the code as
571 portable across the 2-3 divide as we can.
572
573 <<Python2-3 compatibility>>=
574 # To maximize python3/python2 compatibility
575 from __future__ import print_function
576 from __future__ import unicode_literals
577 from __future__ import division
578 from __future__ import absolute_import
579
580 from .StarFile import StarBlock,StarFile,StarList,StarDict
581 from io import StringIO