-
Notifications
You must be signed in to change notification settings - Fork 138
/
Interface.hs
333 lines (279 loc) · 12.4 KB
/
Interface.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -Wno-orphans #-}
{-# OPTIONS_GHC -Wwarn=deprecations #-}
{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}
{-# OPTIONS_GHC -Wno-x-partial #-}
module Language.Haskell.Liquid.GHC.Interface (
-- * Printer
pprintCBs
-- * predicates
-- , isExportedVar
-- , exportedVars
-- * Internal exports (provisional)
, extractSpecComments
, makeLogicMap
, classCons
, derivedVars
, importVars
, allImports
, qualifiedImports
, modSummaryHsFile
, makeFamInstEnv
, clearSpec
, checkFilePragmas
, lookupTyThing
, lookupTyThings
, availableTyThings
, updLiftedSpec
) where
import Prelude hiding (error)
import Liquid.GHC.API as Ghc hiding ( text
, (<+>)
, panic
, vcat
, showPpr
, mkStableModule
, Located
)
import qualified Liquid.GHC.API as Ghc
import Control.Exception
import Control.Monad
import Control.Monad.Trans.Maybe
import Data.List hiding (intersperse)
import Data.Maybe
import qualified Data.HashSet as S
import System.IO
import Text.Megaparsec.Error
import Text.PrettyPrint.HughesPJ hiding (first, (<>))
import Language.Fixpoint.Types hiding (err, panic, Error, Result, Expr)
import qualified Language.Fixpoint.Misc as Misc
import qualified Language.Haskell.Liquid.GHC.CoreToLogic as CoreToLogic
import Language.Haskell.Liquid.GHC.Misc
import Language.Haskell.Liquid.GHC.Types (MGIModGuts(..))
import Language.Haskell.Liquid.GHC.Play
import Language.Haskell.Liquid.WiredIn (isDerivedInstance)
import qualified Language.Haskell.Liquid.Measure as Ms
import Language.Haskell.Liquid.Parse
import Language.Haskell.Liquid.Types.Errors
import Language.Haskell.Liquid.Types.PrettyPrint
import Language.Haskell.Liquid.Types.Specs
import Language.Haskell.Liquid.Types.Types
import Language.Haskell.Liquid.Types.Visitors
import Language.Haskell.Liquid.UX.Config
import Language.Haskell.Liquid.UX.Tidy
--------------------------------------------------------------------------------
-- | Extract Ids ---------------------------------------------------------------
--------------------------------------------------------------------------------
classCons :: Maybe [ClsInst] -> [Id]
classCons Nothing = []
classCons (Just cs) = concatMap (dataConImplicitIds . head . tyConDataCons . classTyCon . is_cls) cs
derivedVars :: Config -> MGIModGuts -> [Var]
derivedVars cfg mg = concatMap (dFunIdVars cbs . is_dfun) derInsts
where
derInsts
| checkDer = insts
| otherwise = filter isDerivedInstance insts
insts = mgClsInstances mg
checkDer = checkDerived cfg
cbs = mgi_binds mg
mgClsInstances :: MGIModGuts -> [ClsInst]
mgClsInstances = fromMaybe [] . mgi_cls_inst
dFunIdVars :: CoreProgram -> DFunId -> [Id]
dFunIdVars cbs fd = notracepp msg $ concatMap bindersOf cbs' ++ deps
where
msg = "DERIVED-VARS-OF: " ++ showpp fd
cbs' = filter f cbs
f (NonRec x _) = eqFd x
f (Rec xes) = any eqFd (fst <$> xes)
eqFd x = varName x == varName fd
deps = concatMap unfoldDep unfolds
unfolds = realUnfoldingInfo . idInfo <$> concatMap bindersOf cbs'
unfoldDep :: Unfolding -> [Id]
unfoldDep (DFunUnfolding _ _ e) = concatMap exprDep e
unfoldDep CoreUnfolding {uf_tmpl = e} = exprDep e
unfoldDep _ = []
exprDep :: CoreExpr -> [Id]
exprDep = freeVars S.empty
importVars :: CoreProgram -> [Id]
importVars = freeVars S.empty
_definedVars :: CoreProgram -> [Id]
_definedVars = concatMap defs
where
defs (NonRec x _) = [x]
defs (Rec xes) = map fst xes
--------------------------------------------------------------------------------
-- | Per-Module Pipeline -------------------------------------------------------
--------------------------------------------------------------------------------
updLiftedSpec :: Ms.BareSpec -> Maybe Ms.BareSpec -> Ms.BareSpec
updLiftedSpec s1 Nothing = s1
updLiftedSpec s1 (Just s2) = clearSpec s1 `mappend` s2
clearSpec :: Ms.BareSpec -> Ms.BareSpec
clearSpec s = s { sigs = [], asmSigs = [], aliases = [], ealiases = [], qualifiers = [], dataDecls = [] }
allImports :: [LImportDecl GhcRn] -> S.HashSet Symbol
allImports imps = S.fromList (symbol . unLoc . ideclName . unLoc <$> imps)
qualifiedImports :: [LImportDecl GhcRn] -> QImports
qualifiedImports imps =
qImports [ (qn, n) | i <- imps
, let decl = unLoc i
, let m = unLoc (ideclName decl)
, qm <- maybeToList (unLoc <$> ideclAs decl)
, let [n,qn] = symbol <$> [m, qm]
]
qImports :: [(Symbol, Symbol)] -> QImports
qImports qns = QImports
{ qiNames = Misc.group qns
, qiModules = S.fromList (snd <$> qns)
}
---------------------------------------------------------------------------------------
-- | @lookupTyThings@ grabs all the @Name@s and associated @TyThing@ known to GHC
-- for this module; we will use this to create our name-resolution environment
-- (see `Bare.Resolve`)
---------------------------------------------------------------------------------------
lookupTyThings :: (GhcMonad m) => TcGblEnv -> m [(Name, Maybe TyThing)]
lookupTyThings tcGblEnv = zip names <$> mapM (lookupTyThing (Ghc.tcg_type_env tcGblEnv)) names
where
names = liftA2 (++)
(fmap Ghc.greName . Ghc.globalRdrEnvElts . tcg_rdr_env)
(fmap is_dfun_name . tcg_insts)
tcGblEnv
lookupTyThing :: (GhcMonad m) => Ghc.TypeEnv -> Name -> m (Maybe TyThing)
lookupTyThing tyEnv name = do
runMaybeT . msum . map MaybeT $
[ pure (lookupTypeEnv tyEnv name)
, lookupName name
]
availableTyThings :: (GhcMonad m) => TcGblEnv -> [AvailInfo] -> m [TyThing]
availableTyThings tcGblEnv avails =
fmap catMaybes $
mapM (lookupTyThing (Ghc.tcg_type_env tcGblEnv)) $
concatMap availNames avails
_dumpTypeEnv :: TypecheckedModule -> IO ()
_dumpTypeEnv tm = do
print ("DUMP-TYPE-ENV" :: String)
print (showpp <$> tcmTyThings tm)
tcmTyThings :: TypecheckedModule -> Maybe [Name]
tcmTyThings
=
-- typeEnvElts
-- . tcg_type_env . fst
-- . md_types . snd
-- . tm_internals_
modInfoTopLevelScope
. tm_checked_module_info
modSummaryHsFile :: ModSummary -> FilePath
modSummaryHsFile modSummary =
fromMaybe
(panic Nothing $
"modSummaryHsFile: missing .hs file for " ++
showPpr (ms_mod modSummary))
(ml_hs_file $ ms_location modSummary)
checkFilePragmas :: [Located String] -> IO ()
checkFilePragmas = Misc.applyNonNull (return ()) throw . mapMaybe err
where
err pragma
| check (val pragma) = Just (ErrFilePragma $ fSrcSpan pragma :: Error)
| otherwise = Nothing
check pragma = any (`isPrefixOf` pragma) bad
bad =
[ "-i", "--idirs"
, "-g", "--ghc-option"
, "--c-files", "--cfiles"
]
--------------------------------------------------------------------------------
-- | Family instance information
--------------------------------------------------------------------------------
makeFamInstEnv :: [FamInst] -> ([Ghc.TyCon], [(Symbol, DataCon)])
makeFamInstEnv famInsts =
let fiTcs = [ tc | FamInst { fi_flavor = DataFamilyInst tc } <- famInsts ]
fiDcs = [ (symbol d, d) | tc <- fiTcs, d <- tyConDataCons tc ]
in (fiTcs, fiDcs)
--------------------------------------------------------------------------------
-- | Extract Specifications from GHC -------------------------------------------
--------------------------------------------------------------------------------
extractSpecComments :: HsParsedModule -> [(Maybe RealSrcLoc, String)]
extractSpecComments = mapMaybe extractSpecComment . apiComments
-- | 'extractSpecComment' pulls out the specification part from a full comment
-- string, i.e. if the string is of the form:
-- 1. '{-@ S @-}' then it returns the substring 'S',
-- 2. '{-@ ... -}' then it throws a malformed SPECIFICATION ERROR, and
-- 3. Otherwise it is just treated as a plain comment so we return Nothing.
extractSpecComment :: Ghc.Located ApiComment -> Maybe (Maybe RealSrcLoc, String)
extractSpecComment (Ghc.L sp (ApiBlockComment txt))
| isPrefixOf "{-@" txt && isSuffixOf "@-}" txt -- valid specification
= Just (offsetPos, take (length txt - 6) $ drop 3 txt)
| isPrefixOf "{-@" txt -- invalid specification
= uError $ ErrParseAnn sp "A valid specification must have a closing '@-}'."
where
offsetPos = offsetRealSrcLoc . realSrcSpanStart <$> srcSpanToRealSrcSpan sp
offsetRealSrcLoc s =
mkRealSrcLoc (srcLocFile s) (srcLocLine s) (srcLocCol s + 3)
extractSpecComment _ = Nothing
--------------------------------------------------------------------------------
-- Assemble Information for Spec Extraction ------------------------------------
--------------------------------------------------------------------------------
makeLogicMap :: IO LogicMap
makeLogicMap = do
case parseSymbolToLogic "CoreToLogic.coreToLogic" CoreToLogic.coreToLogic of
Left peb -> do
hPutStrLn stderr (errorBundlePretty peb)
panic Nothing "makeLogicMap failed"
Right lm -> return (lm <> listLMap)
listLMap :: LogicMap -- TODO-REBARE: move to wiredIn
listLMap = toLogicMap [ (dummyLoc nilName , [] , hNil)
, (dummyLoc consName, [x, xs], hCons (EVar <$> [x, xs])) ]
where
x = "x"
xs = "xs"
hNil = mkEApp (dcSym Ghc.nilDataCon ) []
hCons = mkEApp (dcSym Ghc.consDataCon)
dcSym = dummyLoc . dropModuleUnique . symbol
--------------------------------------------------------------------------------
-- | Pretty Printing -----------------------------------------------------------
--------------------------------------------------------------------------------
instance PPrint TargetSpec where
pprintTidy k spec = vcat
[ "******* Target Variables ********************"
, pprintTidy k $ gsTgtVars (gsVars spec)
, "******* Type Signatures *********************"
, pprintLongList k (gsTySigs (gsSig spec))
, "******* Assumed Type Signatures *************"
, pprintLongList k (gsAsmSigs (gsSig spec))
, "******* DataCon Specifications (Measure) ****"
, pprintLongList k (gsCtors (gsData spec))
, "******* Measure Specifications **************"
, pprintLongList k (gsMeas (gsData spec)) ]
instance PPrint TargetInfo where
pprintTidy k info = vcat
[ -- "*************** Imports *********************"
-- , intersperse comma $ text <$> imports info
-- , "*************** Includes ********************"
-- , intersperse comma $ text <$> includes info
"*************** Imported Variables **********"
, pprDoc $ _giImpVars (fromTargetSrc $ giSrc info)
, "*************** Defined Variables ***********"
, pprDoc $ _giDefVars (fromTargetSrc $ giSrc info)
, "*************** Specification ***************"
, pprintTidy k $ giSpec info
, "*************** Core Bindings ***************"
, pprintCBs $ _giCbs (fromTargetSrc $ giSrc info) ]
pprintCBs :: [CoreBind] -> Doc
pprintCBs = pprDoc . tidyCBs
-- To print verbosely
-- = text . O.showSDocDebug unsafeGlobalDynFlags . O.ppr . tidyCBs
instance Show TargetInfo where
show = showpp
------------------------------------------------------------------------
-- Dealing with Errors ---------------------------------------------------
------------------------------------------------------------------------
instance Result SourceError where
result e = Crash ((, Nothing) <$> sourceErrors "" e) "Invalid Source"