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