0 | module Idris.Desugar
   1 |
   2 | import Core.CompileExpr
   3 | import Core.Env
   4 | import Core.Metadata
   5 | import Core.Unify
   6 |
   7 | import Libraries.Data.List.Extra
   8 | import Libraries.Data.ANameMap
   9 |
  10 | import Idris.Doc.String
  11 | import Idris.Error
  12 | import Idris.Pretty
  13 | import Idris.REPL.Opts
  14 | import Idris.Syntax
  15 | import Idris.Syntax.Builtin
  16 |
  17 | import Idris.Elab.Implementation
  18 | import Idris.Elab.Interface
  19 |
  20 | import Idris.Desugar.Mutual
  21 |
  22 | import Parser.Support.Escaping
  23 |
  24 | import TTImp.BindImplicits
  25 | import TTImp.Parser
  26 | import TTImp.ProcessType
  27 | import TTImp.TTImp
  28 | import TTImp.Utils
  29 |
  30 | import Libraries.Data.IMaybe
  31 | import Libraries.Data.WithDefault
  32 | import Libraries.Utils.Shunting
  33 |
  34 | import Data.List.Views
  35 | import Data.SortedMap
  36 | import Data.SortedSet
  37 | import Data.String
  38 |
  39 | -- Convert high level Idris declarations (PDecl from Idris.Syntax) into
  40 | -- TTImp, recording any high level syntax info on the way (e.g. infix
  41 | -- operators)
  42 |
  43 | -- Desugaring from high level Idris syntax to TTImp involves:
  44 |
  45 | -- * Shunting infix operators into function applications according to precedence
  46 | -- * Replacing 'do' notating with applications of (>>=)
  47 | -- * Replacing string interpolation with concatenation by (++)
  48 | -- * Replacing pattern matching binds with 'case'
  49 | -- * Changing tuples to 'Pair/MkPair'
  50 | -- * List notation
  51 | -- * Replacing !-notation
  52 | -- * Dependent pair notation
  53 | -- * Idiom brackets
  54 |
  55 | %default covering
  56 |
  57 | public export
  58 | data Side = LHS | AnyExpr
  59 |
  60 | export
  61 | Eq Side where
  62 |   LHS == LHS = True
  63 |   AnyExpr == AnyExpr = True
  64 |   _ == _ = False
  65 |
  66 | export
  67 | extendSyn : {auto s : Ref Syn SyntaxInfo} ->
  68 |             {auto c : Ref Ctxt Defs} ->
  69 |             SyntaxInfo -> Core ()
  70 | extendSyn newsyn
  71 |     = do syn <- get Syn
  72 |          log "doc.module" 20 $ unlines
  73 |            [ "Old (" ++ unwords (map show $ saveMod syn) ++ "): "
  74 |               ++ show (modDocstrings syn)
  75 |            , "New (" ++ unwords (map show $ saveMod newsyn) ++ "): "
  76 |               ++ show (modDocstrings newsyn)
  77 |            ]
  78 |
  79 |          -- Before we merge the two syntax environement, we remove the
  80 |          -- private fixities from the one we are importing.
  81 |          -- We keep the local private fixities since they are visible in the
  82 |          -- current file.
  83 |          let filteredFixities = removePrivate (fixities newsyn)
  84 |          put Syn ({ fixities $= merge filteredFixities,
  85 |                     ifaces $= merge (ifaces newsyn),
  86 |                     modDocstrings $= mergeLeft (modDocstrings newsyn),
  87 |                     modDocexports $= mergeLeft (modDocexports newsyn),
  88 |                     defDocstrings $= merge (defDocstrings newsyn),
  89 |                     bracketholes $= sortedNub . ((bracketholes newsyn) ++) }
  90 |                   syn)
  91 |   where
  92 |     removePrivate : ANameMap FixityInfo -> ANameMap FixityInfo
  93 |     removePrivate = fromList . filter ((/= Private) . vis . snd) . toList
  94 |
  95 | mkPrec : Fixity -> Nat -> OpPrec
  96 | mkPrec InfixL = AssocL
  97 | mkPrec InfixR = AssocR
  98 | mkPrec Infix  = NonAssoc
  99 | mkPrec Prefix = Prefix
 100 |
 101 | -- This is used to print the error message for fixities
 102 | [interpName] Interpolation ((OpStr' Name, FixityDeclarationInfo), b) where
 103 |   interpolate ((x, _), _) = show x.toName
 104 |
 105 | [showWithLoc] Show ((OpStr' Name, FixityDeclarationInfo), b) where
 106 |   show ((x, DeclaredFixity y), _) = show x ++ " at " ++ show y.fc
 107 |   show ((x, UndeclaredFixity), _) = show x
 108 |
 109 | -- Check that an operator does not have any conflicting fixities in scope.
 110 | -- Each operator can have its fixity defined multiple times across multiple
 111 | -- modules as long as the fixities are consistent. If they aren't, the fixity
 112 | -- can be hidden with %hide, this is handled by `removeFixity`.
 113 | -- Once conflicts are handled we return the operator precedence we found.
 114 | checkConflictingFixities : {auto s : Ref Syn SyntaxInfo} ->
 115 |                            {auto c : Ref Ctxt Defs} ->
 116 |                            (isPrefix : Bool) ->
 117 |                            WithFC (OpStr' Name) -> Core (OpPrec, FixityDeclarationInfo)
 118 | checkConflictingFixities isPrefix opn
 119 |   = do let op = nameRoot opn.val.toName
 120 |        foundFixities <- getFixityInfo op
 121 |        let (pre, inf) = partition ((== Prefix) . fix . snd) foundFixities
 122 |        case (isPrefix, pre, inf) of
 123 |             -- If we do not find any fixity, and it is a backticked operator, then we
 124 |             -- return the default fixity and associativity for backticked operators
 125 |             -- Otherwise, it's an unknown operator.
 126 |             (_, [], []) => case opn.val of
 127 |                               OpSymbols _ => throw (GenericMsg opn.fc "Unknown operator '\{op}'")
 128 |                               Backticked _ =>  pure (NonAssoc 1, UndeclaredFixity) -- Backticks are non associative by default
 129 |
 130 |             (True, ((fxName, fx) :: _), _) => do
 131 |                 -- in the prefix case, remove conflicts with infix (-)
 132 |                 let extraFixities = pre ++ (filter (\(nm, _) => not $ nameRoot nm == "-") inf)
 133 |                 unless (isCompatible fx extraFixities) $ warnConflict fxName extraFixities
 134 |                 pure (mkPrec fx.fix fx.precedence, DeclaredFixity fx)
 135 |             -- Could not find any prefix operator fixities, there may still be conflicts with
 136 |             -- the infix ones.
 137 |             (True, [] , _) => throw (GenericMsg opn.fc $ "'\{op}' is not a prefix operator")
 138 |
 139 |             (False, _, ((fxName, fx) :: _)) => do
 140 |                 -- In the infix case, remove conflicts with prefix (-)
 141 |                 let extraFixities = (filter (\(nm, _) => not $ nm == UN (Basic "-")) pre) ++ inf
 142 |                 unless (isCompatible fx extraFixities) $ warnConflict fxName extraFixities
 143 |                 pure (mkPrec fx.fix fx.precedence, DeclaredFixity fx)
 144 |             -- Could not find any infix operator fixities, there may be prefix ones
 145 |             (False, _, []) => throw (GenericMsg opn.fc $ "'\{op}' is not an infix operator")
 146 |   where
 147 |     -- Fixities are compatible with all others of the same name that share the same
 148 |     -- fixity, precedence, and binding information
 149 |     isCompatible :  FixityInfo -> (fixities : List (Name, FixityInfo)) -> Bool
 150 |     isCompatible fx
 151 |       = all (\fx' => fx.fix == fx'.fix
 152 |                   && fx.precedence == fx'.precedence
 153 |                   && fx.bindingInfo == fx'.bindingInfo) . map snd
 154 |
 155 |     -- Emits a warning using the fixity that we picked and the list of all conflicting fixities
 156 |     warnConflict : (picked : Name) -> (conflicts : List (Name, FixityInfo)) -> Core ()
 157 |     warnConflict fxName all =
 158 |       recordWarning $ GenericWarn opn.fc $ """
 159 |                    operator fixity is ambiguous, we are picking \{show fxName} out of :
 160 |                    \{unlines $ map (\(nm, fx) => " - \{show nm}, precedence level \{show fx.precedence}") $ toList all}
 161 |                    To remove this warning, use `%hide` with the fixity to remove
 162 |                    For example: %hide \{show fxName}
 163 |                    """
 164 |
 165 | checkConflictingBinding : Ref Ctxt Defs =>
 166 |                           Ref Syn SyntaxInfo =>
 167 |                           WithFC OpStr -> (foundFixity : FixityDeclarationInfo) ->
 168 |                           (usage : OperatorLHSInfo PTerm) -> (rhs : PTerm) -> Core ()
 169 | checkConflictingBinding opName foundFixity use_site rhs
 170 |     = if isCompatible foundFixity use_site
 171 |          then pure ()
 172 |          else throw $ OperatorBindingMismatch
 173 |              {print = byShow} opName.fc foundFixity use_site (opNameToEither opName.val) rhs !candidates
 174 |     where
 175 |
 176 |       isCompatible : FixityDeclarationInfo -> OperatorLHSInfo PTerm -> Bool
 177 |       isCompatible UndeclaredFixity (NoBinder lhs) = True
 178 |       isCompatible UndeclaredFixity _ = False
 179 |       isCompatible (DeclaredFixity fixInfo) (NoBinder lhs) = fixInfo.bindingInfo == NotBinding
 180 |       isCompatible (DeclaredFixity fixInfo) (BindType name ty) = fixInfo.bindingInfo == Typebind
 181 |       isCompatible (DeclaredFixity fixInfo) (BindExpr name expr) = fixInfo.bindingInfo == Autobind
 182 |       isCompatible (DeclaredFixity fixInfo) (BindExplicitType name type expr)
 183 |           = fixInfo.bindingInfo == Autobind
 184 |
 185 |       keepCompatibleBinding : BindingModifier -> (Name, GlobalDef) -> Core Bool
 186 |       keepCompatibleBinding compatibleBinder (name, def) = do
 187 |         fixities <- getFixityInfo (nameRoot name)
 188 |         let compatible = any (\(_, fx) => fx.bindingInfo == use_site.getBinder) fixities
 189 |         pure compatible
 190 |
 191 |       candidates : Core (List String)
 192 |       candidates = do let DeclaredFixity fxInfo = foundFixity
 193 |                         | _ => pure [] -- if there is no declared fixity we can't know what's
 194 |                                        -- supposed to go there.
 195 |                       Just (nm, cs) <- getSimilarNames {keepPredicate = Just (keepCompatibleBinding fxInfo.bindingInfo)} opName.val.toName
 196 |                         | Nothing => pure []
 197 |                       ns <- currentNS <$> get Ctxt
 198 |                       pure (showSimilarNames ns opName.val.toName nm cs)
 199 |
 200 | checkValidFixity : BindingModifier -> Fixity -> Nat -> Bool
 201 |
 202 | -- If the fixity declaration is not binding, there are no restrictions
 203 | checkValidFixity NotBinding _ _ = True
 204 |
 205 | -- If the fixity declaration is not binding, either typebind or autobind
 206 | -- the fixity can only be `infixr` with precedence `0`. We might want
 207 | -- to revisit that in the future, but as of right now we want to be
 208 | -- conservative and avoid abuse.
 209 | -- having multiple precedence levels would mean that if
 210 | -- =@ has higher precedence than -@
 211 | -- the expression (x : a) =@ b -@ (y : List a) =@ List b
 212 | -- would be bracketed as ((x : a) =@ b) -@ (y : List a) =@ List b
 213 | -- instead of (x : a) =@ (b -@ ((y : List a) =@ List b))
 214 | checkValidFixity _ InfixR 0 = True
 215 |
 216 | -- If it's binding but not infixr precedence 0, raise an error
 217 | checkValidFixity _ _ _ = False
 218 |
 219 | parameters (side : Side)
 220 |   toTokList : {auto s : Ref Syn SyntaxInfo} ->
 221 |               {auto c : Ref Ctxt Defs} ->
 222 |               PTerm -> Core (List (Tok ((OpStr, FixityDeclarationInfo), Maybe (OperatorLHSInfo PTerm)) PTerm))
 223 |   toTokList (POp fc (MkWithData _ l) opn r)
 224 |       = do (precInfo, fixInfo) <- checkConflictingFixities False opn
 225 |            unless (side == LHS) -- do not check for conflicting fixity on the LHS
 226 |                                 -- This is because we do not parse binders on the lhs
 227 |                                 -- and so, if we check, we will find uses of regular
 228 |                                 -- operator when binding is expected.
 229 |                   (checkConflictingBinding opn fixInfo l r)
 230 |            rtoks <- toTokList r
 231 |            pure (Expr l.getLhs :: Op fc opn.fc ((opn.val, fixInfo), Just l) precInfo :: rtoks)
 232 |   toTokList (PPrefixOp fc opn arg)
 233 |       = do (precInfo, fixInfo) <- checkConflictingFixities True opn
 234 |            rtoks <- toTokList arg
 235 |            pure (Op fc opn.fc ((opn.val, fixInfo), Nothing) precInfo :: rtoks)
 236 |   toTokList t = pure [Expr t]
 237 |
 238 | record BangData where
 239 |   constructor MkBangData
 240 |   nextName : Int
 241 |   bangNames : List (Name, FC, RawImp)
 242 |   mbNamespace : Maybe Namespace
 243 |
 244 | initBangs : Maybe Namespace -> BangData
 245 | initBangs = MkBangData 0 []
 246 |
 247 | addNS : Maybe Namespace -> Name -> Name
 248 | addNS (Just ns) n@(NS {}) = n
 249 | addNS (Just ns) n = NS ns n
 250 | addNS _ n = n
 251 |
 252 | bindFun : FC -> Maybe Namespace -> RawImp -> RawImp -> RawImp
 253 | bindFun fc ns ma f =
 254 |   let fc = virtualiseFC fc in
 255 |   IApp fc (IApp fc (IVar fc (addNS ns $ UN $ Basic ">>=")) ma) f
 256 |
 257 | seqFun : FC -> Maybe Namespace -> RawImp -> RawImp -> RawImp
 258 | seqFun fc ns ma mb =
 259 |   let fc = virtualiseFC fc in
 260 |   IApp fc (IApp fc (IVar fc (addNS ns (UN $ Basic ">>"))) ma) mb
 261 |
 262 | bindBangs : List (Name, FC, RawImp) -> Maybe Namespace -> RawImp -> RawImp
 263 | bindBangs [] ns tm = tm
 264 | bindBangs ((n, fc, btm) :: bs) ns tm
 265 |     = bindBangs bs ns
 266 |     $ bindFun fc ns btm
 267 |     $ ILam EmptyFC top Explicit (Just n) (Implicit fc False) tm
 268 |
 269 | idiomise : FC -> Maybe Namespace -> Maybe Namespace -> RawImp -> RawImp
 270 | idiomise fc dons mns (IAlternative afc u alts)
 271 |   = IAlternative afc (mapAltType (idiomise afc dons mns) u) (idiomise afc dons mns <$> alts)
 272 | idiomise fc dons mns (IApp afc f a)
 273 |   = let fc  = virtualiseFC fc
 274 |         app = UN $ Basic "<*>"
 275 |         nm  = maybe app (`NS` app) (mns <|> dons)
 276 |      in IApp fc (IApp fc (IVar fc nm) (idiomise afc dons mns f)) a
 277 | idiomise fc dons mns fn
 278 |   = let fc  = virtualiseFC fc
 279 |         pur = UN $ Basic "pure"
 280 |         nm  = maybe pur (`NS` pur) (mns <|> dons)
 281 |      in IApp fc (IVar fc nm) fn
 282 |
 283 | data Bang : Type where
 284 |
 285 | mutual
 286 |   desugarB : {auto s : Ref Syn SyntaxInfo} ->
 287 |              {auto b : Ref Bang BangData} ->
 288 |              {auto c : Ref Ctxt Defs} ->
 289 |              {auto m : Ref MD Metadata} ->
 290 |              {auto u : Ref UST UState} ->
 291 |              {auto o : Ref ROpts REPLOpts} ->
 292 |              Side -> List Name -> PTerm -> Core RawImp
 293 |   desugarB side ps (PRef fc x) = do
 294 |     let ns = mbNamespace !(get Bang)
 295 |     let pur = UN $ Basic "pure"
 296 |     case x == pur of -- implicitly add namespace to unqualified occurrences of `pure` in a qualified do-block
 297 |       False => pure $ IVar fc x
 298 |       True => pure $ IVar fc (maybe pur (`NS` pur) ns)
 299 |
 300 |   -- Desugaring forall n1, n2, n3 . s into
 301 |   -- {0 n1 : ?} -> {0 n2 : ?} -> {0 n3 : ?} -> s
 302 |   desugarB side ps (Forall (MkWithData _ (names, scope)))
 303 |         = desugarForallNames ps (forget names)
 304 |       where
 305 |         desugarForallNames : (ctx : List Name) ->
 306 |                              (names : List (WithFC Name)) -> Core RawImp
 307 |         desugarForallNames ctx [] = desugarB side ctx scope
 308 |         desugarForallNames ctx (x :: xs)
 309 |           = IPi x.fc erased Implicit (Just x.val)
 310 |           <$> desugarB side ps (PImplicit x.fc)
 311 |           <*> desugarForallNames (x.val :: ctx) xs
 312 |
 313 |   -- Desugaring (n1, n2, n3 : t) -> s into
 314 |   -- (n1 : t) -> (n2 : t) -> (n3 : t) -> s
 315 |   desugarB side ps
 316 |       (NewPi binder@(MkWithData _
 317 |           (MkPBinderScope (MkPBinder info (MkBasicMultiBinder rig names type)) scope)))
 318 |         = desugarMultiBinder ps (forget names)
 319 |       where
 320 |         desugarMultiBinder : (ctx : List Name) -> List (WithFC Name) -> Core RawImp
 321 |         desugarMultiBinder ctx []
 322 |           = desugarB side ctx scope
 323 |         desugarMultiBinder ctx (name :: xs)
 324 |           = let extendedCtx = name.val :: ps
 325 |             in IPi binder.fc rig
 326 |               <$> mapDesugarPiInfo extendedCtx info
 327 |               <*> (pure (Just name.val))
 328 |               <*> desugarB side ps type
 329 |               <*> desugarMultiBinder extendedCtx xs
 330 |
 331 |   desugarB side ps (PPi fc rig p mn argTy retTy)
 332 |       = let ps' = maybe ps (:: ps) mn in
 333 |             pure $ IPi fc rig !(traverse (desugar side ps') p)
 334 |                               mn !(desugarB side ps argTy)
 335 |                                  !(desugarB side ps' retTy)
 336 |   desugarB side ps (PLam fc rig p pat@(PRef prefFC n@(UN nm)) argTy scope)
 337 |       =  if isPatternVariable nm
 338 |            then do whenJust (isConcreteFC prefFC) $ \nfc
 339 |                      => addSemanticDecorations [(nfc, Bound, Just n)]
 340 |                    pure $ ILam fc rig !(traverse (desugar AnyExpr ps) p)
 341 |                            (Just n) !(desugarB AnyExpr ps argTy)
 342 |                                     !(desugar AnyExpr (n :: ps) scope)
 343 |            else pure $ ILam EmptyFC rig !(traverse (desugar AnyExpr ps) p)
 344 |                    (Just (MN "lamc" 0)) !(desugarB AnyExpr ps argTy) $
 345 |                  ICase fc [] (IVar EmptyFC (MN "lamc" 0)) (Implicit fc False)
 346 |                      [snd !(desugarClause ps True (MkPatClause fc pat scope []))]
 347 |   desugarB side ps (PLam fc rig p (PRef _ n@(MN {})) argTy scope)
 348 |       = pure $ ILam fc rig !(traverse (desugar AnyExpr ps) p)
 349 |                            (Just n) !(desugarB AnyExpr ps argTy)
 350 |                                     !(desugar AnyExpr (n :: ps) scope)
 351 |   desugarB side ps (PLam fc rig p (PImplicit _) argTy scope)
 352 |       = pure $ ILam fc rig !(traverse (desugar AnyExpr ps) p)
 353 |                            Nothing !(desugarB AnyExpr ps argTy)
 354 |                                    !(desugar AnyExpr ps scope)
 355 |   desugarB side ps (PLam fc rig p pat argTy scope)
 356 |       = pure $ ILam EmptyFC rig !(traverse (desugar AnyExpr ps) p)
 357 |                    (Just (MN "lamc" 0)) !(desugarB AnyExpr ps argTy) $
 358 |                  ICase fc [] (IVar EmptyFC (MN "lamc" 0)) (Implicit fc False)
 359 |                      [snd !(desugarClause ps True (MkPatClause fc pat scope []))]
 360 |   desugarB side ps (PLet fc rig (PRef prefFC n) nTy nVal scope [])
 361 |       = do whenJust (isConcreteFC prefFC) $ \nfc =>
 362 |              addSemanticDecorations [(nfc, Bound, Just n)]
 363 |            pure $ ILet fc prefFC rig n !(desugarB side ps nTy) !(desugarB side ps nVal)
 364 |                                        !(desugar side (n :: ps) scope)
 365 |   desugarB side ps (PLet fc rig pat nTy nVal scope alts)
 366 |       = pure $ ICase fc [] !(desugarB side ps nVal) !(desugarB side ps nTy)
 367 |                         !(traverse (map snd . desugarClause ps True)
 368 |                             (MkPatClause fc pat scope [] :: alts))
 369 |   desugarB side ps (PCase fc opts scr cls)
 370 |       = do opts <- traverse (desugarFnOpt ps) opts
 371 |            scr <- desugarB side ps scr
 372 |            let scrty = Implicit (virtualiseFC fc) False
 373 |            cls <- traverse (map snd . desugarClause ps True) cls
 374 |            pure $ ICase fc opts scr scrty cls
 375 |   desugarB side ps (PLocal fc xs scope)
 376 |       = let ps' = definedIn (map val xs) ++ ps in
 377 |             pure $ ILocal fc (concat !(traverse (desugarDecl ps') xs))
 378 |                              !(desugar side ps' scope)
 379 |   desugarB side ps (PApp pfc (PUpdate fc fs) rec)
 380 |       = pure $ IUpdate pfc !(traverse (desugarUpdate side ps) fs)
 381 |                            !(desugarB side ps rec)
 382 |   desugarB side ps (PUpdate fc fs)
 383 |       = desugarB side ps
 384 |       $ let vfc = virtualiseFC fc in
 385 |       PLam vfc top Explicit (PRef vfc (MN "rec" 0)) (PImplicit vfc)
 386 |       $ PApp vfc (PUpdate fc fs) (PRef vfc (MN "rec" 0))
 387 |   desugarB side ps (PApp fc x y)
 388 |       = pure $ IApp fc !(desugarB side ps x) !(desugarB side ps y)
 389 |   desugarB side ps (PAutoApp fc x y)
 390 |       = pure $ IAutoApp fc !(desugarB side ps x) !(desugarB side ps y)
 391 |   desugarB side ps (PWithApp fc x y)
 392 |       = pure $ IWithApp fc !(desugarB side ps x) !(desugarB side ps y)
 393 |   desugarB side ps (PNamedApp fc x argn y)
 394 |       = pure $ INamedApp fc !(desugarB side ps x) argn !(desugarB side ps y)
 395 |   desugarB side ps (PDelayed fc r ty)
 396 |       = pure $ IDelayed fc r !(desugarB side ps ty)
 397 |   desugarB side ps (PDelay fc tm)
 398 |       = pure $ IDelay fc !(desugarB side ps tm)
 399 |   desugarB side ps (PForce fc tm)
 400 |       = pure $ IForce fc !(desugarB side ps tm)
 401 |   desugarB side ps (PEq fc l r)
 402 |       = do l' <- desugarB side ps l
 403 |            r' <- desugarB side ps r
 404 |            pure $ IAlternative fc FirstSuccess
 405 |                      [apply (IVar fc (UN $ Basic "===")) [l', r'],
 406 |                       apply (IVar fc (UN $ Basic "~=~")) [l', r']]
 407 |   desugarB side ps (PBracketed fc e) = desugarB side ps e
 408 |   desugarB side ps (POp fc l op r)
 409 |       = do ts <- toTokList side (POp fc l op r)
 410 |            tree <- parseOps @{interpName} @{showWithLoc} ts
 411 |            unop <- desugarTree side ps (mapFst (\((x, _), y) => (x, y)) tree)
 412 |            desugarB side ps unop
 413 |   desugarB side ps (PPrefixOp fc op arg)
 414 |       = do ts <- toTokList side (PPrefixOp fc op arg)
 415 |            tree <- parseOps @{interpName} @{showWithLoc} ts
 416 |            unop <- desugarTree side ps (mapFst (\((x, _), y) => (x, y)) tree)
 417 |            desugarB side ps unop
 418 |   desugarB side ps (PSectionL fc op arg)
 419 |       = do syn <- get Syn
 420 |            -- It might actually be a prefix argument rather than a section
 421 |            -- so check that first, otherwise desugar as a lambda
 422 |            case lookupName op.val.toName (prefixes syn) of
 423 |                 [] =>
 424 |                     desugarB side ps
 425 |                         (PLam fc top Explicit (PRef fc (MN "arg" 0)) (PImplicit fc)
 426 |                             (POp fc (MkFCVal op.fc (NoBinder (PRef fc (MN "arg" 0)))) op arg))
 427 |                 (prec :: _) => desugarB side ps (PPrefixOp fc op arg)
 428 |   desugarB side ps (PSectionR fc arg op)
 429 |       = desugarB side ps
 430 |           (PLam fc top Explicit (PRef fc (MN "arg" 0)) (PImplicit fc)
 431 |               (POp fc (MkFCVal op.fc $ NoBinder arg) op (PRef fc (MN "arg" 0))))
 432 |   desugarB side ps (PSearch fc depth) = pure $ ISearch fc depth
 433 |   desugarB side ps (PPrimVal fc (BI x))
 434 |       = case !fromIntegerName of
 435 |              Nothing =>
 436 |                 pure $ IAlternative fc (UniqueDefault (IPrimVal fc (BI x)))
 437 |                                 [IPrimVal fc (BI x),
 438 |                                  IPrimVal fc (I (fromInteger x))]
 439 |              Just fi =>
 440 |                let vfc = virtualiseFC fc in
 441 |                pure $ IApp vfc (IVar vfc fi) (IPrimVal fc (BI x))
 442 |   desugarB side ps (PPrimVal fc (Ch x))
 443 |       = case !fromCharName of
 444 |              Nothing =>
 445 |                 pure $ IPrimVal fc (Ch x)
 446 |              Just f =>
 447 |                let vfc = virtualiseFC fc in
 448 |                pure $ IApp vfc (IVar vfc f) (IPrimVal fc (Ch x))
 449 |   desugarB side ps (PPrimVal fc (Db x))
 450 |       = case !fromDoubleName of
 451 |              Nothing =>
 452 |                 pure $ IPrimVal fc (Db x)
 453 |              Just f =>
 454 |                let vfc = virtualiseFC fc in
 455 |                pure $ IApp vfc (IVar vfc f) (IPrimVal fc (Db x))
 456 |   desugarB side ps (PPrimVal fc x) = pure $ IPrimVal fc x
 457 |   desugarB side ps (PQuote fc tm)
 458 |       = do let q = IQuote fc !(desugarB side ps tm)
 459 |            case side of
 460 |                 AnyExpr => pure $ maybeIApp fc !fromTTImpName q
 461 |                 _ => pure q
 462 |   desugarB side ps (PQuoteName fc n)
 463 |       = do let q = IQuoteName fc n
 464 |            case side of
 465 |                 AnyExpr => pure $ maybeIApp fc !fromNameName q
 466 |                 _ => pure q
 467 |   desugarB side ps (PQuoteDecl fc x)
 468 |       = do xs <- traverse (desugarDecl ps) x
 469 |            let dls = IQuoteDecl fc (concat xs)
 470 |            case side of
 471 |                 AnyExpr => pure $ maybeIApp fc !fromDeclsName dls
 472 |                 _ => pure dls
 473 |   desugarB side ps (PUnquote fc tm)
 474 |       = pure $ IUnquote fc !(desugarB side ps tm)
 475 |   desugarB side ps (PRunElab fc tm)
 476 |       = pure $ IRunElab fc True !(desugarB side ps tm)
 477 |   desugarB side ps (PHole fc br holename)
 478 |       = do when br $ update Syn { bracketholes $= ((UN (Basic holename)) ::) }
 479 |            pure $ IHole fc holename
 480 |   desugarB side ps (PType fc) = pure $ IType fc
 481 |   desugarB side ps (PAs fc nameFC vname pattern)
 482 |       = pure $ IAs fc nameFC UseRight vname !(desugarB side ps pattern)
 483 |   desugarB side ps (PDotted fc x)
 484 |       = pure $ IMustUnify fc UserDotted !(desugarB side ps x)
 485 |   desugarB side ps (PImplicit fc) = pure $ Implicit fc True
 486 |   desugarB side ps (PInfer fc)
 487 |     = do when (side == LHS) $
 488 |            throw (GenericMsg fc "? is not a valid pattern")
 489 |          pure $ Implicit fc False
 490 |   desugarB side ps (PMultiline fc hashtag indent lines)
 491 |       = pure $ maybeIApp fc !fromStringName !(expandString side ps fc hashtag !(trimMultiline fc indent lines))
 492 |
 493 |   -- We only add `fromString` if we are looking at a plain string literal.
 494 |   -- Interpolated string literals don't have a `fromString` call since they
 495 |   -- are always concatenated with other strings and therefore can never use
 496 |   -- another `fromString` implementation that differs from `id`.
 497 |   desugarB side ps (PString fc hashtag [])
 498 |       = pure $ maybeIApp fc !fromStringName (IPrimVal fc (Str ""))
 499 |   desugarB side ps (PString fc hashtag [StrLiteral fc' str])
 500 |       = case unescape hashtag str of
 501 |              Just str => pure $ maybeIApp fc !fromStringName (IPrimVal fc' (Str str))
 502 |              Nothing => throw (GenericMsg fc "Invalid escape sequence: \{show str}")
 503 |   desugarB side ps (PString fc hashtag strs)
 504 |       = expandString side ps fc hashtag strs
 505 |
 506 |   desugarB side ps (PDoBlock fc ns block)
 507 |       = expandDo side ps fc ns block
 508 |   desugarB side ps (PBang fc term)
 509 |       = do itm <- desugarB side ps term
 510 |            bs <- get Bang
 511 |            let bn = MN "bind" (nextName bs)
 512 |            put Bang ({ nextName $= (+1),
 513 |                        bangNames $= ((bn, fc, itm) ::)
 514 |                      } bs)
 515 |            pure (IVar (virtualiseFC fc) bn)
 516 |   desugarB side ps (PIdiom fc ns term)
 517 |       = do itm <- desugarB side ps term
 518 |            logRaw "desugar.idiom" 10 "Desugaring idiom for" itm
 519 |            let val = idiomise fc (mbNamespace !(get Bang)) ns itm
 520 |            logRaw "desugar.idiom" 10 "Desugared to" val
 521 |            pure val
 522 |   desugarB side ps (PList fc nilFC args)
 523 |       = expandList side ps nilFC args
 524 |   desugarB side ps (PSnocList fc nilFC args)
 525 |       = expandSnocList side ps nilFC args
 526 |   desugarB side ps (PPair fc l r)
 527 |       = do l' <- desugarB side ps l
 528 |            r' <- desugarB side ps r
 529 |            let pval = apply (IVar fc mkpairname) [l', r']
 530 |            pure $ IAlternative fc (UniqueDefault pval)
 531 |                   [apply (IVar fc pairname) [l', r'], pval]
 532 |   desugarB side ps (PDPair fc opFC (PRef nameFC n@(UN _)) (PImplicit _) r)
 533 |       = do r' <- desugarB side ps r
 534 |            let pval = apply (IVar opFC mkdpairname) [IVar nameFC n, r']
 535 |            let vfc = virtualiseFC nameFC
 536 |            whenJust (isConcreteFC nameFC) $ \nfc =>
 537 |              addSemanticDefault (nfc, Bound, Just n)
 538 |            pure $ IAlternative fc (UniqueDefault pval)
 539 |                   [apply (IVar opFC dpairname)
 540 |                       [Implicit vfc False,
 541 |                        ILam nameFC top Explicit (Just n) (Implicit vfc False) r'],
 542 |                    pval]
 543 |   desugarB side ps (PDPair fc opFC (PRef namefc n@(UN _)) ty r)
 544 |       = do ty' <- desugarB side ps ty
 545 |            r' <- desugarB side ps r
 546 |            pure $ apply (IVar opFC dpairname)
 547 |                         [ty', ILam namefc top Explicit (Just n) ty' r']
 548 |   desugarB side ps (PDPair fc opFC l (PImplicit _) r)
 549 |       = do l' <- desugarB side ps l
 550 |            r' <- desugarB side ps r
 551 |            pure $ apply (IVar opFC mkdpairname) [l', r']
 552 |   desugarB side ps (PDPair fc opFC l ty r)
 553 |       = throw (GenericMsg fc "Invalid dependent pair type")
 554 |   desugarB side ps (PUnit fc)
 555 |       = pure $ IAlternative fc (UniqueDefault (IVar fc (UN $ Basic "MkUnit")))
 556 |                [IVar fc (UN $ Basic "Unit"),
 557 |                 IVar fc (UN $ Basic "MkUnit")]
 558 |   desugarB side ps (PIfThenElse fc x t e)
 559 |       = let fc = virtualiseFC fc in
 560 |         pure $ ICase fc [] !(desugarB side ps x) (IVar fc (UN $ Basic "Bool"))
 561 |                    [PatClause fc (IVar fc (UN $ Basic "True")) !(desugar side ps t),
 562 |                     PatClause fc (IVar fc (UN $ Basic "False")) !(desugar side ps e)]
 563 |   desugarB side ps (PComprehension fc ret conds) = do
 564 |         let ns = mbNamespace !(get Bang)
 565 |         desugarB side ps (PDoBlock fc ns (map (guard ns) conds ++ [toPure ns ret]))
 566 |     where
 567 |       guard : Maybe Namespace -> PDo -> PDo
 568 |       guard ns (DoExp fc tm)
 569 |        = DoExp fc (PApp fc (PRef fc (mbApplyNS ns $ UN $ Basic "guard")) tm)
 570 |       guard ns d = d
 571 |
 572 |       toPure : Maybe Namespace -> PTerm -> PDo
 573 |       toPure ns tm = DoExp fc (PApp fc (PRef fc (mbApplyNS ns $ UN $ Basic "pure")) tm)
 574 |   desugarB side ps (PRewrite fc rule tm)
 575 |       = pure $ IRewrite fc !(desugarB side ps rule) !(desugarB side ps tm)
 576 |   desugarB side ps (PRange fc start next end)
 577 |       = let fc = virtualiseFC fc in
 578 |         desugarB side ps $ case next of
 579 |            Nothing => papply fc (PRef fc (UN $ Basic "rangeFromTo")) [start,end]
 580 |            Just n  => papply fc (PRef fc (UN $ Basic "rangeFromThenTo")) [start, n, end]
 581 |   desugarB side ps (PRangeStream fc start next)
 582 |       = let fc = virtualiseFC fc in
 583 |         desugarB side ps $ case next of
 584 |            Nothing => papply fc (PRef fc (UN $ Basic "rangeFrom")) [start]
 585 |            Just n  => papply fc (PRef fc (UN $ Basic "rangeFromThen")) [start, n]
 586 |   desugarB side ps (PUnifyLog fc lvl tm)
 587 |       = pure $ IUnifyLog fc lvl !(desugarB side ps tm)
 588 |   desugarB side ps (PPostfixApp fc rec projs)
 589 |       = desugarB side ps
 590 |       $ foldl (\x, (fc, proj) => PApp fc (PRef fc proj) x) rec projs
 591 |   desugarB side ps (PPostfixAppPartial fc projs)
 592 |       = do let vfc = virtualiseFC fc
 593 |            let var = PRef vfc (MN "paRoot" 0)
 594 |            desugarB side ps $
 595 |              PLam fc top Explicit var (PImplicit vfc) $
 596 |                foldl (\r, (fc, proj) => PApp fc (PRef fc proj) r) var projs
 597 |   desugarB side ps (PWithUnambigNames fc ns rhs)
 598 |       = IWithUnambigNames fc ns <$> desugarB side ps rhs
 599 |
 600 |   desugarUpdate : {auto s : Ref Syn SyntaxInfo} ->
 601 |                   {auto b : Ref Bang BangData} ->
 602 |                   {auto c : Ref Ctxt Defs} ->
 603 |                   {auto u : Ref UST UState} ->
 604 |                   {auto m : Ref MD Metadata} ->
 605 |                   {auto o : Ref ROpts REPLOpts} ->
 606 |                   Side -> List Name -> PFieldUpdate -> Core IFieldUpdate
 607 |   desugarUpdate side ps (PSetField p v)
 608 |       = pure (ISetField p !(desugarB side ps v))
 609 |   desugarUpdate side ps (PSetFieldApp p v)
 610 |       = pure (ISetFieldApp p !(desugarB side ps v))
 611 |
 612 |   expandList : {auto s : Ref Syn SyntaxInfo} ->
 613 |                {auto b : Ref Bang BangData} ->
 614 |                {auto c : Ref Ctxt Defs} ->
 615 |                {auto u : Ref UST UState} ->
 616 |                {auto m : Ref MD Metadata} ->
 617 |                {auto o : Ref ROpts REPLOpts} ->
 618 |                Side -> List Name ->
 619 |                (nilFC : FC) -> List (FC, PTerm) -> Core RawImp
 620 |   expandList side ps nilFC [] = pure (IVar nilFC (UN $ Basic "Nil"))
 621 |   expandList side ps nilFC ((consFC, x) :: xs)
 622 |       = pure $ apply (IVar consFC (UN $ Basic "::"))
 623 |                 [!(desugarB side ps x), !(expandList side ps nilFC xs)]
 624 |
 625 |   expandSnocList
 626 |              : {auto s : Ref Syn SyntaxInfo} ->
 627 |                {auto b : Ref Bang BangData} ->
 628 |                {auto c : Ref Ctxt Defs} ->
 629 |                {auto u : Ref UST UState} ->
 630 |                {auto m : Ref MD Metadata} ->
 631 |                {auto o : Ref ROpts REPLOpts} ->
 632 |                Side -> List Name -> (nilFC : FC) ->
 633 |                SnocList (FC, PTerm) -> Core RawImp
 634 |   expandSnocList side ps nilFC [<] = pure (IVar nilFC (UN $ Basic "Lin"))
 635 |   expandSnocList side ps nilFC (xs :< (consFC, x))
 636 |       = pure $ apply (IVar consFC (UN $ Basic ":<"))
 637 |                 [!(expandSnocList side ps nilFC xs) , !(desugarB side ps x)]
 638 |
 639 |   maybeIApp : FC -> Maybe Name -> RawImp -> RawImp
 640 |   maybeIApp fc nm tm
 641 |       = case nm of
 642 |              Nothing => tm
 643 |              Just f =>
 644 |                let fc = virtualiseFC fc in
 645 |                IApp fc (IVar fc f) tm
 646 |
 647 |   expandString : {auto s : Ref Syn SyntaxInfo} ->
 648 |                  {auto b : Ref Bang BangData} ->
 649 |                  {auto c : Ref Ctxt Defs} ->
 650 |                  {auto m : Ref MD Metadata} ->
 651 |                  {auto u : Ref UST UState} ->
 652 |                  {auto o : Ref ROpts REPLOpts} ->
 653 |                  Side -> List Name -> FC -> Nat -> List PStr -> Core RawImp
 654 |   expandString side ps fc hashtag xs
 655 |     = do xs <- traverse toRawImp (filter notEmpty $ mergeStrLit xs)
 656 |          pure $ case xs of
 657 |            [] => IPrimVal fc (Str "")
 658 |            (_ :: _) =>
 659 |              let vfc = virtualiseFC fc in
 660 |              IApp vfc
 661 |                (INamedApp vfc
 662 |                  (IVar vfc (NS preludeNS $ UN $ Basic "concat"))
 663 |                  (UN $ Basic "t")
 664 |                  (IVar vfc (NS preludeNS $ UN $ Basic "List")))
 665 |                (strInterpolate xs)
 666 |     where
 667 |       toRawImp : PStr -> Core RawImp
 668 |       toRawImp (StrLiteral fc str) =
 669 |         case unescape hashtag str of
 670 |              Just str => pure $ IPrimVal fc (Str str)
 671 |              Nothing => throw (GenericMsg fc "Invalid escape sequence: \{show str}")
 672 |       toRawImp (StrInterp fc tm) = desugarB side ps tm
 673 |
 674 |       -- merge neighbouring StrLiteral
 675 |       mergeStrLit : List PStr -> List PStr
 676 |       mergeStrLit xs = case List.spanBy isStrLiteral xs of
 677 |         ([], []) => []
 678 |         ([], x::xs) => x :: mergeStrLit xs
 679 |         (lits@(_::_), xs) =>
 680 |           -- TODO: merge all the FCs of the merged literals!
 681 |           let fc  = fst $ head lits in
 682 |           let lit = fastConcat $ snd <$> lits in
 683 |           StrLiteral fc lit :: mergeStrLit xs
 684 |
 685 |       notEmpty : PStr -> Bool
 686 |       notEmpty (StrLiteral _ str) = str /= ""
 687 |       notEmpty (StrInterp {}) = True
 688 |
 689 |       strInterpolate : List RawImp -> RawImp
 690 |       strInterpolate []
 691 |         = IVar EmptyFC nilName
 692 |       strInterpolate (x :: xs)
 693 |         = let xFC = virtualiseFC (getFC x) in
 694 |           apply (IVar xFC consName)
 695 |           [ IApp xFC (IVar EmptyFC interpolateName)
 696 |                      x
 697 |           , strInterpolate xs
 698 |           ]
 699 |
 700 |   trimMultiline : FC -> Nat -> List (List PStr) -> Core (List PStr)
 701 |   trimMultiline fc indent lines
 702 |       = do lines <- trimLast fc lines
 703 |            lines <- traverse (trimLeft indent) lines
 704 |            pure $ concat $ dropLastNL lines
 705 |
 706 |     where
 707 |       trimLast : FC -> List (List PStr) -> Core (List (List PStr))
 708 |       trimLast fc lines with (snocList lines)
 709 |         trimLast fc [] | Empty = throw $ BadMultiline fc "Expected new line"
 710 |         trimLast _ (initLines `snoc` []) | Snoc [] initLines _ = pure lines
 711 |         trimLast _ (initLines `snoc` [StrLiteral fc str]) | Snoc [(StrLiteral {})] initLines _
 712 |             = if any (not . isSpace) (fastUnpack str)
 713 |                      then throw $ BadMultiline fc "Closing delimiter of multiline strings cannot be preceded by non-whitespace characters"
 714 |                      else pure initLines
 715 |         trimLast _ (initLines `snoc` xs) | Snoc xs initLines _
 716 |             = let fc = fromMaybe fc $ findBy isStrInterp xs in
 717 |                   throw $ BadMultiline fc "Closing delimiter of multiline strings cannot be preceded by non-whitespace characters"
 718 |
 719 |       trimLeft : Nat -> List PStr -> Core (List PStr)
 720 |       trimLeft indent [] = pure []
 721 |       trimLeft indent [StrLiteral fc str]
 722 |           = let (trimed, rest) = splitAt indent (fastUnpack str) in
 723 |             if any (not . isSpace) trimed
 724 |               then throw $ BadMultiline fc "Line is less indented than the closing delimiter"
 725 |               else let str = if null rest then "\n" else fastPack rest in
 726 |                    pure [StrLiteral fc str]
 727 |       trimLeft indent (StrLiteral fc str :: xs)
 728 |           = let (trimed, rest) = splitAt indent (fastUnpack str) in
 729 |             if any (not . isSpace) trimed || length trimed < indent
 730 |               then throw $ BadMultiline fc "Line is less indented than the closing delimiter"
 731 |              else pure $ (StrLiteral fc (fastPack rest))::xs
 732 |       trimLeft indent xs = throw $ BadMultiline fc "Line is less indented than the closing delimiter"
 733 |
 734 |       mapLast : (a -> a) -> List a -> List a
 735 |       mapLast f [] = []
 736 |       mapLast f [x] = [f x]
 737 |       mapLast f (x :: xs) = x :: mapLast f xs
 738 |
 739 |       dropLastNL : List (List PStr) -> List (List PStr)
 740 |       dropLastNL
 741 |           = mapLast $ mapLast $
 742 |               \case StrLiteral fc str => StrLiteral fc (fst $ break isNL str)
 743 |                     other => other
 744 |
 745 |   expandDo : {auto s : Ref Syn SyntaxInfo} ->
 746 |              {auto c : Ref Ctxt Defs} ->
 747 |              {auto u : Ref UST UState} ->
 748 |              {auto m : Ref MD Metadata} ->
 749 |              {auto o : Ref ROpts REPLOpts} ->
 750 |              Side -> List Name -> FC -> Maybe Namespace -> List PDo -> Core RawImp
 751 |   expandDo side ps fc ns [] = throw (GenericMsg fc "Do block cannot be empty")
 752 |   expandDo side ps _ ns [DoExp fc tm] = desugarDo side ps ns tm
 753 |   expandDo side ps fc ns [e]
 754 |       = throw (GenericMsg (getLoc e)
 755 |                   "Last statement in do block must be an expression")
 756 |   expandDo side ps topfc ns (DoExp fc tm :: rest)
 757 |       = do tm' <- desugarDo side ps ns tm
 758 |            rest' <- expandDo side ps topfc ns rest
 759 |            pure $ seqFun fc ns tm' rest'
 760 |   expandDo side ps topfc ns (DoBind fc nameFC n rig ty tm :: rest)
 761 |       = do tm' <- desugarDo side ps ns tm
 762 |            whenJust (isConcreteFC nameFC) $ \nfc => addSemanticDecorations [(nfc, Bound, Just n)]
 763 |            ty' <- maybe (pure $ Implicit (virtualiseFC fc) False)
 764 |                         (\ty => desugarDo side ps ns ty) ty
 765 |            rest' <- expandDo side ps topfc ns rest
 766 |            pure $ bindFun fc ns tm'
 767 |                 $ ILam nameFC rig Explicit (Just n) ty' rest'
 768 |   expandDo side ps topfc ns (DoBindPat fc pat ty exp alts :: rest)
 769 |       = do pat' <- desugarDo LHS ps ns pat
 770 |            (newps, bpat) <- bindNames False pat'
 771 |            exp' <- desugarDo side ps ns exp
 772 |            alts' <- traverse (map snd . desugarClause ps True) alts
 773 |            let ps' = newps ++ ps
 774 |            let fcOriginal = fc
 775 |            let fc = virtualiseFC fc
 776 |            let patFC = virtualiseFC (getFC bpat)
 777 |            ty' <- maybe (pure $ Implicit fc False)
 778 |                         (\ty => desugarDo side ps ns ty) ty
 779 |            rest' <- expandDo side ps' topfc ns rest
 780 |            pure $ bindFun fc ns exp'
 781 |                 $ ILam EmptyFC top Explicit (Just (MN "_" 0))
 782 |                           ty'
 783 |                           (ICase fc [] (IVar patFC (MN "_" 0))
 784 |                                (Implicit fc False)
 785 |                                (PatClause fcOriginal bpat rest'
 786 |                                   :: alts'))
 787 |   expandDo side ps topfc ns (DoLet fc lhsFC n rig ty tm :: rest)
 788 |       = do b <- newRef Bang (initBangs ns)
 789 |            tm' <- desugarB side ps tm
 790 |            ty' <- desugarDo side ps ns ty
 791 |            rest' <- expandDo side ps topfc ns rest
 792 |            whenJust (isConcreteFC lhsFC) $ \nfc =>
 793 |              addSemanticDecorations [(nfc, Bound, Just n)]
 794 |            let bind = ILet fc lhsFC rig n ty' tm' rest'
 795 |            bd <- get Bang
 796 |            pure $ bindBangs (bangNames bd) ns bind
 797 |   expandDo side ps topfc ns (DoLetPat fc pat ty tm alts :: rest)
 798 |       = do b <- newRef Bang (initBangs ns)
 799 |            pat' <- desugarDo LHS ps ns pat
 800 |            ty' <- desugarDo side ps ns ty
 801 |            (newps, bpat) <- bindNames False pat'
 802 |            tm' <- desugarB side ps tm
 803 |            alts' <- traverse (map snd . desugarClause ps True) alts
 804 |            let ps' = newps ++ ps
 805 |            rest' <- expandDo side ps' topfc ns rest
 806 |            bd <- get Bang
 807 |            let fc = virtualiseFC fc
 808 |            pure $ bindBangs (bangNames bd) ns $
 809 |                     ICase fc [] tm' ty'
 810 |                        (PatClause fc bpat rest'
 811 |                                   :: alts')
 812 |   expandDo side ps topfc ns (DoLetLocal fc decls :: rest)
 813 |       = do decls' <- traverse (desugarDecl ps) decls
 814 |            rest' <- expandDo side ps topfc ns rest
 815 |            pure $ ILocal fc (concat decls') rest'
 816 |   expandDo side ps topfc ns (DoRewrite fc rule :: rest)
 817 |       = do rule' <- desugarDo side ps ns rule
 818 |            rest' <- expandDo side ps topfc ns rest
 819 |            pure $ IRewrite fc rule' rest'
 820 |
 821 |   -- Replace all operator by function application
 822 |   desugarTree : Side -> List Name -> Tree (OpStr, Maybe $ OperatorLHSInfo PTerm) PTerm ->
 823 |                 Core PTerm
 824 |   desugarTree side ps (Infix loc eqFC (OpSymbols $ UN $ Basic "=", _) l r) -- special case since '=' is special syntax
 825 |       = pure $ PEq eqFC !(desugarTree side ps l) !(desugarTree side ps r)
 826 |
 827 |   desugarTree side ps (Infix loc _ (OpSymbols $ UN $ Basic "$", _) l r) -- special case since '$' is special syntax
 828 |       = do l' <- desugarTree side ps l
 829 |            r' <- desugarTree side ps r
 830 |            pure (PApp loc l' r')
 831 |   -- normal operators
 832 |   desugarTree side ps (Infix loc opFC (op, Just (NoBinder lhs)) l r)
 833 |       = do l' <- desugarTree side ps l
 834 |            r' <- desugarTree side ps r
 835 |            pure (PApp loc (PApp loc (PRef opFC op.toName) l') r')
 836 |   -- (x : ty) =@ f x ==>> (=@) ty (\x : ty => f x)
 837 |   desugarTree side ps (Infix loc opFC (op, Just (BindType pat lhs)) l r)
 838 |       = do l' <- desugarTree side ps l
 839 |            body <- desugarTree side ps r
 840 |            pure $ PApp loc (PApp loc (PRef opFC op.toName) l')
 841 |                       (PLam loc top Explicit pat l' body)
 842 |   -- (x := exp) =@ f x ==>> (=@) exp (\x : ? => f x)
 843 |   desugarTree side ps (Infix loc opFC (op, Just (BindExpr pat lhs)) l r)
 844 |       = do l' <- desugarTree side ps l
 845 |            body <- desugarTree side ps r
 846 |            pure $ PApp loc (PApp loc (PRef opFC op.toName) l')
 847 |                       (PLam loc top Explicit pat (PInfer opFC) body)
 848 |
 849 |   -- (x : ty := exp) =@ f x ==>> (=@) exp (\x : ty => f x)
 850 |   desugarTree side ps (Infix loc opFC (op, Just (BindExplicitType pat ty expr)) l r)
 851 |       = do l' <- desugarTree side ps l
 852 |            body <- desugarTree side ps r
 853 |            pure $ PApp loc (PApp loc (PRef opFC op.toName) l')
 854 |                       (PLam loc top Explicit pat ty body)
 855 |   desugarTree side ps (Infix loc opFC (op, Nothing) _ r)
 856 |       = throw $ InternalError "illegal fixity: Parsed as infix but no binding information"
 857 |
 858 |   -- negation is a special case, since we can't have an operator with
 859 |   -- two meanings otherwise
 860 |   --
 861 |   -- Note: In case of negated signed integer literals, we apply the
 862 |   -- negation directly. Otherwise, the literal might be
 863 |   -- truncated to 0 before being passed on to `negate`.
 864 |   desugarTree side ps (Pre loc opFC (OpSymbols $ UN $ Basic "-", _) $ Leaf $ PPrimVal fc c)
 865 |     = let newFC    = fromMaybe EmptyFC (mergeFC loc fc)
 866 |           continue = desugarTree side ps . Leaf . PPrimVal newFC
 867 |        in case c of
 868 |             I   x => continue $ I (-x)
 869 |             I8  x => continue $ I8 (-x)
 870 |             I16 x => continue $ I16 (-x)
 871 |             I32 x => continue $ I32 (-x)
 872 |             I64 x => continue $ I64 (-x)
 873 |             BI  x => continue $ BI (-x)
 874 |
 875 |             -- not a signed integer literal. proceed by desugaring
 876 |             -- and applying to `negate`.
 877 |             _     => do arg' <- desugarTree side ps (Leaf $ PPrimVal fc c)
 878 |                         pure (PApp loc (PRef opFC (UN $ Basic "negate")) arg')
 879 |
 880 |   desugarTree side ps (Pre loc opFC (OpSymbols $ UN $ Basic "-", _) arg)
 881 |     = do arg' <- desugarTree side ps arg
 882 |          pure (PApp loc (PRef opFC (UN $ Basic "negate")) arg')
 883 |
 884 |   desugarTree side ps (Pre loc opFC (op, _) arg)
 885 |       = do arg' <- desugarTree side ps arg
 886 |            pure (PApp loc (PRef opFC op.toName) arg')
 887 |   desugarTree side ps (Leaf t) = pure t
 888 |
 889 |   desugarType : {auto s : Ref Syn SyntaxInfo} ->
 890 |                 {auto c : Ref Ctxt Defs} ->
 891 |                 {auto u : Ref UST UState} ->
 892 |                 {auto m : Ref MD Metadata} ->
 893 |                 {auto o : Ref ROpts REPLOpts} ->
 894 |                 List Name -> PTypeDecl -> Core (List ImpTy)
 895 |   desugarType ps pty@(MkWithData _ $ MkPTy names d ty)
 896 |       = flip Core.traverse (forget names) $ \(doc, n) : (String, WithFC Name) =>
 897 |           do addDocString n.val (d ++ doc)
 898 |              syn <- get Syn
 899 |              pure $ Mk [pty.fc, n] !(bindTypeNames pty.fc (usingImpl syn)
 900 |                                                  ps !(desugar AnyExpr ps ty))
 901 |
 902 |   -- Attempt to get the function name from a function pattern. For example,
 903 |   --   - given the pattern 'f x y', getClauseFn would return 'f'.
 904 |   --   - given the pattern 'x == y', getClausefn would return '=='.
 905 |   getClauseFn : RawImp -> Core Name
 906 |   getClauseFn (IVar _ n) = pure n
 907 |   getClauseFn (IApp _ f _) = getClauseFn f
 908 |   getClauseFn (IWithApp _ f _) = getClauseFn f
 909 |   getClauseFn (IAutoApp _ f _) = getClauseFn f
 910 |   getClauseFn (INamedApp _ f _ _) = getClauseFn f
 911 |   getClauseFn tm = throw $ GenericMsg (getFC tm) "Head term in pattern must be a function name"
 912 |
 913 |   desugarLHS : {auto s : Ref Syn SyntaxInfo} ->
 914 |                {auto c : Ref Ctxt Defs} ->
 915 |                {auto m : Ref MD Metadata} ->
 916 |                {auto u : Ref UST UState} ->
 917 |                {auto o : Ref ROpts REPLOpts} ->
 918 |                List Name -> (arg : Bool) -> PTerm ->
 919 |                Core (IMaybe (not arg) Name, List Name, RawImp)
 920 |                   -- ^ we only look for the head name of the expression...
 921 |                   --   if we are actually looking at a headed thing!
 922 |   desugarLHS ps arg lhs =
 923 |     do rawlhs <- desugar LHS ps lhs
 924 |        inm <- iunless arg $ getClauseFn rawlhs
 925 |        (bound, blhs) <- bindNames arg rawlhs
 926 |        log "desugar.lhs" 10 "Desugared \{show lhs} to \{show blhs}"
 927 |        iwhenJust inm $ \ nm =>
 928 |          when (nm `elem` bound) $ do
 929 |            let fc = getPTermLoc lhs
 930 |            throw $ GenericMsg fc $ concat $ the (List String)
 931 |              [ "Declaration name ("
 932 |              , show nm
 933 |              , ") shadowed by a pattern variable."
 934 |              ]
 935 |
 936 |        pure (inm, bound, blhs)
 937 |
 938 |   desugarWithProblem :
 939 |     {auto s : Ref Syn SyntaxInfo} ->
 940 |     {auto c : Ref Ctxt Defs} ->
 941 |     {auto u : Ref UST UState} ->
 942 |     {auto m : Ref MD Metadata} ->
 943 |     {auto o : Ref ROpts REPLOpts} ->
 944 |     List Name -> PWithProblem ->
 945 |     Core (RigCount, RawImp, Maybe (RigCount, Name))
 946 |   desugarWithProblem ps (MkPWithProblem rig wval mnm)
 947 |     = (rig,,mnm) <$> desugar AnyExpr ps wval
 948 |
 949 |   desugarClause : {auto s : Ref Syn SyntaxInfo} ->
 950 |                   {auto c : Ref Ctxt Defs} ->
 951 |                   {auto u : Ref UST UState} ->
 952 |                   {auto m : Ref MD Metadata} ->
 953 |                   {auto o : Ref ROpts REPLOpts} ->
 954 |                   List Name -> (arg : Bool) -> PClause ->
 955 |                   Core (IMaybe (not arg) Name, ImpClause)
 956 |   desugarClause ps arg (MkPatClause fc lhs rhs wheres)
 957 |       = do ws <- traverse (desugarDecl ps) wheres
 958 |
 959 |            (nm, bound, lhs') <- desugarLHS ps arg lhs
 960 |
 961 |            -- desugar rhs, putting where clauses as local definitions
 962 |            rhs' <- desugar AnyExpr (bound ++ ps) rhs
 963 |            let rhs' = case ws of
 964 |                         [] => rhs'
 965 |                         _ => ILocal fc (concat ws) rhs'
 966 |
 967 |            pure (nm, PatClause fc lhs' rhs')
 968 |
 969 |   desugarClause ps arg (MkWithClause fc lhs wps flags cs)
 970 |       = do cs' <- traverse (map snd . desugarClause ps arg) cs
 971 |            (nm, bound, lhs') <- desugarLHS ps arg lhs
 972 |            wps' <- traverseList1 (desugarWithProblem (bound ++ ps)) wps
 973 |            pure (nm, mkWithClause fc lhs' wps' flags cs')
 974 |
 975 |   desugarClause ps arg (MkImpossible fc lhs)
 976 |       = do (nm, _, lhs') <- desugarLHS ps arg lhs
 977 |            pure (nm, ImpossibleClause fc lhs')
 978 |
 979 |   desugarData : {auto s : Ref Syn SyntaxInfo} ->
 980 |                 {auto c : Ref Ctxt Defs} ->
 981 |                 {auto u : Ref UST UState} ->
 982 |                 {auto m : Ref MD Metadata} ->
 983 |                 {auto o : Ref ROpts REPLOpts} ->
 984 |                 List Name -> (doc : String) ->
 985 |                 PDataDecl -> Core ImpData
 986 |   desugarData ps doc (MkPData fc n tycon opts datacons)
 987 |       = do addDocString n doc
 988 |            syn <- get Syn
 989 |            mm <- traverse (desugarType ps) datacons
 990 |            pure $ MkImpData fc n
 991 |                    !(flip traverseOpt tycon $ \ tycon => do
 992 |                       tycon <- desugar AnyExpr ps tycon
 993 |                       bindTypeNames fc (usingImpl syn) ps tycon)
 994 |                    opts
 995 |                    (concat mm)
 996 |   desugarData ps doc (MkPLater fc n tycon)
 997 |       = do addDocString n doc
 998 |            syn <- get Syn
 999 |            pure $ MkImpLater fc n !(bindTypeNames fc (usingImpl syn)
1000 |                                                   ps !(desugar AnyExpr ps tycon))
1001 |
1002 |   desugarField : {auto s : Ref Syn SyntaxInfo} ->
1003 |                  {auto c : Ref Ctxt Defs} ->
1004 |                  {auto u : Ref UST UState} ->
1005 |                  {auto m : Ref MD Metadata} ->
1006 |                  {auto o : Ref ROpts REPLOpts} ->
1007 |                  List Name -> Namespace -> PField ->
1008 |                  Core (List IField)
1009 |   desugarField ps ns field
1010 |       = flip Core.traverse field.names $ \n : WithFC Name => do
1011 |            addDocStringNS ns n.val field.doc
1012 |            addDocStringNS ns (toRF n.val) field.doc
1013 |            syn <- get Syn
1014 |            p' <- traverse (desugar AnyExpr ps) field.val.info
1015 |            ty' <- bindTypeNames field.fc (usingImpl syn) ps !(desugar AnyExpr ps field.val.boundType)
1016 |            pure (Mk [field.fc, field.rig, n] (MkPiBindData p' ty'))
1017 |
1018 |         where
1019 |           toRF : Name -> Name
1020 |           toRF (UN (Basic n)) = UN (Field n)
1021 |           toRF n = n
1022 |
1023 |   export
1024 |   desugarFnOpt : {auto s : Ref Syn SyntaxInfo} ->
1025 |                  {auto c : Ref Ctxt Defs} ->
1026 |                  {auto u : Ref UST UState} ->
1027 |                  {auto m : Ref MD Metadata} ->
1028 |                  {auto o : Ref ROpts REPLOpts} ->
1029 |                  List Name -> PFnOpt -> Core FnOpt
1030 |   desugarFnOpt ps (IFnOpt f) = pure f
1031 |   desugarFnOpt ps (PForeign tms)
1032 |       = do tms' <- traverse (desugar AnyExpr ps) tms
1033 |            pure (ForeignFn tms')
1034 |   desugarFnOpt ps (PForeignExport tms)
1035 |       = do tms' <- traverse (desugar AnyExpr ps) tms
1036 |            pure (ForeignExport tms')
1037 |
1038 |   %inline
1039 |   mapDesugarPiInfo : {auto s : Ref Syn SyntaxInfo} ->
1040 |                      {auto c : Ref Ctxt Defs} ->
1041 |                      {auto u : Ref UST UState} ->
1042 |                      {auto m : Ref MD Metadata} ->
1043 |                      {auto o : Ref ROpts REPLOpts} ->
1044 |                      List Name -> PiInfo PTerm -> Core (PiInfo RawImp)
1045 |   mapDesugarPiInfo ps = PiInfo.traverse (desugar AnyExpr ps)
1046 |
1047 |   displayFixity : Maybe Visibility -> BindingModifier -> Fixity -> Nat -> OpStr -> String
1048 |   displayFixity Nothing NotBinding fix prec op = "\{show fix} \{show prec} \{show op}"
1049 |   displayFixity Nothing bind fix prec op = "\{show bind} \{show fix} \{show prec} \{show op}"
1050 |   displayFixity (Just vis) NotBinding fix prec op = "\{show vis} \{show fix} \{show prec} \{show op}"
1051 |   displayFixity (Just vis) bind fix prec op = "\{show vis} \{show bind} \{show fix} \{show prec} \{show op}"
1052 |
1053 |   verifyTotalityModifiers : {auto c : Ref Ctxt Defs} ->
1054 |                             FC -> List FnOpt -> Core ()
1055 |   verifyTotalityModifiers fc opts =
1056 |     when (count isTotalityReq opts > 1) $ do
1057 |       let totalities = sort $ mapMaybe extractTotality opts
1058 |       let dedupTotalities = dedup totalities
1059 |       defaultTotality <- getDefaultTotalityOption
1060 |       throw $ GenericMsgSol fc "Multiple totality modifiers" "Possible solutions" $
1061 |         catMaybes $
1062 |           [ checkDuplicates totalities dedupTotalities
1063 |           , checkCompability dedupTotalities
1064 |           , checkDefault defaultTotality dedupTotalities
1065 |           ]
1066 |     where
1067 |       showModifiers : Show a => List a -> String
1068 |       showModifiers = concat . intersperse ", " . map (\s => "`\{show s}`")
1069 |
1070 |       checkCompability : List TotalReq -> Maybe String
1071 |       checkCompability totalities =
1072 |         toMaybe (length totalities > 1) $
1073 |           "Leave only one modifier out of " ++ showModifiers totalities
1074 |
1075 |       checkDuplicates : List TotalReq -> List TotalReq -> Maybe String
1076 |       checkDuplicates totalities dedupTotalities =
1077 |         toMaybe (totalities /= dedupTotalities) $ do
1078 |           let repeated = filter (\x => count (x ==) totalities > 1) dedupTotalities
1079 |           "Remove duplicates of " ++ showModifiers repeated
1080 |
1081 |       checkDefault : TotalReq -> List TotalReq -> Maybe String
1082 |       checkDefault def totalities =
1083 |         toMaybe (def `elem` totalities) $
1084 |           "Remove modifiers " ++ showModifiers totalities ++
1085 |           ", resulting in the default totality of " ++ showModifiers [def]
1086 |
1087 |   -- Given a high level declaration, return a list of TTImp declarations
1088 |   -- which process it, and update any necessary state on the way.
1089 |   export
1090 |   desugarDecl : {auto s : Ref Syn SyntaxInfo} ->
1091 |                 {auto c : Ref Ctxt Defs} ->
1092 |                 {auto u : Ref UST UState} ->
1093 |                 {auto m : Ref MD Metadata} ->
1094 |                 {auto o : Ref ROpts REPLOpts} ->
1095 |                 List Name -> PDecl -> Core (List ImpDecl)
1096 |   desugarDecl ps claim@(MkWithData _ (PClaim (MkPClaim rig vis fnopts ty)))
1097 |       = do opts <- traverse (desugarFnOpt ps) fnopts
1098 |            verifyTotalityModifiers claim.fc opts
1099 |
1100 |            types <- desugarType ps ty
1101 |            pure $ flip (map {f = List, b = ImpDecl}) types $ \ty' =>
1102 |                       IClaim (MkFCVal claim.fc $ MkIClaimData rig vis opts ty')
1103 |
1104 |   desugarDecl ps (MkWithData fc (PDef clauses))
1105 |   -- The clauses won't necessarily all be from the same function, so split
1106 |   -- after desugaring, by function name, using collectDefs from RawImp
1107 |       = do ncs <- traverse (desugarClause ps False) clauses
1108 |            defs <- traverse (uncurry $ toIDef . fromJust) ncs
1109 |            pure (collectDefs defs)
1110 |     where
1111 |       toIDef : Name -> ImpClause -> Core ImpDecl
1112 |       toIDef nm (PatClause fc lhs rhs)
1113 |           = pure $ IDef fc nm [PatClause fc lhs rhs]
1114 |       toIDef nm (WithClause fc lhs rig rhs prf flags cs)
1115 |           = pure $ IDef fc nm [WithClause fc lhs rig rhs prf flags cs]
1116 |       toIDef nm (ImpossibleClause fc lhs)
1117 |           = pure $ IDef fc nm [ImpossibleClause fc lhs]
1118 |
1119 |   desugarDecl ps dat@(MkWithData _ $ PData doc vis mbtot ddecl)
1120 |       = pure [IData dat.fc vis mbtot !(desugarData ps doc ddecl)]
1121 |
1122 |   desugarDecl ps pp@(MkWithData _ $ PParameters params pds)
1123 |       = do
1124 |            params' <- getArgs params
1125 |            let paramList = forget params'
1126 |            let paramNames = map (.name.val) paramList
1127 |            pds' <- traverse (desugarDecl (ps ++ paramNames)) pds
1128 |            -- Look for implicitly bindable names in the parameters
1129 |            pnames <- ifThenElse (not !isUnboundImplicits) (pure [])
1130 |              $ map concat
1131 |              $ for (map (boundType . val) paramList)
1132 |              $ findUniqueBindableNames pp.fc True (ps ++ paramNames) []
1133 |
1134 |            let paramsb = map {f = List1} (map {f = WithData _} (mapType (doBind pnames))) params'
1135 |            pure [IParameters pp.fc paramsb (concat pds')]
1136 |       where
1137 |         getArgs : Either (List1 PlainBinder)
1138 |                          (List1 PBinder) ->
1139 |                          Core (List1 (ImpParameter' RawImp))
1140 |         getArgs (Left params)
1141 |           = traverseList1 (\ty => do
1142 |               ty' <- desugar AnyExpr ps ty.val
1143 |               pure (Mk [top, ty.name] (MkPiBindData Explicit ty'))) params
1144 |         getArgs (Right params)
1145 |           = join <$> traverseList1 (\(MkPBinder info (MkBasicMultiBinder rig n ntm)) => do
1146 |               tm' <- desugar AnyExpr ps ntm
1147 |               i' <- traverse (desugar AnyExpr ps) info
1148 |               let allbinders = map (\nn => Mk [rig, nn] (MkPiBindData i' tm')) n
1149 |               pure allbinders) params
1150 |
1151 |   desugarDecl ps use@(MkWithData _ $ PUsing uimpls uds)
1152 |       = do syn <- get Syn
1153 |            let oldu = usingImpl syn
1154 |            uimpls' <- traverse (\ ntm => do tm' <- desugar AnyExpr ps (snd ntm)
1155 |                                             btm <- bindTypeNames use.fc oldu ps tm'
1156 |                                             pure (fst ntm, btm)) uimpls
1157 |            put Syn ({ usingImpl := uimpls' ++ oldu } syn)
1158 |            uds' <- traverse (desugarDecl ps) uds
1159 |            update Syn { usingImpl := oldu }
1160 |            pure (concat uds')
1161 |   desugarDecl ps int@(MkWithData _ $ PInterface vis cons_in tn doc params det conname body)
1162 |       = do addDocString tn doc
1163 |            let paramNames = concatMap (map val . forget . names) params
1164 |
1165 |            let cons = concatMap expandConstraint cons_in
1166 |            cons' <- traverse (\ ntm => do tm' <- desugar AnyExpr (ps ++ paramNames)
1167 |                                                          (snd ntm)
1168 |                                           pure (fst ntm, tm')) cons
1169 |            params' : List (WithFC Name, RigCount, RawImp) <-
1170 |                         map concat $ for params $ \ (MkBasicMultiBinder rig nm tm) =>
1171 |                            do tm' <- desugar AnyExpr ps tm
1172 |                               pure $ map (, rig, tm') (forget nm)
1173 |            -- Look for bindable names in all the constraints and parameters
1174 |            let mnames = map dropNS (definedIn (map val body))
1175 |            bnames <- ifThenElse (not !isUnboundImplicits) (pure [])
1176 |              $ map concat
1177 |              $ for (map Builtin.snd cons' ++ map (snd . snd) params')
1178 |              $ findUniqueBindableNames int.fc True (ps ++ mnames ++ paramNames) []
1179 |
1180 |            let paramsb = map (\ (nm, (rig, tm)) =>
1181 |                                  let tm' = doBind bnames tm in
1182 |                                  (nm.val, (rig, tm')))
1183 |                          params'
1184 |            let consb = map (\ (nm, tm) => (nm, doBind bnames tm)) cons'
1185 |
1186 |            body' <- traverse (desugarDecl (ps ++ mnames ++ paramNames)) body
1187 |            pure [IPragma int.fc (maybe [tn] (\n => [tn, n.val]) conname)
1188 |                             (\nest, env =>
1189 |                               elabInterface int.fc vis env nest consb
1190 |                                             tn paramsb det conname
1191 |                                             (concat body'))]
1192 |     where
1193 |       -- Turns pairs in the constraints to individual constraints. This
1194 |       -- is a bit of a hack, but it's necessary to build parent constraint
1195 |       -- chasing functions correctly
1196 |       pairToCons : PTerm -> List PTerm
1197 |       pairToCons (PPair _ l r) = pairToCons l ++ pairToCons r
1198 |       pairToCons t = [t]
1199 |
1200 |       expandConstraint : (Maybe Name, PTerm) -> List (Maybe Name, PTerm)
1201 |       expandConstraint (Just n, t) = [(Just n, t)]
1202 |       expandConstraint (Nothing, p)
1203 |           = map (\x => (Nothing, x)) (pairToCons p)
1204 |
1205 |   desugarDecl ps impl@(MkWithData _ $ PImplementation vis fnopts pass is cons tn params impln nusing body)
1206 |       = do opts <- traverse (desugarFnOpt ps) fnopts
1207 |            verifyTotalityModifiers impl.fc opts
1208 |
1209 |            is' <- for is $ traverse (\ bind =>
1210 |                      do tm' <- desugar AnyExpr ps bind.boundType
1211 |                         pi' <- mapDesugarPiInfo ps bind.info
1212 |                         pure (MkPiBindData pi' tm'))
1213 |            cons' <- for cons $ \ (n, tm) =>
1214 |                      do tm' <- desugar AnyExpr ps tm
1215 |                         pure (n, tm')
1216 |            params' : List RawImp <- traverse (desugar AnyExpr ps) params
1217 |            -- Look for bindable names in all the constraints and parameters
1218 |            bnames <- ifThenElse (not !isUnboundImplicits) (pure [])
1219 |              $ map concat
1220 |              $ for (map snd cons' ++ params')
1221 |              $ findUniqueBindableNames impl.fc True ps []
1222 |
1223 |            let paramsb = map (doBind bnames) params'
1224 |            let isb = map (map (mapType (doBind bnames))) is'
1225 |            let consb = map (map (doBind bnames)) cons'
1226 |
1227 |            body' <- maybe (pure Nothing)
1228 |                           (\b => do b' <- traverse (desugarDecl ps) b
1229 |                                     pure (Just (concat b'))) body
1230 |            -- calculate the name of the implementation, if it's not explicitly
1231 |            -- given.
1232 |            let impname = maybe (mkImplName impl.fc tn paramsb) id impln
1233 |
1234 |            pure [IPragma impl.fc [impname]
1235 |                             (\nest, env =>
1236 |                                elabImplementation impl.fc vis opts pass env nest isb consb
1237 |                                                   tn paramsb (isNamed impln)
1238 |                                                   impname nusing
1239 |                                                   body')]
1240 |     where
1241 |       isNamed : Maybe a -> Bool
1242 |       isNamed Nothing = False
1243 |       isNamed (Just _) = True
1244 |
1245 |   desugarDecl ps rec@(MkWithData fc $ PRecord doc vis mbtot (MkPRecordLater tn params))
1246 |       = desugarDecl ps (MkWithData fc $ PData doc vis mbtot (MkPLater rec.fc tn (mkRecType params)))
1247 |     where
1248 |       mkRecType : List PBinder -> PTerm
1249 |       mkRecType [] = PType rec.fc
1250 |       mkRecType (MkPBinder p (MkBasicMultiBinder c (n ::: []) t) :: ts)
1251 |         = PPi rec.fc c p (Just n.val) t (mkRecType ts)
1252 |       mkRecType (MkPBinder p (MkBasicMultiBinder c (n ::: x :: xs) t) :: ts)
1253 |         = PPi rec.fc c p (Just n.val) t (mkRecType (MkPBinder p (MkBasicMultiBinder c (x ::: xs) t) :: ts))
1254 |   desugarDecl ps rec@(MkWithData _ $ PRecord doc vis mbtot (MkPRecord tn params opts conname_in fields))
1255 |       = do addDocString tn doc
1256 |            params' : List ImpParameter <-
1257 |               map concat $ for params $ \ (MkPBinder info (MkBasicMultiBinder rig names tm)) =>
1258 |                  do tm' <- desugar AnyExpr ps tm
1259 |                     p'  <- mapDesugarPiInfo ps info
1260 |                     let allBinders = map (\nm => Mk [rig, nm] (MkPiBindData p' tm')) (forget names)
1261 |                     pure allBinders
1262 |            let fnames : List Name = concatMap getfname fields
1263 |            let paramNames : List Name = concatMap (map val . forget . names . bind) params
1264 |
1265 |            -- Look for bindable names in the parameters
1266 |            let bnames : List (Name, Name) =
1267 |                 if !isUnboundImplicits
1268 |                    then concatMap (findBindableNames True (ps ++ fnames ++ paramNames) [])
1269 |                                   (map (boundType . val) params')
1270 |                    else []
1271 |
1272 |            let paramsb : List ImpParameter = map (map $ mapType $ doBind bnames) params'
1273 |            let recName = nameRoot tn
1274 |            fields' : List (List IField) <- for fields (desugarField (ps ++ fnames ++ paramNames)
1275 |                                                                     (mkNamespace recName))
1276 |            let conname : Name = maybe (mkConName tn) val conname_in
1277 |            whenJust (get "doc" <$> conname_in) (addDocString conname)
1278 |            pure [IRecord rec.fc (Just recName)
1279 |                          vis mbtot (Mk [rec.fc] $ MkImpRecord (Mk [NoFC tn] paramsb) (Mk [NoFC conname, opts] (concat fields')))]
1280 |     where
1281 |       getfname : PField -> List Name
1282 |       getfname x = map val x.names
1283 |
1284 |       mkConName : Name -> Name
1285 |       mkConName (NS ns (UN n))
1286 |         = let str = displayUserName n in
1287 |           NS ns (DN str (MN ("__mk" ++ str) 0))
1288 |       mkConName n = DN (show n) (MN ("__mk" ++ show n) 0)
1289 |
1290 |   desugarDecl ps fx@(MkWithData _ $ PFixity (MkPFixityData vis binding fix prec opNames))
1291 |       = flip (Core.traverseList1_ {b = Unit}) opNames (\opName : OpStr => do
1292 |            unless (checkValidFixity binding fix prec)
1293 |              (throw $ GenericMsgSol fx.fc
1294 |                  "Invalid fixity, \{binding} operator must be infixr 0." "Possible solutions"
1295 |                  [ "Make it `infixr 0`: `\{binding} infixr 0 \{show opName}`"
1296 |                  , "Remove the binding keyword: `\{fix} \{show prec} \{show opName}`"
1297 |                  ])
1298 |            when (isDefaulted vis) $
1299 |              let adjustedExport = displayFixity (Just Export) binding fix prec opName
1300 |                  adjustedPrivate = displayFixity (Just Private) binding fix prec opName
1301 |                  originalFixity = displayFixity Nothing binding fix prec opName
1302 |              in recordWarning $ GenericWarn fx.fc """
1303 |                Fixity declaration '\{originalFixity}' does not have an export modifier, and
1304 |                will become private by default in a future version.
1305 |                To expose it outside of its module, write '\{adjustedExport}'. If you
1306 |                intend to keep it private, write '\{adjustedPrivate}'.
1307 |                """
1308 |            ctx <- get Ctxt
1309 |            -- We update the context of fixities by adding a namespaced fixity
1310 |            -- given by the current namespace and its fixity name.
1311 |            -- This allows fixities to be stored along with the namespace at their
1312 |            -- declaration site and detect and handle ambiguous fixities
1313 |            let updatedNS = NS (mkNestedNamespace (Just ctx.currentNS) (show fix))
1314 |                               (UN $ Basic $ nameRoot opName.toName)
1315 |
1316 |            update Syn
1317 |              { fixities $=
1318 |                addName updatedNS
1319 |                  (MkFixityInfo fx.fc (collapseDefault vis) binding fix prec) })
1320 |         >> pure []
1321 |   desugarDecl ps d@(MkWithData _ $ PFail mmsg ds)
1322 |       = do -- save the state: the content of a failing block should be discarded
1323 |            ust <- get UST
1324 |            md <- get MD
1325 |            opts <- get ROpts
1326 |            syn <- get Syn
1327 |            defs <- branch
1328 |            log "desugar.failing" 20 $ "Desugaring the block:\n" ++ show d.val
1329 |            -- See whether the desugaring phase fails and return
1330 |            -- * Right ds                            if the desugaring succeeded
1331 |            --                                       the error will have to come later in the pipeline
1332 |            -- * Left Nothing                        if the block correctly failed
1333 |            -- * Left (Just (FailingWrongError err)) if the block failed with the wrong error
1334 |            result <- catch
1335 |              (do -- run the desugarer
1336 |                  ds <- traverse (desugarDecl ps) ds
1337 |                  pure (Right (concat ds)))
1338 |              (\err => do -- no message: any error will do
1339 |                          let Just msg = mmsg
1340 |                              | _ => pure (Left Nothing)
1341 |                          -- otherwise have a look at the displayed message
1342 |                          log "desugar.failing" 10 $ "Failing block based on \{show msg} failed with \{show err}"
1343 |                          test <- checkError msg err
1344 |                          pure $ Left $ do
1345 |                               -- Unless the error is the expected one
1346 |                               guard (not test)
1347 |                               -- We should complain we had the wrong one
1348 |                               pure (FailingWrongError d.fc msg (err ::: [])))
1349 |            -- Reset the state
1350 |            put UST ust
1351 |            md' <- get MD
1352 |            put MD ({ semanticHighlighting := semanticHighlighting md'
1353 |                    , semanticAliases := semanticAliases md'
1354 |                    , semanticDefaults := semanticDefaults md'
1355 |                    } md)
1356 |            put Syn syn
1357 |            put Ctxt defs
1358 |            -- either fail or return the block that should fail during the elab phase
1359 |            case the (Either (Maybe Error) (List ImpDecl)) result of
1360 |              Right ds => [IFail d.fc mmsg ds] <$ log "desugar.failing" 20 "Success"
1361 |              Left Nothing => [] <$ log "desugar.failing" 20 "Correctly failed"
1362 |              Left (Just err) => throw err
1363 |   desugarDecl ps (MkWithData _ $ PMutual ds)
1364 |       = do let (tys, defs) = splitMutual ds
1365 |            mds' <- traverse (desugarDecl ps) (tys ++ defs)
1366 |            pure (concat mds')
1367 |   desugarDecl ps n@(MkWithData _ $ PNamespace ns decls)
1368 |       = withExtendedNS ns $ do
1369 |            ds <- traverse (desugarDecl ps) decls
1370 |            pure [INamespace n.fc ns (concat ds)]
1371 |   desugarDecl ps ts@(MkWithData _ $ PTransform n lhs rhs)
1372 |       = do (bound, blhs) <- bindNames False !(desugar LHS ps lhs)
1373 |            rhs' <- desugar AnyExpr (bound ++ ps) rhs
1374 |            pure [ITransform ts.fc (UN $ Basic n) blhs rhs']
1375 |   desugarDecl ps el@(MkWithData _ $ PRunElabDecl tm)
1376 |       = do tm' <- desugar AnyExpr ps tm
1377 |            pure [IRunElabDecl el.fc tm']
1378 |   desugarDecl ps dir@(MkWithData _ $ PDirective d)
1379 |       = let fc = dir.fc in case d of
1380 |              Hide (HideName n) => pure [IPragma fc [] (\nest, env => hide fc n)]
1381 |              Hide (HideFixity fx n) => pure [IPragma fc [] (\_, _ => removeFixity fc fx n)]
1382 |              Unhide n => pure [IPragma fc [] (\nest, env => unhide fc n)]
1383 |              Logging i => pure [ILog ((\ i => (topics i, verbosity i)) <$> i)]
1384 |              LazyOn a => pure [IPragma fc [] (\nest, env => lazyActive a)]
1385 |              UnboundImplicits a => do
1386 |                setUnboundImplicits a
1387 |                pure [IPragma fc [] (\nest, env => setUnboundImplicits a)]
1388 |              PrefixRecordProjections b => do
1389 |                pure [IPragma fc [] (\nest, env => setPrefixRecordProjections b)]
1390 |              AmbigDepth n => pure [IPragma fc [] (\nest, env => setAmbigLimit n)]
1391 |              TotalityDepth n => pure [IPragma fc [] (\next, env => setTotalLimit n)]
1392 |              AutoImplicitDepth n => pure [IPragma fc [] (\nest, env => setAutoImplicitLimit n)]
1393 |              NFMetavarThreshold n => pure [IPragma fc [] (\nest, env => setNFThreshold n)]
1394 |              SearchTimeout n => pure [IPragma fc [] (\nest, env => setSearchTimeout n)]
1395 |              PairNames ty f s => pure [IPragma fc [] (\nest, env => setPair fc ty f s)]
1396 |              RewriteName eq rw => pure [IPragma fc [] (\nest, env => setRewrite fc eq rw)]
1397 |              PrimInteger n => pure [IPragma fc [] (\nest, env => setFromInteger n)]
1398 |              PrimString n => pure [IPragma fc [] (\nest, env => setFromString n)]
1399 |              PrimChar n => pure [IPragma fc [] (\nest, env => setFromChar n)]
1400 |              PrimDouble n => pure [IPragma fc [] (\nest, env => setFromDouble n)]
1401 |              PrimTTImp n => pure [IPragma fc [] (\nest, env => setFromTTImp n)]
1402 |              PrimName n => pure [IPragma fc [] (\nest, env => setFromName n)]
1403 |              PrimDecls n => pure [IPragma fc [] (\nest, env => setFromDecls n)]
1404 |              CGAction cg dir => pure [IPragma fc [] (\nest, env => addDirective cg dir)]
1405 |              Names n ns => pure [IPragma fc [] (\nest, env => addNameDirective fc n ns)]
1406 |              StartExpr tm => pure [IPragma fc [] (\nest, env => throw (InternalError "%start not implemented"))] -- TODO!
1407 |              Overloadable n => pure [IPragma fc [] (\nest, env => setNameFlag fc n Overloadable)]
1408 |              Extension e => pure [IPragma fc [] (\nest, env => setExtension e)]
1409 |              DefaultTotality tot => pure [IPragma fc [] (\_, _ => setDefaultTotalityOption tot)]
1410 |              ForeignImpl n cs => do
1411 |                cs' <- traverse (desugar AnyExpr ps) cs
1412 |                pure [IPragma fc [] (\nest, env => do
1413 |                       defs <- get Ctxt
1414 |                       let calls : List String = !(traverse getFnString cs')
1415 |                       [(n',_,gdef)] <- lookupCtxtName n (gamma defs)
1416 |                         | [] => throw (UndefinedName fc n)
1417 |                         | xs => throw (AmbiguousName fc (map fst xs))
1418 |                       let ForeignDef arity xs = gdef.definition
1419 |                         | _ => throw (GenericMsg fc "\{show n} is not a foreign definition")
1420 |
1421 |                       update Ctxt { options->foreignImpl $= \xs => foldr SortedSet.insert xs (map (n',) calls) }
1422 |                     )]
1423 |   desugarDecl ps bt@(MkWithData _ $ PBuiltin type name) = pure [IBuiltin bt.fc type name]
1424 |
1425 |   export
1426 |   desugarDo : {auto s : Ref Syn SyntaxInfo} ->
1427 |               {auto c : Ref Ctxt Defs} ->
1428 |               {auto m : Ref MD Metadata} ->
1429 |               {auto u : Ref UST UState} ->
1430 |               {auto o : Ref ROpts REPLOpts} ->
1431 |               Side -> List Name -> Maybe Namespace -> PTerm -> Core RawImp
1432 |   desugarDo s ps doNamespace tm
1433 |       = do b <- newRef Bang (initBangs doNamespace)
1434 |            tm' <- desugarB s ps tm
1435 |            bd <- get Bang
1436 |            pure $ bindBangs (bangNames bd) doNamespace tm'
1437 |
1438 |   export
1439 |   desugar : {auto s : Ref Syn SyntaxInfo} ->
1440 |             {auto c : Ref Ctxt Defs} ->
1441 |             {auto m : Ref MD Metadata} ->
1442 |             {auto u : Ref UST UState} ->
1443 |             {auto o : Ref ROpts REPLOpts} ->
1444 |             Side -> List Name -> PTerm -> Core RawImp
1445 |
1446 |   desugar s ps tm = desugarDo s ps Nothing tm
1447 |