[project @ 2002-02-13 12:17:48 by simonmar]
[ghc-hetmet.git] / ghc / utils / genprimopcode / Main.hs
1
2 ------------------------------------------------------------------
3 -- A primop-table mangling program                              --
4 ------------------------------------------------------------------
5
6 module Main where
7
8 import Parsec
9 import Monad
10 import Char
11 import List
12 import System ( getArgs )
13 import Maybe ( catMaybes )
14
15 main = getArgs >>= \args ->
16        if length args /= 1 || head args `notElem` known_args
17        then error ("usage: genprimopcode command < primops.txt > ...\n"
18                    ++ "   where command is one of\n"
19                    ++ unlines (map ("            "++) known_args)
20                   )
21        else
22        do s <- getContents
23           let pres = parse pTop "" s
24           case pres of
25              Left err -> error ("parse error at " ++ (show err))
26              Right p_o_specs
27                 -> myseq (sanityTop p_o_specs) (
28                    case head args of
29
30                       "--data-decl" 
31                          -> putStr (gen_data_decl p_o_specs)
32
33                       "--has-side-effects" 
34                          -> putStr (gen_switch_from_attribs 
35                                        "has_side_effects" 
36                                        "primOpHasSideEffects" p_o_specs)
37
38                       "--out-of-line" 
39                          -> putStr (gen_switch_from_attribs 
40                                        "out_of_line" 
41                                        "primOpOutOfLine" p_o_specs)
42
43                       "--commutable" 
44                          -> putStr (gen_switch_from_attribs 
45                                        "commutable" 
46                                        "commutableOp" p_o_specs)
47
48                       "--needs-wrapper" 
49                          -> putStr (gen_switch_from_attribs 
50                                        "needs_wrapper" 
51                                        "primOpNeedsWrapper" p_o_specs)
52
53                       "--can-fail" 
54                          -> putStr (gen_switch_from_attribs 
55                                        "can_fail" 
56                                        "primOpCanFail" p_o_specs)
57
58                       "--strictness" 
59                          -> putStr (gen_switch_from_attribs 
60                                        "strictness" 
61                                        "primOpStrictness" p_o_specs)
62
63                       "--usage" 
64                          -> putStr (gen_switch_from_attribs 
65                                        "usage" 
66                                        "primOpUsg" p_o_specs)
67
68                       "--primop-primop-info" 
69                          -> putStr (gen_primop_info p_o_specs)
70
71                       "--primop-tag" 
72                          -> putStr (gen_primop_tag p_o_specs)
73
74                       "--primop-list" 
75                          -> putStr (gen_primop_list p_o_specs)
76
77                       "--make-haskell-wrappers" 
78                          -> putStr (gen_wrappers p_o_specs)
79                         
80                       "--make-latex-doc"
81                          -> putStr (gen_latex_doc p_o_specs)
82                    )
83
84
85 known_args 
86    = [ "--data-decl",
87        "--has-side-effects",
88        "--out-of-line",
89        "--commutable",
90        "--needs-wrapper",
91        "--can-fail",
92        "--strictness",
93        "--usage",
94        "--primop-primop-info",
95        "--primop-tag",
96        "--primop-list",
97        "--make-haskell-wrappers",
98        "--make-latex-doc"
99      ]
100
101 ------------------------------------------------------------------
102 -- Code generators -----------------------------------------------
103 ------------------------------------------------------------------
104
105 gen_latex_doc (Info defaults entries)
106    = "\\primopdefaults{" 
107          ++ mk_options defaults
108          ++ "}\n"
109      ++ (concat (map mk_entry entries))
110      where mk_entry (PrimOpSpec {cons=cons,name=name,ty=ty,cat=cat,desc=desc,opts=opts}) =
111                  "\\primopdesc{" 
112                  ++ latex_encode cons ++ "}{"
113                  ++ latex_encode name ++ "}{"
114                  ++ latex_encode (zencode name) ++ "}{"
115                  ++ latex_encode (show cat) ++ "}{"
116                  ++ latex_encode (mk_source_ty ty) ++ "}{"
117                  ++ latex_encode (mk_core_ty ty) ++ "}{"
118                  ++ desc ++ "}{"
119                  ++ mk_options opts
120                  ++ "}\n"
121            mk_entry (Section {title=title,desc=desc}) =
122                  "\\primopsection{" 
123                  ++ latex_encode title ++ "}{" 
124                  ++ desc ++ "}\n"
125            mk_source_ty t = pty t
126              where pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2
127                    pty t = pbty t
128                    pbty (TyApp tc ts) = tc ++ (concat (map (' ':) (map paty ts)))
129                    pbty (TyUTup ts) = "(# " ++ (concat (intersperse "," (map pty ts))) ++ " #)"
130                    pbty t = paty t
131                    paty (TyVar tv) = tv
132                    paty t = "(" ++ pty t ++ ")"
133            
134            mk_core_ty t = foralls ++ (pty t)
135              where pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2
136                    pty t = pbty t
137                    pbty (TyApp tc ts) = (zencode tc) ++ (concat (map (' ':) (map paty ts)))
138                    pbty (TyUTup ts) = (zencode (utuplenm (length ts))) ++ (concat ((map (' ':) (map paty ts))))
139                    pbty t = paty t
140                    paty (TyVar tv) = zencode tv
141                    paty (TyApp tc []) = zencode tc
142                    paty t = "(" ++ pty t ++ ")"
143                    utuplenm 1 = "(# #)"
144                    utuplenm n = "(#" ++ (replicate (n-1) ',') ++ "#)"
145                    foralls = if tvars == [] then "" else "%forall " ++ (tbinds tvars)
146                    tvars = tvars_of t
147                    tbinds [] = ". " 
148                    tbinds ("o":tbs) = "(o::?) " ++ (tbinds tbs)
149                    tbinds (tv:tbs) = tv ++ " " ++ (tbinds tbs)
150            tvars_of (TyF t1 t2) = tvars_of t1 `union` tvars_of t2
151            tvars_of (TyApp tc ts) = foldl union [] (map tvars_of ts)
152            tvars_of (TyUTup ts) = foldr union [] (map tvars_of ts)
153            tvars_of (TyVar tv) = [tv]
154            
155            mk_options opts = 
156              "\\primoptions{"
157               ++ mk_has_side_effects opts ++ "}{"
158               ++ mk_out_of_line opts ++ "}{"
159               ++ mk_commutable opts ++ "}{"
160               ++ mk_needs_wrapper opts ++ "}{"
161               ++ mk_can_fail opts ++ "}{"
162               ++ latex_encode (mk_strictness opts) ++ "}{"
163               ++ latex_encode (mk_usage opts)
164               ++ "}"
165
166            mk_has_side_effects opts = mk_bool_opt opts "has_side_effects" "Has side effects." "Has no side effects."
167            mk_out_of_line opts = mk_bool_opt opts "out_of_line" "Implemented out of line." "Implemented in line."
168            mk_commutable opts = mk_bool_opt opts "commutable" "Commutable." "Not commutable."
169            mk_needs_wrapper opts = mk_bool_opt opts "needs_wrapper" "Needs wrapper." "Needs no wrapper."
170            mk_can_fail opts = mk_bool_opt opts "can_fail" "Can fail." "Cannot fail."
171
172            mk_bool_opt opts opt_name if_true if_false =
173              case lookup_attrib opt_name opts of
174                Just (OptionTrue _) -> if_true
175                Just (OptionFalse _) -> if_false
176                Nothing -> ""
177            
178            mk_strictness opts = 
179              case lookup_attrib "strictness" opts of
180                Just (OptionString _ s) -> s  -- for now
181                Nothing -> "" 
182
183            mk_usage opts = 
184              case lookup_attrib "usage" opts of
185                Just (OptionString _ s) -> s  -- for now
186                Nothing -> "" 
187
188            zencode cs = 
189              case maybe_tuple cs of
190                 Just n  -> n            -- Tuples go to Z2T etc
191                 Nothing -> concat (map encode_ch cs)
192              where
193                maybe_tuple "(# #)" = Just("Z1H")
194                maybe_tuple ('(' : '#' : cs) = case count_commas (0::Int) cs of
195                                                 (n, '#' : ')' : cs) -> Just ('Z' : shows (n+1) "H")
196                                                 other                -> Nothing
197                maybe_tuple "()" = Just("Z0T")
198                maybe_tuple ('(' : cs)       = case count_commas (0::Int) cs of
199                                                 (n, ')' : cs) -> Just ('Z' : shows (n+1) "T")
200                                                 other          -> Nothing
201                maybe_tuple other             = Nothing
202                
203                count_commas :: Int -> String -> (Int, String)
204                count_commas n (',' : cs) = count_commas (n+1) cs
205                count_commas n cs          = (n,cs)
206                
207                unencodedChar :: Char -> Bool    -- True for chars that don't need encoding
208                unencodedChar 'Z' = False
209                unencodedChar 'z' = False
210                unencodedChar c   = isAlphaNum c
211                
212                encode_ch :: Char -> String
213                encode_ch c | unencodedChar c = [c]      -- Common case first
214                
215                -- Constructors
216                encode_ch '('  = "ZL"    -- Needed for things like (,), and (->)
217                encode_ch ')'  = "ZR"    -- For symmetry with (
218                encode_ch '['  = "ZM"
219                encode_ch ']'  = "ZN"
220                encode_ch ':'  = "ZC"
221                encode_ch 'Z'  = "ZZ"
222                
223                -- Variables
224                encode_ch 'z'  = "zz"
225                encode_ch '&'  = "za"
226                encode_ch '|'  = "zb"
227                encode_ch '^'  = "zc"
228                encode_ch '$'  = "zd"
229                encode_ch '='  = "ze"
230                encode_ch '>'  = "zg"
231                encode_ch '#'  = "zh"
232                encode_ch '.'  = "zi"
233                encode_ch '<'  = "zl"
234                encode_ch '-'  = "zm"
235                encode_ch '!'  = "zn"
236                encode_ch '+'  = "zp"
237                encode_ch '\'' = "zq"
238                encode_ch '\\' = "zr"
239                encode_ch '/'  = "zs"
240                encode_ch '*'  = "zt"
241                encode_ch '_'  = "zu"
242                encode_ch '%'  = "zv"
243                encode_ch c    = 'z' : shows (ord c) "U"
244                        
245            latex_encode [] = []
246            latex_encode (c:cs) | c `elem` "#$%&_^{}" = "\\" ++ c:(latex_encode cs)
247            latex_encode ('~':cs) = "\\verb!~!" ++ (latex_encode cs)
248            latex_encode ('\\':cs) = "$\\backslash$" ++ (latex_encode cs)
249            latex_encode (c:cs) = c:(latex_encode cs)
250
251 gen_wrappers (Info defaults entries)
252    = "{-# OPTIONS -fno-implicit-prelude #-}\n" 
253         -- Dependencies on Prelude must be explicit in libraries/base, but we
254         -- don't need the Prelude here so we add -fno-implicit-prelude.
255      ++ "module GHC.PrimopWrappers where\n" 
256      ++ "import qualified GHC.Prim\n" 
257      ++ unlines (map f (filter (not.dodgy) (filter is_primop entries)))
258      where
259         f spec = let args = map (\n -> "a" ++ show n) [1 .. arity (ty spec)]
260                      src_name = wrap (name spec)
261                  in "{-# NOINLINE " ++ src_name ++ " #-}\n" ++ 
262                     src_name ++ " " ++ unwords args 
263                      ++ " = (GHC.Prim." ++ name spec ++ ") " ++ unwords args
264         wrap nm | isLower (head nm) = nm
265                 | otherwise = "(" ++ nm ++ ")"
266
267         dodgy spec
268            = name spec `elem` 
269              [-- C code generator can't handle these
270               "seq#", 
271               "tagToEnum#",
272               -- not interested in parallel support
273               "par#", "parGlobal#", "parLocal#", "parAt#", 
274               "parAtAbs#", "parAtRel#", "parAtForNow#" 
275              ]
276
277
278 gen_primop_list (Info defaults entries)
279    = unlines (
280         [      "   [" ++ cons first       ]
281         ++
282         map (\pi -> "   , " ++ cons pi) rest
283         ++ 
284         [     "   ]"     ]
285      ) where (first:rest) = filter is_primop entries
286
287 gen_primop_tag (Info defaults entries)
288    = unlines (zipWith f (filter is_primop entries) [1..])
289      where
290         f i n = "tagOf_PrimOp " ++ cons i 
291                 ++ " = _ILIT(" ++ show n ++ ") :: FastInt"
292
293 gen_data_decl (Info defaults entries)
294    = let conss = map cons (filter is_primop entries)
295      in  "data PrimOp\n   = " ++ head conss ++ "\n"
296          ++ unlines (map ("   | "++) (tail conss))
297
298 gen_switch_from_attribs :: String -> String -> Info -> String
299 gen_switch_from_attribs attrib_name fn_name (Info defaults entries)
300    = let defv = lookup_attrib attrib_name defaults
301          alts = catMaybes (map mkAlt (filter is_primop entries))
302
303          getAltRhs (OptionFalse _)    = "False"
304          getAltRhs (OptionTrue _)     = "True"
305          getAltRhs (OptionString _ s) = s
306
307          mkAlt po
308             = case lookup_attrib attrib_name (opts po) of
309                  Nothing -> Nothing
310                  Just xx -> Just (fn_name ++ " " ++ cons po ++ " = " ++ getAltRhs xx)
311
312      in
313          case defv of
314             Nothing -> error ("gen_switch_from: " ++ attrib_name)
315             Just xx 
316                -> unlines alts 
317                   ++ fn_name ++ " other = " ++ getAltRhs xx ++ "\n"
318
319 ------------------------------------------------------------------
320 -- Create PrimOpInfo text from PrimOpSpecs -----------------------
321 ------------------------------------------------------------------
322
323
324 gen_primop_info (Info defaults entries)
325    = unlines (map mkPOItext (filter is_primop entries))
326
327 mkPOItext i = mkPOI_LHS_text i ++ mkPOI_RHS_text i
328
329 mkPOI_LHS_text i
330    = "primOpInfo " ++ cons i ++ " = "
331
332 mkPOI_RHS_text i
333    = case cat i of
334         Compare 
335            -> case ty i of
336                  TyF t1 (TyF t2 td) 
337                     -> "mkCompare " ++ sl_name i ++ ppType t1
338         Monadic
339            -> case ty i of
340                  TyF t1 td
341                     -> "mkMonadic " ++ sl_name i ++ ppType t1
342         Dyadic
343            -> case ty i of
344                  TyF t1 (TyF t2 td)
345                     -> "mkDyadic " ++ sl_name i ++ ppType t1
346         GenPrimOp
347            -> let (argTys, resTy) = flatTys (ty i)
348                   tvs = nub (tvsIn (ty i))
349               in
350                   "mkGenPrimOp " ++ sl_name i ++ " " 
351                       ++ listify (map ppTyVar tvs) ++ " "
352                       ++ listify (map ppType argTys) ++ " "
353                       ++ "(" ++ ppType resTy ++ ")"
354             
355 sl_name i = "SLIT(\"" ++ name i ++ "\") "
356
357 ppTyVar "a" = "alphaTyVar"
358 ppTyVar "b" = "betaTyVar"
359 ppTyVar "c" = "gammaTyVar"
360 ppTyVar "s" = "deltaTyVar"
361 ppTyVar "o" = "openAlphaTyVar"
362
363
364 ppType (TyApp "Bool"        []) = "boolTy"
365
366 ppType (TyApp "Int#"        []) = "intPrimTy"
367 ppType (TyApp "Int32#"      []) = "int32PrimTy"
368 ppType (TyApp "Int64#"      []) = "int64PrimTy"
369 ppType (TyApp "Char#"       []) = "charPrimTy"
370 ppType (TyApp "Word#"       []) = "wordPrimTy"
371 ppType (TyApp "Word32#"     []) = "word32PrimTy"
372 ppType (TyApp "Word64#"     []) = "word64PrimTy"
373 ppType (TyApp "Addr#"       []) = "addrPrimTy"
374 ppType (TyApp "Float#"      []) = "floatPrimTy"
375 ppType (TyApp "Double#"     []) = "doublePrimTy"
376 ppType (TyApp "ByteArr#"    []) = "byteArrayPrimTy"
377 ppType (TyApp "RealWorld"   []) = "realWorldTy"
378 ppType (TyApp "ThreadId#"   []) = "threadIdPrimTy"
379 ppType (TyApp "ForeignObj#" []) = "foreignObjPrimTy"
380 ppType (TyApp "BCO#"        []) = "bcoPrimTy"
381 ppType (TyApp "Unit"        []) = "unitTy"   -- dodgy
382
383
384 ppType (TyVar "a")               = "alphaTy"
385 ppType (TyVar "b")               = "betaTy"
386 ppType (TyVar "c")               = "gammaTy"
387 ppType (TyVar "s")               = "deltaTy"
388 ppType (TyVar "o")               = "openAlphaTy"
389 ppType (TyApp "State#" [x])      = "mkStatePrimTy " ++ ppType x
390 ppType (TyApp "MutVar#" [x,y])   = "mkMutVarPrimTy " ++ ppType x 
391                                    ++ " " ++ ppType y
392 ppType (TyApp "MutArr#" [x,y])   = "mkMutableArrayPrimTy " ++ ppType x 
393                                    ++ " " ++ ppType y
394
395 ppType (TyApp "MutByteArr#" [x]) = "mkMutableByteArrayPrimTy " 
396                                    ++ ppType x
397
398 ppType (TyApp "Array#" [x])      = "mkArrayPrimTy " ++ ppType x
399
400
401 ppType (TyApp "Weak#"  [x])      = "mkWeakPrimTy " ++ ppType x
402 ppType (TyApp "StablePtr#"  [x])      = "mkStablePtrPrimTy " ++ ppType x
403 ppType (TyApp "StableName#"  [x])      = "mkStableNamePrimTy " ++ ppType x
404
405 ppType (TyApp "MVar#" [x,y])     = "mkMVarPrimTy " ++ ppType x 
406                                    ++ " " ++ ppType y
407 ppType (TyUTup ts)               = "(mkTupleTy Unboxed " ++ show (length ts)
408                                    ++ " "
409                                    ++ listify (map ppType ts) ++ ")"
410
411 ppType (TyF s d) = "(mkFunTy (" ++ ppType s ++ ") (" ++ ppType d ++ "))"
412
413 ppType other
414    = error ("ppType: can't handle: " ++ show other ++ "\n")
415
416 listify :: [String] -> String
417 listify ss = "[" ++ concat (intersperse ", " ss) ++ "]"
418
419 flatTys (TyF t1 t2) = case flatTys t2 of (ts,t) -> (t1:ts,t)
420 flatTys other       = ([],other)
421
422 tvsIn (TyF t1 t2)    = tvsIn t1 ++ tvsIn t2
423 tvsIn (TyApp tc tys) = concatMap tvsIn tys
424 tvsIn (TyVar tv)     = [tv]
425 tvsIn (TyUTup tys)   = concatMap tvsIn tys
426
427 arity = length . fst . flatTys
428
429
430 ------------------------------------------------------------------
431 -- Abstract syntax -----------------------------------------------
432 ------------------------------------------------------------------
433
434 -- info for all primops; the totality of the info in primops.txt(.pp)
435 data Info
436    = Info [Option] [Entry]   -- defaults, primops
437      deriving Show
438
439 -- info for one primop
440 data Entry
441     = PrimOpSpec { cons  :: String,      -- PrimOp name
442                    name  :: String,      -- name in prog text
443                    ty    :: Ty,          -- type
444                    cat   :: Category,    -- category
445                    desc  :: String,      -- description
446                    opts  :: [Option] }   -- default overrides
447     | Section { title :: String,         -- section title
448                 desc  :: String }        -- description
449     deriving Show
450
451 is_primop (PrimOpSpec _ _ _ _ _ _) = True
452 is_primop _ = False
453
454 -- a binding of property to value
455 data Option
456    = OptionFalse  String          -- name = False
457    | OptionTrue   String          -- name = True
458    | OptionString String String   -- name = { ... unparsed stuff ... }
459      deriving Show
460
461 -- categorises primops
462 data Category
463    = Dyadic | Monadic | Compare | GenPrimOp
464      deriving Show
465
466 -- types
467 data Ty
468    = TyF    Ty Ty
469    | TyApp  TyCon [Ty]
470    | TyVar  TyVar
471    | TyUTup [Ty]   -- unboxed tuples; just a TyCon really, 
472                    -- but convenient like this
473    deriving (Eq,Show)
474
475 type TyVar = String
476 type TyCon = String
477
478
479 ------------------------------------------------------------------
480 -- Sanity checking -----------------------------------------------
481 ------------------------------------------------------------------
482
483 {- Do some simple sanity checks:
484     * all the default field names are unique
485     * for each PrimOpSpec, all override field names are unique
486     * for each PrimOpSpec, all overriden field names   
487           have a corresponding default value
488     * that primop types correspond in certain ways to the 
489       Category: eg if Comparison, the type must be of the form
490          T -> T -> Bool.
491    Dies with "error" if there's a problem, else returns ().
492 -}
493 myseq () x = x
494 myseqAll (():ys) x = myseqAll ys x
495 myseqAll []      x = x
496
497 sanityTop :: Info -> ()
498 sanityTop (Info defs entries)
499    = let opt_names = map get_attrib_name defs
500          primops = filter is_primop entries
501      in  
502      if   length opt_names /= length (nub opt_names)
503      then error ("non-unique default attribute names: " ++ show opt_names ++ "\n")
504      else myseqAll (map (sanityPrimOp opt_names) primops) ()
505
506 sanityPrimOp def_names p
507    = let p_names = map get_attrib_name (opts p)
508          p_names_ok
509             = length p_names == length (nub p_names)
510               && all (`elem` def_names) p_names
511          ty_ok = sane_ty (cat p) (ty p)
512      in
513          if   not p_names_ok
514          then error ("attribute names are non-unique or have no default in\n" ++
515                      "info for primop " ++ cons p ++ "\n")
516          else
517          if   not ty_ok
518          then error ("type of primop " ++ cons p ++ " doesn't make sense w.r.t" ++
519                      " category " ++ show (cat p) ++ "\n")
520          else ()
521
522 sane_ty Compare (TyF t1 (TyF t2 td)) 
523    | t1 == t2 && td == TyApp "Bool" []  = True
524 sane_ty Monadic (TyF t1 td) 
525    | t1 == td  = True
526 sane_ty Dyadic (TyF t1 (TyF t2 td))
527    | t1 == t2 && t2 == t2  = True
528 sane_ty GenPrimOp any_old_thing
529    = True
530 sane_ty _ _
531    = False
532
533 get_attrib_name (OptionFalse nm) = nm
534 get_attrib_name (OptionTrue nm)  = nm
535 get_attrib_name (OptionString nm _) = nm
536
537 lookup_attrib nm [] = Nothing
538 lookup_attrib nm (a:as) 
539     = if get_attrib_name a == nm then Just a else lookup_attrib nm as
540
541 ------------------------------------------------------------------
542 -- The parser ----------------------------------------------------
543 ------------------------------------------------------------------
544
545 -- Due to lack of proper lexing facilities, a hack to zap any
546 -- leading comments
547 pTop :: Parser Info
548 pTop = then4 (\_ ds es _ -> Info ds es) 
549              pCommentAndWhitespace pDefaults (many pEntry)
550              (lit "thats_all_folks")
551
552 pEntry :: Parser Entry
553 pEntry 
554   = alts [pPrimOpSpec, pSection]
555
556 pSection :: Parser Entry
557 pSection = then3 (\_ n d -> Section {title = n, desc = d}) 
558                  (lit "section") stringLiteral pDesc
559
560 pDefaults :: Parser [Option]
561 pDefaults = then2 sel22 (lit "defaults") (many pOption)
562
563 pOption :: Parser Option
564 pOption 
565    = alts [
566         then3 (\nm eq ff -> OptionFalse nm)  pName (lit "=") (lit "False"),
567         then3 (\nm eq tt -> OptionTrue nm)   pName (lit "=") (lit "True"),
568         then3 (\nm eq zz -> OptionString nm zz)
569               pName (lit "=") pStuffBetweenBraces
570      ]
571
572 pPrimOpSpec :: Parser Entry
573 pPrimOpSpec
574    = then7 (\_ c n k t d o -> PrimOpSpec { cons = c, name = n, ty = t, 
575                                            cat = k, desc = d, opts = o } )
576            (lit "primop") pConstructor stringLiteral 
577            pCategory pType pDesc pOptions
578
579 pOptions :: Parser [Option]
580 pOptions = optdef [] (then2 sel22 (lit "with") (many pOption))
581
582 pCategory :: Parser Category
583 pCategory 
584    = alts [
585         apply (const Dyadic)    (lit "Dyadic"),
586         apply (const Monadic)   (lit "Monadic"),
587         apply (const Compare)   (lit "Compare"),
588         apply (const GenPrimOp) (lit "GenPrimOp")
589      ]
590
591 pDesc :: Parser String
592 pDesc = optdef "" pStuffBetweenBraces
593
594 pStuffBetweenBraces :: Parser String
595 pStuffBetweenBraces
596     = lexeme (
597         do char '{'
598            ass <- many pInsides
599            char '}'
600            return (concat ass) )
601
602 pInsides :: Parser String
603 pInsides 
604     = (do char '{' 
605           stuff <- many pInsides
606           char '}'
607           return ("{" ++ (concat stuff) ++ "}"))
608       <|> 
609       (do c <- satisfy (/= '}')
610           return [c])
611
612
613
614 -------------------
615 -- Parsing types --
616 -------------------
617
618 pType :: Parser Ty
619 pType = then2 (\t maybe_tt -> case maybe_tt of 
620                                  Just tt -> TyF t tt
621                                  Nothing -> t)
622               paT 
623               (opt (then2 sel22 (lit "->") pType))
624
625 -- Atomic types
626 paT = alts [ then2 TyApp pTycon (many ppT),
627              pUnboxedTupleTy,
628              then3 sel23 (lit "(") pType (lit ")"),
629              ppT 
630       ]
631
632 -- the magic bit in the middle is:  T (,T)*  so to speak
633 pUnboxedTupleTy
634    = then3 (\ _ ts _ -> TyUTup ts)
635            (lit "(#")
636            (then2 (:) pType (many (then2 sel22 (lit ",") pType)))
637            (lit "#)")
638
639 -- Primitive types
640 ppT = alts [apply TyVar pTyvar,
641             apply (\tc -> TyApp tc []) pTycon
642            ]
643
644 pTyvar       = sat (`notElem` ["section","primop","with"]) pName
645 pTycon       = pConstructor
646 pName        = lexeme (then2 (:) lower (many isIdChar))
647 pConstructor = lexeme (then2 (:) upper (many isIdChar))
648
649 isIdChar = satisfy (`elem` idChars)
650 idChars  = ['a' .. 'z'] ++ ['A' .. 'Z'] ++ ['0' .. '9'] ++ "#_"
651
652 sat pred p
653    = do x <- try p
654         if pred x
655          then return x
656          else pzero
657
658 ------------------------------------------------------------------
659 -- Helpful additions to Daan's parser stuff ----------------------
660 ------------------------------------------------------------------
661
662 alts [p1]       = try p1
663 alts (p1:p2:ps) = (try p1) <|> alts (p2:ps)
664
665 then2 f p1 p2 
666    = do x1 <- p1 ; x2 <- p2 ; return (f x1 x2)
667 then3 f p1 p2 p3
668    = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; return (f x1 x2 x3)
669 then4 f p1 p2 p3 p4
670    = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; return (f x1 x2 x3 x4)
671 then5 f p1 p2 p3 p4 p5
672    = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; x5 <- p5
673         return (f x1 x2 x3 x4 x5)
674 then6 f p1 p2 p3 p4 p5 p6
675    = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; x5 <- p5 ; x6 <- p6
676         return (f x1 x2 x3 x4 x5 x6)
677 then7 f p1 p2 p3 p4 p5 p6 p7
678    = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; x5 <- p5 ; x6 <- p6 ; x7 <- p7
679         return (f x1 x2 x3 x4 x5 x6 x7)
680 opt p
681    = (do x <- p; return (Just x)) <|> return Nothing
682 optdef d p
683    = (do x <- p; return x) <|> return d
684
685 sel12 a b = a
686 sel22 a b = b
687 sel23 a b c = b
688 apply f p = liftM f p
689
690 -- Hacks for zapping whitespace and comments, unfortunately needed
691 -- because Daan won't let us have a lexer before the parser :-(
692 lexeme  :: Parser p -> Parser p
693 lexeme p = then2 sel12 p pCommentAndWhitespace
694
695 lit :: String -> Parser ()
696 lit s = apply (const ()) (lexeme (string s))
697
698 pCommentAndWhitespace :: Parser ()
699 pCommentAndWhitespace
700    = apply (const ()) (many (alts [pLineComment, 
701                                    apply (const ()) (satisfy isSpace)]))
702      <|>
703      return ()
704
705 pLineComment :: Parser ()
706 pLineComment
707    = try (then3 (\_ _ _ -> ()) (string "--") (many (satisfy (/= '\n'))) (char '\n'))
708
709 stringLiteral :: Parser String
710 stringLiteral   = lexeme (
711                       do { between (char '"')                   
712                                    (char '"' <?> "end of string")
713                                    (many (noneOf "\"")) 
714                          }
715                       <?> "literal string")
716
717
718
719 ------------------------------------------------------------------
720 -- end                                                          --
721 ------------------------------------------------------------------
722
723
724