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 892 aaronmk
import util
8 77 aaronmk
import xml_dom
9 21 aaronmk
10 1001 aaronmk
##### Path elements
11
12 21 aaronmk
class XpathElem:
13 1002 aaronmk
    def __init__(self, name='', value=None, is_attr=False):
14 21 aaronmk
        self.name = name
15
        self.value = value
16
        self.is_attr = is_attr
17 97 aaronmk
        self.is_positive = True
18 94 aaronmk
        self.is_ptr = False
19
        self.keys = []
20
        self.attrs = []
21 78 aaronmk
        self.other_branches = [] # temp implementation for split paths
22 21 aaronmk
23
    def __repr__(self):
24
        str_ = ''
25 141 aaronmk
        if not self.is_positive: str_ += '!'
26 21 aaronmk
        if self.is_attr: str_ += '@'
27 1004 aaronmk
        if self.name == '': str_ += '""'
28
        else: str_ += self.name
29 94 aaronmk
        if self.keys != []: str_ += repr(self.keys)
30
        if self.attrs != []: str_ += ':'+repr(self.attrs)
31
        if self.is_ptr: str_ += '->'
32
        if self.other_branches != []: str_ += '{'+repr(self.other_branches)+'}'
33 25 aaronmk
        if self.value != None: str_ += '='+repr(self.value)
34 21 aaronmk
        return str_
35
36
    def __eq__(self, other): return self.__dict__ == other.__dict__
37
38 1002 aaronmk
empty_elem = XpathElem()
39
40
def elem_is_empty(elem): return elem == empty_elem
41
42 1004 aaronmk
def is_self(elem): return elem.name == '' or elem.name == '.'
43
44
def is_parent(elem): return elem.name == '..'
45
46 1001 aaronmk
##### Paths
47
48 99 aaronmk
def is_positive(path): return path[0].is_positive
49
50 1003 aaronmk
def is_rooted(path): return elem_is_empty(path[0])
51
52 24 aaronmk
def value(path): return path[-1].value
53
54 22 aaronmk
def set_value(path, value): path[-1].value = value
55
56 32 aaronmk
def backward_id(elem):
57 171 aaronmk
    if len(elem.keys) >= 1 and value(elem.keys[0]) == None: return elem.keys[0]
58 32 aaronmk
    else: return None
59
60 1001 aaronmk
instance_level = 1 # root's grandchildren
61
62
def obj(path):
63
    obj_path = copy.deepcopy(path[:instance_level+1])
64
    obj_path[-1].is_ptr = False # prevent pointer w/o target
65
    return obj_path
66
67
def set_id(path, id_, has_types=True):
68
    if has_types: id_level = instance_level
69
    else: id_level = 0 # root's children
70 1004 aaronmk
    if is_self(path[0]): id_level += 1 # explicit root element
71 1001 aaronmk
    path[id_level].keys.append([XpathElem('id', id_, True)])
72
73
def is_id(path): return path[0].is_attr and path[0].name == 'id'
74
75
def is_instance(elem): return elem.keys != [] and is_id(elem.keys[0])
76
77
##### Parsing
78
79 170 aaronmk
def expand_abbr(name, repl):
80
    before, abbr, after = name.partition('*')
81
    if abbr != '': name = before+repl+after
82
    return name
83
84 154 aaronmk
_cache = {}
85
86 76 aaronmk
def parse(str_):
87 154 aaronmk
    try: return _cache[str_]
88
    except KeyError: pass
89
90 76 aaronmk
    parser = Parser(str_)
91 21 aaronmk
92 76 aaronmk
    def _path():
93 97 aaronmk
        is_positive = not parser.str_('!')
94
95 21 aaronmk
        tree = []
96
        while True:
97 38 aaronmk
            # Split path
98 76 aaronmk
            if parser.str_('{'):
99 94 aaronmk
                tree[-1].other_branches = _paths()
100 76 aaronmk
                parser.str_('}', required=True)
101 94 aaronmk
                tree += tree[-1].other_branches.pop(0) # use first path for now
102 38 aaronmk
                break # nothing allowed after split path
103 36 aaronmk
104 754 aaronmk
            elem = XpathElem(is_attr=parser.str_('@'), name=_value())
105 38 aaronmk
106 94 aaronmk
            # Keys used to match nodes
107 76 aaronmk
            if parser.str_('['):
108 94 aaronmk
                elem.keys = _paths()
109 76 aaronmk
                parser.str_(']', required=True)
110 36 aaronmk
111 94 aaronmk
            # Attrs created when no matching node exists
112
            if parser.str_(':'):
113
                parser.str_('[', required=True)
114
                elem.attrs = _paths()
115
                parser.str_(']', required=True)
116
117 76 aaronmk
            elem.is_ptr = parser.str_('->')
118 21 aaronmk
            tree.append(elem)
119 36 aaronmk
120
            # Lookahead assertion
121 76 aaronmk
            if parser.str_('('):
122
                parser.str_('/', required=True) # next / is inside ()
123
                path = _path()
124
                parser.str_(')', required=True)
125 94 aaronmk
                elem.keys.append(path)
126 36 aaronmk
                tree += path
127
128 76 aaronmk
            if not parser.str_('/'): break
129 32 aaronmk
130 97 aaronmk
        tree[0].is_positive = is_positive
131
132
        # Value
133 997 aaronmk
        if parser.str_('='):
134 1009 aaronmk
            if parser.str_('$'): # reference (different from a pointer)
135
                value = _path()
136
            else: value = _value() # literal value
137 997 aaronmk
            set_value(tree, value)
138 85 aaronmk
139 32 aaronmk
        # Expand * abbrs
140 70 aaronmk
        for i in reversed(xrange(len(tree))):
141
            elem = tree[i]
142 171 aaronmk
            if elem.is_ptr: offset = 2
143 32 aaronmk
            else: offset = 1
144 170 aaronmk
            try: repl = tree[i+offset].name
145 171 aaronmk
            except IndexError: pass # no replacement elem
146
            else: elem.name = expand_abbr(elem.name, repl)
147 32 aaronmk
148 21 aaronmk
        return tree
149 76 aaronmk
150 754 aaronmk
    def _value():
151
        if parser.str_('"'):
152
            value = parser.re(r'[^"]*')
153
            parser.str_('"', required=True)
154
        else: value = parser.re(r'(?:(?:\w+:)*[\w.*]+)?')
155
        return value
156
157 94 aaronmk
    def _paths():
158
        paths = []
159
        while True:
160
            paths.append(_path())
161
            if not parser.str_(','): break
162
        return paths
163
164 76 aaronmk
    path = _path()
165
    parser.end()
166 154 aaronmk
    _cache[str_] = path
167 76 aaronmk
    return path
168 21 aaronmk
169 1001 aaronmk
##### Querying/creating XML trees
170 22 aaronmk
171 1005 aaronmk
def get(root, xpath, create=False, last_only=None, limit=1, allow_rooted=True):
172 141 aaronmk
    '''Warning: The last_only optimization may put data that should be together
173
    into separate nodes'''
174 77 aaronmk
    if last_only == None: last_only = create
175 887 aaronmk
    if limit == None or limit > 1: last_only = False
176 892 aaronmk
    if util.is_str(xpath): xpath = parse(xpath)
177 99 aaronmk
178 1005 aaronmk
    # Handle edge cases
179 998 aaronmk
    if xpath == []: return [root]
180 886 aaronmk
    if create and not is_positive(xpath): return []
181 1005 aaronmk
182
    # Define vars
183 998 aaronmk
    doc = root.ownerDocument
184 1005 aaronmk
    if allow_rooted and is_rooted(xpath): root = doc.documentElement
185 165 aaronmk
    elem = xpath[0]
186
187
    # Find possible matches
188
    children = []
189
    if elem.is_attr:
190 998 aaronmk
        child = root.getAttributeNode(elem.name)
191 165 aaronmk
        if child != None: children = [child]
192 1004 aaronmk
    elif is_self(elem): children = [root]
193
    elif is_parent(elem):
194 1000 aaronmk
        parent = xml_dom.parent(root)
195 1013 aaronmk
        if parent == None: return [] # don't try to create doc root's parent
196
        root = parent
197
        children = [root]
198 165 aaronmk
    else:
199 998 aaronmk
        children = xml_dom.by_tag_name(root, elem.name,
200 1013 aaronmk
            last_only and (elem.keys == [] or is_instance(elem)))
201 165 aaronmk
202 1009 aaronmk
    # Retrieve elem value
203
    value_ = elem.value
204
    if util.is_list(value_): # reference (different from a pointer)
205
        targets = get(root, value_)
206
        try: target = targets[0]
207
        except IndexError:
208
            warnings.warn(UserWarning('XPath reference target missing: '
209
                +str(value_)+'\nXPath: '+str(xpath)))
210
            value_ = None
211
        else: value_ = xml_dom.value(target)
212
213 165 aaronmk
    # Check each match
214 885 aaronmk
    nodes = []
215 165 aaronmk
    for child in children:
216 1009 aaronmk
        is_match = value_ == None or xml_dom.value(child) == value_
217 165 aaronmk
        for attr in elem.keys:
218
            if not is_match: break
219 1011 aaronmk
            is_match = ((get(child, attr, False, last_only,
220
                allow_rooted=False) != []) == is_positive(attr))
221 885 aaronmk
        if is_match:
222
            nodes.append(child)
223
            if limit != None and len(nodes) >= limit: break
224 165 aaronmk
225
    # Create node
226 886 aaronmk
    if nodes == []:
227
        if not create: return []
228 77 aaronmk
        if elem.is_attr:
229 998 aaronmk
            root.setAttribute(elem.name, '')
230
            node = root.getAttributeNode(elem.name)
231 1013 aaronmk
        elif util.list_eq_is(children, [root]): node = root
232 998 aaronmk
        else: node = root.appendChild(doc.createElement(elem.name))
233 1009 aaronmk
        if value_ != None: xml_dom.set_value(node, value_)
234 886 aaronmk
        nodes.append(node)
235 165 aaronmk
236 1009 aaronmk
    path_value = value(xpath)
237 165 aaronmk
    xpath = xpath[1:] # rest of XPath
238
239 886 aaronmk
    next = []
240
    for node in nodes:
241
        # Create attrs
242
        if create:
243
            for attr in elem.keys + elem.attrs:
244 1011 aaronmk
                get(node, attr, create, last_only, allow_rooted=False)
245 886 aaronmk
246
        # Follow pointer
247
        if elem.is_ptr:
248 998 aaronmk
            root = doc.documentElement
249 886 aaronmk
            xpath = copy.deepcopy(xpath)
250
            id_path = backward_id(xpath[instance_level])
251
            if id_path != None: # backward (child-to-parent) pointer with ID key
252
                id_path[0].name = expand_abbr(id_path[0].name, node.tagName)
253
                set_value(id_path, xml_dom.get_id(node)) # modify xpath's id key
254
            else: # forward (parent-to-child) pointer
255
                id_ = xml_dom.value(node)
256
                obj_xpath = obj(xpath) # target object
257
                if id_ == None or get(root, obj_xpath, False, True) == []:
258
                    # no target or target keys don't match
259
                    if not create: continue
260
261
                    # Use last target object's ID + 1
262
                    obj_xpath[-1].keys = [] # just get by tag name
263
                    last = get(root, obj_xpath, False, True)
264
                    if last != []: id_ = str(int(xml_dom.get_id(last[0])) + 1)
265
                    else: id_ = '0'
266
267
                    # Will append if target keys didn't match.
268
                    # Use lookahead assertion to avoid this.
269
                    xml_dom.set_value(node, id_)
270
                else: last_only = False
271
                set_id(xpath, id_)
272
        else: root = node
273 1005 aaronmk
        next += get(root, xpath, create, last_only, limit, allow_rooted=False)
274 886 aaronmk
275
        for branch in elem.other_branches:
276
            branch = copy.deepcopy(branch)
277 1009 aaronmk
            set_value(branch, path_value)
278 1005 aaronmk
            next += get(node, branch, create, last_only, limit,
279
                allow_rooted=False)
280 165 aaronmk
281
    return next
282 82 aaronmk
283 141 aaronmk
def put_obj(root, xpath, id_, has_types, value=None):
284 892 aaronmk
    if util.is_str(xpath): xpath = parse(xpath)
285 155 aaronmk
286 82 aaronmk
    xpath = copy.deepcopy(xpath) # don't modify input!
287
    set_id(xpath, id_, has_types)
288 85 aaronmk
    if value != None: set_value(xpath, value)
289 141 aaronmk
    get(root, xpath, True)
290 133 aaronmk
291 135 aaronmk
def path2xml(xpath, first_branch=True):
292
    root = xml_dom.create_doc().documentElement
293 141 aaronmk
    get(root, xpath, True)
294 135 aaronmk
    return root
295 133 aaronmk
296 141 aaronmk
def xml_set_id(root, id_): xml_dom.set_id(root.firstChild, id_)