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 backward_id(elem):
65
    if len(elem.keys) >= 1 and value(elem.keys[0]) == None: return elem.keys[0]
66
    else: return None
67

    
68
instance_level = 1 # root's grandchildren
69

    
70
def obj(path):
71
    obj_path = copy.deepcopy(path[:instance_level+1])
72
    obj_path[-1].is_ptr = False # prevent pointer w/o target
73
    return obj_path
74

    
75
def set_id(path, id_, has_types=True):
76
    '''Caller must make a shallow copy of the path to prevent modifications from
77
    propagating to other copies of the path (a deep copy is not needed)'''
78
    if has_types: id_level = instance_level
79
    else: id_level = 0 # root's children
80
    if is_self(path[0]): id_level += 1 # explicit root element
81
    
82
    id_elem = path[id_level] = copy.copy(path[id_level])
83
        # don't modify other copies of the path
84
    id_elem.keys = id_elem.keys[:] # don't modify other copies of the elem
85
    id_elem.keys.append([XpathElem('id', id_, True)])
86

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

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

    
91
##### Parsing
92

    
93
import xpath_func
94

    
95
def expand_abbr(name, repl):
96
    before, abbr, after = name.partition('*')
97
    if abbr != '': name = before+repl+after
98
    return name
99

    
100
_cache = {}
101

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

    
194
##### Querying/creating XML trees
195

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

    
308
def get_1(*args, **kw_args):
309
    '''Runs get() and returns the first result'''
310
    return util.list_get(get(*args, **kw_args), 0)
311

    
312
def put_obj(root, xpath, id_, has_types, value=None):
313
    if util.is_str(xpath): xpath = parse(xpath)
314
    
315
    xpath = xpath[:] # don't modify input!
316
    set_id(xpath, id_, has_types)
317
    if value != None: set_value(xpath, value)
318
    get(root, xpath, True)
319

    
320
def path2xml(xpath, first_branch=True):
321
    root = xml_dom.create_doc().documentElement
322
    get(root, xpath, True)
323
    return root
324

    
325
def xml_set_id(root, id_): xml_dom.set_id(root.firstChild, id_)
(16-16/17)