Debian Codegraph @

gavo/votable/dec_tabledata.py

raw
1 """
2 Coding and decoding from tabledata.
3 """
4
5 #c Copyright 2008-2025, the GAVO project <[email protected]>
6 #c
7 #c This program is free software, covered by the GNU GPL. See the
8 #c COPYING file in the source distribution.
9
10
11 import re #noflake: used by generated code
12
13 from gavo import utils #noflake: used by generated code
14 from gavo.utils import parseDefaultDatetime, parseDefaultDate #noflake: used by generated code
15 from gavo.utils import pgsphere #noflake: used by generated code
16 from gavo.votable import coding
17 from gavo.votable import common
18 from gavo.votable.model import VOTable
19
20 from gavo.utils.dachstypes import (
21 Any, Callable, Dict, Iterator, List, Optional, Tuple)
22
23 try:
24 from gavo import stc #noflake: used by generated code
25 except ImportError:
26 # see modelgroups
27 pass
28
29
30 # literals for TDENC booleans
31 TDENCBOOL = {
32 't': True,
33 '1': True,
34 'true': True,
35 'f': False,
36 '0': False,
37 'false': False,
38 '?': None,
39 '': None,
40 }
41
42
43 def tokenizeComplexArr(val: str) -> Iterator[str]:
44 """iterates over suitable number literal pairs from the VOTable complex
45 array literal val.
46 """
47 last = None
48 if val is None:
49 return
50 for item in val.split():
51 if not item:
52 continue
53 if last is None:
54 last = item
55 else:
56 yield f"{last} {item}"
57 last = None
58 if last:
59 yield last
60
61
62 def tokenizeBitArr(val: str) -> Iterator[str]:
63 """iterates over 0 or 1 tokens in val, discarding everything else.
64 """
65 if val is None:
66 return
67 for item in val:
68 if item in "01":
69 yield item
70
71
72 def tokenizeNormalArr(val: str) -> Iterator[str]:
73 """iterates over all whitespace-separated tokens in val
74 """
75 if val is None:
76 return
77 for item in val.split():
78 if item:
79 yield item
80
81
82 def _addNullvalueCode(
83 field: VOTable.TypedElement,
84 src: List[str],
85 validator: Callable[[Any], Any]) -> List[str]:
86 """adds code to catch nullvalues if required by field.
87
88 validator must be a function returning a valid python value for
89 a nullvalue attribute or raise an exception. This is security
90 critical since whatever validator returns gets embedded into
91 natively-run source code.
92 """
93 nullvalue = coding.getNullvalue(field, validator)
94 if nullvalue is not None:
95 src = [
96 'if val=="%s":'%nullvalue,
97 ' row.append(None)',
98 'else:']+common.indentList(src, " ")
99 return src
100
101
102 def _makeFloatDecoder(field: VOTable.TypedElement) -> List[str]:
103 src = [
104 'if not val or val=="NaN":',
105 ' row.append(None)',
106 'else:',
107 ' row.append(float(val))',]
108 return _addNullvalueCode(field, src, float)
109
110
111 def _makeComplexDecoder(field: VOTable.TypedElement) -> List[str]:
112 src = [
113 'if not val:',
114 ' row.append(None)',
115 'else:',
116 ' try:',
117 ' r, i = val.split()',
118 ' except ValueError:',
119 ' r, i = float(val), 0',
120 ' if r!=r or i!=i:',
121 ' row.append(None)',
122 ' else:'
123 ' row.append(complex(float(r), float(i)))',]
124 return _addNullvalueCode(field, src, common.validateTDComplex)
125
126
127 def _makeIntDecoder(field: VOTable.TypedElement, maxInt: int) -> List[str]:
128 src = [
129 'if not val:',
130 ' row.append(None)',
131 'elif val.startswith("0x"):',
132 ' unsigned = int(val[2:], 16)',
133 # Python hex parsing is unsigned, fix manually based on maxInt
134 ' if unsigned>=%d:'%maxInt,
135 ' row.append(unsigned-%d)'%((maxInt+1)*2),
136 ' else:',
137 ' row.append(unsigned)',
138 'else:',
139 ' row.append(int(val))']
140 return _addNullvalueCode(field, src, common.validateVOTInt)
141
142
143 def _makeCharDecoder(
144 field: VOTable.TypedElement,
145 emptyIsNull: bool = True,
146 fallbackEncoding: Optional[str] = "ascii") -> List[str]:
147 """returns code lines to decode VOTable char literals.
148
149 This will insert xtype parsers where appropriate.
150 """
151 # Elementtree makes sure we're only seeing unicode strings here
152 # We simply pass these on -- while this makes us accept more than
153 # we should, in practice returning bytes here would cause a lot
154 # more headache. Ask astropy users.
155 src = []
156 if emptyIsNull:
157 src.extend([
158 'if not val:',
159 ' val = None',])
160 else:
161 src.extend([
162 'if val is None:',
163 ' val = ""'])
164
165 nullvalue = coding.getNullvalue(field, str, "")
166
167 if nullvalue:
168 src.extend([
169 'if val==%s:'%repr(nullvalue),
170 ' val = None',])
171
172 if field.isMultiDim():
173 src.append("val = coding.unravelArray(%s, val)"%repr(field.arraysize))
174
175 xtypeDecoder = common.getXtypeDecoderCode(field)
176 if xtypeDecoder:
177 src.extend(xtypeDecoder)
178
179 src.append("row.append(val)")
180 return src
181
182
183 def _makeUnicodeDecoder(
184 field: VOTable.TypedElement,
185 emptyIsNull: bool = True) -> List[str]:
186 return _makeCharDecoder(field, emptyIsNull, fallbackEncoding=None)
187
188
189 def _makeBooleanDecoder(field: VOTable.TypedElement) -> List[str]:
190 return ['row.append(TDENCBOOL[val.strip().lower()])']
191
192
193 def _makeBitDecoder(field: VOTable.TypedElement) -> List[str]:
194 return ['row.append(int(val))']
195
196
197 _decoders: Dict[str, Tuple[Callable, str]] = {
198 'boolean': (_makeBooleanDecoder, 'list'),
199 'bit': (_makeBitDecoder, 'list'),
200 'unsignedByte': (lambda v: _makeIntDecoder(v, 256), 'bytelist'),
201 'char': (_makeCharDecoder, 'list'),
202 'unicodeChar': (_makeUnicodeDecoder, 'list'),
203 'short': (lambda v: _makeIntDecoder(v, 32767), 'intlist'),
204 'int': (lambda v: _makeIntDecoder(v, 2147483647), 'intlist'),
205 'long': (lambda v: _makeIntDecoder(v, 9223372036854775807), 'intlist'),
206 'float': (_makeFloatDecoder, 'floatlist'),
207 'double': (_makeFloatDecoder, 'floatlist'),
208 'floatComplex': (_makeComplexDecoder, 'complexlist'),
209 'doubleComplex': (_makeComplexDecoder, 'complexlist'),
210 }
211
212 def _getArrayDecoderLines(field: VOTable.TypedElement) -> List[str]:
213 """returns lines that decode arrays of literals.
214
215 Unfortunately, the spec is plain nuts, so we need to pull some tricks here.
216
217 As per VOTable 1.3, we translate empty strings to Nones; we use the
218 liberty that empty and NULL arrays are not distinguished to return
219 empty arrays as empty arrays, though.
220 """
221 # TODO: this now contains enough generic code to marry it with the
222 # respective function in dec_binary (and move the result to coding.py).
223 type = field.datatype
224
225 if type=='char':
226 return _makeCharDecoder(field, emptyIsNull=True)
227 elif type=='unicodeChar':
228 return _makeUnicodeDecoder(field, emptyIsNull=True)
229
230 decoder, listtype = _decoders[type]
231
232 src = [ # OMG. I'm still hellbent on not calling functions here.
233 'arrayLiteral = val',
234 'fullRow, row = row, []',
235 ]
236 if type=='floatComplex' or type=='doubleComplex':
237 src.append("for val in tokenizeComplexArr(arrayLiteral):")
238 elif type=='bit':
239 src.append("for val in tokenizeBitArr(arrayLiteral):")
240 else:
241 src.append("for val in tokenizeNormalArr(arrayLiteral):")
242
243 src.extend(common.indentList(decoder(field), " "))
244
245 src.extend(coding.makeShapeValidator(field))
246 src.extend([
247 "val = utils.%s(row)"%listtype,
248 "row = fullRow"])
249 src.append("val = coding.unravelArray(%s, val)"%repr(field.arraysize))
250 src.extend(common.getXtypeDecoderCode(field))
251 src.extend([
252 "row.append(val)"])
253
254 return [
255 "if val=='':",
256 " row.append(None)",
257 "else:"]+common.indentList(src, " ")
258
259
260 def getLinesFor(field: VOTable.TypedElement) -> List[str]:
261 """returns a sequence of python source lines to decode TABLEDATA-encoded
262 values for field.
263 """
264 if field.isScalar():
265 return _decoders[field.datatype][0](field)
266 else:
267 return _getArrayDecoderLines(field)
268
269
270 def getRowDecoderSource(tableDefinition: VOTable.TABLE):
271 """returns the source for a function deserializing rows of tableDefition
272 in TABLEDATA.
273
274 tableDefinition is a VOTable.TABLE instance.
275 """
276 source = ["def codec(rawRow):", " row = []"]
277 for index, field in enumerate(
278 tableDefinition.iterChildrenOfType(VOTable.FIELD)):
279 source.extend([
280 " try:",
281 " val = rawRow[%d]"%index,]+
282 common.indentList(getLinesFor(field), " ")+[
283 " except common.VOTableError:",
284 " raise",
285 " except Exception as ex:",
286 # " import traceback; traceback.print_exc()",
287 " raise common.BadVOTableLiteral('%s', val, ex, name=%r)"%(
288 field.datatype, field.name)])
289 source.append(" return row")
290 return "\n".join(source)
291
292 return source
293
294
295 def getGlobals(tableDefinition: Optional[VOTable.TABLE]) -> Dict[str, Any]:
296 return globals()