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
def is_all(elem): return elem.name == '*'
49

    
50
##### Paths
51

    
52
def is_xpath(value):
53
    return isinstance(value, list) and (len(value) == 0
54
        or isinstance(value[0], XpathElem))
55

    
56
def path_is_empty(path): return path == [] or path == [empty_elem]
57

    
58
def is_positive(path): return path[0].is_positive
59

    
60
def is_rooted(path): return elem_is_empty(path[0])
61

    
62
def value(path): return path[-1].value
63

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

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

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

    
81
instance_level = 1 # root's grandchildren
82

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

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

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

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

    
116
##### Parsing
117

    
118
import xpath_func
119

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

    
125
_cache = {}
126

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

    
218
##### Querying/creating XML trees
219

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

    
337
def get_1(*args, **kw_args):
338
    '''Runs get() and returns the first result'''
339
    return util.list_get(get(*args, **kw_args), 0)
340

    
341
def get_value(*args, **kw_args):
342
    '''Runs get_1() and returns the value of any result node'''
343
    return util.do_ignore_none(xml_dom.value, get_1(*args, **kw_args))
344

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

    
354
def path2xml(xpath, first_branch=True):
355
    root = xml_dom.create_doc().documentElement
356
    get(root, xpath, True)
357
    return root.firstChild # skip to tree created inside root
358

    
359
def xml_set_id(root, id_): xml_dom.set_id(root.firstChild, id_)
(38-38/39)