Lex.lhs 39.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
%
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
%
\section[Lexical analysis]{Lexical analysis}

--------------------------------------------------------
[Jan 98]
There's a known bug in here:

	If an interface file ends prematurely, Lex tries to
	do headFS of an empty FastString.

An example that provokes the error is

	f _:_ _forall_ [a] <<<END OF FILE>>>
--------------------------------------------------------

\begin{code}
19

20
21
module Lex (

22
	ifaceParseErr, srcParseErr,
23
24
25
26
27
28
29

	-- Monad for parser
	Token(..), lexer, ParseResult(..), PState(..),
	checkVersion, 
	StringBuffer,

	P, thenP, thenP_, returnP, mapP, failP, failMsgP,
30
	getSrcLocP, setSrcLocP, getSrcFile,
31
32
33
34
35
	layoutOn, layoutOff, pushContext, popContext
    ) where

#include "HsVersions.h"

36
import Char 		( isSpace, toUpper )
37
38
import List             ( isSuffixOf )

39
import IdInfo		( InlinePragInfo(..) )
40
import PrelNames	( mkTupNameStr )
41
import CmdLineOpts	( opt_HiVersion, opt_NoHiCheck )
42
import ForeignCall	( Safety(..) )
43
import Demand		( Demand(..) {- instance Read -} )
44
import UniqFM           ( listToUFM, lookupUFM )
45
import BasicTypes	( Boxity(..) )
46
47
48
49
50
51
52
53
54
import SrcLoc		( SrcLoc, incSrcLine, srcLocFile, srcLocLine,
			  replaceSrcLine, mkSrcLoc )

import ErrUtils		( Message )
import Outputable

import FastString
import StringBuffer
import GlaExts
55
import Ctype
56
import Char		( chr, ord )
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import PrelRead 	( readRational__ ) -- Glasgow non-std
\end{code}

%************************************************************************
%*									*
\subsection{Data types}
%*									*
%************************************************************************

The token data type, fairly un-interesting except from one
constructor, @ITidinfo@, which is used to lazily lex id info (arity,
strictness, unfolding etc).

The Idea/Observation here is that the renamer needs to scan through
all of an interface file before it can continue. But only a fraction
of the information contained in the file turns out to be useful, so
delaying as much as possible of the scanning and parsing of an
interface file Makes Sense (Heap profiles of the compiler 
show a reduction in heap usage by at least a factor of two,
post-renamer). 

Hence, the interface file lexer spots when value declarations are
being scanned and return the @ITidinfo@ and @ITtype@ constructors
for the type and any other id info for that binding (unfolding, strictness
etc). These constructors are applied to the result of lexing these sub-chunks.

The lexing of the type and id info is all done lazily, of course, so
the scanning (and subsequent parsing) will be done *only* on the ids the
renamer finds out that it is interested in. The rest will just be junked.
Laziness, you know it makes sense :-)

\begin{code}
data Token
90
91
  = ITas  			-- Haskell keywords
  | ITcase
92
93
94
95
96
97
  | ITclass
  | ITdata
  | ITdefault
  | ITderiving
  | ITdo
  | ITelse
98
  | IThiding
99
100
101
102
103
104
105
106
107
108
109
  | ITif
  | ITimport
  | ITin
  | ITinfix
  | ITinfixl
  | ITinfixr
  | ITinstance
  | ITlet
  | ITmodule
  | ITnewtype
  | ITof
110
  | ITqualified
111
112
113
  | ITthen
  | ITtype
  | ITwhere
114
  | ITscc			-- ToDo: remove (we use {-# SCC "..." #-} now)
115
116
117
118
119
120
121

  | ITforall			-- GHC extension keywords
  | ITforeign
  | ITexport
  | ITlabel
  | ITdynamic
  | ITunsafe
122
  | ITwith
sof's avatar
sof committed
123
124
  | ITstdcallconv
  | ITccallconv
125
  | ITdotnet
126
127
128
129
130
131
132
133
134

  | ITinterface			-- interface keywords
  | IT__export
  | ITdepends
  | IT__forall
  | ITletrec 
  | ITcoerce
  | ITinlineMe
  | ITinlineCall
135
  | ITccall (Bool,Bool,Safety)	-- (is_dyn, is_casm, may_gc)
136
137
138
139
  | ITdefaultbranch
  | ITbottom
  | ITinteger_lit 
  | ITfloat_lit
140
141
142
  | ITword_lit
  | ITword64_lit
  | ITint64_lit
143
144
  | ITrational_lit
  | ITaddr_lit
145
  | ITlabel_lit
146
147
148
  | ITlit_lit
  | ITstring_lit
  | ITtypeapp
149
150
  | ITusage
  | ITfuall
151
152
153
154
155
156
  | ITarity 
  | ITspecialise
  | ITnocaf
  | ITunfold InlinePragInfo
  | ITstrict ([Demand], Bool)
  | ITrules
157
  | ITcprinfo
158
  | ITdeprecated
159
  | IT__scc
160
161
162
163
164
165
166
  | ITsccAllCafs

  | ITspecialise_prag		-- Pragmas
  | ITsource_prag
  | ITinline_prag
  | ITnoinline_prag
  | ITrules_prag
167
  | ITdeprecated_prag
168
  | ITline_prag
169
  | ITscc_prag
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
  | ITclose_prag

  | ITdotdot  			-- reserved symbols
  | ITdcolon
  | ITequal
  | ITlam
  | ITvbar
  | ITlarrow
  | ITrarrow
  | ITat
  | ITtilde
  | ITdarrow
  | ITminus
  | ITbang
  | ITdot

  | ITbiglam			-- GHC-extension symbols

  | ITocurly  			-- special symbols
  | ITccurly
190
191
  | ITocurlybar                 -- {|, for type applications
  | ITccurlybar                 -- |}, for type applications
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
  | ITvccurly
  | ITobrack
  | ITcbrack
  | IToparen
  | ITcparen
  | IToubxparen
  | ITcubxparen
  | ITsemi
  | ITcomma
  | ITunderscore
  | ITbackquote

  | ITvarid   FAST_STRING	-- identifiers
  | ITconid   FAST_STRING
  | ITvarsym  FAST_STRING
  | ITconsym  FAST_STRING
  | ITqvarid  (FAST_STRING,FAST_STRING)
  | ITqconid  (FAST_STRING,FAST_STRING)
  | ITqvarsym (FAST_STRING,FAST_STRING)
  | ITqconsym (FAST_STRING,FAST_STRING)

213
214
  | ITipvarid FAST_STRING	-- GHC extension: implicit param: ?x

215
216
  | ITpragma StringBuffer

217
  | ITchar       Int
218
  | ITstring     FAST_STRING
219
  | ITinteger    Integer
220
221
  | ITrational   Rational

222
  | ITprimchar   Int
223
224
225
226
227
228
229
230
  | ITprimstring FAST_STRING
  | ITprimint    Integer
  | ITprimfloat  Rational
  | ITprimdouble Rational
  | ITlitlit     FAST_STRING

  | ITunknown String		-- Used when the lexer can't make sense of it
  | ITeof			-- end of file token
231
  deriving Show -- debugging
232
233
234
235
236
237
238
239
240
241
242
243
244
\end{code}

-----------------------------------------------------------------------------
Keyword Lists

\begin{code}
pragmaKeywordsFM = listToUFM $
      map (\ (x,y) -> (_PK_ x,y))
       [( "SPECIALISE", ITspecialise_prag ),
	( "SPECIALIZE", ITspecialise_prag ),
	( "SOURCE",	ITsource_prag ),
	( "INLINE",     ITinline_prag ),
	( "NOINLINE",   ITnoinline_prag ),
245
	( "NOTINLINE",	ITnoinline_prag ),
246
247
	( "LINE",       ITline_prag ),
	( "RULES",	ITrules_prag ),
248
	( "RULEZ",	ITrules_prag ),	-- american spelling :-)
249
	( "SCC",	ITscc_prag ),
250
	( "DEPRECATED",	ITdeprecated_prag )
251
252
253
254
255
 	]

haskellKeywordsFM = listToUFM $
      map (\ (x,y) -> (_PK_ x,y))
       [( "_",		ITunderscore ),
256
	( "as",		ITas ),
257
258
259
260
261
262
263
	( "case",	ITcase ),     
	( "class",	ITclass ),    
	( "data",	ITdata ),     
	( "default",	ITdefault ),  
	( "deriving",	ITderiving ), 
	( "do",		ITdo ),       
	( "else",	ITelse ),     
264
	( "hiding",	IThiding ),
265
266
267
268
269
270
271
272
273
274
275
	( "if",		ITif ),       
	( "import",	ITimport ),   
	( "in",		ITin ),       
	( "infix",	ITinfix ),    
	( "infixl",	ITinfixl ),   
	( "infixr",	ITinfixr ),   
	( "instance",	ITinstance ), 
	( "let",	ITlet ),      
	( "module",	ITmodule ),   
	( "newtype",	ITnewtype ),  
	( "of",		ITof ),       
276
	( "qualified",	ITqualified ),
277
278
	( "then",	ITthen ),     
	( "type",	ITtype ),     
279
	( "where",	ITwhere ),
280
	( "_scc_",	ITscc )		-- ToDo: remove
281
282
     ]

283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
isSpecial :: Token -> Bool
-- If we see M.x, where x is a keyword, but
-- is special, we treat is as just plain M.x, 
-- not as a keyword.
isSpecial ITas        	= True
isSpecial IThiding    	= True
isSpecial ITqualified 	= True
isSpecial ITforall    	= True
isSpecial ITexport    	= True
isSpecial ITlabel     	= True
isSpecial ITdynamic   	= True
isSpecial ITunsafe    	= True
isSpecial ITwith      	= True
isSpecial ITccallconv   = True
isSpecial ITstdcallconv = True
298
isSpecial _             = False
299

300
-- IMPORTANT: Keep this in synch with ParseIface.y's var_fs production! (SUP)
301
302
303
304
305
306
307
308
ghcExtensionKeywordsFM = listToUFM $
	map (\ (x,y) -> (_PK_ x,y))
     [	( "forall",	ITforall ),
	( "foreign",	ITforeign ),
	( "export",	ITexport ),
	( "label",	ITlabel ),
	( "dynamic",	ITdynamic ),
	( "unsafe",	ITunsafe ),
309
	( "with",	ITwith ),
sof's avatar
sof committed
310
311
	( "stdcall",    ITstdcallconv),
	( "ccall",      ITccallconv),
312
	( "dotnet",     ITdotnet),
313
314
315
316
        ("_ccall_",	ITccall (False, False, PlayRisky)),
        ("_ccall_GC_",	ITccall (False, False, PlaySafe)),
        ("_casm_",	ITccall (False, True,  PlayRisky)),
        ("_casm_GC_",	ITccall (False, True,  PlaySafe)),
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331

	-- interface keywords
        ("__interface",		ITinterface),
	("__export",		IT__export),
	("__depends",		ITdepends),
	("__forall",		IT__forall),
	("__letrec",		ITletrec),
	("__coerce",		ITcoerce),
	("__inline_me",		ITinlineMe),
	("__inline_call",	ITinlineCall),
	("__depends",		ITdepends),
	("__DEFAULT",		ITdefaultbranch),
	("__bot",		ITbottom),
	("__integer",		ITinteger_lit),
	("__float",		ITfloat_lit),
332
333
334
	("__int64",		ITint64_lit),
	("__word",		ITword_lit),
	("__word64",		ITword64_lit),
335
336
	("__rational",		ITrational_lit),
	("__addr",		ITaddr_lit),
337
	("__label",		ITlabel_lit),
338
339
340
	("__litlit",		ITlit_lit),
	("__string",		ITstring_lit),
	("__a",			ITtypeapp),
341
342
	("__u",			ITusage),
	("__fuall",		ITfuall),
343
344
345
346
	("__A",			ITarity),
	("__P",			ITspecialise),
	("__C",			ITnocaf),
	("__R",			ITrules),
347
        ("__D",			ITdeprecated),
348
        ("__U",			ITunfold NoInlinePragInfo),
349
	
350
351
352
353
354
355
356
357
        ("__ccall",		ITccall (False, False, PlayRisky)),
        ("__ccall_GC",		ITccall (False, False, PlaySafe)),
        ("__dyn_ccall",		ITccall (True,  False, PlayRisky)),
        ("__dyn_ccall_GC",	ITccall (True,  False, PlaySafe)),
        ("__casm",		ITccall (False, True,  PlayRisky)),
        ("__dyn_casm",		ITccall (True,  True,  PlayRisky)),
        ("__casm_GC",		ITccall (False, True,  PlaySafe)),
        ("__dyn_casm_GC",	ITccall (True,  True,  PlaySafe)),
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402

        ("/\\",			ITbiglam)
     ]


haskellKeySymsFM = listToUFM $
	map (\ (x,y) -> (_PK_ x,y))
      [ ("..",		ITdotdot)
       ,("::",		ITdcolon)
       ,("=",		ITequal)
       ,("\\",		ITlam)
       ,("|",		ITvbar)
       ,("<-",		ITlarrow)
       ,("->",		ITrarrow)
       ,("@",		ITat)
       ,("~",		ITtilde)
       ,("=>",		ITdarrow)
       ,("-",		ITminus)
       ,("!",		ITbang)
       ,(".",		ITdot)		-- sadly, for 'forall a . t'
       ]
\end{code}

-----------------------------------------------------------------------------
The lexical analyser

Lexer state:

	- (glaexts) lexing an interface file or -fglasgow-exts
	- (bol)   pointer to beginning of line (for column calculations)
	- (buf)   pointer to beginning of token
	- (buf)   pointer to current char
	- (atbol) flag indicating whether we're at the beginning of a line

\begin{code}
lexer :: (Token -> P a) -> P a
lexer cont buf s@(PState{
		    loc = loc,
		    glasgow_exts = glaexts,
		    bol = bol,
		    atbol = atbol,
		    context = ctx
		})

	-- first, start a new lexeme and lose all the whitespace
403
404
  =  _scc_ "Lexer" 
  tab line bol atbol (stepOverLexeme buf)
405
406
407
  where
	line = srcLocLine loc

408
	tab y bol atbol buf = -- trace ("tab: " ++ show (I# y) ++ " : " ++ show (currentChar buf)) $
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
	  case currentChar# buf of

	    '\NUL'# ->
	 	   if bufferExhausted (stepOn buf)
	       		then cont ITeof buf s'
			else trace "lexer: misplaced NUL?" $ 
			     tab y bol atbol (stepOn buf)

	    '\n'# -> let buf' = stepOn buf
		     in tab (y +# 1#) (currentIndex# buf') 1# buf'

		-- find comments.  This got harder in Haskell 98.
	    '-'# ->  let trundle n = 
			  let next = lookAhead# buf n in
			  if next `eqChar#` '-'# then trundle (n +# 1#)
			  else if is_symbol next || n <# 2#
				then is_a_token
426
427
			        else tab y bol atbol 
					 (stepOnUntilChar# (stepOnBy# buf n) '\n'#)
428
429
430
431
432
433
		    in trundle 1#

		-- comments and pragmas.  We deal with LINE pragmas here,
		-- and throw out any unrecognised pragmas as comments.  Any
		-- pragmas we know about are dealt with later (after any layout
		-- processing if necessary).
434
            '{'# | lookAhead# buf 1# `eqChar#` '-'# ->
435
436
437
438
		if lookAhead# buf 2# `eqChar#` '#'# then
		  if lookAhead# buf 3# `eqChar#` '#'# then is_a_token else
		  case expandWhile# is_space (setCurrentPos# buf 3#) of { buf1->
		  case expandWhile# is_ident (stepOverLexeme buf1)   of { buf2->
439
440
		  let lexeme = mkFastString -- ToDo: too slow
			          (map toUpper (lexemeToString buf2)) in
441
		  case lookupUFM pragmaKeywordsFM lexeme of
442
443
			Just ITline_prag -> 
			   line_prag skip_to_end buf2 s'
444
			Just other -> is_a_token
445
			Nothing -> skip_to_end (stepOnBy# buf 2#) s'
446
		  }}
447
448

		else skip_to_end (stepOnBy# buf 2#) s'
449
		where
450
451
452
453
		    skip_to_end = nested_comment (lexer cont)

		-- special GHC extension: we grok cpp-style #line pragmas
	    '#'# | lexemeIndex buf ==# bol -> 	-- the '#' must be in column 0
454
455
456
457
458
		case expandWhile# is_space (stepOn buf) of { buf1 ->
		if is_digit (currentChar# buf1) 
			then line_prag next_line buf1 s'
			else is_a_token
		}
459
460
		where
		next_line buf = lexer cont (stepOnUntilChar# buf '\n'#)
461
462
463
464
465
466
467
468
469
470
471
472
473

		-- tabs have been expanded beforehand
	    c | is_space c -> tab y bol atbol (stepOn buf)
	      | otherwise  -> is_a_token

	   where s' = s{loc = replaceSrcLine loc y, 
		        bol = bol,
		       atbol = atbol}

	      	 is_a_token | atbol /=# 0# = lexBOL cont buf s'
	      		    | otherwise    = lexToken cont glaexts buf s'

-- {-# LINE .. #-} pragmas.  yeuch.
474
line_prag cont buf s@PState{loc=loc} =
475
476
477
478
479
  case expandWhile# is_space buf 		of { buf1 ->
  case scanNumLit 0 (stepOverLexeme buf1) 	of { (line,buf2) ->
  -- subtract one: the line number refers to the *following* line.
  let real_line = line - 1 in
  case fromInteger real_line 			of { i@(I# l) -> 
480
	-- ToDo, if no filename then we skip the newline.... d'oh
481
482
483
484
  case expandWhile# is_space buf2 		of { buf3 ->
  case currentChar# buf3 			of
     '\"'#{-"-} -> 
	case untilEndOfString# (stepOn (stepOverLexeme buf3)) of { buf4 ->
485
486
487
488
489
490
491
	let 
	    file = lexemeToFastString buf4 
	    new_buf = stepOn (stepOverLexeme buf4)
	in
	if nullFastString file
		then cont new_buf s{loc = replaceSrcLine loc l}
		else cont new_buf s{loc = mkSrcLoc file i}
492
	}
493
     _other -> cont (stepOverLexeme buf3) s{loc = replaceSrcLine loc l}
494
495
496
497
498
499
500
501
  }}}}

nested_comment :: P a -> P a
nested_comment cont buf = loop buf
 where
   loop buf = 
     case currentChar# buf of
	'\NUL'# | bufferExhausted (stepOn buf) -> 
502
		lexError "unterminated `{-'" buf -- -}
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
	'-'# | lookAhead# buf 1# `eqChar#` '}'# ->
		cont (stepOnBy# buf 2#)

	'{'# | lookAhead# buf 1# `eqChar#` '-'# ->
	      nested_comment (nested_comment cont) (stepOnBy# buf 2#)

	'\n'# -> \ s@PState{loc=loc} ->
		 let buf' = stepOn buf in
		 nested_comment cont buf'
			s{loc = incSrcLine loc, bol = currentIndex# buf',
			  atbol = 1#}

	_   -> nested_comment cont (stepOn buf)

-- When we are lexing the first token of a line, check whether we need to
-- insert virtual semicolons or close braces due to layout.

lexBOL :: (Token -> P a) -> P a
lexBOL cont buf s@(PState{
		    loc = loc,
		    glasgow_exts = glaexts,
		    bol = bol,
		    atbol = atbol,
		    context = ctx
		  }) =
	if need_close_curly then 
	        --trace ("col = " ++ show (I# col) ++ ", layout: inserting '}'") $
		cont ITvccurly buf s{atbol = 1#, context = tail ctx}
	else if need_semi_colon then
	        --trace ("col = " ++ show (I# col) ++ ", layout: inserting ';'") $
		cont ITsemi buf s{atbol = 0#}
	else
		lexToken cont glaexts buf s{atbol = 0#}
  where
	col = currentIndex# buf -# bol

	need_close_curly =
		case ctx of
			[] -> False
			(i:_) -> case i of
				    NoLayout -> False
				    Layout n -> col <# n
	need_semi_colon =
		case ctx of
			[] -> False
			(i:_) -> case i of
				    NoLayout -> False
				    Layout n -> col ==# n


lexToken :: (Token -> P a) -> Int# -> P a
lexToken cont glaexts buf =
555
 -- trace "lexToken" $
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
  case currentChar# buf of

    -- special symbols ----------------------------------------------------
    '('# | flag glaexts && lookAhead# buf 1# `eqChar#` '#'# 
		-> cont IToubxparen (setCurrentPos# buf 2#)
	 | otherwise
		-> cont IToparen (incLexeme buf)

    ')'# -> cont ITcparen    (incLexeme buf)
    '['# -> cont ITobrack    (incLexeme buf)
    ']'# -> cont ITcbrack    (incLexeme buf)
    ','# -> cont ITcomma     (incLexeme buf)
    ';'# -> cont ITsemi      (incLexeme buf)
    '}'# -> \ s@PState{context = ctx} ->
	    case ctx of	
571
572
		(_:ctx') -> cont ITccurly (incLexeme buf) s{context=ctx'}
		_  	 -> lexError "too many '}'s" buf s
573
574
575
576
    '|'# -> case lookAhead# buf 1# of
	         '}'#  | flag glaexts -> cont ITccurlybar 
                                              (setCurrentPos# buf 2#)
                 _                    -> lex_sym cont (incLexeme buf)
577

578
                
579
580
    '#'# -> case lookAhead# buf 1# of
		')'#  | flag glaexts -> cont ITcubxparen (setCurrentPos# buf 2#)
581
582
583
584
585
586
587
588
589
590
591
		'-'# -> case lookAhead# buf 2# of
			   '}'# -> cont ITclose_prag (setCurrentPos# buf 3#)
			   _    -> lex_sym cont (incLexeme buf)
		_    -> lex_sym cont (incLexeme buf)

    '`'# | flag glaexts && lookAhead# buf 1# `eqChar#` '`'#
		-> lex_cstring cont (setCurrentPos# buf 2#)
	 | otherwise
	   	-> cont ITbackquote (incLexeme buf)

    '{'# ->	-- look for "{-##" special iface pragma
592
593
594
            case lookAhead# buf 1# of
           '|'# | flag glaexts 
                -> cont ITocurlybar (setCurrentPos# buf 2#)
595
596
	   '-'# -> case lookAhead# buf 2# of
		    '#'# -> case lookAhead# buf 3# of
597
				'#'# -> 
598
				   let (lexeme, buf') 
599
					  = doDiscard 0# (stepOnBy# (stepOverLexeme buf) 4#) in
600
                                            cont (ITpragma lexeme) buf'
601
				_ -> lex_prag cont (setCurrentPos# buf 3#)
602
603
	   	    _    -> cont ITocurly (incLexeme buf) 
	   _ -> (layoutOff `thenP_` cont ITocurly)  (incLexeme buf) 
604
605

    -- strings/characters -------------------------------------------------
606
    '\"'#{-"-} -> lex_string cont glaexts [] (incLexeme buf)
607
608
609
610
611
612
613
614
615
616
    '\''#      -> lex_char (char_end cont) glaexts (incLexeme buf)

    -- strictness and cpr pragmas and __scc treated specially.
    '_'# | flag glaexts ->
	 case lookAhead# buf 1# of
	   '_'# -> case lookAhead# buf 2# of
	   	    'S'# -> 
			lex_demand cont (stepOnUntil (not . isSpace) 
		                        (stepOnBy# buf 3#)) -- past __S
	   	    'M'# -> 
617
618
			cont ITcprinfo (stepOnBy# buf 3#)	-- past __M

619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
	   	    's'# -> 
			case prefixMatch (stepOnBy# buf 3#) "cc" of
		               Just buf' -> lex_scc cont (stepOverLexeme buf')
		     	       Nothing   -> lex_id cont glaexts buf
		    _ -> lex_id cont glaexts buf
	   _    -> lex_id cont glaexts buf

	-- Hexadecimal and octal constants
    '0'# | (ch `eqChar#` 'x'# || ch `eqChar#` 'X'#) && is_hexdigit ch2
		-> readNum (after_lexnum cont glaexts) buf' is_hexdigit 16 hex
	 | (ch `eqChar#` 'o'# || ch `eqChar#` 'O'#) && is_octdigit ch2
		-> readNum (after_lexnum cont glaexts) buf' is_octdigit  8 oct_or_dec
	where ch   = lookAhead# buf 1#
	      ch2  = lookAhead# buf 2#
	      buf' = setCurrentPos# buf 2#

    '\NUL'# ->
	    if bufferExhausted (stepOn buf) then
	       cont ITeof buf
	    else
	       trace "lexIface: misplaced NUL?" $ 
	       cont (ITunknown "\NUL") (stepOn buf)

642
    '?'# | flag glaexts && is_lower (lookAhead# buf 1#) ->
643
	    lex_ip cont (incLexeme buf)
644
645
    c | is_digit  c -> lex_num cont glaexts 0 buf
      | is_symbol c -> lex_sym cont buf
646
      | is_upper  c -> lex_con cont glaexts buf buf
647
      | is_ident  c -> lex_id  cont glaexts buf
648
      | otherwise   -> lexError "illegal character" buf
649
650
651
652
653
654
655
656
657
658
659
660
661

-- Int# is unlifted, and therefore faster than Bool for flags.
{-# INLINE flag #-}
flag :: Int# -> Bool
flag 0# = False
flag _  = True

-------------------------------------------------------------------------------
-- Pragmas

lex_prag cont buf
  = case expandWhile# is_space buf of { buf1 ->
    case expandWhile# is_ident (stepOverLexeme buf1) of { buf2 -> 
662
    let lexeme = mkFastString (map toUpper (lexemeToString buf2)) in
663
664
665
666
667
668
669
670
671
672
673
    case lookupUFM pragmaKeywordsFM lexeme of
	Just kw -> cont kw (mergeLexemes buf buf2)
	Nothing -> panic "lex_prag"
  }}

-------------------------------------------------------------------------------
-- Strings & Chars

lex_string cont glaexts s buf
  = case currentChar# buf of
	'"'#{-"-} -> 
674
675
676
	   let buf' = incLexeme buf
               s' = mkFastStringNarrow (map chr (reverse s)) 
           in case currentChar# buf' of
677
678
		'#'# | flag glaexts -> if all (<= 0xFF) s
                    then cont (ITprimstring s') (incLexeme buf')
679
                    else lexError "primitive string literal must contain only characters <= \'\\xFF\'" buf'
680
681
682
683
		_                   -> cont (ITstring s') buf'

	-- ignore \& in a string, deal with string gaps
	'\\'# | next_ch `eqChar#` '&'# 
684
		-> lex_string cont glaexts s buf'
685
	      | is_space next_ch
686
		-> lex_stringgap cont glaexts s (incLexeme buf)
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703

	    where next_ch = lookAhead# buf 1#
		  buf' = setCurrentPos# buf 2#

	_ -> lex_char (lex_next_string cont s) glaexts buf

lex_stringgap cont glaexts s buf
  = let buf' = incLexeme buf in
    case currentChar# buf of
	'\n'# -> \st@PState{loc = loc} -> lex_stringgap cont glaexts s buf' 
		  st{loc = incSrcLine loc}
	'\\'# -> lex_string cont glaexts s buf'
	c | is_space c -> lex_stringgap cont glaexts s buf'
	other -> charError buf'

lex_next_string cont s glaexts c buf = lex_string cont glaexts (c:s) buf

704
lex_char :: (Int# -> Int -> P a) -> Int# -> P a
705
706
707
lex_char cont glaexts buf
  = case currentChar# buf of
	'\\'# -> lex_escape (cont glaexts) (incLexeme buf)
708
	c | is_any c -> cont glaexts (I# (ord# c)) (incLexeme buf)
709
710
711
712
713
714
715
716
717
718
719
720
721
722
	other -> charError buf

char_end cont glaexts c buf
  = case currentChar# buf of
	'\''# -> let buf' = incLexeme buf in
		 case currentChar# buf' of
			'#'# | flag glaexts 
				-> cont (ITprimchar c) (incLexeme buf')
			_   	-> cont (ITchar c) buf'
	_     -> charError buf

lex_escape cont buf
  = let buf' = incLexeme buf in
    case currentChar# buf of
723
724
725
726
727
728
729
730
731
732
	'a'#	   -> cont (ord '\a') buf'
	'b'#	   -> cont (ord '\b') buf'
	'f'#	   -> cont (ord '\f') buf'
	'n'#	   -> cont (ord '\n') buf'
	'r'#	   -> cont (ord '\r') buf'
	't'#	   -> cont (ord '\t') buf'
	'v'#	   -> cont (ord '\v') buf'
	'\\'#      -> cont (ord '\\') buf'
	'"'#       -> cont (ord '\"') buf'
	'\''#      -> cont (ord '\'') buf'
733
734
	'^'#	   -> let c = currentChar# buf' in
		      if c `geChar#` '@'# && c `leChar#` '_'#
735
			then cont (I# (ord# c -# ord# '@'#)) (incLexeme buf')
736
737
738
739
740
741
742
743
744
			else charError buf'

	'x'#      -> readNum (after_charnum cont) buf' is_hexdigit 16 hex
	'o'#      -> readNum (after_charnum cont) buf' is_octdigit  8 oct_or_dec
	x | is_digit x 
		  -> readNum (after_charnum cont) buf is_digit    10 oct_or_dec

	_          -> case [ (c,buf2) | (p,c) <- silly_escape_chars,
				       Just buf2 <- [prefixMatch buf p] ] of
745
			    (c,buf2):_ -> cont (ord c) buf2
746
747
			    [] -> charError buf'

748
749
750
751
after_charnum cont i buf
  = if i >= 0 && i <= 0x10FFFF
	then cont (fromInteger i) buf
	else charError buf
752
753
754
755
756
757
758
759
760
761
762

readNum cont buf is_digit base conv = read buf 0
  where read buf i 
	  = case currentChar# buf of { c ->
	    if is_digit c
		then read (incLexeme buf) (i*base + (toInteger (I# (conv c))))
		else cont i buf
	    }

is_hexdigit c 
	=  is_digit c 
763
764
	|| (c `geChar#` 'a'# && c `leChar#` 'f'#)
	|| (c `geChar#` 'A'# && c `leChar#` 'F'#)
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833

hex c | is_digit c = ord# c -# ord# '0'#
      | otherwise  = ord# (to_lower c) -# ord# 'a'# +# 10#
oct_or_dec c = ord# c -# ord# '0'#

is_octdigit c = c `geChar#` '0'# && c `leChar#` '7'#

to_lower c 
  | c `geChar#` 'A'# && c `leChar#` 'Z'#  
	= chr# (ord# c -# (ord# 'A'# -# ord# 'a'#))
  | otherwise = c

charError buf = lexError "error in character literal" buf

silly_escape_chars = [
	("NUL", '\NUL'),
	("SOH", '\SOH'),
	("STX", '\STX'),
	("ETX", '\ETX'),
	("EOT", '\EOT'),
	("ENQ", '\ENQ'),
	("ACK", '\ACK'),
	("BEL", '\BEL'),
	("BS", '\BS'),
	("HT", '\HT'),
	("LF", '\LF'),
	("VT", '\VT'),
	("FF", '\FF'),
	("CR", '\CR'),
	("SO", '\SO'),
	("SI", '\SI'),
	("DLE", '\DLE'),
	("DC1", '\DC1'),
	("DC2", '\DC2'),
	("DC3", '\DC3'),
	("DC4", '\DC4'),
	("NAK", '\NAK'),
	("SYN", '\SYN'),
	("ETB", '\ETB'),
	("CAN", '\CAN'),
	("EM", '\EM'),
	("SUB", '\SUB'),
	("ESC", '\ESC'),
	("FS", '\FS'),
	("GS", '\GS'),
	("RS", '\RS'),
	("US", '\US'),
	("SP", '\SP'),
	("DEL", '\DEL')
	]

-------------------------------------------------------------------------------

lex_demand cont buf = 
 case read_em [] buf of { (ls,buf') -> 
 case currentChar# buf' of
   'B'# -> cont (ITstrict (ls, True )) (incLexeme buf')
   _    -> cont (ITstrict (ls, False)) buf'
 }
 where
   -- code snatched from Demand.lhs
  read_em acc buf = 
   case currentChar# buf of
    'L'# -> read_em (WwLazy False : acc) (stepOn buf)
    'A'# -> read_em (WwLazy True  : acc) (stepOn buf)
    'S'# -> read_em (WwStrict     : acc) (stepOn buf)
    'P'# -> read_em (WwPrim       : acc) (stepOn buf)
    'E'# -> read_em (WwEnum       : acc) (stepOn buf)
    ')'# -> (reverse acc, stepOn buf)
834
835
    'U'# -> do_unpack True  acc (stepOnBy# buf 2#)
    'u'# -> do_unpack False acc (stepOnBy# buf 2#)
836
837
    _    -> (reverse acc, buf)

838
  do_unpack wrapper_unpacks acc buf
839
   = case read_em [] buf of
840
      (stuff, rest) -> read_em (WwUnpack wrapper_unpacks stuff : acc) rest
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900


------------------
lex_scc cont buf =
 case currentChar# buf of
  'C'# -> cont ITsccAllCafs (incLexeme buf)
  other -> cont ITscc buf

-----------------------------------------------------------------------------
-- Numbers

lex_num :: (Token -> P a) -> Int# -> Integer -> P a
lex_num cont glaexts acc buf =
 case scanNumLit acc buf of
     (acc',buf') ->
       case currentChar# buf' of
         '.'# | is_digit (lookAhead# buf' 1#) ->
             -- this case is not optimised at all, as the
             -- presence of floating point numbers in interface
             -- files is not that common. (ToDo)
	    case expandWhile# is_digit (incLexeme buf') of
              buf2 -> -- points to first non digit char

		let l = case currentChar# buf2 of
			  'E'# -> do_exponent
		          'e'# -> do_exponent
		          _ -> buf2

		    do_exponent 
			= let buf3 = incLexeme buf2 in
			  case currentChar# buf3 of
				'-'# -> expandWhile# is_digit (incLexeme buf3)
				'+'# -> expandWhile# is_digit (incLexeme buf3)
				x | is_digit x -> expandWhile# is_digit buf3
				_ -> buf2

		    v = readRational__ (lexemeToString l)

		in case currentChar# l of -- glasgow exts only
		      '#'# | flag glaexts -> let l' = incLexeme l in
			      case currentChar# l' of
				'#'# -> cont (ITprimdouble v) (incLexeme l')
				_    -> cont (ITprimfloat  v) l'
		      _ -> cont (ITrational v) l

         _ -> after_lexnum cont glaexts acc' buf'
		
after_lexnum cont glaexts i buf
  = case currentChar# buf of
	'#'# | flag glaexts -> cont (ITprimint i) (incLexeme buf)
	_    -> cont (ITinteger i) buf

-----------------------------------------------------------------------------
-- C "literal literal"s  (i.e. things like ``NULL'', ``stdout'' etc.)

-- we lexemeToFastString on the bit between the ``''s, but include the
-- quotes in the full lexeme.

lex_cstring cont buf =
 case expandUntilMatch (stepOverLexeme buf) "\'\'" of
901
   Just buf' -> cont (ITlitlit (lexemeToFastString 
902
				(setCurrentPos# buf' (negateInt# 2#))))
903
904
           	   (mergeLexemes buf buf')
   Nothing   -> lexError "unterminated ``" buf
905
906
907
908

-----------------------------------------------------------------------------
-- identifiers, symbols etc.

909
910
911
912
913
lex_ip cont buf =
 case expandWhile# is_ident buf of
   buf' -> cont (ITipvarid lexeme) buf'
	   where lexeme = lexemeToFastString buf'

914
lex_id cont glaexts buf =
915
916
 let buf1 = expandWhile# is_ident buf in
 seq buf1 $
917
918
919
920
921
922
923

 case (if flag glaexts 
	then expandWhile# (eqChar# '#'#) buf1 -- slurp trailing hashes
	else buf1) 				of { buf' ->

 let lexeme  = lexemeToFastString buf' in

924
 case _scc_ "Lex.haskellKeyword" lookupUFM haskellKeywordsFM lexeme of {
925
926
927
928
 	Just kwd_token -> --trace ("hkeywd: "++_UNPK_(lexeme)) $
			  cont kwd_token buf';
 	Nothing        -> 

929
 let var_token = cont (ITvarid lexeme) buf' in
930
931
932
933
934
935
936
937
938

 if not (flag glaexts)
   then var_token
   else

 case lookupUFM ghcExtensionKeywordsFM lexeme of {
	Just kwd_token -> cont kwd_token buf';
	Nothing        -> var_token

939
 }}}
940
941

lex_sym cont buf =
942
 -- trace "lex_sym" $
943
944
945
946
947
948
949
950
951
952
 case expandWhile# is_symbol buf of
   buf' -> case lookupUFM haskellKeySymsFM lexeme of {
	 	Just kwd_token -> --trace ("keysym: "++unpackFS lexeme) $
				  cont kwd_token buf' ;
	 	Nothing        -> --trace ("sym: "++unpackFS lexeme) $
				  cont (mk_var_token lexeme) buf'
           }
   	where lexeme = lexemeToFastString buf'


953
954
955
956
957
958
-- lex_con recursively collects components of a qualified identifer.
-- The argument modbuf is the StringBuffer representing the lexeme
-- identified so far.  The buf argument is an empty StringBuffer pointing
-- to the next character to be examined.

lex_con cont glaexts modbuf buf =
959
 -- trace ("con: "{-++unpackFS lexeme-}) $
960
961
962
963
 case expandWhile# is_ident buf          of { buf1 ->
 case slurp_trailing_hashes buf1 glaexts of { buf' ->

 case currentChar# buf' of
964
965
     '.'# -> maybe_qualified cont glaexts modbuf' mod_lexeme 
		(incLexeme buf') just_a_conid
966
     _    -> just_a_conid
967
968
969
970
971
972
973
974
975
976
977
978
979
  where 
    mod_lexeme = lexemeToFastString modbuf'
    modbuf'    = mergeLexemes modbuf buf'

    just_a_conid
	| emptyLexeme modbuf = cont (ITconid mod_lexeme) buf'
	| otherwise 	     = cont (ITqconid (lexemeToFastString modbuf,
					       lexemeToFastString buf')) buf'
  }}


maybe_qualified cont glaexts modbuf mod buf just_a_conid =
 -- trace ("qid: "{-++unpackFS lexeme-}) $
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
 case currentChar# buf of
  '['# -> 	-- Special case for []
    case lookAhead# buf 1# of
     ']'# -> cont (ITqconid  (mod,SLIT("[]"))) (setCurrentPos# buf 2#)
     _    -> just_a_conid

  '('# ->  -- Special case for (,,,)
	   -- This *is* necessary to deal with e.g. "instance C PrelBase.(,,)"
    case lookAhead# buf 1# of
     '#'# | flag glaexts -> case lookAhead# buf 2# of
		','# -> lex_ubx_tuple cont mod (setCurrentPos# buf 3#) 
				just_a_conid
		_    -> just_a_conid
     ')'# -> cont (ITqconid (mod,SLIT("()"))) (setCurrentPos# buf 2#)
     ','# -> lex_tuple cont mod (setCurrentPos# buf 2#) just_a_conid
     _    -> just_a_conid

  '-'# -> case lookAhead# buf 1# of
998
            '>'# -> cont (ITqconid (mod,SLIT("(->)"))) (setCurrentPos# buf 2#)
999
1000
1001
1002
1003
1004
1005
1006
            _    -> lex_id3 cont glaexts modbuf mod buf just_a_conid

  _    -> lex_id3 cont glaexts modbuf mod buf just_a_conid


lex_id3 cont glaexts modbuf mod buf just_a_conid
  | is_upper (currentChar# buf) =
     lex_con cont glaexts modbuf (stepOverLexeme buf)
1007
1008
1009
1010
1011

  | is_symbol (currentChar# buf) =
     let 
	start_new_lexeme = stepOverLexeme buf
     in
1012
     -- trace ("lex_id31 "{-++unpackFS lexeme-}) $
1013
1014
1015
1016
1017
1018
     case expandWhile# is_symbol start_new_lexeme of { buf' ->
     let
       lexeme  = lexemeToFastString buf'
	-- real lexeme is M.<sym>
       new_buf = mergeLexemes buf buf'
     in
1019
1020
1021
     cont (mk_qvar_token mod lexeme) new_buf
	-- wrong, but arguably morally right: M... is now a qvarsym
     }
1022
1023
1024
1025
1026

  | otherwise   =
     let 
	start_new_lexeme = stepOverLexeme buf
     in
1027
     -- trace ("lex_id32 "{-++unpackFS lexeme-}) $
1028
1029
1030
1031
1032
1033
1034
1035
     case expandWhile# is_ident start_new_lexeme of { buf1 ->
     if emptyLexeme buf1 
    	    then just_a_conid
    	    else

     case slurp_trailing_hashes buf1 glaexts of { buf' ->

     let
1036
1037
      lexeme	  = lexemeToFastString buf'
      new_buf     = mergeLexemes buf buf'
1038
      is_a_qvarid = cont (mk_qvar_token mod lexeme) new_buf
1039
     in
1040
     case _scc_ "Lex.haskellKeyword" lookupUFM haskellKeywordsFM lexeme of {
1041
    	    Nothing          -> is_a_qvarid ;
1042

1043
1044
1045
1046
1047
    	    Just kwd_token | isSpecial kwd_token   -- special ids (as, qualified, hiding) shouldn't be
			   -> is_a_qvarid	   --  recognised as keywords here.
			   | otherwise
			   -> just_a_conid	   -- avoid M.where etc.
     }}}
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060

slurp_trailing_hashes buf glaexts
  | flag glaexts = expandWhile# (`eqChar#` '#'#) buf
  | otherwise    = buf


mk_var_token pk_str
  | is_upper f		= ITconid pk_str
  | is_ident f		= ITvarid pk_str
  | f `eqChar#` ':'#	= ITconsym pk_str
  | otherwise		= ITvarsym pk_str
  where
      (C# f) = _HEAD_ pk_str
1061
      -- tl     = _TAIL_ pk_str
1062
1063

mk_qvar_token m token =
1064
-- trace ("mk_qvar ") $ 
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
 case mk_var_token token of
   ITconid n  -> ITqconid  (m,n)
   ITvarid n  -> ITqvarid  (m,n)
   ITconsym n -> ITqconsym (m,n)
   ITvarsym n -> ITqvarsym (m,n)
   _	      -> ITunknown (show token)
\end{code}

----------------------------------------------------------------------------
Horrible stuff for dealing with M.(,,,)

\begin{code}
lex_tuple cont mod buf back_off =
  go 2 buf
  where
   go n buf =
    case currentChar# buf of
      ','# -> go (n+1) (stepOn buf)
1083
      ')'# -> cont (ITqconid (mod, snd (mkTupNameStr Boxed n))) (stepOn buf)
1084
1085
1086
1087
1088
1089
1090
1091
1092
      _    -> back_off

lex_ubx_tuple cont mod buf back_off =
  go 2 buf
  where
   go n buf =
    case currentChar# buf of
      ','# -> go (n+1) (stepOn buf)
      '#'# -> case lookAhead# buf 1# of
1093
		')'# -> cont (ITqconid (mod, snd (mkTupNameStr Unboxed n)))
1094
1095
1096
1097
1098
1099
				 (stepOnBy# buf 2#)
	        _    -> back_off
      _    -> back_off
\end{code}

-----------------------------------------------------------------------------
1100
doDiscard rips along really fast, looking for a '##-}', 
1101
1102
1103
1104
1105
indicating the end of the pragma we're skipping

\begin{code}
doDiscard inStr buf =
 case currentChar# buf of
1106
   '#'# | inStr ==# 0# ->
1107
1108
1109
1110
1111
1112
1113
       case lookAhead# buf 1# of { '#'# -> 
       case lookAhead# buf 2# of { '-'# ->
       case lookAhead# buf 3# of { '}'# -> 
	   (lexemeToBuffer buf, stepOverLexeme (setCurrentPos# buf 4#));
	_    -> doDiscard inStr (incLexeme buf) };
        _    -> doDiscard inStr (incLexeme buf) };
        _    -> doDiscard inStr (incLexeme buf) }
1114

1115
1116
1117
1118
1119
1120
   '"'# ->
       let
        odd_slashes buf flg i# =
          case lookAhead# buf i# of
	   '\\'# -> odd_slashes buf (not flg) (i# -# 1#)
	   _     -> flg
1121
1122

	not_inStr = if inStr ==# 0# then 1# else 0#
1123
1124
1125
       in
       case lookAhead# buf (negateInt# 1#) of --backwards, actually
	 '\\'# -> -- escaping something..
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
	   if odd_slashes buf True (negateInt# 2#) 
		then  -- odd number of slashes, " is escaped.
	      	      doDiscard inStr (incLexeme buf)
	        else  -- even number of slashes, \ is escaped.
	      	      doDiscard not_inStr (incLexeme buf)
         _ -> doDiscard not_inStr (incLexeme buf)

   '\''# | inStr ==# 0# ->
	case lookAhead# buf 1# of { '"'# ->
	case lookAhead# buf 2# of { '\''# ->
	   doDiscard inStr (setCurrentPos# buf 3#);
	_ -> doDiscard inStr (incLexeme buf) };
	_ -> doDiscard inStr (incLexeme buf) }

1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
   _ -> doDiscard inStr (incLexeme buf)

\end{code}

-----------------------------------------------------------------------------

\begin{code}
data LayoutContext
  = NoLayout
  | Layout Int#

data ParseResult a
  = POk PState a
  | PFailed Message

data PState = PState { 
	loc           :: SrcLoc,
	glasgow_exts  :: Int#,
	bol           :: Int#,
	atbol         :: Int#,
	context	      :: [LayoutContext]
     }

type P a = StringBuffer		-- Input string
	-> PState
	-> ParseResult a

returnP   :: a -> P a
returnP a buf s = POk s a

thenP	   :: P a -> (a -> P b) -> P b
m `thenP` k = \ buf s ->
	case m buf s of
		POk s1 a -> k a buf s1
		PFailed err  -> PFailed err

thenP_ 	   :: P a -> P b -> P b
m `thenP_` k = m `thenP` \_ -> k

mapP :: (a -> P b) -> [a] -> P [b]
mapP f [] = returnP []
mapP f (a:as) = 
     f a `thenP` \b ->
     mapP f as `thenP` \bs ->
     returnP (b:bs)

failP :: String -> P a
failP msg buf s = PFailed (text msg)

failMsgP :: Message -> P a
failMsgP msg buf s = PFailed msg

lexError :: String -> P a
lexError str buf s@PState{ loc = loc } 
  = failMsgP (hcat [ppr loc, text ": ", text str]) buf s

getSrcLocP :: P SrcLoc
getSrcLocP buf s@(PState{ loc = loc }) = POk s loc

1199
-- use a temporary SrcLoc for the duration of the argument
1200
setSrcLocP :: SrcLoc -> P a -> P a
1201
1202
setSrcLocP new_loc p buf s = 
  case p buf s{ loc=new_loc } of
1203
1204
1205
      POk _ a   -> POk s a
      PFailed e -> PFailed e
  
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
getSrcFile :: P FAST_STRING
getSrcFile buf s@(PState{ loc = loc }) = POk s (srcLocFile loc)

pushContext :: LayoutContext -> P ()
pushContext ctxt buf s@(PState{ context = ctx }) = POk s{context = ctxt:ctx} ()

{-

This special case in layoutOn is to handle layout contexts with are
indented the same or less than the current context.  This is illegal
according to the Haskell spec, so we have to arrange to close the
current context.  eg.

class Foo a where
class Bar a

after the first 'where', the sequence of events is:

	- layout system inserts a ';' (column 0)
	- parser begins a new context at column 0
	- parser shifts ';' (legal empty declaration)
	- parser sees 'class': parse error (we're still in the inner context)

trouble is, by the time we know we need a new context, the lexer has
already generated the ';'.  Hacky solution is as follows: since we
know the column of the next token (it's the column number of the new
context), we set the ACTUAL column number of the new context to this
numer plus one.  Hence the next time the lexer is called, a '}' will
be generated to close the new context straight away.  Furthermore, we
have to set the atbol flag so that the ';' that the parser shifted as
part of the new context is re-generated.

when the new context is *less* indented than the current one:

f = f where g = g where
h = h

	- current context: column 12.
	- on seeing 'h' (column 0), the layout system inserts '}'
	- parser starts a new context, column 0
	- parser sees '}', uses it to close new context
	- we still need to insert another '}' followed by a ';',
	  hence the atbol trick.

1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
There's also a special hack in here to deal with

	do
	   ....
	   e $ do
	   blah

i.e. the inner context is at the same indentation level as the outer
context.  This is strictly illegal according to Haskell 98, but
there's a lot of existing code using this style and it doesn't make
any sense to disallow it, since empty 'do' lists don't make sense.
1261
1262
-}

1263
1264
layoutOn :: Bool -> P ()
layoutOn strict buf s@(PState{ bol = bol, context = ctx }) =
1265
1266
    let offset = lexemeIndex buf -# bol in
    case ctx of
1267
1268
	Layout prev_off : _ 
	   | if strict then prev_off >=# offset else prev_off ># offset ->
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
		--trace ("layout on, column: " ++  show (I# offset)) $
		POk s{ context = Layout (offset +# 1#) : ctx, atbol = 1# } ()
	other -> 
		--trace ("layout on, column: " ++  show (I# offset)) $
    		POk s{ context = Layout offset : ctx } ()

layoutOff :: P ()
layoutOff buf s@(PState{ context = ctx }) =
    POk s{ context = NoLayout:ctx } ()

popContext :: P ()
1280
popContext = \ buf s@(PState{ context = ctx, loc = loc }) ->
1281
1282
  case ctx of
	(_:tl) -> POk s{ context = tl } ()
1283
	[]     -> PFailed (srcParseErr buf loc)
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324

{- 
 Note that if the name of the file we're processing ends
 with `hi-boot', we accept it on faith as having the right
 version. This is done so that .hi-boot files that comes
 with hsc don't have to be updated before every release,
 *and* it allows us to share .hi-boot files with versions
 of hsc that don't have .hi version checking (e.g., ghc-2.10's)

 If the version number is 0, the checking is also turned off.
 (needed to deal with GHC.hi only!)

 Once we can assume we're compiling with a version of ghc that
 supports interface file checking, we can drop the special
 pleading
-}
checkVersion :: Maybe Integer -> P ()
checkVersion mb@(Just v) buf s@(PState{loc = loc})
 | (v==0) || (v == fromInt opt_HiVersion) || opt_NoHiCheck = POk s ()
 | otherwise = PFailed (ifaceVersionErr mb loc ([]::[Token]){-Todo-})
checkVersion mb@Nothing  buf s@(PState{loc = loc})
 | "hi-boot" `isSuffixOf` (_UNPK_ (srcLocFile loc)) = POk s ()
 | otherwise = PFailed (ifaceVersionErr mb loc ([]::[Token]){-Todo-})

-----------------------------------------------------------------

ifaceParseErr :: StringBuffer -> SrcLoc -> Message
ifaceParseErr s l
  = hsep [ppr l, ptext SLIT("Interface file parse error; on input `"),
          text (lexemeToString s), char '\'']

ifaceVersionErr hi_vers l toks
  = hsep [ppr l, ptext SLIT("Interface file version error;"),
          ptext SLIT("Expected"), int opt_HiVersion, 
	  ptext SLIT("found "), pp_version]
    where
     pp_version =
      case hi_vers of
        Nothing -> ptext SLIT("pre ghc-3.02 version")
	Just v  -> ptext SLIT("version") <+> integer v

1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
-----------------------------------------------------------------------------

srcParseErr :: StringBuffer -> SrcLoc -> Message
srcParseErr s l
  = hcat [ppr l, 
	  if null token 
	     then ptext SLIT(": parse error (possibly incorrect indentation)")
	     else hcat [ptext SLIT(": parse error on input "),
          	  	char '`', text token, char '\'']
    ]
  where 
	token = lexemeToString s

1338
\end{code}