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