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