Project

General

Profile

1
# XPath parsing
2

    
3
import copy
4
import warnings
5

    
6
from Parser import Parser
7
import util
8
import xml_dom
9

    
10
##### Path elements
11

    
12
class XpathElem:
13
    def __init__(self, name='', value=None, is_attr=False):
14
        self.name = name
15
        self.value = value
16
        self.is_attr = is_attr
17
        self.is_positive = True
18
        self.is_lookup_only = False
19
        self.is_ptr = False
20
        self.keys = []
21
        self.attrs = []
22
        self.other_branches = [] # temp implementation for split paths
23
    
24
    def __repr__(self):
25
        str_ = ''
26
        if not self.is_positive: str_ += '!'
27
        if self.is_attr: str_ += '@'
28
        if self.name == '': str_ += '""'
29
        else: str_ += self.name
30
        if self.is_lookup_only: str_ += '?'
31
        if self.keys != []: str_ += repr(self.keys)
32
        if self.attrs != []: str_ += ':'+repr(self.attrs)
33
        if self.is_ptr: str_ += '->'
34
        if self.other_branches != []: str_ += '{'+repr(self.other_branches)+'}'
35
        if self.value != None: str_ += '='+repr(self.value)
36
        return str_
37
    
38
    def __eq__(self, other): return self.__dict__ == other.__dict__
39

    
40
empty_elem = XpathElem()
41

    
42
def elem_is_empty(elem): return elem == empty_elem
43

    
44
def is_self(elem): return elem.name == '' or elem.name == '.'
45

    
46
def is_parent(elem): return elem.name == '..'
47

    
48
##### Paths
49

    
50
def path_is_empty(path): return path == [] or path == [empty_elem]
51

    
52
def is_positive(path): return path[0].is_positive
53

    
54
def is_rooted(path): return elem_is_empty(path[0])
55

    
56
def value(path): return path[-1].value
57

    
58
def set_value(path, value):
59
    '''Caller must make a shallow copy of the path to prevent modifications from
60
    propagating to other copies of the path (a deep copy is not needed)'''
61
    path[-1] = copy.copy(path[-1]) # don't modify other copies of the path
62
    path[-1].value = value
63

    
64
def append(path, subpath, i=0):
65
    '''Recursively appends subpath to every leaf of a path tree'''
66
    if i >= len(path): path += subpath
67
    else:
68
        append(path, subpath, i+1)
69
        for branch in path[i].other_branches: append(branch, subpath)
70

    
71
def backward_id(elem):
72
    if len(elem.keys) >= 1 and value(elem.keys[0]) == None: return elem.keys[0]
73
    else: return None
74

    
75
instance_level = 1 # root's grandchildren
76

    
77
def obj(path):
78
    obj_path = copy.deepcopy(path[:instance_level+1])
79
    obj_path[-1].is_ptr = False # prevent pointer w/o target
80
    return obj_path
81

    
82
def set_id(path, id_, has_types=True):
83
    '''Caller must make a shallow copy of the path to prevent modifications from
84
    propagating to other copies of the path (a deep copy is not needed).
85
    @return The path to the ID attr, which can be used to change the ID
86
    '''
87
    if has_types: id_level = instance_level
88
    else: id_level = 0 # root's children
89
    if is_self(path[0]): id_level += 1 # explicit root element
90
    
91
    id_elem = path[id_level] = copy.copy(path[id_level])
92
        # don't modify other copies of the path
93
    id_elem.keys = id_elem.keys[:] # don't modify other copies of the elem
94
    id_attr = XpathElem('id', None, is_attr=True)
95
    
96
    # Save the path to the ID attr
97
    id_path = path[:id_level] # the path before the ID level
98
    id_path.append(copy.deepcopy(id_elem)) # this path's id_elem is independent
99
    id_path.append(copy.copy(id_attr)) # this path's id_attr is independent
100
    
101
    # Set the ID attr on the provided XPath
102
    id_attr.value = id_
103
    id_elem.keys.append([id_attr])
104
    
105
    return id_path
106

    
107
def is_id(path): return path[0].is_attr and path[0].name == 'id'
108

    
109
def is_instance(elem): return elem.keys != [] and is_id(elem.keys[0])
110

    
111
##### Parsing
112

    
113
import xpath_func
114

    
115
def expand_abbr(name, repl):
116
    before, abbr, after = name.partition('*')
117
    if abbr != '': name = before+repl+after
118
    return name
119

    
120
_cache = {}
121

    
122
def parse(str_):
123
    try: return _cache[str_]
124
    except KeyError: pass
125
    
126
    parser = Parser(str_)
127
    
128
    def _path():
129
        is_positive = not parser.str_('!')
130
        
131
        tree = []
132
        while True:
133
            # Split path
134
            if parser.str_('{'):
135
                try: last = tree[-1]
136
                except IndexError: parser.syntax_err('./{')
137
                last.other_branches = _paths()
138
                tree += last.other_branches.pop(0) # use first path for now
139
                parser.str_('}', required=True)
140
                if parser.str_('/'): append(tree, _path()) # subpath after {}
141
                break # anything after split path has already been parsed
142
            
143
            elem = XpathElem(is_attr=parser.str_('@'), name=_value())
144
            
145
            elem.is_lookup_only = parser.str_('?')
146
            
147
            # Keys used to match nodes
148
            if parser.str_('['):
149
                elem.keys = _paths()
150
                parser.str_(']', required=True)
151
            
152
            # Attrs created when no matching node exists
153
            if parser.str_(':'):
154
                parser.str_('[', required=True)
155
                elem.attrs = _paths()
156
                parser.str_(']', required=True)
157
            
158
            elem.is_ptr = parser.str_('->')
159
            tree.append(elem)
160
            
161
            # Lookahead assertion
162
            if parser.str_('('):
163
                parser.str_('/', required=True) # next / is inside ()
164
                path = _path()
165
                parser.str_(')', required=True)
166
                elem.keys.append(path)
167
                tree += path
168
            
169
            if not parser.str_('/'): break
170
        
171
        tree[0].is_positive = is_positive
172
        
173
        # Value
174
        if parser.str_('='):
175
            if parser.str_('$'): # reference (different from a pointer)
176
                value = _path()
177
            else: value = _value() # literal value
178
            set_value(tree, value)
179
        
180
        # Expand * abbrs
181
        for i in reversed(xrange(len(tree))):
182
            elem = tree[i]
183
            if elem.is_ptr: offset = 2
184
            else: offset = 1
185
            try: repl = tree[i+offset].name
186
            except IndexError: pass # no replacement elem
187
            else: elem.name = expand_abbr(elem.name, repl)
188
        
189
        return tree
190
    
191
    def _value():
192
        if parser.str_('"'):
193
            value = parser.re(r'[^"]*')
194
            parser.str_('"', required=True)
195
        else: value = parser.re(r'(?:(?:\w+:)*[\w.*]+)?')
196
        return value
197
    
198
    def _paths():
199
        paths = []
200
        path = _path()
201
        if not path_is_empty(path): # not empty list
202
            paths.append(path)
203
            while parser.str_(','): paths.append(_path())
204
            if path_is_empty(paths[-1]): paths.pop() # remove trailing ","
205
        return paths
206
    
207
    path = _path()
208
    parser.end()
209
    path = xpath_func.process(path)
210
    _cache[str_] = path
211
    return path
212

    
213
##### Querying/creating XML trees
214

    
215
def get(root, xpath, create=False, last_only=None, limit=1, allow_rooted=True):
216
    '''Warning: The last_only optimization may put data that should be together
217
    into separate nodes'''
218
    if last_only == None: last_only = create
219
    if limit == None or limit > 1: last_only = False
220
    if util.is_str(xpath): xpath = parse(xpath)
221
    
222
    # Handle edge cases
223
    if xpath == []: return [root]
224
    if create and not is_positive(xpath): return []
225
    
226
    # Define vars
227
    doc = root.ownerDocument
228
    if allow_rooted and is_rooted(xpath): root = doc.documentElement
229
    elem = xpath[0]
230
    
231
    # Find possible matches
232
    children = []
233
    if elem.is_attr:
234
        child = root.getAttributeNode(elem.name)
235
        if child != None: children = [child]
236
    elif is_self(elem): children = [root]
237
    elif is_parent(elem):
238
        parent = xml_dom.parent(root)
239
        if parent == None: return [] # don't try to create doc root's parent
240
        root = parent
241
        children = [root]
242
    else:
243
        children = xml_dom.by_tag_name(root, elem.name,
244
            last_only=(last_only and (elem.keys == [] or is_instance(elem))),
245
            ignore_namespace=False) # later set ignore_namespace to True?
246
    
247
    # Retrieve elem value
248
    value_ = elem.value
249
    if util.is_list(value_): # reference (different from a pointer)
250
        targets = get(root, value_)
251
        try: target = targets[0]
252
        except IndexError:
253
            warnings.warn(UserWarning('XPath reference target missing: '
254
                +str(value_)+'\nXPath: '+str(xpath)))
255
            value_ = None
256
        else: value_ = xml_dom.value(target)
257
    
258
    # Check each match
259
    nodes = []
260
    for child in children:
261
        is_match = value_ == None or xml_dom.value(child) == value_
262
        for attr in elem.keys:
263
            if not is_match: break
264
            is_match = ((get(child, attr, False, last_only,
265
                allow_rooted=False) != []) == is_positive(attr))
266
        if is_match:
267
            nodes.append(child)
268
            if limit != None and len(nodes) >= limit: break
269
    
270
    # Create node
271
    if nodes == []:
272
        if not create or elem.is_lookup_only: return []
273
        if elem.is_attr:
274
            root.setAttribute(elem.name, '')
275
            node = root.getAttributeNode(elem.name)
276
        elif util.list_eq_is(children, [root]): node = root
277
        else: node = root.appendChild(doc.createElement(elem.name))
278
        if value_ != None: xml_dom.set_value(node, value_)
279
        nodes.append(node)
280
    
281
    path_value = value(xpath)
282
    xpath = xpath[1:] # rest of XPath
283
    
284
    next = []
285
    for node in nodes:
286
        # Create attrs
287
        if create:
288
            for attr in elem.keys + elem.attrs:
289
                get(node, attr, create, last_only, allow_rooted=False)
290
        
291
        # Follow pointer
292
        if elem.is_ptr:
293
            root = doc.documentElement
294
            xpath = copy.deepcopy(xpath)
295
            id_path = backward_id(xpath[instance_level])
296
            if id_path != None: # backward (child-to-parent) pointer with ID key
297
                id_path[0].name = expand_abbr(id_path[0].name, node.tagName)
298
                set_value(id_path, xml_dom.get_id(node)) # modify xpath's id key
299
            else: # forward (parent-to-child) pointer
300
                id_ = xml_dom.value(node)
301
                obj_xpath = obj(xpath) # target object
302
                if id_ == None or get(root, obj_xpath, False, True) == []:
303
                    # no target or target keys don't match
304
                    if not create: continue
305
                    
306
                    # Use last target object's ID + 1
307
                    obj_xpath[-1].keys = [] # just get by tag name
308
                    last = get(root, obj_xpath, False, True)
309
                    if last != []: id_ = str(int(util.coalesce(
310
                        xml_dom.get_id(last[0]), 0)) + 1)
311
                    else: id_ = '0'
312
                    
313
                    # Will append if target keys didn't match.
314
                    # Use lookahead assertion to avoid this.
315
                    xml_dom.set_value(node, id_)
316
                else: last_only = False
317
                set_id(xpath, id_)
318
        else: root = node
319
        next += get(root, xpath, create, last_only, limit, allow_rooted=False)
320
        
321
        for branch in elem.other_branches:
322
            branch = branch[:] # don't modify input!
323
            set_value(branch, path_value)
324
            next += get(node, branch, create, last_only, limit,
325
                allow_rooted=False)
326
    
327
    return next
328

    
329
def get_1(*args, **kw_args):
330
    '''Runs get() and returns the first result'''
331
    return util.list_get(get(*args, **kw_args), 0)
332

    
333
def get_value(*args, **kw_args):
334
    '''Runs get_1() and returns the value of any result node'''
335
    return util.do_ignore_none(xml_dom.value, get_1(*args, **kw_args))
336

    
337
def put_obj(root, xpath, id_, has_types, value=None):
338
    if util.is_str(xpath): xpath = parse(xpath)
339
    
340
    xpath = xpath[:] # don't modify input!
341
    set_id(xpath, id_, has_types)
342
    if value != None: set_value(xpath, value)
343
    return get(root, xpath, True)
344

    
345
def path2xml(xpath, first_branch=True):
346
    root = xml_dom.create_doc().documentElement
347
    get(root, xpath, True)
348
    return root
349

    
350
def xml_set_id(root, id_): xml_dom.set_id(root.firstChild, id_)
(32-32/33)