| 1 |
# The STAR2 syntax |
| 2 |
# |
| 3 |
# <STAR2_syntax>= |
| 4 |
# Python 2/3 compatibility. We try to keep the code as |
| 5 |
# portable across the 2-3 divide as we can. |
| 6 |
# |
| 7 |
# |
| 8 |
# <Python2-3 compatibility>= |
| 9 |
# To maximize python3/python2 compatibility |
| 10 |
from __future__ import print_function |
| 11 |
from __future__ import unicode_literals |
| 12 |
from __future__ import division |
| 13 |
from __future__ import absolute_import |
| 14 |
|
| 15 |
from .StarFile import StarBlock,StarFile,StarList,StarDict |
| 16 |
from . import CifSyntaxError |
| 17 |
from io import StringIO |
| 18 |
# Helper functions. |
| 19 |
# |
| 20 |
# We have a monitor function which we can call to save the last parsed |
| 21 |
# value (and print, if we are debugging). We also have functions for |
| 22 |
# stripping off delimiters from strings. Finally, we match up our |
| 23 |
# loops after reading them in. Note that we have function stripextras, |
| 24 |
# which is only for semicolon strings, and stripstring, which is for |
| 25 |
# getting rid of the inverted commas. |
| 26 |
# |
| 27 |
# |
| 28 |
# <Helper functions>= |
| 29 |
# An alternative specification for the Cif Parser, based on Yapps2 |
| 30 |
# by Amit Patel (http://theory.stanford.edu/~amitp/Yapps) |
| 31 |
# |
| 32 |
# helper code: we define our match tokens |
| 33 |
lastval = '' |
| 34 |
def monitor(location,value): |
| 35 |
global lastval |
| 36 |
#print 'At %s: %s' % (location,repr(value)) |
| 37 |
lastval = repr(value) |
| 38 |
return value |
| 39 |
|
| 40 |
# Strip extras gets rid of leading and trailing whitespace, and |
| 41 |
# semicolons. |
| 42 |
def stripextras(value): |
| 43 |
from .StarFile import remove_line_folding, remove_line_prefix |
| 44 |
# we get rid of semicolons and leading/trailing terminators etc. |
| 45 |
import re |
| 46 |
jj = re.compile("[\n\r\f \t\v]*") |
| 47 |
semis = re.compile("[\n\r\f \t\v]*[\n\r\f]\n*;") |
| 48 |
cut = semis.match(value) |
| 49 |
if cut: #we have a semicolon-delimited string |
| 50 |
nv = value[cut.end():len(value)-2] |
| 51 |
try: |
| 52 |
if nv[-1]=='\r': nv = nv[:-1] |
| 53 |
except IndexError: #empty data value |
| 54 |
pass |
| 55 |
# apply protocols |
| 56 |
nv = remove_line_prefix(nv) |
| 57 |
nv = remove_line_folding(nv) |
| 58 |
return nv |
| 59 |
else: |
| 60 |
cut = jj.match(value) |
| 61 |
if cut: |
| 62 |
return stripstring(value[cut.end():]) |
| 63 |
return value |
| 64 |
|
| 65 |
# helper function to get rid of inverted commas etc. |
| 66 |
|
| 67 |
def stripstring(value): |
| 68 |
if value: |
| 69 |
if value[0]== '\'' and value[-1]=='\'': |
| 70 |
return value[1:-1] |
| 71 |
if value[0]=='"' and value[-1]=='"': |
| 72 |
return value[1:-1] |
| 73 |
return value |
| 74 |
|
| 75 |
# helper function to get rid of triple quotes |
| 76 |
def striptriple(value): |
| 77 |
if value: |
| 78 |
if value[:3] == '"""' and value[-3:] == '"""': |
| 79 |
return value[3:-3] |
| 80 |
if value[:3] == "'''" and value[-3:] == "'''": |
| 81 |
return value[3:-3] |
| 82 |
return value |
| 83 |
|
| 84 |
# helper function to populate a StarBlock given a list of names |
| 85 |
# and values . |
| 86 |
# |
| 87 |
# Note that there may be an empty list at the very end of our itemlists, |
| 88 |
# so we remove that if necessary. |
| 89 |
# |
| 90 |
|
| 91 |
def makeloop(target_block,loopdata, context): |
| 92 |
loop_seq,itemlists = loopdata |
| 93 |
if itemlists[-1] == []: itemlists.pop(-1) |
| 94 |
# print('Making loop with %s' % repr(itemlists)) |
| 95 |
step_size = len(loop_seq) |
| 96 |
for col_no in range(step_size): |
| 97 |
target_block.AddItem(loop_seq[col_no], itemlists[col_no::step_size],precheck=True) |
| 98 |
# now construct the loop |
| 99 |
try: |
| 100 |
target_block.CreateLoop(loop_seq) #will raise ValueError on problem |
| 101 |
except ValueError: |
| 102 |
charpos = context.scanner.get_prev_char_pos() |
| 103 |
error_string = 'Incorrect number of loop values for loop containing %s' % repr(loop_seq) |
| 104 |
raise CifSyntaxError(charpos=charpos, context=context, msg = error_string) |
| 105 |
|
| 106 |
# return an object with the appropriate amount of nesting |
| 107 |
def make_empty(nestlevel): |
| 108 |
gd = [] |
| 109 |
for i in range(1,nestlevel): |
| 110 |
gd = [gd] |
| 111 |
return gd |
| 112 |
|
| 113 |
# this function updates a dictionary first checking for name collisions, |
| 114 |
# which imply that the CIF is invalid. We need case insensitivity for |
| 115 |
# names. |
| 116 |
|
| 117 |
# Unfortunately we cannot check loop item contents against non-loop contents |
| 118 |
# in a non-messy way during parsing, as we may not have easy access to previous |
| 119 |
# key value pairs in the context of our call (unlike our built-in access to all |
| 120 |
# previous loops). |
| 121 |
# For this reason, we don't waste time checking looped items against non-looped |
| 122 |
# names during parsing of a data block. This would only match a subset of the |
| 123 |
# final items. We do check against ordinary items, however. |
| 124 |
# |
| 125 |
# Note the following situations: |
| 126 |
# (1) new_dict is empty -> we have just added a loop; do no checking |
| 127 |
# (2) new_dict is not empty -> we have some new key-value pairs |
| 128 |
# |
| 129 |
def cif_update(old_dict,new_dict,loops): |
| 130 |
old_keys = map(lambda a:a.lower(),old_dict.keys()) |
| 131 |
if new_dict != {}: # otherwise we have a new loop |
| 132 |
#print 'Comparing %s to %s' % (repr(old_keys),repr(new_dict.keys())) |
| 133 |
for new_key in new_dict.keys(): |
| 134 |
if new_key.lower() in old_keys: |
| 135 |
raise CifError("Duplicate dataname or blockname %s in input file" % new_key) |
| 136 |
old_dict[new_key] = new_dict[new_key] |
| 137 |
# |
| 138 |
# this takes two lines, so we couldn't fit it into a one line execution statement... |
| 139 |
def order_update(order_array,new_name): |
| 140 |
order_array.append(new_name) |
| 141 |
return new_name |
| 142 |
|
| 143 |
# and finally...turn a sequence into a python dict (thanks to Stackoverflow) |
| 144 |
def pairwise(iterable): |
| 145 |
try: |
| 146 |
it = iter(iterable) |
| 147 |
while 1: |
| 148 |
yield next(it), next(it) |
| 149 |
except StopIteration: |
| 150 |
return |
| 151 |
%% |
| 152 |
parser StarParser: |
| 153 |
# We can simplify the BNC specification of Nick Spadaccini. First of |
| 154 |
# all, we do not have to have type I and type II strings, which are |
| 155 |
# distinguished by the presence or absence of a line feed directly |
| 156 |
# preceding them and thus by being allowed a semicolon at the front or |
| 157 |
# not. We take care of this by treating as whitespace all terminators |
| 158 |
# except for those with a following semicolon, so that a |
| 159 |
# carriage-return-semicolon sequence matches the start_sc_line uniquely. |
| 160 |
# |
| 161 |
# We include reserved words and save frames. The other reserved words |
| 162 |
# have no rules defined, so will flag a syntax error. However, as yapps |
| 163 |
# is a context-sensitive parser, it will by default make any word found |
| 164 |
# starting with our reserved words into a data value if it occurs in the |
| 165 |
# expected position, so we explicity exclude stuff starting with our |
| 166 |
# words in the definition of data_value_1. |
| 167 |
# |
| 168 |
# The syntax rules below correspond to the current STAR2 paper. Commas |
| 169 |
# are not allowed in non-delimited data values so that they can be used |
| 170 |
# to separate list items. |
| 171 |
# |
| 172 |
# Note that we do not recognise characters outside the Unicode basic |
| 173 |
# multilingual plane in datanames, data headings and save headings. |
| 174 |
# This is due to a limitation of Python 2 unicode strings and will be |
| 175 |
# removed when PyCIFRW is ported to Python 3. |
| 176 |
# |
| 177 |
# |
| 178 |
# <Regular expressions STAR2>= |
| 179 |
# <STAR2-CIF2 common regular expressions block 1>= |
| 180 |
# first handle whitespace and comments, keeping whitespace |
| 181 |
# before a semicolon |
| 182 |
ignore: r"([ \t\n\r](?!;))|[ \t]" |
| 183 |
ignore: r"(#.*[\n\r](?!;))|(#.*)" |
| 184 |
# now the tokens |
| 185 |
token LBLOCK: "(L|l)(O|o)(O|o)(P|p)_" # loop_ |
| 186 |
token GLOBAL: "(G|g)(L|l)(O|o)(B|b)(A|a)(L|l)_" |
| 187 |
token STOP: "(S|s)(T|t)(O|o)(P|p)_" |
| 188 |
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-]+" |
| 189 |
token save_end: "(S|s)(A|a)(V|v)(E|e)_" |
| 190 |
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 |
| 191 |
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-]+" |
| 192 |
token start_sc_line: "(\n|\r\n);([^\n\r])*(\r\n|\r|\n)+" |
| 193 |
token sc_line_of_text: "[^;\r\n]([^\r\n])*(\r\n|\r|\n)+" |
| 194 |
token end_sc_line: ";" |
| 195 |
token c_c_b: "}" |
| 196 |
token o_c_b: "{" |
| 197 |
token c_s_b: "]" |
| 198 |
token o_s_b: r"\[" |
| 199 |
#token dat_val_nocomma_nosq: "([^\s\"#$,'_\(\{\[\]][^\s,\[\]]*)|'(('(?![\s,]))|([^\n\r\f']))*'+|\"((\"(?![\s,]))|([^\n\r\"]))*\"+" |
| 200 |
token dat_val_internal_sq: r"\[([^\s[\]]*)\]" |
| 201 |
# token dat_val_nocomma_nocurl: "([^\s\"#$,'_\(\{\[\]][^\s,}]*)|'(('(?![\s,]))|([^\n\r\f']))*'+|\"([^\n\r\"])*\"+" |
| 202 |
# For tests of new DDLm syntax - no quotes or apostrophes in strings, no commas, braces or square brackets in undelimited data values |
| 203 |
# This token for triple-quote delimited strings must come before single-quote delimited strings to avoid the opening quotes being |
| 204 |
# interpreted as a single-quote delimited string |
| 205 |
token triple_quote_data_value: "(?s)'''.*?'''|\"\"\".*?\"\"\"" |
| 206 |
token single_quote_data_value: r"'([^\n\r\f'])*'+|\"([^\n\r\"])*\"+" |
| 207 |
|
| 208 |
# Currently just a single line but we allow a whole block just in case. |
| 209 |
# |
| 210 |
# |
| 211 |
# <STAR2-CIF2 common regular expressions block 2>= |
| 212 |
token END: '$' |
| 213 |
|
| 214 |
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,{}[\]]*)" |
| 215 |
|
| 216 |
# The final returned value is a StarFile, with each key a datablock name. |
| 217 |
# The value attached to each key is an entire dictionary for that block. We |
| 218 |
# bypass the standard __setitem__ methods to gain precision in checking for |
| 219 |
# duplicate blocknames and skipping name checks. |
| 220 |
# |
| 221 |
# Note in the following grammar that we have adjusted for some yapps idiosyncracies: |
| 222 |
# in particular, a nested bracket expression needs to be distinguished from the |
| 223 |
# top-level nested bracket expression otherwise the context-sensitive parser |
| 224 |
# will search for all those items which could follow the top level bracket |
| 225 |
# expression in nested expressions. The current version produces slightly |
| 226 |
# incorrect error messages in that any type of close bracket is supposedly |
| 227 |
# OK, even though only a particular type will be accepted. |
| 228 |
# |
| 229 |
# We also have to deal with Dimension-type lists, where there may be square brackets |
| 230 |
# as part of the value (e.g. [4[5]]). This requires catching internal square brackets |
| 231 |
# as well. The current grammar specification catches only this case i.e. the first |
| 232 |
# element of the array can be of the form xxx[yyy]. No other elements can have this |
| 233 |
# form, and there can be no trailing characters. This form can be allowed for other |
| 234 |
# elements by trivial expansion of the current description but, until further notice, |
| 235 |
# I do not think it is useful to allow square brackets in list values. |
| 236 |
# |
| 237 |
# |
| 238 |
# <Grammar specification STAR2>= |
| 239 |
# CIF2 and STAR2 are almost identical in grammar |
| 240 |
# |
| 241 |
# |
| 242 |
# <CIF2-STAR2 common grammar>= |
| 243 |
# now the rules |
| 244 |
|
| 245 |
rule input<<prepared>>: ( (( |
| 246 |
dblock<<prepared>> {{allblocks = prepared; allblocks.merge_fast(dblock)}} |
| 247 |
( |
| 248 |
dblock<<prepared>> {{allblocks.merge_fast(dblock)}} # |
| 249 |
)* |
| 250 |
END |
| 251 |
) |
| 252 |
| |
| 253 |
( |
| 254 |
END {{allblocks = prepared}} |
| 255 |
))) {{allblocks.unlock(); return allblocks}} |
| 256 |
|
| 257 |
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 |
| 258 |
( |
| 259 |
dataseq<<stored_block>> #because merging may have changed the heading |
| 260 |
| |
| 261 |
save_frame<<prepared>> {{thisbc.merge_fast(save_frame,parent=stored_block)}} |
| 262 |
)* |
| 263 |
) {{stored_block.setmaxnamelength(stored_block.maxnamelength);return (monitor('dblock',thisbc))}} # but may be empty |
| 264 |
|
| 265 |
rule dataseq<<starblock>>: data<<starblock>> |
| 266 |
( |
| 267 |
data<<starblock>> |
| 268 |
)* |
| 269 |
|
| 270 |
rule data<<currentblock>>: top_loop {{makeloop(currentblock,top_loop,_context)}} |
| 271 |
| |
| 272 |
datakvpair {{currentblock.AddItem(datakvpair[0],datakvpair[1],precheck=True)}} #kv pair |
| 273 |
|
| 274 |
rule datakvpair: data_name data_value {{return [data_name,data_value]}} # name-value |
| 275 |
|
| 276 |
rule data_value: (data_value_1 {{thisval = data_value_1}} |
| 277 |
| |
| 278 |
delimited_data_value {{thisval = delimited_data_value}} |
| 279 |
| |
| 280 |
sc_lines_of_text {{thisval = stripextras(sc_lines_of_text)}} |
| 281 |
| |
| 282 |
bracket_expression {{thisval = bracket_expression}} |
| 283 |
) {{return monitor('data_value',thisval)}} |
| 284 |
|
| 285 |
rule delimited_data_value: (triple_quote_data_value {{thisval = striptriple(triple_quote_data_value)}} |
| 286 |
| |
| 287 |
single_quote_data_value {{thisval = stripstring(single_quote_data_value)}} |
| 288 |
) {{return thisval}} |
| 289 |
|
| 290 |
rule sc_lines_of_text: start_sc_line {{lines = StringIO();lines.write(start_sc_line)}} |
| 291 |
( |
| 292 |
sc_line_of_text {{lines.write(sc_line_of_text)}} |
| 293 |
)* |
| 294 |
end_sc_line {{lines.write(end_sc_line);return monitor('sc_line_of_text',lines.getvalue())}} |
| 295 |
|
| 296 |
rule bracket_expression: square_bracket_expr {{return square_bracket_expr}} |
| 297 |
| |
| 298 |
curly_bracket_expr {{return curly_bracket_expr}} |
| 299 |
|
| 300 |
|
| 301 |
# due to the inability of the parser to backtrack, we contruct our loops in helper functions, |
| 302 |
# and simply collect data during parsing proper. |
| 303 |
|
| 304 |
rule top_loop: LBLOCK loopfield loopvalues {{return loopfield,loopvalues}} |
| 305 |
|
| 306 |
# OK: a loopfield is either a sequence of datanames |
| 307 |
|
| 308 |
rule loopfield: ( {{loop_seq=[] }} |
| 309 |
( |
| 310 |
( data_name ) {{loop_seq.append(data_name)}} |
| 311 |
)* |
| 312 |
) {{return loop_seq}} # sequence of data names |
| 313 |
|
| 314 |
|
| 315 |
rule loopvalues: ( |
| 316 |
(data_value ) {{dataloop=[data_value]}} |
| 317 |
( |
| 318 |
(data_value ) {{dataloop.append(monitor('loopval',data_value))}} |
| 319 |
)* |
| 320 |
) {{return dataloop}} |
| 321 |
|
| 322 |
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] }} |
| 323 |
( |
| 324 |
dataseq<<savebc[savehead]>> |
| 325 |
| |
| 326 |
save_frame<<prepared>> {{savebc.merge_fast(save_frame,parent=stored_block)}} |
| 327 |
)* |
| 328 |
save_end {{return monitor('save_frame',savebc)}} |
| 329 |
|
| 330 |
# STAR2 specifies nested save frames and comma-separated list and table elements, |
| 331 |
# whereas CIF2 has space-separated elements. |
| 332 |
# |
| 333 |
# |
| 334 |
# <STAR2-specific grammar>= |
| 335 |
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] }} |
| 336 |
( |
| 337 |
dataseq<<savebc[savehead]>> |
| 338 |
| |
| 339 |
save_frame<<prepared>> {{savebc.merge_fast(save_frame,parent=stored_block)}} |
| 340 |
)* |
| 341 |
save_end {{return monitor('save_frame',savebc)}} |
| 342 |
|
| 343 |
rule square_bracket_expr: o_s_b {{this_list = []}} |
| 344 |
( data_value {{this_list.append(data_value)}} |
| 345 |
( "," |
| 346 |
data_value {{this_list.append(data_value)}} |
| 347 |
) * |
| 348 |
) * |
| 349 |
c_s_b {{return StarList(this_list)}} |
| 350 |
|
| 351 |
rule curly_bracket_expr: ( o_c_b {{table_as_list = []}} |
| 352 |
( delimited_data_value {{table_as_list = [delimited_data_value]}} |
| 353 |
":" |
| 354 |
data_value {{table_as_list.append(data_value)}} |
| 355 |
( "," |
| 356 |
delimited_data_value {{table_as_list.append(delimited_data_value)}} |
| 357 |
":" |
| 358 |
data_value {{table_as_list.append(data_value)}} |
| 359 |
) * |
| 360 |
) * |
| 361 |
c_c_b ) {{return StarDict(pairwise(table_as_list))}} |
| 362 |
|
| 363 |
|
| 364 |
|
| 365 |
|
| 366 |
%% |