Debian Codegraph @

c2hs/chs/CHS.hs

raw symbols SCIP
1 -- C->Haskell Compiler: CHS file abstraction
2 --
3 -- Author : Manuel M T Chakravarty
4 -- Created: 16 August 99
5 --
6 -- Version $Revision: 1.3 $ from $Date: 2005/01/23 15:44:36 $
7 --
8 -- Copyright (c) [1999..2004] Manuel M T Chakravarty
9 --
10 -- This file is free software; you can redistribute it and/or modify
11 -- it under the terms of the GNU General Public License as published by
12 -- the Free Software Foundation; either version 2 of the License, or
13 -- (at your option) any later version.
14 --
15 -- This file is distributed in the hope that it will be useful,
16 -- but WITHOUT ANY WARRANTY; without even the implied warranty of
17 -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 -- GNU General Public License for more details.
19 --
20 --- DESCRIPTION ---------------------------------------------------------------
21 --
22 -- Main file for reading CHS files.
23 --
24 -- Import hooks & .chi files
25 -- -------------------------
26 --
27 -- Reading of `.chi' files is interleaved with parsing. More precisely,
28 -- whenever the parser comes across an import hook, it immediately reads the
29 -- `.chi' file and inserts its contents into the abstract representation of
30 -- the hook. The parser checks the version of the `.chi' file, but does not
31 -- otherwise attempt to interpret its contents. This is only done during
32 -- generation of the binding module. The first line of a .chi file has the
33 -- form
34 --
35 -- C->Haskell Interface Version <version>
36 --
37 -- where <version> is the three component version number `Version.version'.
38 -- C->Haskell will only accept files whose version number match its own in
39 -- the first two components (ie, major and minor version). In other words,
40 -- it must be guaranteed that the format of .chi files is not altered between
41 -- versions that differ only in their patchlevel. All remaining lines of the
42 -- file are version dependent and contain a dump of state information that
43 -- the binding file generator needs to rescue across modules.
44 --
45 --- DOCU ----------------------------------------------------------------------
46 --
47 -- language: Haskell 98
48 --
49 -- The following binding hooks are recognised:
50 --
51 -- hook -> `{#' inner `#}'
52 -- inner -> `import' ['qualified'] ident
53 -- | `context' ctxt
54 -- | `type' ident
55 -- | `sizeof' ident
56 -- | `enum' idalias trans [`with' prefix] [deriving]
57 -- | `call' [`pure'] [`unsafe'] [`nolock'] idalias
58 -- | `fun' [`pure'] [`unsafe'] [`nolock'] idalias parms
59 -- | `get' apath
60 -- | `set' apath
61 -- | `pointer' ['*'] idalias ptrkind
62 -- | `class' [ident `=>'] ident ident
63 -- ctxt -> [`lib' `=' string] [prefix] [lock]
64 -- idalias -> ident [`as' (ident | `^')]
65 -- prefix -> `prefix' `=' string
66 -- lock -> `lock' `=' string
67 -- deriving -> `deriving' `(' ident_1 `,' ... `,' ident_n `)'
68 -- parms -> [verbhs `=>'] `{' parm_1 `,' ... `,' parm_n `}' `->' parm
69 -- parm -> [ident_1 [`*' | `-']] verbhs [`&'] [ident_2 [`*' | `-']]
70 -- apath -> ident
71 -- | `*' apath
72 -- | apath `.' ident
73 -- | apath `->' ident
74 -- trans -> `{' alias_1 `,' ... `,' alias_n `}'
75 -- alias -> `underscoreToCase'
76 -- | ident `as' ident
77 -- ptrkind -> [`foreign' | `stable' ] ['newtype' | '->' ident]
78 --
79 -- If `underscoreToCase' occurs in a translation table, it must be the first
80 -- entry.
81 --
82 -- Remark: Optional Haskell names are normalised during structure tree
83 -- construction, ie, associations that associated a name with itself
84 -- are removed. (They don't carry semantic content, and make some
85 -- tests more complicated.)
86 --
87 --- TODO ----------------------------------------------------------------------
88 --
89
90 module CHS (CHSModule(..), CHSFrag(..), CHSHook(..), CHSTrans(..), CHSParm(..),
91 CHSArg(..), CHSAccess(..), CHSAPath(..), CHSPtrType(..),
92 skipToLangPragma, hasCPP,
93 loadCHS, dumpCHS, hssuffix, chssuffix, loadAllCHI, loadCHI, dumpCHI,
94 chisuffix, showCHSParm)
95 where
96
97 -- standard libraries
98 import Data.Char (isSpace, toUpper, toLower)
99 import Data.List (intersperse)
100 import Control.Monad (when, unless)
101
102 -- Compiler Toolkit
103 import Position (Position(..), Pos(posOf), nopos, isBuiltinPos)
104 import Errors (interr)
105 import Idents (Ident, identToLexeme, onlyPosIdent)
106
107 -- C->Haskell
108 import C2HSState (CST, nop, doesFileExistCIO, readFileCIO, writeFileCIO, getId,
109 getSwitch, chiPathSB, catchExc, throwExc, raiseError,
110 fatal, errorsPresent, showErrors, Traces(..), putTraceStr)
111
112 -- friends
113 import CHSLexer (CHSToken(..), lexCHS)
114
115
116 -- CHS abstract syntax
117 -- -------------------
118
119 -- representation of a CHS module (EXPORTED)
120 --
121 data CHSModule = CHSModule [CHSFrag]
122
123 -- a CHS code fragament (EXPORTED)
124 --
125 -- * `CHSVerb' fragments are present throughout the compilation and finally
126 -- they are the only type of fragment (describing the generated Haskell
127 -- code)
128 --
129 -- * `CHSHook' are binding hooks, which are being replaced by Haskell code by
130 -- `GenBind.expandHooks'
131 --
132 -- * `CHSCPP' and `CHSC' are fragments of C code that are being removed when
133 -- generating the custom C header in `GenHeader.genHeader'
134 --
135 -- * `CHSCond' are strutured conditionals that are being generated by
136 -- `GenHeader.genHeader' from conditional CPP directives (`CHSCPP')
137 --
138 data CHSFrag = CHSVerb String -- Haskell code
139 Position
140 | CHSHook CHSHook -- binding hook
141 | CHSCPP String -- pre-processor directive
142 Position
143 | CHSLine Position -- line pragma
144 | CHSC String -- C code
145 Position
146 | CHSCond [(Ident, -- C variable repr. condition
147 [CHSFrag])] -- then/elif branches
148 (Maybe [CHSFrag]) -- else branch
149 | CHSLang [String] -- GHC language pragma
150 Position
151
152 instance Pos CHSFrag where
153 posOf (CHSVerb _ pos ) = pos
154 posOf (CHSHook hook ) = posOf hook
155 posOf (CHSCPP _ pos ) = pos
156 posOf (CHSLine pos ) = pos
157 posOf (CHSC _ pos ) = pos
158 posOf (CHSCond alts _) = case alts of
159 (_, frag:_):_ -> posOf frag
160 _ -> nopos
161 posOf (CHSLang _ pos) = pos
162
163 -- a CHS binding hook (EXPORTED)
164 --
165 data CHSHook = CHSImport Bool -- qualified?
166 Ident -- module name
167 String -- content of .chi file
168 Position
169 | CHSContext (Maybe String) -- library name
170 (Maybe String) -- prefix
171 (Maybe String) -- lock function
172 Position
173 | CHSType Ident -- C type
174 Position
175 | CHSSizeof Ident -- C type
176 Position
177 | CHSEnum Ident -- C enumeration type
178 (Maybe Ident) -- Haskell name
179 CHSTrans -- translation table
180 (Maybe String) -- local prefix
181 [Ident] -- instance requests from user
182 Position
183 | CHSCall Bool -- is a pure function?
184 Bool -- is unsafe?
185 Bool -- is without lock?
186 Ident -- C function
187 (Maybe Ident) -- Haskell name
188 Position
189 | CHSFun Bool -- is a pure function?
190 Bool -- is unsafe?
191 Bool -- is without lock?
192 Ident -- C function
193 (Maybe Ident) -- Haskell name
194 (Maybe String) -- type context
195 [CHSParm] -- argument marshalling
196 CHSParm -- result marshalling
197 Position
198 | CHSField CHSAccess -- access type
199 CHSAPath -- access path
200 Position
201 | CHSPointer Bool -- explicit '*' in hook
202 Ident -- C pointer name
203 (Maybe Ident) -- Haskell name
204 CHSPtrType -- Ptr, ForeignPtr or StablePtr
205 Bool -- create new type?
206 (Maybe Ident) -- Haskell type pointed to
207 Position
208 | CHSClass (Maybe Ident) -- superclass
209 Ident -- class name
210 Ident -- name of pointer type
211 Position
212
213 instance Pos CHSHook where
214 posOf (CHSImport _ _ _ pos) = pos
215 posOf (CHSContext _ _ _ pos) = pos
216 posOf (CHSType _ pos) = pos
217 posOf (CHSSizeof _ pos) = pos
218 posOf (CHSEnum _ _ _ _ _ pos) = pos
219 posOf (CHSCall _ _ _ _ _ pos) = pos
220 posOf (CHSFun _ _ _ _ _ _ _ _ pos) = pos
221 posOf (CHSField _ _ pos) = pos
222 posOf (CHSPointer _ _ _ _ _ _ pos) = pos
223 posOf (CHSClass _ _ _ pos) = pos
224
225 -- two hooks are equal if they have the same Haskell name and reference the
226 -- same C object
227 --
228 instance Eq CHSHook where
229 (CHSImport qual1 ide1 _ _) == (CHSImport qual2 ide2 _ _) =
230 qual1 == qual2 && ide1 == ide2
231 (CHSContext olib1 opref1 olock1 _ ) ==
232 (CHSContext olib2 opref2 olock2 _ ) =
233 olib1 == olib1 && opref1 == opref2 && olock1 == olock2
234 (CHSType ide1 _) == (CHSType ide2 _) =
235 ide1 == ide2
236 (CHSSizeof ide1 _) == (CHSSizeof ide2 _) =
237 ide1 == ide2
238 (CHSEnum ide1 oalias1 _ _ _ _) == (CHSEnum ide2 oalias2 _ _ _ _) =
239 oalias1 == oalias2 && ide1 == ide2
240 (CHSCall _ _ _ ide1 oalias1 _) == (CHSCall _ _ _ ide2 oalias2 _) =
241 oalias1 == oalias2 && ide1 == ide2
242 (CHSFun _ _ _ ide1 oalias1 _ _ _ _)
243 == (CHSFun _ _ _ ide2 oalias2 _ _ _ _) =
244 oalias1 == oalias2 && ide1 == ide2
245 (CHSField acc1 path1 _) == (CHSField acc2 path2 _) =
246 acc1 == acc2 && path1 == path2
247 (CHSPointer _ ide1 oalias1 _ _ _ _)
248 == (CHSPointer _ ide2 oalias2 _ _ _ _) =
249 ide1 == ide2 && oalias1 == oalias2
250 (CHSClass _ ide1 _ _) == (CHSClass _ ide2 _ _) =
251 ide1 == ide2
252 _ == _ = False
253
254 -- translation table (EXPORTED)
255 --
256 data CHSTrans = CHSTrans Bool -- underscore to case?
257 [(Ident, Ident)] -- alias list
258
259 -- marshalling descriptor for function hooks (EXPORTED)
260 --
261 -- * a marshaller consists of a function name and flag indicating whether it
262 -- has to be executed in the IO monad
263 --
264 data CHSParm = CHSParm (Maybe (Ident, CHSArg)) -- "in" marshaller
265 String -- Haskell type
266 Bool -- C repr: two values?
267 (Maybe (Ident, CHSArg)) -- "out" marshaller
268 Position
269
270 -- kinds of arguments in function hooks (EXPORTED)
271 --
272 data CHSArg = CHSValArg -- plain value argument
273 | CHSIOArg -- reference argument
274 | CHSVoidArg -- no argument
275 deriving (Eq)
276
277 -- structure member access types (EXPORTED)
278 --
279 data CHSAccess = CHSSet -- set structure field
280 | CHSGet -- get structure field
281 deriving (Eq)
282
283 -- structure access path (EXPORTED)
284 --
285 data CHSAPath = CHSRoot Ident -- root of access path
286 | CHSDeref CHSAPath Position -- dereferencing
287 | CHSRef CHSAPath Ident -- member referencing
288 deriving (Eq)
289
290 -- pointer options (EXPORTED)
291 --
292
293 data CHSPtrType = CHSPtr -- standard Ptr from Haskell
294 | CHSForeignPtr -- a pointer with a finalizer
295 | CHSStablePtr -- a pointer into Haskell land
296 deriving (Eq)
297
298 instance Show CHSPtrType where
299 show CHSPtr = "Ptr"
300 show CHSForeignPtr = "ForeignPtr"
301 show CHSStablePtr = "StablePtr"
302
303 instance Read CHSPtrType where
304 readsPrec _ ( 'P':'t':'r':rest) =
305 [(CHSPtr, rest)]
306 readsPrec _ ('F':'o':'r':'e':'i':'g':'n':'P':'t':'r':rest) =
307 [(CHSForeignPtr, rest)]
308 readsPrec _ ('S':'t':'a':'b':'l':'e' :'P':'t':'r':rest) =
309 [(CHSStablePtr, rest)]
310 readsPrec p (c:cs)
311 | isSpace c = readsPrec p cs
312 readsPrec _ _ = []
313
314
315 -- return a modified module description that starts off with a LANGUAGE pragma
316 -- if it contains a LANGUAGE pragma at all
317 skipToLangPragma :: CHSModule -> Maybe CHSModule
318 skipToLangPragma (CHSModule frags) = hLP frags
319 where
320 hLP all@(CHSLang exts _:_) = Just (CHSModule all)
321 hLP (x:xs) = hLP xs
322 hLP [] = Nothing
323
324 -- test if the language pragma contains the CPP option
325 hasCPP :: CHSModule -> Bool
326 hasCPP (CHSModule (CHSLang exts _:_)) = "CPP" `elem` exts
327 hasCPP _ = False
328
329 -- load and dump a CHS file
330 -- ------------------------
331
332 hssuffix, chssuffix :: String
333 hssuffix = ".hs"
334 chssuffix = ".chs"
335
336 -- parse a CHS module (EXPORTED)
337 --
338 -- * in case of a syntactical or lexical error, a fatal error is raised;
339 -- warnings are returned together with the module
340 --
341 loadCHS :: FilePath -> CST s (CHSModule, String)
342 loadCHS fname = do
343 -- parse
344 --
345 traceInfoRead fname
346 contents <- readFileCIO fname
347 traceInfoParse
348 mod <- parseCHSModule (Position fname 1 1) contents
349
350 -- check for errors and finalize
351 --
352 errs <- errorsPresent
353 if errs
354 then do
355 traceInfoErr
356 errmsgs <- showErrors
357 fatal ("CHS module contains \
358 \errors:\n\n" ++ errmsgs) -- fatal error
359 else do
360 traceInfoOK
361 warnmsgs <- showErrors
362 return (mod, warnmsgs)
363 where
364 traceInfoRead fname = putTraceStr tracePhasesSW
365 ("Attempting to read file `"
366 ++ fname ++ "'...\n")
367 traceInfoParse = putTraceStr tracePhasesSW
368 ("...parsing `"
369 ++ fname ++ "'...\n")
370 traceInfoErr = putTraceStr tracePhasesSW
371 ("...error(s) detected in `"
372 ++ fname ++ "'.\n")
373 traceInfoOK = putTraceStr tracePhasesSW
374 ("...successfully loaded `"
375 ++ fname ++ "'.\n")
376
377 -- given a file name (no suffix) and a CHS module, the module is printed
378 -- into that file (EXPORTED)
379 --
380 -- * the module can be flagged as being pure Haskell
381 --
382 -- * the correct suffix will automagically be appended
383 --
384 dumpCHS :: String -> CHSModule -> Bool -> CST s ()
385 dumpCHS fname mod pureHaskell =
386 do
387 let (suffix, kind) = if pureHaskell
388 then (hssuffix , "(Haskell)")
389 else (chssuffix, "(C->HS binding)")
390 (version, _, _) <- getId
391 writeFileCIO (fname ++ suffix) (contents version kind)
392 where
393 contents version kind | hasCPP mod = showCHSModule mod pureHaskell
394 | otherwise =
395 "-- GENERATED by " ++ version ++ " " ++ kind ++ "\n\
396 \-- Edit the ORIGINAL .chs file instead!\n\n"
397 ++ showCHSModule mod pureHaskell
398
399 -- to keep track of the current state of the line emission automaton
400 --
401 data LineState = Emit -- emit LINE pragma if next frag is Haskell
402 | Wait -- emit LINE pragma after the next '\n'
403 | NoLine -- no pragma needed
404 deriving (Eq)
405
406 -- convert a CHS module into a string
407 --
408 -- * if the second argument is `True', all fragments must contain Haskell code
409 --
410 showCHSModule :: CHSModule -> Bool -> String
411 showCHSModule (CHSModule frags) pureHaskell =
412 showFrags pureHaskell Emit frags []
413 where
414 -- the second argument indicates whether the next fragment (if it is
415 -- Haskell code) should be preceded by a LINE pragma; in particular
416 -- generated fragments and those following them need to be prefixed with a
417 -- LINE pragma
418 --
419 showFrags :: Bool -> LineState -> [CHSFrag] -> ShowS
420 showFrags _ _ [] = id
421 showFrags pureHs state (CHSVerb s pos : frags) =
422 let
423 (Position fname line _) = pos
424 generated = isBuiltinPos pos
425 emitNow = state == Emit ||
426 (state == Wait && not (null s) && nlStart)
427 nlStart = head s == '\n'
428 nextState = if generated then Wait else NoLine
429 in
430 (if emitNow then
431 showString ("\n{-# LINE " ++ show (line `max` 0) ++ " " ++
432 show fname ++ " #-}" ++
433 (if nlStart then "" else "\n"))
434 else id)
435 . showString s
436 . showFrags pureHs nextState frags
437 showFrags False _ (CHSHook hook : frags) =
438 showString "{#"
439 . showCHSHook hook
440 . showString "#}"
441 . showFrags False Wait frags
442 showFrags False _ (CHSCPP s _ : frags) =
443 showChar '#'
444 . showString s
445 -- . showChar '\n'
446 . showFrags False Emit frags
447 showFrags pureHs _ (CHSLine s : frags) =
448 showFrags pureHs Emit frags
449 showFrags False _ (CHSC s _ : frags) =
450 showString "\n#c"
451 . showString s
452 . showString "\n#endc"
453 . showFrags False Emit frags
454 showFrags False _ (CHSCond _ _ : frags) =
455 interr "showCHSFrag: Cannot print `CHSCond'!"
456 showFrags pureHs _ (CHSLang exts _ : frags) =
457 let extsNoCPP = filter ((/=) "CPP") exts in
458 if null extsNoCPP then showFrags pureHs Emit frags else
459 showString "{-# LANGUAGE "
460 . showString (concat (intersperse "," extsNoCPP))
461 . showString " #-}\n"
462 . showFrags pureHs Emit frags
463 showFrags True _ _ =
464 interr "showCHSFrag: Illegal hook, cpp directive, or inline C code!"
465
466 showCHSHook :: CHSHook -> ShowS
467 showCHSHook (CHSImport isQual ide _ _) =
468 showString "import "
469 . (if isQual then showString "qualified " else id)
470 . showCHSIdent ide
471 showCHSHook (CHSContext olib oprefix olock _) =
472 showString "context "
473 . (case olib of
474 Nothing -> showString ""
475 Just lib -> showString "lib = " . showString lib . showString " ")
476 . showPrefix oprefix False
477 . (case olock of
478 Nothing -> showString ""
479 Just lock -> showString "lock = " . showString lock . showString " ")
480 showCHSHook (CHSType ide _) =
481 showString "type "
482 . showCHSIdent ide
483 showCHSHook (CHSSizeof ide _) =
484 showString "sizeof "
485 . showCHSIdent ide
486 showCHSHook (CHSEnum ide oalias trans oprefix derive _) =
487 showString "enum "
488 . showIdAlias ide oalias
489 . showCHSTrans trans
490 . showPrefix oprefix True
491 . if null derive then id else showString $
492 "deriving ("
493 ++ concat (intersperse ", " (map identToLexeme derive))
494 ++ ") "
495 showCHSHook (CHSCall isPure isUns isNol ide oalias _) =
496 showString "call "
497 . (if isPure then showString "pure " else id)
498 . (if isUns then showString "unsafe " else id)
499 . (if isNol then showString "nolock " else id)
500 . showIdAlias ide oalias
501 showCHSHook (CHSFun isPure isUns isNol ide oalias octxt parms parm _) =
502 showString "fun "
503 . (if isPure then showString "pure " else id)
504 . (if isUns then showString "unsafe " else id)
505 . (if isNol then showString "nolock " else id)
506 . showIdAlias ide oalias
507 . (case octxt of
508 Nothing -> showChar ' '
509 Just ctxtStr -> showString ctxtStr . showString " => ")
510 . showString "{"
511 . foldr (.) id (intersperse (showString ", ") (map showCHSParm parms))
512 . showString "} -> "
513 . showCHSParm parm
514 showCHSHook (CHSField acc path _) =
515 (case acc of
516 CHSGet -> showString "get "
517 CHSSet -> showString "set ")
518 . showCHSAPath path
519 showCHSHook (CHSPointer star ide oalias ptrType isNewtype oRefType _) =
520 showString "pointer "
521 . (if star then showString "*" else showString "")
522 . showIdAlias ide oalias
523 . (case ptrType of
524 CHSForeignPtr -> showString " foreign"
525 CHSStablePtr -> showString " stable"
526 _ -> showString "")
527 . (case (isNewtype, oRefType) of
528 (True , _ ) -> showString " newtype"
529 (False, Just ide) -> showString " -> " . showCHSIdent ide
530 (False, Nothing ) -> showString "")
531 showCHSHook (CHSClass oclassIde classIde typeIde _) =
532 showString "class "
533 . (case oclassIde of
534 Nothing -> showString ""
535 Just classIde -> showCHSIdent classIde . showString " => ")
536 . showCHSIdent classIde
537 . showString " "
538 . showCHSIdent typeIde
539
540 showPrefix :: Maybe String -> Bool -> ShowS
541 showPrefix Nothing _ = showString ""
542 showPrefix (Just prefix) withWith = maybeWith
543 . showString "prefix = "
544 . showString prefix
545 . showString " "
546 where
547 maybeWith = if withWith then showString "with " else id
548
549 showIdAlias :: Ident -> Maybe Ident -> ShowS
550 showIdAlias ide oalias =
551 showCHSIdent ide
552 . (case oalias of
553 Nothing -> id
554 Just ide -> showString " as " . showCHSIdent ide)
555
556 showCHSParm :: CHSParm -> ShowS
557 showCHSParm (CHSParm oimMarsh hsTyStr twoCVals oomMarsh _) =
558 showOMarsh oimMarsh
559 . showChar ' '
560 . showHsVerb hsTyStr
561 . (if twoCVals then showChar '&' else id)
562 . showChar ' '
563 . showOMarsh oomMarsh
564 where
565 showOMarsh Nothing = id
566 showOMarsh (Just (ide, argKind)) = showCHSIdent ide
567 . (case argKind of
568 CHSValArg -> id
569 CHSIOArg -> showString "*"
570 CHSVoidArg -> showString "-")
571 --
572 showHsVerb str = showChar '`' . showString str . showChar '\''
573
574 showCHSTrans :: CHSTrans -> ShowS
575 showCHSTrans (CHSTrans _2Case assocs) =
576 showString "{"
577 . (if _2Case then showString ("underscoreToCase" ++ maybeComma) else id)
578 . foldr (.) id (intersperse (showString ", ") (map showAssoc assocs))
579 . showString "}"
580 where
581 maybeComma = if null assocs then "" else ", "
582 --
583 showAssoc (ide1, ide2) =
584 showCHSIdent ide1
585 . showString " as "
586 . showCHSIdent ide2
587
588 showCHSAPath :: CHSAPath -> ShowS
589 showCHSAPath (CHSRoot ide) =
590 showCHSIdent ide
591 showCHSAPath (CHSDeref path _) =
592 showString "* "
593 . showCHSAPath path
594 showCHSAPath (CHSRef (CHSDeref path _) ide) =
595 showCHSAPath path
596 . showString "->"
597 . showCHSIdent ide
598 showCHSAPath (CHSRef path ide) =
599 showCHSAPath path
600 . showString "."
601 . showCHSIdent ide
602
603 showCHSIdent :: Ident -> ShowS
604 showCHSIdent = showString . identToLexeme
605
606
607 -- load and dump a CHI file
608 -- ------------------------
609
610 chisuffix :: String
611 chisuffix = ".chi"
612
613 versionPrefix :: String
614 versionPrefix = "C->Haskell Interface Version "
615
616 -- replace all import names with the content of the CHI file
617 loadAllCHI :: CHSModule -> CST s CHSModule
618 loadAllCHI (CHSModule frags) = do
619 let checkFrag (CHSHook (CHSImport qual name fName pos)) = do
620 chi <- loadCHI fName
621 return (CHSHook (CHSImport qual name chi pos))
622 checkFrag h = return h
623 frags' <- mapM checkFrag frags
624 return (CHSModule frags')
625
626 -- load a CHI file (EXPORTED)
627 --
628 -- * the file suffix is automagically appended
629 --
630 -- * any error raises a syntax exception (see below)
631 --
632 -- * the version of the .chi file is checked against the version of the current
633 -- executable; they must match in the major and minor version
634 --
635 loadCHI :: FilePath -> CST s String
636 loadCHI fname = do
637 -- search for .chi files
638 --
639 paths <- getSwitch chiPathSB
640 let fullnames = [path ++ '/':fname ++ chisuffix |
641 path <- paths]
642 fullname <- findFirst fullnames
643 (fatal $ fname++chisuffix++" not found in:\n"++
644 unlines paths)
645 -- read file
646 --
647 traceInfoRead fullname
648 contents <- readFileCIO fullname
649
650 -- parse
651 --
652 traceInfoVersion
653 let ls = lines contents
654 when (null ls) $
655 errorCHICorrupt fname
656 let versline:chi = ls
657 prefixLen = length versionPrefix
658 when (length versline < prefixLen
659 || take prefixLen versline /= versionPrefix) $
660 errorCHICorrupt fname
661 let versline' = drop prefixLen versline
662 (major, minor) <- case majorMinor versline' of
663 Nothing -> errorCHICorrupt fname
664 Just majMin -> return majMin
665
666 (version, _, _) <- getId
667 let Just (myMajor, myMinor) = majorMinor version
668 when (major /= myMajor || minor /= myMinor) $
669 errorCHIVersion fname
670 (major ++ "." ++ minor) (myMajor ++ "." ++ myMinor)
671
672 -- finalize
673 --
674 traceInfoOK
675 return $ concat chi
676 where
677 traceInfoRead fname = putTraceStr tracePhasesSW
678 ("Attempting to read file `"
679 ++ fname ++ "'...\n")
680 traceInfoVersion = putTraceStr tracePhasesSW
681 ("...checking version `"
682 ++ fname ++ "'...\n")
683 traceInfoOK = putTraceStr tracePhasesSW
684 ("...successfully loaded `"
685 ++ fname ++ "'.\n")
686 findFirst [] err = err
687 findFirst (p:aths) err = do
688 e <- doesFileExistCIO p
689 if e then return p else findFirst aths err
690
691
692 -- given a file name (no suffix) and a CHI file, the information is printed
693 -- into that file (EXPORTED)
694 --
695 -- * the correct suffix will automagically be appended
696 --
697 dumpCHI :: String -> String -> CST s ()
698 dumpCHI fname contents =
699 do
700 (version, _, _) <- getId
701 writeFileCIO (fname ++ chisuffix) $
702 versionPrefix ++ version ++ "\n" ++ contents
703
704 -- extract major and minor number from a version string
705 --
706 majorMinor :: String -> Maybe (String, String)
707 majorMinor vers = let (major, rest) = break (== '.') vers
708 (minor, _ ) = break (== '.') . tail $ rest
709 in
710 if null rest then Nothing else Just (major, minor)
711
712
713 -- parsing a CHS token stream
714 -- --------------------------
715
716 syntaxExc :: String
717 syntaxExc = "syntax"
718
719 -- alternative action in case of a syntax exception
720 --
721 ifError :: CST s a -> CST s a -> CST s a
722 ifError action handler = action `catchExc` (syntaxExc, const handler)
723
724 -- raise syntax error exception
725 --
726 raiseSyntaxError :: CST s a
727 raiseSyntaxError = throwExc syntaxExc "syntax error"
728
729 -- parse a complete module
730 --
731 -- * errors are entered into the compiler state
732 --
733 parseCHSModule :: Position -> String -> CST s CHSModule
734 parseCHSModule pos cs = do
735 toks <- lexCHS cs pos
736 frags <- parseFrags toks
737 return (CHSModule frags)
738
739 -- parsing of code fragments
740 --
741 -- * in case of an error, all tokens that are neither Haskell nor control
742 -- tokens are skipped; afterwards parsing continues
743 --
744 -- * when encountering inline-C code we scan forward over all inline-C and
745 -- control tokens to avoid turning the control tokens within a sequence of
746 -- inline-C into Haskell fragments
747 --
748 parseFrags :: [CHSToken] -> CST s [CHSFrag]
749 parseFrags toks = do
750 parseFrags0 toks
751 `ifError` contFrags toks
752 where
753 parseFrags0 :: [CHSToken] -> CST s [CHSFrag]
754 parseFrags0 [] = return []
755 parseFrags0 (CHSTokHaskell pos s:toks) = do
756 frags <- parseFrags toks
757 return $ CHSVerb s pos : frags
758 parseFrags0 (CHSTokCtrl pos c:toks) = do
759 frags <- parseFrags toks
760 return $ CHSVerb [c] pos : frags
761 parseFrags0 (CHSTokCPP pos s:toks) = do
762 frags <- parseFrags toks
763 return $ CHSCPP s pos : frags
764 parseFrags0 (CHSTokLine pos :toks) = do
765 frags <- parseFrags toks
766 return $ CHSLine pos : frags
767 parseFrags0 (CHSTokC pos s:toks) = parseC pos s toks
768 parseFrags0 (CHSTokImport pos :toks) = parseImport pos toks
769 parseFrags0 (CHSTokContext pos :toks) = parseContext pos toks
770 parseFrags0 (CHSTokType pos :toks) = parseType pos toks
771 parseFrags0 (CHSTokSizeof pos :toks) = parseSizeof pos toks
772 parseFrags0 (CHSTokEnum pos :toks) = parseEnum pos toks
773 parseFrags0 (CHSTokCall pos :toks) = parseCall pos toks
774 parseFrags0 (CHSTokFun pos :toks) = parseFun pos toks
775 parseFrags0 (CHSTokGet pos :toks) = parseField pos CHSGet toks
776 parseFrags0 (CHSTokSet pos :toks) = parseField pos CHSSet toks
777 parseFrags0 (CHSTokClass pos :toks) = parseClass pos toks
778 parseFrags0 (CHSTokPointer pos :toks) = parsePointer pos toks
779 parseFrags0 (CHSTokPragma pos :toks) = parsePragma pos toks
780 parseFrags0 toks = syntaxError toks
781 --
782 -- skip to next Haskell or control token
783 --
784 contFrags [] = return []
785 contFrags toks@(CHSTokHaskell _ _:_ ) = parseFrags toks
786 contFrags toks@(CHSTokCtrl _ _:_ ) = parseFrags toks
787 contFrags (_ :toks) = contFrags toks
788
789 parseC :: Position -> String -> [CHSToken] -> CST s [CHSFrag]
790 parseC pos s toks =
791 do
792 frags <- collectCtrlAndC toks
793 return $ CHSC s pos : frags
794 where
795 collectCtrlAndC (CHSTokCtrl pos c:toks) = do
796 frags <- collectCtrlAndC toks
797 return $ CHSC [c] pos : frags
798 collectCtrlAndC (CHSTokC pos s:toks) = do
799 frags <- collectCtrlAndC toks
800 return $ CHSC s pos : frags
801 collectCtrlAndC toks = parseFrags toks
802
803 parseImport :: Position -> [CHSToken] -> CST s [CHSFrag]
804 parseImport pos toks = do
805 (qual, modid, toks') <-
806 case toks of
807 CHSTokIdent _ ide :toks ->
808 let (ide', toks') = rebuildModuleId ide toks
809 in return (False, ide', toks')
810 CHSTokQualif _: CHSTokIdent _ ide:toks ->
811 let (ide', toks') = rebuildModuleId ide toks
812 in return (True , ide', toks')
813 _ -> syntaxError toks
814 let fName = moduleNameToFileName . identToLexeme $ modid
815 toks'' <- parseEndHook toks'
816 frags <- parseFrags toks''
817 return $ CHSHook (CHSImport qual modid fName pos) : frags
818
819 -- Qualified module names do not get lexed as a single token so we need to
820 -- reconstruct it from a sequence of identifier and dot tokens.
821 --
822 rebuildModuleId ide (CHSTokDot _ : CHSTokIdent _ ide' : toks) =
823 let catIdent ide ide' = onlyPosIdent (posOf ide) --FIXME: unpleasant hack
824 (identToLexeme ide ++ '.' : identToLexeme ide')
825 in rebuildModuleId (catIdent ide ide') toks
826 rebuildModuleId ide toks = (ide, toks)
827
828 moduleNameToFileName :: String -> FilePath
829 moduleNameToFileName = map dotToSlash
830 where dotToSlash '.' = '/'
831 dotToSlash c = c
832
833 parseContext :: Position -> [CHSToken] -> CST s [CHSFrag]
834 parseContext pos toks = do
835 (olib , toks ) <- parseOptLib toks
836 (opref , toks) <- parseOptPrefix False toks
837 (olock , toks) <- parseOptLock toks
838 toks <- parseEndHook toks
839 frags <- parseFrags toks
840 let frag = CHSContext olib opref olock pos
841 return $ CHSHook frag : frags
842
843 parseType :: Position -> [CHSToken] -> CST s [CHSFrag]
844 parseType pos (CHSTokIdent _ ide:toks) =
845 do
846 toks' <- parseEndHook toks
847 frags <- parseFrags toks'
848 return $ CHSHook (CHSType ide pos) : frags
849 parseType _ toks = syntaxError toks
850
851 parseSizeof :: Position -> [CHSToken] -> CST s [CHSFrag]
852 parseSizeof pos (CHSTokIdent _ ide:toks) =
853 do
854 toks' <- parseEndHook toks
855 frags <- parseFrags toks'
856 return $ CHSHook (CHSSizeof ide pos) : frags
857 parseSizeof _ toks = syntaxError toks
858
859 parseEnum :: Position -> [CHSToken] -> CST s [CHSFrag]
860 parseEnum pos (CHSTokIdent _ ide:toks) =
861 do
862 (oalias, toks' ) <- parseOptAs ide True toks
863 (trans , toks'') <- parseTrans toks'
864 (oprefix, toks''') <- parseOptPrefix True toks''
865 (derive, toks'''') <- parseDerive toks'''
866 toks''''' <- parseEndHook toks''''
867 frags <- parseFrags toks'''''
868 return $ CHSHook (CHSEnum ide (norm oalias) trans oprefix derive pos) : frags
869 where
870 norm Nothing = Nothing
871 norm (Just ide') | ide == ide' = Nothing
872 | otherwise = Just ide'
873 parseEnum _ toks = syntaxError toks
874
875 parseCall :: Position -> [CHSToken] -> CST s [CHSFrag]
876 parseCall pos toks =
877 do
878 (isPure , toks ) <- parseIsPure toks
879 (isUnsafe, toks ) <- parseIsUnsafe toks
880 (isNolock, toks ) <- parseIsNolock toks
881 (ide , toks ) <- parseIdent toks
882 (oalias , toks ) <- parseOptAs ide False toks
883 toks <- parseEndHook toks
884 frags <- parseFrags toks
885 return $
886 CHSHook (CHSCall isPure isUnsafe isNolock ide (norm ide oalias) pos) : frags
887
888 parseFun :: Position -> [CHSToken] -> CST s [CHSFrag]
889 parseFun pos toks =
890 do
891 (isPure , toks' ) <- parseIsPure toks
892 (isUnsafe, toks'2) <- parseIsUnsafe toks'
893 (isNolock, toks'3) <- parseIsNolock toks'2
894 (ide , toks'4) <- parseIdent toks'3
895 (oalias , toks'5) <- parseOptAs ide False toks'4
896 (octxt , toks'6) <- parseOptContext toks'5
897 (parms , toks'7) <- parseParms toks'6
898 (parm , toks'8) <- parseParm toks'7
899 toks'9 <- parseEndHook toks'8
900 frags <- parseFrags toks'9
901 return $
902 CHSHook
903 (CHSFun isPure isUnsafe isNolock ide (norm ide oalias) octxt parms parm pos) :
904 frags
905 where
906 parseOptContext (CHSTokHSVerb _ ctxt:CHSTokDArrow _:toks) =
907 return (Just ctxt, toks)
908 parseOptContext toks =
909 return (Nothing , toks)
910 --
911 parseParms (CHSTokLBrace _:CHSTokRBrace _:CHSTokArrow _:toks) =
912 return ([], toks)
913 parseParms (CHSTokLBrace _ :toks) =
914 parseParms' (CHSTokComma nopos:toks)
915 parseParms toks =
916 syntaxError toks
917 --
918 parseParms' (CHSTokRBrace _:CHSTokArrow _:toks) = return ([], toks)
919 parseParms' (CHSTokComma _ :toks) = do
920 (parm , toks' ) <- parseParm toks
921 (parms, toks'') <- parseParms' toks'
922 return (parm:parms, toks'')
923 parseParms' (CHSTokRBrace _ :toks) = syntaxError toks
924 -- gives better error messages
925 parseParms' toks = syntaxError toks
926
927 parseIsPure :: [CHSToken] -> CST s (Bool, [CHSToken])
928 parseIsPure (CHSTokPure _:toks) = return (True , toks)
929 parseIsPure (CHSTokFun _:toks) = return (True , toks) -- backwards compat.
930 parseIsPure toks = return (False, toks)
931 -- FIXME: eventually, remove `fun'; it's currently deprecated
932
933 parseIsUnsafe :: [CHSToken] -> CST s (Bool, [CHSToken])
934 parseIsUnsafe (CHSTokUnsafe _:toks) = return (True , toks)
935 parseIsUnsafe toks = return (False, toks)
936
937 parseIsNolock :: [CHSToken] -> CST s (Bool, [CHSToken])
938 parseIsNolock (CHSTokNolock _:toks) = return (True , toks)
939 parseIsNolock toks = return (False, toks)
940
941 norm :: Ident -> Maybe Ident -> Maybe Ident
942 norm ide Nothing = Nothing
943 norm ide (Just ide') | ide == ide' = Nothing
944 | otherwise = Just ide'
945
946 parseParm :: [CHSToken] -> CST s (CHSParm, [CHSToken])
947 parseParm toks =
948 do
949 (oimMarsh, toks' ) <- parseOptMarsh toks
950 (hsTyStr, twoCVals, pos, toks'2) <-
951 case toks' of
952 (CHSTokHSVerb pos hsTyStr:CHSTokAmp _:toks'2) ->
953 return (hsTyStr, True , pos, toks'2)
954 (CHSTokHSVerb pos hsTyStr :toks'2) ->
955 return (hsTyStr, False, pos, toks'2)
956 toks -> syntaxError toks
957 (oomMarsh, toks'3) <- parseOptMarsh toks'2
958 return (CHSParm oimMarsh hsTyStr twoCVals oomMarsh pos, toks'3)
959 where
960 parseOptMarsh :: [CHSToken] -> CST s (Maybe (Ident, CHSArg), [CHSToken])
961 parseOptMarsh (CHSTokIdent _ ide:CHSTokStar _ :toks) =
962 return (Just (ide, CHSIOArg) , toks)
963 parseOptMarsh (CHSTokIdent _ ide:CHSTokMinus _:toks) =
964 return (Just (ide, CHSVoidArg), toks)
965 parseOptMarsh (CHSTokIdent _ ide :toks) =
966 return (Just (ide, CHSValArg) , toks)
967 parseOptMarsh toks =
968 return (Nothing, toks)
969
970 parseField :: Position -> CHSAccess -> [CHSToken] -> CST s [CHSFrag]
971 parseField pos access toks =
972 do
973 (path, toks') <- parsePath toks
974 frags <- parseFrags toks'
975 return $ CHSHook (CHSField access path pos) : frags
976
977 parsePointer :: Position -> [CHSToken] -> CST s [CHSFrag]
978 parsePointer pos toks =
979 do
980 (isStar, ide, toks') <-
981 case toks of
982 CHSTokStar _:CHSTokIdent _ ide:toks' -> return (True , ide, toks')
983 CHSTokIdent _ ide :toks' -> return (False, ide, toks')
984 _ -> syntaxError toks
985 (oalias , toks'2) <- parseOptAs ide True toks'
986 (ptrType, toks'3) <- parsePtrType toks'2
987 let
988 (isNewtype, oRefType, toks'4) =
989 case toks'3 of
990 CHSTokNewtype _ :toks' -> (True , Nothing , toks' )
991 CHSTokArrow _:CHSTokIdent _ ide:toks' -> (False, Just ide, toks' )
992 _ -> (False, Nothing , toks'3)
993 toks'5 <- parseEndHook toks'4
994 frags <- parseFrags toks'5
995 return $
996 CHSHook
997 (CHSPointer isStar ide (norm ide oalias) ptrType isNewtype oRefType pos)
998 : frags
999 where
1000 parsePtrType :: [CHSToken] -> CST s (CHSPtrType, [CHSToken])
1001 parsePtrType (CHSTokForeign _:toks) = return (CHSForeignPtr, toks)
1002 parsePtrType (CHSTokStable _ :toks) = return (CHSStablePtr, toks)
1003 parsePtrType toks = return (CHSPtr, toks)
1004
1005 norm ide Nothing = Nothing
1006 norm ide (Just ide') | ide == ide' = Nothing
1007 | otherwise = Just ide'
1008
1009 parsePragma :: Position -> [CHSToken] -> CST s [CHSFrag]
1010 parsePragma pos toks = do
1011 let
1012 parseExts exts (CHSTokIdent _ ide:CHSTokComma _:toks) =
1013 parseExts (identToLexeme ide:exts) toks
1014 parseExts exts (CHSTokIdent _ ide:CHSTokPragEnd _:toks) =
1015 return (reverse (identToLexeme ide:exts), toks)
1016 parseExts exts toks = syntaxError toks
1017 (exts, toks) <- parseExts [] toks
1018 frags <- parseFrags toks
1019 return (CHSLang exts pos : frags)
1020
1021 parseClass :: Position -> [CHSToken] -> CST s [CHSFrag]
1022 parseClass pos (CHSTokIdent _ sclassIde:
1023 CHSTokDArrow _ :
1024 CHSTokIdent _ classIde :
1025 CHSTokIdent _ typeIde :
1026 toks) =
1027 do
1028 toks' <- parseEndHook toks
1029 frags <- parseFrags toks'
1030 return $ CHSHook (CHSClass (Just sclassIde) classIde typeIde pos) : frags
1031 parseClass pos (CHSTokIdent _ classIde :
1032 CHSTokIdent _ typeIde :
1033 toks) =
1034 do
1035 toks' <- parseEndHook toks
1036 frags <- parseFrags toks'
1037 return $ CHSHook (CHSClass Nothing classIde typeIde pos) : frags
1038 parseClass _ toks = syntaxError toks
1039
1040 parseOptLib :: [CHSToken] -> CST s (Maybe String, [CHSToken])
1041 parseOptLib (CHSTokLib _ :
1042 CHSTokEqual _ :
1043 CHSTokString _ str:
1044 toks) = return (Just str, toks)
1045 parseOptLib (CHSTokLib _:toks ) = syntaxError toks
1046 parseOptLib toks = return (Nothing, toks)
1047
1048 parseOptLock :: [CHSToken] -> CST s (Maybe String, [CHSToken])
1049 parseOptLock (CHSTokLock _ :
1050 CHSTokEqual _ :
1051 CHSTokString _ str:
1052 toks) = return (Just str, toks)
1053 parseOptLock (CHSTokLock _:toks ) = syntaxError toks
1054 parseOptLock toks = return (Nothing, toks)
1055
1056 parseOptPrefix :: Bool -> [CHSToken] -> CST s (Maybe String, [CHSToken])
1057 parseOptPrefix False (CHSTokPrefix _ :
1058 CHSTokEqual _ :
1059 CHSTokString _ str:
1060 toks) = return (Just str, toks)
1061 parseOptPrefix True (CHSTokWith _ :
1062 CHSTokPrefix _ :
1063 CHSTokEqual _ :
1064 CHSTokString _ str:
1065 toks) = return (Just str, toks)
1066 parseOptPrefix _ (CHSTokWith _:toks) = syntaxError toks
1067 parseOptPrefix _ (CHSTokPrefix _:toks) = syntaxError toks
1068 parseOptPrefix _ toks = return (Nothing, toks)
1069
1070 -- first argument is the identifier that is to be used when `^' is given and
1071 -- the second indicates whether the first character has to be upper case
1072 --
1073 parseOptAs :: Ident -> Bool -> [CHSToken] -> CST s (Maybe Ident, [CHSToken])
1074 parseOptAs _ _ (CHSTokAs _:CHSTokIdent _ ide:toks) =
1075 return (Just ide, toks)
1076 parseOptAs ide upper (CHSTokAs _:CHSTokHat pos :toks) =
1077 return (Just $ underscoreToCase ide upper pos, toks)
1078 parseOptAs _ _ (CHSTokAs _ :toks) = syntaxError toks
1079 parseOptAs _ _ toks =
1080 return (Nothing, toks)
1081
1082 -- convert C style identifier to Haskell style identifier
1083 --
1084 underscoreToCase :: Ident -> Bool -> Position -> Ident
1085 underscoreToCase ide upper pos =
1086 let lexeme = identToLexeme ide
1087 ps = filter (not . null) . parts $ lexeme
1088 in
1089 onlyPosIdent pos . adjustHead . concat . map adjustCase $ ps
1090 where
1091 parts s = let (l, s') = break (== '_') s
1092 in
1093 l : case s' of
1094 [] -> []
1095 (_:s'') -> parts s''
1096 --
1097 adjustCase (c:cs) = toUpper c : map toLower cs
1098 --
1099 adjustHead "" = ""
1100 adjustHead (c:cs) = if upper then toUpper c : cs else toLower c:cs
1101
1102 -- this is disambiguated and left factored
1103 --
1104 parsePath :: [CHSToken] -> CST s (CHSAPath, [CHSToken])
1105 parsePath (CHSTokStar pos:toks) =
1106 do
1107 (path, toks') <- parsePath toks
1108 return (CHSDeref path pos, toks')
1109 parsePath (CHSTokIdent _ ide:toks) =
1110 do
1111 (pathWithHole, toks') <- parsePath' toks
1112 return (pathWithHole (CHSRoot ide), toks')
1113 parsePath toks = syntaxError toks
1114
1115 -- `s->m' is represented by `(*s).m' in the tree
1116 --
1117 parsePath' :: [CHSToken] -> CST s (CHSAPath -> CHSAPath, [CHSToken])
1118 parsePath' (CHSTokDot _:CHSTokIdent _ ide:toks) =
1119 do
1120 (pathWithHole, toks') <- parsePath' toks
1121 return (pathWithHole . (\hole -> CHSRef hole ide), toks')
1122 parsePath' (CHSTokDot _:toks) =
1123 syntaxError toks
1124 parsePath' (CHSTokArrow pos:CHSTokIdent _ ide:toks) =
1125 do
1126 (pathWithHole, toks') <- parsePath' toks
1127 return (pathWithHole . (\hole -> CHSRef (CHSDeref hole pos) ide), toks')
1128 parsePath' (CHSTokArrow _:toks) =
1129 syntaxError toks
1130 parsePath' toks =
1131 do
1132 toks' <- parseEndHook toks
1133 return (id, toks')
1134
1135 parseTrans :: [CHSToken] -> CST s (CHSTrans, [CHSToken])
1136 parseTrans (CHSTokLBrace _:toks) =
1137 do
1138 (_2Case, toks' ) <- parse_2Case toks
1139 case toks' of
1140 (CHSTokRBrace _:toks'') -> return (CHSTrans _2Case [], toks'')
1141 _ ->
1142 do
1143 -- if there was no `underscoreToCase', we add a comma token to meet
1144 -- the invariant of `parseTranss'
1145 --
1146 (transs, toks'') <- if _2Case
1147 then parseTranss toks'
1148 else parseTranss (CHSTokComma nopos:toks')
1149 return (CHSTrans _2Case transs, toks'')
1150 where
1151 parse_2Case (CHSTok_2Case _:toks) = return (True, toks)
1152 parse_2Case toks = return (False, toks)
1153 --
1154 parseTranss (CHSTokRBrace _:toks) = return ([], toks)
1155 parseTranss (CHSTokComma _:toks) = do
1156 (assoc, toks' ) <- parseAssoc toks
1157 (trans, toks'') <- parseTranss toks'
1158 return (assoc:trans, toks'')
1159 parseTranss toks = syntaxError toks
1160 --
1161 parseAssoc (CHSTokIdent _ ide1:CHSTokAs _:CHSTokIdent _ ide2:toks) =
1162 return ((ide1, ide2), toks)
1163 parseAssoc (CHSTokIdent _ ide1:CHSTokAs _:toks ) =
1164 syntaxError toks
1165 parseAssoc (CHSTokIdent _ ide1:toks ) =
1166 syntaxError toks
1167 parseAssoc toks =
1168 syntaxError toks
1169 parseTrans toks = syntaxError toks
1170
1171 parseDerive :: [CHSToken] -> CST s ([Ident], [CHSToken])
1172 parseDerive (CHSTokDerive _ :CHSTokLParen _:CHSTokRParen _:toks) =
1173 return ([], toks)
1174 parseDerive (CHSTokDerive _ :CHSTokLParen _:toks) =
1175 parseCommaIdent (CHSTokComma nopos:toks)
1176 where
1177 parseCommaIdent :: [CHSToken] -> CST s ([Ident], [CHSToken])
1178 parseCommaIdent (CHSTokComma _:CHSTokIdent _ ide:toks) =
1179 do
1180 (ids, tok') <- parseCommaIdent toks
1181 return (ide:ids, tok')
1182 parseCommaIdent (CHSTokRParen _ :toks) =
1183 return ([], toks)
1184 parseDerive toks = return ([],toks)
1185
1186 parseIdent :: [CHSToken] -> CST s (Ident, [CHSToken])
1187 parseIdent (CHSTokIdent _ ide:toks) = return (ide, toks)
1188 parseIdent toks = syntaxError toks
1189
1190 parseEndHook :: [CHSToken] -> CST s ([CHSToken])
1191 parseEndHook (CHSTokEndHook _:toks) = return toks
1192 parseEndHook toks = syntaxError toks
1193
1194 syntaxError :: [CHSToken] -> CST s a
1195 syntaxError [] = errorEOF
1196 syntaxError (tok:_) = errorIllegal tok
1197
1198 errorIllegal :: CHSToken -> CST s a
1199 errorIllegal tok = do
1200 raiseError (posOf tok)
1201 ["Syntax error!",
1202 "The phrase `" ++ show tok ++ "' is not allowed \
1203 \here."]
1204 raiseSyntaxError
1205
1206 errorEOF :: CST s a
1207 errorEOF = do
1208 raiseError nopos
1209 ["Premature end of file!",
1210 "The .chs file ends in the middle of a binding hook."]
1211 raiseSyntaxError
1212
1213 errorCHINotFound :: String -> CST s a
1214 errorCHINotFound ide = do
1215 raiseError nopos
1216 ["Unknown .chi file!",
1217 "Cannot find the .chi file for `" ++ ide ++ "'."]
1218 raiseSyntaxError
1219
1220 errorCHICorrupt :: String -> CST s a
1221 errorCHICorrupt ide = do
1222 raiseError nopos
1223 ["Corrupt .chi file!",
1224 "The file `" ++ ide ++ ".chi' is corrupt."]
1225 raiseSyntaxError
1226
1227 errorCHIVersion :: String -> String -> String -> CST s a
1228 errorCHIVersion ide chiVersion myVersion = do
1229 raiseError nopos
1230 ["Wrong version of .chi file!",
1231 "The file `" ++ ide ++ ".chi' is version "
1232 ++ chiVersion ++ ", but mine is " ++ myVersion ++ "."]
1233 raiseSyntaxError