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 is_xpath(value):
51
    return isinstance(value, list) and (len(value) == 0
52
        or isinstance(value[0], XpathElem))
53

    
54
def path_is_empty(path): return path == [] or path == [empty_elem]
55

    
56
def is_positive(path): return path[0].is_positive
57

    
58
def is_rooted(path): return elem_is_empty(path[0])
59

    
60
def value(path): return path[-1].value
61

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

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

    
75
def backward_id(elem):
76
    if len(elem.keys) >= 1 and value(elem.keys[0]) == None: return elem.keys[0]
77
    else: return None
78

    
79
instance_level = 1 # root's grandchildren
80

    
81
def obj(path):
82
    obj_path = copy.deepcopy(path[:instance_level+1])
83
    obj_path[-1].is_ptr = False # prevent pointer w/o target
84
    return obj_path
85

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

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

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

    
114
##### Parsing
115

    
116
import xpath_func
117

    
118
def expand_abbr(name, repl):
119
    before, abbr, after = name.partition('*')
120
    if abbr != '': name = before+repl+after
121
    return name
122

    
123
_cache = {}
124

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

    
216
##### Querying/creating XML trees
217

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

    
332
def get_1(*args, **kw_args):
333
    '''Runs get() and returns the first result'''
334
    return util.list_get(get(*args, **kw_args), 0)
335

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

    
340
def put_obj(root, xpath, id_, has_types, value=None):
341
    '''@return tuple(inserted_node, id_attr_node)'''
342
    if util.is_str(xpath): xpath = parse(xpath)
343
    
344
    xpath = xpath[:] # don't modify input!
345
    id_path = set_id(xpath, id_, has_types)
346
    if value != None: set_value(xpath, value)
347
    return (get(root, xpath, True), get_1(root, id_path))
348

    
349
def path2xml(xpath, first_branch=True):
350
    root = xml_dom.create_doc().documentElement
351
    get(root, xpath, True)
352
    return root
353

    
354
def xml_set_id(root, id_): xml_dom.set_id(root.firstChild, id_)
(35-35/36)