Debian Codegraph @

gavo/grammars/columngrammar.py

raw
1 """
2 A grammar that just splits the source into input lines and then
3 lets you name character ranges.
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 from gavo import base
13 from gavo import utils
14 from gavo.grammars.common import (
15 Grammar, FileRowIterator, FileRowAttributes, REAttribute)
16 from gavo.utils import parsetricks
17
18
19 class SplitLineIterator(FileRowIterator):
20 def __init__(self, grammar, sourceToken, **kwargs):
21 FileRowIterator.__init__(self, grammar, sourceToken, **kwargs)
22 for i in range(self.grammar.topIgnoredLines):
23 self.inputFile.readline()
24 self.lineNo = self.grammar.topIgnoredLines
25
26 def _iterRows(self):
27 while True:
28 self.lineNo += 1
29 inputLine = self.inputFile.readline()
30 if not inputLine:
31 break
32 if self.grammar.endMarker:
33 if self.grammar.endMarker.match(inputLine):
34 break
35
36 if (self.grammar.commentIntroducer is not base.NotGiven
37 and inputLine.startswith(self.grammar.commentIntroducer)):
38 continue
39
40 res = self._parse(inputLine)
41 yield res
42 self.recNo += 1
43
44 self.inputFile.close()
45 self.grammar = None
46
47 def _parse(self, inputLine):
48 res = {}
49 try:
50 for key, slice in self.grammar.colRanges.items():
51 if self.grammar.strip:
52 res[key] = inputLine[slice].strip()
53 else:
54 res[key] = inputLine[slice]
55 except IndexError:
56 raise base.ui.logOldExc(base.SourceParseError("Short line", inputLine,
57 self.getLocator(), self.sourceToken))
58 return res
59
60 def getLocator(self):
61 return "line %d"%self.lineNo
62
63
64 class ColRangeAttribute(base.AtomicAttribute):
65 """A range of indices.
66
67 Ranges can be specified as either <int1>-<int2>, just <int>
68 (which is equivalent to <int>-<int>), or as half-open ranges
69 (<int>- or -<int>) Ranges are, contrary to
70 python slices, inclusive on both sides, and start counting
71 from one.
72 """
73 def parse(self, value):
74 if isinstance(value, slice):
75 # we're already parsed
76 return value
77
78 try:
79 if "-" in value:
80 startLit, endLit = value.split("-")
81 start, end = None, None
82 if startLit.strip():
83 start = int(startLit)-1
84 if endLit.strip():
85 end = int(endLit)
86 return slice(start, end)
87 else:
88 col = int(value)
89 return slice(col-1, col)
90 except ValueError:
91 raise base.ui.logOldExc(
92 base.LiteralParseError("colRanges", value, hint="A column range,"
93 " (either int1-int2 or just an int) is expected here."))
94
95 def unparse(self, value):
96 return f"{value.start}-{value.stop}"
97
98
99 class ColumnGrammar(Grammar, FileRowAttributes):
100 """A grammar that builds rowdicts out of character index ranges.
101
102 This works by using the colRanges attribute like <col key="mag">12-16</col>,
103 which will take the characters 12 through 16 inclusive from each input
104 line to build the input column mag.
105
106 As a shortcut, you can also use the colDefs attribute; it contains
107 a string of the form {<key>:<range>}, i.e.,
108 a whitespace-separated list of colon-separated items of key and range
109 as accepted by cols, e.g.::
110
111 <colDefs>
112 a: 3-4
113 _u: 7
114 </colDefs>
115 """
116 name_ = "columnGrammar"
117
118 _til = base.IntAttribute("topIgnoredLines", default=0, description=
119 "Skip this many lines at the top of each source file.",
120 copyable=True)
121 _cols = base.DictAttribute("colRanges", description="Mapping of"
122 " source keys to column ranges.", itemAttD=ColRangeAttribute("col"),
123 aliases=["col"], copyable=True)
124 _colDefs = base.ActionAttribute("colDefs", description="Shortcut"
125 " way of defining cols", methodName="_parseColDefs")
126 _commentIntroducer = base.UnicodeAttribute("commentIntroducer",
127 default=base.NotGiven, description="A character sequence"
128 " that, when found at the beginning of a line makes this line"
129 " ignored", copyable=True)
130 _strip = base.BooleanAttribute("strip", default=True,
131 description="Strip all parsed strings?", copyable=True)
132 _endMarker = REAttribute("endMarker",
133 description="A regular expression that, when it matches an"
134 " entire line read, stops processing. This is for when"
135 " there is trailing junk in files.", copyable=True)
136
137 def _getColDefGrammar(self):
138 with parsetricks.pyparsingWhitechars("\n\t\r "):
139 intLiteral = parsetricks.Word(parsetricks.nums)
140 # need to manually swallow whitespace after literals
141 blindWhite = parsetricks.Suppress(parsetricks.Optional(parsetricks.White()))
142 dash = blindWhite + parsetricks.Literal("-") + blindWhite
143
144 range = parsetricks.Combine(
145 dash + blindWhite + intLiteral
146 | intLiteral + parsetricks.Optional(dash + parsetricks.Optional(intLiteral)))
147 range.setName("Column range")
148
149 identifier = parsetricks.Regex(utils.identifierPattern.pattern[:-1])
150 identifier.setName("Column key")
151
152 clause = (identifier + parsetricks.Literal(":") + blindWhite + range
153 ).addParseAction(lambda s,p,t: (t[0], t[2]))
154 colDefs = parsetricks.ZeroOrMore(clause)+parsetricks.StringEnd()
155 # range.setDebug(True);identifier.setDebug(True);clause.setDebug(True)
156 return colDefs
157
158 def _parseColDefs(self, ctx):
159 # the handler for colDefs -- parse shortcut colDefs
160 try:
161 for key, range in utils.pyparseString(self._getColDefGrammar(),
162 self.colDefs):
163 self.colRanges[key] = self._cols.itemAttD.parse(range)
164 except parsetricks.ParseException as ex:
165 raise base.LiteralParseError("colDefs", self.colDefs,
166 hint="colDefs is a whitespace-separated list of key:range pairs."
167 " Your literal doesn't look like this, and here's what the"
168 " parser had to complain: %s"%ex)
169
170
171 rowIterator = SplitLineIterator