cc29e6dcf4ae8840140a3974569b771daeedc1dd
[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 (max_def : zipWith f primop_entries [1..])
294      where
295         primop_entries = filter is_primop entries
296         f i n = "tagOf_PrimOp " ++ cons i 
297                 ++ " = _ILIT(" ++ show n ++ ") :: FastInt"
298         max_def = "maxPrimOpTag = " ++ show (length primop_entries) ++ " :: Int"
299
300 gen_data_decl (Info defaults entries)
301    = let conss = map cons (filter is_primop entries)
302      in  "data PrimOp\n   = " ++ head conss ++ "\n"
303          ++ unlines (map ("   | "++) (tail conss))
304
305 gen_switch_from_attribs :: String -> String -> Info -> String
306 gen_switch_from_attribs attrib_name fn_name (Info defaults entries)
307    = let defv = lookup_attrib attrib_name defaults
308          alts = catMaybes (map mkAlt (filter is_primop entries))
309
310          getAltRhs (OptionFalse _)    = "False"
311          getAltRhs (OptionTrue _)     = "True"
312          getAltRhs (OptionString _ s) = s
313
314          mkAlt po
315             = case lookup_attrib attrib_name (opts po) of
316                  Nothing -> Nothing
317                  Just xx -> Just (fn_name ++ " " ++ cons po ++ " = " ++ getAltRhs xx)
318
319      in
320          case defv of
321             Nothing -> error ("gen_switch_from: " ++ attrib_name)
322             Just xx 
323                -> unlines alts 
324                   ++ fn_name ++ " other = " ++ getAltRhs xx ++ "\n"
325
326 ------------------------------------------------------------------
327 -- Create PrimOpInfo text from PrimOpSpecs -----------------------
328 ------------------------------------------------------------------
329
330
331 gen_primop_info (Info defaults entries)
332    = unlines (map mkPOItext (filter is_primop entries))
333
334 mkPOItext i = mkPOI_LHS_text i ++ mkPOI_RHS_text i
335
336 mkPOI_LHS_text i
337    = "primOpInfo " ++ cons i ++ " = "
338
339 mkPOI_RHS_text i
340    = case cat i of
341         Compare 
342            -> case ty i of
343                  TyF t1 (TyF t2 td) 
344                     -> "mkCompare " ++ sl_name i ++ ppType t1
345         Monadic
346            -> case ty i of
347                  TyF t1 td
348                     -> "mkMonadic " ++ sl_name i ++ ppType t1
349         Dyadic
350            -> case ty i of
351                  TyF t1 (TyF t2 td)
352                     -> "mkDyadic " ++ sl_name i ++ ppType t1
353         GenPrimOp
354            -> let (argTys, resTy) = flatTys (ty i)
355                   tvs = nub (tvsIn (ty i))
356               in
357                   "mkGenPrimOp " ++ sl_name i ++ " " 
358                       ++ listify (map ppTyVar tvs) ++ " "
359                       ++ listify (map ppType argTys) ++ " "
360                       ++ "(" ++ ppType resTy ++ ")"
361             
362 sl_name i = "FSLIT(\"" ++ name i ++ "\") "
363
364 ppTyVar "a" = "alphaTyVar"
365 ppTyVar "b" = "betaTyVar"
366 ppTyVar "c" = "gammaTyVar"
367 ppTyVar "s" = "deltaTyVar"
368 ppTyVar "o" = "openAlphaTyVar"
369
370
371 ppType (TyApp "Bool"        []) = "boolTy"
372
373 ppType (TyApp "Int#"        []) = "intPrimTy"
374 ppType (TyApp "Int32#"      []) = "int32PrimTy"
375 ppType (TyApp "Int64#"      []) = "int64PrimTy"
376 ppType (TyApp "Char#"       []) = "charPrimTy"
377 ppType (TyApp "Word#"       []) = "wordPrimTy"
378 ppType (TyApp "Word32#"     []) = "word32PrimTy"
379 ppType (TyApp "Word64#"     []) = "word64PrimTy"
380 ppType (TyApp "Addr#"       []) = "addrPrimTy"
381 ppType (TyApp "Float#"      []) = "floatPrimTy"
382 ppType (TyApp "Double#"     []) = "doublePrimTy"
383 ppType (TyApp "ByteArr#"    []) = "byteArrayPrimTy"
384 ppType (TyApp "RealWorld"   []) = "realWorldTy"
385 ppType (TyApp "ThreadId#"   []) = "threadIdPrimTy"
386 ppType (TyApp "ForeignObj#" []) = "foreignObjPrimTy"
387 ppType (TyApp "BCO#"        []) = "bcoPrimTy"
388 ppType (TyApp "()"          []) = "unitTy"      -- unitTy is TysWiredIn's name for ()
389
390
391 ppType (TyVar "a")               = "alphaTy"
392 ppType (TyVar "b")               = "betaTy"
393 ppType (TyVar "c")               = "gammaTy"
394 ppType (TyVar "s")               = "deltaTy"
395 ppType (TyVar "o")               = "openAlphaTy"
396 ppType (TyApp "State#" [x])      = "mkStatePrimTy " ++ ppType x
397 ppType (TyApp "MutVar#" [x,y])   = "mkMutVarPrimTy " ++ ppType x 
398                                    ++ " " ++ ppType y
399 ppType (TyApp "MutArr#" [x,y])   = "mkMutableArrayPrimTy " ++ ppType x 
400                                    ++ " " ++ ppType y
401
402 ppType (TyApp "MutByteArr#" [x]) = "mkMutableByteArrayPrimTy " 
403                                    ++ ppType x
404
405 ppType (TyApp "Array#" [x])      = "mkArrayPrimTy " ++ ppType x
406
407
408 ppType (TyApp "Weak#"  [x])      = "mkWeakPrimTy " ++ ppType x
409 ppType (TyApp "StablePtr#"  [x])      = "mkStablePtrPrimTy " ++ ppType x
410 ppType (TyApp "StableName#"  [x])      = "mkStableNamePrimTy " ++ ppType x
411
412 ppType (TyApp "MVar#" [x,y])     = "mkMVarPrimTy " ++ ppType x 
413                                    ++ " " ++ ppType y
414 ppType (TyApp "TVar#" [x,y])     = "mkTVarPrimTy " ++ ppType x 
415                                    ++ " " ++ ppType y
416 ppType (TyUTup ts)               = "(mkTupleTy Unboxed " ++ show (length ts)
417                                    ++ " "
418                                    ++ listify (map ppType ts) ++ ")"
419
420 ppType (TyF s d) = "(mkFunTy (" ++ ppType s ++ ") (" ++ ppType d ++ "))"
421
422 ppType other
423    = error ("ppType: can't handle: " ++ show other ++ "\n")
424
425 listify :: [String] -> String
426 listify ss = "[" ++ concat (intersperse ", " ss) ++ "]"
427
428 flatTys (TyF t1 t2) = case flatTys t2 of (ts,t) -> (t1:ts,t)
429 flatTys other       = ([],other)
430
431 tvsIn (TyF t1 t2)    = tvsIn t1 ++ tvsIn t2
432 tvsIn (TyApp tc tys) = concatMap tvsIn tys
433 tvsIn (TyVar tv)     = [tv]
434 tvsIn (TyUTup tys)   = concatMap tvsIn tys
435
436 arity = length . fst . flatTys
437
438
439 ------------------------------------------------------------------
440 -- Abstract syntax -----------------------------------------------
441 ------------------------------------------------------------------
442
443 -- info for all primops; the totality of the info in primops.txt(.pp)
444 data Info
445    = Info [Option] [Entry]   -- defaults, primops
446      deriving Show
447
448 -- info for one primop
449 data Entry
450     = PrimOpSpec { cons  :: String,      -- PrimOp name
451                    name  :: String,      -- name in prog text
452                    ty    :: Ty,          -- type
453                    cat   :: Category,    -- category
454                    desc  :: String,      -- description
455                    opts  :: [Option] }   -- default overrides
456     | Section { title :: String,         -- section title
457                 desc  :: String }        -- description
458     deriving Show
459
460 is_primop (PrimOpSpec _ _ _ _ _ _) = True
461 is_primop _ = False
462
463 -- a binding of property to value
464 data Option
465    = OptionFalse  String          -- name = False
466    | OptionTrue   String          -- name = True
467    | OptionString String String   -- name = { ... unparsed stuff ... }
468      deriving Show
469
470 -- categorises primops
471 data Category
472    = Dyadic | Monadic | Compare | GenPrimOp
473      deriving Show
474
475 -- types
476 data Ty
477    = TyF    Ty Ty
478    | TyApp  TyCon [Ty]
479    | TyVar  TyVar
480    | TyUTup [Ty]   -- unboxed tuples; just a TyCon really, 
481                    -- but convenient like this
482    deriving (Eq,Show)
483
484 type TyVar = String
485 type TyCon = String
486
487
488 ------------------------------------------------------------------
489 -- Sanity checking -----------------------------------------------
490 ------------------------------------------------------------------
491
492 {- Do some simple sanity checks:
493     * all the default field names are unique
494     * for each PrimOpSpec, all override field names are unique
495     * for each PrimOpSpec, all overriden field names   
496           have a corresponding default value
497     * that primop types correspond in certain ways to the 
498       Category: eg if Comparison, the type must be of the form
499          T -> T -> Bool.
500    Dies with "error" if there's a problem, else returns ().
501 -}
502 myseq () x = x
503 myseqAll (():ys) x = myseqAll ys x
504 myseqAll []      x = x
505
506 sanityTop :: Info -> ()
507 sanityTop (Info defs entries)
508    = let opt_names = map get_attrib_name defs
509          primops = filter is_primop entries
510      in  
511      if   length opt_names /= length (nub opt_names)
512      then error ("non-unique default attribute names: " ++ show opt_names ++ "\n")
513      else myseqAll (map (sanityPrimOp opt_names) primops) ()
514
515 sanityPrimOp def_names p
516    = let p_names = map get_attrib_name (opts p)
517          p_names_ok
518             = length p_names == length (nub p_names)
519               && all (`elem` def_names) p_names
520          ty_ok = sane_ty (cat p) (ty p)
521      in
522          if   not p_names_ok
523          then error ("attribute names are non-unique or have no default in\n" ++
524                      "info for primop " ++ cons p ++ "\n")
525          else
526          if   not ty_ok
527          then error ("type of primop " ++ cons p ++ " doesn't make sense w.r.t" ++
528                      " category " ++ show (cat p) ++ "\n")
529          else ()
530
531 sane_ty Compare (TyF t1 (TyF t2 td)) 
532    | t1 == t2 && td == TyApp "Bool" []  = True
533 sane_ty Monadic (TyF t1 td) 
534    | t1 == td  = True
535 sane_ty Dyadic (TyF t1 (TyF t2 td))
536    | t1 == t2 && t2 == t2  = True
537 sane_ty GenPrimOp any_old_thing
538    = True
539 sane_ty _ _
540    = False
541
542 get_attrib_name (OptionFalse nm) = nm
543 get_attrib_name (OptionTrue nm)  = nm
544 get_attrib_name (OptionString nm _) = nm
545
546 lookup_attrib nm [] = Nothing
547 lookup_attrib nm (a:as) 
548     = if get_attrib_name a == nm then Just a else lookup_attrib nm as
549
550 ------------------------------------------------------------------
551 -- The parser ----------------------------------------------------
552 ------------------------------------------------------------------
553
554 -- Due to lack of proper lexing facilities, a hack to zap any
555 -- leading comments
556 pTop :: Parser Info
557 pTop = then4 (\_ ds es _ -> Info ds es) 
558              pCommentAndWhitespace pDefaults (many pEntry)
559              (lit "thats_all_folks")
560
561 pEntry :: Parser Entry
562 pEntry 
563   = alts [pPrimOpSpec, pSection]
564
565 pSection :: Parser Entry
566 pSection = then3 (\_ n d -> Section {title = n, desc = d}) 
567                  (lit "section") stringLiteral pDesc
568
569 pDefaults :: Parser [Option]
570 pDefaults = then2 sel22 (lit "defaults") (many pOption)
571
572 pOption :: Parser Option
573 pOption 
574    = alts [
575         then3 (\nm eq ff -> OptionFalse nm)  pName (lit "=") (lit "False"),
576         then3 (\nm eq tt -> OptionTrue nm)   pName (lit "=") (lit "True"),
577         then3 (\nm eq zz -> OptionString nm zz)
578               pName (lit "=") pStuffBetweenBraces
579      ]
580
581 pPrimOpSpec :: Parser Entry
582 pPrimOpSpec
583    = then7 (\_ c n k t d o -> PrimOpSpec { cons = c, name = n, ty = t, 
584                                            cat = k, desc = d, opts = o } )
585            (lit "primop") pConstructor stringLiteral 
586            pCategory pType pDesc pOptions
587
588 pOptions :: Parser [Option]
589 pOptions = optdef [] (then2 sel22 (lit "with") (many pOption))
590
591 pCategory :: Parser Category
592 pCategory 
593    = alts [
594         apply (const Dyadic)    (lit "Dyadic"),
595         apply (const Monadic)   (lit "Monadic"),
596         apply (const Compare)   (lit "Compare"),
597         apply (const GenPrimOp) (lit "GenPrimOp")
598      ]
599
600 pDesc :: Parser String
601 pDesc = optdef "" pStuffBetweenBraces
602
603 pStuffBetweenBraces :: Parser String
604 pStuffBetweenBraces
605     = lexeme (
606         do char '{'
607            ass <- many pInsides
608            char '}'
609            return (concat ass) )
610
611 pInsides :: Parser String
612 pInsides 
613     = (do char '{' 
614           stuff <- many pInsides
615           char '}'
616           return ("{" ++ (concat stuff) ++ "}"))
617       <|> 
618       (do c <- satisfy (/= '}')
619           return [c])
620
621
622
623 -------------------
624 -- Parsing types --
625 -------------------
626
627 pType :: Parser Ty
628 pType = then2 (\t maybe_tt -> case maybe_tt of 
629                                  Just tt -> TyF t tt
630                                  Nothing -> t)
631               paT 
632               (opt (then2 sel22 (lit "->") pType))
633
634 -- Atomic types
635 paT = alts [ then2 TyApp pTycon (many ppT),
636              pUnboxedTupleTy,
637              then3 sel23 (lit "(") pType (lit ")"),
638              ppT 
639       ]
640
641 -- the magic bit in the middle is:  T (,T)*  so to speak
642 pUnboxedTupleTy
643    = then3 (\ _ ts _ -> TyUTup ts)
644            (lit "(#")
645            (then2 (:) pType (many (then2 sel22 (lit ",") pType)))
646            (lit "#)")
647
648 -- Primitive types
649 ppT = alts [apply TyVar pTyvar,
650             apply (\tc -> TyApp tc []) pTycon
651            ]
652
653 pTyvar       = sat (`notElem` ["section","primop","with"]) pName
654 pTycon       = alts [pConstructor, lexeme (string "()")]
655 pName        = lexeme (then2 (:) lower (many isIdChar))
656 pConstructor = lexeme (then2 (:) upper (many isIdChar))
657
658 isIdChar = satisfy (`elem` idChars)
659 idChars  = ['a' .. 'z'] ++ ['A' .. 'Z'] ++ ['0' .. '9'] ++ "#_"
660
661 sat pred p
662    = do x <- try p
663         if pred x
664          then return x
665          else pzero
666
667 ------------------------------------------------------------------
668 -- Helpful additions to Daan's parser stuff ----------------------
669 ------------------------------------------------------------------
670
671 alts [p1]       = try p1
672 alts (p1:p2:ps) = (try p1) <|> alts (p2:ps)
673
674 then2 f p1 p2 
675    = do x1 <- p1 ; x2 <- p2 ; return (f x1 x2)
676 then3 f p1 p2 p3
677    = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; return (f x1 x2 x3)
678 then4 f p1 p2 p3 p4
679    = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; return (f x1 x2 x3 x4)
680 then5 f p1 p2 p3 p4 p5
681    = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; x5 <- p5
682         return (f x1 x2 x3 x4 x5)
683 then6 f p1 p2 p3 p4 p5 p6
684    = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; x5 <- p5 ; x6 <- p6
685         return (f x1 x2 x3 x4 x5 x6)
686 then7 f p1 p2 p3 p4 p5 p6 p7
687    = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; x5 <- p5 ; x6 <- p6 ; x7 <- p7
688         return (f x1 x2 x3 x4 x5 x6 x7)
689 opt p
690    = (do x <- p; return (Just x)) <|> return Nothing
691 optdef d p
692    = (do x <- p; return x) <|> return d
693
694 sel12 a b = a
695 sel22 a b = b
696 sel23 a b c = b
697 apply f p = liftM f p
698
699 -- Hacks for zapping whitespace and comments, unfortunately needed
700 -- because Daan won't let us have a lexer before the parser :-(
701 lexeme  :: Parser p -> Parser p
702 lexeme p = then2 sel12 p pCommentAndWhitespace
703
704 lit :: String -> Parser ()
705 lit s = apply (const ()) (lexeme (string s))
706
707 pCommentAndWhitespace :: Parser ()
708 pCommentAndWhitespace
709    = apply (const ()) (many (alts [pLineComment, 
710                                    apply (const ()) (satisfy isSpace)]))
711      <|>
712      return ()
713
714 pLineComment :: Parser ()
715 pLineComment
716    = try (then3 (\_ _ _ -> ()) (string "--") (many (satisfy (/= '\n'))) (char '\n'))
717
718 stringLiteral :: Parser String
719 stringLiteral   = lexeme (
720                       do { between (char '"')                   
721                                    (char '"' <?> "end of string")
722                                    (many (noneOf "\"")) 
723                          }
724                       <?> "literal string")
725
726
727
728 ------------------------------------------------------------------
729 -- end                                                          --
730 ------------------------------------------------------------------
731
732
733