1{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}
2
3{-
4Forked from GHC v8.10.1 to work around the readFile side effect in mkHiefile
5
6Main functions for .hie file generation
7-}
8{- HLINT ignore -}
9{-# LANGUAGE OverloadedStrings #-}
10{-# LANGUAGE FlexibleInstances #-}
11{-# LANGUAGE UndecidableInstances #-}
12{-# LANGUAGE FlexibleContexts #-}
13{-# LANGUAGE TypeSynonymInstances #-}
14{-# LANGUAGE ScopedTypeVariables #-}
15{-# LANGUAGE TypeFamilies #-}
16{-# LANGUAGE TypeApplications #-}
17{-# LANGUAGE AllowAmbiguousTypes #-}
18{-# LANGUAGE ViewPatterns #-}
19{-# LANGUAGE DeriveDataTypeable #-}
20module Compat.HieAst ( enrichHie ) where
21
22import GhcPrelude
23
24import Avail                      ( Avails )
25import Bag                        ( Bag, bagToList )
26import BasicTypes
27import BooleanFormula
28import Class                      ( FunDep )
29import CoreUtils                  ( exprType )
30import ConLike                    ( conLikeName )
31import Desugar                    ( deSugarExpr )
32import FieldLabel
33import GHC.Hs
34import HscTypes
35import Module                     ( ModuleName )
36import MonadUtils                 ( concatMapM, liftIO )
37import Name                       ( Name, nameSrcSpan )
38import NameEnv                    ( NameEnv, emptyNameEnv, extendNameEnv, lookupNameEnv )
39import SrcLoc
40import TcHsSyn                    ( hsLitType, hsPatType )
41import Type                       ( mkVisFunTys, Type )
42import TysWiredIn                 ( mkListTy, mkSumTy )
43import Var                        ( Id, Var, setVarName, varName, varType )
44import Panic
45
46import HieTypes
47import HieUtils
48
49import qualified Data.Map as M
50import qualified Data.Set as S
51import Data.Data                  ( Data, Typeable )
52import Data.List                  ( foldl1' )
53import Data.Maybe                 ( listToMaybe )
54import Control.Monad.Trans.Reader
55import Control.Monad.Trans.Class  ( lift )
56
57{- Note [Updating HieAst for changes in the GHC AST]
58
59When updating the code in this file for changes in the GHC AST, you
60need to pay attention to the following things:
61
621) Symbols (Names/Vars/Modules) in the following categories:
63
64   a) Symbols that appear in the source file that directly correspond to
65   something the user typed
66   b) Symbols that don't appear in the source, but should be in some sense
67   "visible" to a user, particularly via IDE tooling or the like. This
68   includes things like the names introduced by RecordWildcards (We record
69   all the names introduced by a (..) in HIE files), and will include implicit
70   parameters and evidence variables after one of my pending MRs lands.
71
722) Subtrees that may contain such symbols, or correspond to a SrcSpan in
73   the file. This includes all `Located` things
74
75For 1), you need to call `toHie` for one of the following instances
76
77instance ToHie (Context (Located Name)) where ...
78instance ToHie (Context (Located Var)) where ...
79instance ToHie (IEContext (Located ModuleName)) where ...
80
81`Context` is a data type that looks like:
82
83data Context a = C ContextInfo a -- Used for names and bindings
84
85`ContextInfo` is defined in `HieTypes`, and looks like
86
87data ContextInfo
88  = Use                -- ^ regular variable
89  | MatchBind
90  | IEThing IEType     -- ^ import/export
91  | TyDecl
92  -- | Value binding
93  | ValBind
94      BindType     -- ^ whether or not the binding is in an instance
95      Scope        -- ^ scope over which the value is bound
96      (Maybe Span) -- ^ span of entire binding
97  ...
98
99It is used to annotate symbols in the .hie files with some extra information on
100the context in which they occur and should be fairly self explanatory. You need
101to select one that looks appropriate for the symbol usage. In very rare cases,
102you might need to extend this sum type if none of the cases seem appropriate.
103
104So, given a `Located Name` that is just being "used", and not defined at a
105particular location, you would do the following:
106
107   toHie $ C Use located_name
108
109If you select one that corresponds to a binding site, you will need to
110provide a `Scope` and a `Span` for your binding. Both of these are basically
111`SrcSpans`.
112
113The `SrcSpan` in the `Scope` is supposed to span over the part of the source
114where the symbol can be legally allowed to occur. For more details on how to
115calculate this, see Note [Capturing Scopes and other non local information]
116in HieAst.
117
118The binding `Span` is supposed to be the span of the entire binding for
119the name.
120
121For a function definition `foo`:
122
123foo x = x + y
124  where y = x^2
125
126The binding `Span` is the span of the entire function definition from `foo x`
127to `x^2`.  For a class definition, this is the span of the entire class, and
128so on.  If this isn't well defined for your bit of syntax (like a variable
129bound by a lambda), then you can just supply a `Nothing`
130
131There is a test that checks that all symbols in the resulting HIE file
132occur inside their stated `Scope`. This can be turned on by passing the
133-fvalidate-ide-info flag to ghc along with -fwrite-ide-info to generate the
134.hie file.
135
136You may also want to provide a test in testsuite/test/hiefile that includes
137a file containing your new construction, and tests that the calculated scope
138is valid (by using -fvalidate-ide-info)
139
140For subtrees in the AST that may contain symbols, the procedure is fairly
141straightforward.  If you are extending the GHC AST, you will need to provide a
142`ToHie` instance for any new types you may have introduced in the AST.
143
144Here are is an extract from the `ToHie` instance for (LHsExpr (GhcPass p)):
145
146  toHie e@(L mspan oexpr) = concatM $ getTypeNode e : case oexpr of
147      HsVar _ (L _ var) ->
148        [ toHie $ C Use (L mspan var)
149             -- Patch up var location since typechecker removes it
150        ]
151      HsConLikeOut _ con ->
152        [ toHie $ C Use $ L mspan $ conLikeName con
153        ]
154      ...
155      HsApp _ a b ->
156        [ toHie a
157        , toHie b
158        ]
159
160If your subtree is `Located` or has a `SrcSpan` available, the output list
161should contain a HieAst `Node` corresponding to the subtree. You can use
162either `makeNode` or `getTypeNode` for this purpose, depending on whether it
163makes sense to assign a `Type` to the subtree. After this, you just need
164to concatenate the result of calling `toHie` on all subexpressions and
165appropriately annotated symbols contained in the subtree.
166
167The code above from the ToHie instance of `LhsExpr (GhcPass p)` is supposed
168to work for both the renamed and typechecked source. `getTypeNode` is from
169the `HasType` class defined in this file, and it has different instances
170for `GhcTc` and `GhcRn` that allow it to access the type of the expression
171when given a typechecked AST:
172
173class Data a => HasType a where
174  getTypeNode :: a -> HieM [HieAST Type]
175instance HasType (LHsExpr GhcTc) where
176  getTypeNode e@(L spn e') = ... -- Actually get the type for this expression
177instance HasType (LHsExpr GhcRn) where
178  getTypeNode (L spn e) = makeNode e spn -- Fallback to a regular `makeNode` without recording the type
179
180If your subtree doesn't have a span available, you can omit the `makeNode`
181call and just recurse directly in to the subexpressions.
182
183-}
184
185-- These synonyms match those defined in main/GHC.hs
186type RenamedSource     = ( HsGroup GhcRn, [LImportDecl GhcRn]
187                         , Maybe [(LIE GhcRn, Avails)]
188                         , Maybe LHsDocString )
189type TypecheckedSource = LHsBinds GhcTc
190
191
192{- Note [Name Remapping]
193The Typechecker introduces new names for mono names in AbsBinds.
194We don't care about the distinction between mono and poly bindings,
195so we replace all occurrences of the mono name with the poly name.
196-}
197newtype HieState = HieState
198  { name_remapping :: NameEnv Id
199  }
200
201initState :: HieState
202initState = HieState emptyNameEnv
203
204class ModifyState a where -- See Note [Name Remapping]
205  addSubstitution :: a -> a -> HieState -> HieState
206
207instance ModifyState Name where
208  addSubstitution _ _ hs = hs
209
210instance ModifyState Id where
211  addSubstitution mono poly hs =
212    hs{name_remapping = extendNameEnv (name_remapping hs) (varName mono) poly}
213
214modifyState :: ModifyState (IdP p) => [ABExport p] -> HieState -> HieState
215modifyState = foldr go id
216  where
217    go ABE{abe_poly=poly,abe_mono=mono} f = addSubstitution mono poly . f
218    go _ f = f
219
220type HieM = ReaderT HieState Hsc
221
222enrichHie :: TypecheckedSource -> RenamedSource -> Hsc (HieASTs Type)
223enrichHie ts (hsGrp, imports, exports, _) = flip runReaderT initState $ do
224    tasts <- toHie $ fmap (BC RegularBind ModuleScope) ts
225    rasts <- processGrp hsGrp
226    imps <- toHie $ filter (not . ideclImplicit . unLoc) imports
227    exps <- toHie $ fmap (map $ IEC Export . fst) exports
228    let spanFile children = case children of
229          [] -> mkRealSrcSpan (mkRealSrcLoc "" 1 1) (mkRealSrcLoc "" 1 1)
230          _ -> mkRealSrcSpan (realSrcSpanStart $ nodeSpan $ head children)
231                             (realSrcSpanEnd   $ nodeSpan $ last children)
232
233        modulify xs =
234          Node (simpleNodeInfo "Module" "Module") (spanFile xs) xs
235
236        asts = HieASTs
237          $ resolveTyVarScopes
238          $ M.map (modulify . mergeSortAsts)
239          $ M.fromListWith (++)
240          $ map (\x -> (srcSpanFile (nodeSpan x),[x])) flat_asts
241
242        flat_asts = concat
243          [ tasts
244          , rasts
245          , imps
246          , exps
247          ]
248    return asts
249  where
250    processGrp grp = concatM
251      [ toHie $ fmap (RS ModuleScope ) hs_valds grp
252      , toHie $ hs_splcds grp
253      , toHie $ hs_tyclds grp
254      , toHie $ hs_derivds grp
255      , toHie $ hs_fixds grp
256      , toHie $ hs_defds grp
257      , toHie $ hs_fords grp
258      , toHie $ hs_warnds grp
259      , toHie $ hs_annds grp
260      , toHie $ hs_ruleds grp
261      ]
262
263getRealSpan :: SrcSpan -> Maybe Span
264getRealSpan (RealSrcSpan sp) = Just sp
265getRealSpan _ = Nothing
266
267grhss_span :: GRHSs p body -> SrcSpan
268grhss_span (GRHSs _ xs bs) = foldl' combineSrcSpans (getLoc bs) (map getLoc xs)
269grhss_span (XGRHSs _) = panic "XGRHS has no span"
270
271bindingsOnly :: [Context Name] -> [HieAST a]
272bindingsOnly [] = []
273bindingsOnly (C c n : xs) = case nameSrcSpan n of
274  RealSrcSpan span -> Node nodeinfo span [] : bindingsOnly xs
275    where nodeinfo = NodeInfo S.empty [] (M.singleton (Right n) info)
276          info = mempty{identInfo = S.singleton c}
277  _ -> bindingsOnly xs
278
279concatM :: Monad m => [m [a]] -> m [a]
280concatM xs = concat <$> sequence xs
281
282{- Note [Capturing Scopes and other non local information]
283toHie is a local tranformation, but scopes of bindings cannot be known locally,
284hence we have to push the relevant info down into the binding nodes.
285We use the following types (*Context and *Scoped) to wrap things and
286carry the required info
287(Maybe Span) always carries the span of the entire binding, including rhs
288-}
289data Context a = C ContextInfo a -- Used for names and bindings
290
291data RContext a = RC RecFieldContext a
292data RFContext a = RFC RecFieldContext (Maybe Span) a
293-- ^ context for record fields
294
295data IEContext a = IEC IEType a
296-- ^ context for imports/exports
297
298data BindContext a = BC BindType Scope a
299-- ^ context for imports/exports
300
301data PatSynFieldContext a = PSC (Maybe Span) a
302-- ^ context for pattern synonym fields.
303
304data SigContext a = SC SigInfo a
305-- ^ context for type signatures
306
307data SigInfo = SI SigType (Maybe Span)
308
309data SigType = BindSig | ClassSig | InstSig
310
311data RScoped a = RS Scope a
312-- ^ Scope spans over everything to the right of a, (mostly) not
313-- including a itself
314-- (Includes a in a few special cases like recursive do bindings) or
315-- let/where bindings
316
317-- | Pattern scope
318data PScoped a = PS (Maybe Span)
319                    Scope       -- ^ use site of the pattern
320                    Scope       -- ^ pattern to the right of a, not including a
321                    a
322  deriving (Typeable, Data) -- Pattern Scope
323
324{- Note [TyVar Scopes]
325Due to -XScopedTypeVariables, type variables can be in scope quite far from
326their original binding. We resolve the scope of these type variables
327in a separate pass
328-}
329data TScoped a = TS TyVarScope a -- TyVarScope
330
331data TVScoped a = TVS TyVarScope Scope a -- TyVarScope
332-- ^ First scope remains constant
333-- Second scope is used to build up the scope of a tyvar over
334-- things to its right, ala RScoped
335
336-- | Each element scopes over the elements to the right
337listScopes :: Scope -> [Located a] -> [RScoped (Located a)]
338listScopes _ [] = []
339listScopes rhsScope [pat] = [RS rhsScope pat]
340listScopes rhsScope (pat : pats) = RS sc pat : pats'
341  where
342    pats'@((RS scope p):_) = listScopes rhsScope pats
343    sc = combineScopes scope $ mkScope $ getLoc p
344
345-- | 'listScopes' specialised to 'PScoped' things
346patScopes
347  :: Maybe Span
348  -> Scope
349  -> Scope
350  -> [LPat (GhcPass p)]
351  -> [PScoped (LPat (GhcPass p))]
352patScopes rsp useScope patScope xs =
353  map (\(RS sc a) -> PS rsp useScope sc (composeSrcSpan a)) $
354    listScopes patScope (map dL xs)
355
356-- | 'listScopes' specialised to 'TVScoped' things
357tvScopes
358  :: TyVarScope
359  -> Scope
360  -> [LHsTyVarBndr a]
361  -> [TVScoped (LHsTyVarBndr a)]
362tvScopes tvScope rhsScope xs =
363  map (\(RS sc a)-> TVS tvScope sc a) $ listScopes rhsScope xs
364
365{- Note [Scoping Rules for SigPat]
366Explicitly quantified variables in pattern type signatures are not
367brought into scope in the rhs, but implicitly quantified variables
368are (HsWC and HsIB).
369This is unlike other signatures, where explicitly quantified variables
370are brought into the RHS Scope
371For example
372foo :: forall a. ...;
373foo = ... -- a is in scope here
374
375bar (x :: forall a. a -> a) = ... -- a is not in scope here
376--   ^ a is in scope here (pattern body)
377
378bax (x :: a) = ... -- a is in scope here
379Because of HsWC and HsIB pass on their scope to their children
380we must wrap the LHsType in pattern signatures in a
381Shielded explictly, so that the HsWC/HsIB scope is not passed
382on the the LHsType
383-}
384
385data Shielded a = SH Scope a -- Ignores its TScope, uses its own scope instead
386
387type family ProtectedSig a where
388  ProtectedSig GhcRn = HsWildCardBndrs GhcRn (HsImplicitBndrs
389                                                GhcRn
390                                                (Shielded (LHsType GhcRn)))
391  ProtectedSig GhcTc = NoExtField
392
393class ProtectSig a where
394  protectSig :: Scope -> LHsSigWcType (NoGhcTc a) -> ProtectedSig a
395
396instance (HasLoc a) => HasLoc (Shielded a) where
397  loc (SH _ a) = loc a
398
399instance (ToHie (TScoped a)) => ToHie (TScoped (Shielded a)) where
400  toHie (TS _ (SH sc a)) = toHie (TS (ResolvedScopes [sc]) a)
401
402instance ProtectSig GhcTc where
403  protectSig _ _ = noExtField
404
405instance ProtectSig GhcRn where
406  protectSig sc (HsWC a (HsIB b sig)) =
407    HsWC a (HsIB b (SH sc sig))
408  protectSig _ (HsWC _ (XHsImplicitBndrs nec)) = noExtCon nec
409  protectSig _ (XHsWildCardBndrs nec) = noExtCon nec
410
411class HasLoc a where
412  -- ^ defined so that HsImplicitBndrs and HsWildCardBndrs can
413  -- know what their implicit bindings are scoping over
414  loc :: a -> SrcSpan
415
416instance HasLoc thing => HasLoc (TScoped thing) where
417  loc (TS _ a) = loc a
418
419instance HasLoc thing => HasLoc (PScoped thing) where
420  loc (PS _ _ _ a) = loc a
421
422instance HasLoc (LHsQTyVars GhcRn) where
423  loc (HsQTvs _ vs) = loc vs
424  loc _ = noSrcSpan
425
426instance HasLoc thing => HasLoc (HsImplicitBndrs a thing) where
427  loc (HsIB _ a) = loc a
428  loc _ = noSrcSpan
429
430instance HasLoc thing => HasLoc (HsWildCardBndrs a thing) where
431  loc (HsWC _ a) = loc a
432  loc _ = noSrcSpan
433
434instance HasLoc (Located a) where
435  loc (L l _) = l
436
437instance HasLoc a => HasLoc [a] where
438  loc [] = noSrcSpan
439  loc xs = foldl1' combineSrcSpans $ map loc xs
440
441instance HasLoc a => HasLoc (FamEqn s a) where
442  loc (FamEqn _ a Nothing b _ c) = foldl1' combineSrcSpans [loc a, loc b, loc c]
443  loc (FamEqn _ a (Just tvs) b _ c) = foldl1' combineSrcSpans
444                                              [loc a, loc tvs, loc b, loc c]
445  loc _ = noSrcSpan
446instance (HasLoc tm, HasLoc ty) => HasLoc (HsArg tm ty) where
447  loc (HsValArg tm) = loc tm
448  loc (HsTypeArg _ ty) = loc ty
449  loc (HsArgPar sp)  = sp
450
451instance HasLoc (HsDataDefn GhcRn) where
452  loc def@(HsDataDefn{}) = loc $ dd_cons def
453    -- Only used for data family instances, so we only need rhs
454    -- Most probably the rest will be unhelpful anyway
455  loc _ = noSrcSpan
456
457{- Note [Real DataCon Name]
458The typechecker subtitutes the conLikeWrapId for the name, but we don't want
459this showing up in the hieFile, so we replace the name in the Id with the
460original datacon name
461See also Note [Data Constructor Naming]
462-}
463class HasRealDataConName p where
464  getRealDataCon :: XRecordCon p -> Located (IdP p) -> Located (IdP p)
465
466instance HasRealDataConName GhcRn where
467  getRealDataCon _ n = n
468instance HasRealDataConName GhcTc where
469  getRealDataCon RecordConTc{rcon_con_like = con} (L sp var) =
470    L sp (setVarName var (conLikeName con))
471
472-- | The main worker class
473-- See Note [Updating HieAst for changes in the GHC AST] for more information
474-- on how to add/modify instances for this.
475class ToHie a where
476  toHie :: a -> HieM [HieAST Type]
477
478-- | Used to collect type info
479class Data a => HasType a where
480  getTypeNode :: a -> HieM [HieAST Type]
481
482instance (ToHie a) => ToHie [a] where
483  toHie = concatMapM toHie
484
485instance (ToHie a) => ToHie (Bag a) where
486  toHie = toHie . bagToList
487
488instance (ToHie a) => ToHie (Maybe a) where
489  toHie = maybe (pure []) toHie
490
491instance ToHie (Context (Located NoExtField)) where
492  toHie _ = pure []
493
494instance ToHie (TScoped NoExtField) where
495  toHie _ = pure []
496
497instance ToHie (IEContext (Located ModuleName)) where
498  toHie (IEC c (L (RealSrcSpan span) mname)) =
499      pure $ [Node (NodeInfo S.empty [] idents) span []]
500    where details = mempty{identInfo = S.singleton (IEThing c)}
501          idents = M.singleton (Left mname) details
502  toHie _ = pure []
503
504instance ToHie (Context (Located Var)) where
505  toHie c = case c of
506      C context (L (RealSrcSpan span) name')
507        -> do
508        m <- asks name_remapping
509        let name = case lookupNameEnv m (varName name') of
510              Just var -> var
511              Nothing-> name'
512        pure
513          [Node
514            (NodeInfo S.empty [] $
515              M.singleton (Right $ varName name)
516                          (IdentifierDetails (Just $ varType name')
517                                             (S.singleton context)))
518            span
519            []]
520      _ -> pure []
521
522instance ToHie (Context (Located Name)) where
523  toHie c = case c of
524      C context (L (RealSrcSpan span) name') -> do
525        m <- asks name_remapping
526        let name = case lookupNameEnv m name' of
527              Just var -> varName var
528              Nothing -> name'
529        pure
530          [Node
531            (NodeInfo S.empty [] $
532              M.singleton (Right name)
533                          (IdentifierDetails Nothing
534                                             (S.singleton context)))
535            span
536            []]
537      _ -> pure []
538
539-- | Dummy instances - never called
540instance ToHie (TScoped (LHsSigWcType GhcTc)) where
541  toHie _ = pure []
542instance ToHie (TScoped (LHsWcType GhcTc)) where
543  toHie _ = pure []
544instance ToHie (SigContext (LSig GhcTc)) where
545  toHie _ = pure []
546instance ToHie (TScoped Type) where
547  toHie _ = pure []
548
549instance HasType (LHsBind GhcRn) where
550  getTypeNode (L spn bind) = makeNode bind spn
551
552instance HasType (LHsBind GhcTc) where
553  getTypeNode (L spn bind) = case bind of
554      FunBind{fun_id = name} -> makeTypeNode bind spn (varType $ unLoc name)
555      _ -> makeNode bind spn
556
557instance HasType (Located (Pat GhcRn)) where
558  getTypeNode (dL -> L spn pat) = makeNode pat spn
559
560instance HasType (Located (Pat GhcTc)) where
561  getTypeNode (dL -> L spn opat) = makeTypeNode opat spn (hsPatType opat)
562
563instance HasType (LHsExpr GhcRn) where
564  getTypeNode (L spn e) = makeNode e spn
565
566-- | This instance tries to construct 'HieAST' nodes which include the type of
567-- the expression. It is not yet possible to do this efficiently for all
568-- expression forms, so we skip filling in the type for those inputs.
569--
570-- 'HsApp', for example, doesn't have any type information available directly on
571-- the node. Our next recourse would be to desugar it into a 'CoreExpr' then
572-- query the type of that. Yet both the desugaring call and the type query both
573-- involve recursive calls to the function and argument! This is particularly
574-- problematic when you realize that the HIE traversal will eventually visit
575-- those nodes too and ask for their types again.
576--
577-- Since the above is quite costly, we just skip cases where computing the
578-- expression's type is going to be expensive.
579--
580-- See #16233
581instance HasType (LHsExpr GhcTc) where
582  getTypeNode e@(L spn e') = lift $
583    -- Some expression forms have their type immediately available
584    let tyOpt = case e' of
585          HsLit _ l -> Just (hsLitType l)
586          HsOverLit _ o -> Just (overLitType o)
587
588          HsLam     _ (MG { mg_ext = groupTy }) -> Just (matchGroupType groupTy)
589          HsLamCase _ (MG { mg_ext = groupTy }) -> Just (matchGroupType groupTy)
590          HsCase _  _ (MG { mg_ext = groupTy }) -> Just (mg_res_ty groupTy)
591
592          ExplicitList  ty _ _   -> Just (mkListTy ty)
593          ExplicitSum   ty _ _ _ -> Just (mkSumTy ty)
594          HsDo          ty _ _   -> Just ty
595          HsMultiIf     ty _     -> Just ty
596
597          _ -> Nothing
598
599    in
600    case tyOpt of
601      Just t -> makeTypeNode e' spn t
602      Nothing
603        | skipDesugaring e' -> fallback
604        | otherwise -> do
605            hs_env <- Hsc $ \e w -> return (e,w)
606            (_,mbe) <- liftIO $ deSugarExpr hs_env e
607            maybe fallback (makeTypeNode e' spn . exprType) mbe
608    where
609      fallback = makeNode e' spn
610
611      matchGroupType :: MatchGroupTc -> Type
612      matchGroupType (MatchGroupTc args res) = mkVisFunTys args res
613
614      -- | Skip desugaring of these expressions for performance reasons.
615      --
616      -- See impact on Haddock output (esp. missing type annotations or links)
617      -- before marking more things here as 'False'. See impact on Haddock
618      -- performance before marking more things as 'True'.
619      skipDesugaring :: HsExpr a -> Bool
620      skipDesugaring e = case e of
621        HsVar{}        -> False
622        HsUnboundVar{} -> False
623        HsConLikeOut{} -> False
624        HsRecFld{}     -> False
625        HsOverLabel{}  -> False
626        HsIPVar{}      -> False
627        HsWrap{}       -> False
628        _              -> True
629
630instance ( ToHie (Context (Located (IdP a)))
631         , ToHie (MatchGroup a (LHsExpr a))
632         , ToHie (PScoped (LPat a))
633         , ToHie (GRHSs a (LHsExpr a))
634         , ToHie (LHsExpr a)
635         , ToHie (Located (PatSynBind a a))
636         , HasType (LHsBind a)
637         , ModifyState (IdP a)
638         , Data (HsBind a)
639         ) => ToHie (BindContext (LHsBind a)) where
640  toHie (BC context scope b@(L span bind)) =
641    concatM $ getTypeNode b : case bind of
642      FunBind{fun_id = name, fun_matches = matches} ->
643        [ toHie $ C (ValBind context scope $ getRealSpan span) name
644        , toHie matches
645        ]
646      PatBind{pat_lhs = lhs, pat_rhs = rhs} ->
647        [ toHie $ PS (getRealSpan span) scope NoScope lhs
648        , toHie rhs
649        ]
650      VarBind{var_rhs = expr} ->
651        [ toHie expr
652        ]
653      AbsBinds{abs_exports = xs, abs_binds = binds} ->
654        [ local (modifyState xs) $ -- Note [Name Remapping]
655            toHie $ fmap (BC context scope) binds
656        ]
657      PatSynBind _ psb ->
658        [ toHie $ L span psb -- PatSynBinds only occur at the top level
659        ]
660      XHsBindsLR _ -> []
661
662instance ( ToHie (LMatch a body)
663         ) => ToHie (MatchGroup a body) where
664  toHie mg = concatM $ case mg of
665    MG{ mg_alts = (L span alts) , mg_origin = FromSource } ->
666      [ pure $ locOnly span
667      , toHie alts
668      ]
669    MG{} -> []
670    XMatchGroup _ -> []
671
672instance ( ToHie (Context (Located (IdP a)))
673         , ToHie (PScoped (LPat a))
674         , ToHie (HsPatSynDir a)
675         ) => ToHie (Located (PatSynBind a a)) where
676    toHie (L sp psb) = concatM $ case psb of
677      PSB{psb_id=var, psb_args=dets, psb_def=pat, psb_dir=dir} ->
678        [ toHie $ C (Decl PatSynDec $ getRealSpan sp) var
679        , toHie $ toBind dets
680        , toHie $ PS Nothing lhsScope NoScope pat
681        , toHie dir
682        ]
683        where
684          lhsScope = combineScopes varScope detScope
685          varScope = mkLScope var
686          detScope = case dets of
687            (PrefixCon args) -> foldr combineScopes NoScope $ map mkLScope args
688            (InfixCon a b) -> combineScopes (mkLScope a) (mkLScope b)
689            (RecCon r) -> foldr go NoScope r
690          go (RecordPatSynField a b) c = combineScopes c
691            $ combineScopes (mkLScope a) (mkLScope b)
692          detSpan = case detScope of
693            LocalScope a -> Just a
694            _ -> Nothing
695          toBind (PrefixCon args) = PrefixCon $ map (C Use) args
696          toBind (InfixCon a b) = InfixCon (C Use a) (C Use b)
697          toBind (RecCon r) = RecCon $ map (PSC detSpan) r
698      XPatSynBind _ -> []
699
700instance ( ToHie (MatchGroup a (LHsExpr a))
701         ) => ToHie (HsPatSynDir a) where
702  toHie dir = case dir of
703    ExplicitBidirectional mg -> toHie mg
704    _ -> pure []
705
706instance ( a ~ GhcPass p
707         , ToHie body
708         , ToHie (HsMatchContext (NameOrRdrName (IdP a)))
709         , ToHie (PScoped (LPat a))
710         , ToHie (GRHSs a body)
711         , Data (Match a body)
712         ) => ToHie (LMatch (GhcPass p) body) where
713  toHie (L span m ) = concatM $ makeNode m span : case m of
714    Match{m_ctxt=mctx, m_pats = pats, m_grhss =  grhss } ->
715      [ toHie mctx
716      , let rhsScope = mkScope $ grhss_span grhss
717          in toHie $ patScopes Nothing rhsScope NoScope pats
718      , toHie grhss
719      ]
720    XMatch _ -> []
721
722instance ( ToHie (Context (Located a))
723         ) => ToHie (HsMatchContext a) where
724  toHie (FunRhs{mc_fun=name}) = toHie $ C MatchBind name
725  toHie (StmtCtxt a) = toHie a
726  toHie _ = pure []
727
728instance ( ToHie (HsMatchContext a)
729         ) => ToHie (HsStmtContext a) where
730  toHie (PatGuard a) = toHie a
731  toHie (ParStmtCtxt a) = toHie a
732  toHie (TransStmtCtxt a) = toHie a
733  toHie _ = pure []
734
735instance ( a ~ GhcPass p
736         , ToHie (Context (Located (IdP a)))
737         , ToHie (RContext (HsRecFields a (PScoped (LPat a))))
738         , ToHie (LHsExpr a)
739         , ToHie (TScoped (LHsSigWcType a))
740         , ProtectSig a
741         , ToHie (TScoped (ProtectedSig a))
742         , HasType (LPat a)
743         , Data (HsSplice a)
744         ) => ToHie (PScoped (Located (Pat (GhcPass p)))) where
745  toHie (PS rsp scope pscope lpat@(dL -> L ospan opat)) =
746    concatM $ getTypeNode lpat : case opat of
747      WildPat _ ->
748        []
749      VarPat _ lname ->
750        [ toHie $ C (PatternBind scope pscope rsp) lname
751        ]
752      LazyPat _ p ->
753        [ toHie $ PS rsp scope pscope p
754        ]
755      AsPat _ lname pat ->
756        [ toHie $ C (PatternBind scope
757                                 (combineScopes (mkLScope (dL pat)) pscope)
758                                 rsp)
759                    lname
760        , toHie $ PS rsp scope pscope pat
761        ]
762      ParPat _ pat ->
763        [ toHie $ PS rsp scope pscope pat
764        ]
765      BangPat _ pat ->
766        [ toHie $ PS rsp scope pscope pat
767        ]
768      ListPat _ pats ->
769        [ toHie $ patScopes rsp scope pscope pats
770        ]
771      TuplePat _ pats _ ->
772        [ toHie $ patScopes rsp scope pscope pats
773        ]
774      SumPat _ pat _ _ ->
775        [ toHie $ PS rsp scope pscope pat
776        ]
777      ConPatIn c dets ->
778        [ toHie $ C Use c
779        , toHie $ contextify dets
780        ]
781      ConPatOut {pat_con = con, pat_args = dets}->
782        [ toHie $ C Use $ fmap conLikeName con
783        , toHie $ contextify dets
784        ]
785      ViewPat _ expr pat ->
786        [ toHie expr
787        , toHie $ PS rsp scope pscope pat
788        ]
789      SplicePat _ sp ->
790        [ toHie $ L ospan sp
791        ]
792      LitPat _ _ ->
793        []
794      NPat _ _ _ _ ->
795        []
796      NPlusKPat _ n _ _ _ _ ->
797        [ toHie $ C (PatternBind scope pscope rsp) n
798        ]
799      SigPat _ pat sig ->
800        [ toHie $ PS rsp scope pscope pat
801        , let cscope = mkLScope (dL pat) in
802            toHie $ TS (ResolvedScopes [cscope, scope, pscope])
803                       (protectSig @a cscope sig)
804              -- See Note [Scoping Rules for SigPat]
805        ]
806      CoPat _ _ _ _ ->
807        []
808      XPat _ -> []
809    where
810      contextify (PrefixCon args) = PrefixCon $ patScopes rsp scope pscope args
811      contextify (InfixCon a b) = InfixCon a' b'
812        where [a', b'] = patScopes rsp scope pscope [a,b]
813      contextify (RecCon r) = RecCon $ RC RecFieldMatch $ contextify_rec r
814      contextify_rec (HsRecFields fds a) = HsRecFields (map go scoped_fds) a
815        where
816          go (RS fscope (L spn (HsRecField lbl pat pun))) =
817            L spn $ HsRecField lbl (PS rsp scope fscope pat) pun
818          scoped_fds = listScopes pscope fds
819
820instance ( ToHie body
821         , ToHie (LGRHS a body)
822         , ToHie (RScoped (LHsLocalBinds a))
823         ) => ToHie (GRHSs a body) where
824  toHie grhs = concatM $ case grhs of
825    GRHSs _ grhss binds ->
826     [ toHie grhss
827     , toHie $ RS (mkScope $ grhss_span grhs) binds
828     ]
829    XGRHSs _ -> []
830
831instance ( ToHie (Located body)
832         , ToHie (RScoped (GuardLStmt a))
833         , Data (GRHS a (Located body))
834         ) => ToHie (LGRHS a (Located body)) where
835  toHie (L span g) = concatM $ makeNode g span : case g of
836    GRHS _ guards body ->
837      [ toHie $ listScopes (mkLScope body) guards
838      , toHie body
839      ]
840    XGRHS _ -> []
841
842instance ( a ~ GhcPass p
843         , ToHie (Context (Located (IdP a)))
844         , HasType (LHsExpr a)
845         , ToHie (PScoped (LPat a))
846         , ToHie (MatchGroup a (LHsExpr a))
847         , ToHie (LGRHS a (LHsExpr a))
848         , ToHie (RContext (HsRecordBinds a))
849         , ToHie (RFContext (Located (AmbiguousFieldOcc a)))
850         , ToHie (ArithSeqInfo a)
851         , ToHie (LHsCmdTop a)
852         , ToHie (RScoped (GuardLStmt a))
853         , ToHie (RScoped (LHsLocalBinds a))
854         , ToHie (TScoped (LHsWcType (NoGhcTc a)))
855         , ToHie (TScoped (LHsSigWcType (NoGhcTc a)))
856         , Data (HsExpr a)
857         , Data (HsSplice a)
858         , Data (HsTupArg a)
859         , Data (AmbiguousFieldOcc a)
860         , (HasRealDataConName a)
861         ) => ToHie (LHsExpr (GhcPass p)) where
862  toHie e@(L mspan oexpr) = concatM $ getTypeNode e : case oexpr of
863      HsVar _ (L _ var) ->
864        [ toHie $ C Use (L mspan var)
865             -- Patch up var location since typechecker removes it
866        ]
867      HsUnboundVar _ _ ->
868        []
869      HsConLikeOut _ con ->
870        [ toHie $ C Use $ L mspan $ conLikeName con
871        ]
872      HsRecFld _ fld ->
873        [ toHie $ RFC RecFieldOcc Nothing (L mspan fld)
874        ]
875      HsOverLabel _ _ _ -> []
876      HsIPVar _ _ -> []
877      HsOverLit _ _ -> []
878      HsLit _ _ -> []
879      HsLam _ mg ->
880        [ toHie mg
881        ]
882      HsLamCase _ mg ->
883        [ toHie mg
884        ]
885      HsApp _ a b ->
886        [ toHie a
887        , toHie b
888        ]
889      HsAppType _ expr sig ->
890        [ toHie expr
891        , toHie $ TS (ResolvedScopes []) sig
892        ]
893      OpApp _ a b c ->
894        [ toHie a
895        , toHie b
896        , toHie c
897        ]
898      NegApp _ a _ ->
899        [ toHie a
900        ]
901      HsPar _ a ->
902        [ toHie a
903        ]
904      SectionL _ a b ->
905        [ toHie a
906        , toHie b
907        ]
908      SectionR _ a b ->
909        [ toHie a
910        , toHie b
911        ]
912      ExplicitTuple _ args _ ->
913        [ toHie args
914        ]
915      ExplicitSum _ _ _ expr ->
916        [ toHie expr
917        ]
918      HsCase _ expr matches ->
919        [ toHie expr
920        , toHie matches
921        ]
922      HsIf _ _ a b c ->
923        [ toHie a
924        , toHie b
925        , toHie c
926        ]
927      HsMultiIf _ grhss ->
928        [ toHie grhss
929        ]
930      HsLet _ binds expr ->
931        [ toHie $ RS (mkLScope expr) binds
932        , toHie expr
933        ]
934      HsDo _ _ (L ispan stmts) ->
935        [ pure $ locOnly ispan
936        , toHie $ listScopes NoScope stmts
937        ]
938      ExplicitList _ _ exprs ->
939        [ toHie exprs
940        ]
941      RecordCon {rcon_ext = mrealcon, rcon_con_name = name, rcon_flds = binds} ->
942        [ toHie $ C Use (getRealDataCon @a mrealcon name)
943            -- See Note [Real DataCon Name]
944        , toHie $ RC RecFieldAssign $ binds
945        ]
946      RecordUpd {rupd_expr = expr, rupd_flds = upds}->
947        [ toHie expr
948        , toHie $ map (RC RecFieldAssign) upds
949        ]
950      ExprWithTySig _ expr sig ->
951        [ toHie expr
952        , toHie $ TS (ResolvedScopes [mkLScope expr]) sig
953        ]
954      ArithSeq _ _ info ->
955        [ toHie info
956        ]
957      HsSCC _ _ _ expr ->
958        [ toHie expr
959        ]
960      HsCoreAnn _ _ _ expr ->
961        [ toHie expr
962        ]
963      HsProc _ pat cmdtop ->
964        [ toHie $ PS Nothing (mkLScope cmdtop) NoScope pat
965        , toHie cmdtop
966        ]
967      HsStatic _ expr ->
968        [ toHie expr
969        ]
970      HsTick _ _ expr ->
971        [ toHie expr
972        ]
973      HsBinTick _ _ _ expr ->
974        [ toHie expr
975        ]
976      HsTickPragma _ _ _ _ expr ->
977        [ toHie expr
978        ]
979      HsWrap _ _ a ->
980        [ toHie $ L mspan a
981        ]
982      HsBracket _ b ->
983        [ toHie b
984        ]
985      HsRnBracketOut _ b p ->
986        [ toHie b
987        , toHie p
988        ]
989      HsTcBracketOut _ b p ->
990        [ toHie b
991        , toHie p
992        ]
993      HsSpliceE _ x ->
994        [ toHie $ L mspan x
995        ]
996      XExpr _ -> []
997
998instance ( a ~ GhcPass p
999         , ToHie (LHsExpr a)
1000         , Data (HsTupArg a)
1001         ) => ToHie (LHsTupArg (GhcPass p)) where
1002  toHie (L span arg) = concatM $ makeNode arg span : case arg of
1003    Present _ expr ->
1004      [ toHie expr
1005      ]
1006    Missing _ -> []
1007    XTupArg _ -> []
1008
1009instance ( a ~ GhcPass p
1010         , ToHie (PScoped (LPat a))
1011         , ToHie (LHsExpr a)
1012         , ToHie (SigContext (LSig a))
1013         , ToHie (RScoped (LHsLocalBinds a))
1014         , ToHie (RScoped (ApplicativeArg a))
1015         , ToHie (Located body)
1016         , Data (StmtLR a a (Located body))
1017         , Data (StmtLR a a (Located (HsExpr a)))
1018         ) => ToHie (RScoped (LStmt (GhcPass p) (Located body))) where
1019  toHie (RS scope (L span stmt)) = concatM $ makeNode stmt span : case stmt of
1020      LastStmt _ body _ _ ->
1021        [ toHie body
1022        ]
1023      BindStmt _ pat body _ _ ->
1024        [ toHie $ PS (getRealSpan $ getLoc body) scope NoScope pat
1025        , toHie body
1026        ]
1027      ApplicativeStmt _ stmts _ ->
1028        [ concatMapM (toHie . RS scope . snd) stmts
1029        ]
1030      BodyStmt _ body _ _ ->
1031        [ toHie body
1032        ]
1033      LetStmt _ binds ->
1034        [ toHie $ RS scope binds
1035        ]
1036      ParStmt _ parstmts _ _ ->
1037        [ concatMapM (\(ParStmtBlock _ stmts _ _) ->
1038                          toHie $ listScopes NoScope stmts)
1039                     parstmts
1040        ]
1041      TransStmt {trS_stmts = stmts, trS_using = using, trS_by = by} ->
1042        [ toHie $ listScopes scope stmts
1043        , toHie using
1044        , toHie by
1045        ]
1046      RecStmt {recS_stmts = stmts} ->
1047        [ toHie $ map (RS $ combineScopes scope (mkScope span)) stmts
1048        ]
1049      XStmtLR _ -> []
1050
1051instance ( ToHie (LHsExpr a)
1052         , ToHie (PScoped (LPat a))
1053         , ToHie (BindContext (LHsBind a))
1054         , ToHie (SigContext (LSig a))
1055         , ToHie (RScoped (HsValBindsLR a a))
1056         , Data (HsLocalBinds a)
1057         ) => ToHie (RScoped (LHsLocalBinds a)) where
1058  toHie (RS scope (L sp binds)) = concatM $ makeNode binds sp : case binds of
1059      EmptyLocalBinds _ -> []
1060      HsIPBinds _ _ -> []
1061      HsValBinds _ valBinds ->
1062        [ toHie $ RS (combineScopes scope $ mkScope sp)
1063                      valBinds
1064        ]
1065      XHsLocalBindsLR _ -> []
1066
1067instance ( ToHie (BindContext (LHsBind a))
1068         , ToHie (SigContext (LSig a))
1069         , ToHie (RScoped (XXValBindsLR a a))
1070         ) => ToHie (RScoped (HsValBindsLR a a)) where
1071  toHie (RS sc v) = concatM $ case v of
1072    ValBinds _ binds sigs ->
1073      [ toHie $ fmap (BC RegularBind sc) binds
1074      , toHie $ fmap (SC (SI BindSig Nothing)) sigs
1075      ]
1076    XValBindsLR x -> [ toHie $ RS sc x ]
1077
1078instance ToHie (RScoped (NHsValBindsLR GhcTc)) where
1079  toHie (RS sc (NValBinds binds sigs)) = concatM $
1080    [ toHie (concatMap (map (BC RegularBind sc) . bagToList . snd) binds)
1081    , toHie $ fmap (SC (SI BindSig Nothing)) sigs
1082    ]
1083instance ToHie (RScoped (NHsValBindsLR GhcRn)) where
1084  toHie (RS sc (NValBinds binds sigs)) = concatM $
1085    [ toHie (concatMap (map (BC RegularBind sc) . bagToList . snd) binds)
1086    , toHie $ fmap (SC (SI BindSig Nothing)) sigs
1087    ]
1088
1089instance ( ToHie (RContext (LHsRecField a arg))
1090         ) => ToHie (RContext (HsRecFields a arg)) where
1091  toHie (RC c (HsRecFields fields _)) = toHie $ map (RC c) fields
1092
1093instance ( ToHie (RFContext (Located label))
1094         , ToHie arg
1095         , HasLoc arg
1096         , Data label
1097         , Data arg
1098         ) => ToHie (RContext (LHsRecField' label arg)) where
1099  toHie (RC c (L span recfld)) = concatM $ makeNode recfld span : case recfld of
1100    HsRecField label expr _ ->
1101      [ toHie $ RFC c (getRealSpan $ loc expr) label
1102      , toHie expr
1103      ]
1104
1105instance ToHie (RFContext (LFieldOcc GhcRn)) where
1106  toHie (RFC c rhs (L nspan f)) = concatM $ case f of
1107    FieldOcc name _ ->
1108      [ toHie $ C (RecField c rhs) (L nspan name)
1109      ]
1110    XFieldOcc _ -> []
1111
1112instance ToHie (RFContext (LFieldOcc GhcTc)) where
1113  toHie (RFC c rhs (L nspan f)) = concatM $ case f of
1114    FieldOcc var _ ->
1115      let var' = setVarName var (varName var)
1116      in [ toHie $ C (RecField c rhs) (L nspan var')
1117         ]
1118    XFieldOcc _ -> []
1119
1120instance ToHie (RFContext (Located (AmbiguousFieldOcc GhcRn))) where
1121  toHie (RFC c rhs (L nspan afo)) = concatM $ case afo of
1122    Unambiguous name _ ->
1123      [ toHie $ C (RecField c rhs) $ L nspan name
1124      ]
1125    Ambiguous _name _ ->
1126      [ ]
1127    XAmbiguousFieldOcc _ -> []
1128
1129instance ToHie (RFContext (Located (AmbiguousFieldOcc GhcTc))) where
1130  toHie (RFC c rhs (L nspan afo)) = concatM $ case afo of
1131    Unambiguous var _ ->
1132      let var' = setVarName var (varName var)
1133      in [ toHie $ C (RecField c rhs) (L nspan var')
1134         ]
1135    Ambiguous var _ ->
1136      let var' = setVarName var (varName var)
1137      in [ toHie $ C (RecField c rhs) (L nspan var')
1138         ]
1139    XAmbiguousFieldOcc _ -> []
1140
1141instance ( a ~ GhcPass p
1142         , ToHie (PScoped (LPat a))
1143         , ToHie (BindContext (LHsBind a))
1144         , ToHie (LHsExpr a)
1145         , ToHie (SigContext (LSig a))
1146         , ToHie (RScoped (HsValBindsLR a a))
1147         , Data (StmtLR a a (Located (HsExpr a)))
1148         , Data (HsLocalBinds a)
1149         ) => ToHie (RScoped (ApplicativeArg (GhcPass p))) where
1150  toHie (RS sc (ApplicativeArgOne _ pat expr _ _)) = concatM
1151    [ toHie $ PS Nothing sc NoScope pat
1152    , toHie expr
1153    ]
1154  toHie (RS sc (ApplicativeArgMany _ stmts _ pat)) = concatM
1155    [ toHie $ listScopes NoScope stmts
1156    , toHie $ PS Nothing sc NoScope pat
1157    ]
1158  toHie (RS _ (XApplicativeArg _)) = pure []
1159
1160instance (ToHie arg, ToHie rec) => ToHie (HsConDetails arg rec) where
1161  toHie (PrefixCon args) = toHie args
1162  toHie (RecCon rec) = toHie rec
1163  toHie (InfixCon a b) = concatM [ toHie a, toHie b]
1164
1165instance ( ToHie (LHsCmd a)
1166         , Data  (HsCmdTop a)
1167         ) => ToHie (LHsCmdTop a) where
1168  toHie (L span top) = concatM $ makeNode top span : case top of
1169    HsCmdTop _ cmd ->
1170      [ toHie cmd
1171      ]
1172    XCmdTop _ -> []
1173
1174instance ( a ~ GhcPass p
1175         , ToHie (PScoped (LPat a))
1176         , ToHie (BindContext (LHsBind a))
1177         , ToHie (LHsExpr a)
1178         , ToHie (MatchGroup a (LHsCmd a))
1179         , ToHie (SigContext (LSig a))
1180         , ToHie (RScoped (HsValBindsLR a a))
1181         , Data (HsCmd a)
1182         , Data (HsCmdTop a)
1183         , Data (StmtLR a a (Located (HsCmd a)))
1184         , Data (HsLocalBinds a)
1185         , Data (StmtLR a a (Located (HsExpr a)))
1186         ) => ToHie (LHsCmd (GhcPass p)) where
1187  toHie (L span cmd) = concatM $ makeNode cmd span : case cmd of
1188      HsCmdArrApp _ a b _ _ ->
1189        [ toHie a
1190        , toHie b
1191        ]
1192      HsCmdArrForm _ a _ _ cmdtops ->
1193        [ toHie a
1194        , toHie cmdtops
1195        ]
1196      HsCmdApp _ a b ->
1197        [ toHie a
1198        , toHie b
1199        ]
1200      HsCmdLam _ mg ->
1201        [ toHie mg
1202        ]
1203      HsCmdPar _ a ->
1204        [ toHie a
1205        ]
1206      HsCmdCase _ expr alts ->
1207        [ toHie expr
1208        , toHie alts
1209        ]
1210      HsCmdIf _ _ a b c ->
1211        [ toHie a
1212        , toHie b
1213        , toHie c
1214        ]
1215      HsCmdLet _ binds cmd' ->
1216        [ toHie $ RS (mkLScope cmd') binds
1217        , toHie cmd'
1218        ]
1219      HsCmdDo _ (L ispan stmts) ->
1220        [ pure $ locOnly ispan
1221        , toHie $ listScopes NoScope stmts
1222        ]
1223      HsCmdWrap _ _ _ -> []
1224      XCmd _ -> []
1225
1226instance ToHie (TyClGroup GhcRn) where
1227  toHie TyClGroup{ group_tyclds = classes
1228                 , group_roles  = roles
1229                 , group_kisigs = sigs
1230                 , group_instds = instances } =
1231    concatM
1232    [ toHie classes
1233    , toHie sigs
1234    , toHie roles
1235    , toHie instances
1236    ]
1237  toHie (XTyClGroup _) = pure []
1238
1239instance ToHie (LTyClDecl GhcRn) where
1240  toHie (L span decl) = concatM $ makeNode decl span : case decl of
1241      FamDecl {tcdFam = fdecl} ->
1242        [ toHie (L span fdecl)
1243        ]
1244      SynDecl {tcdLName = name, tcdTyVars = vars, tcdRhs = typ} ->
1245        [ toHie $ C (Decl SynDec $ getRealSpan span) name
1246        , toHie $ TS (ResolvedScopes [mkScope $ getLoc typ]) vars
1247        , toHie typ
1248        ]
1249      DataDecl {tcdLName = name, tcdTyVars = vars, tcdDataDefn = defn} ->
1250        [ toHie $ C (Decl DataDec $ getRealSpan span) name
1251        , toHie $ TS (ResolvedScopes [quant_scope, rhs_scope]) vars
1252        , toHie defn
1253        ]
1254        where
1255          quant_scope = mkLScope $ dd_ctxt defn
1256          rhs_scope = sig_sc `combineScopes` con_sc `combineScopes` deriv_sc
1257          sig_sc = maybe NoScope mkLScope $ dd_kindSig defn
1258          con_sc = foldr combineScopes NoScope $ map mkLScope $ dd_cons defn
1259          deriv_sc = mkLScope $ dd_derivs defn
1260      ClassDecl { tcdCtxt = context
1261                , tcdLName = name
1262                , tcdTyVars = vars
1263                , tcdFDs = deps
1264                , tcdSigs = sigs
1265                , tcdMeths = meths
1266                , tcdATs = typs
1267                , tcdATDefs = deftyps
1268                } ->
1269        [ toHie $ C (Decl ClassDec $ getRealSpan span) name
1270        , toHie context
1271        , toHie $ TS (ResolvedScopes [context_scope, rhs_scope]) vars
1272        , toHie deps
1273        , toHie $ map (SC $ SI ClassSig $ getRealSpan span) sigs
1274        , toHie $ fmap (BC InstanceBind ModuleScope) meths
1275        , toHie typs
1276        , concatMapM (pure . locOnly . getLoc) deftyps
1277        , toHie deftyps
1278        ]
1279        where
1280          context_scope = mkLScope context
1281          rhs_scope = foldl1' combineScopes $ map mkScope
1282            [ loc deps, loc sigs, loc (bagToList meths), loc typs, loc deftyps]
1283      XTyClDecl _ -> []
1284
1285instance ToHie (LFamilyDecl GhcRn) where
1286  toHie (L span decl) = concatM $ makeNode decl span : case decl of
1287      FamilyDecl _ info name vars _ sig inj ->
1288        [ toHie $ C (Decl FamDec $ getRealSpan span) name
1289        , toHie $ TS (ResolvedScopes [rhsSpan]) vars
1290        , toHie info
1291        , toHie $ RS injSpan sig
1292        , toHie inj
1293        ]
1294        where
1295          rhsSpan = sigSpan `combineScopes` injSpan
1296          sigSpan = mkScope $ getLoc sig
1297          injSpan = maybe NoScope (mkScope . getLoc) inj
1298      XFamilyDecl _ -> []
1299
1300instance ToHie (FamilyInfo GhcRn) where
1301  toHie (ClosedTypeFamily (Just eqns)) = concatM $
1302    [ concatMapM (pure . locOnly . getLoc) eqns
1303    , toHie $ map go eqns
1304    ]
1305    where
1306      go (L l ib) = TS (ResolvedScopes [mkScope l]) ib
1307  toHie _ = pure []
1308
1309instance ToHie (RScoped (LFamilyResultSig GhcRn)) where
1310  toHie (RS sc (L span sig)) = concatM $ makeNode sig span : case sig of
1311      NoSig _ ->
1312        []
1313      KindSig _ k ->
1314        [ toHie k
1315        ]
1316      TyVarSig _ bndr ->
1317        [ toHie $ TVS (ResolvedScopes [sc]) NoScope bndr
1318        ]
1319      XFamilyResultSig _ -> []
1320
1321instance ToHie (Located (FunDep (Located Name))) where
1322  toHie (L span fd@(lhs, rhs)) = concatM $
1323    [ makeNode fd span
1324    , toHie $ map (C Use) lhs
1325    , toHie $ map (C Use) rhs
1326    ]
1327
1328instance (ToHie rhs, HasLoc rhs)
1329    => ToHie (TScoped (FamEqn GhcRn rhs)) where
1330  toHie (TS _ f) = toHie f
1331
1332instance (ToHie rhs, HasLoc rhs)
1333    => ToHie (FamEqn GhcRn rhs) where
1334  toHie fe@(FamEqn _ var tybndrs pats _ rhs) = concatM $
1335    [ toHie $ C (Decl InstDec $ getRealSpan $ loc fe) var
1336    , toHie $ fmap (tvScopes (ResolvedScopes []) scope) tybndrs
1337    , toHie pats
1338    , toHie rhs
1339    ]
1340    where scope = combineScopes patsScope rhsScope
1341          patsScope = mkScope (loc pats)
1342          rhsScope = mkScope (loc rhs)
1343  toHie (XFamEqn _) = pure []
1344
1345instance ToHie (LInjectivityAnn GhcRn) where
1346  toHie (L span ann) = concatM $ makeNode ann span : case ann of
1347      InjectivityAnn lhs rhs ->
1348        [ toHie $ C Use lhs
1349        , toHie $ map (C Use) rhs
1350        ]
1351
1352instance ToHie (HsDataDefn GhcRn) where
1353  toHie (HsDataDefn _ _ ctx _ mkind cons derivs) = concatM
1354    [ toHie ctx
1355    , toHie mkind
1356    , toHie cons
1357    , toHie derivs
1358    ]
1359  toHie (XHsDataDefn _) = pure []
1360
1361instance ToHie (HsDeriving GhcRn) where
1362  toHie (L span clauses) = concatM
1363    [ pure $ locOnly span
1364    , toHie clauses
1365    ]
1366
1367instance ToHie (LHsDerivingClause GhcRn) where
1368  toHie (L span cl) = concatM $ makeNode cl span : case cl of
1369      HsDerivingClause _ strat (L ispan tys) ->
1370        [ toHie strat
1371        , pure $ locOnly ispan
1372        , toHie $ map (TS (ResolvedScopes [])) tys
1373        ]
1374      XHsDerivingClause _ -> []
1375
1376instance ToHie (Located (DerivStrategy GhcRn)) where
1377  toHie (L span strat) = concatM $ makeNode strat span : case strat of
1378      StockStrategy -> []
1379      AnyclassStrategy -> []
1380      NewtypeStrategy -> []
1381      ViaStrategy s -> [ toHie $ TS (ResolvedScopes []) s ]
1382
1383instance ToHie (Located OverlapMode) where
1384  toHie (L span _) = pure $ locOnly span
1385
1386instance ToHie (LConDecl GhcRn) where
1387  toHie (L span decl) = concatM $ makeNode decl span : case decl of
1388      ConDeclGADT { con_names = names, con_qvars = qvars
1389                  , con_mb_cxt = ctx, con_args = args, con_res_ty = typ } ->
1390        [ toHie $ map (C (Decl ConDec $ getRealSpan span)) names
1391        , toHie $ TS (ResolvedScopes [ctxScope, rhsScope]) qvars
1392        , toHie ctx
1393        , toHie args
1394        , toHie typ
1395        ]
1396        where
1397          rhsScope = combineScopes argsScope tyScope
1398          ctxScope = maybe NoScope mkLScope ctx
1399          argsScope = condecl_scope args
1400          tyScope = mkLScope typ
1401      ConDeclH98 { con_name = name, con_ex_tvs = qvars
1402                 , con_mb_cxt = ctx, con_args = dets } ->
1403        [ toHie $ C (Decl ConDec $ getRealSpan span) name
1404        , toHie $ tvScopes (ResolvedScopes []) rhsScope qvars
1405        , toHie ctx
1406        , toHie dets
1407        ]
1408        where
1409          rhsScope = combineScopes ctxScope argsScope
1410          ctxScope = maybe NoScope mkLScope ctx
1411          argsScope = condecl_scope dets
1412      XConDecl _ -> []
1413    where condecl_scope args = case args of
1414            PrefixCon xs -> foldr combineScopes NoScope $ map mkLScope xs
1415            InfixCon a b -> combineScopes (mkLScope a) (mkLScope b)
1416            RecCon x -> mkLScope x
1417
1418instance ToHie (Located [LConDeclField GhcRn]) where
1419  toHie (L span decls) = concatM $
1420    [ pure $ locOnly span
1421    , toHie decls
1422    ]
1423
1424instance ( HasLoc thing
1425         , ToHie (TScoped thing)
1426         ) => ToHie (TScoped (HsImplicitBndrs GhcRn thing)) where
1427  toHie (TS sc (HsIB ibrn a)) = concatM $
1428      [ pure $ bindingsOnly $ map (C $ TyVarBind (mkScope span) sc) ibrn
1429      , toHie $ TS sc a
1430      ]
1431    where span = loc a
1432  toHie (TS _ (XHsImplicitBndrs _)) = pure []
1433
1434instance ( HasLoc thing
1435         , ToHie (TScoped thing)
1436         ) => ToHie (TScoped (HsWildCardBndrs GhcRn thing)) where
1437  toHie (TS sc (HsWC names a)) = concatM $
1438      [ pure $ bindingsOnly $ map (C $ TyVarBind (mkScope span) sc) names
1439      , toHie $ TS sc a
1440      ]
1441    where span = loc a
1442  toHie (TS _ (XHsWildCardBndrs _)) = pure []
1443
1444instance ToHie (LStandaloneKindSig GhcRn) where
1445  toHie (L sp sig) = concatM [makeNode sig sp, toHie sig]
1446
1447instance ToHie (StandaloneKindSig GhcRn) where
1448  toHie sig = concatM $ case sig of
1449    StandaloneKindSig _ name typ ->
1450      [ toHie $ C TyDecl name
1451      , toHie $ TS (ResolvedScopes []) typ
1452      ]
1453    XStandaloneKindSig _ -> []
1454
1455instance ToHie (SigContext (LSig GhcRn)) where
1456  toHie (SC (SI styp msp) (L sp sig)) = concatM $ makeNode sig sp : case sig of
1457      TypeSig _ names typ ->
1458        [ toHie $ map (C TyDecl) names
1459        , toHie $ TS (UnresolvedScope (map unLoc names) Nothing) typ
1460        ]
1461      PatSynSig _ names typ ->
1462        [ toHie $ map (C TyDecl) names
1463        , toHie $ TS (UnresolvedScope (map unLoc names) Nothing) typ
1464        ]
1465      ClassOpSig _ _ names typ ->
1466        [ case styp of
1467            ClassSig -> toHie $ map (C $ ClassTyDecl $ getRealSpan sp) names
1468            _  -> toHie $ map (C $ TyDecl) names
1469        , toHie $ TS (UnresolvedScope (map unLoc names) msp) typ
1470        ]
1471      IdSig _ _ -> []
1472      FixSig _ fsig ->
1473        [ toHie $ L sp fsig
1474        ]
1475      InlineSig _ name _ ->
1476        [ toHie $ (C Use) name
1477        ]
1478      SpecSig _ name typs _ ->
1479        [ toHie $ (C Use) name
1480        , toHie $ map (TS (ResolvedScopes [])) typs
1481        ]
1482      SpecInstSig _ _ typ ->
1483        [ toHie $ TS (ResolvedScopes []) typ
1484        ]
1485      MinimalSig _ _ form ->
1486        [ toHie form
1487        ]
1488      SCCFunSig _ _ name mtxt ->
1489        [ toHie $ (C Use) name
1490        , pure $ maybe [] (locOnly . getLoc) mtxt
1491        ]
1492      CompleteMatchSig _ _ (L ispan names) typ ->
1493        [ pure $ locOnly ispan
1494        , toHie $ map (C Use) names
1495        , toHie $ fmap (C Use) typ
1496        ]
1497      XSig _ -> []
1498
1499instance ToHie (LHsType GhcRn) where
1500  toHie x = toHie $ TS (ResolvedScopes []) x
1501
1502instance ToHie (TScoped (LHsType GhcRn)) where
1503  toHie (TS tsc (L span t)) = concatM $ makeNode t span : case t of
1504      HsForAllTy _ _ bndrs body ->
1505        [ toHie $ tvScopes tsc (mkScope $ getLoc body) bndrs
1506        , toHie body
1507        ]
1508      HsQualTy _ ctx body ->
1509        [ toHie ctx
1510        , toHie body
1511        ]
1512      HsTyVar _ _ var ->
1513        [ toHie $ C Use var
1514        ]
1515      HsAppTy _ a b ->
1516        [ toHie a
1517        , toHie b
1518        ]
1519      HsAppKindTy _ ty ki ->
1520        [ toHie ty
1521        , toHie $ TS (ResolvedScopes []) ki
1522        ]
1523      HsFunTy _ a b ->
1524        [ toHie a
1525        , toHie b
1526        ]
1527      HsListTy _ a ->
1528        [ toHie a
1529        ]
1530      HsTupleTy _ _ tys ->
1531        [ toHie tys
1532        ]
1533      HsSumTy _ tys ->
1534        [ toHie tys
1535        ]
1536      HsOpTy _ a op b ->
1537        [ toHie a
1538        , toHie $ C Use op
1539        , toHie b
1540        ]
1541      HsParTy _ a ->
1542        [ toHie a
1543        ]
1544      HsIParamTy _ ip ty ->
1545        [ toHie ip
1546        , toHie ty
1547        ]
1548      HsKindSig _ a b ->
1549        [ toHie a
1550        , toHie b
1551        ]
1552      HsSpliceTy _ a ->
1553        [ toHie $ L span a
1554        ]
1555      HsDocTy _ a _ ->
1556        [ toHie a
1557        ]
1558      HsBangTy _ _ ty ->
1559        [ toHie ty
1560        ]
1561      HsRecTy _ fields ->
1562        [ toHie fields
1563        ]
1564      HsExplicitListTy _ _ tys ->
1565        [ toHie tys
1566        ]
1567      HsExplicitTupleTy _ tys ->
1568        [ toHie tys
1569        ]
1570      HsTyLit _ _ -> []
1571      HsWildCardTy _ -> []
1572      HsStarTy _ _ -> []
1573      XHsType _ -> []
1574
1575instance (ToHie tm, ToHie ty) => ToHie (HsArg tm ty) where
1576  toHie (HsValArg tm) = toHie tm
1577  toHie (HsTypeArg _ ty) = toHie ty
1578  toHie (HsArgPar sp) = pure $ locOnly sp
1579
1580instance ToHie (TVScoped (LHsTyVarBndr GhcRn)) where
1581  toHie (TVS tsc sc (L span bndr)) = concatM $ makeNode bndr span : case bndr of
1582      UserTyVar _ var ->
1583        [ toHie $ C (TyVarBind sc tsc) var
1584        ]
1585      KindedTyVar _ var kind ->
1586        [ toHie $ C (TyVarBind sc tsc) var
1587        , toHie kind
1588        ]
1589      XTyVarBndr _ -> []
1590
1591instance ToHie (TScoped (LHsQTyVars GhcRn)) where
1592  toHie (TS sc (HsQTvs implicits vars)) = concatM $
1593    [ pure $ bindingsOnly bindings
1594    , toHie $ tvScopes sc NoScope vars
1595    ]
1596    where
1597      varLoc = loc vars
1598      bindings = map (C $ TyVarBind (mkScope varLoc) sc) implicits
1599  toHie (TS _ (XLHsQTyVars _)) = pure []
1600
1601instance ToHie (LHsContext GhcRn) where
1602  toHie (L span tys) = concatM $
1603      [ pure $ locOnly span
1604      , toHie tys
1605      ]
1606
1607instance ToHie (LConDeclField GhcRn) where
1608  toHie (L span field) = concatM $ makeNode field span : case field of
1609      ConDeclField _ fields typ _ ->
1610        [ toHie $ map (RFC RecFieldDecl (getRealSpan $ loc typ)) fields
1611        , toHie typ
1612        ]
1613      XConDeclField _ -> []
1614
1615instance ToHie (LHsExpr a) => ToHie (ArithSeqInfo a) where
1616  toHie (From expr) = toHie expr
1617  toHie (FromThen a b) = concatM $
1618    [ toHie a
1619    , toHie b
1620    ]
1621  toHie (FromTo a b) = concatM $
1622    [ toHie a
1623    , toHie b
1624    ]
1625  toHie (FromThenTo a b c) = concatM $
1626    [ toHie a
1627    , toHie b
1628    , toHie c
1629    ]
1630
1631instance ToHie (LSpliceDecl GhcRn) where
1632  toHie (L span decl) = concatM $ makeNode decl span : case decl of
1633      SpliceDecl _ splice _ ->
1634        [ toHie splice
1635        ]
1636      XSpliceDecl _ -> []
1637
1638instance ToHie (HsBracket a) where
1639  toHie _ = pure []
1640
1641instance ToHie PendingRnSplice where
1642  toHie _ = pure []
1643
1644instance ToHie PendingTcSplice where
1645  toHie _ = pure []
1646
1647instance ToHie (LBooleanFormula (Located Name)) where
1648  toHie (L span form) = concatM $ makeNode form span : case form of
1649      Var a ->
1650        [ toHie $ C Use a
1651        ]
1652      And forms ->
1653        [ toHie forms
1654        ]
1655      Or forms ->
1656        [ toHie forms
1657        ]
1658      Parens f ->
1659        [ toHie f
1660        ]
1661
1662instance ToHie (Located HsIPName) where
1663  toHie (L span e) = makeNode e span
1664
1665instance ( ToHie (LHsExpr a)
1666         , Data (HsSplice a)
1667         ) => ToHie (Located (HsSplice a)) where
1668  toHie (L span sp) = concatM $ makeNode sp span : case sp of
1669      HsTypedSplice _ _ _ expr ->
1670        [ toHie expr
1671        ]
1672      HsUntypedSplice _ _ _ expr ->
1673        [ toHie expr
1674        ]
1675      HsQuasiQuote _ _ _ ispan _ ->
1676        [ pure $ locOnly ispan
1677        ]
1678      HsSpliced _ _ _ ->
1679        []
1680      HsSplicedT _ ->
1681        []
1682      XSplice _ -> []
1683
1684instance ToHie (LRoleAnnotDecl GhcRn) where
1685  toHie (L span annot) = concatM $ makeNode annot span : case annot of
1686      RoleAnnotDecl _ var roles ->
1687        [ toHie $ C Use var
1688        , concatMapM (pure . locOnly . getLoc) roles
1689        ]
1690      XRoleAnnotDecl _ -> []
1691
1692instance ToHie (LInstDecl GhcRn) where
1693  toHie (L span decl) = concatM $ makeNode decl span : case decl of
1694      ClsInstD _ d ->
1695        [ toHie $ L span d
1696        ]
1697      DataFamInstD _ d ->
1698        [ toHie $ L span d
1699        ]
1700      TyFamInstD _ d ->
1701        [ toHie $ L span d
1702        ]
1703      XInstDecl _ -> []
1704
1705instance ToHie (LClsInstDecl GhcRn) where
1706  toHie (L span decl) = concatM
1707    [ toHie $ TS (ResolvedScopes [mkScope span]) $ cid_poly_ty decl
1708    , toHie $ fmap (BC InstanceBind ModuleScope) $ cid_binds decl
1709    , toHie $ map (SC $ SI InstSig $ getRealSpan span) $ cid_sigs decl
1710    , pure $ concatMap (locOnly . getLoc) $ cid_tyfam_insts decl
1711    , toHie $ cid_tyfam_insts decl
1712    , pure $ concatMap (locOnly . getLoc) $ cid_datafam_insts decl
1713    , toHie $ cid_datafam_insts decl
1714    , toHie $ cid_overlap_mode decl
1715    ]
1716
1717instance ToHie (LDataFamInstDecl GhcRn) where
1718  toHie (L sp (DataFamInstDecl d)) = toHie $ TS (ResolvedScopes [mkScope sp]) d
1719
1720instance ToHie (LTyFamInstDecl GhcRn) where
1721  toHie (L sp (TyFamInstDecl d)) = toHie $ TS (ResolvedScopes [mkScope sp]) d
1722
1723instance ToHie (Context a)
1724         => ToHie (PatSynFieldContext (RecordPatSynField a)) where
1725  toHie (PSC sp (RecordPatSynField a b)) = concatM $
1726    [ toHie $ C (RecField RecFieldDecl sp) a
1727    , toHie $ C Use b
1728    ]
1729
1730instance ToHie (LDerivDecl GhcRn) where
1731  toHie (L span decl) = concatM $ makeNode decl span : case decl of
1732      DerivDecl _ typ strat overlap ->
1733        [ toHie $ TS (ResolvedScopes []) typ
1734        , toHie strat
1735        , toHie overlap
1736        ]
1737      XDerivDecl _ -> []
1738
1739instance ToHie (LFixitySig GhcRn) where
1740  toHie (L span sig) = concatM $ makeNode sig span : case sig of
1741      FixitySig _ vars _ ->
1742        [ toHie $ map (C Use) vars
1743        ]
1744      XFixitySig _ -> []
1745
1746instance ToHie (LDefaultDecl GhcRn) where
1747  toHie (L span decl) = concatM $ makeNode decl span : case decl of
1748      DefaultDecl _ typs ->
1749        [ toHie typs
1750        ]
1751      XDefaultDecl _ -> []
1752
1753instance ToHie (LForeignDecl GhcRn) where
1754  toHie (L span decl) = concatM $ makeNode decl span : case decl of
1755      ForeignImport {fd_name = name, fd_sig_ty = sig, fd_fi = fi} ->
1756        [ toHie $ C (ValBind RegularBind ModuleScope $ getRealSpan span) name
1757        , toHie $ TS (ResolvedScopes []) sig
1758        , toHie fi
1759        ]
1760      ForeignExport {fd_name = name, fd_sig_ty = sig, fd_fe = fe} ->
1761        [ toHie $ C Use name
1762        , toHie $ TS (ResolvedScopes []) sig
1763        , toHie fe
1764        ]
1765      XForeignDecl _ -> []
1766
1767instance ToHie ForeignImport where
1768  toHie (CImport (L a _) (L b _) _ _ (L c _)) = pure $ concat $
1769    [ locOnly a
1770    , locOnly b
1771    , locOnly c
1772    ]
1773
1774instance ToHie ForeignExport where
1775  toHie (CExport (L a _) (L b _)) = pure $ concat $
1776    [ locOnly a
1777    , locOnly b
1778    ]
1779
1780instance ToHie (LWarnDecls GhcRn) where
1781  toHie (L span decl) = concatM $ makeNode decl span : case decl of
1782      Warnings _ _ warnings ->
1783        [ toHie warnings
1784        ]
1785      XWarnDecls _ -> []
1786
1787instance ToHie (LWarnDecl GhcRn) where
1788  toHie (L span decl) = concatM $ makeNode decl span : case decl of
1789      Warning _ vars _ ->
1790        [ toHie $ map (C Use) vars
1791        ]
1792      XWarnDecl _ -> []
1793
1794instance ToHie (LAnnDecl GhcRn) where
1795  toHie (L span decl) = concatM $ makeNode decl span : case decl of
1796      HsAnnotation _ _ prov expr ->
1797        [ toHie prov
1798        , toHie expr
1799        ]
1800      XAnnDecl _ -> []
1801
1802instance ToHie (Context (Located a)) => ToHie (AnnProvenance a) where
1803  toHie (ValueAnnProvenance a) = toHie $ C Use a
1804  toHie (TypeAnnProvenance a) = toHie $ C Use a
1805  toHie ModuleAnnProvenance = pure []
1806
1807instance ToHie (LRuleDecls GhcRn) where
1808  toHie (L span decl) = concatM $ makeNode decl span : case decl of
1809      HsRules _ _ rules ->
1810        [ toHie rules
1811        ]
1812      XRuleDecls _ -> []
1813
1814instance ToHie (LRuleDecl GhcRn) where
1815  toHie (L _ (XRuleDecl _)) = pure []
1816  toHie (L span r@(HsRule _ rname _ tybndrs bndrs exprA exprB)) = concatM
1817        [ makeNode r span
1818        , pure $ locOnly $ getLoc rname
1819        , toHie $ fmap (tvScopes (ResolvedScopes []) scope) tybndrs
1820        , toHie $ map (RS $ mkScope span) bndrs
1821        , toHie exprA
1822        , toHie exprB
1823        ]
1824    where scope = bndrs_sc `combineScopes` exprA_sc `combineScopes` exprB_sc
1825          bndrs_sc = maybe NoScope mkLScope (listToMaybe bndrs)
1826          exprA_sc = mkLScope exprA
1827          exprB_sc = mkLScope exprB
1828
1829instance ToHie (RScoped (LRuleBndr GhcRn)) where
1830  toHie (RS sc (L span bndr)) = concatM $ makeNode bndr span : case bndr of
1831      RuleBndr _ var ->
1832        [ toHie $ C (ValBind RegularBind sc Nothing) var
1833        ]
1834      RuleBndrSig _ var typ ->
1835        [ toHie $ C (ValBind RegularBind sc Nothing) var
1836        , toHie $ TS (ResolvedScopes [sc]) typ
1837        ]
1838      XRuleBndr _ -> []
1839
1840instance ToHie (LImportDecl GhcRn) where
1841  toHie (L span decl) = concatM $ makeNode decl span : case decl of
1842      ImportDecl { ideclName = name, ideclAs = as, ideclHiding = hidden } ->
1843        [ toHie $ IEC Import name
1844        , toHie $ fmap (IEC ImportAs) as
1845        , maybe (pure []) goIE hidden
1846        ]
1847      XImportDecl _ -> []
1848    where
1849      goIE (hiding, (L sp liens)) = concatM $
1850        [ pure $ locOnly sp
1851        , toHie $ map (IEC c) liens
1852        ]
1853        where
1854         c = if hiding then ImportHiding else Import
1855
1856instance ToHie (IEContext (LIE GhcRn)) where
1857  toHie (IEC c (L span ie)) = concatM $ makeNode ie span : case ie of
1858      IEVar _ n ->
1859        [ toHie $ IEC c n
1860        ]
1861      IEThingAbs _ n ->
1862        [ toHie $ IEC c n
1863        ]
1864      IEThingAll _ n ->
1865        [ toHie $ IEC c n
1866        ]
1867      IEThingWith _ n _ ns flds ->
1868        [ toHie $ IEC c n
1869        , toHie $ map (IEC c) ns
1870        , toHie $ map (IEC c) flds
1871        ]
1872      IEModuleContents _ n ->
1873        [ toHie $ IEC c n
1874        ]
1875      IEGroup _ _ _ -> []
1876      IEDoc _ _ -> []
1877      IEDocNamed _ _ -> []
1878      XIE _ -> []
1879
1880instance ToHie (IEContext (LIEWrappedName Name)) where
1881  toHie (IEC c (L span iewn)) = concatM $ makeNode iewn span : case iewn of
1882      IEName n ->
1883        [ toHie $ C (IEThing c) n
1884        ]
1885      IEPattern p ->
1886        [ toHie $ C (IEThing c) p
1887        ]
1888      IEType n ->
1889        [ toHie $ C (IEThing c) n
1890        ]
1891
1892instance ToHie (IEContext (Located (FieldLbl Name))) where
1893  toHie (IEC c (L span lbl)) = concatM $ makeNode lbl span : case lbl of
1894      FieldLabel _ _ n ->
1895        [ toHie $ C (IEThing c) $ L span n
1896        ]
1897