0a247e0d03211c7c9d2dccda16123dd0233c4653
[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
20 module Lex (
21
22         ifaceParseErr, srcParseErr,
23
24         -- Monad for parser
25         Token(..), lexer, ParseResult(..), PState(..),
26         checkVersion, 
27         StringBuffer,
28
29         P, thenP, thenP_, returnP, mapP, failP, failMsgP,
30         getSrcLocP, getSrcFile,
31         layoutOn, layoutOff, pushContext, popContext
32     ) where
33
34 #include "HsVersions.h"
35
36 import Char             ( ord, isSpace, toUpper )
37 import List             ( isSuffixOf )
38
39 import IdInfo           ( InlinePragInfo(..), CprInfo(..) )
40 import Name             ( isLowerISO, isUpperISO )
41 import PrelMods         ( mkTupNameStr, mkUbxTupNameStr )
42 import CmdLineOpts      ( opt_IgnoreIfacePragmas, opt_HiVersion, opt_NoHiCheck )
43 import Demand           ( Demand(..) {- instance Read -} )
44 import UniqFM           ( UniqFM, listToUFM, lookupUFM)
45 import BasicTypes       ( NewOrData(..) )
46 import SrcLoc           ( SrcLoc, incSrcLine, srcLocFile, srcLocLine,
47                           replaceSrcLine, mkSrcLoc )
48
49 import Maybes           ( MaybeErr(..) )
50 import ErrUtils         ( Message )
51 import Outputable
52
53 import FastString
54 import StringBuffer
55 import GlaExts
56 import ST               ( runST )
57 import Ctype
58 import Char             ( chr )
59 import Addr
60 import PrelRead         ( readRational__ ) -- Glasgow non-std
61 \end{code}
62
63 %************************************************************************
64 %*                                                                      *
65 \subsection{Data types}
66 %*                                                                      *
67 %************************************************************************
68
69 The token data type, fairly un-interesting except from one
70 constructor, @ITidinfo@, which is used to lazily lex id info (arity,
71 strictness, unfolding etc).
72
73 The Idea/Observation here is that the renamer needs to scan through
74 all of an interface file before it can continue. But only a fraction
75 of the information contained in the file turns out to be useful, so
76 delaying as much as possible of the scanning and parsing of an
77 interface file Makes Sense (Heap profiles of the compiler 
78 show a reduction in heap usage by at least a factor of two,
79 post-renamer). 
80
81 Hence, the interface file lexer spots when value declarations are
82 being scanned and return the @ITidinfo@ and @ITtype@ constructors
83 for the type and any other id info for that binding (unfolding, strictness
84 etc). These constructors are applied to the result of lexing these sub-chunks.
85
86 The lexing of the type and id info is all done lazily, of course, so
87 the scanning (and subsequent parsing) will be done *only* on the ids the
88 renamer finds out that it is interested in. The rest will just be junked.
89 Laziness, you know it makes sense :-)
90
91 \begin{code}
92 data Token
93   = ITas                        -- Haskell keywords
94   | ITcase
95   | ITclass
96   | ITdata
97   | ITdefault
98   | ITderiving
99   | ITdo
100   | ITelse
101   | IThiding
102   | ITif
103   | ITimport
104   | ITin
105   | ITinfix
106   | ITinfixl
107   | ITinfixr
108   | ITinstance
109   | ITlet
110   | ITmodule
111   | ITnewtype
112   | ITof
113   | ITqualified
114   | ITthen
115   | ITtype
116   | ITwhere
117   | ITscc
118
119   | ITforall                    -- GHC extension keywords
120   | ITforeign
121   | ITexport
122   | ITlabel
123   | ITdynamic
124   | ITunsafe
125   | ITwith
126   | ITstdcallconv
127   | ITccallconv
128
129   | ITinterface                 -- interface keywords
130   | IT__export
131   | ITdepends
132   | IT__forall
133   | ITletrec 
134   | ITcoerce
135   | ITinlineMe
136   | ITinlineCall
137   | ITccall (Bool,Bool,Bool)    -- (is_dyn, is_casm, may_gc)
138   | ITdefaultbranch
139   | ITbottom
140   | ITinteger_lit 
141   | ITfloat_lit
142   | ITword_lit
143   | ITword64_lit
144   | ITint64_lit
145   | ITrational_lit
146   | ITaddr_lit
147   | ITlit_lit
148   | ITstring_lit
149   | ITtypeapp
150   | ITusage
151   | ITfuall
152   | ITarity 
153   | ITspecialise
154   | ITnocaf
155   | ITunfold InlinePragInfo
156   | ITstrict ([Demand], Bool)
157   | ITrules
158   | ITcprinfo
159   | ITdeprecated
160   | IT__scc
161   | ITsccAllCafs
162
163   | ITspecialise_prag           -- Pragmas
164   | ITsource_prag
165   | ITinline_prag
166   | ITnoinline_prag
167   | ITrules_prag
168   | ITdeprecated_prag
169   | ITline_prag
170   | ITclose_prag
171
172   | ITdotdot                    -- reserved symbols
173   | ITdcolon
174   | ITequal
175   | ITlam
176   | ITvbar
177   | ITlarrow
178   | ITrarrow
179   | ITat
180   | ITtilde
181   | ITdarrow
182   | ITminus
183   | ITbang
184   | ITdot
185
186   | ITbiglam                    -- GHC-extension symbols
187
188   | ITocurly                    -- special symbols
189   | ITccurly
190   | ITvccurly
191   | ITobrack
192   | ITcbrack
193   | IToparen
194   | ITcparen
195   | IToubxparen
196   | ITcubxparen
197   | ITsemi
198   | ITcomma
199   | ITunderscore
200   | ITbackquote
201
202   | ITvarid   FAST_STRING       -- identifiers
203   | ITconid   FAST_STRING
204   | ITvarsym  FAST_STRING
205   | ITconsym  FAST_STRING
206   | ITqvarid  (FAST_STRING,FAST_STRING)
207   | ITqconid  (FAST_STRING,FAST_STRING)
208   | ITqvarsym (FAST_STRING,FAST_STRING)
209   | ITqconsym (FAST_STRING,FAST_STRING)
210
211   | ITipvarid FAST_STRING       -- GHC extension: implicit param: ?x
212
213   | ITpragma StringBuffer
214
215   | ITchar       Char 
216   | ITstring     FAST_STRING
217   | ITinteger    Integer 
218   | ITrational   Rational
219
220   | ITprimchar   Char
221   | ITprimstring FAST_STRING
222   | ITprimint    Integer
223   | ITprimfloat  Rational
224   | ITprimdouble Rational
225   | ITlitlit     FAST_STRING
226
227   | ITunknown String            -- Used when the lexer can't make sense of it
228   | ITeof                       -- end of file token
229   deriving Show -- debugging
230 \end{code}
231
232 -----------------------------------------------------------------------------
233 Keyword Lists
234
235 \begin{code}
236 pragmaKeywordsFM = listToUFM $
237       map (\ (x,y) -> (_PK_ x,y))
238        [( "SPECIALISE", ITspecialise_prag ),
239         ( "SPECIALIZE", ITspecialise_prag ),
240         ( "SOURCE",     ITsource_prag ),
241         ( "INLINE",     ITinline_prag ),
242         ( "NOINLINE",   ITnoinline_prag ),
243         ( "NOTINLINE",  ITnoinline_prag ),
244         ( "LINE",       ITline_prag ),
245         ( "RULES",      ITrules_prag ),
246         ( "RULEZ",      ITrules_prag ), -- american spelling :-)
247         ( "DEPRECATED", ITdeprecated_prag )
248         ]
249
250 haskellKeywordsFM = listToUFM $
251       map (\ (x,y) -> (_PK_ x,y))
252        [( "_",          ITunderscore ),
253         ( "as",         ITas ),
254         ( "case",       ITcase ),     
255         ( "class",      ITclass ),    
256         ( "data",       ITdata ),     
257         ( "default",    ITdefault ),  
258         ( "deriving",   ITderiving ), 
259         ( "do",         ITdo ),       
260         ( "else",       ITelse ),     
261         ( "hiding",     IThiding ),
262         ( "if",         ITif ),       
263         ( "import",     ITimport ),   
264         ( "in",         ITin ),       
265         ( "infix",      ITinfix ),    
266         ( "infixl",     ITinfixl ),   
267         ( "infixr",     ITinfixr ),   
268         ( "instance",   ITinstance ), 
269         ( "let",        ITlet ),      
270         ( "module",     ITmodule ),   
271         ( "newtype",    ITnewtype ),  
272         ( "of",         ITof ),       
273         ( "qualified",  ITqualified ),
274         ( "then",       ITthen ),     
275         ( "type",       ITtype ),     
276         ( "where",      ITwhere ),
277         ( "_scc_",      ITscc )
278      ]
279
280 -- IMPORTANT: Keep this in synch with ParseIface.y's var_fs production! (SUP)
281 ghcExtensionKeywordsFM = listToUFM $
282         map (\ (x,y) -> (_PK_ x,y))
283      [  ( "forall",     ITforall ),
284         ( "foreign",    ITforeign ),
285         ( "export",     ITexport ),
286         ( "label",      ITlabel ),
287         ( "dynamic",    ITdynamic ),
288         ( "unsafe",     ITunsafe ),
289         ( "with",       ITwith ),
290         ( "stdcall",    ITstdcallconv),
291         ( "ccall",      ITccallconv),
292         ("_ccall_",     ITccall (False, False, False)),
293         ("_ccall_GC_",  ITccall (False, False, True)),
294         ("_casm_",      ITccall (False, True,  False)),
295         ("_casm_GC_",   ITccall (False, True,  True)),
296
297         -- interface keywords
298         ("__interface",         ITinterface),
299         ("__export",            IT__export),
300         ("__depends",           ITdepends),
301         ("__forall",            IT__forall),
302         ("__letrec",            ITletrec),
303         ("__coerce",            ITcoerce),
304         ("__inline_me",         ITinlineMe),
305         ("__inline_call",       ITinlineCall),
306         ("__depends",           ITdepends),
307         ("__DEFAULT",           ITdefaultbranch),
308         ("__bot",               ITbottom),
309         ("__integer",           ITinteger_lit),
310         ("__float",             ITfloat_lit),
311         ("__int64",             ITint64_lit),
312         ("__word",              ITword_lit),
313         ("__word64",            ITword64_lit),
314         ("__rational",          ITrational_lit),
315         ("__addr",              ITaddr_lit),
316         ("__litlit",            ITlit_lit),
317         ("__string",            ITstring_lit),
318         ("__a",                 ITtypeapp),
319         ("__u",                 ITusage),
320         ("__fuall",             ITfuall),
321         ("__A",                 ITarity),
322         ("__P",                 ITspecialise),
323         ("__C",                 ITnocaf),
324         ("__R",                 ITrules),
325         ("__D",                 ITdeprecated),
326         ("__U",                 ITunfold NoInlinePragInfo),
327         
328         ("__ccall",             ITccall (False, False, False)),
329         ("__ccall_GC",          ITccall (False, False, True)),
330         ("__dyn_ccall",         ITccall (True,  False, False)),
331         ("__dyn_ccall_GC",      ITccall (True,  False, True)),
332         ("__casm",              ITccall (False, True,  False)),
333         ("__dyn_casm",          ITccall (True,  True,  False)),
334         ("__casm_GC",           ITccall (False, True,  True)),
335         ("__dyn_casm_GC",       ITccall (True,  True,  True)),
336
337         ("/\\",                 ITbiglam)
338      ]
339
340
341 haskellKeySymsFM = listToUFM $
342         map (\ (x,y) -> (_PK_ x,y))
343       [ ("..",          ITdotdot)
344        ,("::",          ITdcolon)
345        ,("=",           ITequal)
346        ,("\\",          ITlam)
347        ,("|",           ITvbar)
348        ,("<-",          ITlarrow)
349        ,("->",          ITrarrow)
350        ,("@",           ITat)
351        ,("~",           ITtilde)
352        ,("=>",          ITdarrow)
353        ,("-",           ITminus)
354        ,("!",           ITbang)
355        ,(".",           ITdot)          -- sadly, for 'forall a . t'
356        ]
357 \end{code}
358
359 -----------------------------------------------------------------------------
360 The lexical analyser
361
362 Lexer state:
363
364         - (glaexts) lexing an interface file or -fglasgow-exts
365         - (bol)   pointer to beginning of line (for column calculations)
366         - (buf)   pointer to beginning of token
367         - (buf)   pointer to current char
368         - (atbol) flag indicating whether we're at the beginning of a line
369
370 \begin{code}
371 lexer :: (Token -> P a) -> P a
372 lexer cont buf s@(PState{
373                     loc = loc,
374                     glasgow_exts = glaexts,
375                     bol = bol,
376                     atbol = atbol,
377                     context = ctx
378                 })
379
380         -- first, start a new lexeme and lose all the whitespace
381   =  _scc_ "Lexer" 
382   tab line bol atbol (stepOverLexeme buf)
383   where
384         line = srcLocLine loc
385
386         tab y bol atbol buf = --trace ("tab: " ++ show (I# y) ++ " : " ++ show (currentChar buf)) $
387           case currentChar# buf of
388
389             '\NUL'# ->
390                    if bufferExhausted (stepOn buf)
391                         then cont ITeof buf s'
392                         else trace "lexer: misplaced NUL?" $ 
393                              tab y bol atbol (stepOn buf)
394
395             '\n'# -> let buf' = stepOn buf
396                      in tab (y +# 1#) (currentIndex# buf') 1# buf'
397
398                 -- find comments.  This got harder in Haskell 98.
399             '-'# ->  let trundle n = 
400                           let next = lookAhead# buf n in
401                           if next `eqChar#` '-'# then trundle (n +# 1#)
402                           else if is_symbol next || n <# 2#
403                                 then is_a_token
404                                 else case untilChar# (stepOnBy# buf n) '\n'# of 
405                                     { buf' -> tab y bol atbol (stepOverLexeme buf')
406                                     }
407                     in trundle 1#
408
409                 -- comments and pragmas.  We deal with LINE pragmas here,
410                 -- and throw out any unrecognised pragmas as comments.  Any
411                 -- pragmas we know about are dealt with later (after any layout
412                 -- processing if necessary).
413
414             '{'# | lookAhead# buf 1# `eqChar#` '-'# ->
415                 if lookAhead# buf 2# `eqChar#` '#'# then
416                   if lookAhead# buf 3# `eqChar#` '#'# then is_a_token else
417                   case expandWhile# is_space (setCurrentPos# buf 3#) of { buf1->
418                   case expandWhile# is_ident (stepOverLexeme buf1)   of { buf2->
419                   let lexeme = mkFastString -- ToDo: too slow
420                                   (map toUpper (lexemeToString buf2)) in
421                   case lookupUFM pragmaKeywordsFM lexeme of
422                         Just ITline_prag -> line_prag (lexer cont) buf2 s'
423                         Just other -> is_a_token
424                         Nothing -> skip_to_end (stepOnBy# buf 2#)
425                   }}
426                 
427                 else skip_to_end (stepOnBy# buf 2#)
428                 where
429                     skip_to_end buf = nested_comment (lexer cont) buf s'
430
431                 -- tabs have been expanded beforehand
432             c | is_space c -> tab y bol atbol (stepOn buf)
433               | otherwise  -> is_a_token
434
435            where s' = s{loc = replaceSrcLine loc y, 
436                         bol = bol,
437                        atbol = atbol}
438
439                  is_a_token | atbol /=# 0# = lexBOL cont buf s'
440                             | otherwise    = lexToken cont glaexts buf s'
441
442 -- {-# LINE .. #-} pragmas.  yeuch.
443 line_prag cont buf =
444   case expandWhile# is_space buf                of { buf1 ->
445   case scanNumLit 0 (stepOverLexeme buf1)       of { (line,buf2) ->
446   -- subtract one: the line number refers to the *following* line.
447   let real_line = line - 1 in
448   case fromInteger real_line                    of { i@(I# l) -> 
449   case expandWhile# is_space buf2               of { buf3 ->
450   case currentChar# buf3                        of
451      '\"'#{-"-} -> 
452         case untilEndOfString# (stepOn (stepOverLexeme buf3)) of { buf4 ->
453         let file = lexemeToFastString buf4 in
454         \s@PState{loc=loc} -> skipToEnd buf4 s{loc = mkSrcLoc file i}
455         }
456      other -> \s@PState{loc=loc} -> skipToEnd buf3 s{loc = replaceSrcLine loc l}
457   }}}}
458   where
459         skipToEnd buf = nested_comment cont buf
460
461 nested_comment :: P a -> P a
462 nested_comment cont buf = loop buf
463  where
464    loop buf = 
465      case currentChar# buf of
466         '\NUL'# | bufferExhausted (stepOn buf) -> 
467                 lexError "unterminated `{-'" buf
468
469         '-'# | lookAhead# buf 1# `eqChar#` '}'# ->
470                 cont (stepOnBy# buf 2#)
471
472         '{'# | lookAhead# buf 1# `eqChar#` '-'# ->
473               nested_comment (nested_comment cont) (stepOnBy# buf 2#)
474
475         '\n'# -> \ s@PState{loc=loc} ->
476                  let buf' = stepOn buf in
477                  nested_comment cont buf'
478                         s{loc = incSrcLine loc, bol = currentIndex# buf',
479                           atbol = 1#}
480
481         _   -> nested_comment cont (stepOn buf)
482
483 -- When we are lexing the first token of a line, check whether we need to
484 -- insert virtual semicolons or close braces due to layout.
485
486 lexBOL :: (Token -> P a) -> P a
487 lexBOL cont buf s@(PState{
488                     loc = loc,
489                     glasgow_exts = glaexts,
490                     bol = bol,
491                     atbol = atbol,
492                     context = ctx
493                   }) =
494         if need_close_curly then 
495                 --trace ("col = " ++ show (I# col) ++ ", layout: inserting '}'") $
496                 cont ITvccurly buf s{atbol = 1#, context = tail ctx}
497         else if need_semi_colon then
498                 --trace ("col = " ++ show (I# col) ++ ", layout: inserting ';'") $
499                 cont ITsemi buf s{atbol = 0#}
500         else
501                 lexToken cont glaexts buf s{atbol = 0#}
502   where
503         col = currentIndex# buf -# bol
504
505         need_close_curly =
506                 case ctx of
507                         [] -> False
508                         (i:_) -> case i of
509                                     NoLayout -> False
510                                     Layout n -> col <# n
511         need_semi_colon =
512                 case ctx of
513                         [] -> False
514                         (i:_) -> case i of
515                                     NoLayout -> False
516                                     Layout n -> col ==# n
517
518
519 lexToken :: (Token -> P a) -> Int# -> P a
520 lexToken cont glaexts buf =
521  --trace "lexToken" $
522   case currentChar# buf of
523
524     -- special symbols ----------------------------------------------------
525     '('# | flag glaexts && lookAhead# buf 1# `eqChar#` '#'# 
526                 -> cont IToubxparen (setCurrentPos# buf 2#)
527          | otherwise
528                 -> cont IToparen (incLexeme buf)
529
530     ')'# -> cont ITcparen    (incLexeme buf)
531     '['# -> cont ITobrack    (incLexeme buf)
532     ']'# -> cont ITcbrack    (incLexeme buf)
533     ','# -> cont ITcomma     (incLexeme buf)
534     ';'# -> cont ITsemi      (incLexeme buf)
535
536     '}'# -> \ s@PState{context = ctx} ->
537             case ctx of 
538                 (_:ctx') -> cont ITccurly (incLexeme buf) s{context=ctx'}
539                 _        -> lexError "too many '}'s" buf s
540
541     '#'# -> case lookAhead# buf 1# of
542                 ')'#  | flag glaexts -> cont ITcubxparen (setCurrentPos# buf 2#)
543                 '-'# -> case lookAhead# buf 2# of
544                            '}'# -> cont ITclose_prag (setCurrentPos# buf 3#)
545                            _    -> lex_sym cont (incLexeme buf)
546                 _    -> lex_sym cont (incLexeme buf)
547
548     '`'# | flag glaexts && lookAhead# buf 1# `eqChar#` '`'#
549                 -> lex_cstring cont (setCurrentPos# buf 2#)
550          | otherwise
551                 -> cont ITbackquote (incLexeme buf)
552
553     '{'# ->     -- look for "{-##" special iface pragma
554         case lookAhead# buf 1# of
555            '-'# -> case lookAhead# buf 2# of
556                     '#'# -> case lookAhead# buf 3# of
557                                 '#'# ->  
558                                    let (lexeme, buf') 
559                                           = doDiscard False (stepOnBy# (stepOverLexeme buf) 4#) in
560                                    cont (ITpragma lexeme) buf'
561                                 _ -> lex_prag cont (setCurrentPos# buf 3#)
562                     _    -> cont ITocurly (incLexeme buf)
563            _ -> (layoutOff `thenP_` cont ITocurly)  (incLexeme buf)
564
565     -- strings/characters -------------------------------------------------
566     '\"'#{-"-} -> lex_string cont glaexts "" (incLexeme buf)
567     '\''#      -> lex_char (char_end cont) glaexts (incLexeme buf)
568
569     -- strictness and cpr pragmas and __scc treated specially.
570     '_'# | flag glaexts ->
571          case lookAhead# buf 1# of
572            '_'# -> case lookAhead# buf 2# of
573                     'S'# -> 
574                         lex_demand cont (stepOnUntil (not . isSpace) 
575                                         (stepOnBy# buf 3#)) -- past __S
576                     'M'# -> 
577                         cont ITcprinfo (stepOnBy# buf 3#)       -- past __M
578
579                     's'# -> 
580                         case prefixMatch (stepOnBy# buf 3#) "cc" of
581                                Just buf' -> lex_scc cont (stepOverLexeme buf')
582                                Nothing   -> lex_id cont glaexts buf
583                     _ -> lex_id cont glaexts buf
584            _    -> lex_id cont glaexts buf
585
586         -- Hexadecimal and octal constants
587     '0'# | (ch `eqChar#` 'x'# || ch `eqChar#` 'X'#) && is_hexdigit ch2
588                 -> readNum (after_lexnum cont glaexts) buf' is_hexdigit 16 hex
589          | (ch `eqChar#` 'o'# || ch `eqChar#` 'O'#) && is_octdigit ch2
590                 -> readNum (after_lexnum cont glaexts) buf' is_octdigit  8 oct_or_dec
591         where ch   = lookAhead# buf 1#
592               ch2  = lookAhead# buf 2#
593               buf' = setCurrentPos# buf 2#
594
595     '\NUL'# ->
596             if bufferExhausted (stepOn buf) then
597                cont ITeof buf
598             else
599                trace "lexIface: misplaced NUL?" $ 
600                cont (ITunknown "\NUL") (stepOn buf)
601
602     '?'# | flag glaexts && is_lower (lookAhead# buf 1#) ->
603             lex_ip cont (incLexeme buf)
604     c | is_digit  c -> lex_num cont glaexts 0 buf
605       | is_symbol c -> lex_sym cont buf
606       | is_upper  c -> lex_con cont glaexts buf
607       | is_ident  c -> lex_id  cont glaexts buf
608       | otherwise   -> lexError "illegal character" buf
609
610 -- Int# is unlifted, and therefore faster than Bool for flags.
611 {-# INLINE flag #-}
612 flag :: Int# -> Bool
613 flag 0# = False
614 flag _  = True
615
616 -------------------------------------------------------------------------------
617 -- Pragmas
618
619 lex_prag cont buf
620   = case expandWhile# is_space buf of { buf1 ->
621     case expandWhile# is_ident (stepOverLexeme buf1) of { buf2 -> 
622     let lexeme = mkFastString (map toUpper (lexemeToString buf2)) in
623     case lookupUFM pragmaKeywordsFM lexeme of
624         Just kw -> cont kw (mergeLexemes buf buf2)
625         Nothing -> panic "lex_prag"
626   }}
627
628 -------------------------------------------------------------------------------
629 -- Strings & Chars
630
631 lex_string cont glaexts s buf
632   = case currentChar# buf of
633         '"'#{-"-} -> 
634            let buf' = incLexeme buf; s' = mkFastString (reverse s) in
635            case currentChar# buf' of
636                 '#'# | flag glaexts -> cont (ITprimstring s') (incLexeme buf')
637                 _                   -> cont (ITstring s') buf'
638
639         -- ignore \& in a string, deal with string gaps
640         '\\'# | next_ch `eqChar#` '&'# 
641                 -> lex_string cont glaexts s buf'
642               | is_space next_ch
643                 -> lex_stringgap cont glaexts s (incLexeme buf)
644
645             where next_ch = lookAhead# buf 1#
646                   buf' = setCurrentPos# buf 2#
647
648         _ -> lex_char (lex_next_string cont s) glaexts buf
649
650 lex_stringgap cont glaexts s buf
651   = let buf' = incLexeme buf in
652     case currentChar# buf of
653         '\n'# -> \st@PState{loc = loc} -> lex_stringgap cont glaexts s buf' 
654                   st{loc = incSrcLine loc}
655         '\\'# -> lex_string cont glaexts s buf'
656         c | is_space c -> lex_stringgap cont glaexts s buf'
657         other -> charError buf'
658
659 lex_next_string cont s glaexts c buf = lex_string cont glaexts (c:s) buf
660
661 lex_char :: (Int# -> Char -> P a) -> Int# -> P a
662 lex_char cont glaexts buf
663   = case currentChar# buf of
664         '\\'# -> lex_escape (cont glaexts) (incLexeme buf)
665         c | is_any c -> cont glaexts (C# c) (incLexeme buf)
666         other -> charError buf
667
668 char_end cont glaexts c buf
669   = case currentChar# buf of
670         '\''# -> let buf' = incLexeme buf in
671                  case currentChar# buf' of
672                         '#'# | flag glaexts 
673                                 -> cont (ITprimchar c) (incLexeme buf')
674                         _       -> cont (ITchar c) buf'
675         _     -> charError buf
676
677 lex_escape cont buf
678   = let buf' = incLexeme buf in
679     case currentChar# buf of
680         'a'#       -> cont '\a' buf'
681         'b'#       -> cont '\b' buf'
682         'f'#       -> cont '\f' buf'
683         'n'#       -> cont '\n' buf'
684         'r'#       -> cont '\r' buf'
685         't'#       -> cont '\t' buf'
686         'v'#       -> cont '\v' buf'
687         '\\'#      -> cont '\\' buf'
688         '"'#       -> cont '\"' buf'
689         '\''#      -> cont '\'' buf'
690         '^'#       -> let c = currentChar# buf' in
691                       if c `geChar#` '@'# && c `leChar#` '_'#
692                         then cont (C# (chr# (ord# c -# ord# '@'#))) (incLexeme buf')
693                         else charError buf'
694
695         'x'#      -> readNum (after_charnum cont) buf' is_hexdigit 16 hex
696         'o'#      -> readNum (after_charnum cont) buf' is_octdigit  8 oct_or_dec
697         x | is_digit x 
698                   -> readNum (after_charnum cont) buf is_digit    10 oct_or_dec
699
700         _          -> case [ (c,buf2) | (p,c) <- silly_escape_chars,
701                                        Just buf2 <- [prefixMatch buf p] ] of
702                             (c,buf2):_ -> cont c buf2
703                             [] -> charError buf'
704
705 after_charnum cont i buf 
706   = let int = fromInteger i in
707     if i >= 0 && i <= 255 
708         then cont (chr int) buf
709         else charError buf
710
711 readNum cont buf is_digit base conv = read buf 0
712   where read buf i 
713           = case currentChar# buf of { c ->
714             if is_digit c
715                 then read (incLexeme buf) (i*base + (toInteger (I# (conv c))))
716                 else cont i buf
717             }
718
719 is_hexdigit c 
720         =  is_digit c 
721         || (c `geChar#` 'a'# && c `leChar#` 'f'#)
722         || (c `geChar#` 'A'# && c `leChar#` 'F'#)
723
724 hex c | is_digit c = ord# c -# ord# '0'#
725       | otherwise  = ord# (to_lower c) -# ord# 'a'# +# 10#
726 oct_or_dec c = ord# c -# ord# '0'#
727
728 is_octdigit c = c `geChar#` '0'# && c `leChar#` '7'#
729
730 to_lower c 
731   | c `geChar#` 'A'# && c `leChar#` 'Z'#  
732         = chr# (ord# c -# (ord# 'A'# -# ord# 'a'#))
733   | otherwise = c
734
735 charError buf = lexError "error in character literal" buf
736
737 silly_escape_chars = [
738         ("NUL", '\NUL'),
739         ("SOH", '\SOH'),
740         ("STX", '\STX'),
741         ("ETX", '\ETX'),
742         ("EOT", '\EOT'),
743         ("ENQ", '\ENQ'),
744         ("ACK", '\ACK'),
745         ("BEL", '\BEL'),
746         ("BS", '\BS'),
747         ("HT", '\HT'),
748         ("LF", '\LF'),
749         ("VT", '\VT'),
750         ("FF", '\FF'),
751         ("CR", '\CR'),
752         ("SO", '\SO'),
753         ("SI", '\SI'),
754         ("DLE", '\DLE'),
755         ("DC1", '\DC1'),
756         ("DC2", '\DC2'),
757         ("DC3", '\DC3'),
758         ("DC4", '\DC4'),
759         ("NAK", '\NAK'),
760         ("SYN", '\SYN'),
761         ("ETB", '\ETB'),
762         ("CAN", '\CAN'),
763         ("EM", '\EM'),
764         ("SUB", '\SUB'),
765         ("ESC", '\ESC'),
766         ("FS", '\FS'),
767         ("GS", '\GS'),
768         ("RS", '\RS'),
769         ("US", '\US'),
770         ("SP", '\SP'),
771         ("DEL", '\DEL')
772         ]
773
774 -------------------------------------------------------------------------------
775
776 lex_demand cont buf = 
777  case read_em [] buf of { (ls,buf') -> 
778  case currentChar# buf' of
779    'B'# -> cont (ITstrict (ls, True )) (incLexeme buf')
780    _    -> cont (ITstrict (ls, False)) buf'
781  }
782  where
783    -- code snatched from Demand.lhs
784   read_em acc buf = 
785    case currentChar# buf of
786     'L'# -> read_em (WwLazy False : acc) (stepOn buf)
787     'A'# -> read_em (WwLazy True  : acc) (stepOn buf)
788     'S'# -> read_em (WwStrict     : acc) (stepOn buf)
789     'P'# -> read_em (WwPrim       : acc) (stepOn buf)
790     'E'# -> read_em (WwEnum       : acc) (stepOn buf)
791     ')'# -> (reverse acc, stepOn buf)
792     'U'# -> do_unpack DataType True  acc (stepOnBy# buf 2#)
793     'u'# -> do_unpack DataType False acc (stepOnBy# buf 2#)
794     'N'# -> do_unpack NewType True  acc (stepOnBy# buf 2#)
795     'n'# -> do_unpack NewType False acc (stepOnBy# buf 2#)
796     _    -> (reverse acc, buf)
797
798   do_unpack new_or_data wrapper_unpacks acc buf
799    = case read_em [] buf of
800       (stuff, rest) -> read_em (WwUnpack new_or_data wrapper_unpacks stuff : acc) rest
801
802
803 ------------------
804 lex_scc cont buf =
805  case currentChar# buf of
806   'C'# -> cont ITsccAllCafs (incLexeme buf)
807   other -> cont ITscc buf
808
809 -----------------------------------------------------------------------------
810 -- Numbers
811
812 lex_num :: (Token -> P a) -> Int# -> Integer -> P a
813 lex_num cont glaexts acc buf =
814  case scanNumLit acc buf of
815      (acc',buf') ->
816        case currentChar# buf' of
817          '.'# | is_digit (lookAhead# buf' 1#) ->
818              -- this case is not optimised at all, as the
819              -- presence of floating point numbers in interface
820              -- files is not that common. (ToDo)
821             case expandWhile# is_digit (incLexeme buf') of
822               buf2 -> -- points to first non digit char
823
824                 let l = case currentChar# buf2 of
825                           'E'# -> do_exponent
826                           'e'# -> do_exponent
827                           _ -> buf2
828
829                     do_exponent 
830                         = let buf3 = incLexeme buf2 in
831                           case currentChar# buf3 of
832                                 '-'# -> expandWhile# is_digit (incLexeme buf3)
833                                 '+'# -> expandWhile# is_digit (incLexeme buf3)
834                                 x | is_digit x -> expandWhile# is_digit buf3
835                                 _ -> buf2
836
837                     v = readRational__ (lexemeToString l)
838
839                 in case currentChar# l of -- glasgow exts only
840                       '#'# | flag glaexts -> let l' = incLexeme l in
841                               case currentChar# l' of
842                                 '#'# -> cont (ITprimdouble v) (incLexeme l')
843                                 _    -> cont (ITprimfloat  v) l'
844                       _ -> cont (ITrational v) l
845
846          _ -> after_lexnum cont glaexts acc' buf'
847                 
848 after_lexnum cont glaexts i buf
849   = case currentChar# buf of
850         '#'# | flag glaexts -> cont (ITprimint i) (incLexeme buf)
851         _    -> cont (ITinteger i) buf
852
853 -----------------------------------------------------------------------------
854 -- C "literal literal"s  (i.e. things like ``NULL'', ``stdout'' etc.)
855
856 -- we lexemeToFastString on the bit between the ``''s, but include the
857 -- quotes in the full lexeme.
858
859 lex_cstring cont buf =
860  case expandUntilMatch (stepOverLexeme buf) "\'\'" of
861    Just buf' -> cont (ITlitlit (lexemeToFastString 
862                                 (setCurrentPos# buf' (negateInt# 2#))))
863                    (mergeLexemes buf buf')
864    Nothing   -> lexError "unterminated ``" buf
865
866 -----------------------------------------------------------------------------
867 -- identifiers, symbols etc.
868
869 lex_ip cont buf =
870  case expandWhile# is_ident buf of
871    buf' -> cont (ITipvarid lexeme) buf'
872            where lexeme = lexemeToFastString buf'
873
874 lex_id cont glaexts buf =
875  case expandWhile# is_ident buf of { buf1 -> 
876
877  case (if flag glaexts 
878         then expandWhile# (eqChar# '#'#) buf1 -- slurp trailing hashes
879         else buf1)                              of { buf' ->
880
881  let lexeme  = lexemeToFastString buf' in
882
883  case _scc_ "Lex.haskellKeyword" lookupUFM haskellKeywordsFM lexeme of {
884         Just kwd_token -> --trace ("hkeywd: "++_UNPK_(lexeme)) $
885                           cont kwd_token buf';
886         Nothing        -> 
887
888  let var_token = cont (mk_var_token lexeme) buf' in
889
890  if not (flag glaexts)
891    then var_token
892    else
893
894  case lookupUFM ghcExtensionKeywordsFM lexeme of {
895         Just kwd_token -> cont kwd_token buf';
896         Nothing        -> var_token
897
898  }}}}
899
900 lex_sym cont buf =
901  case expandWhile# is_symbol buf of
902    buf' -> case lookupUFM haskellKeySymsFM lexeme of {
903                 Just kwd_token -> --trace ("keysym: "++unpackFS lexeme) $
904                                   cont kwd_token buf' ;
905                 Nothing        -> --trace ("sym: "++unpackFS lexeme) $
906                                   cont (mk_var_token lexeme) buf'
907            }
908         where lexeme = lexemeToFastString buf'
909
910
911 lex_con cont glaexts buf = 
912  case expandWhile# is_ident buf          of { buf1 ->
913  case slurp_trailing_hashes buf1 glaexts of { buf' ->
914
915  case currentChar# buf' of
916      '.'# -> munch
917      _    -> just_a_conid
918  
919    where
920     just_a_conid = --trace ("con: "++unpackFS lexeme) $
921                    cont (ITconid lexeme) buf'
922     lexeme = lexemeToFastString buf'
923     munch = lex_qid cont glaexts lexeme (incLexeme buf') just_a_conid
924  }}
925
926 lex_qid cont glaexts mod buf just_a_conid =
927  case currentChar# buf of
928   '['# ->       -- Special case for []
929     case lookAhead# buf 1# of
930      ']'# -> cont (ITqconid  (mod,SLIT("[]"))) (setCurrentPos# buf 2#)
931      _    -> just_a_conid
932
933   '('# ->  -- Special case for (,,,)
934            -- This *is* necessary to deal with e.g. "instance C PrelBase.(,,)"
935     case lookAhead# buf 1# of
936      '#'# | flag glaexts -> case lookAhead# buf 2# of
937                 ','# -> lex_ubx_tuple cont mod (setCurrentPos# buf 3#) 
938                                 just_a_conid
939                 _    -> just_a_conid
940      ')'# -> cont (ITqconid (mod,SLIT("()"))) (setCurrentPos# buf 2#)
941      ','# -> lex_tuple cont mod (setCurrentPos# buf 2#) just_a_conid
942      _    -> just_a_conid
943
944   '-'# -> case lookAhead# buf 1# of
945             '>'# -> cont (ITqconid (mod,SLIT("->"))) (setCurrentPos# buf 2#)
946             _    -> lex_id3 cont glaexts mod buf just_a_conid
947   _    -> lex_id3 cont glaexts mod buf just_a_conid
948
949 lex_id3 cont glaexts mod buf just_a_conid
950   | is_symbol (currentChar# buf) =
951      let 
952         start_new_lexeme = stepOverLexeme buf
953      in
954      case expandWhile# is_symbol start_new_lexeme of { buf' ->
955      let
956        lexeme  = lexemeToFastString buf'
957         -- real lexeme is M.<sym>
958        new_buf = mergeLexemes buf buf'
959      in
960      cont (mk_qvar_token mod lexeme) new_buf
961         -- wrong, but arguably morally right: M... is now a qvarsym
962      }
963
964   | otherwise   =
965      let 
966         start_new_lexeme = stepOverLexeme buf
967      in
968      case expandWhile# is_ident start_new_lexeme of { buf1 ->
969      if emptyLexeme buf1 
970             then just_a_conid
971             else
972
973      case slurp_trailing_hashes buf1 glaexts of { buf' ->
974
975      let
976       lexeme  = lexemeToFastString buf'
977       new_buf = mergeLexemes buf buf'
978       is_a_qvarid = cont (mk_qvar_token mod lexeme) new_buf
979      in
980      case _scc_ "Lex.haskellKeyword" lookupUFM haskellKeywordsFM lexeme of {
981             Just kwd_token -> just_a_conid; -- avoid M.where etc.
982             Nothing        -> is_a_qvarid
983         -- TODO: special ids (as, qualified, hiding) shouldn't be
984         -- recognised as keywords here.  ie.  M.as is a qualified varid.
985      }}}
986
987
988 slurp_trailing_hashes buf glaexts
989   | flag glaexts = expandWhile# (`eqChar#` '#'#) buf
990   | otherwise    = buf
991
992
993 mk_var_token pk_str
994   | is_upper f          = ITconid pk_str
995   | is_ident f          = ITvarid pk_str
996   | f `eqChar#` ':'#    = ITconsym pk_str
997   | otherwise           = ITvarsym pk_str
998   where
999       (C# f) = _HEAD_ pk_str
1000       tl     = _TAIL_ pk_str
1001
1002 mk_qvar_token m token =
1003  case mk_var_token token of
1004    ITconid n  -> ITqconid  (m,n)
1005    ITvarid n  -> ITqvarid  (m,n)
1006    ITconsym n -> ITqconsym (m,n)
1007    ITvarsym n -> ITqvarsym (m,n)
1008    _          -> ITunknown (show token)
1009 \end{code}
1010
1011 ----------------------------------------------------------------------------
1012 Horrible stuff for dealing with M.(,,,)
1013
1014 \begin{code}
1015 lex_tuple cont mod buf back_off =
1016   go 2 buf
1017   where
1018    go n buf =
1019     case currentChar# buf of
1020       ','# -> go (n+1) (stepOn buf)
1021       ')'# -> cont (ITqconid (mod, snd (mkTupNameStr n))) (stepOn buf)
1022       _    -> back_off
1023
1024 lex_ubx_tuple cont mod buf back_off =
1025   go 2 buf
1026   where
1027    go n buf =
1028     case currentChar# buf of
1029       ','# -> go (n+1) (stepOn buf)
1030       '#'# -> case lookAhead# buf 1# of
1031                 ')'# -> cont (ITqconid (mod, snd (mkUbxTupNameStr n)))
1032                                  (stepOnBy# buf 2#)
1033                 _    -> back_off
1034       _    -> back_off
1035 \end{code}
1036
1037 -----------------------------------------------------------------------------
1038 doDiscard rips along really fast, looking for a '#-}', 
1039 indicating the end of the pragma we're skipping
1040
1041 \begin{code}
1042 doDiscard inStr buf =
1043  case currentChar# buf of
1044    '#'# | not inStr ->
1045        case lookAhead# buf 1# of { '#'# -> 
1046        case lookAhead# buf 2# of { '-'# ->
1047        case lookAhead# buf 3# of { '}'# -> 
1048            (lexemeToBuffer buf, stepOverLexeme (setCurrentPos# buf 4#));
1049         _    -> doDiscard inStr (incLexeme buf) };
1050         _    -> doDiscard inStr (incLexeme buf) };
1051         _    -> doDiscard inStr (incLexeme buf) }
1052    '"'# ->
1053        let
1054         odd_slashes buf flg i# =
1055           case lookAhead# buf i# of
1056            '\\'# -> odd_slashes buf (not flg) (i# -# 1#)
1057            _     -> flg
1058        in
1059        case lookAhead# buf (negateInt# 1#) of --backwards, actually
1060          '\\'# -> -- escaping something..
1061            if odd_slashes buf True (negateInt# 2#) then
1062                -- odd number of slashes, " is escaped.
1063               doDiscard inStr (incLexeme buf)
1064            else
1065                -- even number of slashes, \ is escaped.
1066               doDiscard (not inStr) (incLexeme buf)
1067          _ -> case inStr of -- forced to avoid build-up
1068                True  -> doDiscard False (incLexeme buf)
1069                False -> doDiscard True  (incLexeme buf)
1070    _ -> doDiscard inStr (incLexeme buf)
1071
1072 \end{code}
1073
1074 -----------------------------------------------------------------------------
1075
1076 \begin{code}
1077 data LayoutContext
1078   = NoLayout
1079   | Layout Int#
1080
1081 data ParseResult a
1082   = POk PState a
1083   | PFailed Message
1084
1085 data PState = PState { 
1086         loc           :: SrcLoc,
1087         glasgow_exts  :: Int#,
1088         bol           :: Int#,
1089         atbol         :: Int#,
1090         context       :: [LayoutContext]
1091      }
1092
1093 type P a = StringBuffer         -- Input string
1094         -> PState
1095         -> ParseResult a
1096
1097 returnP   :: a -> P a
1098 returnP a buf s = POk s a
1099
1100 thenP      :: P a -> (a -> P b) -> P b
1101 m `thenP` k = \ buf s ->
1102         case m buf s of
1103                 POk s1 a -> k a buf s1
1104                 PFailed err  -> PFailed err
1105
1106 thenP_     :: P a -> P b -> P b
1107 m `thenP_` k = m `thenP` \_ -> k
1108
1109 mapP :: (a -> P b) -> [a] -> P [b]
1110 mapP f [] = returnP []
1111 mapP f (a:as) = 
1112      f a `thenP` \b ->
1113      mapP f as `thenP` \bs ->
1114      returnP (b:bs)
1115
1116 failP :: String -> P a
1117 failP msg buf s = PFailed (text msg)
1118
1119 failMsgP :: Message -> P a
1120 failMsgP msg buf s = PFailed msg
1121
1122 lexError :: String -> P a
1123 lexError str buf s@PState{ loc = loc } 
1124   = failMsgP (hcat [ppr loc, text ": ", text str]) buf s
1125
1126 getSrcLocP :: P SrcLoc
1127 getSrcLocP buf s@(PState{ loc = loc }) = POk s loc
1128
1129 getSrcFile :: P FAST_STRING
1130 getSrcFile buf s@(PState{ loc = loc }) = POk s (srcLocFile loc)
1131
1132 getContext :: P [LayoutContext]
1133 getContext buf s@(PState{ context = ctx }) = POk s ctx
1134
1135 pushContext :: LayoutContext -> P ()
1136 pushContext ctxt buf s@(PState{ context = ctx }) = POk s{context = ctxt:ctx} ()
1137
1138 {-
1139
1140 This special case in layoutOn is to handle layout contexts with are
1141 indented the same or less than the current context.  This is illegal
1142 according to the Haskell spec, so we have to arrange to close the
1143 current context.  eg.
1144
1145 class Foo a where
1146 class Bar a
1147
1148 after the first 'where', the sequence of events is:
1149
1150         - layout system inserts a ';' (column 0)
1151         - parser begins a new context at column 0
1152         - parser shifts ';' (legal empty declaration)
1153         - parser sees 'class': parse error (we're still in the inner context)
1154
1155 trouble is, by the time we know we need a new context, the lexer has
1156 already generated the ';'.  Hacky solution is as follows: since we
1157 know the column of the next token (it's the column number of the new
1158 context), we set the ACTUAL column number of the new context to this
1159 numer plus one.  Hence the next time the lexer is called, a '}' will
1160 be generated to close the new context straight away.  Furthermore, we
1161 have to set the atbol flag so that the ';' that the parser shifted as
1162 part of the new context is re-generated.
1163
1164 when the new context is *less* indented than the current one:
1165
1166 f = f where g = g where
1167 h = h
1168
1169         - current context: column 12.
1170         - on seeing 'h' (column 0), the layout system inserts '}'
1171         - parser starts a new context, column 0
1172         - parser sees '}', uses it to close new context
1173         - we still need to insert another '}' followed by a ';',
1174           hence the atbol trick.
1175
1176 There's also a special hack in here to deal with
1177
1178         do
1179            ....
1180            e $ do
1181            blah
1182
1183 i.e. the inner context is at the same indentation level as the outer
1184 context.  This is strictly illegal according to Haskell 98, but
1185 there's a lot of existing code using this style and it doesn't make
1186 any sense to disallow it, since empty 'do' lists don't make sense.
1187 -}
1188
1189 layoutOn :: Bool -> P ()
1190 layoutOn strict buf s@(PState{ bol = bol, context = ctx }) =
1191     let offset = lexemeIndex buf -# bol in
1192     case ctx of
1193         Layout prev_off : _ 
1194            | if strict then prev_off >=# offset else prev_off ># offset ->
1195                 --trace ("layout on, column: " ++  show (I# offset)) $
1196                 POk s{ context = Layout (offset +# 1#) : ctx, atbol = 1# } ()
1197         other -> 
1198                 --trace ("layout on, column: " ++  show (I# offset)) $
1199                 POk s{ context = Layout offset : ctx } ()
1200
1201 layoutOff :: P ()
1202 layoutOff buf s@(PState{ context = ctx }) =
1203     POk s{ context = NoLayout:ctx } ()
1204
1205 popContext :: P ()
1206 popContext = \ buf s@(PState{ context = ctx, loc = loc }) ->
1207   case ctx of
1208         (_:tl) -> POk s{ context = tl } ()
1209         []     -> PFailed (srcParseErr buf loc)
1210
1211 {- 
1212  Note that if the name of the file we're processing ends
1213  with `hi-boot', we accept it on faith as having the right
1214  version. This is done so that .hi-boot files that comes
1215  with hsc don't have to be updated before every release,
1216  *and* it allows us to share .hi-boot files with versions
1217  of hsc that don't have .hi version checking (e.g., ghc-2.10's)
1218
1219  If the version number is 0, the checking is also turned off.
1220  (needed to deal with GHC.hi only!)
1221
1222  Once we can assume we're compiling with a version of ghc that
1223  supports interface file checking, we can drop the special
1224  pleading
1225 -}
1226 checkVersion :: Maybe Integer -> P ()
1227 checkVersion mb@(Just v) buf s@(PState{loc = loc})
1228  | (v==0) || (v == fromInt opt_HiVersion) || opt_NoHiCheck = POk s ()
1229  | otherwise = PFailed (ifaceVersionErr mb loc ([]::[Token]){-Todo-})
1230 checkVersion mb@Nothing  buf s@(PState{loc = loc})
1231  | "hi-boot" `isSuffixOf` (_UNPK_ (srcLocFile loc)) = POk s ()
1232  | otherwise = PFailed (ifaceVersionErr mb loc ([]::[Token]){-Todo-})
1233
1234 -----------------------------------------------------------------
1235
1236 ifaceParseErr :: StringBuffer -> SrcLoc -> Message
1237 ifaceParseErr s l
1238   = hsep [ppr l, ptext SLIT("Interface file parse error; on input `"),
1239           text (lexemeToString s), char '\'']
1240
1241 ifaceVersionErr hi_vers l toks
1242   = hsep [ppr l, ptext SLIT("Interface file version error;"),
1243           ptext SLIT("Expected"), int opt_HiVersion, 
1244           ptext SLIT("found "), pp_version]
1245     where
1246      pp_version =
1247       case hi_vers of
1248         Nothing -> ptext SLIT("pre ghc-3.02 version")
1249         Just v  -> ptext SLIT("version") <+> integer v
1250
1251 -----------------------------------------------------------------------------
1252
1253 srcParseErr :: StringBuffer -> SrcLoc -> Message
1254 srcParseErr s l
1255   = hcat [ppr l, 
1256           if null token 
1257              then ptext SLIT(": parse error (possibly incorrect indentation)")
1258              else hcat [ptext SLIT(": parse error on input "),
1259                         char '`', text token, char '\'']
1260     ]
1261   where 
1262         token = lexemeToString s
1263
1264 \end{code}