Debian Codegraph @

importers/ding2tei/src/Language/Ding/AlexScanner.x

raw
1 -- Language/Ding/AlexScanner.x - lexer
2 --
3 -- Copyright 2020,2022 Einhard Leichtfuß
4 --
5 -- This file is part of ding2tei-haskell.
6 --
7 -- ding2tei-haskell is free software: you can redistribute it and/or modify
8 -- it under the terms of the GNU Affero General Public License as published
9 -- by the Free Software Foundation, either version 3 of the License, or
10 -- (at your option) any later version.
11 --
12 -- ding2tei-haskell is distributed in the hope that it will be useful,
13 -- but WITHOUT ANY WARRANTY; without even the implied warranty of
14 -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 -- GNU Affero General Public License for more details.
16 --
17 -- You should have received a copy of the GNU Affero General Public License
18 -- along with ding2tei-haskell. If not, see <https://www.gnu.org/licenses/>.
19
20
21 -- Notes:
22 -- * This file is supposed to be processed by Alex, "the lexical analyser
23 -- generator for Haskell". It contains both Alex code and regular Haskell
24 -- code. The result of Alex invocation is a regular Haskell source file.
25 -- * Alex User Guide: https://www.haskell.org/alex/#Documentation
26
27
28 {
29 -- Haskell module header and import statements.
30
31 module Language.Ding.AlexScanner (scan, AlexPosn) where
32
33
34 import Data.NatLang.Grammar
35 import Language.Ding.Token
36 }
37
38
39 -- In contrast to the "basic" wrapper, "posn" allows for keeping track of
40 -- positions.
41 %wrapper "posn"
42
43
44 -------------------------------------------------------------------------------
45 -- Definition of named character sets and regexes
46 -------------------------------------------------------------------------------
47
48 -- Notes:
49 -- * $x is a (named) character set
50 -- * @y is a (named) regular expression
51 -- * $x # $y is the set difference of $x and $y ($x - $y).
52 -- * See also: Alex User Guide, chapter 4.
53
54 $anyLeftBracket = [ \{ \( \[ \< ]
55 $anyRightBracket = [ \} \) \] \> ]
56 $anyBracket = [ $anyLeftBracket $anyRightBracket ]
57
58 -- Any character that may (!) have special semantics (incl. <:>), excluding
59 -- $slashSpecialChar.
60 -- Note that <:> is only included to avoid matching <::> as part of @word.
61 -- Some characters, in particular all single colons have to be merged with
62 -- their surrounding (e.g., text atoms) later.
63 $specialChar = [ $anyBracket : \| \; \, \/ \~ \+ ]
64
65 -- Characters that are special in that they may occur enclosed in slashes.
66 $slashSpecialChar = [ $specialChar \% \@ ]
67
68 $textChar = $printable # [$specialChar $white]
69
70 -- Anything printable, not containing a special char, nor whitespace.
71 @word = $textChar+
72
73 -- To allow infix whitespace, use the below (in place of @word):
74 -- @text = [$textChar # $white] ($textChar* [$textChar # $white])?
75
76 -- A left context that marks a slash as "left-free". This is used
77 -- particularly to identify "opening" and "closing" slashes, where the
78 -- former is "left-free", but not "right-free", as for example in
79 -- /abbrev./
80 -- Notes:
81 -- * This must not contain '.' ! (consider /abbrev./)
82 -- * Most interpunctuation is usually followed by a space.
83 -- * $white includes '\n' (which is desired).
84 $slashLeftFree = [ $white $anyLeftBracket ]
85
86 -- A right context that marks a slash as "right-free" (see just above).
87 -- This should in theory contain all interpunctuation (that does not require
88 -- preceding whitespace).
89 -- Note:
90 -- * Expand the interpunctuation character set as needed.
91 $slashRightFree = [ $white $anyRightBracket \; \, : \. \? ! ]
92
93 -- A non-empty sequence of slash-separated words (@slashWordList), which forms
94 -- a special case within slashes.
95 -- Notes:
96 -- * The final optional dot is redundant, as of now.
97 -- * This should not be used as generic word macro, as possibly desired for
98 -- "<>". (General mord macros should not allow a terminating '.'.)
99 -- * $textChar should possibly be replaced by something more sensible.
100 @slashWord = [$textChar # \/]+ (\.|\?)?
101 @slashWordList = @slashWord ("/" @slashWord)+
102
103 -- There is only one known smiley, as of now.
104 -- Smileys are treated as abbreviations.
105 @smiley = ":-)"
106
107 -- Abbreviations that cannot be easily parsed by normal means.
108 @specialAbbrev = @smiley | "/.ed"
109
110 $word_end = ~$textChar
111
112
113 -------------------------------------------------------------------------------
114 -- Mapping from regexes to Haskell functions (actions)
115 -------------------------------------------------------------------------------
116
117 -- Notes:
118 -- * The functions are expected to take a matched string and produce a
119 -- corresponding token.
120 -- * Because the "posn" wrapper is used (instead of "basic"), most such
121 -- functions have to be wrapped in `regularToken'.
122 -- * Alex takes longest matching sequences (maximal munch).
123 -- * If several rules match the same longest sequence, the first one of them
124 -- applies.
125 -- * The lexer should always succeed. Hence there is no special error
126 -- mechanism needed.
127 -- * This might change if the allowed whitespace characters are reduced.
128 -- * Also, if triple+ '/' should be caught at the lexer level.
129 -- * At the parser level, they'd be caught as successive '//', '/'.
130
131 tokens :-
132
133 -- A header line. To be parsed as is by Language.Ding.Parser.Header.
134 ^ \# .* $ { regularToken HeaderLine }
135
136
137 ---------------------------------------------------------------------------
138 -- Separators (excl. slashes and single angle brackets)
139
140 \n { regularToken $ const NL }
141
142 :: { regularToken $ const LangSep }
143 \| { regularToken $ const Vert }
144 \; { regularToken $ const Semi }
145 \, { regularToken $ const Comma }
146 \~ { regularToken $ const Tilde }
147 \+ { regularToken $ const Plus }
148 \<\> { regularToken $ const Wordswitch }
149
150 \{ { regularToken $ const OBrace }
151 \} { regularToken $ const CBrace }
152 \[ { regularToken $ const OBracket }
153 \] { regularToken $ const CBracket }
154 \( { regularToken $ const OParen }
155 \) { regularToken $ const CParen }
156
157
158 -- This is only caught explicitly, since it may not be caught as part of
159 -- @word (which could be changed, by complicating the regex--<::> would
160 -- still need to be excluded).
161 : { regularToken Text }
162
163
164 ---------------------------------------------------------------------------
165 -- Slashes
166
167 -- See doc/syntax.slashes
168
169 -- Divide slashes into categories.
170 -- Slashes have many roles (in particular one similar to brackets), but
171 -- unfortunately there are no different opening and closing '/'-characters.
172 -- Hence, infer such information from the context.
173 -- * (The description there is not strictly equivalent, but should be in all
174 -- practical cases.)
175
176 $slashLeftFree ^ "/" / $slashRightFree { regularToken $ const WeakSlash }
177 $slashLeftFree ^ "/" { regularToken $ const OSlash }
178 "/" / "..." { regularToken $ const StrongSlash }
179 "/" / $slashRightFree { regularToken $ const CSlash }
180 "/" { regularToken $ const StrongSlash }
181
182 -- Treat single special characters between free slashes differently.
183 -- This would typically be done in the parser, however it is difficult to
184 -- identify such expressions using a CFG.
185 -- Consider "+ / % / ~". Since "word+ / word+ / word+" is generally
186 -- permitted, this could not easily unambiguously parsed. (Note that the
187 -- "correct" parsing in this case is unclear.
188 $slashLeftFree ^ "/ " $specialChar " /" / $slashRightFree {
189 regularToken $ SlashSpecial . pure . (!!2) }
190
191 $slashLeftFree ^ "/ " @specialAbbrev " /" / $slashRightFree {
192 regularToken $ Abbrev . dropLast 2 . drop 2 }
193
194 -- Treat stuff like "/ AC/DC /" also as a special case. This is because,
195 -- in general, strong slashes may occur in between weak slashes. For this
196 -- reason, this rule may actually incorrectly catch such cases. However,
197 -- the ambiguity needs to be taken care of somehow and this is the best
198 -- way known to me.
199
200 -- The dropLast part would be more efficient if the "monad" or
201 -- "monadUserState" wrapper was used (one gets the length of the input).
202 $slashLeftFree ^ "/ " @slashWordList " /" / $slashRightFree {
203 regularToken $ Abbrev . dropLast 2 . drop 2 }
204
205 -- An awkward special case that cannot (easily) be handled otherwise:
206 $white ^ \"\/\.ed\" / $white {
207 regularToken $ Abbrev . dropLast 1 . drop 1 }
208 -- "
209
210 -- Plural abbreviations.
211 -- Note: No more than one word between the slashes is permitted.
212 -- Otherwise, lexing + parsing would become more difficult.
213 $slashLeftFree ^ "/" @slashWord "/s" / $slashRightFree {
214 regularToken $ AbbrevPlural . dropLast 2 . drop 1 }
215
216 -- Double slashes are used (onserved once) to bind two adjacent alternative
217 -- expressions (bound by a strong slash).
218 -- Semantic: "a/b//c/d" -> (a or b) or (c or d)
219 "//" { regularToken $ const DoubleSlash }
220
221
222 ---------------------------------------------------------------------------
223 -- Angle brackets
224
225 -- Angle brackets are special in that they also may signify less- resp.
226 -- greater-than. Fortunately, they are, when brackets, always close to the
227 -- enclosed object. Treat similar to left and right slashes.
228 -- Important: This rule must be above the generic \< and \> rule(s).
229 $slashLeftFree ^ [\< \>] / $slashRightFree { regularToken Text }
230
231 \< { regularToken $ const OAngle }
232 \> { regularToken $ const CAngle }
233
234
235 ---------------------------------------------------------------------------
236 -- Keywords
237
238 -- Note:
239 -- * Multi-word keywords need to be given the right context $word_end.
240 -- * This ensures that the word ends there.
241 -- * Ex.: Let "a b" be a multi-word keyword, and "a bc " at the start of
242 -- the character stream. This should be matched as two text tokens, "a"
243 -- and "bc", not as keyword "a b" and text "c".
244
245 "to" { regularToken $ const KW_to }
246
247 -- Grammar keywords
248 "f" { gramKW $ Gender Feminine }
249 "m" { gramKW $ Gender Masculine }
250 "n" { gramKW $ Gender Neuter }
251 "sing" { gramKW $ Number $ Singular False }
252 "pl" { gramKW $ Number $ Plural False }
253 "no pl" / $word_end { gramKW $ Number $ Singular True }
254 "no sing" / $word_end { gramKW $ Number $ Plural True }
255 --
256 "v" { gramKW $ PartOfSpeech $ Verb [] }
257 "vt" { gramKW $ PartOfSpeech $ Verb [Transitive] }
258 "vi" { gramKW $ PartOfSpeech $ Verb [Intransitive] }
259 "vr" { gramKW $ PartOfSpeech $ Verb [Reflexive] }
260 "adj" { gramKW $ PartOfSpeech Adjective }
261 "adv" { gramKW $ PartOfSpeech Adverb }
262 "prp" { gramKW $ PartOfSpeech Preposition }
263 "conj" { gramKW $ PartOfSpeech Conjunction }
264 "art" { gramKW $ PartOfSpeech Article }
265 "pron" { gramKW $ PartOfSpeech $ Pronoun [] }
266 "ppron" { gramKW $ PartOfSpeech $ Pronoun [Personal] }
267 "pron interrog" / $word_end { gramKW $ PartOfSpeech $
268 Pronoun [Interrogative] }
269 "pron relativ" / $word_end { gramKW $ PartOfSpeech $
270 Pronoun [Relative] }
271 "num" { gramKW $ PartOfSpeech Numeral }
272 "interj" { gramKW $ PartOfSpeech Interjection }
273 "Partikel" { gramKW $ PartOfSpeech Particle }
274 "particle" { gramKW $ PartOfSpeech Particle }
275 --
276 "Gen." { gramKW $ Case Genitive }
277 "Akk." { gramKW $ Case Accusative }
278 "Dat." { gramKW $ Case Dative }
279 "Nom." { gramKW $ Case Nominative }
280
281 -- Interrogative pronouns (not grammar keywords in the strict sense)
282 "wo?" { regularToken IntPronKW }
283 "wohin?" { regularToken IntPronKW }
284 "wann?" { regularToken IntPronKW }
285 "bis wann?" / $word_end { regularToken IntPronKW }
286
287 -- Regular word / text token
288 -- Note:
289 -- * This must come after all the specific keywords, or else this rule
290 -- would be prefered over them (the single word keywords, to be precise).
291 @word { regularToken Text }
292
293 -- Whitespace
294 -- Note:
295 -- * Newlines do not count as whitespace, they serve as line separators,
296 -- where a line is a well defined Ding entity.
297 [$white # \n]+ { const Whitespace }
298
299
300 {
301 -------------------------------------------------------------------------------
302 -- Auxiliary Haskell code.
303 -------------------------------------------------------------------------------
304
305 -- | A simple token, as identified by Alex.
306 data SimpleToken = RegularToken Position Atom
307 | Whitespace String
308
309
310 -- | An action helper for regular tokens, to take care of the AlexPosn.
311 regularToken :: (String -> Atom) -> AlexPosn -> String -> SimpleToken
312 regularToken f p s = RegularToken (toPosition p) (f s)
313
314 gramKW :: GramLexCategory -> AlexPosn -> String -> SimpleToken
315 gramKW gram p _ = RegularToken (toPosition p) (GramKW gram)
316
317 toPosition :: AlexPosn -> Position
318 toPosition (AlexPn _abs line col) = Position line col
319
320
321 -- | Remove the whitespace from the token stream towards the respective
322 -- following regular token, as annotation.
323 mergeWS :: [SimpleToken] -> [Token]
324
325 -- Notes
326 -- * There can never be two whitespace tokens in succession.
327 -- * One could use `foldr' here, but this is not very straightforward - the
328 -- folding function (in some cases) has to inspect the first element of its
329 -- list argument, which therefore is inspected twice (in such cases).
330
331 mergeWS ( RegularToken pos atom : toks) =
332 Token "" pos atom : mergeWS toks
333
334 mergeWS (Whitespace ws : RegularToken pos atom : toks) =
335 Token ws pos atom : mergeWS toks
336
337 mergeWS (Whitespace _ : Whitespace _ : _) =
338 error "Language.Ding.AlexScanner: two successive whitespace tokens"
339
340 -- Ignore terminating whitespace.
341 mergeWS (Whitespace _ : []) = []
342 mergeWS [] = []
343
344
345 -- | Drop the given number of last elements.
346 dropLast :: Int -> [a] -> [a]
347 dropLast n xs = take (length xs - n) xs
348
349
350 -- | Convert a string into a stream of tokens.
351 scan :: String -> [Token]
352 scan = mergeWS . alexScanTokens
353 }
354
355 -- vi: ft=haskell ts=2 sw=2 et