1 -----------------------------------------------------------------------------
2 -- $Id: GetImports.hs,v 1.1 2000/08/02 15:27:25 simonmar Exp $
4 -- Collect up the imports from a Haskell module. This is approximate: we don't
5 -- parse the module, but we do eliminate comments and strings.
7 -- (c) The GHC Team 2000
10 module GetImports (Import(..), getImports) where
13 import Char ( isAlphaNum )
16 = Normal String | Source String
19 getImports :: String -> [Import]
20 getImports = nub . gmiBase . clean
22 -- really get the imports from a de-litted, cpp'd, de-literal'd string
23 gmiBase :: String -> [Import]
27 f ("foreign" : "import" : ws) = f ws
28 f ("import" : "{-#" : "SOURCE" : "#-}" : "qualified" : m : ws)
29 = Source (takeWhile isModId m) : f ws
30 f ("import" : "{-#" : "SOURCE" : "#-}" : m : ws)
31 = Source (takeWhile isModId m) : f ws
32 f ("import" : "qualified" : m : ws)
33 = Normal (takeWhile isModId m) : f ws
35 = Normal (takeWhile isModId m) : f ws
39 isModId c = isAlphaNum c || c `elem` "'_"
41 -- remove literals and comments from a string
42 clean :: String -> String
46 -- running through text we want to keep
48 keep ('"':cs) = dquote cs
49 -- try to eliminate single quotes when they're part of
51 keep (c:'\'':cs) | isAlphaNum c || c == '_' = keep (dropWhile (=='\'') cs)
52 keep ('\'':cs) = squote cs
53 keep ('-':'-':cs) = linecomment cs
54 keep ('{':'-':'#':' ':cs) = "{-# " ++ keep cs
55 keep ('{':'-':cs) = runcomment cs
56 keep (c:cs) = c : keep cs
58 -- in a double-quoted string
60 dquote ('\\':'\"':cs) = dquote cs
61 dquote ('\\':'\\':cs) = dquote cs
62 dquote ('\"':cs) = keep cs
63 dquote (c:cs) = dquote cs
65 -- in a single-quoted string
67 squote ('\\':'\'':cs) = squote cs
68 squote ('\\':'\\':cs) = squote cs
69 squote ('\'':cs) = keep cs
70 squote (c:cs) = squote cs
74 linecomment ('\n':cs) = '\n':keep cs
75 linecomment (c:cs) = linecomment cs
77 -- in a running comment
79 runcomment ('-':'}':cs) = keep cs
80 runcomment (c:cs) = runcomment cs