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 = obj(path) # a copy of the path up through the ID level
98
    id_path.append(copy.copy(id_attr)) # this path's id_attr is independent
99
    
100
    # Set the ID attr on the provided XPath
101
    id_attr.value = id_
102
    id_elem.keys.append([id_attr])
103
    
104
    return id_path
105

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

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

    
110
##### Parsing
111

    
112
import xpath_func
113

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

    
119
_cache = {}
120

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

    
212
##### Querying/creating XML trees
213

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

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

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

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

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

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