Debian Codegraph @

gavo/dm/sil.py

raw
1 """
2 SIL, the Simple Instance Language, is an attempt to allow
3 data model instances written in a simple, JSON-like language.
4 """
5
6 #c Copyright 2008-2025, the GAVO project <[email protected]>
7 #c
8 #c This program is free software, covered by the GNU GPL. See the
9 #c COPYING file in the source distribution.
10
11
12 import functools
13 import re
14
15 from gavo import utils
16 from gavo.dm import common
17
18
19 # sentinels for further processing
20 class Atom(str):
21 """a sentinel class for atomic values of roles
22 """
23 noQuotesOkRE = re.compile(r"[\w_.]+$")
24
25 def asSIL(self):
26 if self.noQuotesOkRE.match(self):
27 return str(self)
28 else:
29 return '"%s"'%(self.replace('"', '""'))
30
31 def __repr__(self):
32 return "a"+str.__repr__(self).lstrip("u")
33
34
35 class Reference(str):
36 """a sentinel class for roles referencing something else.
37 """
38 def asSIL(self):
39 return "@%s"%self
40
41
42 # parse methods, used by getGrammar, by nonterminal name there
43 def _pa_attributeDef(s, p, toks):
44 return ("attr", toks[0], toks[2])
45
46 def _pa_valueWithFallback(s, p, toks):
47 return ("fallback", toks[0], toks[2])
48
49 def _pa_typeAnnotation(s, p, toks):
50 return toks[1]
51
52 def _pa_collection(s, p, toks):
53 if len(toks)==1:
54 # no explicit type annotation; we return None as type.
55 return ("coll", None, toks[0])
56 else:
57 return ("coll", toks[0], toks[1])
58
59 def _pa_obj(s, p, toks):
60 if len(toks)==2:
61 # with type annotation
62 return ("obj", toks[0], toks[1][2])
63 else:
64 # no type annotation; we should later add an annotation based on
65 # the default for the DM
66 return ("obj", None, toks[0][2])
67
68 def _pa_objectBody(s, p, toks):
69 return ("uobj", None, toks[1].asList())
70
71 def _pa_sequenceBody(s, p, toks):
72 return [toks[1].asList()]
73
74 def _pa_reference(s, p, toks):
75 return Reference(toks[1])
76
77 def _pa_simpleImmediate(s, p, toks):
78 return Atom(toks[0])
79
80 def _pa_nullLiteral(s, p, toks):
81 return [None]
82
83
84 @functools.cache
85 def getGrammar(debug=False):
86 """returns a grammar for parsing a SIL object description.
87 """
88 from gavo.utils.parsetricks import (Word, Literal, alphas, alphanums,
89 QuotedString, Forward, ZeroOrMore, Group, Optional, cStyleComment,
90 pyparsingWhitechars, ParserElement)
91
92 with pyparsingWhitechars("\t\n\r "):
93 qualifiedIdentifier = Word(alphas+"_:", alphanums+"-._:")
94 plainIdentifier = Word(alphas+"_", alphanums+"-._")
95 externalIdentifier = Word(alphas+"_", alphanums+"._/#-")
96 plainLiteral = Word(alphanums+"_-.")
97 quotedLiteral = QuotedString(quoteChar='"', escQuote='""')
98 nullLiteral = Literal("__NULL__")
99 reference = (Literal('@') + externalIdentifier)
100
101 complexImmediate = Forward()
102 simpleImmediate = plainLiteral | quotedLiteral
103 value = (nullLiteral | reference | complexImmediate | simpleImmediate)
104
105 valueWithFallback = (value
106 + "|"
107 - value)
108 attributeDef = (plainIdentifier
109 + Literal(":")
110 + (valueWithFallback | value))
111
112 typeAnnotation = (Literal('(')
113 + qualifiedIdentifier
114 + Literal(')'))
115 objectBody = (Literal('{')
116 + Group(ZeroOrMore( attributeDef ))
117 + Literal('}'))
118 obj = Optional(typeAnnotation) + objectBody
119
120 sequenceBody = (Literal('[')
121 + Group(ZeroOrMore(
122 valueWithFallback | value | objectBody))
123 + Literal(']'))
124 collection = Optional(typeAnnotation) + sequenceBody
125
126 complexImmediate << ( obj | collection )
127
128 for sym in [complexImmediate, collection, sequenceBody,
129 objectBody, typeAnnotation, attributeDef]:
130 sym.ignore(cStyleComment)
131
132 for n, func in globals().items():
133 if n.startswith("_pa_"):
134 locals()[n[4:]].setParseAction(func)
135
136 if debug:
137 for name, sym in locals().items():
138 if isinstance(sym, ParserElement):
139 sym.setDebug(True)
140 sym.setName(name)
141
142 return obj
143
144
145
146 def _getAttributeEvents(attrNode):
147 """returns a list of events for an attr node in the parse tree.
148 """
149 assert attrNode[0]=='attr'
150 if isinstance(attrNode[2], (Reference, Atom)):
151 return [('attr', attrNode[1], attrNode[2])]
152
153 elif isinstance(attrNode[2], tuple):
154 return list(
155 _parseTreeToEvents(attrNode[2], roleName=attrNode[1]))
156
157 elif attrNode[2] is None:
158 # swallow __NULL__ attributes
159 return []
160
161 else:
162 assert False, "Bad object as parsed value: %s"%repr(attrNode[2])
163
164
165 def _getFallbackAttrEv(node):
166 """returns a parser event for a fallback node.
167 """
168 # we're copying the current (attribute) child and parse
169 # the two arms of the fallback node; then we produce
170 # a fallback node with the two resulting event streams.
171 return ("fallback",
172 _getAttributeEvents((node[0], node[1], node[2][1])),
173 _getAttributeEvents((node[0], node[1], node[2][2])))
174
175
176 def _iterAttrs(node, seqType=None, roleName=None):
177 """generates parse events for nodes with attribute children.
178
179 (see _parseTreeToEvents).
180
181 roleName and seqType are ignored here (the attribute names are part of the
182 events). They are just part of the signature because _iterObjs needs them.
183 """
184 for child in node[2]:
185 if isinstance(child[2], tuple) and child[2][0]=="fallback":
186 yield _getFallbackAttrEv(child)
187 else:
188 yield from iter(_getAttributeEvents(child))
189
190
191 def _getObjectEvents(itemNode, seqType, roleName):
192 """returns a list parser events for an item node in the parse tree.
193
194 This isn't a iterator because the lists are needed as is for
195 fallbacks.
196 """
197 if isinstance(itemNode, (Reference, Atom)):
198 return [('item', itemNode, None)]
199
200 elif itemNode[0]=="fallback":
201 return [("fallback",
202 _getObjectEvents(itemNode[1], seqType, roleName),
203 _getObjectEvents(itemNode[2], seqType, roleName))]
204
205 else:
206 # complex node -- recurse into _parseTreeToEvents
207 return list(_parseTreeToEvents(
208 itemNode, seqType=seqType, roleName=roleName))
209
210
211 def _iterObjs(node, seqType, roleName):
212 """generates parse events for sequences.
213
214 (see _parseTreeToEvents).
215 """
216 for child in node[2]:
217 yield from iter(_getObjectEvents(child, seqType, roleName))
218
219
220 _PARSER_EVENT_MAPPING = {
221 # -> (iterparse ev name, type source, child parser)
222 'obj': ('obj', 'fromNode', _iterAttrs),
223 'uobj': ('obj', 'seqType', _iterAttrs),
224 'coll': ('coll', 'fromNode', _iterObjs),
225 }
226
227 def _parseTreeToEvents(node, seqType=None, roleName=None):
228 """helps iterparse by translating parse tree nodes into the events
229 iterparse yields.
230
231 This works by invoking sub-parsers as per _PARSER_EVENT_MAPPING, which
232 maps parse tree node types to tuples of the parser event type,
233 an indicator of where to get the the type from (either from the
234 node or, for collection, from the embedding sequence), an the
235 child parser.
236 """
237 opener, typeSource, childParser = _PARSER_EVENT_MAPPING[node[0]]
238 if typeSource=='fromNode':
239 nodeType = node[1]
240 elif typeSource=='seqType':
241 nodeType = seqType
242 else:
243 assert False
244 yield (opener, roleName, nodeType)
245
246 for child in childParser(node, nodeType, roleName):
247 yield child
248
249 yield ('pop', None, None)
250
251
252 def iterparse(silLiteral):
253 """yields parse events for a SIL literal in a string.
254
255 The parse events are triples of one of the forms:
256
257 * ('attr', roleName, value) add an attribute to the current
258 annotation; value can be a "value" (as in object, reference,...)
259 or an Alternative instance from fallbacks.
260 * ('obj', roleName, type) create a new object object of type
261 * ('coll', type, None) create a new collection annotation (type can be None)
262 * ('item', val, None) add an atomic value to the current collection
263 * ('pop', None, None) finish current annotation and add it to its container
264
265 These events are generated from the tree that the grammar produces
266 by logic in _parseTreeToEvents.
267 """
268 root = getGrammar().parseString(silLiteral, parseAll=True)[0]
269 return _parseTreeToEvents(root)
270
271
272 class AnnotationBuilder:
273 """A class to build the table annotation.
274
275 It is constructed with an iterator over the annotation events (from
276 sil.iterparse), and an annotationFactory, which is a callable
277 taking an attribute name and an attribute value, producing an Annotation
278 instance. There, the value will be either an Atom or a Reference.
279
280 Internally, the AnnotationBuilder works with an object stack, onto
281 which built annotations are pushed. They are taken off as annotations
282 get built.
283
284 After construction, use the feed method to feed the parser events into
285 the builder. When self.result becomes non-None, the Builder considers
286 its job done and will AttributeError on further feed attempts.
287 """
288 def __init__(self, annotationFactory):
289 self.annotationFactory = annotationFactory
290 self.obStack, self.result = [], None
291 self.root = None
292
293 @classmethod
294 def fromSILLiteral(cls, silLiteral, annotationFactory):
295 """builds annotation using annotationFactory from a SIL literal.
296
297 This adds a few sanity checks; fetch the annotation result (which you
298 may not actually care about a lot) from the result's result attribute.
299 """
300 self = cls(annotationFactory)
301 for ev in iterparse(silLiteral):
302 self.feed(*ev)
303
304 if self.result is None:
305 raise utils.StructureError("Data model annotation yielded no result.")
306 if self.result.type is None:
307 raise utils.StructureError("Root of Data Model annotation must"
308 " have a type.")
309 return self
310
311 def feed(self, evType, arg1, arg2):
312 if self.root is None:
313 self._buildRoot(evType, arg1, arg2)
314 else:
315 getattr(self, "_handle_"+evType)(arg1, arg2)
316
317 def _handle_obj(self, arg1, arg2):
318 # an object: push it on the stack
319 self.obStack.append(common.ObjectAnnotation(arg1, arg2, self.root))
320
321 def _handle_coll(self, arg1, arg2):
322 # a collection: push it on the stack
323 self.obStack.append(common.CollectionAnnotation(arg1, arg2, self.root))
324
325 def _handle_pop(self, arg1, arg2):
326 # done with a certain kind of annotation: pop it and add it to
327 # its parent (which is the new stack top).
328 newRole = self.obStack.pop()
329 if self.obStack:
330 self.obStack[-1].add(newRole)
331 else:
332 # we've just popped the total result. Make sure
333 # any further operations fail.
334 del self.obStack
335 self.result = newRole
336
337 def _handle_attr(self, arg1, arg2):
338 # an attribute: add it to the top of the stack (the attribute
339 # name is part of the annotation).
340 self.obStack[-1].add(
341 self.annotationFactory(self.root, arg1, arg2))
342
343 def _handle_fallback(self, arg1, arg2):
344 # a fallback: try building arg1, and if that fails, try arg2.
345 # This leaves all actual action to the (recursive) delegation.
346 try:
347 curStackTop = len(self.obStack)
348 for ev in arg1:
349 self.feed(*ev)
350 except:
351 # unwind the stack if necessary to remove any junk left by
352 # the abortive attempt
353 self.obStack = self.obStack[:curStackTop]
354 for ev in arg2:
355 self.feed(*ev)
356
357 def _handle_item(self, arg1, arg2):
358 collection = self.obStack[-1]
359 assert isinstance(collection, common.CollectionAnnotation)
360 collection.add(
361 self.annotationFactory(self.root, collection.name, arg1))
362
363 def _buildRoot(self, evType, arg1, arg2):
364 assert evType=='obj'
365 self.root = common.ObjectAnnotation(arg1, arg2, None)
366 self.obStack.append(self.root)
367
368
369 def getAnnotation(silLiteral, annotationFactory):
370 """returns an annotation object parsed from silLiteral.
371
372 This is a shallow wrapper around AnnotationBuilder.fromSILLiteral,
373 which you should probably directly use in new code.
374 """
375 res = AnnotationBuilder.fromSILLiteral(silLiteral, annotationFactory)
376 return res.result
377
378
379 if __name__=="__main__":
380 g = getGrammar()
381 getGrammar.enableDebuggingOutput()
382 res = g.parseString(
383 """
384 (:testclass) {
385 seq: [a "b c d" @e]}""", parseAll=True)[0]
386 print(res)