e486403a80e8c57bc122614227c2b4e07ee489a8
[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 (TyUTup ts)               = "(mkTupleTy Unboxed " ++ show (length ts)
415                                    ++ " "
416                                    ++ listify (map ppType ts) ++ ")"
417
418 ppType (TyF s d) = "(mkFunTy (" ++ ppType s ++ ") (" ++ ppType d ++ "))"
419
420 ppType other
421    = error ("ppType: can't handle: " ++ show other ++ "\n")
422
423 listify :: [String] -> String
424 listify ss = "[" ++ concat (intersperse ", " ss) ++ "]"
425
426 flatTys (TyF t1 t2) = case flatTys t2 of (ts,t) -> (t1:ts,t)
427 flatTys other       = ([],other)
428
429 tvsIn (TyF t1 t2)    = tvsIn t1 ++ tvsIn t2
430 tvsIn (TyApp tc tys) = concatMap tvsIn tys
431 tvsIn (TyVar tv)     = [tv]
432 tvsIn (TyUTup tys)   = concatMap tvsIn tys
433
434 arity = length . fst . flatTys
435
436
437 ------------------------------------------------------------------
438 -- Abstract syntax -----------------------------------------------
439 ------------------------------------------------------------------
440
441 -- info for all primops; the totality of the info in primops.txt(.pp)
442 data Info
443    = Info [Option] [Entry]   -- defaults, primops
444      deriving Show
445
446 -- info for one primop
447 data Entry
448     = PrimOpSpec { cons  :: String,      -- PrimOp name
449                    name  :: String,      -- name in prog text
450                    ty    :: Ty,          -- type
451                    cat   :: Category,    -- category
452                    desc  :: String,      -- description
453                    opts  :: [Option] }   -- default overrides
454     | Section { title :: String,         -- section title
455                 desc  :: String }        -- description
456     deriving Show
457
458 is_primop (PrimOpSpec _ _ _ _ _ _) = True
459 is_primop _ = False
460
461 -- a binding of property to value
462 data Option
463    = OptionFalse  String          -- name = False
464    | OptionTrue   String          -- name = True
465    | OptionString String String   -- name = { ... unparsed stuff ... }
466      deriving Show
467
468 -- categorises primops
469 data Category
470    = Dyadic | Monadic | Compare | GenPrimOp
471      deriving Show
472
473 -- types
474 data Ty
475    = TyF    Ty Ty
476    | TyApp  TyCon [Ty]
477    | TyVar  TyVar
478    | TyUTup [Ty]   -- unboxed tuples; just a TyCon really, 
479                    -- but convenient like this
480    deriving (Eq,Show)
481
482 type TyVar = String
483 type TyCon = String
484
485
486 ------------------------------------------------------------------
487 -- Sanity checking -----------------------------------------------
488 ------------------------------------------------------------------
489
490 {- Do some simple sanity checks:
491     * all the default field names are unique
492     * for each PrimOpSpec, all override field names are unique
493     * for each PrimOpSpec, all overriden field names   
494           have a corresponding default value
495     * that primop types correspond in certain ways to the 
496       Category: eg if Comparison, the type must be of the form
497          T -> T -> Bool.
498    Dies with "error" if there's a problem, else returns ().
499 -}
500 myseq () x = x
501 myseqAll (():ys) x = myseqAll ys x
502 myseqAll []      x = x
503
504 sanityTop :: Info -> ()
505 sanityTop (Info defs entries)
506    = let opt_names = map get_attrib_name defs
507          primops = filter is_primop entries
508      in  
509      if   length opt_names /= length (nub opt_names)
510      then error ("non-unique default attribute names: " ++ show opt_names ++ "\n")
511      else myseqAll (map (sanityPrimOp opt_names) primops) ()
512
513 sanityPrimOp def_names p
514    = let p_names = map get_attrib_name (opts p)
515          p_names_ok
516             = length p_names == length (nub p_names)
517               && all (`elem` def_names) p_names
518          ty_ok = sane_ty (cat p) (ty p)
519      in
520          if   not p_names_ok
521          then error ("attribute names are non-unique or have no default in\n" ++
522                      "info for primop " ++ cons p ++ "\n")
523          else
524          if   not ty_ok
525          then error ("type of primop " ++ cons p ++ " doesn't make sense w.r.t" ++
526                      " category " ++ show (cat p) ++ "\n")
527          else ()
528
529 sane_ty Compare (TyF t1 (TyF t2 td)) 
530    | t1 == t2 && td == TyApp "Bool" []  = True
531 sane_ty Monadic (TyF t1 td) 
532    | t1 == td  = True
533 sane_ty Dyadic (TyF t1 (TyF t2 td))
534    | t1 == t2 && t2 == t2  = True
535 sane_ty GenPrimOp any_old_thing
536    = True
537 sane_ty _ _
538    = False
539
540 get_attrib_name (OptionFalse nm) = nm
541 get_attrib_name (OptionTrue nm)  = nm
542 get_attrib_name (OptionString nm _) = nm
543
544 lookup_attrib nm [] = Nothing
545 lookup_attrib nm (a:as) 
546     = if get_attrib_name a == nm then Just a else lookup_attrib nm as
547
548 ------------------------------------------------------------------
549 -- The parser ----------------------------------------------------
550 ------------------------------------------------------------------
551
552 -- Due to lack of proper lexing facilities, a hack to zap any
553 -- leading comments
554 pTop :: Parser Info
555 pTop = then4 (\_ ds es _ -> Info ds es) 
556              pCommentAndWhitespace pDefaults (many pEntry)
557              (lit "thats_all_folks")
558
559 pEntry :: Parser Entry
560 pEntry 
561   = alts [pPrimOpSpec, pSection]
562
563 pSection :: Parser Entry
564 pSection = then3 (\_ n d -> Section {title = n, desc = d}) 
565                  (lit "section") stringLiteral pDesc
566
567 pDefaults :: Parser [Option]
568 pDefaults = then2 sel22 (lit "defaults") (many pOption)
569
570 pOption :: Parser Option
571 pOption 
572    = alts [
573         then3 (\nm eq ff -> OptionFalse nm)  pName (lit "=") (lit "False"),
574         then3 (\nm eq tt -> OptionTrue nm)   pName (lit "=") (lit "True"),
575         then3 (\nm eq zz -> OptionString nm zz)
576               pName (lit "=") pStuffBetweenBraces
577      ]
578
579 pPrimOpSpec :: Parser Entry
580 pPrimOpSpec
581    = then7 (\_ c n k t d o -> PrimOpSpec { cons = c, name = n, ty = t, 
582                                            cat = k, desc = d, opts = o } )
583            (lit "primop") pConstructor stringLiteral 
584            pCategory pType pDesc pOptions
585
586 pOptions :: Parser [Option]
587 pOptions = optdef [] (then2 sel22 (lit "with") (many pOption))
588
589 pCategory :: Parser Category
590 pCategory 
591    = alts [
592         apply (const Dyadic)    (lit "Dyadic"),
593         apply (const Monadic)   (lit "Monadic"),
594         apply (const Compare)   (lit "Compare"),
595         apply (const GenPrimOp) (lit "GenPrimOp")
596      ]
597
598 pDesc :: Parser String
599 pDesc = optdef "" pStuffBetweenBraces
600
601 pStuffBetweenBraces :: Parser String
602 pStuffBetweenBraces
603     = lexeme (
604         do char '{'
605            ass <- many pInsides
606            char '}'
607            return (concat ass) )
608
609 pInsides :: Parser String
610 pInsides 
611     = (do char '{' 
612           stuff <- many pInsides
613           char '}'
614           return ("{" ++ (concat stuff) ++ "}"))
615       <|> 
616       (do c <- satisfy (/= '}')
617           return [c])
618
619
620
621 -------------------
622 -- Parsing types --
623 -------------------
624
625 pType :: Parser Ty
626 pType = then2 (\t maybe_tt -> case maybe_tt of 
627                                  Just tt -> TyF t tt
628                                  Nothing -> t)
629               paT 
630               (opt (then2 sel22 (lit "->") pType))
631
632 -- Atomic types
633 paT = alts [ then2 TyApp pTycon (many ppT),
634              pUnboxedTupleTy,
635              then3 sel23 (lit "(") pType (lit ")"),
636              ppT 
637       ]
638
639 -- the magic bit in the middle is:  T (,T)*  so to speak
640 pUnboxedTupleTy
641    = then3 (\ _ ts _ -> TyUTup ts)
642            (lit "(#")
643            (then2 (:) pType (many (then2 sel22 (lit ",") pType)))
644            (lit "#)")
645
646 -- Primitive types
647 ppT = alts [apply TyVar pTyvar,
648             apply (\tc -> TyApp tc []) pTycon
649            ]
650
651 pTyvar       = sat (`notElem` ["section","primop","with"]) pName
652 pTycon       = alts [pConstructor, lexeme (string "()")]
653 pName        = lexeme (then2 (:) lower (many isIdChar))
654 pConstructor = lexeme (then2 (:) upper (many isIdChar))
655
656 isIdChar = satisfy (`elem` idChars)
657 idChars  = ['a' .. 'z'] ++ ['A' .. 'Z'] ++ ['0' .. '9'] ++ "#_"
658
659 sat pred p
660    = do x <- try p
661         if pred x
662          then return x
663          else pzero
664
665 ------------------------------------------------------------------
666 -- Helpful additions to Daan's parser stuff ----------------------
667 ------------------------------------------------------------------
668
669 alts [p1]       = try p1
670 alts (p1:p2:ps) = (try p1) <|> alts (p2:ps)
671
672 then2 f p1 p2 
673    = do x1 <- p1 ; x2 <- p2 ; return (f x1 x2)
674 then3 f p1 p2 p3
675    = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; return (f x1 x2 x3)
676 then4 f p1 p2 p3 p4
677    = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; return (f x1 x2 x3 x4)
678 then5 f p1 p2 p3 p4 p5
679    = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; x5 <- p5
680         return (f x1 x2 x3 x4 x5)
681 then6 f p1 p2 p3 p4 p5 p6
682    = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; x5 <- p5 ; x6 <- p6
683         return (f x1 x2 x3 x4 x5 x6)
684 then7 f p1 p2 p3 p4 p5 p6 p7
685    = do x1 <- p1 ; x2 <- p2 ; x3 <- p3 ; x4 <- p4 ; x5 <- p5 ; x6 <- p6 ; x7 <- p7
686         return (f x1 x2 x3 x4 x5 x6 x7)
687 opt p
688    = (do x <- p; return (Just x)) <|> return Nothing
689 optdef d p
690    = (do x <- p; return x) <|> return d
691
692 sel12 a b = a
693 sel22 a b = b
694 sel23 a b c = b
695 apply f p = liftM f p
696
697 -- Hacks for zapping whitespace and comments, unfortunately needed
698 -- because Daan won't let us have a lexer before the parser :-(
699 lexeme  :: Parser p -> Parser p
700 lexeme p = then2 sel12 p pCommentAndWhitespace
701
702 lit :: String -> Parser ()
703 lit s = apply (const ()) (lexeme (string s))
704
705 pCommentAndWhitespace :: Parser ()
706 pCommentAndWhitespace
707    = apply (const ()) (many (alts [pLineComment, 
708                                    apply (const ()) (satisfy isSpace)]))
709      <|>
710      return ()
711
712 pLineComment :: Parser ()
713 pLineComment
714    = try (then3 (\_ _ _ -> ()) (string "--") (many (satisfy (/= '\n'))) (char '\n'))
715
716 stringLiteral :: Parser String
717 stringLiteral   = lexeme (
718                       do { between (char '"')                   
719                                    (char '"' <?> "end of string")
720                                    (many (noneOf "\"")) 
721                          }
722                       <?> "literal string")
723
724
725
726 ------------------------------------------------------------------
727 -- end                                                          --
728 ------------------------------------------------------------------
729
730
731