[project @ 2003-05-29 14:39:26 by sof]
[ghc-hetmet.git] / ghc / compiler / parser / Lex.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[Lexical analysis]{Lexical analysis}
5
6 --------------------------------------------------------
7 [Jan 98]
8 There's a known bug in here:
9
10         If an interface file ends prematurely, Lex tries to
11         do headFS of an empty FastString.
12
13 An example that provokes the error is
14
15         f _:_ _forall_ [a] <<<END OF FILE>>>
16 --------------------------------------------------------
17
18 \begin{code}
19 module Lex (
20
21         srcParseErr,
22
23         -- Monad for parser
24         Token(..), lexer, ParseResult(..), PState(..),
25         ExtFlags(..), mkPState, 
26         StringBuffer,
27
28         P, thenP, thenP_, returnP, mapP, failP, failMsgP,
29         getSrcLocP, setSrcLocP, getSrcFile,
30         layoutOn, layoutOff, pushContext, popContext
31     ) where
32
33 #include "HsVersions.h"
34
35 import Char             ( toUpper, isDigit, chr, ord )
36 import Ratio            ( (%) )
37
38 import PrelNames        ( mkTupNameStr )
39 import ForeignCall      ( Safety(..) )
40 import UniqFM           ( listToUFM, lookupUFM )
41 import BasicTypes       ( Boxity(..) )
42 import SrcLoc           ( SrcLoc, incSrcLine, srcLocFile, srcLocLine,
43                           replaceSrcLine, mkSrcLoc )
44
45 import ErrUtils         ( Message )
46 import Outputable
47
48 import FastString
49 import StringBuffer
50 import Ctype
51
52 import GLAEXTS
53 import DATA_BITS        ( Bits(..) )
54 import DATA_INT         ( Int32 )
55 \end{code}
56
57 %************************************************************************
58 %*                                                                      *
59 \subsection{Data types}
60 %*                                                                      *
61 %************************************************************************
62
63 The token data type, fairly un-interesting except from one
64 constructor, @ITidinfo@, which is used to lazily lex id info (arity,
65 strictness, unfolding etc).
66
67 The Idea/Observation here is that the renamer needs to scan through
68 all of an interface file before it can continue. But only a fraction
69 of the information contained in the file turns out to be useful, so
70 delaying as much as possible of the scanning and parsing of an
71 interface file Makes Sense (Heap profiles of the compiler 
72 show a reduction in heap usage by at least a factor of two,
73 post-renamer). 
74
75 Hence, the interface file lexer spots when value declarations are
76 being scanned and return the @ITidinfo@ and @ITtype@ constructors
77 for the type and any other id info for that binding (unfolding, strictness
78 etc). These constructors are applied to the result of lexing these sub-chunks.
79
80 The lexing of the type and id info is all done lazily, of course, so
81 the scanning (and subsequent parsing) will be done *only* on the ids the
82 renamer finds out that it is interested in. The rest will just be junked.
83 Laziness, you know it makes sense :-)
84
85 \begin{code}
86 data Token
87   = ITas                        -- Haskell keywords
88   | ITcase
89   | ITclass
90   | ITdata
91   | ITdefault
92   | ITderiving
93   | ITdo
94   | ITelse
95   | IThiding
96   | ITif
97   | ITimport
98   | ITin
99   | ITinfix
100   | ITinfixl
101   | ITinfixr
102   | ITinstance
103   | ITlet
104   | ITmodule
105   | ITnewtype
106   | ITof
107   | ITqualified
108   | ITthen
109   | ITtype
110   | ITwhere
111   | ITscc                       -- ToDo: remove (we use {-# SCC "..." #-} now)
112
113   | ITforall                    -- GHC extension keywords
114   | ITforeign
115   | ITexport
116   | ITlabel
117   | ITdynamic
118   | ITsafe
119   | ITthreadsafe
120   | ITunsafe
121   | ITwith
122   | ITstdcallconv
123   | ITccallconv
124   | ITdotnet
125   | ITccall (Bool,Bool,Safety)  -- (is_dyn, is_casm, may_gc)
126   | ITmdo
127
128   | ITspecialise_prag           -- Pragmas
129   | ITsource_prag
130   | ITinline_prag
131   | ITnoinline_prag
132   | ITrules_prag
133   | ITdeprecated_prag
134   | ITline_prag
135   | ITscc_prag
136   | ITcore_prag                 -- hdaume: core annotations
137   | ITclose_prag
138
139   | ITdotdot                    -- reserved symbols
140   | ITcolon
141   | ITdcolon
142   | ITequal
143   | ITlam
144   | ITvbar
145   | ITlarrow
146   | ITrarrow
147   | ITat
148   | ITtilde
149   | ITdarrow
150   | ITminus
151   | ITbang
152   | ITstar
153   | ITdot
154
155   | ITbiglam                    -- GHC-extension symbols
156
157   | ITocurly                    -- special symbols
158   | ITccurly
159   | ITocurlybar                 -- {|, for type applications
160   | ITccurlybar                 -- |}, for type applications
161   | ITvccurly
162   | ITobrack
163   | ITopabrack                  -- [:, for parallel arrays with -fparr
164   | ITcpabrack                  -- :], for parallel arrays with -fparr
165   | ITcbrack
166   | IToparen
167   | ITcparen
168   | IToubxparen
169   | ITcubxparen
170   | ITsemi
171   | ITcomma
172   | ITunderscore
173   | ITbackquote
174
175   | ITvarid   FastString        -- identifiers
176   | ITconid   FastString
177   | ITvarsym  FastString
178   | ITconsym  FastString
179   | ITqvarid  (FastString,FastString)
180   | ITqconid  (FastString,FastString)
181   | ITqvarsym (FastString,FastString)
182   | ITqconsym (FastString,FastString)
183
184   | ITdupipvarid   FastString   -- GHC extension: implicit param: ?x
185   | ITsplitipvarid FastString   -- GHC extension: implicit param: %x
186
187   | ITpragma StringBuffer
188
189   | ITchar       Int
190   | ITstring     FastString
191   | ITinteger    Integer
192   | ITrational   Rational
193
194   | ITprimchar   Int
195   | ITprimstring FastString
196   | ITprimint    Integer
197   | ITprimfloat  Rational
198   | ITprimdouble Rational
199   | ITlitlit     FastString
200
201   -- MetaHaskell extension tokens
202   | ITopenExpQuote              -- [| or [e|
203   | ITopenPatQuote              -- [p|
204   | ITopenDecQuote              -- [d|
205   | ITopenTypQuote              -- [t|         
206   | ITcloseQuote                -- |]
207   | ITidEscape   FastString     -- $x
208   | ITparenEscape               -- $( 
209   | ITreifyType
210   | ITreifyDecl
211   | ITreifyFixity
212
213   | ITunknown String            -- Used when the lexer can't make sense of it
214   | ITeof                       -- end of file token
215   deriving Show -- debugging
216 \end{code}
217
218 -----------------------------------------------------------------------------
219 Keyword Lists
220
221 \begin{code}
222 pragmaKeywordsFM = listToUFM $
223       map (\ (x,y) -> (mkFastString x,y))
224        [( "SPECIALISE", ITspecialise_prag ),
225         ( "SPECIALIZE", ITspecialise_prag ),
226         ( "SOURCE",     ITsource_prag ),
227         ( "INLINE",     ITinline_prag ),
228         ( "NOINLINE",   ITnoinline_prag ),
229         ( "NOTINLINE",  ITnoinline_prag ),
230         ( "LINE",       ITline_prag ),
231         ( "RULES",      ITrules_prag ),
232         ( "RULEZ",      ITrules_prag ), -- american spelling :-)
233         ( "SCC",        ITscc_prag ),
234         ( "CORE",       ITcore_prag ),  -- hdaume: core annotation
235         ( "DEPRECATED", ITdeprecated_prag )
236         ]
237
238 haskellKeywordsFM = listToUFM $
239       map (\ (x,y) -> (mkFastString x,y))
240        [( "_",          ITunderscore ),
241         ( "as",         ITas ),
242         ( "case",       ITcase ),     
243         ( "class",      ITclass ),    
244         ( "data",       ITdata ),     
245         ( "default",    ITdefault ),  
246         ( "deriving",   ITderiving ), 
247         ( "do",         ITdo ),       
248         ( "else",       ITelse ),     
249         ( "hiding",     IThiding ),
250         ( "if",         ITif ),       
251         ( "import",     ITimport ),   
252         ( "in",         ITin ),       
253         ( "infix",      ITinfix ),    
254         ( "infixl",     ITinfixl ),   
255         ( "infixr",     ITinfixr ),   
256         ( "instance",   ITinstance ), 
257         ( "let",        ITlet ),      
258         ( "module",     ITmodule ),   
259         ( "newtype",    ITnewtype ),  
260         ( "of",         ITof ),       
261         ( "qualified",  ITqualified ),
262         ( "then",       ITthen ),     
263         ( "type",       ITtype ),     
264         ( "where",      ITwhere ),
265         ( "_scc_",      ITscc )         -- ToDo: remove
266      ]
267
268 isSpecial :: Token -> Bool
269 -- If we see M.x, where x is a keyword, but
270 -- is special, we treat is as just plain M.x, 
271 -- not as a keyword.
272 isSpecial ITas          = True
273 isSpecial IThiding      = True
274 isSpecial ITqualified   = True
275 isSpecial ITforall      = True
276 isSpecial ITexport      = True
277 isSpecial ITlabel       = True
278 isSpecial ITdynamic     = True
279 isSpecial ITsafe        = True
280 isSpecial ITthreadsafe  = True
281 isSpecial ITunsafe      = True
282 isSpecial ITwith        = True
283 isSpecial ITccallconv   = True
284 isSpecial ITstdcallconv = True
285 isSpecial ITmdo         = True
286 isSpecial _             = False
287
288 -- the bitmap provided as the third component indicates whether the
289 -- corresponding extension keyword is valid under the extension options
290 -- provided to the compiler; if the extension corresponding to *any* of the
291 -- bits set in the bitmap is enabled, the keyword is valid (this setup
292 -- facilitates using a keyword in two different extensions that can be
293 -- activated independently)
294 --
295 ghcExtensionKeywordsFM = listToUFM $
296         map (\(x, y, z) -> (mkFastString x, (y, z)))
297      [  ( "forall",     ITforall,        bit glaExtsBit),
298         ( "foreign",    ITforeign,       bit ffiBit),
299         ( "export",     ITexport,        bit ffiBit),
300         ( "label",      ITlabel,         bit ffiBit),
301         ( "dynamic",    ITdynamic,       bit ffiBit),
302         ( "safe",       ITsafe,          bit ffiBit),
303         ( "threadsafe", ITthreadsafe,    bit ffiBit),
304         ( "unsafe",     ITunsafe,        bit ffiBit),
305         ( "with",       ITwith,          bit withBit),
306         ( "mdo",        ITmdo,           bit glaExtsBit),
307         ( "stdcall",    ITstdcallconv,   bit ffiBit),
308         ( "ccall",      ITccallconv,     bit ffiBit),
309         ( "dotnet",     ITdotnet,        bit ffiBit),
310         ( "reifyDecl",  ITreifyDecl,     bit glaExtsBit),
311         ( "reifyType",  ITreifyType,     bit glaExtsBit),
312         ( "reifyFixity",ITreifyFixity,   bit glaExtsBit),
313         ("_ccall_",     ITccall (False, False, PlayRisky),
314                                          bit glaExtsBit),
315         ("_ccall_GC_",  ITccall (False, False, PlaySafe False),
316                                          bit glaExtsBit),
317         ("_casm_",      ITccall (False, True,  PlayRisky),
318                                          bit glaExtsBit),
319         ("_casm_GC_",   ITccall (False, True,  PlaySafe False),
320                                          bit glaExtsBit)
321      ]
322
323 haskellKeySymsFM = listToUFM $
324         map (\ (x,y) -> (mkFastString x,y))
325       [ ("..",          ITdotdot)
326        ,(":",           ITcolon)        -- (:) is a reserved op, 
327                                         -- meaning only list cons
328        ,("::",          ITdcolon)
329        ,("=",           ITequal)
330        ,("\\",          ITlam)
331        ,("|",           ITvbar)
332        ,("<-",          ITlarrow)
333        ,("->",          ITrarrow)
334        ,("@",           ITat)
335        ,("~",           ITtilde)
336        ,("=>",          ITdarrow)
337        ,("-",           ITminus)
338        ,("!",           ITbang)
339        ,("*",           ITstar)
340        ,(".",           ITdot)          -- sadly, for 'forall a . t'
341        ]
342
343 \end{code}
344
345 -----------------------------------------------------------------------------
346 The lexical analyser
347
348 Lexer state:
349
350         - (exts)  lexing a source with extensions, eg, an interface file or 
351                   with -fglasgow-exts
352         - (bol)   pointer to beginning of line (for column calculations)
353         - (buf)   pointer to beginning of token
354         - (buf)   pointer to current char
355         - (atbol) flag indicating whether we're at the beginning of a line
356
357 \begin{code}
358 lexer :: (Token -> P a) -> P a
359 lexer cont buf s@(PState{
360                     loc = loc,
361                     extsBitmap = exts,
362                     bol = bol,
363                     atbol = atbol,
364                     context = ctx
365                 })
366
367         -- first, start a new lexeme and lose all the whitespace
368   =  _scc_ "Lexer" 
369   tab line bol atbol (stepOverLexeme buf)
370   where
371         line = srcLocLine loc
372
373         tab y bol atbol buf = --trace ("tab: " ++ show (I# y) ++ " : " ++ show (currentChar buf)) $
374           case currentChar# buf of
375
376             '\NUL'# ->
377                    if bufferExhausted (stepOn buf)
378                         then cont ITeof buf s'
379                         else trace "lexer: misplaced NUL?" $ 
380                              tab y bol atbol (stepOn buf)
381
382             '\n'# -> let buf' = stepOn buf
383                      in tab (y +# 1#) (currentIndex# buf') 1# buf'
384
385                 -- find comments.  This got harder in Haskell 98.
386             '-'# ->  let trundle n = 
387                           let next = lookAhead# buf n in
388                           if next `eqChar#` '-'# then trundle (n +# 1#)
389                           else if is_symbol next || n <# 2#
390                                 then is_a_token
391                                 else tab y bol atbol 
392                                          (stepOnUntilChar# (stepOnBy# buf n) '\n'#)
393                     in trundle 1#
394
395                 -- comments and pragmas.  We deal with LINE pragmas here,
396                 -- and throw out any unrecognised pragmas as comments.  Any
397                 -- pragmas we know about are dealt with later (after any layout
398                 -- processing if necessary).
399             '{'# | lookAhead# buf 1# `eqChar#` '-'# ->
400                 if lookAhead# buf 2# `eqChar#` '#'# then
401                   case expandWhile# is_space (addToCurrentPos buf 3#) of { buf1->
402                   case expandWhile# is_ident (stepOverLexeme buf1)   of { buf2->
403                   let lexeme = mkFastString -- ToDo: too slow
404                                   (map toUpper (lexemeToString buf2)) in
405                   case lookupUFM pragmaKeywordsFM lexeme of
406                         -- ignore RULES pragmas when -fglasgow-exts is off
407                         Just ITrules_prag | not (glaExtsEnabled exts) ->
408                            skip_to_end (stepOnBy# buf 2#) s'
409                         Just ITline_prag -> 
410                            line_prag skip_to_end buf2 s'
411                         Just other -> is_a_token
412                         Nothing -> skip_to_end (stepOnBy# buf 2#) s'
413                   }}
414
415                 else skip_to_end (stepOnBy# buf 2#) s'
416                 where
417                     skip_to_end = skipNestedComment (lexer cont)
418
419                 -- special GHC extension: we grok cpp-style #line pragmas
420             '#'# | lexemeIndex buf ==# bol ->   -- the '#' must be in column 0
421                 let buf1 | lookAhead# buf 1# `eqChar#` 'l'# &&
422                            lookAhead# buf 2# `eqChar#` 'i'# &&
423                            lookAhead# buf 3# `eqChar#` 'n'# &&
424                            lookAhead# buf 4# `eqChar#` 'e'#  = stepOnBy# buf 5#
425                          | otherwise = stepOn buf
426                 in
427                 case expandWhile# is_space buf1 of { buf2 ->
428                 if is_digit (currentChar# buf2) 
429                         then line_prag next_line buf2 s'
430                         else is_a_token
431                 }
432                 where
433                 next_line buf = lexer cont (stepOnUntilChar# buf '\n'#)
434
435                 -- tabs have been expanded beforehand
436             c | is_space c -> tab y bol atbol (stepOn buf)
437               | otherwise  -> is_a_token
438
439            where s' = s{loc = replaceSrcLine loc y, 
440                         bol = bol,
441                        atbol = atbol}
442
443                  is_a_token | atbol /=# 0# = lexBOL cont buf s'
444                             | otherwise    = lexToken cont exts buf s'
445
446 -- {-# LINE .. #-} pragmas.  yeuch.
447 line_prag cont buf s@PState{loc=loc} =
448   case expandWhile# is_space buf                of { buf1 ->
449   case scanNumLit 0 (stepOverLexeme buf1)       of { (line,buf2) ->
450   -- subtract one: the line number refers to the *following* line.
451   let real_line = line - 1 in
452   case fromInteger real_line                    of { i@(I# l) -> 
453         -- ToDo, if no filename then we skip the newline.... d'oh
454   case expandWhile# is_space buf2               of { buf3 ->
455   case currentChar# buf3                        of
456      '\"'#{-"-} -> 
457         case untilEndOfString# (stepOn (stepOverLexeme buf3)) of { buf4 ->
458         let 
459             file = lexemeToFastString buf4 
460             new_buf = stepOn (stepOverLexeme buf4)
461         in
462         if nullFastString file
463                 then cont new_buf s{loc = replaceSrcLine loc l}
464                 else cont new_buf s{loc = mkSrcLoc file i}
465         }
466      _other -> cont (stepOverLexeme buf3) s{loc = replaceSrcLine loc l}
467   }}}}
468
469 skipNestedComment :: P a -> P a
470 skipNestedComment cont buf state = skipNestedComment' (loc state) cont buf state
471
472 skipNestedComment' :: SrcLoc -> P a -> P a
473 skipNestedComment' orig_loc cont buf = loop buf
474  where
475    loop buf = 
476      case currentChar# buf of
477         '-'# | lookAhead# buf 1# `eqChar#` '}'# -> cont (stepOnBy# buf 2#)
478
479         '{'# | lookAhead# buf 1# `eqChar#` '-'# ->
480               skipNestedComment 
481                 (skipNestedComment' orig_loc cont) 
482                 (stepOnBy# buf 2#)
483
484         '\n'# -> \ s@PState{loc=loc} ->
485                  let buf' = stepOn buf in
486                  loop buf' s{loc = incSrcLine loc, 
487                              bol = currentIndex# buf',
488                              atbol = 1#}
489
490         -- pass the original SrcLoc to lexError so that the error is
491         -- reported at the line it was originally on, not the line at
492         -- the end of the file.
493         '\NUL'# | bufferExhausted (stepOn buf) -> 
494                 \s -> lexError "unterminated `{-'" buf s{loc=orig_loc} -- -}
495
496         _   -> loop (stepOn buf)
497
498 -- When we are lexing the first token of a line, check whether we need to
499 -- insert virtual semicolons or close braces due to layout.
500
501 lexBOL :: (Token -> P a) -> P a
502 lexBOL cont buf s@(PState{
503                     loc = loc,
504                     extsBitmap = exts,
505                     bol = bol,
506                     atbol = atbol,
507                     context = ctx
508                   }) =
509         if need_close_curly then 
510                 --trace ("col = " ++ show (I# col) ++ ", layout: inserting '}'") $
511                 cont ITvccurly buf s{atbol = 1#, context = tail ctx}
512         else if need_semi_colon then
513                 --trace ("col = " ++ show (I# col) ++ ", layout: inserting ';'") $
514                 cont ITsemi buf s{atbol = 0#}
515         else
516                 lexToken cont exts buf s{atbol = 0#}
517   where
518         col = currentIndex# buf -# bol
519
520         need_close_curly =
521                 case ctx of
522                         [] -> False
523                         (i:_) -> case i of
524                                     NoLayout -> False
525                                     Layout n -> col <# n
526         need_semi_colon =
527                 case ctx of
528                         [] -> False
529                         (i:_) -> case i of
530                                     NoLayout -> False
531                                     Layout n -> col ==# n
532
533
534 lexToken :: (Token -> P a) -> Int# -> P a
535 lexToken cont exts buf =
536 -- trace "lexToken" $
537   case currentChar# buf of
538
539     -- special symbols ----------------------------------------------------
540     '('# | glaExtsEnabled exts && lookAhead# buf 1# `eqChar#` '#'# 
541                 -> cont IToubxparen (addToCurrentPos buf 2#)
542          | otherwise
543                 -> cont IToparen (incCurrentPos buf)
544
545     ')'# -> cont ITcparen    (incCurrentPos buf)
546     '['# | parrEnabled exts && lookAhead# buf 1# `eqChar#` ':'# ->
547             cont ITopabrack  (addToCurrentPos buf 2#)
548          ------- MetaHaskell Extensions, looking for [| [e|  [t|  [p| and [d|
549          | glaExtsEnabled exts && 
550            ((lookAhead# buf 1# ) `eqChar#` '|'# ) ->
551                 cont ITopenExpQuote (addToCurrentPos buf 2# ) 
552          | glaExtsEnabled exts && 
553            (let c = (lookAhead# buf 1# ) 
554             in eqChar# c 'e'# || eqChar# c 't'# || eqChar# c 'd'#  || eqChar# c 'p'#) &&
555            ((lookAhead# buf 2#) `eqChar#` '|'#) ->
556                 let quote 'e'# = ITopenExpQuote
557                     quote 'p'# = ITopenPatQuote
558                     quote 'd'# = ITopenDecQuote
559                     quote 't'# = ITopenTypQuote
560                 in cont (quote (lookAhead# buf 1#)) (addToCurrentPos buf 3# )
561          | otherwise -> 
562             cont ITobrack    (incCurrentPos buf)
563             
564     ']'# -> cont ITcbrack    (incCurrentPos buf)
565     ','# -> cont ITcomma     (incCurrentPos buf)
566     ';'# -> cont ITsemi      (incCurrentPos buf)
567     '}'# -> \ s@PState{context = ctx} ->
568             case ctx of 
569                 (_:ctx') -> cont ITccurly (incCurrentPos buf) s{context=ctx'}
570                 _        -> lexError "too many '}'s" buf s
571     '|'# -> case lookAhead# buf 1# of
572                  '}'#  | glaExtsEnabled exts -> cont ITccurlybar 
573                                                      (addToCurrentPos buf 2#)
574                  -- MetaHaskell extension 
575                  ']'#  |  glaExtsEnabled exts -> cont ITcloseQuote (addToCurrentPos buf 2#)
576                  other -> lex_sym cont (incCurrentPos buf)
577     ':'# -> case lookAhead# buf 1# of
578                  ']'#  | parrEnabled exts    -> cont ITcpabrack
579                                                      (addToCurrentPos buf 2#)
580                  _                           -> lex_sym cont (incCurrentPos buf)
581
582                 
583     '#'# -> case lookAhead# buf 1# of
584                 ')'#  | glaExtsEnabled exts 
585                      -> cont ITcubxparen (addToCurrentPos buf 2#)
586                 '-'# -> case lookAhead# buf 2# of
587                            '}'# -> cont ITclose_prag (addToCurrentPos buf 3#)
588                            _    -> lex_sym cont (incCurrentPos buf)
589                 _    -> lex_sym cont (incCurrentPos buf)
590
591     '`'# | glaExtsEnabled exts && lookAhead# buf 1# `eqChar#` '`'#
592                 -> lex_cstring cont (addToCurrentPos buf 2#)
593          | otherwise
594                 -> cont ITbackquote (incCurrentPos buf)
595
596     '{'# ->   -- for Emacs: -}
597             case lookAhead# buf 1# of
598            '|'# | glaExtsEnabled exts 
599                 -> cont ITocurlybar (addToCurrentPos buf 2#)
600            '-'# -> case lookAhead# buf 2# of
601                     '#'# -> lex_prag cont (addToCurrentPos buf 3#)
602                     _    -> cont ITocurly (incCurrentPos buf) 
603            _ -> (layoutOff `thenP_` cont ITocurly)  (incCurrentPos buf) 
604
605     
606               
607
608     -- strings/characters -------------------------------------------------
609     '\"'#{-"-} -> lex_string cont exts [] (incCurrentPos buf)
610     '\''#      -> lex_char (char_end cont) exts (incCurrentPos buf)
611
612         -- Hexadecimal and octal constants
613     '0'# | (ch `eqChar#` 'x'# || ch `eqChar#` 'X'#) && is_hexdigit ch2
614                 -> readNum (after_lexnum cont exts) buf' is_hexdigit 16 hex
615          | (ch `eqChar#` 'o'# || ch `eqChar#` 'O'#) && is_octdigit ch2
616                 -> readNum (after_lexnum cont exts) buf' is_octdigit  8 oct_or_dec
617         where ch   = lookAhead# buf 1#
618               ch2  = lookAhead# buf 2#
619               buf' = addToCurrentPos buf 2#
620
621     '\NUL'# ->
622             if bufferExhausted (stepOn buf) then
623                cont ITeof buf
624             else
625                trace "lexIface: misplaced NUL?" $ 
626                cont (ITunknown "\NUL") (stepOn buf)
627
628     '?'# | glaExtsEnabled exts && is_lower (lookAhead# buf 1#) ->  -- ?x implicit parameter
629             specialPrefixId ITdupipvarid cont exts (incCurrentPos buf)
630     '%'# | glaExtsEnabled exts && is_lower (lookAhead# buf 1#) ->
631             specialPrefixId ITsplitipvarid cont exts (incCurrentPos buf)
632             
633     ---------------- MetaHaskell Extensions for quotation escape    
634     '$'# | glaExtsEnabled exts && is_lower (lookAhead# buf 1#) ->  -- $x  variable escape 
635             specialPrefixId ITidEscape cont exts (addToCurrentPos buf 1#) 
636     '$'# | glaExtsEnabled exts &&  -- $( f x )  expression escape 
637            ((lookAhead# buf 1#) `eqChar#` '('#) -> cont ITparenEscape (addToCurrentPos buf 2#)
638           
639     c | is_digit  c -> lex_num cont exts 0 buf
640       | is_symbol c -> lex_sym cont buf
641       | is_upper  c -> lex_con cont exts buf
642       | is_lower  c -> lex_id  cont exts buf
643       | otherwise   -> lexError "illegal character" buf
644
645 -- Int# is unlifted, and therefore faster than Bool for flags.
646 {-# INLINE flag #-}
647 flag :: Int# -> Bool
648 flag 0# = False
649 flag _  = True
650
651 -------------------------------------------------------------------------------
652 -- Pragmas
653
654 lex_prag cont buf
655   = case expandWhile# is_space buf of { buf1 ->
656     case expandWhile# is_ident (stepOverLexeme buf1) of { buf2 -> 
657     let lexeme = mkFastString (map toUpper (lexemeToString buf2)) in
658     case lookupUFM pragmaKeywordsFM lexeme of
659         Just kw -> cont kw (mergeLexemes buf buf2)
660         Nothing -> panic "lex_prag"
661   }}
662
663 -------------------------------------------------------------------------------
664 -- Strings & Chars
665
666 lex_string cont exts s buf
667   = case currentChar# buf of
668         '"'#{-"-} -> 
669            let buf' = incCurrentPos buf
670            in case currentChar# buf' of
671                 '#'# | glaExtsEnabled exts -> 
672                    if any (> 0xFF) s
673                     then lexError "primitive string literal must contain only characters <= \'\\xFF\'" buf'
674                     else let s' = mkFastStringNarrow (map chr (reverse s)) in
675                          -- always a narrow string/byte array
676                          cont (ITprimstring s') (incCurrentPos buf')
677
678                 _other -> let s' = mkFastString (map chr (reverse s)) 
679                           in cont (ITstring s') buf'
680
681         -- ignore \& in a string, deal with string gaps
682         '\\'# | next_ch `eqChar#` '&'# 
683                 -> lex_string cont exts s buf'
684               | is_space next_ch
685                 -> lex_stringgap cont exts s (incCurrentPos buf)
686
687             where next_ch = lookAhead# buf 1#
688                   buf' = addToCurrentPos buf 2#
689
690         _ -> lex_char (lex_next_string cont s) exts buf
691
692 lex_stringgap cont exts s buf
693   = let buf' = incCurrentPos buf in
694     case currentChar# buf of
695         '\n'# -> \st@PState{loc = loc} -> lex_stringgap cont exts s buf' 
696                   st{loc = incSrcLine loc}
697         '\\'# -> lex_string cont exts s buf'
698         c | is_space c -> lex_stringgap cont exts s buf'
699         other -> charError buf'
700
701 lex_next_string cont s exts c buf = lex_string cont exts (c:s) buf
702
703 lex_char :: (Int# -> Int -> P a) -> Int# -> P a
704 lex_char cont exts buf
705   = case currentChar# buf of
706         '\\'# -> lex_escape (cont exts) (incCurrentPos buf)
707         c | is_any c -> cont exts (I# (ord# c)) (incCurrentPos buf)
708         other -> charError buf
709
710 char_end cont exts c buf
711   = case currentChar# buf of
712         '\''# -> let buf' = incCurrentPos buf in
713                  case currentChar# buf' of
714                         '#'# | glaExtsEnabled exts 
715                                 -> cont (ITprimchar c) (incCurrentPos buf')
716                         _       -> cont (ITchar c) buf'
717         _     -> charError buf
718
719 lex_escape cont buf
720   = let buf' = incCurrentPos buf in
721     case currentChar# buf of
722         'a'#       -> cont (ord '\a') buf'
723         'b'#       -> cont (ord '\b') buf'
724         'f'#       -> cont (ord '\f') buf'
725         'n'#       -> cont (ord '\n') buf'
726         'r'#       -> cont (ord '\r') buf'
727         't'#       -> cont (ord '\t') buf'
728         'v'#       -> cont (ord '\v') buf'
729         '\\'#      -> cont (ord '\\') buf'
730         '"'#       -> cont (ord '\"') buf'
731         '\''#      -> cont (ord '\'') buf'
732         '^'#       -> let c = currentChar# buf' in
733                       if c `geChar#` '@'# && c `leChar#` '_'#
734                         then cont (I# (ord# c -# ord# '@'#)) (incCurrentPos buf')
735                         else charError buf'
736
737         'x'#      -> readNum (after_charnum cont) buf' is_hexdigit 16 hex
738         'o'#      -> readNum (after_charnum cont) buf' is_octdigit  8 oct_or_dec
739         x | is_digit x 
740                   -> readNum (after_charnum cont) buf is_digit    10 oct_or_dec
741
742         _          -> case [ (c,buf2) | (p,c) <- silly_escape_chars,
743                                        Just buf2 <- [prefixMatch buf p] ] of
744                             (c,buf2):_ -> cont (ord c) buf2
745                             [] -> charError buf'
746
747 after_charnum cont i buf
748   = if i >= 0 && i <= 0x10FFFF
749         then cont (fromInteger i) buf
750         else charError buf
751
752 readNum cont buf is_digit base conv = read buf 0
753   where read buf i 
754           = case currentChar# buf of { c ->
755             if is_digit c
756                 then read (incCurrentPos buf) (i*base + (toInteger (I# (conv c))))
757                 else cont i buf
758             }
759
760 is_hexdigit c 
761         =  is_digit c 
762         || (c `geChar#` 'a'# && c `leChar#` 'f'#)
763         || (c `geChar#` 'A'# && c `leChar#` 'F'#)
764
765 hex c | is_digit c = ord# c -# ord# '0'#
766       | otherwise  = ord# (to_lower c) -# ord# 'a'# +# 10#
767 oct_or_dec c = ord# c -# ord# '0'#
768
769 is_octdigit c = c `geChar#` '0'# && c `leChar#` '7'#
770
771 to_lower c 
772   | c `geChar#` 'A'# && c `leChar#` 'Z'#  
773         = chr# (ord# c -# (ord# 'A'# -# ord# 'a'#))
774   | otherwise = c
775
776 charError buf = lexError "error in character literal" buf
777
778 silly_escape_chars = [
779         ("NUL", '\NUL'),
780         ("SOH", '\SOH'),
781         ("STX", '\STX'),
782         ("ETX", '\ETX'),
783         ("EOT", '\EOT'),
784         ("ENQ", '\ENQ'),
785         ("ACK", '\ACK'),
786         ("BEL", '\BEL'),
787         ("BS", '\BS'),
788         ("HT", '\HT'),
789         ("LF", '\LF'),
790         ("VT", '\VT'),
791         ("FF", '\FF'),
792         ("CR", '\CR'),
793         ("SO", '\SO'),
794         ("SI", '\SI'),
795         ("DLE", '\DLE'),
796         ("DC1", '\DC1'),
797         ("DC2", '\DC2'),
798         ("DC3", '\DC3'),
799         ("DC4", '\DC4'),
800         ("NAK", '\NAK'),
801         ("SYN", '\SYN'),
802         ("ETB", '\ETB'),
803         ("CAN", '\CAN'),
804         ("EM", '\EM'),
805         ("SUB", '\SUB'),
806         ("ESC", '\ESC'),
807         ("FS", '\FS'),
808         ("GS", '\GS'),
809         ("RS", '\RS'),
810         ("US", '\US'),
811         ("SP", '\SP'),
812         ("DEL", '\DEL')
813         ]
814
815 -----------------------------------------------------------------------------
816 -- Numbers
817
818 lex_num :: (Token -> P a) -> Int# -> Integer -> P a
819 lex_num cont exts acc buf =
820  case scanNumLit acc buf of
821      (acc',buf') ->
822        case currentChar# buf' of
823          '.'# | is_digit (lookAhead# buf' 1#) ->
824              -- this case is not optimised at all, as the
825              -- presence of floating point numbers in interface
826              -- files is not that common. (ToDo)
827             case expandWhile# is_digit (incCurrentPos buf') of
828               buf2 -> -- points to first non digit char
829                   case currentChar# buf2 of
830                         'E'# -> float_exponent cont exts buf2
831                         'e'# -> float_exponent cont exts buf2
832                         _    -> float_done cont exts buf2
833
834          -- numbers like '9e4' are floats
835          'E'# -> float_exponent cont exts buf'
836          'e'# -> float_exponent cont exts buf'
837          _    -> after_lexnum cont exts acc' buf' -- it's an integer
838                 
839 float_exponent cont exts buf2 =
840   let buf3 = incCurrentPos buf2
841       buf4 = case currentChar# buf3 of
842                 '-'# | is_digit (lookAhead# buf3 1#)
843                         -> expandWhile# is_digit (incCurrentPos buf3)
844                 '+'# | is_digit (lookAhead# buf3 1#)
845                         -> expandWhile# is_digit (incCurrentPos buf3)
846                 x | is_digit x -> expandWhile# is_digit buf3
847                 _ -> buf2
848   in 
849      float_done cont exts buf4
850
851 float_done cont exts buf =
852    case currentChar# buf of -- glasgow exts only
853         '#'# | glaExtsEnabled exts -> 
854               let buf' = incCurrentPos buf in
855               case currentChar# buf' of
856                 '#'# -> cont (ITprimdouble v) (incCurrentPos buf')
857                 _    -> cont (ITprimfloat  v) buf'
858         _ -> cont (ITrational v) buf
859  where
860    v = readRational__ (lexemeToString buf)
861
862 after_lexnum cont exts i buf
863   = case currentChar# buf of
864         '#'# | glaExtsEnabled exts -> cont (ITprimint i) (incCurrentPos buf)
865         _                          -> cont (ITinteger i) buf
866
867 readRational :: ReadS Rational -- NB: doesn't handle leading "-"
868 readRational r = do 
869      (n,d,s) <- readFix r
870      (k,t)   <- readExp s
871      return ((n%1)*10^^(k-d), t)
872  where
873      readFix r = do
874         (ds,s)  <- lexDecDigits r
875         (ds',t) <- lexDotDigits s
876         return (read (ds++ds'), length ds', t)
877
878      readExp (e:s) | e `elem` "eE" = readExp' s
879      readExp s                     = return (0,s)
880
881      readExp' ('+':s) = readDec s
882      readExp' ('-':s) = do
883                         (k,t) <- readDec s
884                         return (-k,t)
885      readExp' s       = readDec s
886
887      readDec s = do
888         (ds,r) <- nonnull isDigit s
889         return (foldl1 (\n d -> n * 10 + d) [ ord d - ord '0' | d <- ds ],
890                 r)
891
892      lexDecDigits = nonnull isDigit
893
894      lexDotDigits ('.':s) = return (span isDigit s)
895      lexDotDigits s       = return ("",s)
896
897      nonnull p s = do (cs@(_:_),t) <- return (span p s)
898                       return (cs,t)
899
900 readRational__ :: String -> Rational -- NB: *does* handle a leading "-"
901 readRational__ top_s
902   = case top_s of
903       '-' : xs -> - (read_me xs)
904       xs       -> read_me xs
905   where
906     read_me s
907       = case (do { (x,"") <- readRational s ; return x }) of
908           [x] -> x
909           []  -> error ("readRational__: no parse:"        ++ top_s)
910           _   -> error ("readRational__: ambiguous parse:" ++ top_s)
911
912 -----------------------------------------------------------------------------
913 -- C "literal literal"s  (i.e. things like ``NULL'', ``stdout'' etc.)
914
915 -- we lexemeToFastString on the bit between the ``''s, but include the
916 -- quotes in the full lexeme.
917
918 lex_cstring cont buf =
919  case expandUntilMatch (stepOverLexeme buf) "\'\'" of
920    Just buf' -> cont (ITlitlit (lexemeToFastString 
921                                 (addToCurrentPos buf' (negateInt# 2#))))
922                    (mergeLexemes buf buf')
923    Nothing   -> lexError "unterminated ``" buf
924
925 -----------------------------------------------------------------------------
926 -- identifiers, symbols etc.
927
928 -- used for identifiers with special prefixes like 
929 -- ?x (implicit parameters), $x (MetaHaskell escapes) and #x
930 -- we've already seen the prefix char, so look for an id, and wrap 
931 -- the new "ip_constr" around the lexeme returned
932
933 specialPrefixId ip_constr cont exts buf = lex_id newcont exts buf
934  where newcont (ITvarid lexeme) buf2 = cont (ip_constr (tailFS lexeme)) buf2
935        newcont token buf2 = cont token buf2
936 {-  
937  case expandWhile# is_ident buf of
938    buf' -> cont (ip_constr (tailFS lexeme)) buf'
939         where lexeme = lexemeToFastString buf'
940 -}
941
942 lex_id cont exts buf =
943  let buf1 = expandWhile# is_ident buf in
944  seq buf1 $
945
946  case (if glaExtsEnabled exts 
947         then expandWhile# (eqChar# '#'#) buf1 -- slurp trailing hashes
948         else buf1)                              of { buf' ->
949  seq buf' $
950
951  let lexeme  = lexemeToFastString buf' in
952
953  case _scc_ "haskellKeyword" lookupUFM haskellKeywordsFM lexeme of {
954         Just kwd_token -> --trace ("hkeywd: "++unpackFS(lexeme)) $
955                           cont kwd_token buf';
956         Nothing        -> 
957
958  let var_token = cont (ITvarid lexeme) buf' in
959
960  case lookupUFM ghcExtensionKeywordsFM lexeme of {
961     Just (kwd_token, validExts) 
962       | validExts .&. (toInt32 exts) /= 0 -> cont kwd_token buf';
963     _                                     -> var_token
964
965  }}}
966
967 lex_sym cont buf =
968  -- trace "lex_sym" $
969  case expandWhile# is_symbol buf of
970    buf' -> case lookupUFM haskellKeySymsFM lexeme of {
971                 Just kwd_token -> --trace ("keysym: "++unpackFS lexeme) $
972                                   cont kwd_token buf' ;
973                 Nothing        -> --trace ("sym: "++unpackFS lexeme) $ 
974                           cont (mk_var_token lexeme) buf'
975            }
976         where lexeme = lexemeToFastString buf'
977
978
979 -- lex_con recursively collects components of a qualified identifer.
980 -- The argument buf is the StringBuffer representing the lexeme
981 -- identified so far, where the next character is upper-case.
982
983 lex_con cont exts buf =
984  -- trace ("con: "{-++unpackFS lexeme-}) $
985  let empty_buf = stepOverLexeme buf in
986  case expandWhile# is_ident empty_buf of { buf1 ->
987  case slurp_trailing_hashes buf1 exts of { con_buf ->
988
989  let all_buf = mergeLexemes buf con_buf
990      
991      con_lexeme = lexemeToFastString con_buf
992      mod_lexeme = lexemeToFastString (decCurrentPos buf)
993      all_lexeme = lexemeToFastString all_buf
994
995      just_a_conid
996         | emptyLexeme buf = cont (ITconid con_lexeme)               all_buf
997         | otherwise       = cont (ITqconid (mod_lexeme,con_lexeme)) all_buf
998  in
999
1000  case currentChar# all_buf of
1001      '.'# -> maybe_qualified cont exts all_lexeme 
1002                 (incCurrentPos all_buf) just_a_conid
1003      _    -> just_a_conid
1004   }}
1005
1006
1007 maybe_qualified cont exts mod buf just_a_conid =
1008  -- trace ("qid: "{-++unpackFS lexeme-}) $
1009  case currentChar# buf of
1010   '['# ->       -- Special case for []
1011     case lookAhead# buf 1# of
1012      ']'# -> cont (ITqconid  (mod,FSLIT("[]"))) (addToCurrentPos buf 2#)
1013      _    -> just_a_conid
1014
1015   '('# ->  -- Special case for (,,,)
1016            -- This *is* necessary to deal with e.g. "instance C PrelBase.(,,)"
1017     case lookAhead# buf 1# of
1018      '#'# | glaExtsEnabled exts -> case lookAhead# buf 2# of
1019                 ','# -> lex_ubx_tuple cont mod (addToCurrentPos buf 3#) 
1020                                 just_a_conid
1021                 _    -> just_a_conid
1022      ')'# -> cont (ITqconid (mod,FSLIT("()"))) (addToCurrentPos buf 2#)
1023      ','# -> lex_tuple cont mod (addToCurrentPos buf 2#) just_a_conid
1024      _    -> just_a_conid
1025
1026   '-'# -> case lookAhead# buf 1# of
1027             '>'# -> cont (ITqconid (mod,FSLIT("(->)"))) (addToCurrentPos buf 2#)
1028             _    -> lex_id3 cont exts mod buf just_a_conid
1029
1030   _    -> lex_id3 cont exts mod buf just_a_conid
1031
1032
1033 lex_id3 cont exts mod buf just_a_conid
1034   | is_upper (currentChar# buf) =
1035      lex_con cont exts buf
1036
1037   | is_symbol (currentChar# buf) =
1038      let 
1039         start_new_lexeme = stepOverLexeme buf
1040      in
1041      -- trace ("lex_id31 "{-++unpackFS lexeme-}) $
1042      case expandWhile# is_symbol start_new_lexeme of { buf' ->
1043      let
1044        lexeme  = lexemeToFastString buf'
1045         -- real lexeme is M.<sym>
1046        new_buf = mergeLexemes buf buf'
1047      in
1048      cont (mk_qvar_token mod lexeme) new_buf
1049         -- wrong, but arguably morally right: M... is now a qvarsym
1050      }
1051
1052   | otherwise   =
1053      let 
1054         start_new_lexeme = stepOverLexeme buf
1055      in
1056      -- trace ("lex_id32 "{-++unpackFS lexeme-}) $
1057      case expandWhile# is_ident start_new_lexeme of { buf1 ->
1058      if emptyLexeme buf1 
1059             then just_a_conid
1060             else
1061
1062      case slurp_trailing_hashes buf1 exts of { buf' ->
1063
1064      let
1065       lexeme      = lexemeToFastString buf'
1066       new_buf     = mergeLexemes buf buf'
1067       is_a_qvarid = cont (mk_qvar_token mod lexeme) new_buf
1068      in
1069      case _scc_ "haskellKeyword" lookupUFM haskellKeywordsFM lexeme of {
1070             Nothing          -> is_a_qvarid ;
1071
1072             Just kwd_token | isSpecial kwd_token   -- special ids (as, qualified, hiding) shouldn't be
1073                            -> is_a_qvarid          --  recognised as keywords here.
1074                            | otherwise
1075                            -> just_a_conid         -- avoid M.where etc.
1076      }}}
1077
1078 slurp_trailing_hashes buf exts
1079   | glaExtsEnabled exts = expandWhile# (`eqChar#` '#'#) buf
1080   | otherwise           = buf
1081
1082
1083 mk_var_token pk_str
1084   | is_upper f          = ITconid pk_str
1085   | is_ident f          = ITvarid pk_str
1086   | f `eqChar#` ':'#    = ITconsym pk_str
1087   | otherwise           = ITvarsym pk_str
1088   where
1089       (C# f) = headFS pk_str
1090       -- tl     = _TAIL_ pk_str
1091
1092 mk_qvar_token m token =
1093 -- trace ("mk_qvar ") $ 
1094  case mk_var_token token of
1095    ITconid n  -> ITqconid  (m,n)
1096    ITvarid n  -> ITqvarid  (m,n)
1097    ITconsym n -> ITqconsym (m,n)
1098    ITvarsym n -> ITqvarsym (m,n)
1099    _          -> ITunknown (show token)
1100 \end{code}
1101
1102 ----------------------------------------------------------------------------
1103 Horrible stuff for dealing with M.(,,,)
1104
1105 \begin{code}
1106 lex_tuple cont mod buf back_off =
1107   go 2 buf
1108   where
1109    go n buf =
1110     case currentChar# buf of
1111       ','# -> go (n+1) (stepOn buf)
1112       ')'# -> cont (ITqconid (mod, snd (mkTupNameStr Boxed n))) (stepOn buf)
1113       _    -> back_off
1114
1115 lex_ubx_tuple cont mod buf back_off =
1116   go 2 buf
1117   where
1118    go n buf =
1119     case currentChar# buf of
1120       ','# -> go (n+1) (stepOn buf)
1121       '#'# -> case lookAhead# buf 1# of
1122                 ')'# -> cont (ITqconid (mod, snd (mkTupNameStr Unboxed n)))
1123                                  (stepOnBy# buf 2#)
1124                 _    -> back_off
1125       _    -> back_off
1126 \end{code}
1127
1128 -----------------------------------------------------------------------------
1129
1130 \begin{code}
1131 data LayoutContext
1132   = NoLayout
1133   | Layout Int#
1134
1135 data ParseResult a
1136   = POk PState a
1137   | PFailed Message
1138
1139 data PState = PState { 
1140         loc        :: SrcLoc,
1141         extsBitmap :: Int#,     -- bitmap that determines permitted extensions
1142         bol        :: Int#,
1143         atbol      :: Int#,
1144         context    :: [LayoutContext]
1145      }
1146
1147 type P a = StringBuffer         -- Input string
1148         -> PState
1149         -> ParseResult a
1150
1151 returnP   :: a -> P a
1152 returnP a buf s = POk s a
1153
1154 thenP      :: P a -> (a -> P b) -> P b
1155 m `thenP` k = \ buf s ->
1156         case m buf s of
1157                 POk s1 a -> k a buf s1
1158                 PFailed err  -> PFailed err
1159
1160 thenP_     :: P a -> P b -> P b
1161 m `thenP_` k = m `thenP` \_ -> k
1162
1163 mapP :: (a -> P b) -> [a] -> P [b]
1164 mapP f [] = returnP []
1165 mapP f (a:as) = 
1166      f a `thenP` \b ->
1167      mapP f as `thenP` \bs ->
1168      returnP (b:bs)
1169
1170 failP :: String -> P a
1171 failP msg buf s = PFailed (text msg)
1172
1173 failMsgP :: Message -> P a
1174 failMsgP msg buf s = PFailed msg
1175
1176 lexError :: String -> P a
1177 lexError str buf s@PState{ loc = loc } 
1178   = failMsgP (hcat [ppr loc, text ": ", text str]) buf s
1179
1180 getSrcLocP :: P SrcLoc
1181 getSrcLocP buf s@(PState{ loc = loc }) = POk s loc
1182
1183 -- use a temporary SrcLoc for the duration of the argument
1184 setSrcLocP :: SrcLoc -> P a -> P a
1185 setSrcLocP new_loc p buf s = 
1186   case p buf s{ loc=new_loc } of
1187       POk _ a   -> POk s a
1188       PFailed e -> PFailed e
1189   
1190 getSrcFile :: P FastString
1191 getSrcFile buf s@(PState{ loc = loc }) = POk s (srcLocFile loc)
1192
1193 pushContext :: LayoutContext -> P ()
1194 pushContext ctxt buf s@(PState{ context = ctx }) = POk s{context = ctxt:ctx} ()
1195
1196 {-
1197
1198 This special case in layoutOn is to handle layout contexts with are
1199 indented the same or less than the current context.  This is illegal
1200 according to the Haskell spec, so we have to arrange to close the
1201 current context.  eg.
1202
1203 class Foo a where
1204 class Bar a
1205
1206 after the first 'where', the sequence of events is:
1207
1208         - layout system inserts a ';' (column 0)
1209         - parser begins a new context at column 0
1210         - parser shifts ';' (legal empty declaration)
1211         - parser sees 'class': parse error (we're still in the inner context)
1212
1213 trouble is, by the time we know we need a new context, the lexer has
1214 already generated the ';'.  Hacky solution is as follows: since we
1215 know the column of the next token (it's the column number of the new
1216 context), we set the ACTUAL column number of the new context to this
1217 numer plus one.  Hence the next time the lexer is called, a '}' will
1218 be generated to close the new context straight away.  Furthermore, we
1219 have to set the atbol flag so that the ';' that the parser shifted as
1220 part of the new context is re-generated.
1221
1222 when the new context is *less* indented than the current one:
1223
1224 f = f where g = g where
1225 h = h
1226
1227         - current context: column 12.
1228         - on seeing 'h' (column 0), the layout system inserts '}'
1229         - parser starts a new context, column 0
1230         - parser sees '}', uses it to close new context
1231         - we still need to insert another '}' followed by a ';',
1232           hence the atbol trick.
1233
1234 There's also a special hack in here to deal with
1235
1236         do
1237            ....
1238            e $ do
1239            blah
1240
1241 i.e. the inner context is at the same indentation level as the outer
1242 context.  This is strictly illegal according to Haskell 98, but
1243 there's a lot of existing code using this style and it doesn't make
1244 any sense to disallow it, since empty 'do' lists don't make sense.
1245 -}
1246
1247 layoutOn :: Bool -> P ()
1248 layoutOn strict buf s@(PState{ bol = bol, context = ctx }) =
1249     let offset = lexemeIndex buf -# bol in
1250     case ctx of
1251         Layout prev_off : _ 
1252            | if strict then prev_off >=# offset else prev_off ># offset ->
1253                 --trace ("layout on, column: " ++  show (I# offset)) $
1254                 POk s{ context = Layout (offset +# 1#) : ctx, atbol = 1# } ()
1255         other -> 
1256                 --trace ("layout on, column: " ++  show (I# offset)) $
1257                 POk s{ context = Layout offset : ctx } ()
1258
1259 layoutOff :: P ()
1260 layoutOff buf s@(PState{ context = ctx }) =
1261     POk s{ context = NoLayout:ctx } ()
1262
1263 popContext :: P ()
1264 popContext = \ buf s@(PState{ context = ctx, loc = loc }) ->
1265   case ctx of
1266         (_:tl) -> POk s{ context = tl } ()
1267         []     -> PFailed (srcParseErr buf loc)
1268
1269 -- for reasons of efficiency, flags indicating language extensions (eg,
1270 -- -fglasgow-exts or -fparr) are represented by a bitmap stored in an unboxed
1271 -- integer
1272
1273 glaExtsBit, ffiBit, parrBit :: Int
1274 glaExtsBit = 0
1275 ffiBit     = 1
1276 parrBit    = 2
1277 withBit    = 3
1278
1279 glaExtsEnabled, ffiEnabled, parrEnabled :: Int# -> Bool
1280 glaExtsEnabled flags = testBit (toInt32 flags) glaExtsBit
1281 ffiEnabled     flags = testBit (toInt32 flags) ffiBit
1282 withEnabled    flags = testBit (toInt32 flags) withBit
1283 parrEnabled    flags = testBit (toInt32 flags) parrBit
1284
1285 toInt32 :: Int# -> Int32
1286 toInt32 x# = fromIntegral (I# x#)
1287
1288 -- convenient record-based bitmap for the interface to the rest of the world
1289 --
1290 -- NB: `glasgowExtsEF' implies `ffiEF' (see `mkPState' below)
1291 --
1292 data ExtFlags = ExtFlags {
1293                   glasgowExtsEF :: Bool,
1294                   ffiEF         :: Bool,
1295                   withEF        :: Bool,
1296                   parrEF        :: Bool
1297                 }
1298
1299 -- create a parse state
1300 --
1301 mkPState          :: SrcLoc -> ExtFlags -> PState
1302 mkPState loc exts  = 
1303   PState {
1304     loc        = loc,
1305       extsBitmap = case (fromIntegral bitmap) of {I# bits -> bits},
1306       bol         = 0#,
1307       atbol      = 1#,
1308       context    = []
1309     }
1310     where
1311       bitmap =     glaExtsBit `setBitIf` glasgowExtsEF     exts
1312                .|. ffiBit     `setBitIf` (ffiEF            exts
1313                                           || glasgowExtsEF exts)
1314                .|. withBit    `setBitIf` withEF            exts
1315                .|. parrBit    `setBitIf` parrEF            exts
1316       --
1317       setBitIf :: Int -> Bool -> Int32
1318       b `setBitIf` cond | cond      = bit b
1319                         | otherwise = 0
1320
1321 -----------------------------------------------------------------------------
1322
1323 srcParseErr :: StringBuffer -> SrcLoc -> Message
1324 srcParseErr s l
1325   = hcat [ppr l, 
1326           if null token 
1327              then ptext SLIT(": parse error (possibly incorrect indentation)")
1328              else hcat [ptext SLIT(": parse error on input "),
1329                         char '`', text token, char '\'']
1330     ]
1331   where 
1332         token = lexemeToString s
1333
1334 \end{code}