Debian Codegraph @

gavo/grammars/freeregrammar.py

raw
1 """
2 A grammar based on repeated application of REs
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
13 from gavo import base
14 from gavo import utils
15 from gavo.grammars import common
16 from gavo.grammars import regrammar
17
18
19 _onlyWhitespaceLeft = re.compile(r"\s*$")
20
21 class RowIterator(common.FileRowIterator):
22 chunkSize = 8192
23
24 def _iterRecords(self):
25 curPos, buffer = 0, ""
26 recPat = self.grammar.rowProduction
27
28 if self.grammar.ignoreJunk:
29 getNext = recPat.search
30 else:
31 getNext = recPat.match
32
33 while True:
34 mat = getNext(buffer, curPos)
35 if not mat: # no match, fetch new stuff.
36 newStuff = self.inputFile.read(self.chunkSize)
37 if not newStuff: # file exhausted
38 break
39 buffer = buffer[curPos:]+newStuff
40 curPos = 0
41 continue
42 res = mat.group()
43 yield res
44 curPos = mat.end()
45 self.curLine += res.count("\n")
46 buffer = buffer[curPos:]
47 if not self.grammar.ignoreJunk and not _onlyWhitespaceLeft.match(buffer):
48 raise utils.SourceParseError("Junk at end of file",
49 location=self.getLocator(),
50 offending=buffer)
51
52 def _iterRows(self):
53 for rawRec in self._iterRecords():
54 try:
55 res = self.grammar.parseRE.match(rawRec).groupdict()
56 if self.grammar.stripTokens:
57 res = dict((k, v.strip()) for k, v in res.items())
58 yield res
59 except AttributeError:
60 raise base.ui.logOldExc(
61 utils.SourceParseError("Malformed input, parseRE did not match.",
62 location=self.getLocator(),
63 offending=rawRec))
64
65 def getLocator(self):
66 return "%s, line %d"%(self.sourceToken, self.curLine)
67
68
69 class FreeREGrammar(common.Grammar):
70 """A grammar allowing "free" regular expressions to parse a document.
71
72 Basically, you give a rowProduction to match individual records in the
73 document. All matches of rowProduction will then be matched with
74 parseRE, which in turn must have named groups. The dictionary from
75 named groups to their matches makes up the input row.
76
77 For writing the parseRE, we recommend writing an element, using a
78 CDATA construct, and taking advantage of python's "verbose" regular
79 expressions. Here's an example::
80
81 <parseRE><![CDATA[(?xsm)^name::(?P<name>.*)
82 ^query::(?P<query>.*)
83 ^description::(?P<description>.*)\\.\\.
84 ]]></parseRE>
85 """
86 name_ = "freeREGrammar"
87
88 _rowProduction = regrammar.REAttribute("rowProduction",
89 default=re.compile(r"(?m)^.+$\n"), description="RE matching a complete"
90 " record.")
91 _parseRE = regrammar.REAttribute("parseRE", default=base.Undefined,
92 description="RE containing named groups matching a record")
93 _stripTokens = base.BooleanAttribute("stripTokens", default=False,
94 description="Strip whitespace from result tokens?")
95 _ignoreJunk = base.BooleanAttribute("ignoreJunk", default=False,
96 description="Ignore everything outside of the row production")
97 rowIterator = RowIterator