Debian Codegraph @

src/YappsStarParser_1_1.g

raw
1 # <1.1_syntax>=
2 # Python 2/3 compatibility. We try to keep the code as
3 # portable across the 2-3 divide as we can.
4 #
5 #
6 # <Python2-3 compatibility>=
7 # To maximize python3/python2 compatibility
8 from __future__ import print_function
9 from __future__ import unicode_literals
10 from __future__ import division
11 from __future__ import absolute_import
12
13 from .StarFile import StarBlock,StarFile,StarList,StarDict
14 from . import CifSyntaxError
15 from io import StringIO
16 # Helper functions.
17 #
18 # We have a monitor function which we can call to save the last parsed
19 # value (and print, if we are debugging). We also have functions for
20 # stripping off delimiters from strings. Finally, we match up our
21 # loops after reading them in. Note that we have function stripextras,
22 # which is only for semicolon strings, and stripstring, which is for
23 # getting rid of the inverted commas.
24 #
25 #
26 # <Helper functions>=
27 # An alternative specification for the Cif Parser, based on Yapps2
28 # by Amit Patel (http://theory.stanford.edu/~amitp/Yapps)
29 #
30 # helper code: we define our match tokens
31 lastval = ''
32 def monitor(location,value):
33 global lastval
34 #print 'At %s: %s' % (location,repr(value))
35 lastval = repr(value)
36 return value
37
38 # Strip extras gets rid of leading and trailing whitespace, and
39 # semicolons.
40 def stripextras(value):
41 from .StarFile import remove_line_folding, remove_line_prefix
42 # we get rid of semicolons and leading/trailing terminators etc.
43 import re
44 jj = re.compile("[\n\r\f \t\v]*")
45 semis = re.compile("[\n\r\f \t\v]*[\n\r\f]\n*;")
46 cut = semis.match(value)
47 if cut: #we have a semicolon-delimited string
48 nv = value[cut.end():len(value)-2]
49 try:
50 if nv[-1]=='\r': nv = nv[:-1]
51 except IndexError: #empty data value
52 pass
53 # apply protocols
54 nv = remove_line_prefix(nv)
55 nv = remove_line_folding(nv)
56 return nv
57 else:
58 cut = jj.match(value)
59 if cut:
60 return stripstring(value[cut.end():])
61 return value
62
63 # helper function to get rid of inverted commas etc.
64
65 def stripstring(value):
66 if value:
67 if value[0]== '\'' and value[-1]=='\'':
68 return value[1:-1]
69 if value[0]=='"' and value[-1]=='"':
70 return value[1:-1]
71 return value
72
73 # helper function to get rid of triple quotes
74 def striptriple(value):
75 if value:
76 if value[:3] == '"""' and value[-3:] == '"""':
77 return value[3:-3]
78 if value[:3] == "'''" and value[-3:] == "'''":
79 return value[3:-3]
80 return value
81
82 # helper function to populate a StarBlock given a list of names
83 # and values .
84 #
85 # Note that there may be an empty list at the very end of our itemlists,
86 # so we remove that if necessary.
87 #
88
89 def makeloop(target_block,loopdata, context):
90 loop_seq,itemlists = loopdata
91 if itemlists[-1] == []: itemlists.pop(-1)
92 # print('Making loop with %s' % repr(itemlists))
93 step_size = len(loop_seq)
94 for col_no in range(step_size):
95 target_block.AddItem(loop_seq[col_no], itemlists[col_no::step_size],precheck=True)
96 # now construct the loop
97 try:
98 target_block.CreateLoop(loop_seq) #will raise ValueError on problem
99 except ValueError:
100 charpos = context.scanner.get_prev_char_pos()
101 error_string = 'Incorrect number of loop values for loop containing %s' % repr(loop_seq)
102 raise YappsSyntaxError(charpos=charpos, context=context, msg = error_string)
103
104 # return an object with the appropriate amount of nesting
105 def make_empty(nestlevel):
106 gd = []
107 for i in range(1,nestlevel):
108 gd = [gd]
109 return gd
110
111 # this function updates a dictionary first checking for name collisions,
112 # which imply that the CIF is invalid. We need case insensitivity for
113 # names.
114
115 # Unfortunately we cannot check loop item contents against non-loop contents
116 # in a non-messy way during parsing, as we may not have easy access to previous
117 # key value pairs in the context of our call (unlike our built-in access to all
118 # previous loops).
119 # For this reason, we don't waste time checking looped items against non-looped
120 # names during parsing of a data block. This would only match a subset of the
121 # final items. We do check against ordinary items, however.
122 #
123 # Note the following situations:
124 # (1) new_dict is empty -> we have just added a loop; do no checking
125 # (2) new_dict is not empty -> we have some new key-value pairs
126 #
127 def cif_update(old_dict,new_dict,loops):
128 old_keys = map(lambda a:a.lower(),old_dict.keys())
129 if new_dict != {}: # otherwise we have a new loop
130 #print 'Comparing %s to %s' % (repr(old_keys),repr(new_dict.keys()))
131 for new_key in new_dict.keys():
132 if new_key.lower() in old_keys:
133 raise CifError("Duplicate dataname or blockname %s in input file" % new_key)
134 old_dict[new_key] = new_dict[new_key]
135 #
136 # this takes two lines, so we couldn't fit it into a one line execution statement...
137 def order_update(order_array,new_name):
138 order_array.append(new_name)
139 return new_name
140
141 # and finally...turn a sequence into a python dict (thanks to Stackoverflow)
142 def pairwise(iterable):
143 try:
144 it = iter(iterable)
145 while 1:
146 yield next(it), next(it)
147 except StopIteration:
148 return
149 %%
150 parser StarParser:
151 # CIF 1.1 does not allow unquoted data values to begin with a bracket character, but does not have bracket expressions
152 # as such.
153 #
154 #
155 # <Regular expressions 1.1>=
156 # first handle whitespace and comments, keeping whitespace
157 # before a semicolon
158 ignore: r"([ \t\n\r](?!;))|[ \t]"
159 ignore: r"(#.*[\n\r](?!;))|(#.*)"
160 # now the tokens
161 token LBLOCK: "(L|l)(O|o)(O|o)(P|p)_" # loop_
162 token GLOBAL: "(G|g)(L|l)(O|o)(B|b)(A|a)(L|l)_"
163 token STOP: "(S|s)(T|t)(O|o)(P|p)_"
164 token save_heading: r"(S|s)(A|a)(V|v)(E|e)_[][!%&()*+,./:<=>?@0-9A-Za-z\\\\^`{}|~\"#$';_-]+"
165 token save_end: "(S|s)(A|a)(V|v)(E|e)_"
166 token data_name: r"_[][!%&()*+,./:<=>?@0-9A-Za-z\\\\^`{}|~\"#$';_-]+" #_followed by stuff
167 token data_heading: r"(D|d)(A|a)(T|t)(A|a)_[][!%&()*+,./:<=>?@0-9A-Za-z\\\\^`{}|~\"#$';_-]+"
168 token start_sc_line: r"(\n|\r\n);([^\n\r])*(\r\n|\r|\n)+"
169 token sc_line_of_text: r"[^;\r\n]([^\r\n])*(\r\n|\r|\n)+"
170 token end_sc_line: ";"
171 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\"]))*\"+"
172 token END: '$'
173
174 # The CIF 1.1 grammar specification does not include bracket expressions, but does exclude brackets from
175 # beginning unquoted data values. We pass through the argument [[prepared]] so we can deal with non-standard
176 # dictionary files that contain duplicate datablocks.
177 #
178 #
179 # <Grammar specification 1.1>=
180 # now the rules
181
182 rule input<<prepared>>: ( ((
183 dblock<<prepared>> {{allblocks = prepared;allblocks.merge_fast(dblock)}}
184 (
185 dblock<<prepared>> {{allblocks.merge_fast(dblock)}} #
186 )*
187 END
188 )
189 |
190 (
191 END {{allblocks = prepared}}
192 ))) {{allblocks.unlock();return allblocks}}
193
194 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
195 (
196 dataseq<<thisbc[heading]>>
197 |
198 save_frame<<prepared>> {{thisbc.merge_fast(save_frame,parent=act_block)}}
199 )*
200 # A trick to force rechecking of all datanames, which was skipped by the precheck = True option below
201 ) {{thisbc[heading].setmaxnamelength(thisbc[heading].maxnamelength);return (monitor('dblock',thisbc))}} # but may be empty
202
203 rule dataseq<<starblock>>: data<<starblock>>
204 (
205 data<<starblock>>
206 )*
207
208 rule data<<currentblock>>: top_loop {{makeloop(currentblock,top_loop,_context)}}
209 |
210 datakvpair {{currentblock.AddItem(datakvpair[0],datakvpair[1],precheck=True)}} #kv pair
211
212 rule datakvpair: data_name data_value {{return [data_name,data_value]}} # name-value
213
214 rule data_value: (data_value_1 {{thisval = stripstring(data_value_1)}}
215 |
216 sc_lines_of_text {{thisval = stripextras(sc_lines_of_text)}}
217 ) {{return monitor('data_value',thisval)}}
218
219 rule sc_lines_of_text: start_sc_line {{lines = StringIO();lines.write(start_sc_line)}}
220 (
221 sc_line_of_text {{lines.write(sc_line_of_text)}}
222 )*
223 end_sc_line {{lines.write(end_sc_line);return monitor('sc_line_of_text',lines.getvalue())}}
224
225 # due to the inability of the parser to backtrack, we contruct our loops in helper functions,
226 # and simply collect data during parsing proper.
227
228 rule top_loop: LBLOCK loopfield loopvalues {{return loopfield,loopvalues}}
229
230 # OK: a loopfield is either a sequence of dataname*,loopfield with stop
231 # or else dataname,loopfield without stop
232
233 rule loopfield: ( {{toploop=[]}}
234 (
235 ( data_name ) {{toploop.append(data_name)}}
236 )*
237 ) {{return toploop}} # sequence of data names
238
239
240 rule loopvalues: (
241 (data_value ) {{dataloop=[data_value]}}
242 (
243 (data_value ) {{dataloop.append(monitor('loopval',data_value))}}
244 )*
245 ) {{return dataloop}}
246
247 rule save_frame<<prepared>>: save_heading {{savehead = save_heading[5:];savebc = StarFile();newname=savebc.NewBlock(savehead,prepared.blocktype(overwrite=False));act_block=savebc[newname] }}
248 (
249 dataseq<<savebc[savehead]>>
250 |
251 save_frame<<prepared>> {{savebc.merge_fast(save_frame,parent=act_block)}}
252 )*
253 save_end {{return monitor('save_frame',savebc)}}
254
255
256 %%