d2cbd7f07c2cb987ec17ae17d52d65e6def6c65e
[ghc-hetmet.git] / compiler / basicTypes / SrcLoc.lhs
1 %
2 % (c) The University of Glasgow, 1992-2006
3 %
4
5 \begin{code}
6 -- | This module contains types that relate to the positions of things
7 -- in source files, and allow tagging of those things with locations
8 module SrcLoc (
9         -- * SrcLoc
10         SrcLoc,                 -- Abstract
11
12         -- ** Constructing SrcLoc
13         mkSrcLoc, mkGeneralSrcLoc,
14
15         noSrcLoc,               -- "I'm sorry, I haven't a clue"
16         generatedSrcLoc,        -- Code generated within the compiler
17         interactiveSrcLoc,      -- Code from an interactive session
18
19         advanceSrcLoc,
20
21         -- ** Unsafely deconstructing SrcLoc
22         -- These are dubious exports, because they crash on some inputs
23         srcLocFile,             -- return the file name part
24         srcLocLine,             -- return the line part
25         srcLocCol,              -- return the column part
26         
27         -- ** Misc. operations on SrcLoc
28         pprDefnLoc,
29         
30         -- ** Predicates on SrcLoc
31         isGoodSrcLoc,
32
33         -- * SrcSpan
34         SrcSpan,                -- Abstract
35
36         -- ** Constructing SrcSpan
37         mkGeneralSrcSpan, mkSrcSpan, 
38         noSrcSpan, 
39         wiredInSrcSpan,         -- Something wired into the compiler
40         srcLocSpan,
41         combineSrcSpans,
42         
43         -- ** Deconstructing SrcSpan
44         srcSpanStart, srcSpanEnd,
45         srcSpanFileName_maybe,
46
47         -- ** Unsafely deconstructing SrcSpan
48         -- These are dubious exports, because they crash on some inputs
49         srcSpanFile, 
50         srcSpanStartLine, srcSpanEndLine, 
51         srcSpanStartCol, srcSpanEndCol,
52
53         -- ** Predicates on SrcSpan
54         isGoodSrcSpan, isOneLineSpan,
55
56         -- * Located
57         Located(..), 
58         
59         -- ** Constructing Located
60         noLoc,
61         mkGeneralLocated,
62         
63         -- ** Deconstructing Located
64         getLoc, unLoc, 
65         
66         -- ** Combining and comparing Located values
67         eqLocated, cmpLocated, combineLocs, addCLoc,
68         leftmost_smallest, leftmost_largest, rightmost, 
69         spans, isSubspanOf
70     ) where
71
72 #include "Typeable.h"
73
74 import Util
75 import Outputable
76 import FastString
77
78 import Data.Bits
79 import Data.Data
80 \end{code}
81
82 %************************************************************************
83 %*                                                                      *
84 \subsection[SrcLoc-SrcLocations]{Source-location information}
85 %*                                                                      *
86 %************************************************************************
87
88 We keep information about the {\em definition} point for each entity;
89 this is the obvious stuff:
90 \begin{code}
91 -- | Represents a single point within a file
92 data SrcLoc
93   = SrcLoc      FastString      -- A precise location (file name)
94                 {-# UNPACK #-} !Int             -- line number, begins at 1
95                 {-# UNPACK #-} !Int             -- column number, begins at 1
96   | UnhelpfulLoc FastString     -- Just a general indication
97 \end{code}
98
99 %************************************************************************
100 %*                                                                      *
101 \subsection[SrcLoc-access-fns]{Access functions}
102 %*                                                                      *
103 %************************************************************************
104
105 \begin{code}
106 mkSrcLoc :: FastString -> Int -> Int -> SrcLoc
107 mkSrcLoc x line col = SrcLoc x line col
108
109 -- | Built-in "bad" 'SrcLoc' values for particular locations
110 noSrcLoc, generatedSrcLoc, interactiveSrcLoc :: SrcLoc
111 noSrcLoc          = UnhelpfulLoc (fsLit "<no location info>")
112 generatedSrcLoc   = UnhelpfulLoc (fsLit "<compiler-generated code>")
113 interactiveSrcLoc = UnhelpfulLoc (fsLit "<interactive session>")
114
115 -- | Creates a "bad" 'SrcLoc' that has no detailed information about its location
116 mkGeneralSrcLoc :: FastString -> SrcLoc
117 mkGeneralSrcLoc = UnhelpfulLoc 
118
119 -- | "Good" 'SrcLoc's have precise information about their location
120 isGoodSrcLoc :: SrcLoc -> Bool
121 isGoodSrcLoc (SrcLoc _ _ _) = True
122 isGoodSrcLoc _other         = False
123
124 -- | Gives the filename of the 'SrcLoc' if it is available, otherwise returns a dummy value
125 srcLocFile :: SrcLoc -> FastString
126 srcLocFile (SrcLoc fname _ _) = fname
127 srcLocFile _other             = (fsLit "<unknown file")
128
129 -- | Raises an error when used on a "bad" 'SrcLoc'
130 srcLocLine :: SrcLoc -> Int
131 srcLocLine (SrcLoc _ l _) = l
132 srcLocLine (UnhelpfulLoc s) = pprPanic "srcLocLine" (ftext s)
133
134 -- | Raises an error when used on a "bad" 'SrcLoc'
135 srcLocCol :: SrcLoc -> Int
136 srcLocCol (SrcLoc _ _ c) = c
137 srcLocCol (UnhelpfulLoc s) = pprPanic "srcLocCol" (ftext s)
138
139 -- | Move the 'SrcLoc' down by one line if the character is a newline,
140 -- to the next 8-char tabstop if it is a tab, and across by one
141 -- character in any other case
142 advanceSrcLoc :: SrcLoc -> Char -> SrcLoc
143 advanceSrcLoc (SrcLoc f l _) '\n' = SrcLoc f  (l + 1) 1
144 advanceSrcLoc (SrcLoc f l c) '\t' = SrcLoc f  l (((((c - 1) `shiftR` 3) + 1)
145                                                   `shiftL` 3) + 1)
146 advanceSrcLoc (SrcLoc f l c) _    = SrcLoc f  l (c + 1)
147 advanceSrcLoc loc            _    = loc -- Better than nothing
148 \end{code}
149
150 %************************************************************************
151 %*                                                                      *
152 \subsection[SrcLoc-instances]{Instance declarations for various names}
153 %*                                                                      *
154 %************************************************************************
155
156 \begin{code}
157 -- SrcLoc is an instance of Ord so that we can sort error messages easily
158 instance Eq SrcLoc where
159   loc1 == loc2 = case loc1 `cmpSrcLoc` loc2 of
160                    EQ     -> True
161                    _other -> False
162
163 instance Ord SrcLoc where
164   compare = cmpSrcLoc
165    
166 cmpSrcLoc :: SrcLoc -> SrcLoc -> Ordering
167 cmpSrcLoc (UnhelpfulLoc s1) (UnhelpfulLoc s2) = s1 `compare` s2
168 cmpSrcLoc (UnhelpfulLoc _)  (SrcLoc _ _ _)    = GT
169 cmpSrcLoc (SrcLoc _ _ _)    (UnhelpfulLoc _)  = LT
170
171 cmpSrcLoc (SrcLoc s1 l1 c1) (SrcLoc s2 l2 c2)      
172   = (s1 `compare` s2) `thenCmp` (l1 `compare` l2) `thenCmp` (c1 `compare` c2)
173
174 instance Outputable SrcLoc where
175     ppr (SrcLoc src_path src_line src_col)
176       = getPprStyle $ \ sty ->
177         if userStyle sty || debugStyle sty then
178             hcat [ pprFastFilePath src_path, char ':', 
179                    int src_line,
180                    char ':', int src_col
181                  ]
182         else
183             hcat [text "{-# LINE ", int src_line, space,
184                   char '\"', pprFastFilePath src_path, text " #-}"]
185
186     ppr (UnhelpfulLoc s)  = ftext s
187
188 instance Data SrcSpan where
189   -- don't traverse?
190   toConstr _   = abstractConstr "SrcSpan"
191   gunfold _ _  = error "gunfold"
192   dataTypeOf _ = mkNoRepType "SrcSpan"
193 \end{code}
194
195 %************************************************************************
196 %*                                                                      *
197 \subsection[SrcSpan]{Source Spans}
198 %*                                                                      *
199 %************************************************************************
200
201 \begin{code}
202 {- |
203 A SrcSpan delimits a portion of a text file.  It could be represented
204 by a pair of (line,column) coordinates, but in fact we optimise
205 slightly by using more compact representations for single-line and
206 zero-length spans, both of which are quite common.
207
208 The end position is defined to be the column /after/ the end of the
209 span.  That is, a span of (1,1)-(1,2) is one character long, and a
210 span of (1,1)-(1,1) is zero characters long.
211 -}
212 data SrcSpan
213   = SrcSpanOneLine              -- a common case: a single line
214         { srcSpanFile     :: !FastString,
215           srcSpanLine     :: {-# UNPACK #-} !Int,
216           srcSpanSCol     :: {-# UNPACK #-} !Int,
217           srcSpanECol     :: {-# UNPACK #-} !Int
218         }
219
220   | SrcSpanMultiLine
221         { srcSpanFile     :: !FastString,
222           srcSpanSLine    :: {-# UNPACK #-} !Int,
223           srcSpanSCol     :: {-# UNPACK #-} !Int,
224           srcSpanELine    :: {-# UNPACK #-} !Int,
225           srcSpanECol     :: {-# UNPACK #-} !Int
226         }
227
228   | SrcSpanPoint
229         { srcSpanFile     :: !FastString,
230           srcSpanLine     :: {-# UNPACK #-} !Int,
231           srcSpanCol      :: {-# UNPACK #-} !Int
232         }
233
234   | UnhelpfulSpan !FastString   -- Just a general indication
235                                 -- also used to indicate an empty span
236
237 #ifdef DEBUG
238   deriving (Eq, Typeable, Show) -- Show is used by Lexer.x, becuase we
239                                 -- derive Show for Token
240 #else
241   deriving (Eq, Typeable)
242 #endif
243
244 -- | Built-in "bad" 'SrcSpan's for common sources of location uncertainty
245 noSrcSpan, wiredInSrcSpan :: SrcSpan
246 noSrcSpan      = UnhelpfulSpan (fsLit "<no location info>")
247 wiredInSrcSpan = UnhelpfulSpan (fsLit "<wired into compiler>")
248
249 -- | Create a "bad" 'SrcSpan' that has not location information
250 mkGeneralSrcSpan :: FastString -> SrcSpan
251 mkGeneralSrcSpan = UnhelpfulSpan
252
253 -- | Create a 'SrcSpan' corresponding to a single point
254 srcLocSpan :: SrcLoc -> SrcSpan
255 srcLocSpan (UnhelpfulLoc str) = UnhelpfulSpan str
256 srcLocSpan (SrcLoc file line col) = SrcSpanPoint file line col
257
258 -- | Create a 'SrcSpan' between two points in a file
259 mkSrcSpan :: SrcLoc -> SrcLoc -> SrcSpan
260 mkSrcSpan (UnhelpfulLoc str) _ = UnhelpfulSpan str
261 mkSrcSpan _ (UnhelpfulLoc str) = UnhelpfulSpan str
262 mkSrcSpan loc1 loc2
263   | line1 == line2 = if col1 == col2
264                         then SrcSpanPoint file line1 col1
265                         else SrcSpanOneLine file line1 col1 col2
266   | otherwise      = SrcSpanMultiLine file line1 col1 line2 col2
267   where
268         line1 = srcLocLine loc1
269         line2 = srcLocLine loc2
270         col1 = srcLocCol loc1
271         col2 = srcLocCol loc2
272         file = srcLocFile loc1
273
274 -- | Combines two 'SrcSpan' into one that spans at least all the characters
275 -- within both spans. Assumes the "file" part is the same in both inputs
276 combineSrcSpans :: SrcSpan -> SrcSpan -> SrcSpan
277 combineSrcSpans (UnhelpfulSpan _) r = r -- this seems more useful
278 combineSrcSpans l (UnhelpfulSpan _) = l
279 combineSrcSpans span1 span2
280  = if line_start == line_end 
281    then if col_start == col_end
282         then SrcSpanPoint     file line_start col_start
283         else SrcSpanOneLine   file line_start col_start col_end
284    else      SrcSpanMultiLine file line_start col_start line_end col_end
285   where
286     (line_start, col_start) = min (srcSpanStartLine span1, srcSpanStartCol span1)
287                                   (srcSpanStartLine span2, srcSpanStartCol span2)
288     (line_end, col_end)     = max (srcSpanEndLine span1, srcSpanEndCol span1)
289                                   (srcSpanEndLine span2, srcSpanEndCol span2)
290     file = srcSpanFile span1
291 \end{code}
292
293 %************************************************************************
294 %*                                                                      *
295 \subsection[SrcSpan-predicates]{Predicates}
296 %*                                                                      *
297 %************************************************************************
298
299 \begin{code}
300 -- | Test if a 'SrcSpan' is "good", i.e. has precise location information
301 isGoodSrcSpan :: SrcSpan -> Bool
302 isGoodSrcSpan SrcSpanOneLine{} = True
303 isGoodSrcSpan SrcSpanMultiLine{} = True
304 isGoodSrcSpan SrcSpanPoint{} = True
305 isGoodSrcSpan _ = False
306
307 isOneLineSpan :: SrcSpan -> Bool
308 -- ^ True if the span is known to straddle only one line.
309 -- For "bad" 'SrcSpan', it returns False
310 isOneLineSpan s
311   | isGoodSrcSpan s = srcSpanStartLine s == srcSpanEndLine s
312   | otherwise       = False             
313
314 \end{code}
315
316 %************************************************************************
317 %*                                                                      *
318 \subsection[SrcSpan-unsafe-access-fns]{Unsafe access functions}
319 %*                                                                      *
320 %************************************************************************
321
322 \begin{code}
323
324 -- | Raises an error when used on a "bad" 'SrcSpan'
325 srcSpanStartLine :: SrcSpan -> Int
326 -- | Raises an error when used on a "bad" 'SrcSpan'
327 srcSpanEndLine :: SrcSpan -> Int
328 -- | Raises an error when used on a "bad" 'SrcSpan'
329 srcSpanStartCol :: SrcSpan -> Int
330 -- | Raises an error when used on a "bad" 'SrcSpan'
331 srcSpanEndCol :: SrcSpan -> Int
332
333 srcSpanStartLine SrcSpanOneLine{ srcSpanLine=l } = l
334 srcSpanStartLine SrcSpanMultiLine{ srcSpanSLine=l } = l
335 srcSpanStartLine SrcSpanPoint{ srcSpanLine=l } = l
336 srcSpanStartLine _ = panic "SrcLoc.srcSpanStartLine"
337
338 srcSpanEndLine SrcSpanOneLine{ srcSpanLine=l } = l
339 srcSpanEndLine SrcSpanMultiLine{ srcSpanELine=l } = l
340 srcSpanEndLine SrcSpanPoint{ srcSpanLine=l } = l
341 srcSpanEndLine _ = panic "SrcLoc.srcSpanEndLine"
342
343 srcSpanStartCol SrcSpanOneLine{ srcSpanSCol=l } = l
344 srcSpanStartCol SrcSpanMultiLine{ srcSpanSCol=l } = l
345 srcSpanStartCol SrcSpanPoint{ srcSpanCol=l } = l
346 srcSpanStartCol _ = panic "SrcLoc.srcSpanStartCol"
347
348 srcSpanEndCol SrcSpanOneLine{ srcSpanECol=c } = c
349 srcSpanEndCol SrcSpanMultiLine{ srcSpanECol=c } = c
350 srcSpanEndCol SrcSpanPoint{ srcSpanCol=c } = c
351 srcSpanEndCol _ = panic "SrcLoc.srcSpanEndCol"
352
353 \end{code}
354
355 %************************************************************************
356 %*                                                                      *
357 \subsection[SrcSpan-access-fns]{Access functions}
358 %*                                                                      *
359 %************************************************************************
360
361 \begin{code}
362
363 -- | Returns the location at the start of the 'SrcSpan' or a "bad" 'SrcSpan' if that is unavailable
364 srcSpanStart :: SrcSpan -> SrcLoc
365 -- | Returns the location at the end of the 'SrcSpan' or a "bad" 'SrcSpan' if that is unavailable
366 srcSpanEnd :: SrcSpan -> SrcLoc
367
368 srcSpanStart (UnhelpfulSpan str) = UnhelpfulLoc str
369 srcSpanStart s = mkSrcLoc (srcSpanFile s) 
370                           (srcSpanStartLine s)
371                           (srcSpanStartCol s)
372
373 srcSpanEnd (UnhelpfulSpan str) = UnhelpfulLoc str
374 srcSpanEnd s = 
375   mkSrcLoc (srcSpanFile s) 
376            (srcSpanEndLine s)
377            (srcSpanEndCol s)
378
379 -- | Obtains the filename for a 'SrcSpan' if it is "good"
380 srcSpanFileName_maybe :: SrcSpan -> Maybe FastString
381 srcSpanFileName_maybe (SrcSpanOneLine { srcSpanFile = nm })   = Just nm
382 srcSpanFileName_maybe (SrcSpanMultiLine { srcSpanFile = nm }) = Just nm
383 srcSpanFileName_maybe (SrcSpanPoint { srcSpanFile = nm})      = Just nm
384 srcSpanFileName_maybe _                                       = Nothing
385
386 \end{code}
387
388 %************************************************************************
389 %*                                                                      *
390 \subsection[SrcSpan-instances]{Instances}
391 %*                                                                      *
392 %************************************************************************
393
394 \begin{code}
395
396 -- We want to order SrcSpans first by the start point, then by the end point.
397 instance Ord SrcSpan where
398   a `compare` b = 
399      (srcSpanStart a `compare` srcSpanStart b) `thenCmp` 
400      (srcSpanEnd   a `compare` srcSpanEnd   b)
401
402
403 instance Outputable SrcSpan where
404     ppr span
405       = getPprStyle $ \ sty ->
406         if userStyle sty || debugStyle sty then
407            pprUserSpan True span
408         else
409            hcat [text "{-# LINE ", int (srcSpanStartLine span), space,
410                  char '\"', pprFastFilePath $ srcSpanFile span, text " #-}"]
411
412 pprUserSpan :: Bool -> SrcSpan -> SDoc
413 pprUserSpan show_path (SrcSpanOneLine src_path line start_col end_col)
414   = hcat [ ppWhen show_path (pprFastFilePath src_path <> colon)
415          , int line, char ':', int start_col
416          , ppUnless (end_col - start_col <= 1)
417                     (char '-' <> int (end_col-1)) 
418             -- For single-character or point spans, we just 
419             -- output the starting column number
420          ]
421           
422
423 pprUserSpan show_path (SrcSpanMultiLine src_path sline scol eline ecol)
424   = hcat [ ppWhen show_path (pprFastFilePath src_path <> colon)
425          , parens (int sline <> char ',' <>  int scol)
426          , char '-'
427          , parens (int eline <> char ',' <>  
428                    if ecol == 0 then int ecol else int (ecol-1))
429          ]
430
431 pprUserSpan show_path (SrcSpanPoint src_path line col)
432   = hcat [ ppWhen show_path $ (pprFastFilePath src_path <> colon)
433          , int line, char ':', int col ]
434
435 pprUserSpan _ (UnhelpfulSpan s)  = ftext s
436
437 pprDefnLoc :: SrcSpan -> SDoc
438 -- ^ Pretty prints information about the 'SrcSpan' in the style "defined at ..."
439 pprDefnLoc loc
440   | isGoodSrcSpan loc = ptext (sLit "Defined at") <+> ppr loc
441   | otherwise         = ppr loc
442 \end{code}
443
444 %************************************************************************
445 %*                                                                      *
446 \subsection[Located]{Attaching SrcSpans to things}
447 %*                                                                      *
448 %************************************************************************
449
450 \begin{code}
451 -- | We attach SrcSpans to lots of things, so let's have a datatype for it.
452 data Located e = L SrcSpan e
453   deriving (Eq, Ord, Typeable, Data)
454
455 unLoc :: Located e -> e
456 unLoc (L _ e) = e
457
458 getLoc :: Located e -> SrcSpan
459 getLoc (L l _) = l
460
461 noLoc :: e -> Located e
462 noLoc e = L noSrcSpan e
463
464 mkGeneralLocated :: String -> e -> Located e
465 mkGeneralLocated s e = L (mkGeneralSrcSpan (fsLit s)) e
466
467 combineLocs :: Located a -> Located b -> SrcSpan
468 combineLocs a b = combineSrcSpans (getLoc a) (getLoc b)
469
470 -- | Combine locations from two 'Located' things and add them to a third thing
471 addCLoc :: Located a -> Located b -> c -> Located c
472 addCLoc a b c = L (combineSrcSpans (getLoc a) (getLoc b)) c
473
474 -- not clear whether to add a general Eq instance, but this is useful sometimes:
475
476 -- | Tests whether the two located things are equal
477 eqLocated :: Eq a => Located a -> Located a -> Bool
478 eqLocated a b = unLoc a == unLoc b
479
480 -- not clear whether to add a general Ord instance, but this is useful sometimes:
481
482 -- | Tests the ordering of the two located things
483 cmpLocated :: Ord a => Located a -> Located a -> Ordering
484 cmpLocated a b = unLoc a `compare` unLoc b
485
486 instance Functor Located where
487   fmap f (L l e) = L l (f e)
488
489 instance Outputable e => Outputable (Located e) where
490   ppr (L l e) = ifPprDebug (braces (pprUserSpan False l)) $$ ppr e
491                 -- Print spans without the file name etc
492 \end{code}
493
494 %************************************************************************
495 %*                                                                      *
496 \subsection{Ordering SrcSpans for InteractiveUI}
497 %*                                                                      *
498 %************************************************************************
499
500 \begin{code}
501 -- | Alternative strategies for ordering 'SrcSpan's
502 leftmost_smallest, leftmost_largest, rightmost :: SrcSpan -> SrcSpan -> Ordering
503 rightmost            = flip compare
504 leftmost_smallest    = compare 
505 leftmost_largest a b = (srcSpanStart a `compare` srcSpanStart b)
506                                 `thenCmp`
507                        (srcSpanEnd b `compare` srcSpanEnd a)
508
509
510 -- | Determines whether a span encloses a given line and column index
511 spans :: SrcSpan -> (Int, Int) -> Bool
512 spans span (l,c) = srcSpanStart span <= loc && loc <= srcSpanEnd span
513    where loc = mkSrcLoc (srcSpanFile span) l c
514
515 -- | Determines whether a span is enclosed by another one
516 isSubspanOf :: SrcSpan -- ^ The span that may be enclosed by the other
517             -> SrcSpan -- ^ The span it may be enclosed by
518             -> Bool
519 isSubspanOf src parent 
520     | srcSpanFileName_maybe parent /= srcSpanFileName_maybe src = False
521     | otherwise = srcSpanStart parent <= srcSpanStart src &&
522                   srcSpanEnd parent   >= srcSpanEnd src
523
524 \end{code}