Project

General

Profile

1 55 aaronmk
# XPath parsing
2 21 aaronmk
3 55 aaronmk
import copy
4 1009 aaronmk
import warnings
5 21 aaronmk
6
from Parser import Parser
7 4492 aaronmk
import strings
8 892 aaronmk
import util
9 77 aaronmk
import xml_dom
10 21 aaronmk
11 1001 aaronmk
##### Path elements
12
13 21 aaronmk
class XpathElem:
14 1002 aaronmk
    def __init__(self, name='', value=None, is_attr=False):
15 21 aaronmk
        self.name = name
16
        self.value = value
17
        self.is_attr = is_attr
18 97 aaronmk
        self.is_positive = True
19 1238 aaronmk
        self.is_lookup_only = False
20 94 aaronmk
        self.is_ptr = False
21
        self.keys = []
22
        self.attrs = []
23 78 aaronmk
        self.other_branches = [] # temp implementation for split paths
24 21 aaronmk
25
    def __repr__(self):
26
        str_ = ''
27 141 aaronmk
        if not self.is_positive: str_ += '!'
28 21 aaronmk
        if self.is_attr: str_ += '@'
29 1004 aaronmk
        if self.name == '': str_ += '""'
30
        else: str_ += self.name
31 1238 aaronmk
        if self.is_lookup_only: str_ += '?'
32 4492 aaronmk
        if self.keys != []: str_ += strings.urepr(self.keys)
33
        if self.attrs != []: str_ += ':'+strings.urepr(self.attrs)
34 94 aaronmk
        if self.is_ptr: str_ += '->'
35 4492 aaronmk
        if self.other_branches != []:
36
            str_ += '{'+strings.urepr(self.other_branches)+'}'
37
        if self.value != None: str_ += '='+strings.urepr(self.value)
38 21 aaronmk
        return str_
39
40
    def __eq__(self, other): return self.__dict__ == other.__dict__
41
42 1002 aaronmk
empty_elem = XpathElem()
43
44
def elem_is_empty(elem): return elem == empty_elem
45
46 1004 aaronmk
def is_self(elem): return elem.name == '' or elem.name == '.'
47
48
def is_parent(elem): return elem.name == '..'
49
50 3328 aaronmk
def is_all(elem): return elem.name == '*'
51
52 1001 aaronmk
##### Paths
53
54 2010 aaronmk
def is_xpath(value):
55
    return isinstance(value, list) and (len(value) == 0
56
        or isinstance(value[0], XpathElem))
57
58 1350 aaronmk
def path_is_empty(path): return path == [] or path == [empty_elem]
59
60 99 aaronmk
def is_positive(path): return path[0].is_positive
61
62 1003 aaronmk
def is_rooted(path): return elem_is_empty(path[0])
63
64 24 aaronmk
def value(path): return path[-1].value
65
66 1294 aaronmk
def set_value(path, value):
67
    '''Caller must make a shallow copy of the path to prevent modifications from
68
    propagating to other copies of the path (a deep copy is not needed)'''
69
    path[-1] = copy.copy(path[-1]) # don't modify other copies of the path
70
    path[-1].value = value
71 22 aaronmk
72 1577 aaronmk
def append(path, subpath, i=0):
73
    '''Recursively appends subpath to every leaf of a path tree'''
74
    if i >= len(path): path += subpath
75
    else:
76
        append(path, subpath, i+1)
77
        for branch in path[i].other_branches: append(branch, subpath)
78
79 32 aaronmk
def backward_id(elem):
80 171 aaronmk
    if len(elem.keys) >= 1 and value(elem.keys[0]) == None: return elem.keys[0]
81 32 aaronmk
    else: return None
82
83 1001 aaronmk
instance_level = 1 # root's grandchildren
84
85
def obj(path):
86
    obj_path = copy.deepcopy(path[:instance_level+1])
87
    obj_path[-1].is_ptr = False # prevent pointer w/o target
88
    return obj_path
89
90
def set_id(path, id_, has_types=True):
91 1294 aaronmk
    '''Caller must make a shallow copy of the path to prevent modifications from
92 2001 aaronmk
    propagating to other copies of the path (a deep copy is not needed).
93
    @return The path to the ID attr, which can be used to change the ID
94
    '''
95 1001 aaronmk
    if has_types: id_level = instance_level
96
    else: id_level = 0 # root's children
97 1004 aaronmk
    if is_self(path[0]): id_level += 1 # explicit root element
98 1294 aaronmk
99
    id_elem = path[id_level] = copy.copy(path[id_level])
100
        # don't modify other copies of the path
101
    id_elem.keys = id_elem.keys[:] # don't modify other copies of the elem
102 2001 aaronmk
    id_attr = XpathElem('id', None, is_attr=True)
103
104
    # Save the path to the ID attr
105 2003 aaronmk
    id_path = obj(path) # a copy of the path up through the ID level
106 2002 aaronmk
    id_path.append(copy.copy(id_attr)) # this path's id_attr is independent
107 2001 aaronmk
108
    # Set the ID attr on the provided XPath
109
    id_attr.value = id_
110
    id_elem.keys.append([id_attr])
111
112
    return id_path
113 1001 aaronmk
114
def is_id(path): return path[0].is_attr and path[0].name == 'id'
115
116 1070 aaronmk
def is_instance(elem): return elem.keys != [] and is_id(elem.keys[0])
117 1001 aaronmk
118
##### Parsing
119
120 1345 aaronmk
import xpath_func
121
122 170 aaronmk
def expand_abbr(name, repl):
123
    before, abbr, after = name.partition('*')
124
    if abbr != '': name = before+repl+after
125
    return name
126
127 154 aaronmk
_cache = {}
128
129 76 aaronmk
def parse(str_):
130 154 aaronmk
    try: return _cache[str_]
131
    except KeyError: pass
132
133 76 aaronmk
    parser = Parser(str_)
134 21 aaronmk
135 76 aaronmk
    def _path():
136 97 aaronmk
        is_positive = not parser.str_('!')
137
138 21 aaronmk
        tree = []
139
        while True:
140 38 aaronmk
            # Split path
141 76 aaronmk
            if parser.str_('{'):
142 1398 aaronmk
                try: last = tree[-1]
143
                except IndexError: parser.syntax_err('./{')
144 1070 aaronmk
                last.other_branches = _paths()
145 1577 aaronmk
                tree += last.other_branches.pop(0) # use first path for now
146 76 aaronmk
                parser.str_('}', required=True)
147 1577 aaronmk
                if parser.str_('/'): append(tree, _path()) # subpath after {}
148 1070 aaronmk
                break # anything after split path has already been parsed
149 36 aaronmk
150 754 aaronmk
            elem = XpathElem(is_attr=parser.str_('@'), name=_value())
151 38 aaronmk
152 1238 aaronmk
            elem.is_lookup_only = parser.str_('?')
153
154 94 aaronmk
            # Keys used to match nodes
155 76 aaronmk
            if parser.str_('['):
156 94 aaronmk
                elem.keys = _paths()
157 76 aaronmk
                parser.str_(']', required=True)
158 36 aaronmk
159 94 aaronmk
            # Attrs created when no matching node exists
160
            if parser.str_(':'):
161
                parser.str_('[', required=True)
162
                elem.attrs = _paths()
163
                parser.str_(']', required=True)
164
165 76 aaronmk
            elem.is_ptr = parser.str_('->')
166 21 aaronmk
            tree.append(elem)
167 36 aaronmk
168
            # Lookahead assertion
169 76 aaronmk
            if parser.str_('('):
170
                parser.str_('/', required=True) # next / is inside ()
171
                path = _path()
172
                parser.str_(')', required=True)
173 94 aaronmk
                elem.keys.append(path)
174 36 aaronmk
                tree += path
175
176 76 aaronmk
            if not parser.str_('/'): break
177 32 aaronmk
178 97 aaronmk
        tree[0].is_positive = is_positive
179
180
        # Value
181 997 aaronmk
        if parser.str_('='):
182 1009 aaronmk
            if parser.str_('$'): # reference (different from a pointer)
183
                value = _path()
184
            else: value = _value() # literal value
185 997 aaronmk
            set_value(tree, value)
186 85 aaronmk
187 32 aaronmk
        # Expand * abbrs
188 70 aaronmk
        for i in reversed(xrange(len(tree))):
189
            elem = tree[i]
190 171 aaronmk
            if elem.is_ptr: offset = 2
191 32 aaronmk
            else: offset = 1
192 170 aaronmk
            try: repl = tree[i+offset].name
193 171 aaronmk
            except IndexError: pass # no replacement elem
194
            else: elem.name = expand_abbr(elem.name, repl)
195 32 aaronmk
196 21 aaronmk
        return tree
197 76 aaronmk
198 754 aaronmk
    def _value():
199
        if parser.str_('"'):
200
            value = parser.re(r'[^"]*')
201
            parser.str_('"', required=True)
202 4085 aaronmk
        else: value = parser.re(r'(?:(?:\w+:)*[\w.+*]+)?')
203 754 aaronmk
        return value
204
205 94 aaronmk
    def _paths():
206
        paths = []
207 1350 aaronmk
        path = _path()
208
        if not path_is_empty(path): # not empty list
209
            paths.append(path)
210
            while parser.str_(','): paths.append(_path())
211 1352 aaronmk
            if path_is_empty(paths[-1]): paths.pop() # remove trailing ","
212 94 aaronmk
        return paths
213
214 76 aaronmk
    path = _path()
215
    parser.end()
216 1342 aaronmk
    path = xpath_func.process(path)
217 154 aaronmk
    _cache[str_] = path
218 76 aaronmk
    return path
219 21 aaronmk
220 1001 aaronmk
##### Querying/creating XML trees
221 22 aaronmk
222 1005 aaronmk
def get(root, xpath, create=False, last_only=None, limit=1, allow_rooted=True):
223 141 aaronmk
    '''Warning: The last_only optimization may put data that should be together
224
    into separate nodes'''
225 77 aaronmk
    if last_only == None: last_only = create
226 887 aaronmk
    if limit == None or limit > 1: last_only = False
227 892 aaronmk
    if util.is_str(xpath): xpath = parse(xpath)
228 99 aaronmk
229 1005 aaronmk
    # Handle edge cases
230 998 aaronmk
    if xpath == []: return [root]
231 886 aaronmk
    if create and not is_positive(xpath): return []
232 1005 aaronmk
233
    # Define vars
234 998 aaronmk
    doc = root.ownerDocument
235 1005 aaronmk
    if allow_rooted and is_rooted(xpath): root = doc.documentElement
236 165 aaronmk
    elem = xpath[0]
237
238
    # Find possible matches
239
    children = []
240
    if elem.is_attr:
241 998 aaronmk
        child = root.getAttributeNode(elem.name)
242 165 aaronmk
        if child != None: children = [child]
243 1004 aaronmk
    elif is_self(elem): children = [root]
244
    elif is_parent(elem):
245 1000 aaronmk
        parent = xml_dom.parent(root)
246 1013 aaronmk
        if parent == None: return [] # don't try to create doc root's parent
247
        root = parent
248
        children = [root]
249 3330 aaronmk
    elif is_all(elem): children = list(xml_dom.NodeElemIter(root))
250 165 aaronmk
    else:
251 998 aaronmk
        children = xml_dom.by_tag_name(root, elem.name,
252 1815 aaronmk
            last_only=(last_only and (elem.keys == [] or is_instance(elem))),
253
            ignore_namespace=False) # later set ignore_namespace to True?
254 165 aaronmk
255 1009 aaronmk
    # Retrieve elem value
256
    value_ = elem.value
257
    if util.is_list(value_): # reference (different from a pointer)
258 3796 aaronmk
        target = get_1(root, value_)
259
        if target != None: value_ = xml_dom.value(target)
260 4026 aaronmk
        else:
261 1009 aaronmk
            warnings.warn(UserWarning('XPath reference target missing: '
262 4491 aaronmk
                +strings.ustr(value_)+'\nXPath: '+strings.ustr(xpath)))
263 1009 aaronmk
            value_ = None
264
265 165 aaronmk
    # Check each match
266 885 aaronmk
    nodes = []
267 165 aaronmk
    for child in children:
268 1009 aaronmk
        is_match = value_ == None or xml_dom.value(child) == value_
269 165 aaronmk
        for attr in elem.keys:
270
            if not is_match: break
271 1011 aaronmk
            is_match = ((get(child, attr, False, last_only,
272
                allow_rooted=False) != []) == is_positive(attr))
273 885 aaronmk
        if is_match:
274
            nodes.append(child)
275
            if limit != None and len(nodes) >= limit: break
276 165 aaronmk
277
    # Create node
278 886 aaronmk
    if nodes == []:
279 1239 aaronmk
        if not create or elem.is_lookup_only: return []
280 77 aaronmk
        if elem.is_attr:
281 998 aaronmk
            root.setAttribute(elem.name, '')
282
            node = root.getAttributeNode(elem.name)
283 1013 aaronmk
        elif util.list_eq_is(children, [root]): node = root
284 998 aaronmk
        else: node = root.appendChild(doc.createElement(elem.name))
285 1009 aaronmk
        if value_ != None: xml_dom.set_value(node, value_)
286 886 aaronmk
        nodes.append(node)
287 165 aaronmk
288 1009 aaronmk
    path_value = value(xpath)
289 165 aaronmk
    xpath = xpath[1:] # rest of XPath
290
291 886 aaronmk
    next = []
292
    for node in nodes:
293
        # Create attrs
294
        if create:
295 2556 aaronmk
            # Keys last so that any lookahead assertion's path will be created
296
            # last as it would have without the assertion
297
            for attr in elem.attrs + elem.keys:
298 2109 aaronmk
                get(node, attr, create, last_only=False, allow_rooted=False)
299 886 aaronmk
300
        # Follow pointer
301
        if elem.is_ptr:
302 998 aaronmk
            root = doc.documentElement
303 886 aaronmk
            xpath = copy.deepcopy(xpath)
304
            id_path = backward_id(xpath[instance_level])
305
            if id_path != None: # backward (child-to-parent) pointer with ID key
306
                id_path[0].name = expand_abbr(id_path[0].name, node.tagName)
307
                set_value(id_path, xml_dom.get_id(node)) # modify xpath's id key
308
            else: # forward (parent-to-child) pointer
309
                id_ = xml_dom.value(node)
310
                obj_xpath = obj(xpath) # target object
311
                if id_ == None or get(root, obj_xpath, False, True) == []:
312
                    # no target or target keys don't match
313
                    if not create: continue
314
315
                    # Use last target object's ID + 1
316
                    obj_xpath[-1].keys = [] # just get by tag name
317
                    last = get(root, obj_xpath, False, True)
318 1840 aaronmk
                    if last != []: id_ = str(int(util.coalesce(
319
                        xml_dom.get_id(last[0]), 0)) + 1)
320 886 aaronmk
                    else: id_ = '0'
321
322
                    # Will append if target keys didn't match.
323
                    # Use lookahead assertion to avoid this.
324
                    xml_dom.set_value(node, id_)
325
                else: last_only = False
326
                set_id(xpath, id_)
327
        else: root = node
328 1005 aaronmk
        next += get(root, xpath, create, last_only, limit, allow_rooted=False)
329 886 aaronmk
330
        for branch in elem.other_branches:
331 1294 aaronmk
            branch = branch[:] # don't modify input!
332 1009 aaronmk
            set_value(branch, path_value)
333 1005 aaronmk
            next += get(node, branch, create, last_only, limit,
334
                allow_rooted=False)
335 165 aaronmk
336
    return next
337 82 aaronmk
338 1320 aaronmk
def get_1(*args, **kw_args):
339
    '''Runs get() and returns the first result'''
340
    return util.list_get(get(*args, **kw_args), 0)
341
342 4039 aaronmk
def get_values(*args, **kw_args):
343
    '''Runs get() and returns the value node (first child) of each node'''
344
    return map(xml_dom.value_node, get(*args, **kw_args))
345
346 1689 aaronmk
def get_value(*args, **kw_args):
347
    '''Runs get_1() and returns the value of any result node'''
348
    return util.do_ignore_none(xml_dom.value, get_1(*args, **kw_args))
349
350 141 aaronmk
def put_obj(root, xpath, id_, has_types, value=None):
351 2004 aaronmk
    '''@return tuple(inserted_node, id_attr_node)'''
352 892 aaronmk
    if util.is_str(xpath): xpath = parse(xpath)
353 155 aaronmk
354 1294 aaronmk
    xpath = xpath[:] # don't modify input!
355 2004 aaronmk
    id_path = set_id(xpath, id_, has_types)
356 85 aaronmk
    if value != None: set_value(xpath, value)
357 4040 aaronmk
    return (get_values(root, xpath, True), get_1(root, id_path))
358 133 aaronmk
359 135 aaronmk
def path2xml(xpath, first_branch=True):
360
    root = xml_dom.create_doc().documentElement
361 141 aaronmk
    get(root, xpath, True)
362 3626 aaronmk
    return root.firstChild # skip to tree created inside root
363 133 aaronmk
364 141 aaronmk
def xml_set_id(root, id_): xml_dom.set_id(root.firstChild, id_)