Debian Codegraph @

gavo/grammars/binarygrammar.py

raw
1 """
2 A grammar reading from (fixed-record) binary files.
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
12 import struct
13
14
15 from gavo import base
16 from gavo import utils
17 from gavo.grammars.common import Grammar, FileRowIterator
18 from gavo.utils import misctricks
19 from gavo.utils import parsetricks
20
21
22 class BinaryRowIterator(FileRowIterator):
23 """A row iterator reading from binary files.
24 """
25 fileMode = "rb"
26
27 def _iterUnarmoredRecords(self):
28 while True:
29 data = self.inputFile.read(self.grammar.fieldDefs.recordLength)
30 if data==b"":
31 return
32 yield data
33
34 def _iterInRecords(self):
35 self.inputFile.read(self.grammar.skipBytes)
36 if self.grammar.armor is None:
37 return self._iterUnarmoredRecords()
38 elif self.grammar.armor=="fortran":
39 return misctricks.iterFortranRecs(self.inputFile)
40 else:
41 assert False
42
43 def _iterRows(self):
44 fmtStr = self.grammar.fieldDefs.structFormat
45 fieldNames = self.grammar.fieldDefs.fieldNames
46 try:
47 for rawRec in self._iterInRecords():
48 yield dict(list(zip(fieldNames, struct.unpack(fmtStr, rawRec))))
49 except Exception as ex:
50 raise base.ui.logOldExc(base.SourceParseError(str(ex),
51 location="byte %s"%self.inputFile.tell(),
52 source=str(self.sourceToken)))
53
54
55 def _getFieldsGrammar():
56 with parsetricks.pyparsingWhitechars(" \n\t\r"):
57 identifier = parsetricks.Regex(utils.identifierPattern.pattern[:-1]
58 ).setName("identifier")
59 formatCode = parsetricks.Regex(r"\d+s|[bBhHiIqQfd]"
60 ).setName("fieldSpec")
61 field = ( identifier("identifier")
62 + parsetricks.Suppress(parsetricks.Literal("("))
63 + formatCode("formatCode")
64 + parsetricks.Suppress(parsetricks.Literal(")"))).setParseAction(
65 lambda s, p, t: dict(t))
66 return parsetricks.OneOrMore(field)+parsetricks.StringEnd()
67
68
69 class BinaryRecordDef(base.Structure):
70 """A definition of a binary record.
71
72 A binary records consists of a number of binary fields, each of which
73 is defined by a name and a format code. The format codes supported
74 here are a subset of what python's struct module supports. The
75 widths given below are for big, little, and packed binfmts.
76 For native (which is the default), it depends on your platform.
77
78 * <number>s -- <number> characters making up a string
79 * b,B -- signed and unsigned byte (8 bit)
80 * h,H -- signed and unsigned short (16 bit)
81 * i,I -- signed and unsigned int (32 bit)
82 * q,Q -- signed and unsigned long (64 bit)
83 * f,d -- float and double.
84
85 The content of this element gives the record structure in the format
86 <name>(<code>){<whitespace><name>(<code>)} where <name> is a c-style
87 identifier.
88 """
89 name_ = "binaryRecordDef"
90
91 _fieldsGrammar = _getFieldsGrammar()
92
93 _binfmt = base.EnumeratedUnicodeAttribute("binfmt",
94 default="native",
95 validValues=["big", "little", "native", "packed"],
96 description="Binary format of the input data; big and little stand"
97 " for msb first and lsb first, and"
98 " packed is like native except no alignment takes place.")
99
100 _fields = base.DataContent(description="The enumeration of"
101 " the record fields.")
102
103 _binfmtToStructCode = {
104 "native": "",
105 "packed": "=",
106 "big": ">",
107 "little": "<"}
108
109 def completeElement(self, ctx):
110 try:
111 parsedFields = utils.pyparseString(self._fieldsGrammar, self.content_)
112 except parsetricks.ParseBaseException as ex:
113 raise base.ui.logOldExc(base.LiteralParseError("binaryRecordDef",
114 re.sub(r"\s+", " ", self.content_),
115 pos=str(ex.loc), hint="The parser said: '%s'"%str(ex)))
116 # XXX TODO: Position should probably be position during XML parse.
117 # Fix when we have source positions on parsed elements.
118 self.structFormat = (self._binfmtToStructCode[self.binfmt]+
119 str("".join(f["formatCode"] for f in parsedFields)))
120 self.recordLength = struct.calcsize(self.structFormat)
121 self.fieldNames = tuple(f["identifier"] for f in parsedFields)
122 super().completeElement(ctx)
123
124
125 class BinaryGrammar(Grammar):
126 """A grammar that builds rowdicts from binary data.
127
128 The grammar expects the input to be in fixed-length records.
129 the actual specification of the fields is done via a binaryRecordDef
130 element.
131 """
132 name_ = "binaryGrammar"
133 rowIterator = BinaryRowIterator
134
135 _til = base.IntAttribute("skipBytes",
136 default=0,
137 description="Number of bytes to skip before parsing records.")
138
139 _fdefs = base.StructAttribute("fieldDefs",
140 description="Definition of the record.",
141 childFactory=BinaryRecordDef)
142
143 _armoring = base.EnumeratedUnicodeAttribute("armor",
144 default=None,
145 validValues=["fortran"],
146 description="Record armoring; by default it's None meaning the"
147 " data was dumped to the file sequentially. Set it to fortran"
148 " for fortran unformatted files (4 byte length before and after"
149 " the payload).")