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