Debian Codegraph @

tools/python/mllib/dom.py

raw
1 #
2 # Licensed to the Apache Software Foundation (ASF) under one
3 # or more contributor license agreements. See the NOTICE file
4 # distributed with this work for additional information
5 # regarding copyright ownership. The ASF licenses this file
6 # to you under the Apache License, Version 2.0 (the
7 # "License"); you may not use this file except in compliance
8 # with the License. You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing,
13 # software distributed under the License is distributed on an
14 # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 # KIND, either express or implied. See the License for the
16 # specific language governing permissions and limitations
17 # under the License.
18 #
19
20 """
21 Simple DOM for both SGML and XML documents.
22 """
23
24 from __future__ import division
25 from __future__ import generators
26 from __future__ import nested_scopes
27 from __future__ import absolute_import
28
29 import sys
30 if sys.version_info[0] == 2:
31 STRING_TYPES = (basestring,)
32 else:
33 STRING_TYPES = (str,)
34
35
36 class Container:
37
38 def __init__(self):
39 self.children = []
40
41 def add(self, child):
42 child.parent = self
43 self.children.append(child)
44
45 def extend(self, children):
46 for child in children:
47 child.parent = self
48 self.children.append(child)
49
50
51 class Component:
52
53 def __init__(self):
54 self.parent = None
55
56 def index(self):
57 if self.parent:
58 return self.parent.children.index(self)
59 else:
60 return 0
61
62 def _line(self, file, line, column):
63 self.file = file
64 self.line = line
65 self.column = column
66
67
68 class DispatchError(Exception):
69
70 def __init__(self, scope, f):
71 msg = "no such attribute"
72
73
74 class Dispatcher:
75
76 def is_type(self, type):
77 cls = self
78 while cls is not None:
79 if cls.type == type:
80 return True
81 cls = cls.base
82 return False
83
84 def dispatch(self, f, attrs=""):
85 cls = self
86 while cls is not None:
87 if hasattr(f, cls.type):
88 return getattr(f, cls.type)(self)
89 else:
90 cls = cls.base
91
92 cls = self
93 while cls is not None:
94 if attrs:
95 sep = ", "
96 if cls.base is None:
97 sep += "or "
98 else:
99 sep = ""
100 attrs += "%s'%s'" % (sep, cls.type)
101 cls = cls.base
102
103 raise AttributeError("'%s' object has no attribute %s" %
104 (f.__class__.__name__, attrs))
105
106
107 class Node(Container, Component, Dispatcher):
108
109 type = "node"
110 base = None
111
112 def __init__(self):
113 Container.__init__(self)
114 Component.__init__(self)
115 self.query = Query([self])
116
117 def __getitem__(self, name):
118 for nd in self.query[name]:
119 return nd
120
121 def text(self):
122 from . import transforms
123 return self.dispatch(transforms.Text())
124
125 def tag(self, name, *attrs, **kwargs):
126 t = Tag(name, *attrs, **kwargs)
127 self.add(t)
128 return t
129
130 def data(self, s):
131 d = Data(s)
132 self.add(d)
133 return d
134
135 def entity(self, s):
136 e = Entity(s)
137 self.add(e)
138 return e
139
140
141 class Tree(Node):
142
143 type = "tree"
144 base = Node
145
146
147 class Tag(Node):
148
149 type = "tag"
150 base = Node
151
152 def __init__(self, _name, *attrs, **kwargs):
153 Node.__init__(self)
154 self.name = _name
155 self.attrs = list(attrs)
156 self.attrs.extend(kwargs.items())
157 self.singleton = False
158
159 def get_attr(self, name):
160 for k, v in self.attrs:
161 if name == k:
162 return v
163
164 def _idx(self, attr):
165 idx = 0
166 for k, v in self.attrs:
167 if k == attr:
168 return idx
169 idx += 1
170 return None
171
172 def set_attr(self, name, value):
173 idx = self._idx(name)
174 if idx is None:
175 self.attrs.append((name, value))
176 else:
177 self.attrs[idx] = (name, value)
178
179 def dispatch(self, f):
180 try:
181 attr = "do_" + self.name
182 method = getattr(f, attr)
183 except AttributeError:
184 return Dispatcher.dispatch(self, f, "'%s'" % attr)
185 return method(self)
186
187
188 class Leaf(Component, Dispatcher):
189
190 type = "leaf"
191 base = None
192
193 def __init__(self, data):
194 assert isinstance(data, STRING_TYPES)
195 self.data = data
196
197
198 class Data(Leaf):
199 type = "data"
200 base = Leaf
201
202
203 class Entity(Leaf):
204 type = "entity"
205 base = Leaf
206
207
208 class Character(Leaf):
209 type = "character"
210 base = Leaf
211
212
213 class Comment(Leaf):
214 type = "comment"
215 base = Leaf
216
217 ###################
218 ## Query Classes ##
219 ###########################################################################
220
221
222 class Adder:
223
224 def __add__(self, other):
225 return Sum(self, other)
226
227
228 class Sum(Adder):
229
230 def __init__(self, left, right):
231 self.left = left
232 self.right = right
233
234 def __iter__(self):
235 for x in self.left:
236 yield x
237 for x in self.right:
238 yield x
239
240
241 class View(Adder):
242
243 def __init__(self, source):
244 self.source = source
245
246
247 class Filter(View):
248
249 def __init__(self, predicate, source):
250 View.__init__(self, source)
251 self.predicate = predicate
252
253 def __iter__(self):
254 for nd in self.source:
255 if self.predicate(nd):
256 yield nd
257
258
259 class Flatten(View):
260
261 def __iter__(self):
262 sources = [iter(self.source)]
263 while sources:
264 try:
265 nd = next(sources[-1])
266 if isinstance(nd, Tree):
267 sources.append(iter(nd.children))
268 else:
269 yield nd
270 except StopIteration:
271 sources.pop()
272
273
274 class Children(View):
275
276 def __iter__(self):
277 for nd in self.source:
278 for child in nd.children:
279 yield child
280
281
282 class Attributes(View):
283
284 def __iter__(self):
285 for nd in self.source:
286 for a in nd.attrs:
287 yield a
288
289
290 class Values(View):
291
292 def __iter__(self):
293 for name, value in self.source:
294 yield value
295
296
297 def flatten_path(path):
298 if isinstance(path, STRING_TYPES):
299 for part in path.split("/"):
300 yield part
301 elif callable(path):
302 yield path
303 else:
304 for p in path:
305 for fp in flatten_path(p):
306 yield fp
307
308
309 class Query(View):
310
311 def __iter__(self):
312 for nd in self.source:
313 yield nd
314
315 def __getitem__(self, path):
316 query = self.source
317 for p in flatten_path(path):
318 if callable(p):
319 select = Query
320 pred = p
321 source = query
322 elif isinstance(p, STRING_TYPES):
323 if p[0] == "@":
324 select = Values
325 pred = lambda x, n=p[1:]: x[0] == n
326 source = Attributes(query)
327 elif p[0] == "#":
328 select = Query
329 pred = lambda x, t=p[1:]: x.is_type(t)
330 source = Children(query)
331 else:
332 select = Query
333 def pred(x, n=p): return isinstance(x, Tag) and x.name == n
334 source = Flatten(Children(query))
335 else:
336 raise ValueError(p)
337 query = select(Filter(pred, source))
338
339 return query