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
        target = get_1(root, value_)
257
        if target != None: value_ = xml_dom.value(target)
258
        else:
259
            warnings.warn(UserWarning('XPath reference target missing: '
260
                +str(value_)+'\nXPath: '+str(xpath)))
261
            value_ = None
262
    
263
    # Check each match
264
    nodes = []
265
    for child in children:
266
        is_match = value_ == None or xml_dom.value(child) == value_
267
        for attr in elem.keys:
268
            if not is_match: break
269
            is_match = ((get(child, attr, False, last_only,
270
                allow_rooted=False) != []) == is_positive(attr))
271
        if is_match:
272
            nodes.append(child)
273
            if limit != None and len(nodes) >= limit: break
274
    
275
    # Create node
276
    if nodes == []:
277
        if not create or elem.is_lookup_only: return []
278
        if elem.is_attr:
279
            root.setAttribute(elem.name, '')
280
            node = root.getAttributeNode(elem.name)
281
        elif util.list_eq_is(children, [root]): node = root
282
        else: node = root.appendChild(doc.createElement(elem.name))
283
        if value_ != None: xml_dom.set_value(node, value_)
284
        nodes.append(node)
285
    
286
    path_value = value(xpath)
287
    xpath = xpath[1:] # rest of XPath
288
    
289
    next = []
290
    for node in nodes:
291
        # Create attrs
292
        if create:
293
            # Keys last so that any lookahead assertion's path will be created
294
            # last as it would have without the assertion
295
            for attr in elem.attrs + elem.keys:
296
                get(node, attr, create, last_only=False, allow_rooted=False)
297
        
298
        # Follow pointer
299
        if elem.is_ptr:
300
            root = doc.documentElement
301
            xpath = copy.deepcopy(xpath)
302
            id_path = backward_id(xpath[instance_level])
303
            if id_path != None: # backward (child-to-parent) pointer with ID key
304
                id_path[0].name = expand_abbr(id_path[0].name, node.tagName)
305
                set_value(id_path, xml_dom.get_id(node)) # modify xpath's id key
306
            else: # forward (parent-to-child) pointer
307
                id_ = xml_dom.value(node)
308
                obj_xpath = obj(xpath) # target object
309
                if id_ == None or get(root, obj_xpath, False, True) == []:
310
                    # no target or target keys don't match
311
                    if not create: continue
312
                    
313
                    # Use last target object's ID + 1
314
                    obj_xpath[-1].keys = [] # just get by tag name
315
                    last = get(root, obj_xpath, False, True)
316
                    if last != []: id_ = str(int(util.coalesce(
317
                        xml_dom.get_id(last[0]), 0)) + 1)
318
                    else: id_ = '0'
319
                    
320
                    # Will append if target keys didn't match.
321
                    # Use lookahead assertion to avoid this.
322
                    xml_dom.set_value(node, id_)
323
                else: last_only = False
324
                set_id(xpath, id_)
325
        else: root = node
326
        next += get(root, xpath, create, last_only, limit, allow_rooted=False)
327
        
328
        for branch in elem.other_branches:
329
            branch = branch[:] # don't modify input!
330
            set_value(branch, path_value)
331
            next += get(node, branch, create, last_only, limit,
332
                allow_rooted=False)
333
    
334
    return next
335

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

    
340
def get_values(*args, **kw_args):
341
    '''Runs get() and returns the value node (first child) of each node'''
342
    return map(xml_dom.value_node, get(*args, **kw_args))
343

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

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

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

    
362
def xml_set_id(root, id_): xml_dom.set_id(root.firstChild, id_)
(39-39/40)