packages feed

idris 1.1.1 → 1.2.0

raw patch · 431 files changed

+10565/−9476 lines, 431 filesdep +megaparsecdep +semigroupsdep −parsersdep −transformers-compatdep −trifectadep ~Win32dep ~ansi-terminaldep ~optparse-applicativesetup-changedPVP ok

version bump matches the API change (PVP)

Dependencies added: megaparsec, semigroups

Dependencies removed: parsers, transformers-compat, trifecta

Dependency ranges changed: Win32, ansi-terminal, optparse-applicative, transformers

API changes (from Hackage documentation)

- IRTS.BCImp: L :: Int -> Reg
- IRTS.BCImp: NOP :: BC
- IRTS.BCImp: RVal :: Reg
- IRTS.BCImp: bc :: Reg -> SExp -> [BC]
- IRTS.BCImp: data BC
- IRTS.BCImp: data Reg
- IRTS.BCImp: toBC :: (Name, SDecl) -> (Name, [BC])
- IRTS.JavaScript.PrimOp: instance GHC.Classes.Ord IRTS.Lang.PrimFn
- IRTS.Lang: lambdaLift :: Name -> LDecl -> [(Name, LDecl)]
- IRTS.LangOpts: doInline :: LDefs -> LDecl -> LDecl
- IRTS.LangOpts: nextN :: State Int Name
- Idris.AbsSyntaxTree: [lastTokenSpan] :: IState -> Maybe FC
- Idris.CmdOptions: integerReader :: ReadP Int
- Idris.CmdOptions: parseCodegen :: String -> Codegen
- Idris.CmdOptions: parseConsoleWidth :: Monad m => String -> m ConsoleWidth
- Idris.CmdOptions: parseFlags :: Parser [Opt]
- Idris.CmdOptions: parseLogCats :: Monad m => String -> m [LogCat]
- Idris.CmdOptions: parseVersion :: Parser (a -> a)
- Idris.CmdOptions: parser :: Parser [Opt]
- Idris.CmdOptions: preProcOpts :: [Opt] -> [Opt]
- Idris.Core.DeepSeq: instance Control.DeepSeq.NFData GHC.Types.Ordering
- Idris.Core.TT: spanFC :: FC -> FC -> FC
- Idris.DSL: debind :: PTerm -> PTerm -> PTerm
- Idris.DSL: dslify :: SyntaxInfo -> IState -> PTerm -> PTerm
- Idris.DSL: expandSugar :: DSL -> PTerm -> PTerm
- Idris.DSL: mkTTName :: FC -> Name -> PTerm
- Idris.DSL: unIdiom :: PTerm -> PTerm -> FC -> PTerm -> PTerm
- Idris.DSL: var :: DSL -> Name -> PTerm -> Int -> PTerm
- Idris.Options: getCPU :: Opt -> Maybe String
- Idris.Options: getTriple :: Opt -> Maybe String
- Idris.Output: consoleDisplayAnnotated :: Handle -> Doc OutputAnnotation -> Idris ()
- Idris.Output: hWriteDoc :: Handle -> IState -> SimpleDoc OutputAnnotation -> Idris ()
- Idris.Output: iPrintWithStatus :: String -> String -> Idris ()
- Idris.Output: ideModeReturnAnnotated :: Integer -> Handle -> Doc OutputAnnotation -> Idris ()
- Idris.Output: ideModeReturnWithStatus :: String -> Integer -> Handle -> Doc OutputAnnotation -> Idris ()
- Idris.Parser: addHides :: Ctxt Accessibility -> Idris ()
- Idris.Parser: addSyntax :: IState -> Syntax -> IState
- Idris.Parser: argExpr :: SyntaxInfo -> IdrisParser PTerm
- Idris.Parser: caf :: SyntaxInfo -> IdrisParser PDecl
- Idris.Parser: clause :: SyntaxInfo -> IdrisParser PClause
- Idris.Parser: codegen_ :: IdrisParser Codegen
- Idris.Parser: decl' :: SyntaxInfo -> IdrisParser PDecl
- Idris.Parser: declExtension :: SyntaxInfo -> [Maybe (Name, SynMatch)] -> [Syntax] -> IdrisParser [PDecl]
- Idris.Parser: declExtensions :: SyntaxInfo -> [Syntax] -> IdrisParser [PDecl]
- Idris.Parser: directive :: SyntaxInfo -> IdrisParser [PDecl]
- Idris.Parser: docstring :: SyntaxInfo -> IdrisParser (Docstring (Either Err PTerm), [(Name, Docstring (Either Err PTerm))])
- Idris.Parser: externalDecl :: SyntaxInfo -> IdrisParser [PDecl]
- Idris.Parser: findFC :: Doc -> (FC, String)
- Idris.Parser: fnDecl :: SyntaxInfo -> IdrisParser [PDecl]
- Idris.Parser: fnDecl' :: SyntaxInfo -> IdrisParser PDecl
- Idris.Parser: fnOpt :: IdrisParser FnOpt
- Idris.Parser: fnOpts :: IdrisParser ([FnOpt], Accessibility)
- Idris.Parser: implementation :: Bool -> SyntaxInfo -> IdrisParser [PDecl]
- Idris.Parser: implementationBlock :: SyntaxInfo -> IdrisParser [PDecl]
- Idris.Parser: import_ :: IdrisParser ImportInfo
- Idris.Parser: interfaceBlock :: SyntaxInfo -> IdrisParser (Maybe (Name, FC), Docstring (Either Err PTerm), [PDecl])
- Idris.Parser: interface_ :: SyntaxInfo -> IdrisParser [PDecl]
- Idris.Parser: internalDecl :: SyntaxInfo -> IdrisParser [PDecl]
- Idris.Parser: loadModule' :: FilePath -> IBCPhase -> Idris (Maybe String)
- Idris.Parser: loadSource :: Bool -> FilePath -> Maybe Int -> Idris ()
- Idris.Parser: loadSource' :: Bool -> FilePath -> Maybe Int -> Idris ()
- Idris.Parser: moduleHeader :: IdrisParser (Maybe (Docstring ()), [String], [(FC, OutputAnnotation)])
- Idris.Parser: mutual :: SyntaxInfo -> IdrisParser [PDecl]
- Idris.Parser: namespace :: SyntaxInfo -> IdrisParser [PDecl]
- Idris.Parser: openInterface :: SyntaxInfo -> IdrisParser [PDecl]
- Idris.Parser: pLangExt :: IdrisParser LanguageExt
- Idris.Parser: params :: SyntaxInfo -> IdrisParser [PDecl]
- Idris.Parser: parseProg :: SyntaxInfo -> FilePath -> String -> Maybe Delta -> Idris [PDecl]
- Idris.Parser: pattern :: SyntaxInfo -> IdrisParser PDecl
- Idris.Parser: postulate :: SyntaxInfo -> IdrisParser PDecl
- Idris.Parser: prog :: SyntaxInfo -> IdrisParser [PDecl]
- Idris.Parser: provider :: SyntaxInfo -> IdrisParser [PDecl]
- Idris.Parser: rhs :: SyntaxInfo -> Name -> IdrisParser PTerm
- Idris.Parser: runElabDecl :: SyntaxInfo -> IdrisParser PDecl
- Idris.Parser: syntaxDecl :: SyntaxInfo -> IdrisParser PDecl
- Idris.Parser: syntaxRule :: SyntaxInfo -> IdrisParser Syntax
- Idris.Parser: syntaxSym :: IdrisParser SSymbol
- Idris.Parser: totality :: IdrisParser DefaultTotality
- Idris.Parser: transform :: SyntaxInfo -> IdrisParser [PDecl]
- Idris.Parser: usingDecl :: SyntaxInfo -> IdrisParser Using
- Idris.Parser: usingDeclList :: SyntaxInfo -> IdrisParser [Using]
- Idris.Parser: using_ :: SyntaxInfo -> IdrisParser [PDecl]
- Idris.Parser: wExpr :: SyntaxInfo -> IdrisParser PTerm
- Idris.Parser: whereBlock :: Name -> SyntaxInfo -> IdrisParser ([PDecl], [(Name, Name)])
- Idris.Parser.Helpers: IdrisInnerParser :: Parser a -> IdrisInnerParser a
- Idris.Parser.Helpers: IndentProperty :: (Int -> Int -> Bool) -> String -> IndentProperty
- Idris.Parser.Helpers: [runInnerParser] :: IdrisInnerParser a -> Parser a
- Idris.Parser.Helpers: accessibility' :: IdrisParser Accessibility
- Idris.Parser.Helpers: class HasLastTokenSpan m
- Idris.Parser.Helpers: collect :: [PDecl] -> [PDecl]
- Idris.Parser.Helpers: columnNum :: Delta -> Int
- Idris.Parser.Helpers: commentMarkers :: [String]
- Idris.Parser.Helpers: data IndentProperty
- Idris.Parser.Helpers: eqProp :: IndentProperty
- Idris.Parser.Helpers: fileName :: Delta -> String
- Idris.Parser.Helpers: getFC :: MonadicParsing m => m FC
- Idris.Parser.Helpers: getLastTokenSpan :: HasLastTokenSpan m => m (Maybe FC)
- Idris.Parser.Helpers: gtProp :: IndentProperty
- Idris.Parser.Helpers: gteProp :: IndentProperty
- Idris.Parser.Helpers: highlightP :: FC -> OutputAnnotation -> IdrisParser ()
- Idris.Parser.Helpers: idrisStyle :: MonadicParsing m => IdentifierStyle m
- Idris.Parser.Helpers: indent :: IdrisParser Int
- Idris.Parser.Helpers: indentPropHolds :: IndentProperty -> IdrisParser ()
- Idris.Parser.Helpers: initsEndAt :: (a -> Bool) -> [a] -> [[a]]
- Idris.Parser.Helpers: instance (GHC.Base.Monoid a, Data.Semigroup.Semigroup a) => GHC.Base.Monoid (Idris.Parser.Helpers.IdrisInnerParser a)
- Idris.Parser.Helpers: instance GHC.Base.Alternative Idris.Parser.Helpers.IdrisInnerParser
- Idris.Parser.Helpers: instance GHC.Base.Applicative Idris.Parser.Helpers.IdrisInnerParser
- Idris.Parser.Helpers: instance GHC.Base.Functor Idris.Parser.Helpers.IdrisInnerParser
- Idris.Parser.Helpers: instance GHC.Base.Monad Idris.Parser.Helpers.IdrisInnerParser
- Idris.Parser.Helpers: instance GHC.Base.MonadPlus Idris.Parser.Helpers.IdrisInnerParser
- Idris.Parser.Helpers: instance Idris.Parser.Helpers.HasLastTokenSpan Idris.Parser.Helpers.IdrisParser
- Idris.Parser.Helpers: instance Text.Parser.Char.CharParsing Idris.Parser.Helpers.IdrisInnerParser
- Idris.Parser.Helpers: instance Text.Parser.Combinators.Parsing Idris.Parser.Helpers.IdrisInnerParser
- Idris.Parser.Helpers: instance Text.Parser.LookAhead.LookAheadParsing Idris.Parser.Helpers.IdrisInnerParser
- Idris.Parser.Helpers: instance Text.Parser.Token.TokenParsing Idris.Parser.Helpers.IdrisInnerParser
- Idris.Parser.Helpers: instance Text.Parser.Token.TokenParsing Idris.Parser.Helpers.IdrisParser
- Idris.Parser.Helpers: instance Text.Trifecta.Combinators.DeltaParsing Idris.Parser.Helpers.IdrisInnerParser
- Idris.Parser.Helpers: instance Text.Trifecta.Combinators.DeltaParsing Idris.Parser.Helpers.IdrisParser
- Idris.Parser.Helpers: instance Text.Trifecta.Combinators.MarkParsing Text.Trifecta.Delta.Delta Idris.Parser.Helpers.IdrisInnerParser
- Idris.Parser.Helpers: integer :: MonadicParsing m => m Integer
- Idris.Parser.Helpers: invalidOperators :: [String]
- Idris.Parser.Helpers: keepTerminator :: IdrisParser ()
- Idris.Parser.Helpers: lastIndent :: IdrisParser Int
- Idris.Parser.Helpers: lcharFC :: MonadicParsing m => Char -> m FC
- Idris.Parser.Helpers: lineNum :: Delta -> Int
- Idris.Parser.Helpers: ltProp :: IndentProperty
- Idris.Parser.Helpers: lteProp :: IndentProperty
- Idris.Parser.Helpers: mkName :: (String, String) -> Name
- Idris.Parser.Helpers: multiLineComment :: MonadicParsing m => m ()
- Idris.Parser.Helpers: newtype IdrisInnerParser a
- Idris.Parser.Helpers: noDocCommentHere :: String -> IdrisParser ()
- Idris.Parser.Helpers: opChars :: String
- Idris.Parser.Helpers: operator :: MonadicParsing m => m String
- Idris.Parser.Helpers: operatorFC :: MonadicParsing m => m (String, FC)
- Idris.Parser.Helpers: operatorLetter :: MonadicParsing m => m Char
- Idris.Parser.Helpers: reservedFC :: MonadicParsing m => String -> m FC
- Idris.Parser.Helpers: reservedHL :: String -> IdrisParser ()
- Idris.Parser.Helpers: reservedOp :: MonadicParsing m => String -> m ()
- Idris.Parser.Helpers: reservedOpFC :: MonadicParsing m => String -> m FC
- Idris.Parser.Helpers: runparser :: StateT st IdrisInnerParser res -> st -> String -> String -> Result res
- Idris.Parser.Helpers: simpleWhiteSpace :: MonadicParsing m => m ()
- Idris.Parser.Helpers: singleLineComment :: MonadicParsing m => m ()
- Idris.Parser.Helpers: symbolFC :: MonadicParsing m => String -> m FC
- Idris.Parser.Helpers: type MonadicParsing m = (DeltaParsing m, LookAheadParsing m, TokenParsing m, Monad m)
- Idris.Parser.Ops: backtick :: Operator IdrisParser PTerm
- Idris.Parser.Ops: binary :: String -> (FC -> PTerm -> PTerm -> PTerm) -> Assoc -> Operator IdrisParser PTerm
- Idris.Parser.Ops: nofixityoperator :: Operator IdrisParser PTerm
- Idris.Parser.Ops: prefix :: String -> (FC -> PTerm -> PTerm) -> Operator IdrisParser PTerm
- Idris.Parser.Ops: toTable :: [FixDecl] -> OperatorTable IdrisParser PTerm
- Idris.Reflection: RConstraint :: RPlicity
- Idris.Reflection: RCtorField :: RFunArg -> RCtorArg
- Idris.Reflection: RCtorParameter :: RFunArg -> RCtorArg
- Idris.Reflection: RDatatype :: Name -> [RTyConArg] -> Raw -> [(Name, [RCtorArg], Raw)] -> RDatatype
- Idris.Reflection: RErased :: RErasure
- Idris.Reflection: RExplicit :: RPlicity
- Idris.Reflection: RImplicit :: RPlicity
- Idris.Reflection: RIndex :: RFunArg -> RTyConArg
- Idris.Reflection: RNotErased :: RErasure
- Idris.Reflection: RParameter :: RFunArg -> RTyConArg
- Idris.Reflection: claimTy :: Name -> Raw -> ElabD Name
- Idris.Reflection: data RCtorArg
- Idris.Reflection: data RDatatype
- Idris.Reflection: data RErasure
- Idris.Reflection: data RPlicity
- Idris.Reflection: data RTyConArg
- Idris.Reflection: intToReflectedNat :: Int -> Raw
- Idris.Reflection: rArgOpts :: RErasure -> [ArgOpt]
- Idris.Reflection: rawBool :: Bool -> Raw
- Idris.Reflection: rawCons :: Raw -> Raw -> Raw -> Raw
- Idris.Reflection: rawNil :: Raw -> Raw
- Idris.Reflection: rawTriple :: (Raw, Raw, Raw) -> (Raw, Raw, Raw) -> Raw
- Idris.Reflection: rawTripleTy :: Raw -> Raw -> Raw -> Raw
- Idris.Reflection: reflCall :: String -> [Raw] -> Raw
- Idris.Reflection: reflErrName :: String -> Name
- Idris.Reflection: reflectBinder :: Binder Term -> Raw
- Idris.Reflection: reflectBinderQuote :: ([Name] -> a -> Raw) -> Name -> [Name] -> Binder a -> Raw
- Idris.Reflection: reflectBinderQuotePattern :: ([Name] -> a -> ElabD ()) -> Raw -> [Name] -> Binder a -> ElabD ()
- Idris.Reflection: reflectConstant :: Const -> Raw
- Idris.Reflection: reflectCtorArg :: RCtorArg -> Raw
- Idris.Reflection: reflectCtxt :: [(Name, Type)] -> Raw
- Idris.Reflection: reflectErasure :: RErasure -> Raw
- Idris.Reflection: reflectFunClause :: RFunClause Term -> Raw
- Idris.Reflection: reflectNameQuotePattern :: Name -> ElabD ()
- Idris.Reflection: reflectPlicity :: RPlicity -> Raw
- Idris.Reflection: reflectSpecialName :: SpecialName -> Raw
- Idris.Reflection: reflectUExp :: UExp -> Raw
- Idris.Reflection: reflectUniverse :: Universe -> Raw
- Idris.Reflection: reifyApp :: IState -> Name -> [Term] -> ElabD PTactic
- Idris.Reflection: reifyArithTy :: Term -> ElabD ArithTy
- Idris.Reflection: reifyErasure :: Term -> ElabD RErasure
- Idris.Reflection: reifyFC :: Term -> ElabD FC
- Idris.Reflection: reifyInt :: Term -> ElabD Int
- Idris.Reflection: reifyIntTy :: Term -> ElabD IntTy
- Idris.Reflection: reifyNativeTy :: Term -> ElabD NativeTy
- Idris.Reflection: reifyPair :: (Term -> ElabD a) -> (Term -> ElabD b) -> Term -> ElabD (a, b)
- Idris.Reflection: reifyPlicity :: Term -> ElabD RPlicity
- Idris.Reflection: reifyRConstructorDefn :: Term -> ElabD RConstructorDefn
- Idris.Reflection: reifyRFunArg :: Term -> ElabD RFunArg
- Idris.Reflection: reifyRawApp :: Name -> [Term] -> ElabD Raw
- Idris.Reflection: reifyTTApp :: Name -> [Term] -> ElabD Term
- Idris.Reflection: reifyTTBinder :: (Term -> ElabD a) -> Name -> Term -> ElabD (Binder a)
- Idris.Reflection: reifyTTBinderApp :: (Term -> ElabD a) -> Name -> [Term] -> ElabD (Binder a)
- Idris.Reflection: reifyTTConst :: Term -> ElabD Const
- Idris.Reflection: reifyTTConstApp :: Name -> Term -> ElabD Const
- Idris.Reflection: reifyTTNameApp :: Name -> [Term] -> ElabD Name
- Idris.Reflection: reifyTTNameType :: Term -> ElabD NameType
- Idris.Reflection: reifyTTNamespace :: Term -> ElabD [String]
- Idris.Reflection: reifyTTUExp :: Term -> ElabD UExp
- Idris.Reflection: reifyUniverse :: Term -> ElabD Universe
- Idris.Reflection: unApplyRaw :: Raw -> (Raw, [Raw])
- Idris.Termination: Delayed :: Guardedness
- Idris.Termination: Guarded :: Guardedness
- Idris.Termination: Toplevel :: Guardedness
- Idris.Termination: Unguarded :: Guardedness
- Idris.Termination: allNothing :: [Maybe a] -> Bool
- Idris.Termination: buildSCG' :: IState -> Name -> [(Term, Term)] -> [Name] -> [SCGEntry]
- Idris.Termination: calcTotality :: FC -> Name -> [([Name], Term, Term)] -> Idris Totality
- Idris.Termination: checkMP :: IState -> Name -> Int -> MultiPath -> Totality
- Idris.Termination: checkTotality :: [Name] -> FC -> Name -> Idris Totality
- Idris.Termination: collapse :: [Totality] -> Totality
- Idris.Termination: collapse' :: Totality -> [Totality] -> Totality
- Idris.Termination: collapseNothing :: [(Maybe a, b)] -> [(Maybe a, b)]
- Idris.Termination: data Guardedness
- Idris.Termination: delazy :: TT Name -> TT Name
- Idris.Termination: delazy' :: Bool -> TT Name -> TT Name
- Idris.Termination: mkMultiPaths :: IState -> MultiPath -> [SCGEntry] -> [MultiPath]
- Idris.Termination: noPartial :: [Totality] -> Totality
- Idris.Termination: type MultiPath = [SCGEntry]
+ IRTS.JavaScript.Codegen: instance GHC.Base.Monoid IRTS.JavaScript.Codegen.CGStats
+ IRTS.Lang: LFATan2 :: PrimFn
+ IRTS.Lang: instance GHC.Classes.Ord IRTS.Lang.Export
+ IRTS.Lang: instance GHC.Classes.Ord IRTS.Lang.ExportIFace
+ IRTS.Lang: instance GHC.Classes.Ord IRTS.Lang.FCallType
+ IRTS.Lang: instance GHC.Classes.Ord IRTS.Lang.FDesc
+ IRTS.Lang: instance GHC.Classes.Ord IRTS.Lang.FType
+ IRTS.Lang: instance GHC.Classes.Ord IRTS.Lang.LDecl
+ IRTS.Lang: instance GHC.Classes.Ord IRTS.Lang.LExp
+ IRTS.Lang: instance GHC.Classes.Ord IRTS.Lang.LOpt
+ IRTS.Lang: instance GHC.Classes.Ord IRTS.Lang.PrimFn
+ IRTS.Lang: instance GHC.Classes.Ord e => GHC.Classes.Ord (IRTS.Lang.LAlt' e)
+ IRTS.Lang: liftDef :: (Name, LDecl) -> State LiftState ()
+ IRTS.Lang: makeFn :: [Name] -> LExp -> State LiftState Name
+ IRTS.Lang: rename :: [(Name, Name)] -> LExp -> LExp
+ IRTS.Lang: renameArgs :: [Name] -> LExp -> ([Name], LExp)
+ IRTS.Lang: setBaseName :: Name -> State LiftState ()
+ Idris.AbsSyntax: dropLangExt :: LanguageExt -> Idris ()
+ Idris.AbsSyntax: rankedImportDirs :: FilePath -> Idris [FilePath]
+ Idris.AbsSyntaxTree: [ppopt_displayrig] :: PPOption -> Bool
+ Idris.AbsSyntaxTree: expl_linear :: Plicity
+ Idris.Core.Evaluate: visibleDefinitions :: Context -> Ctxt TTDecl
+ Idris.Core.TT: AnnSyntax :: String -> OutputAnnotation
+ Idris.Core.TT: instance GHC.Base.Monoid Idris.Core.TT.FC
+ Idris.Elab.Utils: getLinearUsed :: Context -> Term -> [Name]
+ Idris.IBC: instance Data.Binary.Class.Binary Idris.AbsSyntaxTree.DefaultTotality
+ Idris.IBC: instance Data.Binary.Class.Binary Idris.AbsSyntaxTree.Directive
+ Idris.IBC: instance Data.Binary.Class.Binary Idris.Options.LanguageExt
+ Idris.Imports: data PkgName
+ Idris.Imports: findIBC :: [FilePath] -> FilePath -> FilePath -> Idris (Maybe FilePath)
+ Idris.Imports: instance GHC.Classes.Eq Idris.Imports.PkgName
+ Idris.Imports: instance GHC.Show.Show Idris.Imports.PkgName
+ Idris.Imports: pkgName :: String -> Either String PkgName
+ Idris.Imports: unInitializedPkgName :: PkgName
+ Idris.Imports: unPkgName :: PkgName -> String
+ Idris.Output: class Message a
+ Idris.Output: emitWarning :: Message w => w -> Idris ()
+ Idris.Output: formatMessage :: Message w => w -> Idris OutputDoc
+ Idris.Output: instance Idris.Output.Message Idris.Output.SimpleWarning
+ Idris.Output: messageExtent :: Message a => a -> FC
+ Idris.Output: messageSource :: Message a => a -> Maybe String
+ Idris.Output: messageText :: Message a => a -> OutputDoc
+ Idris.Output: type OutputDoc = Doc OutputAnnotation
+ Idris.Package: makeTarget :: Maybe String -> Maybe String -> IO ()
+ Idris.Package.Parser: clause :: String -> PParser a -> (PkgDesc -> a -> PkgDesc) -> PParser ()
+ Idris.Package.Parser: commaSep :: Parsing m => m a -> m [a]
+ Idris.Package.Parser: filename :: Parsing m => m String
+ Idris.Package.Parser: pClause :: PParser ()
+ Idris.Package.Parser: pPkg :: PParser PkgDesc
+ Idris.Package.Parser: pPkgName :: PParser PkgName
+ Idris.Package.Parser: parseDesc :: FilePath -> IO PkgDesc
+ Idris.Package.Parser: textUntilEol :: Parsing m => m String
+ Idris.Package.Parser: type PParser = Parser PkgDesc
+ Idris.Parser: clearParserWarnings :: Idris ()
+ Idris.Parser: data ParseError
+ Idris.Parser: name :: (Parsing m, MonadState IState m) => m Name
+ Idris.Parser: opChars :: String
+ Idris.Parser: parseErrorDoc :: ParseError -> Doc
+ Idris.Parser: runparser :: Parser st res -> st -> String -> String -> Either ParseError res
+ Idris.Parser: type IdrisParser = Parser IState
+ Idris.Parser.Helpers: highlight :: (MonadState IState m, Parsing m) => OutputAnnotation -> m a -> m a
+ Idris.Parser.Helpers: indentGt :: (Parsing m, MonadState IState m) => m ()
+ Idris.Parser.Helpers: keyword :: (Parsing m, MonadState IState m) => String -> m ()
+ Idris.Parser.Helpers: packageName :: Parsing m => m String
+ Idris.Parser.Helpers: parseErrorDoc :: ParseError -> Doc
+ Idris.Parser.Helpers: someSpace :: Parsing m => m ()
+ Idris.Parser.Helpers: token :: Parsing m => m a -> m a
+ Idris.Parser.Ops: backtickOperator :: (Parsing m, MonadState IState m) => m Name
+ Idris.Parser.Ops: commentMarkers :: [String]
+ Idris.Parser.Ops: invalidOperators :: [String]
+ Idris.Parser.Ops: opChars :: String
+ Idris.Parser.Ops: operatorLetter :: Parsing m => m Char
+ Idris.Parser.Ops: operatorName :: (Parsing m, MonadState IState m) => m Name
+ Idris.Parser.Ops: reservedOp :: Parsing m => String -> m ()
+ Idris.Parser.Ops: symbolicOperator :: Parsing m => m String
+ Idris.Parser.Stack: addExtent :: MonadWriter FC m => FC -> m ()
+ Idris.Parser.Stack: appExtent :: MonadWriter FC m => m (FC -> a) -> m a
+ Idris.Parser.Stack: data ParseError
+ Idris.Parser.Stack: extent :: MonadWriter FC m => m a -> m FC
+ Idris.Parser.Stack: getFC :: Parsing m => m FC
+ Idris.Parser.Stack: instance Idris.Output.Message Idris.Parser.Stack.ParseError
+ Idris.Parser.Stack: mark :: Parsing m => m Mark
+ Idris.Parser.Stack: prettyError :: ParseError -> String
+ Idris.Parser.Stack: restore :: Parsing m => Mark -> m ()
+ Idris.Parser.Stack: runparser :: Parser st res -> st -> String -> String -> Either ParseError res
+ Idris.Parser.Stack: trackExtent :: Parsing m => m a -> m a
+ Idris.Parser.Stack: type Mark = State String
+ Idris.Parser.Stack: type Parser s = StateT s (WriterT FC (Parsec Void String))
+ Idris.Parser.Stack: type Parsing m = (MonadParsec Void String m, MonadWriter FC m)
+ Idris.Parser.Stack: withExtent :: MonadWriter FC m => m a -> m (a, FC)
+ Idris.REPL.Commands: ShowVersion :: Command
- IRTS.Bytecode: constAlt :: t -> Reg -> Bool -> SAlt -> Maybe (Const, [BC])
+ IRTS.Bytecode: constAlt :: () => p -> Reg -> Bool -> SAlt -> Maybe (Const, [BC])
- IRTS.Defunctionalise: DC :: (Maybe LVar) -> Int -> Name -> [DExp] -> DExp
+ IRTS.Defunctionalise: DC :: (Maybe Name) -> Int -> Name -> [DExp] -> DExp
- IRTS.Defunctionalise: DV :: LVar -> DExp
+ IRTS.Defunctionalise: DV :: Name -> DExp
- IRTS.Defunctionalise: mkBigCase :: t -> Int -> DExp -> [DAlt] -> DExp
+ IRTS.Defunctionalise: mkBigCase :: () => p -> Int -> DExp -> [DAlt] -> DExp
- IRTS.Inliner: evalD :: t -> a -> Maybe a
+ IRTS.Inliner: evalD :: () => p -> a -> Maybe a
- IRTS.Lang: LCon :: (Maybe LVar) -> Int -> Name -> [LExp] -> LExp
+ IRTS.Lang: LCon :: (Maybe Name) -> Int -> Name -> [LExp] -> LExp
- IRTS.Lang: LS :: Name -> Int -> [(Name, LDecl)] -> LiftState
+ IRTS.Lang: LS :: (Maybe Name) -> Int -> [(Name, LDecl)] -> (Map ([Name], LExp) Name) -> LiftState
- IRTS.Lang: LV :: LVar -> LExp
+ IRTS.Lang: LV :: Name -> LExp
- IRTS.Lang: usedArg :: (Eq t, Foldable t1) => t1 t -> t -> [t]
+ IRTS.Lang: usedArg :: (Eq a, Foldable t) => t a -> a -> [a]
- Idris.AbsSyntax: expArg :: PArg' t -> Bool
+ Idris.AbsSyntax: expArg :: () => PArg' t -> Bool
- Idris.AbsSyntax: expandImplementationScope :: t3 -> t2 -> [(Name, t1)] -> t -> PDecl' t1 -> PDecl' t1
+ Idris.AbsSyntax: expandImplementationScope :: () => p1 -> p2 -> [(Name, t)] -> p3 -> PDecl' t -> PDecl' t
- Idris.AbsSyntax: mapsnd :: (t2 -> t1) -> (t, t2) -> (t, t1)
+ Idris.AbsSyntax: mapsnd :: () => (t -> b) -> (a, t) -> (a, b)
- Idris.AbsSyntaxTree: DoLet :: FC -> Name -> FC -> t -> t -> PDo' t
+ Idris.AbsSyntaxTree: DoLet :: FC -> RigCount -> Name -> FC -> t -> t -> PDo' t
- Idris.AbsSyntaxTree: DoLetP :: FC -> t -> t -> PDo' t
+ Idris.AbsSyntaxTree: DoLetP :: FC -> t -> t -> [(t, t)] -> PDo' t
- Idris.AbsSyntaxTree: IState :: Context -> Set ConstraintFC -> [FixDecl] -> Ctxt [PArg] -> Ctxt [Bool] -> Ctxt InterfaceInfo -> [Name] -> Ctxt RecordInfo -> Ctxt DSL -> Ctxt OptInfo -> Ctxt TypeInfo -> Ctxt [Name] -> Ctxt ([([(Name, Term)], Term, Term)], [PTerm]) -> Ctxt [FnOpt] -> Ctxt CGInfo -> Ctxt (Docstring DocTerm, [(Name, Docstring DocTerm)]) -> Ctxt (Docstring DocTerm) -> Ctxt TIData -> Ctxt FnInfo -> Ctxt [(Term, Term)] -> Ctxt [Name] -> [(FC, Name)] -> [(FC, Name)] -> [(FC, String)] -> IOption -> Int -> [((FilePath, Int), PTerm)] -> [(Name, (Maybe Name, Int, [Name], Bool, Bool))] -> [Name] -> [(Term, Term)] -> [Name] -> SyntaxRules -> [String] -> [FilePath] -> [(Name, (Int, PrimFn))] -> [(Codegen, FilePath)] -> [(Codegen, String)] -> [(Codegen, String)] -> [(Codegen, String)] -> [(FilePath, Bool)] -> [(Name, (Bool, [String]))] -> Maybe FC -> [(FC, Err)] -> Maybe Name -> [Int] -> [Maybe Int] -> Maybe FC -> Maybe FC -> Ctxt Accessibility -> Accessibility -> DefaultTotality -> [IBCWrite] -> Maybe String -> [DynamicLib] -> [LanguageExt] -> OutputMode -> Bool -> ColourTheme -> [Name] -> (Int, Ctxt (Int, Name)) -> Ctxt (Map Name (Set Name)) -> Map [Text] [Text] -> ConsoleWidth -> Set Name -> Set (Name, Int) -> [(Name, Int)] -> [Name] -> [(Name, Bool)] -> Map Name Name -> [Name] -> [(FC, OutputAnnotation)] -> [(FC, OutputAnnotation)] -> Ctxt String -> Set Name -> Map Term (Int, Term) -> Ctxt String -> InteractiveOpts -> IState
+ Idris.AbsSyntaxTree: IState :: Context -> Set ConstraintFC -> [FixDecl] -> Ctxt [PArg] -> Ctxt [Bool] -> Ctxt InterfaceInfo -> [Name] -> Ctxt RecordInfo -> Ctxt DSL -> Ctxt OptInfo -> Ctxt TypeInfo -> Ctxt [Name] -> Ctxt ([([(Name, Term)], Term, Term)], [PTerm]) -> Ctxt [FnOpt] -> Ctxt CGInfo -> Ctxt (Docstring DocTerm, [(Name, Docstring DocTerm)]) -> Ctxt (Docstring DocTerm) -> Ctxt TIData -> Ctxt FnInfo -> Ctxt [(Term, Term)] -> Ctxt [Name] -> [(FC, Name)] -> [(FC, Name)] -> [(FC, String)] -> IOption -> Int -> [((FilePath, Int), PTerm)] -> [(Name, (Maybe Name, Int, [Name], Bool, Bool))] -> [Name] -> [(Term, Term)] -> [Name] -> SyntaxRules -> [String] -> [FilePath] -> [(Name, (Int, PrimFn))] -> [(Codegen, FilePath)] -> [(Codegen, String)] -> [(Codegen, String)] -> [(Codegen, String)] -> [(FilePath, Bool)] -> [(Name, (Bool, [String]))] -> Maybe FC -> [(FC, Err)] -> Maybe Name -> [Int] -> [Maybe Int] -> Maybe FC -> Ctxt Accessibility -> Accessibility -> DefaultTotality -> [IBCWrite] -> Maybe String -> [DynamicLib] -> [LanguageExt] -> OutputMode -> Bool -> ColourTheme -> [Name] -> (Int, Ctxt (Int, Name)) -> Ctxt (Map Name (Set Name)) -> Map [Text] [Text] -> ConsoleWidth -> Set Name -> Set (Name, Int) -> [(Name, Int)] -> [Name] -> [(Name, Bool)] -> Map Name Name -> [Name] -> [(FC, OutputAnnotation)] -> [(FC, OutputAnnotation)] -> Ctxt String -> Set Name -> Map Term (Int, Term) -> Ctxt String -> InteractiveOpts -> IState
- Idris.AbsSyntaxTree: PLet :: FC -> Name -> FC -> PTerm -> PTerm -> PTerm -> PTerm
+ Idris.AbsSyntaxTree: PLet :: FC -> RigCount -> Name -> FC -> PTerm -> PTerm -> PTerm -> PTerm
- Idris.AbsSyntaxTree: PPOption :: Bool -> Bool -> Bool -> Maybe Int -> PPOption
+ Idris.AbsSyntaxTree: PPOption :: Bool -> Bool -> Bool -> Maybe Int -> Bool -> PPOption
- Idris.AbsSyntaxTree: eqDoc :: Docstring (Either (Err' t) b)
+ Idris.AbsSyntaxTree: eqDoc :: () => Docstring Either Err' t b
- Idris.AbsSyntaxTree: eqOpts :: [t]
+ Idris.AbsSyntaxTree: eqOpts :: () => [a]
- Idris.AbsSyntaxTree: eqParamDoc :: [(Name, Docstring (Either (Err' t) b))]
+ Idris.AbsSyntaxTree: eqParamDoc :: () => [(Name, Docstring Either Err' t b)]
- Idris.AbsSyntaxTree: falseDoc :: Docstring (Err' t)
+ Idris.AbsSyntaxTree: falseDoc :: () => Docstring Err' t
- Idris.AbsSyntaxTree: inferOpts :: [t]
+ Idris.AbsSyntaxTree: inferOpts :: () => [a]
- Idris.AbsSyntaxTree: pconst :: t -> PArg' t
+ Idris.AbsSyntaxTree: pconst :: () => t -> PArg' t
- Idris.AbsSyntaxTree: pexp :: t -> PArg' t
+ Idris.AbsSyntaxTree: pexp :: () => t -> PArg' t
- Idris.AbsSyntaxTree: pimp :: Name -> t -> Bool -> PArg' t
+ Idris.AbsSyntaxTree: pimp :: () => Name -> t -> Bool -> PArg' t
- Idris.AbsSyntaxTree: ptacimp :: Name -> t -> t -> PArg' t
+ Idris.AbsSyntaxTree: ptacimp :: () => Name -> t -> t -> PArg' t
- Idris.Core.Elaborate: defer :: [Name] -> Name -> Elab' aux Name
+ Idris.Core.Elaborate: defer :: [Name] -> [Name] -> Name -> Elab' aux Name
- Idris.Core.Elaborate: dumpprobs :: Show a => [(t2, t1, t, a)] -> [Char]
+ Idris.Core.Elaborate: dumpprobs :: Show a1 => [(a2, b, c, a1)] -> [Char]
- Idris.Core.Elaborate: letbind :: Name -> Raw -> Raw -> Elab' aux ()
+ Idris.Core.Elaborate: letbind :: Name -> RigCount -> Raw -> Raw -> Elab' aux ()
- Idris.Core.Evaluate: VBLet :: Int -> Name -> Value -> Value -> Value -> Value
+ Idris.Core.Evaluate: VBLet :: RigCount -> Int -> Name -> Value -> Value -> Value -> Value
- Idris.Core.ProofState: Defer :: [Name] -> Name -> Tactic
+ Idris.Core.ProofState: Defer :: [Name] -> [Name] -> Name -> Tactic
- Idris.Core.ProofState: LetBind :: Name -> Raw -> Raw -> Tactic
+ Idris.Core.ProofState: LetBind :: Name -> RigCount -> Raw -> Raw -> Tactic
- Idris.Core.ProofState: dropGiven :: (Foldable t, Foldable t1, Eq a) => t1 a -> [(a, TT a)] -> t a -> [(a, TT a)]
+ Idris.Core.ProofState: dropGiven :: (Foldable t2, Foldable t1, Eq a) => t1 a -> [(a, TT a)] -> t2 a -> [(a, TT a)]
- Idris.Core.ProofState: keepGiven :: (Foldable t, Foldable t1, Eq a) => t1 a -> [(a, TT a)] -> t a -> [(a, TT a)]
+ Idris.Core.ProofState: keepGiven :: (Foldable t2, Foldable t1, Eq a) => t1 a -> [(a, TT a)] -> t2 a -> [(a, TT a)]
- Idris.Core.TT: Let :: !b -> b -> Binder b
+ Idris.Core.TT: Let :: RigCount -> !b -> b -> Binder b
- Idris.Core.TT: emptyContext :: Map k a
+ Idris.Core.TT: emptyContext :: () => Map k a
- Idris.Core.TT: envBinders :: [(t2, t, t1)] -> [(t2, t1)]
+ Idris.Core.TT: envBinders :: () => [(a, b1, b2)] -> [(a, b2)]
- Idris.Core.TT: envZero :: [(t2, t, t1)] -> [(t2, RigCount, t1)]
+ Idris.Core.TT: envZero :: () => [(a, b, c)] -> [(a, RigCount, c)]
- Idris.Core.TT: fstEnv :: (t2, t1, t) -> t2
+ Idris.Core.TT: fstEnv :: () => (a, b, c) -> a
- Idris.Core.TT: pmap :: (t1 -> t) -> (t1, t1) -> (t, t)
+ Idris.Core.TT: pmap :: () => (t -> b) -> (t, t) -> (b, b)
- Idris.Core.TT: rigEnv :: (t1, t2, t) -> t2
+ Idris.Core.TT: rigEnv :: () => (a, b, c) -> b
- Idris.Core.TT: showEnvDbg :: (Show a, Eq a) => [(a, RigCount, Binder (TT a))] -> TT a -> [Char]
+ Idris.Core.TT: showEnvDbg :: (Show a, Eq a) => [(a, RigCount, Binder TT a)] -> TT a -> [Char]
- Idris.Core.TT: sndEnv :: (t1, t, t2) -> t2
+ Idris.Core.TT: sndEnv :: () => (a, b, c) -> c
- Idris.Core.TT: traceWhen :: Bool -> String -> t -> t
+ Idris.Core.TT: traceWhen :: () => Bool -> String -> p -> p
- Idris.Core.Typecheck: errEnv :: [(t2, t, Binder t1)] -> [(t2, t1)]
+ Idris.Core.Typecheck: errEnv :: () => [(a, b1, Binder b2)] -> [(a, b2)]
- Idris.Core.Typecheck: isHole :: (t2, t1, Binder t) -> Bool
+ Idris.Core.Typecheck: isHole :: () => (a, b1, Binder b2) -> Bool
- Idris.Elab.AsPat: desugarAs :: PTerm -> PTerm -> (PTerm, PTerm)
+ Idris.Elab.AsPat: desugarAs :: PTerm -> PTerm -> [PDecl] -> (PTerm, PTerm, [PDecl])
- Idris.Elab.Term: proofSearch' :: IState -> Bool -> Bool -> Int -> Bool -> Maybe Name -> Name -> [Name] -> [Name] -> StateT (ElabState EState) TC ()
+ Idris.Elab.Term: proofSearch' :: IState -> Bool -> Bool -> Int -> Bool -> Maybe Name -> Name -> [Name] -> [Name] -> StateT ElabState EState TC ()
- Idris.Elab.Term: solveAll :: StateT (ElabState aux) TC ()
+ Idris.Elab.Term: solveAll :: () => StateT ElabState aux TC ()
- Idris.Elab.Utils: findLinear :: IState -> [Name] -> Term -> [(Name, RigCount)]
+ Idris.Elab.Utils: findLinear :: RigCount -> IState -> [Name] -> Term -> [(Name, RigCount)]
- Idris.Elab.Utils: getFixedInType :: IState -> [Name] -> [PArg' t] -> TT Name -> [Name]
+ Idris.Elab.Utils: getFixedInType :: () => IState -> [Name] -> [PArg' t] -> TT Name -> [Name]
- Idris.Elab.Utils: getPBtys :: TT t -> [(t, TT t)]
+ Idris.Elab.Utils: getPBtys :: () => TT a -> [(a, TT a)]
- Idris.Elab.Utils: paramNames :: (Eq t1, Foldable t) => [TT t1] -> t t1 -> [Int] -> [t1]
+ Idris.Elab.Utils: paramNames :: (Eq a, Foldable t) => [TT a] -> t a -> [Int] -> [a]
- Idris.Elab.Utils: pbty :: TT n -> TT n -> TT n
+ Idris.Elab.Utils: pbty :: () => TT n -> TT n -> TT n
- Idris.Elab.Utils: psolve :: TT t -> StateT (ElabState aux) TC ()
+ Idris.Elab.Utils: psolve :: () => TT n -> StateT ElabState aux TC ()
- Idris.Elab.Utils: recheckC :: String -> FC -> (Err' (TT Name) -> Err) -> Env -> TT Name -> StateT IState (ExceptT Err IO) (Term, Type)
+ Idris.Elab.Utils: recheckC :: String -> FC -> (Err' TT Name -> Err) -> Env -> TT Name -> StateT IState ExceptT Err IO (Term, Type)
- Idris.Elab.Utils: recheckC_borrowing :: Bool -> Bool -> [Name] -> String -> FC -> (Err' (TT Name) -> Err) -> Env -> TT Name -> StateT IState (ExceptT Err IO) (Term, Type)
+ Idris.Elab.Utils: recheckC_borrowing :: Bool -> Bool -> [Name] -> String -> FC -> (Err' TT Name -> Err) -> Env -> TT Name -> StateT IState ExceptT Err IO (Term, Type)
- Idris.ElabDecls: elabDecl' :: ElabWhat -> ElabInfo -> PDecl -> StateT IState (ExceptT Err IO) ()
+ Idris.ElabDecls: elabDecl' :: ElabWhat -> ElabInfo -> PDecl -> StateT IState ExceptT Err IO ()
- Idris.IBC: loadPkgIndex :: String -> Idris ()
+ Idris.IBC: loadPkgIndex :: PkgName -> Idris ()
- Idris.Imports: findPkgIndex :: String -> Idris FilePath
+ Idris.Imports: findPkgIndex :: PkgName -> Idris FilePath
- Idris.Imports: pkgIndex :: String -> FilePath
+ Idris.Imports: pkgIndex :: PkgName -> FilePath
- Idris.Output: iWarn :: FC -> Doc OutputAnnotation -> Idris ()
+ Idris.Output: iWarn :: FC -> OutputDoc -> Idris ()
- Idris.Package: installIBC :: String -> String -> Name -> IO ()
+ Idris.Package: installIBC :: String -> PkgName -> Name -> IO ()
- Idris.Package: installIdx :: String -> String -> IO ()
+ Idris.Package: installIdx :: String -> PkgName -> IO ()
- Idris.Package: installObj :: String -> String -> String -> IO ()
+ Idris.Package: installObj :: String -> PkgName -> String -> IO ()
- Idris.Package: rmIdx :: String -> IO ()
+ Idris.Package: rmIdx :: PkgName -> IO ()
- Idris.Package: testLib :: Bool -> String -> String -> IO Bool
+ Idris.Package: testLib :: Bool -> PkgName -> String -> IO Bool
- Idris.Package.Common: PkgDesc :: String -> [String] -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> [String] -> [String] -> Maybe String -> [Opt] -> String -> [Name] -> Maybe Name -> Maybe String -> [Name] -> PkgDesc
+ Idris.Package.Common: PkgDesc :: PkgName -> [PkgName] -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> [String] -> [String] -> Maybe String -> [Opt] -> String -> [Name] -> Maybe Name -> Maybe String -> [Name] -> PkgDesc
- Idris.Package.Common: [pkgdeps] :: PkgDesc -> [String]
+ Idris.Package.Common: [pkgdeps] :: PkgDesc -> [PkgName]
- Idris.Package.Common: [pkgname] :: PkgDesc -> String
+ Idris.Package.Common: [pkgname] :: PkgDesc -> PkgName
- Idris.Parser: parseConst :: IState -> String -> Result Const
+ Idris.Parser: parseConst :: IState -> String -> Either ParseError Const
- Idris.Parser: parseElabShellStep :: IState -> String -> Result (Either ElabShellCmd PDo)
+ Idris.Parser: parseElabShellStep :: IState -> String -> Either ParseError (Either ElabShellCmd PDo)
- Idris.Parser: parseExpr :: IState -> String -> Result PTerm
+ Idris.Parser: parseExpr :: IState -> String -> Either ParseError PTerm
- Idris.Parser: parseImports :: FilePath -> String -> Idris (Maybe (Docstring ()), [String], [ImportInfo], Maybe Delta)
+ Idris.Parser: parseImports :: FilePath -> String -> Idris (Maybe (Docstring ()), [String], [ImportInfo], Maybe Mark)
- Idris.Parser: parseTactic :: IState -> String -> Result PTactic
+ Idris.Parser: parseTactic :: IState -> String -> Either ParseError PTactic
- Idris.Parser.Expr: autoImplicit :: t -> Static -> SyntaxInfo -> StateT IState IdrisInnerParser PTerm
+ Idris.Parser.Expr: autoImplicit :: () => p -> Static -> SyntaxInfo -> StateT IState WriterT FC Parsec Void String PTerm
- Idris.Parser.Expr: bindsymbol :: (LookAheadParsing m, DeltaParsing m) => [ArgOpt] -> Static -> t -> m Plicity
+ Idris.Parser.Expr: bindsymbol :: (MonadWriter FC m, MonadParsec Void String m) => [ArgOpt] -> Static -> p -> m Plicity
- Idris.Parser.Expr: constant :: IdrisParser (Const, FC)
+ Idris.Parser.Expr: constant :: Parsing m => m Const
- Idris.Parser.Expr: constraintPi :: [ArgOpt] -> Static -> SyntaxInfo -> StateT IState IdrisInnerParser PTerm
+ Idris.Parser.Expr: constraintPi :: [ArgOpt] -> Static -> SyntaxInfo -> StateT IState WriterT FC Parsec Void String PTerm
- Idris.Parser.Expr: defaultImplicit :: t -> Static -> SyntaxInfo -> StateT IState IdrisInnerParser PTerm
+ Idris.Parser.Expr: defaultImplicit :: () => p -> Static -> SyntaxInfo -> StateT IState WriterT FC Parsec Void String PTerm
- Idris.Parser.Expr: do_alt :: SyntaxInfo -> StateT IState IdrisInnerParser (PTerm, PTerm)
+ Idris.Parser.Expr: do_alt :: SyntaxInfo -> StateT IState WriterT FC Parsec Void String (PTerm, PTerm)
- Idris.Parser.Expr: explicitPi :: [ArgOpt] -> Static -> SyntaxInfo -> StateT IState IdrisInnerParser PTerm
+ Idris.Parser.Expr: explicitPi :: [ArgOpt] -> Static -> SyntaxInfo -> StateT IState WriterT FC Parsec Void String PTerm
- Idris.Parser.Expr: implicitPi :: [ArgOpt] -> Static -> SyntaxInfo -> StateT IState IdrisInnerParser PTerm
+ Idris.Parser.Expr: implicitPi :: [ArgOpt] -> Static -> SyntaxInfo -> StateT IState WriterT FC Parsec Void String PTerm
- Idris.Parser.Expr: let_binding :: SyntaxInfo -> StateT IState IdrisInnerParser (FC, PTerm, PTerm, PTerm, [(PTerm, PTerm)])
+ Idris.Parser.Expr: let_binding :: SyntaxInfo -> StateT IState WriterT FC Parsec Void String (FC, PTerm, PTerm, PTerm, [(PTerm, PTerm)])
- Idris.Parser.Expr: normalImplicit :: [ArgOpt] -> Static -> SyntaxInfo -> StateT IState IdrisInnerParser PTerm
+ Idris.Parser.Expr: normalImplicit :: [ArgOpt] -> Static -> SyntaxInfo -> StateT IState WriterT FC Parsec Void String PTerm
- Idris.Parser.Expr: unboundPi :: [ArgOpt] -> Static -> SyntaxInfo -> StateT IState IdrisInnerParser PTerm
+ Idris.Parser.Expr: unboundPi :: [ArgOpt] -> Static -> SyntaxInfo -> StateT IState WriterT FC Parsec Void String PTerm
- Idris.Parser.Expr: unboundPiNoConstraint :: [ArgOpt] -> Static -> SyntaxInfo -> StateT IState IdrisInnerParser PTerm
+ Idris.Parser.Expr: unboundPiNoConstraint :: [ArgOpt] -> Static -> SyntaxInfo -> StateT IState WriterT FC Parsec Void String PTerm
- Idris.Parser.Expr: verbatimStringLiteral :: MonadicParsing m => m (String, FC)
+ Idris.Parser.Expr: verbatimStringLiteral :: Parsing m => m String
- Idris.Parser.Helpers: char :: MonadicParsing m => Char -> m Char
+ Idris.Parser.Helpers: char :: Parsing m => Char -> m Char
- Idris.Parser.Helpers: charLiteral :: (MonadicParsing m, HasLastTokenSpan m) => m (Char, FC)
+ Idris.Parser.Helpers: charLiteral :: Parsing m => m Char
- Idris.Parser.Helpers: commaSeparated :: MonadicParsing m => m a -> m [a]
+ Idris.Parser.Helpers: commaSeparated :: Parsing m => m a -> m [a]
- Idris.Parser.Helpers: eol :: MonadicParsing m => m ()
+ Idris.Parser.Helpers: eol :: Parsing m => m ()
- Idris.Parser.Helpers: float :: (MonadicParsing m, HasLastTokenSpan m) => m (Double, FC)
+ Idris.Parser.Helpers: float :: Parsing m => m Double
- Idris.Parser.Helpers: iName :: (MonadicParsing m, HasLastTokenSpan m) => [String] -> m (Name, FC)
+ Idris.Parser.Helpers: iName :: Parsing m => [String] -> m Name
- Idris.Parser.Helpers: identifier :: (MonadicParsing m) => m (String, FC)
+ Idris.Parser.Helpers: identifier :: Parsing m => m String
- Idris.Parser.Helpers: lchar :: MonadicParsing m => Char -> m Char
+ Idris.Parser.Helpers: lchar :: Parsing m => Char -> m Char
- Idris.Parser.Helpers: lookAheadMatches :: MonadicParsing m => m a -> m Bool
+ Idris.Parser.Helpers: lookAheadMatches :: Parsing m => m a -> m Bool
- Idris.Parser.Helpers: maybeWithNS :: (MonadicParsing m, HasLastTokenSpan m) => m (String, FC) -> Bool -> [String] -> m (Name, FC)
+ Idris.Parser.Helpers: maybeWithNS :: Parsing m => m String -> [String] -> m Name
- Idris.Parser.Helpers: name :: IdrisParser (Name, FC)
+ Idris.Parser.Helpers: name :: (Parsing m, MonadState IState m) => m Name
- Idris.Parser.Helpers: natural :: (MonadicParsing m, HasLastTokenSpan m) => m (Integer, FC)
+ Idris.Parser.Helpers: natural :: Parsing m => m Integer
- Idris.Parser.Helpers: reserved :: MonadicParsing m => String -> m ()
+ Idris.Parser.Helpers: reserved :: Parsing m => String -> m ()
- Idris.Parser.Helpers: string :: MonadicParsing m => String -> m String
+ Idris.Parser.Helpers: string :: Parsing m => String -> m String
- Idris.Parser.Helpers: stringLiteral :: (MonadicParsing m, HasLastTokenSpan m) => m (String, FC)
+ Idris.Parser.Helpers: stringLiteral :: Parsing m => m String
- Idris.Parser.Helpers: symbol :: MonadicParsing m => String -> m String
+ Idris.Parser.Helpers: symbol :: Parsing m => String -> m ()
- Idris.Parser.Helpers: type IdrisParser = StateT IState IdrisInnerParser
+ Idris.Parser.Helpers: type IdrisParser = Parser IState
- Idris.Parser.Helpers: whiteSpace :: MonadicParsing m => m ()
+ Idris.Parser.Helpers: whiteSpace :: Parsing m => m ()
- Idris.Parser.Ops: fnName :: IdrisParser (Name, FC)
+ Idris.Parser.Ops: fnName :: (Parsing m, MonadState IState m) => m Name
- Idris.Parser.Ops: operatorFront :: IdrisParser (Name, FC)
+ Idris.Parser.Ops: operatorFront :: Parsing m => m Name
- Idris.Parser.Ops: table :: [FixDecl] -> OperatorTable IdrisParser PTerm
+ Idris.Parser.Ops: table :: [FixDecl] -> [[Operator IdrisParser PTerm]]
- Idris.REPL.Commands: Apropos :: [String] -> String -> Command
+ Idris.REPL.Commands: Apropos :: [PkgName] -> String -> Command
- Idris.REPL.Commands: Search :: [String] -> PTerm -> Command
+ Idris.REPL.Commands: Search :: [PkgName] -> PTerm -> Command
- Idris.REPL.Parser: parseCmd :: IState -> String -> String -> Result (Either String Command)
+ Idris.REPL.Parser: parseCmd :: IState -> String -> String -> Either ParseError (Either String Command)
- Idris.TypeSearch: searchByType :: [String] -> PTerm -> Idris ()
+ Idris.TypeSearch: searchByType :: [PkgName] -> PTerm -> Idris ()

Files

+ .github/ISSUE_TEMPLATE.md view
@@ -0,0 +1,9 @@+Please attach complete source files that exhibit the issue in addition+to quoting from them here.++# Steps to Reproduce++# Expected Behavior++# Observed Behavior+
.gitignore view
@@ -1,5 +1,6 @@ # Build artefacts dist+dist-newstyle *.ibc *.o *.a
CHANGELOG.md view
@@ -1,3 +1,131 @@+# New in 1.2.0++## Language updates+++ In `@`-patterns such as `x@p`, `x` is now in scope on the right-hand side+  of any definitions in `where` clauses, provided the left-hand side of the+  definition does not shadow it.++ The `LinearTypes` language extension has been revised. It implements the+  rules from Bob Atkey's draft "The Syntax and Semantics of Quantitative+  Type Theory" and now works with holes and case expressions.++ Backticked operators can appear in sections, e.g. ``(`LTE` 42)`` or+  ``(1 `plus`)``.++ Backticked operators can have their precendence and associativity set like+  other operators, e.g. ``infixr 8 `cons` ``.  Backticked operators with+  undeclared fixity are treated as non-associative with precedence lower+  than all declared operators.++ Allow non-injective implementations if explicitly named, e.g.,+  ```idris+  LTB : Nat -> Type+  LTB b = DPair Nat (\ n  => LT n b)++  implementation [uninhabltb] Uninhabited (LTB Z) where+    uninhabited (MkDPair n prf) = absurd prf+  ```+  It is possible to use `using implementation uninhabltb` to add the+  implementation to the automated resolution, but if it fails to find the+  instance due to non-injectivity, one must pass it explicitly to target+  function, i.e. `absurd @{uninhabltb}`.++ Verbatim strings now support trailing quote characters. All quote characters+  until the final three are considered part of the string. Now a string such as+  `""""hello""""` will parse, and is equivalent to `"\"hello\""`.++ C FFI now supports pasting in any expression by prefixing it with '#', e.g.+  ```idris+  intMax : IO Int+  intMax = foreign FFI_C "#INT_MAX" (IO Int) +  ```++ The deprecated keywords `%assert_total`, `abstract`, and `[static]` have+  been removed as well as the use of "public" instead of "public export" to+  expose a symbol.++ The syntax for pattern-match alternatives now works for `let` statements in+  `do` blocks in addition to `let` expressions and `<-` statements, e.g.+  ```idris+    do …+       let Just x = expr | Nothing => empty+       …+  ```+  This means that a `with`-application (using `|`) cannot be used in that+  position anymore.++## Library Updates+++ Removed `oldeffects` library from `libs` folder, use `effects` or `Control.ST` instead.++ Added `Text.Literate`, a module for working with literate source files.++ Added `Data.IORef`, for working with mutable references in `IO` and `JS_IO`.++ Added `discriminate` and `construct` tactics to Pruviloj.++ Added `IsSucc` type to `Prelude`, which proves that a `Nat` is a successor.++ Added `Data.IOArray`, containing primitives for mutable arrays.++ Added `Language.JSON`, for total serialization/deserialization of JSON data.++ Reworked operator fixity for many operators.+  * Changed `&&` and `||` to be right-associative. Increased precedence of `&&`+    to be higher than that of `||`.+  * Removed associativity from Boolean comparison operators `==`, `/=`, `<`, `<=`,+    `>`, and `>=`. Increased precedence of `/=` and `==` to match the others.+  * Made `<|>`, `<$>`, and `.` right-associative.+  * Swapped precedence of `<|>` and `<*>` (and its related operators, `<*` and+    `*>`). Now `<|>` has a lower precedence.+  * Lowered the precedence of `>>=` to be below that of `<|>`.++ Added some useful string manipulation functions to `Data.String.Extra`.++ Added `Control.Delayed`, a module for conditionally making a type `Inf` or `Lazy`.++ Added `Data.Fuel`, which implements the `Fuel` data type and the partial `forever` function.++ Added `Data.Bool.Extra`, a module with properties of boolean operations.++ Moved core of `Text.Lexer` to `Text.Lexer.Core`. Added several new combinators+  and lexers to `Text.Lexer`.++ Moved core of `Text.Parser` to `Text.Parser.Core`. Added several new combinators+  to `Text.Parser`. Made the following changes.+  * Flipped argument order of `parse`.+  * Renamed `optional` to `option` and flip argument order.+  * Renamed `maybe` to `optional`.+  * Generalised many combinators to use an unknown `commit` flag where possible.++ `Prelude.Doubles.atan2` is now implemented as a primitive instead of+  being coded in Idris.++ Added `Test.Unit` to `contrib` for simple unit testing.++ Removed several deprecated items from the libraries shipped with Idris.++ Moved `abs` from the `Neg` interface into its own `Abs` interface.  `Nat`+  implements `Abs` with `abs = id`.++ Added `Control.ST.File`, an ST based implementation of the same behaviour +  implemented by `Effect.File` in the effects package.++## Tool Updates+++ Private functions are no longer visible in the REPL except for modules+  that are explicitly loaded.++ The --interface option now creates CommonJS modules on the node backend.++ The C backend now pass arguments to the C compiler in the same order+  as they were given in the source files.++ Backslash, braces and percent symbols are now correctly pretty printed+  in LaTeX.++ Errors and warnings now consistently have the following format:+  ```idris+  reg068.idr:1:6-8:+    |+  1 | data nat : Type where --error+    |      ~~~+  Main.nat has a name which may be implicitly bound.+  This is likely to lead to problems!+  ```+  The code is highlighted when highlighting information is available.  How+  much highlighting information is available depends on where the error+  occurred.++ The parser provider has been switched from Trifecta to Megaparsec.  This+  could possibly cause some subtle deviations in parsing from previous+  versions of Idris.++ Many more errors now report beginning *and* ending position (which may be+  on different lines), instead of just a single point.  The format is+  `Foo.idr:9:7-15:` if ending column is on the same line or+  `Foo.idr:9:7-10:15:` if the ending column is on a different line.++ Error messages were changed so that the last column is inclusive, e.g.+  `Foo.idr:9:7-15:` includes column 15.  Previously the error would have read+  `Foo.idr:9:7-16:`.++## Packaging Updates+++ Package names now only accept a restrictive charset of letters, numbers and the `-_` characters.+  Package names are also case insensitive.++ When building makefiles for the FFI, the environment variables+  `IDRIS_INCLUDES` and `IDRIS_LDFLAGS` are now set with the correct C+  flags.+ # New in 1.1.1  + Erasure analysis is now faster thanks to a bit smarter constraint solving.
CONTRIBUTING.md view
@@ -20,6 +20,21 @@ Before you report an issue, or wish to add cool functionality please try and check to see if there are existing [issues](https://github.com/idris-lang/Idris-dev/issues) and [pull requests](https://github.com/idris-lang/Idris-dev/pulls). We do not want you wasting your time, duplicating somebody's work! +### Template+Try as closely as possible to describe the issue, ensuring that it has sections that match the following headings:+> \# Steps to Reproduce+>+> \# Expected Behavior+> +> \# Observed Behavior+> +>++In addition, please attach complete source files that exhibit the issue to quoting from them in the issue.++### Feature Requests+We would be delighted to receive feature requests only if they are feasible to implement and the author is willing to implement the suggested features themself. The current Idris developer team consists mostly of volunteers, and so it is unfortunately hard to accommodate implementing nice-to-have ideas that are not essential for core language development.+ ## The Campsite Rule  We try to follow the **campsite rule**: leave the code base in better condition than you found it.
CONTRIBUTORS view
@@ -8,6 +8,7 @@ Ahmad Salim Al-Sibahi Aistis Raulinaitis Alex Feldman-Crough+Alex S. Queiroz e Silva Alexander Berntsen Alexander Shabalin Alyssa Carter@@ -33,6 +34,7 @@ Brian Koropoff Brian McKenna Bryn Keller+Caleb Case Calvin Beck Carsten König Carter Charbonneau@@ -106,6 +108,7 @@ Jan Doms Jan Stolarek Jason Dagit+Jason Felice Jason Gross Jean-Remi Desjardins Jeff Hemphill@@ -119,8 +122,10 @@ John Dobronszki John Wiegley Jon Atack+Jonas De Vuyst Jonas Westerlund Jonathan Sterling+Joomy Korkut Joseph Huang Josh Vera JP Smith@@ -151,6 +156,7 @@ Michael Hensler Michael Maloney Michael McGirr+Michael Morgan Michael Thompson Michael Weiss Miikka Koskinen@@ -176,6 +182,7 @@ Robert Clipsham Robert Edström Ross Meikleham+Rui Barreiro Ryan Scott Sam Elliott Sam T@@ -197,9 +204,11 @@ suhorng Sune Alkærsig Sven Koschnicke+Taran Lynn tdidriksen Tenor Biel Thomas Cooper+Thomas Scholtes Tim Dysinger Tim McGilchrist Timo Petteri Sinnemäki
Setup.hs view
@@ -26,6 +26,11 @@ import qualified System.FilePath.Posix as Px import System.Process +#if (MIN_VERSION_Cabal(2,0,0))+import Distribution.Types.UnqualComponentName+#endif++ -- After Idris is built, we need to check and install the prelude and other libs  -- -----------------------------------------------------------------------------@@ -228,11 +233,16 @@       let buildinfo = (emptyBuildInfo { cppOptions = ["-DVERSION="++hash] }) :: BuildInfo       return (Just buildinfo, []) ++#if !(MIN_VERSION_Cabal(2,0,0))+mkUnqualComponentName = id+#endif+ idrisPreBuild args flags = do #ifdef mingw32_HOST_OS         createDirectoryIfMissingVerbose verbosity True dir         windres verbosity ["icons/idris_icon.rc","-o", dir++"/idris_icon.o"]-        return (Nothing, [("idris", emptyBuildInfo { ldOptions = [dir ++ "/idris_icon.o"] })])+        return (Nothing, [(mkUnqualComponentName "idris", emptyBuildInfo { ldOptions = [dir ++ "/idris_icon.o"] })])      where         verbosity = S.fromFlag $ S.buildVerbosity flags         dir = S.fromFlagOrDefault "dist" $ S.buildDistPref flags
appveyor.yml view
@@ -5,13 +5,13 @@      mkdir C:\ghc -    Invoke-WebRequest "http://downloads.haskell.org/~ghc/7.10.3/ghc-7.10.3-x86_64-unknown-mingw32.tar.xz" -OutFile C:\ghc\ghc.tar.xz -UserAgent "Curl"-    +    Invoke-WebRequest "http://downloads.haskell.org/~ghc/8.2.1/ghc-8.2.1-x86_64-unknown-mingw32.tar.xz" -OutFile C:\ghc\ghc.tar.xz -UserAgent "Curl"+     7z x C:\ghc\ghc.tar.xz -oC:\ghc-    +     7z x C:\ghc\ghc.tar -oC:\ghc -    $env:PATH="$env:PATH;c:\ghc\ghc-7.10.3\bin;$HOME\AppData\Roaming\cabal\bin"+    $env:PATH="$env:PATH;c:\ghc\ghc-8.2.1\bin;$HOME\AppData\Roaming\cabal\bin"      cabal update @@ -21,6 +21,7 @@   MSYSTEM: MINGW64   MSYS2_PATH_TYPE: inherit build_script:-- ps: c:\msys64\usr\bin\bash -l -c "cd $env:current_posix && cabal install -fffi -j4 --enable-tests"+- ps: >-+    c:\msys64\usr\bin\bash -l -c "cd $env:current_posix && cabal install -fffi --enable-tests 2>&1" test_script:-- ps: c:\msys64\usr\bin\bash -l -c "cd $env:current_posix && make test_c"+- ps: c:\msys64\usr\bin\bash -l -c "cd $env:current_posix && make test_c 2>&1"
benchmarks/fasta/fasta.idr view
@@ -38,10 +38,6 @@ replicate 0 c = "" replicate n c = singleton c <+> replicate (n-1) c -scanl : (f : acc -> a -> acc) -> acc -> List a -> List acc-scanl f q ls = q :: (case ls of-                        []    => []-                        x::xs => scanl f (f q x) xs)  accum : (Char,Double) -> (Char,Double) -> (Char,Double) accum (_,p) (c,q) = (c,p+q)
codegen/idris-codegen-c/Main.hs view
@@ -1,7 +1,6 @@ module Main where  import Idris.AbsSyntax-import Idris.Core.TT import Idris.ElabDecls import Idris.Main import Idris.Options@@ -9,8 +8,6 @@ import IRTS.Compiler  import Util.System--import Paths_idris  import Control.Monad import System.Environment
codegen/idris-codegen-javascript/Main.hs view
@@ -1,14 +1,11 @@ module Main where  import Idris.AbsSyntax-import Idris.Core.TT import Idris.ElabDecls import Idris.Main import Idris.Options import IRTS.CodegenJavaScript import IRTS.Compiler--import Paths_idris  import System.Environment import System.Exit
codegen/idris-codegen-node/Main.hs view
@@ -1,7 +1,6 @@ module Main where  import Idris.AbsSyntax-import Idris.Core.TT import Idris.ElabDecls import Idris.Main import Idris.Options@@ -10,10 +9,13 @@  import Paths_idris +import Control.Monad+ import System.Environment import System.Exit  data Opts = Opts { inputs :: [FilePath]+                 , interface :: Bool                  , output :: FilePath                  } @@ -23,17 +25,20 @@  getOpts :: IO Opts getOpts = do xs <- getArgs-             return $ process (Opts [] "main.js") xs+             return $ process (Opts [] False "main.js") xs   where     process opts ("-o":o:xs) = process (opts { output = o }) xs+    process opts ("--interface":xs) = process (opts { interface = True }) xs     process opts (x:xs) = process (opts { inputs = x:inputs opts }) xs     process opts [] = opts  jsMain :: Opts -> Idris () jsMain opts = do elabPrims                  loadInputs (inputs opts) Nothing-                 mainProg <- elabMain-                 ir <- compile (Via IBCFormat "node") (output opts) (Just mainProg)+                 mainProg <- if interface opts+                                then return Nothing+                                else liftM Just elabMain+                 ir <- compile (Via IBCFormat "node") (output opts) mainProg                  runIO $ codegenNode ir  main :: IO ()
docs/conf.py view
@@ -59,9 +59,9 @@ # built documents. # # The short X.Y version.-version = '1.0'+version = '1.2' # The full version, including alpha/beta/rc tags.-release = '1.0'+release = '1.2.0'  # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages.@@ -222,7 +222,7 @@     \begin{center}         \includegraphics[width=0.25\textwidth]{idris-512x512.png}\par         \vspace{1cm}-        {\huge\sffamily\bfseries Documentation for the Idris Language\par}+        {\huge\sffamily\bfseries \makeatletter\@title\makeatother\par}         \vspace{1cm}         {\Large Version \version\par}     \end{center}@@ -284,8 +284,8 @@ \definecolor{VerbatimBorderColor}{rgb}{1,1,1} ''', -'maketitle': latex_title_page-+'maketitle': latex_title_page,+'tableofcontents': "\\tableofcontents" # Latex figure (float) alignment #'figure_align': 'htbp', }@@ -294,7 +294,8 @@ # (source start file, target name, title, #  author, documentclass [howto, manual, or own class]). latex_documents = [-  ('index',  'idris.tex',  u'Documentation for the Idris Language',    u'The Idris Community', 'report')+  ('index',  'idris-documentation-complete.tex',  u'Documentation for the Idris Language',    u'The Idris Community', 'report'),+   ('tutorial/index',  'idris-tutorial.tex',  u'The Idris Tutorial',    u'The Idris Community', 'howto'), ]  
docs/effects/state.rst view
@@ -452,7 +452,7 @@     TransEff.Eff  : (t : Type) -> (input_effs : List EFFECT) ->                                   (output_effs : List EFFECT) -> Type     DepEff.Eff    : (t : Type) -> (input_effs : List EFFECT) ->-                                  (output_effs_fn : x -> List EFFECT) -> Type+                                  (output_effs_fn : t -> List EFFECT) -> Type  So far, we have used only the first version, ``SimpleEff.Eff``, which is defined as follows:
docs/faq/faq.rst view
@@ -137,7 +137,7 @@  ...which is probably not what was intended!  The reason for this rule is so that it is clear just from looking at the type of ``append``, and no other-context, what the implicitly bound names are. +context, what the implicitly bound names are.  If you want to use an unapplied name in a type, you have two options. You can either explicitly qualify it, for example, if ``ty`` is defined in the@@ -149,7 +149,7 @@  Alternatively, you can use a name which does not begin with a lower case letter, which will never be implicitly bound:-    + .. code-block:: idris      Ty : Type@@ -282,6 +282,11 @@ This answer is based on Edwin Brady's response in the following `pull request <https://github.com/idris-lang/Idris-dev/pull/694#issuecomment-29559291>`__. +Where can I find the community standards for the Idris community?+==================================================================++The Idris Community Standards are stated `here+<https://www.idris-lang.org/documentation/community-standards/>`_ .  Where can I find more answers? ==============================
− docs/faq/index.rst
@@ -1,19 +0,0 @@-.. _faq-index:--##########################-Frequently Asked Questions-##########################--.. note::-   The documentation for Idris has been published under the Creative-   Commons CC0 License. As such to the extent possible under law, *The-   Idris Community* has waived all copyright and related or neighboring-   rights to Documentation for Idris.--   More information concerning the CC0 can be found online at: http://creativecommons.org/publicdomain/zero/1.0/---.. toctree::-   :maxdepth: 1--   faq
docs/listing/idris-prompt-helloworld.txt view
@@ -1,7 +1,7 @@ $ idris hello.idr      ____    __     _     /  _/___/ /____(_)____-    / // __  / ___/ / ___/     Version 1.0+    / // __  / ___/ / ___/     Version 1.2.0   _/ // /_/ / /  / (__  )      http://www.idris-lang.org/  /___/\__,_/_/  /_/____/       Type :? for help 
docs/listing/idris-prompt-interp.txt view
@@ -1,7 +1,7 @@ $ idris interp.idr      ____    __     _     /  _/___/ /____(_)____-    / // __  / ___/ / ___/     Version 1.0+    / // __  / ___/ / ___/     Version 1.2.0   _/ // /_/ / /  / (__  )      http://www.idris-lang.org/  /___/\__,_/_/  /_/____/       Type :? for help 
docs/listing/idris-prompt-start.txt view
@@ -1,7 +1,7 @@ $ idris     ____    __     _    /  _/___/ /____(_)____-   / // __  / ___/ / ___/     Version 1.0+   / // __  / ___/ / ___/     Version 1.2.0  _/ // /_/ / /  / (__  )      http://www.idris-lang.org/ /___/\__,_/_/  /_/____/       Type :? for help 
docs/proofs/inductive.rst view
@@ -1,3 +1,5 @@+.. _sect-inductive:+ **************** Inductive Proofs ****************
docs/reference/ffi.rst view
@@ -217,8 +217,129 @@     errno : IO Ptr     errno = foreign FFI_C "&errno" (IO Ptr) -For more complicated interactions with C (such as reading and setting fields of a C struct), there is-a module CFFI available in the contrib package.+If the foreign name is prefixed by a ``#``, the name is pasted in literally. This is+useful to access constants that are preprocessor definitions (like ``INT_MAX``).++.. code-block:: idris++    %include C "limits.h"++    -- access the preprocessor definition INT_MAX+    intMax : IO Int+    intMax = foreign FFI_C "#INT_MAX" (IO Int)++    main : IO ()+    main = print !intMax++For more complicated interactions with C (such as reading and setting fields+of a C struct), there is a module CFFI available in the contrib package.++C heap+------++Idris has two heaps where objects can be allocated:+++--------------------------------------+---------------------------------------++| FP heap                              | C heap                                |++======================================+=======================================++| Cheney-collected                     | Mark-and-sweep-collected              |++--------------------------------------+---------------------------------------++| Garbage collections touches only     | Garbage collection has to traverse    |+| live objects.                        | all registered items.                 |++--------------------------------------+---------------------------------------++| Ideal for FP-style rapid allocation  | Ideal for C-style allocation of a few |+| of lots of small short-lived pieces  | big buffers.                          |+| of memory, such as data constructors.|                                       |++--------------------------------------+---------------------------------------++| Finalizers are impossible to support | Items have finalizers that are called |+| reasonably.                          | on deallocation.                      |++--------------------------------------+---------------------------------------++| Data is copied all the time (when    | Copying does not happen.              |+| collecting garbage, modifying data,  |                                       |+| registering managed pointers, etc.)  |                                       |++--------------------------------------+---------------------------------------++| Contains objects of various types.   | Contains C heap items: ``(void *)``   |+|                                      | pointers with finalizers. A finalizer |+|                                      | is a routine that deallocates the     |+|                                      | resources associated with the item.   |++--------------------------------------+---------------------------------------++| Fixed set of object types.           | The data pointer may point            |+|                                      | to anything, as long as the finalizer |+|                                      | cleans up correctly.                  |++--------------------------------------+---------------------------------------++| Not suitable for C resources and     | Suitable for C resources and arbitrary|+| arbitrary pointers.                  | pointers.                             |++--------------------------------------+---------------------------------------++| Values form a compact memory block.  | Items are kept in a linked list.      |++--------------------------------------+---------------------------------------++| Any Idris value, most notably        | Items represented by the              |+| ``ManagedPtr``.                      | Idris type ``CData``.                 |++--------------------------------------+---------------------------------------++| Data of ``ManagedPtr`` allocated     | Data allocated in C, pointer copied   |+| in C, buffer then copied into the FP | into the C heap.                      |+| heap.                                |                                       |++--------------------------------------+---------------------------------------++| Allocation and reallocation not      | Allocated and reallocate freely in C, |+| possible from C code (without having | registering the allocated items       |+| a reference to the VM). Everything   | in the FFI.                           |+| is copied instead.                   |                                       |++--------------------------------------+---------------------------------------+++The FP heap is the primary heap. It may contain values of type ``CData``,+which are references to items in the C heap. A C heap item contains+a ``(void *)`` pointer and the corresponding finalizer. Once a C heap item+is no longer referenced from the FP heap, it is marked as unused and+the next GC sweep will call its finalizer and deallocate it.++There is no Idris interface for ``CData`` other than its type and FFI.++Usage from C code+~~~~~~~~~~~~~~~~~++* Although not enforced in code, ``CData`` is meant to be opaque+  and non-RTS code (such as libraries or C bindings) should+  access only its ``(void *)`` field called ``data``.++* Feel free to mutate both the pointer ``data`` (eg. after calling ``realloc``)+  and the memory it points to. However, keep in mind+  that this must not break Idris's referential transparency.++* **WARNING!** If you call ``cdata_allocate`` or ``cdata_manage``,+  the resulting ``CData`` object *must* be returned from your+  FFI function so that it is inserted in the C heap by the RTS.+  Otherwise the memory will be leaked.++.. code:: idris++    some_allocating_fun : Int -> IO CData+    some_allocating_fun i = foreign FFI_C "some_allocating_fun" (Int -> IO CData) i++    other_fun : CData -> Int -> IO Int+    other_fun cd i = foreign FFI_C "other_fun" (CData -> Int -> IO Int) cd i++.. code:: cpp++    #include "idris_rts.h"++    static void finalizer(void * data)+    {+        MyStruct * ptr = (MyStruct *) data;+        free_something(ptr->something);+        free(ptr);+    }++    CData some_allocating_fun(int arg)+    {+        void * data = (void *) malloc(...);+        // ...+        return cdata_manage(data, finalizer);+    }++    int other_fun(CData cd, int arg)+    {+        int result = foo(cd->data);+        return result;+    }  FFI implementation ------------------
docs/reference/ide-protocol.rst view
@@ -113,7 +113,7 @@     Return a highlighted string consisting of the results of making all arguments in serialised term ``TM`` (which would previously have been sent as the ``tt-term`` property of a string) follow their usual implicitness setting.    ``(:elaborate-term TM)``-    Return a highlighted string consisting of the the core language term corresponding to serialised term ``TM`` (which would previously have been sent as the ``tt-term`` property of a string).+    Return a highlighted string consisting of the core language term corresponding to serialised term ``TM`` (which would previously have been sent as the ``tt-term`` property of a string).    ``(:print-definition NAME)``     Return the definition of ``NAME`` as a highlighted string.
docs/reference/misc.rst view
@@ -100,113 +100,6 @@                       (x :: qsort (assert_smaller (x :: xs) (filter (>= x) xs))))  -C heap-======--Idris has two heaps where objects can be allocated:--+--------------------------------------+---------------------------------------+-| FP heap                              | C heap                                |-+======================================+=======================================+-| Cheney-collected                     | Mark-and-sweep-collected              |-+--------------------------------------+---------------------------------------+-| Garbage collections touches only     | Garbage collection has to traverse    |-| live objects.                        | all registered items.                 |-+--------------------------------------+---------------------------------------+-| Ideal for FP-style rapid allocation  | Ideal for C-style allocation of a few |-| of lots of small short-lived pieces  | big buffers.                          |-| of memory, such as data constructors.|                                       |-+--------------------------------------+---------------------------------------+-| Finalizers are impossible to support | Items have finalizers that are called |-| reasonably.                          | on deallocation.                      |-+--------------------------------------+---------------------------------------+-| Data is copied all the time (when    | Copying does not happen.              |-| collecting garbage, modifying data,  |                                       |-| registering managed pointers, etc.)  |                                       |-+--------------------------------------+---------------------------------------+-| Contains objects of various types.   | Contains C heap items: ``(void *)``   |-|                                      | pointers with finalizers. A finalizer |-|                                      | is a routine that deallocates the     |-|                                      | resources associated with the item.   |-+--------------------------------------+---------------------------------------+-| Fixed set of object types.           | The data pointer may point            |-|                                      | to anything, as long as the finalizer |-|                                      | cleans up correctly.                  |-+--------------------------------------+---------------------------------------+-| Not suitable for C resources and     | Suitable for C resources and arbitrary|-| arbitrary pointers.                  | pointers.                             |-+--------------------------------------+---------------------------------------+-| Values form a compact memory block.  | Items are kept in a linked list.      |-+--------------------------------------+---------------------------------------+-| Any Idris value, most notably        | Items represented by the              |-| ``ManagedPtr``.                      | Idris type ``CData``.                 |-+--------------------------------------+---------------------------------------+-| Data of ``ManagedPtr`` allocated     | Data allocated in C, pointer copied   |-| in C, buffer then copied into the FP | into the C heap.                      |-| heap.                                |                                       |-+--------------------------------------+---------------------------------------+-| Allocation and reallocation not      | Allocated and reallocate freely in C, |-| possible from C code (without having | registering the allocated items       |-| a reference to the VM). Everything   | in the FFI.                           |-| is copied instead.                   |                                       |-+--------------------------------------+---------------------------------------+--The FP heap is the primary heap. It may contain values of type ``CData``,-which are references to items in the C heap. A C heap item contains-a ``(void *)`` pointer and the corresponding finalizer. Once a C heap item-is no longer referenced from the FP heap, it is marked as unused and-the next GC sweep will call its finalizer and deallocate it.--There is no Idris interface for ``CData`` other than its type and FFI.--Usage from C code--------------------* Although not enforced in code, ``CData`` is meant to be opaque-  and non-RTS code (such as libraries or C bindings) should-  access only its ``(void *)`` field called ``data``.--* Feel free to mutate both the pointer ``data`` (eg. after calling ``realloc``)-  and the memory it points to. However, keep in mind-  that this must not break Idris's referential transparency.--* **WARNING!** If you call ``cdata_allocate`` or ``cdata_manage``,-  the resulting ``CData`` object *must* be returned from your-  FFI function so that it is inserted in the C heap by the RTS.-  Otherwise the memory will be leaked.--.. code:: idris--    some_allocating_fun : Int -> IO CData-    some_allocating_fun i = foreign FFI_C "some_allocating_fun" (Int -> IO CData) i--    other_fun : CData -> Int -> IO Int-    other_fun cd i = foreign FFI_C "other_fun" (CData -> Int -> IO Int) cd i--.. code:: cpp--    #include "idris_rts.h"--    static void finalizer(void * data)-    {-        MyStruct * ptr = (MyStruct *) data;-        free_something(ptr->something);-        free(ptr);-    }--    CData some_allocating_fun(int arg)-    {-        void * data = (void *) malloc(...);-        // ...-        return cdata_manage(data, finalizer);-    }--    int other_fun(CData cd, int arg)-    {-        int result = foo(cd->data);-        return result;-    }- Preorder reasoning ================== 
docs/reference/packages.rst view
@@ -91,7 +91,10 @@  + ``makefile = <file>``, which specifies a ``Makefile``, to be built   before the Idris modules, for example to support linking with a-  ``C`` library.+  ``C`` library. When building, Idris sets the environment variables+  ``IDRIS_INCLUDES`` (with C include flags) and ``IDRIS_LDFLAGS``+  (with C linking flags) so they can be used from inside the+  ``Makefile``.  + ``libs = <libs>``, which takes a comma separated list of libraries   which must be present for the package to be usable.
docs/reference/syntax-guide.rst view
@@ -168,7 +168,7 @@ Records ~~~~~~~ -There is a special syntax for data types with one constructors and+There is a special syntax for data types with one constructor and multiple fields.  .. code:: idris@@ -219,7 +219,7 @@   data Stream : Type -> Type where     (::) a -> Inf (Stream a) -> Stream a -Every occurence of the the defined type in a constructor argument will be+Every occurence of the defined type in a constructor argument will be wrapped in the ``Inf`` type constructor. This has the effect of delaying the evaluation of the second argument when the data constructor is applied. An ``Inf`` argument is constructed using ``Delay`` (which Idris will insert@@ -407,7 +407,6 @@     %no_implicit     %error_handler     %error_reverse-    %assert_total     %reflection     %specialise [<name list>] 
docs/st/state.rst view
@@ -19,10 +19,10 @@              Type  A value of type ``STrans m resultType in_res out_res_fn`` represents a sequence-of actions which can manipulate state. The arguments are: +of actions which can manipulate state. The arguments are:  * ``m``, which is an underlying *computation context* in which the actions will be executed.-  Usually, this will be a generic type with a ``Monad`` implementation, but +  Usually, this will be a generic type with a ``Monad`` implementation, but   it isn't necessarily so. In particular, there is no need to understand monads   to be able to use ``ST`` effectively! * ``resultType``, which is the type of the value the sequence will produce@@ -76,10 +76,10 @@     same. We'll introduce a much more concise way of writing this type at the     end of this section (:ref:`sttype`), when we describe the ``ST`` type     itself.-                   + This function reads the value stored at the resource ``x`` with ``read``, increments it then writes the result back into the resource ``x`` with-``write``. We'll see the types of ``read`` and ``write`` shortly +``write``. We'll see the types of ``read`` and ``write`` shortly (see :ref:`stransprimops`). We can also create and delete resources:  .. code-block:: idris@@ -104,7 +104,7 @@ ``runPure``. For example, try entering the above definitions in a file ``Intro.idr`` then running the following at the REPL: -.. code:: +.. code::      *Intro> runPure (makeAndIncrement 93)     94 : Integer@@ -179,7 +179,7 @@     Conceptually, at least, you can think of it as having the following type:      .. code-block:: idris-    +         (!) : STrans m a state_in state_out -> a      It is syntactic sugar for binding a variable immediately before the@@ -243,7 +243,7 @@ in any context (as long as it has an implementation of ``Applicative``) and we can execute ``ioMakeAndIncrement`` at the REPL as follows: -.. code:: +.. code::      *Intro> :exec run ioMakeAndIncrement     Enter a number: 93@@ -269,7 +269,7 @@   addElement vec item = do xs <- read vec                            write vec (item :: xs) -Note that you'll need to ``import Data.Vect`` to try this example. +Note that you'll need to ``import Data.Vect`` to try this example.  .. topic:: Updating a state directly with ``update`` @@ -344,7 +344,7 @@ Then, when we implement ``readAndAdd`` we need to return the appropriate value for the output state. If we've added an item to the vector, we need to return ``True``, otherwise we need to return ``False``:-                                                     + .. code-block:: idris    readAndAdd : ConsoleIO io => (vec : Var) ->@@ -435,7 +435,7 @@  .. _stransprimops: -``STrans`` Primitive operations +``STrans`` Primitive operations ===============================  Now that we've written a few small examples of ``STrans`` functions, it's@@ -485,7 +485,7 @@  .. code-block:: idris -    new : (val : state) -> +    new : (val : state) ->           STrans m Var res (\lbl => (lbl ::: State state) :: res)  It's important that the new resource has type ``State state``, rather than@@ -526,7 +526,7 @@  .. code-block:: idris -    returning : (result : ty) -> +    returning : (result : ty) ->                 STrans m () res (const (out_fn result)) ->                 STrans m ty res out_fn @@ -555,7 +555,7 @@ .. _sttype:  `ST`: Representing state transitions directly-============================================+=============================================  We've seen a few examples of small ``STrans`` functions now, and their types can become quite verbose given that we need to provide explicit@@ -568,7 +568,7 @@ .. code-block:: idris      ST : (m : Type -> Type) ->-         (resultType : Type) -> +         (resultType : Type) ->          List (Action resultType) -> Type  ``ST`` is a type level function which computes an appropriate ``STrans``@@ -593,9 +593,9 @@ That is, ``increment`` begins and ends with ``x`` in state ``State Integer``.  .. code-block:: idris-  -  makeAndIncrement : Int -> ST m Int [] +  makeAndIncrement : Integer -> ST m Integer []+ That is, ``makeAndIncrement`` begins and ends with no resources.  .. code-block:: idris@@ -652,5 +652,3 @@ section, we'll see how to use the facilities provided by ``ST`` to write a precise API for a system with security properties: a data store requiring a login.--
docs/tutorial/index.rst view
@@ -4,7 +4,7 @@ The Idris Tutorial ################## -This is the Idris Tutorial. +This is the Idris Tutorial. It provides a brief introduction to programming in the Idris Language. It covers the core language features, and assumes some familiarity with an existing functional programming language such as Haskell or OCaml.@@ -30,6 +30,7 @@    interp    views    theorems+   provisional    interactive    syntax    miscellany
docs/tutorial/interfaces.rst view
@@ -48,7 +48,7 @@ Only one implementation of an interface can be given for a type — implementations may not overlap. Implementation declarations can themselves have constraints. To help with resolution, the arguments of an implementation must be-constructors (either data or type constructors) or variables +constructors (either data or type constructors) or variables (i.e. you cannot give an implementation for a function).  For example, to define a ``Show`` implementation for vectors, we need to know that there is a ``Show`` implementation for the element type, because we are@@ -157,7 +157,7 @@ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  Idris is strictly "define before use", except in ``mutual`` blocks.-In a ``mutual`` block, Idris elaborates in two passes: types on the first +In a ``mutual`` block, Idris elaborates in two passes: types on the first pass and definitions on the second. When the mutual block contains an interface declaration, it elaborates the interface header but none of the method types on the first pass, and elaborates the method types and any@@ -259,7 +259,7 @@     Nothing : Maybe Int  Pattern Matching Bind----------------------+~~~~~~~~~~~~~~~~~~~~~  Sometimes we want to pattern match immediately on the result of a function in ``do`` notation. For example, let's say we have a function ``readNumber``@@ -323,7 +323,7 @@ there may be more than one.  ``!``-notation---------------+~~~~~~~~~~~~~~  In many cases, using ``do``-notation can make programs unnecessarily verbose, particularly in cases such as ``m_add`` above where the value@@ -367,7 +367,7 @@                      f g'  Monad comprehensions---------------------+~~~~~~~~~~~~~~~~~~~~  The list comprehension notation we saw in Section :ref:`sect-more-expr` is more general, and applies to anything which@@ -461,7 +461,7 @@     m_add' x y = [| x + y |]  An error-handling interpreter------------------------------+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  Idiom notation is commonly useful when defining evaluators. McBride and Paterson describe such an evaluator [1]_, for a language similar
docs/tutorial/miscellany.rst view
@@ -86,7 +86,7 @@  	fibonacci : {default 0 lag : Nat} -> {default 1 lead : Nat} -> (n : Nat) -> Nat 	fibonacci {lag} Z = lag-	fibonacci {lag} {lead} (S Z) = fibonacci {lag=lead} {lead=lag+lead} n+	fibonacci {lag} {lead} (S n) = fibonacci {lag=lead} {lead=lag+lead} n  After this definition, ``fibonacci 5`` is equivalent to ``fibonacci {lag=0} {lead=1} 5``, and will return the 5th fibonacci number. Note that while this works, this is not the @@ -365,6 +365,14 @@     main : IO ()     main = do          putStrLn $ show $ factorial 3++To compile the generated C with debugging information e.g. to use+``gdb`` to debug segmentation faults in Idris programs, use the+``%flag C`` pragma to include debugging symbols, as is shown below :++.. code-block:: idris++    %flag C "-g"  JavaScript Target =================
docs/tutorial/modules.rst view
@@ -189,8 +189,6 @@     import B     import public C -    public a : AType a = ...- The module ``A`` will export the name ``a``, as well as any public or abstract names in module ``C``, but will not re-export anything from module ``B``.@@ -277,5 +275,3 @@      *params> show (append _ _ (MkVects _ [1,2,3] [4,5,6]))     "[1, 2, 3, 4, 5, 6]" : String--
docs/tutorial/starting.rst view
@@ -11,7 +11,7 @@ of the necessary libraries and tools. You will need:  - A fairly recent version of `GHC <https://www.haskell.org/ghc/>`_. The-  earliest version we currently test with is 7.6.3.+  earliest version we currently test with is 7.10.3.  - The *GNU Multiple Precision Arithmetic Library* (GMP) is available  from MacPorts/Homebrew and all major Linux distributions. 
docs/tutorial/views.rst view
@@ -33,24 +33,36 @@ the fact that matching on a value in a dependently typed language can affect what we know about the forms of other values. In its simplest form, the ``with`` rule adds another argument to the function being-defined, e.g. we have already seen a vector filter function, defined-as follows:+defined. +We have already seen a vector filter function. This time, we define it+using ``with`` as follows:+ .. code-block:: idris      filter : (a -> Bool) -> Vect n a -> (p ** Vect p a)     filter p [] = ( _ ** [] )     filter p (x :: xs) with (filter p xs)-      | ( _ ** xs' ) = if (p x) then ( _ ** x :: xs' ) else ( _ ** xs' )+      filter p (x :: xs) | ( _ ** xs' ) = if (p x) then ( _ ** x :: xs' ) else ( _ ** xs' )  Here, the ``with`` clause allows us to deconstruct the result of-``filter p xs``. Effectively, it adds this value as an extra argument,-which we place after the vertical bar.+``filter p xs``. The view refined argument pattern ``filter p (x ::+xs)`` goes beneath the ``with`` clause, followed by a vertical bar+``|``, followed by the deconstructed intermediate result ``( _ ** xs'+)``. If the view refined argument pattern is unchanged from the+original function argument pattern, then the left side of ``|`` is+extraneous and may be omitted: +.. code-block:: idris++    filter p (x :: xs) with (filter p xs)+      | ( _ ** xs' ) = if (p x) then ( _ ** x :: xs' ) else ( _ ** xs' )+ If the intermediate computation itself has a dependent type, then the result can affect the forms of other arguments — we can learn the form-of one value by testing another. For example, a ``Nat`` is either even-or odd. If it’s even it will be the sum of two equal ``Nat``.+of one value by testing another. In these cases, view refined argument+patterns must be explicit. For example, a ``Nat`` is either even or+odd. If it is even it will be the sum of two equal ``Nat``. Otherwise, it is the sum of two equal ``Nat`` plus one:  .. code-block:: idris@@ -80,14 +92,29 @@        natToBin (j + j)     | Even = False :: natToBin j        natToBin (S (j + j)) | Odd  = True  :: natToBin j -The value of the result of ``parity k`` affects the form of ``k``,-because the result of ``parity k`` depends on ``k``. So, as well as-the patterns for the result of the intermediate computation (``Even``-and ``odd``) right of the ``|``, we also write how the results-affect the other patterns left of the ``|``. Note that there is-a function in the patterns (``+``) and repeated occurrences of-``j``—this is allowed because another argument has determined the form-of these patterns.+The value of ``parity k`` affects the form of ``k``, because the+result of ``parity k`` depends on ``k``. So, as well as the patterns+for the result of the intermediate computation (``Even`` and ``Odd``)+right of the ``|``, we also write how the results affect the other+patterns left of the ``|``. That is:++- When ``parity k`` evaluates to ``Even``, we can refine the original+  argument ``k`` to a refined pattern ``(j + j)`` according to+  ``Parity (n + n)`` from the ``Even`` constructor definition. So+  ``(j + j)`` replaces ``k`` on the left side of ``|``, and the+  ``Even`` constructor appears on the right side. The natural number+  ``j`` in the refined pattern can be used on the ride side of the+  ``=`` sign.++- Otherwise, when ``parity k`` evaluates to ``Odd``, the original+  argument ``k`` is refined to ``S (j + j)`` according to ``Parity (S+  (n + n))`` from the ``Odd`` constructor definition, and ``Odd`` now+  appears on the ride side of ``|``, again with the natural number+  ``j`` used on the ride side of the ``=`` sign.++Note that there is a function in the patterns (``+``) and repeated+occurrences of ``j`` - this is allowed because another argument has+determined the form of these patterns.  We will return to this function in the next section :ref:`sect-parity` to complete the definition of ``parity``.
idris-tutorial.pdf view

binary file changed (326683 → 658507 bytes)

idris.cabal view
@@ -1,5 +1,5 @@ Name:           idris-Version:        1.1.1+Version:        1.2.0 License:        BSD3 License-file:   LICENSE Author:         Edwin Brady@@ -119,7 +119,7 @@ -- Defaults to True because Hackage is a source release Flag release   Description:  This is an official release-  Default:      False+  Default:      True   manual:       True  Flag freestanding@@ -206,10 +206,11 @@                 , Idris.ModeCommon                 , Idris.Options                 , Idris.Parser+                , Idris.Parser.Data+                , Idris.Parser.Expr                 , Idris.Parser.Helpers                 , Idris.Parser.Ops-                , Idris.Parser.Expr-                , Idris.Parser.Data+                , Idris.Parser.Stack                 , Idris.PartialEval                 , Idris.Primitives                 , Idris.ProofSearch@@ -226,7 +227,6 @@                 , Idris.WhoCalls                 , Idris.CmdOptions -                , IRTS.BCImp                 , IRTS.Bytecode                 , IRTS.CodegenC                 , IRTS.CodegenCommon@@ -250,6 +250,7 @@                  , Idris.Package                 , Idris.Package.Common+                , Idris.Package.Parser                  , Util.DynamicLinker                 , Util.ScreenSize@@ -259,7 +260,7 @@                   Util.Pretty                 , Util.Net -                , Idris.Package.Parser+                                  -- Auto Generated                 , Paths_idris@@ -269,7 +270,7 @@   Build-depends:  base >=4 && <5                 , aeson >= 0.6 && < 1.3                 , annotated-wl-pprint >= 0.7 && < 0.8-                , ansi-terminal < 0.7+                , ansi-terminal < 0.8                 , ansi-wl-pprint < 0.7                 , array >= 0.4.0.1 && < 0.6                 , base64-bytestring < 1.1@@ -286,10 +287,10 @@                 , fingertree >= 0.1 && < 0.2                 , haskeline >= 0.7 && < 0.8                 , ieee754 >= 0.7 && < 0.9+                , megaparsec >= 6.2                 , mtl >= 2.1 && < 2.3                 , network < 2.7                 , optparse-applicative >= 0.13 && < 0.15-                , parsers >= 0.9 && < 0.13                 , pretty < 1.2                 , process < 1.7                 , regex-tdfa >= 1.2@@ -298,9 +299,7 @@                 , terminal-size < 0.4                 , text >=1.2.1.0 && < 1.3                 , time >= 1.4 && < 1.9-                , transformers < 0.6-                , transformers-compat >= 0.3-                , trifecta >= 1.6 && < 1.8+                , transformers >= 0.5 && < 0.6                 , uniplate >=1.6 && < 1.7                 , unordered-containers < 0.3                 , utf8-string < 1.1@@ -310,12 +309,15 @@                 , fsnotify >= 0.2 && < 2.2                 , async < 2.2 +  if !impl(ghc >= 8.0)+    Build-Depends: semigroups == 0.18.*+   Default-Language: Haskell2010   ghc-prof-options: -auto-all -caf-all    if os(windows)      build-depends: mintty >= 0.1 && < 0.2-                  , Win32 < 2.4+                  , Win32 < 2.7   else      build-depends: unix < 2.8   if flag(FFI)@@ -360,7 +362,7 @@                , filepath                , directory                , haskeline >= 0.7-               , optparse-applicative >= 0.11 && < 0.14+               , optparse-applicative >= 0.13 && < 0.15                , tagged                , tasty >= 0.8                , tasty-golden >= 2.0@@ -375,6 +377,7 @@  Executable idris-codegen-c   Main-is:        Main.hs+  other-modules:  Paths_idris   hs-source-dirs: codegen/idris-codegen-c    Build-depends:  idris@@ -389,6 +392,7 @@  Executable idris-codegen-javascript   Main-is:        Main.hs+  other-modules:  Paths_idris   hs-source-dirs: codegen/idris-codegen-javascript    Build-depends:  idris@@ -403,6 +407,7 @@  Executable idris-codegen-node   Main-is:        Main.hs+  other-modules:  Paths_idris   hs-source-dirs: codegen/idris-codegen-node    Build-depends:  idris
libs/base/Control/Category.idr view
@@ -4,7 +4,7 @@  %access public export -interface Category (cat : Type -> Type -> Type) where+interface Category (cat : k -> k -> Type) where   id  : cat a a   (.) : cat b c -> cat a b -> cat a c 
libs/base/Control/Monad/State.idr view
@@ -42,6 +42,10 @@     lift x = ST (\st => do r <- x                            pure (r, st)) +implementation (Monad f, Alternative f) => Alternative (StateT st f) where+    empty = lift empty+    (ST f) <|> (ST g) = ST (\st => f st <|> g st)+ ||| Apply a function to modify the context of this computation modify : MonadState stateType m => (stateType -> stateType) -> m () modify f = do s <- get
libs/base/Data/Buffer.idr view
@@ -2,7 +2,11 @@  %include C "idris_buffer.h" -||| A buffer is a pointer to a sized, unstructured, mutable chunk of memory+||| A buffer is a pointer to a sized, unstructured, mutable chunk of memory.+||| There are primitive operations for gettng and setting bytes, ints (32 bit) +||| and strings at a location in the buffer. These operations silently fail +||| if the location is out of bounds, so bounds checking should be done in +||| advance. export record Buffer where   constructor MkBuffer@@ -47,6 +51,15 @@     = foreign FFI_C "idris_setBufferByte" (ManagedPtr -> Int -> Bits8 -> IO ())               (rawdata b) loc val +||| Set the int at position 'loc' to 'val'.+||| Uses 4 bytes (assumes up to 32 bit Int).+||| Does nothing if the location is outside the bounds of the buffer+export+setInt : Buffer -> (loc : Int) -> (val : Int) -> IO ()+setInt b loc val+    = foreign FFI_C "idris_setBufferInt" (ManagedPtr -> Int -> Int -> IO ())+              (rawdata b) loc val+ ||| Set the byte at position 'loc' to 'val'. ||| Does nothing if the location is out of bounds of the buffer, or the string ||| is too long for the location@@ -66,12 +79,31 @@     = foreign FFI_C "idris_copyBuffer" (ManagedPtr -> Int -> Int -> ManagedPtr -> Int -> IO ())               (rawdata src) start len (rawdata dest) loc -||| Return the value at the given location in the buffer+||| Return the value at the given location in the buffer.+||| Returns 0 if out of bounds. export getByte : Buffer -> (loc : Int) -> IO Bits8 getByte b loc     = foreign FFI_C "idris_getBufferByte" (ManagedPtr -> Int -> IO Bits8)               (rawdata b) loc ++||| Return the value at the given location in the buffer, assuming 4+||| bytes to store the Int.+||| Returns 0 if out of bounds.+export+getInt : Buffer -> (loc : Int) -> IO Int+getInt b loc+    = foreign FFI_C "idris_getBufferInt" (ManagedPtr -> Int -> IO Int)+              (rawdata b) loc ++||| Return the string at the given location in the buffer, with the given+||| length. Returns "" if out of bounds.+export+getString : Buffer -> (loc : Int) -> (len : Int) -> IO String+getString b loc len+    = do MkRaw str <- foreign FFI_C "idris_getBufferString" (ManagedPtr -> Int -> Int -> IO (Raw String))+                          (rawdata b) loc len+         pure str  ||| Read 'maxbytes' into the buffer from a file, returning a new ||| buffer with the 'locaton' pointer moved along
libs/base/Data/Complex.idr view
@@ -70,16 +70,11 @@     (*) (a:+b) (c:+d) = ((a*c-b*d):+(b*c+a*d))     fromInteger x = (fromInteger x:+0) --- We can't do "implementation Neg a => Neg (Complex a)" because--- we need "abs" which needs "magnitude" which needs "sqrt" which needs Double-implementation Neg (Complex Double) where+implementation Neg a => Neg (Complex a) where     negate = map negate     (-) (a:+b) (c:+d) = ((a-c):+(b-d))-    abs (a:+b) = (magnitude (a:+b):+0) --- As soon as abs moves out of Neg (issue #3500), the following would become a--- valid instance:---- implementation Neg a => Neg (Complex a) where---     negate = map negate---     (-) (a:+b) (c:+d) = ((a-c):+(b-d))+-- Specific to Double because `abs` needs `magnitude` which needs `sqrt` which+-- operates on Double.+implementation Abs (Complex Double) where+    abs (a:+b) = (magnitude (a:+b):+0)
+ libs/base/Data/IORef.idr view
@@ -0,0 +1,54 @@+module Data.IORef++export+data IORef a = MkIORef a++public export+interface HasReference (ffi : FFI) where+  newIORef' : a -> IO' ffi (IORef a)+  readIORef' : IORef a -> IO' ffi a+  writeIORef' : IORef a -> a -> IO' ffi ()++export+modifyIORef': HasReference ffi => IORef a -> (a -> a) -> IO' ffi ()+modifyIORef' ref fn =+  do+    val <- readIORef' ref+    writeIORef' ref (fn val)++export+implementation HasReference FFI_C where+  newIORef' val+    = do MkRaw ref <- foreign FFI_C "idris_newRef" (Raw a -> IO (Raw a)) (MkRaw val)+         pure (MkIORef ref)+  readIORef' (MkIORef ref)+    = do MkRaw val <- foreign FFI_C "idris_readRef" (Raw a -> IO (Raw a)) (MkRaw ref)+         pure val+  writeIORef' (MkIORef ref) val+    = foreign FFI_C "idris_writeRef" (Raw a -> Raw a -> IO ())+              (MkRaw ref) (MkRaw val)++export+implementation HasReference FFI_JS where+  newIORef' val =+    (MkIORef . believe_me) <$> foreign FFI_JS "{val: %0}" (Ptr -> JS_IO Ptr) (believe_me val)+  readIORef' (MkIORef ref) =+    believe_me <$> foreign FFI_JS "%0.val" (Ptr -> JS_IO Ptr) (believe_me ref)+  writeIORef' (MkIORef ref) val =+    foreign FFI_JS "%0.val = %1" (Ptr -> Ptr -> JS_IO ()) (believe_me ref) (believe_me val)++export+newIORef : a -> IO (IORef a)+newIORef = newIORef'++export+readIORef : IORef a -> IO a+readIORef = readIORef'++export+writeIORef : IORef a -> a -> IO ()+writeIORef = writeIORef'++export+modifyIORef : IORef a -> (a -> a) -> IO ()+modifyIORef = modifyIORef'
libs/base/Data/List.idr view
@@ -15,10 +15,31 @@      ||| Example: `the (Elem "b" ["a", "b"]) (There Here)`      There : (later : Elem x xs) -> Elem x (y :: xs) +||| `Here` will never equal `There`.+hereIsNotThere : Not (Here = There _)+hereIsNotThere Refl impossible++||| If the tails don't match, neither will references to them.+tailMismatch : Not (this = that) -> Not (There this = There that)+tailMismatch f Refl = f Refl++implementation DecEq (Elem x xs) where+  decEq Here Here = Yes Refl+  decEq Here (There later) = No hereIsNotThere+  decEq (There later) Here = No (hereIsNotThere . sym)+  decEq (There this) (There that) with (decEq this that)+    decEq (There this) (There this) | Yes Refl  = Yes Refl+    decEq (There this) (There that) | No contra = No (tailMismatch contra)+ implementation Uninhabited (Elem {a} x []) where      uninhabited Here impossible      uninhabited (There p) impossible +||| An item not in the head and not in the tail is not in the List at all+neitherHereNorThere : {x, y : a} -> {xs : List a} -> Not (x = y) -> Not (Elem x xs) -> Not (Elem x (y :: xs))+neitherHereNorThere xneqy xninxs Here = xneqy Refl+neitherHereNorThere xneqy xninxs (There xinxs) = xninxs xinxs+ ||| Is the given element a member of the given list. ||| ||| @x The element to be tested.@@ -27,15 +48,9 @@ isElem x [] = No absurd isElem x (y :: xs) with (decEq x y)   isElem x (x :: xs) | (Yes Refl) = Yes Here-  isElem x (y :: xs) | (No contra) with (isElem x xs)-    isElem x (y :: xs) | (No contra) | (Yes prf) = Yes (There prf)-    isElem x (y :: xs) | (No contra) | (No f) = No (mkNo contra f)-      where-        mkNo : {xs' : List a} ->-               ((x' = y') -> Void) -> (Elem x' xs' -> Void) ->-               Elem x' (y' :: xs') -> Void-        mkNo f g Here = f Refl-        mkNo f g (There x) = g x+  isElem x (y :: xs) | (No xneqy) with (isElem x xs)+    isElem x (y :: xs) | (No xneqy) | (Yes xinxs) = Yes (There xinxs)+    isElem x (y :: xs) | (No xneqy) | (No xninxs) = No (neitherHereNorThere xneqy xninxs)  ||| Remove the element at the given position. |||
libs/base/Data/Morphisms.idr view
@@ -40,3 +40,15 @@  (~>) : Type -> Type -> Type a ~> b = Morphism a b++Cast (Endomorphism a) (Morphism a a) where+  cast (Endo f) = Mor f++Cast (Morphism a a) (Endomorphism a) where+  cast (Mor f) = Endo f++Monad m => Cast (Morphism a (m b)) (Kleislimorphism m a b) where+  cast (Mor f) = Kleisli f++Cast (Kleislimorphism m a b) (Morphism a (m b)) where+  cast (Kleisli f) = Mor f
libs/base/Data/Primitives/Views.idr view
@@ -12,9 +12,9 @@        DivByZero : Divides x 0        DivBy : (prf : rem >= 0 && rem < d = True) ->                Divides ((d * div) + rem) d-    +   ||| Covering function for the `Divides` view-  export+  public export   divides : (val : Integer) -> (d : Integer) -> Divides val d   divides val 0 = DivByZero   divides val d@@ -22,21 +22,23 @@              let dividend = if d < 0 then -(val `div` abs d)                                      else val `div` d                  remainder = abs (val - dividend * d) in-                 believe_me (DivBy {d} {div = dividend} {rem = remainder}-                                   (believe_me (Refl {x = True})))+                 really_believe_me (DivBy {d} {div = dividend} {rem = remainder}+                                   (really_believe_me (Refl {x = True})))    ||| View for recursion over Integers+  public export   data IntegerRec : Integer -> Type where        IntegerZ : IntegerRec 0        IntegerSucc : IntegerRec (n - 1) -> IntegerRec n        IntegerPred : IntegerRec ((-n) + 1) -> IntegerRec (-n)-  +   ||| Covering function for `IntegerRec`+  public export   integerRec : (x : Integer) -> IntegerRec x   integerRec 0 = IntegerZ   integerRec x = if x > 0 then IntegerSucc (assert_total (integerRec (x - 1)))-                      else believe_me (IntegerPred {n=-x} -                                (assert_total (believe_me (integerRec (x + 1)))))+                      else really_believe_me (IntegerPred {n=-x}+                                (assert_total (really_believe_me (integerRec (x + 1)))))  namespace Int   ||| View for expressing a number as a multiplication + a remainder@@ -45,13 +47,13 @@        DivByZero : Int.Divides x 0        DivBy : (prf : rem >= 0 && rem < d = True) ->                Int.Divides ((d * div) + rem) d-   +   -- I have assumed, but not actually verified, that this will still   -- give a right result (i.e. still adding up) when the Ints overflow.   -- TODO: Someone please check this and fix if necessary...    ||| Covering function for the `Divides` view-  export+  public export   divides : (val : Int) -> (d : Int) -> Divides val d   divides val 0 = DivByZero   divides val d@@ -59,19 +61,21 @@              let dividend = if d < 0 then -(val `div` abs d)                                      else val `div` d                  remainder = abs (val - dividend * d) in-                 believe_me (DivBy {d} {div = dividend} {rem = remainder}-                                   (believe_me (Refl {x = True})))+                 really_believe_me (DivBy {d} {div = dividend} {rem = remainder}+                                   (really_believe_me (Refl {x = True})))    ||| View for recursion over Ints+  public export   data IntRec : Int -> Type where        IntZ : IntRec 0        IntSucc : IntRec (n - 1) -> IntRec n        IntPred : IntRec ((-n) + 1) -> IntRec (-n)-  +   ||| Covering function for `IntRec`+  public export   intRec : (x : Int) -> IntRec x   intRec 0 = IntZ   intRec x = if x > 0 then IntSucc (assert_total (intRec (x - 1)))-                      else believe_me (IntPred {n=-x}-                                (assert_total (believe_me (intRec (x + 1)))))-  +                      else really_believe_me (IntPred {n=-x}+                                (assert_total (really_believe_me (intRec (x + 1)))))+
libs/base/Data/Vect.idr view
@@ -326,10 +326,20 @@ -- Scans -------------------------------------------------------------------------------- +||| The scanl function is similar to foldl, but returns all the intermediate+||| accumulator states in the form of a vector. scanl : (res -> elem -> res) -> res -> Vect len elem -> Vect (S len) res scanl f q []      = [q] scanl f q (x::xs) = q :: scanl f (f q x) xs +||| The scanl1 function is a variant of scanl that doesn't require an explicit+||| starting value.+||| It assumes the first element of the vector to be the starting value and then+||| starts the fold with the element following it.+scanl1 : (elem -> elem -> elem) -> Vect len elem -> Vect len elem+scanl1 f [] = []+scanl1 f (x::xs) = scanl f x xs+ -------------------------------------------------------------------------------- -- Membership tests --------------------------------------------------------------------------------@@ -633,6 +643,14 @@ mapElem : {xs : Vect k t} -> {f : t -> u} -> Elem x xs -> Elem (f x) (map f xs) mapElem Here = Here mapElem (There e) = There (mapElem e)++||| Remove the element at the given position.+|||+||| @xs The vector to be removed from+||| @p A proof that the element to be removed is in the vector+dropElem : (xs : Vect (S k) t) -> (p : Elem x xs) -> Vect k t+dropElem (x :: ys) Here = ys+dropElem {k = (S k)} (x :: ys) (There later) = x :: dropElem ys later  -- Some convenience functions for testing lengths 
libs/base/Language/Reflection/Utils.idr view
@@ -308,7 +308,7 @@           my_show d (RApp tm tm') = assert_total $ showCon d "RApp" $ " " ++ my_show App tm ++ " " ++ my_show App tm'           my_show d RType = "RType"           my_show d (RConstant c) = assert_total $ showCon d "RConstant" $ showArg c-          my_show d (RUType u) = "RUType" +          my_show d (RUType u) = "RUType"   implementation Show Err where@@ -387,3 +387,10 @@       showCon d "MkFunClause" $ showArg lhs ++ showArg rhs   showPrec d (MkImpossibleClause lhs) =       showCon d "MkImpossibleClause" $ showArg lhs++implementation Functor FunClause where+  map f (MkFunClause lhs rhs) = MkFunClause (f lhs) (f rhs)+  map f (MkImpossibleClause lhs) = MkImpossibleClause (f lhs)++implementation Functor FunDefn where+  map f (DefineFun n clauses) = DefineFun n (map (map f) clauses)
libs/base/System.idr view
@@ -97,5 +97,6 @@ usleep : (i : Int) -> { auto prf : So (i >= 0 && i <= 1000000) } -> IO () usleep i = foreign FFI_C "usleep" (Int -> IO ()) i +||| Execute a program and returns its exit status code. system : String -> IO Int system cmd = foreign FFI_C "system" (String -> IO Int) cmd
libs/base/base.ipkg view
@@ -1,47 +1,53 @@ package base  opts = "--nobasepkgs --total --no-elim-deprecation-warnings --partial-eval -i ../prelude"-modules = System, -          Debug.Error, Debug.Trace,+modules = Control.Arrow+        , Control.Catchable+        , Control.Category+        , Control.IOExcept+        , Control.Isomorphism -          System.Info,+        , Control.Monad.Identity+        , Control.Monad.Reader+        , Control.Monad.RWS+        , Control.Monad.State+        , Control.Monad.Trans+        , Control.Monad.Writer -          Language.Reflection.Utils,+        , Data.Bits+        , Data.Buffer+        , Data.Complex+        , Data.Erased+        , Data.Fin+        , Data.HVect+        , Data.IORef -          Syntax.PreorderReasoning,+        , Data.List+        , Data.List.Quantifiers+        , Data.List.Views -          Data.Morphisms,-          Data.Bits,-          Data.Mod2,-          Data.Fin,-          Data.Vect,-          Data.Vect.Views,-          Data.Vect.Quantifiers,-          Data.HVect,-          Data.Complex,-          Data.Erased,-          Data.List,-          Data.List.Views,-          Data.List.Quantifiers,-          Data.Nat.Views,-          Data.Primitives.Views,-          Data.String.Views,-          Data.So,-          Data.String,-          Data.Buffer,+        , Data.Mod2+        , Data.Morphisms+        , Data.Nat.Views+        , Data.Primitives.Views+        , Data.So -          Control.Isomorphism,-          Control.Monad.Identity,-          Control.Monad.RWS,-          Control.Monad.Trans,-          Control.Monad.State,-          Control.Monad.Writer,-          Control.Monad.Reader,-          Control.Category,-          Control.Arrow,-          Control.Catchable,-          Control.IOExcept,+        , Data.String+        , Data.String.Views -          System.Concurrency.Raw,-          System.Concurrency.Channels+        , Data.Vect+        , Data.Vect.Quantifiers+        , Data.Vect.Views++        , Debug.Error+        , Debug.Trace++        , Language.Reflection.Utils++        , Syntax.PreorderReasoning++        , System+        , System.Concurrency.Channels+        , System.Concurrency.Raw+        , System.Info
libs/contrib/CFFI/Memory.idr view
@@ -40,10 +40,11 @@ free (CPt p _ ) = mfree p  ||| Perform an IO action with memory that is freed afterwards-withAlloc : Composite -> (CPtr -> IO ()) -> IO ()+withAlloc : Composite -> (CPtr -> IO a) -> IO a withAlloc t f = do m <- alloc t-                   f m+                   r <- f m                    free m+                   pure r  infixl 1 ~~> ||| Perform an IO action with memory that is freed afterwards
libs/contrib/CFFI/Types.idr view
@@ -29,11 +29,11 @@     show PTR = "PTR"  Show Composite where-    show (T ct) = show ct-    show (ARRAY n t) = "ARRAY " ++ show n ++ " " ++ show t-    show (STRUCT xs) = "STRUCT " ++ show xs-    show (UNION xs) = "UNION " ++ show xs-    show (PACKEDSTRUCT xs) = "PACKEDSTRUCT " ++ show xs+    showPrec d (T ct) = showPrec d ct+    showPrec d (ARRAY n t) = showCon d "ARRAY" $ showArg n ++ showArg t+    showPrec d (STRUCT xs) = showCon d "STRUCT" $ showArg xs+    showPrec d (UNION xs) = showCon d "UNION" $ showArg xs+    showPrec d (PACKEDSTRUCT xs) = showCon d "PACKEDSTRUCT" $ showArg xs  ||| What Idris type the C type is marshalled to translate : CType -> Type
+ libs/contrib/Control/Delayed.idr view
@@ -0,0 +1,26 @@+||| Utilities functions for contitionally delaying values.+module Control.Delayed++%default total++||| Type-level function for a conditionally delayed type (`Lazy` or `Inf`).+public export+delayed : DelayReason -> Bool -> Type -> Type+delayed r False a = a+delayed r True a = Delayed r a++||| Type-level function for a conditionally infinite type.+public export+inf : Bool -> Type -> Type+inf = delayed Infinite++||| Type-level function for a conditionally lazy type.+public export+lazy : Bool -> Type -> Type+lazy = delayed LazyValue++||| Conditionally delay a value.+export+delay : (d : Bool) -> a -> delayed r d a+delay False x = x+delay True x = Delay x
+ libs/contrib/Control/Monad/Syntax.idr view
@@ -0,0 +1,18 @@+module Control.Monad.Syntax++%default total+%access public export++infixr 1 =<<, <=<, >=>++||| Left-to-right Kleisli composition of monads.+(>=>) : Monad m => (a -> m b) -> (b -> m c) -> (a -> m c)+(>=>) f g = \x => f x >>= g++||| Right-to-left Kleisli composition of monads, flipped version of `>=>`.+(<=<) : Monad m => (b -> m c) -> (a -> m b) -> (a -> m c)+(<=<) = flip (>=>)++||| Right-to-left monadic bind, flipped version of `>>=`.+(=<<) : Monad m => (a -> m b) -> m a -> m b+(=<<) = flip (>>=)
libs/contrib/Control/ST.idr view
@@ -1,8 +1,10 @@ module Control.ST -import Language.Reflection.Utils import Control.IOExcept+import Language.Reflection.Utils +import public Data.Fuel+ %default total  infix 5 :::@@ -394,13 +396,6 @@ runST env (Read lbl prf) k = k (lookupEnv prf env) env runST env (Write lbl prf val) k = k () (updateEnv prf env val) -export-data Fuel = Empty | More (Lazy Fuel)--export partial-forever : Fuel-forever = More forever- runSTLoop : Fuel -> Env invars -> STransLoop m a invars outfn ->             (k : (x : a) -> Env (outfn x) -> m b) ->             (onDry : m b) -> m b@@ -589,10 +584,10 @@  export runLoop : Applicative m => Fuel -> STLoop m a [] ->-          (onEmpty : m a) ->+          (onDry : m a) ->           m a-runLoop fuel prog onEmpty-    = runSTLoop fuel [] prog (\res, env' => pure res) onEmpty+runLoop fuel prog onDry+    = runSTLoop fuel [] prog (\res, env' => pure res) onDry  ||| runWith allows running an STrans program with an initial environment, ||| which must be consumed.
+ libs/contrib/Control/ST/File.idr view
@@ -0,0 +1,247 @@+module Control.ST.File ++import Control.ST+import Control.IOExcept++%default total++||| A record of the file modes that can read from a file.+public export+data ValidModeRead : Mode -> Type where+  VMRRead   : ValidModeRead Read+  VMRReadW  : ValidModeRead ReadWrite+  VMRReadWT : ValidModeRead ReadWriteTruncate+  VMRReadA  : ValidModeRead ReadAppend++||| A record of the file modes that can write from a file.+public export+data ValidModeWrite : Mode -> Type where+  VMWWrite  : ValidModeWrite WriteTruncate+  VMWAppend : ValidModeWrite Append+  VMWReadW  : ValidModeWrite ReadWrite+  VMWReadWT : ValidModeWrite ReadWriteTruncate++||| The file handle which will be used as a State Transition +||| resource in the `IO` and `IOExcept` implementations of `File`.+|||+||| @mode The `Mode` that the handle was generated under.+|||+public export+data FileHandle : (mode : Mode) -> Type where+  FH : File -> FileHandle mode++||| Description of state transition operations on a file.+|||+||| +------------+-------------+----------------+----------------+----------------++||| | Operation  | State in    | Mode in        | State out      | Mode out       |+||| +------------+-------------+----------------+----------------+----------------++||| | open       | -           | -              | file handle    | input paramater|+||| | close      | file handle | any            | -              | -              |+||| | eof        | file handle | ValidModeRead  | file handle    | ValidModeRead  |+||| | flush      | file handle | any            | file handle    | unchanged      |+||| | readLine   | file handle | ValidModeRead  | file handle    | ValidModeRead  |+||| | readChar   | file handle | ValidModeRead  | file handle    | ValidModeRead  |+||| | readFile   | -           | -              | -              | -              |+||| | writeString| file handle | ValidModeWrite | file handle    | ValidModeWrite |+||| | writeLine  | file handle | ValidModeWrite | file handle    | ValidModeWrite |+||| | writeFile  | -           | -              | -              | -              |+||| +------------+-------------+----------------+----------------+----------------++|||+public export+interface File (m : Type -> Type) where+  FileHandleI : Mode -> Type++  ||| Open a file.+  |||+  ||| @fname the filename.+  ||| @mode  the mode; either Read, WriteTruncate, Append, ReadWrite,+  |||        ReadWriteTruncate, or ReadAppend+  |||+  open     :  (fname : String)+           -> (mode  : Mode)+           -> ST m (Either FileError Var) [ addIfRight (FileHandleI mode) ]++  ||| Close a file.+  close    :  (fileHandle : Var)+           -> ST m () [ remove fileHandle (FileHandleI mode)  ]++  ||| Have we reached the end of the file.+  eof      :  (fileHandle : Var)+           -> {auto prf   : ValidModeRead mode}+           -> ST m Bool [ fileHandle ::: (FileHandleI mode) ]++  ||| Flush+  flush    :  (fileHandle : Var)+           -> ST m () [ fileHandle ::: (FileHandleI mode) ]++  ||| Read a complete line.+  readLine :  (fileHandle : Var)+           -> {auto prf   : ValidModeRead mode}+           -> ST m (Either FileError String) [ fileHandle ::: (FileHandleI mode) ]++  ||| Read a `Char`.+  readChar :  (fileHandle : Var)+           -> {auto prf   : ValidModeRead mode}+           -> ST m (Either FileError Char) [ fileHandle ::: (FileHandleI mode) ]++  ||| Read the contents of a file into a string.+  |||+  ||| This checks the size of+  ||| the file before beginning to read, and only reads that many bytes,+  ||| to ensure that it remains a total function if the file is appended+  ||| to while being read.+  |||+  ||| Returns an error if fname is not a normal file.+  |||+  readFile :  (fileName : String)+           -> ST m (Either FileError String) []++  ||| Write a complete line to the file.+  |||+  ||| @string The string to be written to file.+  |||+  writeString : (fileHandle : Var)+           -> (string     : String) +           -> {auto prf   : ValidModeWrite mode}+           -> ST m (Either FileError ()) [ fileHandle ::: (FileHandleI mode) ]++  ||| Write a complete line to the file.+  |||+  ||| @string The text to be written to file.+  |||+  writeLine : (fileHandle : Var)+           -> (string     : String) +           -> {auto prf   : ValidModeWrite mode}+           -> ST m (Either FileError ()) [ fileHandle ::: (FileHandleI mode) ]++  ||| Create a file and write contents to the file.+  |||+  ||| @fname  The fileName of the file.+  ||| @string The text to be written to file.+  |||+  writeFile : (fname  : String)+           -> (string : String)+           -> ST m (Either FileError ()) []++public export+File IO where+  FileHandleI mode = State (FileHandle mode) ++  open fname mode = do +      (Right file) <- lift ( openFile fname mode )+                   | (Left  error ) => pure (Left error)+      let fh = FH file+      var <- new fh +      pure (Right var)++  close fh = do +      (FH file) <- read fh+      lift (closeFile file)+      delete fh +      pure ()++  eof fh = do  +      (FH file) <- read fh +      isEof <- lift (fEOF file)+      pure (isEof)++  flush fh = do +      (FH file) <- read fh +      lift (fEOF file)+      pure ()++  readLine fh = do +      (FH file) <- read fh +      (Right string) <- lift (fGetLine file)+                     | (Left  error ) => pure (Left error) +      pure (Right string)++  readChar fh = do +      (FH file) <- read fh +      (Right chr) <- lift (fgetc file)+                  | (Left  error ) => pure (Left error) +      pure (Right chr)++  readFile fname = do+      (Right content) <- lift ( readFile fname )+                      | (Left  error ) => pure (Left error) +      pure (Right content)++  writeString fh str = do +      (FH file) <- read fh +      Right x <- lift (fPutStr file str)+              | (Left  error ) => pure (Left error) +      pure (Right x)++  writeLine fh str = do +      (FH file) <- read fh+      Right x <- lift (fPutStrLn file str)+              | (Left  error ) => pure (Left error) +      pure (Right x)++  writeFile fname str = do+      Right x <- lift (writeFile fname str)+              | (Left error ) => pure (Left error) +      pure (Right x)++public export+File (IOExcept a) where+  FileHandleI mode = State (FileHandle mode) ++  open fname mode = do +      (Right file) <- lift (ioe_lift (openFile fname mode))+                   | (Left  error ) => pure (Left error)+      let fh = FH file+      var <- new fh +      pure (Right var)++  close fh = do +      (FH file) <- read fh+      lift (ioe_lift (closeFile file))+      delete fh +      pure ()++  eof fh = do  +      (FH file) <- read fh +      isEof <- lift (ioe_lift (fEOF file))+      pure (isEof)++  flush fh = do +      (FH file) <- read fh +      lift (ioe_lift (fEOF file))+      pure ()++  readLine fh = do +      (FH file) <- read fh +      (Right string) <- lift (ioe_lift (fGetLine file))+                     | (Left  error ) => pure (Left error) +      pure (Right string)++  readChar fh = do +      (FH file) <- read fh +      (Right chr) <- lift (ioe_lift (fgetc file))+                  | (Left  error ) => pure (Left error) +      pure (Right chr)++  readFile fname = do+      (Right content) <- lift (ioe_lift (readFile fname))+                      | (Left  error ) => pure (Left error) +      pure (Right content)++  writeString fh str = do +      (FH file) <- read fh +      Right x <- lift (ioe_lift (fPutStr file str))+              | (Left  error ) => pure (Left error) +      pure (Right x)++  writeLine fh str = do +      (FH file) <- read fh+      Right x <- lift (ioe_lift (fPutStrLn file str))+              | (Left  error ) => pure (Left error) +      pure (Right x)++  writeFile fname str = do+      Right x <- lift (ioe_lift (writeFile fname str))+              | (Left error ) => pure (Left error) +      pure (Right x)+--- EOF -------------------------------------------------------------------------
+ libs/contrib/Control/ST/Random.idr view
@@ -0,0 +1,42 @@+module Control.ST.Random++import Control.ST+import Data.Vect++%access public export++Random : Type+Random = State Integer++getRandom : (rnd : Var) -> ST m Integer [rnd ::: Random]+getRandom rnd =+  do+    st <- read rnd+    let st' = assert_total ((1664525 * st + 1013904223) `prim__sremBigInt` (pow 2 32))+    write rnd st'+    pure st'++||| Generates a random Integer in a given range+rndInt : (rnd : Var) -> Integer -> Integer -> ST m Integer [rnd ::: Random]+rndInt rnd lower upper = do v <- getRandom rnd+                            pure $ assert_total ((v `prim__sremBigInt` (upper - lower)) + lower)++||| Generate a random number in `Fin (S k)`+|||+||| Note that rndFin k takes values 0, 1, ..., k.+rndFin : (rnd : Var) -> (k : Nat) -> ST m (Fin (S k)) [rnd ::: Random]+rndFin rnd k = do let v = assert_total $ !(getRandom rnd) `prim__sremBigInt` (cast (S k))+                  pure (toFin v)+ where toFin : Integer -> Fin (S k)+       toFin x = case integerToFin x (S k) of+                      Just v => v+                      Nothing => toFin (assert_smaller x (x - cast (S k)))++||| Select a random element from a vector+rndSelect' : (rnd : Var) -> Vect (S k) a -> ST m a [rnd ::: Random]+rndSelect' {k} rnd xs = pure (Vect.index !(rndFin rnd k)  xs)++||| Select a random element from a non-empty list+rndSelect : (rnd : Var) -> (xs : List a) -> {auto ok : NonEmpty xs} -> ST m a [rnd ::: Random]+rndSelect rnd (x::xs) {ok=NonEmpty} = pure ( !(rndSelect' rnd (x::(fromList xs))))+rndSelect rnd [] {ok=NonEmpty} impossible
+ libs/contrib/Data/Bool/Extra.idr view
@@ -0,0 +1,32 @@+module Data.Bool.Extra++%access public export+%default total++andSameNeutral : (x : Bool) -> x && x = x+andSameNeutral False = Refl+andSameNeutral True = Refl++andFalseFalse : (x : Bool) -> x && False = False+andFalseFalse False = Refl+andFalseFalse True = Refl++andTrueNeutral : (x : Bool) -> x && True = x+andTrueNeutral False = Refl+andTrueNeutral True = Refl++orSameNeutral : (x : Bool) -> x || x = x+orSameNeutral False = Refl+orSameNeutral True = Refl++orFalseNeutral : (x : Bool) -> x || False = x+orFalseNeutral False = Refl+orFalseNeutral True = Refl++orTrueTrue : (x : Bool) -> x || True = True+orTrueTrue False = Refl+orTrueTrue True = Refl++orSameAndRightNeutral : (x, right : Bool) -> x || (x && right) = x+orSameAndRightNeutral False _ = Refl+orSameAndRightNeutral True _ = Refl
+ libs/contrib/Data/Combinators.idr view
@@ -0,0 +1,39 @@+||| Combinators that are thought to be at least situationally useful, mostly for+||| tacit (or point-free) programming. "To Mock a Mockingbird" refers to the book+||| "To Mock a Mockingbird and Other Logic Puzzles: Including an Amazing Adventure+||| in Combinatory Logic", by Raymond Smullyan (which the author of this module+||| hasn't actually read). See+||| http://www.angelfire.com/tx4/cus/combinator/birds.html and+||| https://hackage.haskell.org/package/data-aviary-0.4.0/docs/Data-Aviary-Birds.html+||| an (incomplete?) list of birds introduced. Also includes some operations defined+||| over Arrows.++module Data.Combinators++%default total+%access public export++||| Psi combinator - psi bird (?) - Haskell on.+on : (b -> b -> c) -> (a -> b) -> (a -> a -> c)+on f g x y = g x `f` g y+++infixl 9 ...+||| Blackbird, as named in "To Mock a Mockingbird". This is like+||| function composition, but second function takes two arguments. See the talk+||| "Point-Free or Die: Tacit Programming in Haskell and Beyond" by Amar Shah+||| (https://youtu.be/seVSlKazsNk).+(...) : (c -> d) -> (a -> b -> c) -> (a -> b -> d)+(...) = (.) . (.)++||| Warbler, as named in "To Mock a Mockingbird".+||| See http://code.jsoftware.com/wiki/Vocabulary/tilde+||| Equivalent to `join` on the Reader monad (`(->) e` in Haskell)+reflex : (a -> a -> b) -> (a -> b)+reflex f x = f x x++||| Phoenix, according to Data.Aviary.+||| See http://code.jsoftware.com/wiki/Vocabulary/fork.+||| Equivalent to `liftA2` on the Reader monad (`(->) e` in Haskell)+fork2 : (b -> c -> d) -> (a -> b) -> (a -> c) -> (a -> d)+fork2 f g h x = f (g x) (h x)
+ libs/contrib/Data/Combinators/Applicative.idr view
@@ -0,0 +1,27 @@+||| Enable applicative-style syntax (Mostly f <$> g <*> h and idiom brackets)+||| for function composition:+module Data.Combinators.Applicative++import Data.Combinators++%default total+%access public export++||| Pure is just const, also known as the K combinator+pure : a -> b -> a+pure = const++||| `map` is (.), but isn't here to discourage that use of the syntax.+||| `foo <$> bar <*> baz` applies `foo` to the results of `bar` and `baz`,+||| and generalizes to multiple arguments.+(<$>) : (b -> c) -> (a -> b) -> (a -> c)+(<$>) f g x = f (g x)++||| Starling, as named in "To Mock a Mockingbird". This is the S combinator.+||| Equivalent to `<*>` on the Reader monad (`(->) e` in Haskell).+||| See http://code.jsoftware.com/wiki/Vocabulary/hook.+(<*>) : (a -> b -> c) -> (a -> b)-> (a -> c)+(<*>) f g x = f x (g x)++liftA2 : (b -> c -> d) -> (a -> b) -> (a -> c) -> (a -> d)+liftA2 = fork2
+ libs/contrib/Data/Combinators/Arrow.idr view
@@ -0,0 +1,15 @@+||| Combinators from Control.Arrow++first : (a -> b) -> (a, c) -> (b, c)+first f (a, c) = (f a, c)++second : (a -> b) -> ((c, a) -> (c, b))+second f (c, a) = (c, f a)++infixr 3 ***+(***) : (a -> b) -> (a' -> b') -> ((a, a') -> (b, b'))+(***) f g (a, a') = (f a, g a')++infixr 3 &&&+(&&&) : (a -> b) -> (a -> b') -> (a -> (b, b'))+(&&&) f g x = (f x, g x)
+ libs/contrib/Data/Fuel.idr view
@@ -0,0 +1,18 @@+module Data.Fuel++%access public export+%default total++||| Fuel for running total operations potentially indefinitely.+data Fuel = Dry | More (Lazy Fuel)++||| Provide `n` units of fuel.+limit : Nat -> Fuel+limit Z = Dry+limit (S n) = More (limit n)++||| Provide fuel indefinitely.+||| This function is fundamentally partial.+partial+forever : Fuel+forever = More forever
+ libs/contrib/Data/IOArray.idr view
@@ -0,0 +1,47 @@+module Data.IOArray++-- Raw access to IOArrays. This interface is unsafe because there's no+-- bounds checking, and is merely intended to provide primitive access via+-- the RTS. Safe interfaces (either with run time or compile time+-- bounds checking) can be implemented on top of this++-- Implemented entirely by the array primitives in the RTS+data ArrayData : Type -> Type where++export+data IOArray elem = MkIOArray (ArrayData elem)++||| Create a new array of the given size, with all entries set to the+||| given default element.+export+newArray : Int -> elem -> IO (IOArray elem)+newArray size default+    = do vm <- getMyVM+         MkRaw p <- foreign FFI_C "idris_newArray"+                          (Ptr -> Int -> Raw elem -> IO (Raw (ArrayData elem)))+                          vm size (MkRaw default)+         pure (MkIOArray p)++||| Write an element at a location in an array. +||| There is *no* bounds checking, hence this is unsafe. Safe interfaces can+||| be implemented on top of this, either with a run time or compile time+||| check.+export+unsafeWriteArray : IOArray elem -> Int -> elem -> IO ()+unsafeWriteArray (MkIOArray p) i val+    = foreign FFI_C "idris_arraySet"+                    (Raw (ArrayData elem) -> Int -> Raw elem -> IO ())+                    (MkRaw p) i (MkRaw val)++||| Read the element at a location in an array. +||| There is *no* bounds checking, hence this is unsafe. Safe interfaces can+||| be implemented on top of this, either with a run time or compile time+||| check.+export+unsafeReadArray : IOArray elem -> Int -> IO elem+unsafeReadArray (MkIOArray p) i+    = do MkRaw val <- foreign FFI_C "idris_arrayGet"+                              (Raw (ArrayData elem) -> Int -> IO (Raw elem))+                              (MkRaw p) i+         pure val+
+ libs/contrib/Data/List/Group.idr view
@@ -0,0 +1,24 @@+module Data.List.Group++||| The groupBy function returns a list of lists such that the concatenation+||| of the list is equal to the argument, and each sublist contains only+||| elements that are equal according to the user-supplied predicate.+|||+||| ```idris example+||| groupBy (==) [1, 1, 2, 3, 3]+||| ```+|||+groupBy : (a -> a -> Bool) -> List a -> List (List a)+groupBy _ [] = []+groupBy p list@(x :: xs) =+  let (ys, zs) = span (p x) xs in+    (x :: ys) :: groupBy p (assert_smaller list zs)++||| The group function is a special case of groupBy.+|||+||| ```idris example+||| group [1, 1, 2, 3, 3]+||| ```+|||+group : Eq a => List a -> List (List a)+group = groupBy (==)
+ libs/contrib/Data/List/Permutations.idr view
@@ -0,0 +1,10 @@+module Permutations++-- | All permutations of a list.+permutations : List a -> List (List a)+permutations [] = [[]]+permutations xs = [y :: zs | (y, ys) <- select xs, zs <- permutations ys]+  where+    select : List a -> List (a, List a)+    select []        = []+    select (x :: xs) = (x, xs) :: [(y, x::ys) | (y,ys) <- select xs]
libs/contrib/Data/Matrix/Numeric.idr view
@@ -30,8 +30,10 @@  implementation Neg a => Neg (Vect n a) where   (-) = zipWith (-)-  abs = map abs   negate = map negate++implementation Abs a => Abs (Vect n a) where+  abs = map abs  ----------------------------------------------------------------------- --                        Vector functions
+ libs/contrib/Data/Nat/Parity.idr view
@@ -0,0 +1,16 @@+module Data.Nat.Parity++%access public export++--------------------------------------------------------------------------------+-- Parity+--------------------------------------------------------------------------------++mutual+  even : Nat -> Bool+  even Z = True+  even (S k) = odd k++  odd : Nat -> Bool+  odd Z = False+  odd (S k) = even k
+ libs/contrib/Data/Pairs/Implicit.idr view
@@ -0,0 +1,13 @@+||| Implicit conversions for erased dependent pairs.+module Data.Pairs.Implicit++%access public export+%default total++||| Convert an Evidence to its proof.+implicit evidence : (x : Exists p) -> p (getWitness x)+evidence = getProof++||| Convert an Element to its value (a.k.a. witness).+implicit element : Subset a p -> a+element = getWitness
+ libs/contrib/Data/Stream/Extra.idr view
@@ -0,0 +1,10 @@+module Data.Stream.Extra++%access public export+%default total++||| Insert elements from a Foldable at the start of an existing Stream+||| @ pfx the Foldable containing elements to prepend+||| @ stream the Stream to prepend the elements to+startWith : Foldable t => (pfx : t a) -> (stream : Stream a) -> Stream a+startWith pfx stream = foldr (\x, xs => x :: xs) stream pfx        
− libs/contrib/Data/String.idr
@@ -1,31 +0,0 @@-module Data.String--infixl 5 +>-infixr 5 <+--||| Adds a character to the end of the specified string.-|||-||| ```idris example-||| strSnoc "AB" 'C'-||| ```-||| ```idris example-||| strSnoc "" 'A'-||| ```-strSnoc : String -> Char -> String-strSnoc s c = s ++ (singleton c)--||| Alias of `strSnoc`-|||-||| ```idris example-||| "AB" +> 'C'-||| ```-(+>) : String -> Char -> String-(+>) = strSnoc--||| Alias of `strCons`-|||-||| ```idris example-||| 'A' <+ "AB"-||| ```-(<+) : Char -> String -> String-(<+) = strCons
+ libs/contrib/Data/String/Extra.idr view
@@ -0,0 +1,88 @@+module Data.String.Extra++%access public export+%default total++infixl 5 +>+infixr 5 <+++||| Adds a character to the end of the specified string.+|||+||| ```idris example+||| strSnoc "AB" 'C'+||| ```+||| ```idris example+||| strSnoc "" 'A'+||| ```+strSnoc : String -> Char -> String+strSnoc s c = s ++ (singleton c)++||| Alias of `strSnoc`+|||+||| ```idris example+||| "AB" +> 'C'+||| ```+(+>) : String -> Char -> String+(+>) = strSnoc++||| Alias of `strCons`+|||+||| ```idris example+||| 'A' <+ "AB"+||| ```+(<+) : Char -> String -> String+(<+) = strCons++||| Take the first `n` characters from a string. Returns the whole string+||| if it's too short.+take : (n : Nat) -> (input : String) -> String+take n str = substr Z n str++||| Take the last `n` characters from a string. Returns the whole string+||| if it's too short.+takeLast : (n : Nat) -> (input : String) -> String+takeLast n str with (length str)+  takeLast n str | len with (isLTE n len)+    takeLast n str | len | Yes prf = substr (len - n) len str+    takeLast n str | len | No contra = str++||| Remove the first `n` characters from a string. Returns the empty string if+||| the input string is too short.+drop : (n : Nat) -> (input : String) -> String+drop n str = substr n (length str) str++||| Remove the last `n` characters from a string. Returns the empty string if+||| the input string is too short.+dropLast : (n : Nat) -> (input : String) -> String+dropLast n str = reverse (drop n (reverse str))++||| Remove the first and last `n` characters from a string. Returns the empty+||| string if the input string is too short.+shrink : (n : Nat) -> (input : String) -> String+shrink n str = dropLast n (drop n str)++||| Concatenate the strings from a `Foldable` containing strings, separated by+||| the given string.+join : (sep : String) -> Foldable t => (xs : t String) -> String+join sep xs = drop (length sep)+                   (foldl (\acc, x => acc ++ sep ++ x) "" xs)++||| Get a character from a string if the string is long enough.+index : (n : Nat) -> (input : String) -> Maybe Char+index n str with (unpack str)+  index n str | [] = Nothing+  index Z str | (x :: xs) = Just x+  index (S n) str | (x :: xs) = index n str | xs++||| Produce a string by repeating the character `c` `n` times.+replicate : (n : Nat) -> (c : Char) -> String+replicate n c = pack $ replicate n c++||| Indent a given string by `n` spaces.+indent : (n : Nat) -> String -> String+indent n x = replicate n ' ' ++ x++||| Indent each line of a given string by `n` spaces.+indentLines : (n : Nat) -> String -> String+indentLines n str = unlines $ map (indent n) $ lines str+
libs/contrib/Data/ZZ.idr view
@@ -24,8 +24,8 @@ absZ (NegS n) = S n  implementation Show ZZ where-  show (Pos n) = show n-  show (NegS n) = "-" ++ show (S n)+  showPrec d (Pos n) = showPrec d n+  showPrec d (NegS n) = showParens (d >= PrefixMinus) $ "-" ++ showPrec PrefixMinus (S n)  negNat : Nat -> ZZ negNat Z = Pos Z@@ -77,6 +77,9 @@   (*) = multZ   fromInteger = fromInt +implementation Abs ZZ where+    abs = cast . absZ+ mutual   implementation Neg ZZ where     negate (Pos Z)     = Pos Z@@ -84,7 +87,6 @@     negate (NegS n)    = Pos (S n)      (-) = subZ-    abs = cast . absZ    ||| Subtract two `ZZ`s. Consider using `(-) {a=ZZ}`.   subZ : ZZ -> ZZ -> ZZ
+ libs/contrib/Interfaces/Correlative.idr view
@@ -0,0 +1,63 @@+module Interfaces.Correlative++import Data.Vect++%access public export+%default total++infixl 3 </>++||| A Correlative functor is a functor where, given `(xs, ys : Correlative f)`,+||| certain elements from xs and ys can be paired with one another due to some+||| intrinsic property of `f`. Elements that cannot be paired are discarded.+interface Functor f => Correlative (f : Type -> Type) where+  (</>) : f (a -> b) -> f a -> f b++infixl 3 </+(</) : Correlative f => f a -> f b -> f a+x </ y = map const x </> y++infixl 3 />+(/>) : Correlative f => f a -> f b -> f b+x /> y = map (const id) x </> y++||| Combine two containers elementwise using some function.+zipWith : Correlative f => (a -> b -> c) -> f a -> f b -> f c+zipWith f xs ys = (map f xs) </> ys++||| Combine three containers elementwise using some function.+zipWith3 : Correlative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d+zipWith3 f xs ys zs = (map f xs) </> ys </> zs++||| Combine two containers elementwise into a container of pairs.+zip : Correlative f => f a -> f b -> f (a, b)+zip = zipWith (\x, y => (x, y))++||| Combine three containers elementwise into a container of tuples.+zip3 : Correlative f => f a -> f b -> f c -> f (a, b, c)+zip3 = zipWith3 (\x, y, z => (x, y, z))++||| Convert a container of pairs into a pair of containers.+unzip : Functor t => t (a, b) -> (t a, t b)+unzip xs = (map fst xs, map snd xs)++||| Convert a container of tuples into a tuple of containers.+unzip3 : Functor t => t (a, b, c) -> (t a, t b, t c)+unzip3 xs = (map fst xs, unzip (map snd xs))++Correlative Maybe where+  (</>) = (<*>)++Correlative (Either a) where+  (</>) = (<*>)++Correlative List where+  (</>) [] _ = []+  (</>) _ [] = []+  (</>) (f :: fs) (x :: xs) = f x :: (fs </> xs)++Correlative Stream where+  (</>) = (<*>)++Correlative (Vect n) where+  (</>) = (<*>)
+ libs/contrib/Language/JSON.idr view
@@ -0,0 +1,14 @@+||| The JSON language, as described at http://json.org/+module Language.JSON++import Language.JSON.Lexer+import Language.JSON.Parser++import public Language.JSON.Data++%access export+%default total++||| Parse a JSON string.+parse : String -> Maybe JSON+parse x = parseJSON !(lexJSON x)
+ libs/contrib/Language/JSON/Data.idr view
@@ -0,0 +1,98 @@+module Language.JSON.Data++import Data.String.Extra++%access private+%default total++public export+data JSON+   = JNull+   | JBoolean Bool+   | JNumber Double+   | JString String+   | JArray (List JSON)+   | JObject (List (String, JSON))++%name JSON json++showChar : Char -> String+showChar c+  = case c of+         '\b' => "\\b"+         '\f' => "\\f"+         '\n' => "\\n"+         '\r' => "\\r"+         '\t' => "\\t"+         '\\' => "\\\\"+         '"'  => "\\\""+         c => if isControl c || c >= '\127'+                 then "\\u" ++ b16ToHexString (fromInteger (cast (ord c)))+                 else singleton c++showString : String -> String+showString x = "\"" ++ concatMap showChar (unpack x) ++ "\""++||| Convert a JSON value into its string representation.+||| No whitespace is added.+stringify : JSON -> String+stringify JNull = "null"+stringify (JBoolean x) = if x then "true" else "false"+stringify (JNumber x) = show x+stringify (JString x) = showString x+stringify (JArray xs) = "[" ++ stringifyValues xs ++ "]"+  where+    stringifyValues : List JSON -> String+    stringifyValues [] = ""+    stringifyValues (x :: xs) = stringify x+                             ++ if isNil xs+                                   then ""+                                   else "," ++ stringifyValues xs+stringify (JObject xs) = "{" ++ stringifyProps xs ++ "}"+  where+    stringifyProp : (String, JSON) -> String+    stringifyProp (key, value) = showString key ++ ":" ++ stringify value++    stringifyProps : List (String, JSON) -> String+    stringifyProps [] = ""+    stringifyProps (x :: xs) = stringifyProp x+                            ++ if isNil xs+                                  then ""+                                  else "," ++ stringifyProps xs++export+Show JSON where+  show = stringify++||| Format a JSON value, indenting by `n` spaces per nesting level.+|||+||| @curr The current indentation amount, measured in spaces.+||| @n The amount of spaces to indent per nesting level.+export+format : {default 0 curr : Nat} -> (n : Nat) -> JSON -> String+format {curr} n json = indent curr $ formatValue curr n json+  where+    formatValue : (curr, n : Nat) -> JSON -> String+    formatValue _ _ (JArray []) = "[]"+    formatValue curr n (JArray xs@(_ :: _)) = "[\n" ++ formatValues xs+                                           ++ indent curr "]"+      where+        formatValues : (xs : List JSON) -> {auto ok : NonEmpty xs} -> String+        formatValues (x :: xs) = format {curr=(curr + n)} n x+                              ++ case nonEmpty xs of+                                      Yes ok => ",\n" ++ formatValues xs+                                      No _ => "\n"+    formatValue _ _ (JObject []) = "{}"+    formatValue curr n (JObject xs@(_ :: _)) = "{\n" ++ formatProps xs+                                            ++ indent curr "}"+      where+        formatProp : (String, JSON) -> String+        formatProp (key, value) = indent (curr + n) (showString key ++ ": ")+                               ++ formatValue (curr + n) n value++        formatProps : (xs : List (String, JSON)) -> {auto ok : NonEmpty xs} -> String+        formatProps (x :: xs) = formatProp x+                             ++ case nonEmpty xs of+                                     Yes ok => ",\n" ++ formatProps xs+                                     No _ => "\n"+    formatValue _ _ x = stringify x
+ libs/contrib/Language/JSON/Lexer.idr view
@@ -0,0 +1,40 @@+module Language.JSON.Lexer++import Language.JSON.String+import Text.Lexer+import Text.Token++import public Language.JSON.Tokens++%access private+%default total++numberLit : Lexer+numberLit+  = let sign  = is '-'+        whole = is '0' <|> range '1' '9' <+> many digit+        frac  = is '.' <+> digits+        exp   = like 'e' <+> opt (oneOf "+-") <+> digits in+        opt sign <+> whole <+> opt frac <+> opt exp++jsonTokenMap : TokenMap JSONToken+jsonTokenMap = toTokenMap $+  [ (spaces, JTIgnore)+  , (is ',', JTPunct Comma)+  , (is ':', JTPunct Colon)+  , (is '[', JTPunct $ Square Open)+  , (is ']', JTPunct $ Square Close)+  , (is '{', JTPunct $ Curly Open)+  , (is '}', JTPunct $ Curly Close)+  , (exact "null", JTNull)+  , (exact strTrue <|> exact strFalse, JTBoolean)+  , (numberLit, JTNumber)+  , (permissiveStringLit, JTString)+  ]++export+lexJSON : String -> Maybe (List JSONToken)+lexJSON str+  = case lex jsonTokenMap str of+         (tokens, _, _, "") => Just $ map TokenData.tok tokens+         _ => Nothing
+ libs/contrib/Language/JSON/Parser.idr view
@@ -0,0 +1,71 @@+module Language.JSON.Parser++import Language.JSON.Data+import Text.Parser+import Text.Token++import public Language.JSON.Tokens++%access private+%default total++punct : Punctuation -> Grammar JSONToken True ()+punct p = match $ JTPunct p++rawString : Grammar JSONToken True String+rawString = do mstr <- match JTString+               the (Grammar _ False _) $+                   case mstr of+                        Just str => pure str+                        Nothing => fail "invalid string"++mutual+  json : Grammar JSONToken True JSON+  json = object+     <|> array+     <|> string+     <|> boolean+     <|> number+     <|> null++  object : Grammar JSONToken True JSON+  object = do punct $ Curly Open+              commit+              props <- properties+              punct $ Curly Close+              pure $ JObject props+    where+      properties : Grammar JSONToken False (List (String, JSON))+      properties = sepBy (punct Comma) $+                         do key <- rawString+                            punct Colon+                            value <- json+                            pure (key, value)++  array : Grammar JSONToken True JSON+  array = do punct (Square Open)+             commit+             vals <- values+             punct (Square Close)+             pure (JArray vals)+    where+      values : Grammar JSONToken False (List JSON)+      values = sepBy (punct Comma) json++  string : Grammar JSONToken True JSON+  string = map JString rawString++  boolean : Grammar JSONToken True JSON+  boolean = map JBoolean $ match JTBoolean++  number : Grammar JSONToken True JSON+  number = map JNumber $ match JTNumber++  null : Grammar JSONToken True JSON+  null = map (const JNull) $ match JTNull++export+parseJSON : List JSONToken -> Maybe JSON+parseJSON toks = case parse json $ filter (not . ignored) toks of+                      Right (j, []) => Just j+                      _ => Nothing
+ libs/contrib/Language/JSON/String.idr view
@@ -0,0 +1,16 @@+module Language.JSON.String++import Language.JSON.String.Lexer+import Language.JSON.String.Parser+import Language.JSON.String.Tokens+import Text.Lexer++%access export+%default total++permissiveStringLit : Lexer+permissiveStringLit+  = quo <+> manyUntil quo (esc any <|> any) <+> opt quo++stringValue : String -> Maybe String+stringValue x = parseString !(lexString x)
+ libs/contrib/Language/JSON/String/Lexer.idr view
@@ -0,0 +1,38 @@+module Language.JSON.String.Lexer++import Language.JSON.String.Tokens+import Text.Lexer++%access private+%default total++export+quo : Lexer+quo = is '"'++export+esc : Lexer -> Lexer+esc = escape '\\'++unicodeEscape : Lexer+unicodeEscape = esc $ is 'u' <+> count (exactly 4) hexDigit++simpleEscape : Lexer+simpleEscape = esc $ oneOf "\"\\/bfnrt"++legalChar : Lexer+legalChar = non (quo <|> is '\\' <|> control)++jsonStringTokenMap : TokenMap JSONStringToken+jsonStringTokenMap = toTokenMap $+  [ (quo, JSTQuote)+  , (unicodeEscape, JSTUnicodeEscape)+  , (simpleEscape, JSTSimpleEscape)+  , (legalChar, JSTChar)+  ]++export+lexString : String -> Maybe (List JSONStringToken)+lexString x = case lex jsonStringTokenMap x of+                   (toks, _, _, "") => Just $ map TokenData.tok toks+                   _ => Nothing
+ libs/contrib/Language/JSON/String/Parser.idr view
@@ -0,0 +1,25 @@+module Language.JSON.String.Parser++import Language.JSON.String.Tokens+import Text.Lexer+import Text.Parser++%access private+%default total++stringChar : Grammar JSONStringToken True Char+stringChar = match JSTChar+         <|> match JSTSimpleEscape+         <|> match JSTUnicodeEscape++quotedString : Grammar JSONStringToken True String+quotedString = let q = match JSTQuote in+                   do chars <- between q q (many stringChar)+                      eof+                      pure $ pack chars++export+parseString : List JSONStringToken -> Maybe String+parseString toks = case parse quotedString toks of+                        Right (str, []) => Just str+                        _ => Nothing
+ libs/contrib/Language/JSON/String/Tokens.idr view
@@ -0,0 +1,60 @@+module Language.JSON.String.Tokens++import Data.String.Extra+import Text.Token++%access public export+%default total++data JSONStringTokenKind+  = JSTQuote+  | JSTChar+  | JSTSimpleEscape+  | JSTUnicodeEscape++JSONStringToken : Type+JSONStringToken = Token JSONStringTokenKind++Eq JSONStringTokenKind where+  (==) JSTQuote JSTQuote = True+  (==) JSTChar JSTChar = True+  (==) JSTSimpleEscape JSTSimpleEscape = True+  (==) JSTUnicodeEscape JSTUnicodeEscape = True+  (==) _ _ = False++private+charValue : String -> Char+charValue x = case index 0 x of+                   Nothing => '\NUL'+                   Just c  => c++private+simpleEscapeValue : String -> Char+simpleEscapeValue x+  = case index 1 x of+         Nothing => '\NUL'+         Just c => case c of+                        '"'  => '"'+                        '\\' => '\\'+                        '/'  => '/'+                        'b'  => '\b'+                        'f'  => '\f'+                        'n'  => '\n'+                        'r'  => '\r'+                        't'  => '\t'+                        _    => '\NUL'++private+unicodeEscapeValue : String -> Char+unicodeEscapeValue x = chr $ cast ("0x" ++ drop 2 x)++TokenKind JSONStringTokenKind where+  TokType JSTQuote = ()+  TokType JSTChar = Char+  TokType JSTSimpleEscape = Char+  TokType JSTUnicodeEscape = Char++  tokValue JSTQuote = const ()+  tokValue JSTChar = charValue+  tokValue JSTSimpleEscape = simpleEscapeValue+  tokValue JSTUnicodeEscape = unicodeEscapeValue
+ libs/contrib/Language/JSON/Tokens.idr view
@@ -0,0 +1,72 @@+module Language.JSON.Tokens++import Language.JSON.String+import Text.Token++%access public export+%default total++strTrue : String+strTrue = "true"++strFalse : String+strFalse = "false"++data Bracket = Open | Close++Eq Bracket where+  (==) Open Open = True+  (==) Close Close = True+  (==) _ _ = False++data Punctuation+  = Comma+  | Colon+  | Square Bracket+  | Curly Bracket++Eq Punctuation where+  (==) Comma Comma = True+  (==) Colon Colon = True+  (==) (Square b1) (Square b2) = b1 == b2+  (==) (Curly b1) (Curly b2) = b1 == b2+  (==) _ _ = False++data JSONTokenKind+  = JTBoolean+  | JTNumber+  | JTString+  | JTNull+  | JTPunct Punctuation+  | JTIgnore++JSONToken : Type+JSONToken = Token JSONTokenKind++Eq JSONTokenKind where+  (==) JTBoolean JTBoolean = True+  (==) JTNumber JTNumber = True+  (==) JTString JTString = True+  (==) JTNull JTNull = True+  (==) (JTPunct p1) (JTPunct p2) = p1 == p2+  (==) _ _ = False++TokenKind JSONTokenKind where+  TokType JTBoolean = Bool+  TokType JTNumber = Double+  TokType JTString = Maybe String+  TokType JTNull = ()+  TokType (JTPunct _) = ()+  TokType JTIgnore = ()++  tokValue JTBoolean x = x == strTrue+  tokValue JTNumber x = cast x+  tokValue JTString x = stringValue x+  tokValue JTNull _ = ()+  tokValue (JTPunct _) _ = ()+  tokValue JTIgnore _ = ()++export+ignored : JSONToken -> Bool+ignored (Tok JTIgnore _) = True+ignored _ = False
libs/contrib/Network/Socket.idr view
@@ -8,10 +8,6 @@ import Network.Socket.Raw  %include C "idris_net.h"-%include C "sys/types.h"-%include C "sys/socket.h"-%include C "unistd.h"-%include C "netdb.h"  %access export @@ -24,7 +20,7 @@       -> (pnum : ProtocolNumber)       -> IO (Either SocketError Socket) socket sf st pn = do-  socket_res <- foreign FFI_C "socket"+  socket_res <- foreign FFI_C "idrnet_socket"                         (Int -> Int -> Int -> IO Int)                         (toCode sf) (toCode st) pn 
libs/contrib/Network/Socket/Raw.idr view
@@ -8,9 +8,6 @@ import public Network.Socket.Data  %include C "idris_net.h"-%include C "sys/types.h"-%include C "sys/socket.h"-%include C "netdb.h"  %access public export 
+ libs/contrib/Test/Unit.idr view
@@ -0,0 +1,14 @@+-- ---------------------------------------------------------------- [ Unit.idr ]+-- Module    : Unit.idr+-- Copyright : (c) The Idris Community.+-- License   : see LICENSE+-- --------------------------------------------------------------------- [ EOH ]+||| A simple Unit testing framework.+module Test.Unit++import public Test.Unit.Display+import public Test.Unit.Generic+import public Test.Unit.Assertions+import public Test.Unit.Runners++-- --------------------------------------------------------------------- [ EOF ]
+ libs/contrib/Test/Unit/Assertions.idr view
@@ -0,0 +1,37 @@+-- ---------------------------------------------------------- [ Assertions.idr ]+-- Module    : Assertions.idr+-- Copyright : (c) The Idris Community+-- License   : see LICENSE+-- --------------------------------------------------------------------- [ EOH ]+||| Some simple assertions.+module Test.Unit.Assertions++import Test.Unit.Generic++%access export++assertTrue : (given : Bool) -> IO Bool+assertTrue b = genericTest (Just "Assert True") b True (==)++assertFalse : (given : Bool) -> IO Bool+assertFalse b = genericTest (Just "Assert False") b False (==)++assertEquals : (Eq a, Show a) => (given : a) -> (expected : a) -> IO Bool+assertEquals g e = genericTest (Just "Assert Equals") g e (==)++assertNotEquals : (Eq a, Show a) => (given : a) -> (expected : a) -> IO Bool+assertNotEquals g e = genericTest (Just "Assert Not Equals") g e (\x,y => not (x == y))++assertJust : Show a => (given : Maybe a) -> IO Bool+assertJust g = genericTest (Just "Assert Is Just") (isJust g) True (==)++assertNothing : Show a => (given : Maybe a) -> IO Bool+assertNothing g = genericTest (Just "Assert Is Nothing") (isNothing g) True (==)++assertLeft : (Show a, Show b) => (given : Either a b) -> IO Bool+assertLeft g = genericTest (Just "Assert is Left") (isLeft g) True (==)++assertRight : (Show a, Show b) => (given : Either a b) -> IO Bool+assertRight g = genericTest (Just "Assert is Right") (isRight g) True (==)++-- --------------------------------------------------------------------- [ EOF ]
+ libs/contrib/Test/Unit/Display.idr view
@@ -0,0 +1,27 @@+-- ------------------------------------------------------------- [ Display.idr ]+-- Module    : Display.idr+-- Copyright : (c) The Idris Community.+-- License   : see LICENSE+-- --------------------------------------------------------------------- [ EOH ]+||| Some simple utilities to make the display fancier.+module Test.Unit.Display++%access export++fancyLine : Nat -> Char -> String+fancyLine l c = pack $ replicate l c++infoLine : String+infoLine = fancyLine 40 '-'++succLine : String+succLine = fancyLine 40 '='++errLine : String+errLine = fancyLine 40 '+'++heading : String -> String+heading n = unlines [infoLine, n, infoLine]+++-- --------------------------------------------------------------------- [ EOF ]
+ libs/contrib/Test/Unit/Generic.idr view
@@ -0,0 +1,43 @@+-- ------------------------------------------------------------- [ Generic.idr ]+-- Module    : Generic.idr+-- Copyright : (c) The Idris Community+-- License   : see LICENSE+-- --------------------------------------------------------------------- [ EOH ]+||| Generic Tests+module Test.Unit.Generic++import Text.PrettyPrint.WL++import Test.Unit.Display++%default total+%access export++||| Run a generic test.+|||+||| @title     Optional Test title+||| @given     The given string to parse+||| @expected  The expected result+||| @tFunc     The testing function to compare the results.+genericTest : Show a+           => (title : Maybe String)+           -> (given : a)+           -> (expected : a)+           -> (tFunc : a -> a -> Bool)+           -> IO Bool+genericTest title g e eq = do+  putStrLn $ unwords ["Test:" , fromMaybe "Unnamed Test" title]+  let res = eq g e+  when (not res) $ do+     let errMsg = vcat [+           text errLine+         , text "An error occured" <+> colon+         , indent 2 $ text "Given" <+> colon+         , indent 4 $ text (show g)+         , indent 2 $ text "Expected" <+> colon+         , indent 4 $ text (show e)+         , text errLine]+     putStrLn $ Default.toString errMsg+  pure res++-- --------------------------------------------------------------------- [ EOF ]
+ libs/contrib/Test/Unit/Runners.idr view
@@ -0,0 +1,36 @@+-- ------------------------------------------------------------- [ Runners.idr ]+-- Module    : Runners.idr+-- Copyright : (c) The Idris Community.+-- License   : see LICENSE+-- --------------------------------------------------------------------- [ EOH ]+||| Given a series of tests, execute them and report results.+module Test.Unit.Runners++import Test.Unit.Display++%default total+%access export++namespace NonReporting+  ||| Run the given set of tests, but don't return the results.+  runTests : List (IO Bool) -> IO ()+  runTests Nil = do+           putStrLn "All Tests have been performed."+           putStrLn succLine+  runTests (t::ts) = do t; runTests ts++namespace Reporting+  ||| Run the given set of tests and return the results.+  runTests : List (IO Bool) -> IO (List Bool)+  runTests Nil = do+    putStrLn "All tests have been performed."+    putStrLn succLine+    pure Nil+  runTests (x::xs) = do+       r  <- x+       rs <- Reporting.runTests xs+       pure (r::rs)++++-- --------------------------------------------------------------------- [ EOF ]
libs/contrib/Text/Lexer.idr view
@@ -1,248 +1,300 @@ module Text.Lexer +import Data.Bool.Extra++import public Text.Lexer.Core+import public Text.Quantity+import public Text.Token++%access export %default total -||| A language of token recognisers.-||| The `consumes` flag is True is the recogniser is guaranteed to consume-||| at least one character-export-data Recognise : (consumes : Bool) -> Type where-     Empty : Recognise False-     Fail : Recognise c-     Pred : (Char -> Bool) -> Recognise True-     SeqEat : Recognise True -> Inf (Recognise e) -> Recognise True-     SeqEmpty : Recognise e1 -> Recognise e2 -> Recognise (e1 || e2)-     Alt : Recognise e1 -> Recognise e2 -> Recognise (e1 && e2)+toTokenMap : List (Lexer, k) -> TokenMap (Token k)+toTokenMap = map $ \(l, kind) => (l, Tok kind) -||| A token recogniser. Guaranteed to consume at least one character.-public export-Lexer : Type-Lexer = Recognise True+||| Recognise any character.+||| /./+any : Lexer+any = pred (const True) -public export-inf : Bool -> Type -> Type-inf True t = Inf t-inf False t = t+||| Recognise a lexer or recognise no input. This is not guaranteed+||| to consume input.+||| /`l`?/+opt : (l : Lexer) -> Recognise False+opt l = l <|> empty -||| Sequence two recognisers. If either consumes a character, the sequence-||| is guaranteed to consume a character.-export %inline-(<+>) : {c1 : Bool} ->-        Recognise c1 -> inf c1 (Recognise c2) -> Recognise (c1 || c2)-(<+>) {c1 = False} = SeqEmpty-(<+>) {c1 = True} = SeqEat+||| Recognise any character if the sub-lexer `l` fails.+||| /(?!`l`)./+non : (l : Lexer) -> Lexer+non l = reject l <+> any -||| Alternative recognisers. If both consume, the combination is guaranteed-||| to consumer a character.-export-(<|>) : Recognise c1 -> Recognise c2 -> Recognise (c1 && c2)-(<|>) = Alt+||| Produce recognisers by applying a function to elements of a container, and+||| recognise the first match. Consumes input if the function produces consuming+||| recognisers. Fails if the container is empty.+choiceMap : {c : Bool} ->+            Foldable t => (a -> Recognise c) -> t a -> Recognise c+choiceMap {c} f xs = foldr (\x, acc => rewrite sym (andSameNeutral c) in+                                               f x <|> acc)+                           fail xs -||| Recognise a specific character-export-is : Char -> Lexer-is x = Pred (==x)+||| Recognise the first matching recogniser in a container. Consumes input if+||| recognisers in the list consume. Fails if the container is empty.+choice : Foldable t => t (Recognise c) -> Recognise c+choice = choiceMap id -||| Recognise anything but the given character-export-isNot : Char -> Lexer-isNot x = Pred (/=x)+||| Sequence a list of recognisers. Guaranteed to consume input if the list is+||| non-empty and the recognisers consume.+concat : (xs : List (Recognise c)) -> Recognise (c && isCons xs)+concat = concatMap id -||| Recognise a sequence of at least one sub-lexers-export-some : Lexer -> Lexer-some l = l <+> (some l <|> Empty)+||| Recognise a specific character.+||| /[`x`]/+is : (x : Char) -> Lexer+is x = pred (==x) -||| Recognise a sequence of at zero or more sub-lexers. This is not-||| guaranteed to consume input-export-many : Lexer -> Recognise False-many l = some l <|> Empty+||| Recognise anything but the given character.+||| /[\^`x`]/+isNot : (x : Char) -> Lexer+isNot x = pred (/=x) +||| Recognise a specific character (case-insensitive).+||| /[`x`]/i+like : (x : Char) -> Lexer+like x = pred (\y => toUpper x == toUpper y)++||| Recognise anything but the given character (case-insensitive).+||| /[\^`x`]/i+notLike : (x : Char) -> Lexer+notLike x = pred (\y => toUpper x /= toUpper y)++||| Recognise a specific string.+||| Fails if the string is empty.+||| /`str`/+exact : (str : String) -> Lexer+exact str = case unpack str of+                 [] => fail+                 (x :: xs) => concatMap is (x :: xs)++||| Recognise a specific string (case-insensitive).+||| Fails if the string is empty.+||| /`str`/i+approx : (str : String) -> Lexer+approx str = case unpack str of+                  [] => fail+                  (x :: xs) => concatMap like (x :: xs)++||| Recognise any of the characters in the given string.+||| /[`chars`]/+oneOf : (chars : String) -> Lexer+oneOf chars = pred (\x => x `elem` unpack chars)++||| Recognise a character range. Also works in reverse!+||| /[`start`-`end`]/+range : (start : Char) -> (end : Char) -> Lexer+range start end = pred (\x => (x >= min start end)+                           && (x <= max start end))++mutual+  ||| Recognise a sequence of at least one sub-lexers+  ||| /`l`+/+  some : Lexer -> Lexer+  some l = l <+> many l++  ||| Recognise a sequence of at zero or more sub-lexers. This is not+  ||| guaranteed to consume input+  ||| /`l`\*/+  many : Lexer -> Recognise False+  many l = opt (some l)++||| Repeat the sub-lexer `l` zero or more times until the lexer+||| `stopBefore` is encountered. `stopBefore` will not be consumed.+||| Not guaranteed to consume input.+||| /((?!`stopBefore`)`l`)\*/+manyUntil : (stopBefore : Recognise c) -> (l : Lexer) -> Recognise False+manyUntil stopBefore l = many (reject stopBefore <+> l)++||| Repeat the sub-lexer `l` zero or more times until the lexer+||| `stopAfter` is encountered, and consume it. Guaranteed to+||| consume if `stopAfter` consumes.+||| /`l`\*?`stopAfter`/+manyThen : (stopAfter : Recognise c) -> (l : Lexer) -> Recognise c+manyThen stopAfter l = manyUntil stopAfter l <+> stopAfter+ ||| Recognise many instances of `l` until an instance of `end` is ||| encountered. ||| ||| Useful for defining comments.-export-manyTill : (l : Lexer)-        -> (end : Lexer) -> Recognise False-manyTill l end = end-             <|> (l <+> manyTill l end)-             <|> Empty+manyTill : (l : Lexer) -> (end : Lexer) -> Recognise False+manyTill l end = end <|> opt (l <+> manyTill l end)+%deprecate manyTill+    "Prefer `lineComment`, or `manyUntil`/`manyThen` (argument order is flipped)." -||| Recognise any character-export-any : Lexer-any = Pred (const True)+||| Recognise a sub-lexer repeated as specified by `q`. Fails if `q` has+||| `min` and `max` in the wrong order. Consumes input unless `min q` is zero.+||| /`l`{`q`}/+count : (q : Quantity) -> (l : Lexer) -> Recognise (isSucc (min q))+count (Qty Z Nothing) l = many l+count (Qty Z (Just Z)) _ = empty+count (Qty Z (Just (S max))) l = opt $ l <+> count (atMost max) l+count (Qty (S min) Nothing) l = l <+> count (atLeast min) l+count (Qty (S min) (Just Z)) _ = fail+count (Qty (S min) (Just (S max))) l = l <+> count (between min max) l -||| Recognise no input (doesn't consume any input)-export-empty : Recognise False-empty = Empty+||| Recognise a single digit 0-9+||| /[0-9]/+digit : Lexer+digit = pred isDigit -||| Recognise a character that matches a predicate-export-pred : (Char -> Bool) -> Lexer-pred = Pred+||| Recognise one or more digits +||| /[0-9]+/+digits : Lexer+digits = some digit -||| Recognise any of the characters in the given string-export-oneOf : String -> Lexer-oneOf cs = pred (\x => x `elem` unpack cs)+||| Recognise a single hexidecimal digit+||| /[0-9A-Fa-f]/+hexDigit : Lexer+hexDigit = pred isHexDigit -data StrLen : Type where-     MkStrLen : String -> Nat -> StrLen+||| Recognise one or more hexidecimal digits+||| /[0-9A-Fa-f]+/+hexDigits : Lexer+hexDigits = some hexDigit -getString : StrLen -> String-getString (MkStrLen str n) = str+||| Recognise a single alpha character+||| /[A-Za-z]/+alpha : Lexer+alpha = pred isAlpha -strIndex : StrLen -> Nat -> Maybe Char-strIndex (MkStrLen str len) i-    = if i >= len then Nothing-                  else Just (assert_total (prim__strIndex str (cast i)))+||| Recognise one or more alpha characters+||| /[A-Za-z]+/+alphas : Lexer+alphas = some alpha -mkStr : String -> StrLen-mkStr str = MkStrLen str (length str)+||| Recognise a lowercase alpha character+||| /[a-z]/+lower : Lexer+lower = pred isLower -strTail : Nat -> StrLen -> StrLen-strTail start (MkStrLen str len)-    = MkStrLen (substr start len str) (minus len start)+||| Recognise one or more lowercase alpha characters+||| /[a-z]+/+lowers : Lexer+lowers = some lower --- If the string is recognised, returns the index at which the token--- ends-scan : Recognise c -> Nat -> StrLen -> Maybe Nat-scan Empty idx str = pure idx-scan Fail idx str = Nothing-scan (Pred f) idx str-    = do c <- strIndex str idx-         if f c-            then Just (idx + 1)-            else Nothing-scan (SeqEat r1 r2) idx str-    = do idx' <- scan r1 idx str-         -- TODO: Can we prove totality instead by showing idx has increased?-         assert_total (scan r2 idx' str)-scan (SeqEmpty r1 r2) idx str-    = do idx' <- scan r1 idx str-         scan r2 idx' str-scan (Alt r1 r2) idx str-    = case scan r1 idx str of-           Nothing => scan r2 idx str-           Just idx => Just idx+||| Recognise an uppercase alpha character+||| /[A-Z]/+upper : Lexer+upper = pred isUpper -takeToken : Lexer -> StrLen -> Maybe (String, StrLen)-takeToken lex str-    = do i <- scan lex 0 str -- i must be > 0 if successful-         pure (substr 0 i (getString str), strTail i str)+||| Recognise one or more uppercase alpha characters+||| /[A-Z]+/+uppers : Lexer+uppers = some upper -||| Recognise a digit 0-9-export-digits : Lexer-digits = some (Pred isDigit)+||| Recognise an alphanumeric character+||| /[A-Za-z0-9]/+alphaNum : Lexer+alphaNum = pred isAlphaNum -||| Recognise a specific string-export-exact : String -> Lexer-exact str with (unpack str)-  exact str | [] = Fail -- Not allowed, Lexer has to consume-  exact str | (x :: xs)-      = foldl SeqEmpty (is x) (map is xs)+||| Recognise one or more alphanumeric characters+||| /[A-Za-z0-9]+/+alphaNums : Lexer+alphaNums = some alphaNum -||| Recognise a whitespace character-export+||| Recognise a single whitespace character+||| /\\s/ space : Lexer-space = some (pred isSpace)+space = pred isSpace -||| Recognise a non-alphanumeric, non-whitespace character-export+||| Recognise one or more whitespace characters+||| /\\s+/+spaces : Lexer+spaces = some space++||| Recognise a single newline sequence. Understands CRLF, CR, and LF+||| /\\r\\n|[\\r\\n]/+newline : Lexer+newline = let crlf = "\r\n" in+              exact crlf <|> oneOf crlf++||| Recognise one or more newline sequences. Understands CRLF, CR, and LF+||| /(\\r\\n|[\\r\\n])+)/+newlines : Lexer+newlines = some newline++||| Recognise a single non-whitespace, non-alphanumeric character+||| /[\^\\sA-Za-z0-9]/ symbol : Lexer-symbol = some (pred (\x => not (isAlphaNum x) && not (isSpace x)))+symbol = pred (\x => not (isSpace x || isAlphaNum x)) -strChar : Lexer-strChar = (is '\\' <+> any) <|> isNot '"'+||| Recognise one or more non-whitespace, non-alphanumeric characters+||| /[\^\\sA-Za-z0-9]+/+symbols : Lexer+symbols = some symbol +||| Recognise a single control character+||| /[\\x00-\\x1f\\x7f-\\x9f]/+control : Lexer+control = pred isControl++||| Recognise one or more control characters+||| /[\\x00-\\x1f\\x7f-\\x9f]+/+controls : Lexer+controls = some control++||| Recognise zero or more occurrences of a sub-lexer between+||| delimiting lexers+||| /`start`(`l`)\*?`end`/+surround : (start : Lexer) -> (end : Lexer) -> (l : Lexer) -> Lexer+surround start end l = start <+> manyThen end l++||| Recognise zero or more occurrences of a sub-lexer surrounded+||| by the same quote lexer on both sides (useful for strings)+||| /`q`(`l`)\*?`q`/+quote : (q : Lexer) -> (l : Lexer) -> Lexer+quote q l = surround q q l++||| Recognise an escape character (often '\\') followed by a sub-lexer+||| /[`esc`]`l`/+escape : (esc : Char) -> Lexer -> Lexer+escape esc l = is esc <+> l+ ||| Recognise a string literal, including escaped characters. ||| (Note: doesn't yet handle escape sequences such as \123)-export+||| /"(\\\\.|.)\*?"/ stringLit : Lexer-stringLit = is '"' <+> many strChar <+> is '"'+stringLit = quote (is '"') (escape '\\' any <|> any)  ||| Recognise a character literal, including escaped characters. ||| (Note: doesn't yet handle escape sequences such as \123)-export+||| /'(\\\\.|[\^'])'/ charLit : Lexer-charLit = is '\'' <+> strChar <+> is '\''+charLit = let q = '\'' in+              is q <+> (escape '\\' any <|> isNot q) <+> is q  ||| Recognise an integer literal (possibly with a '-' prefix)-export+||| /-?[0-9]+/ intLit : Lexer-intLit = (is '-' <|> Empty) <+> digits--||| A mapping from lexers to the tokens they produce.-||| This is a list of pairs `(Lexer, String -> tokenType)`-||| For each Lexer in the list, if a substring in the input matches, run-||| the associated function to produce a token of type `tokenType`-public export-TokenMap : (tokenType : Type) -> Type-TokenMap tokenType = List (Lexer, String -> tokenType)--||| A token, and the line and column where it was in the input-public export-record TokenData a where-  constructor MkToken-  line : Int-  col : Int-  tok : a+intLit = opt (is '-') <+> digits -fspanEnd : Nat -> (Char -> Bool) -> String -> (Nat, String)-fspanEnd k p "" = (k, "")-fspanEnd k p xxs-    = assert_total $-      let x = prim__strHead xxs-          xs = prim__strTail xxs in-          if p x then fspanEnd (S k) p xs-                 else (k, xxs)+||| Recognise a hexidecimal literal, prefixed by "0x" or "0X"+||| /0[Xx][0-9A-Fa-f]+/+hexLit : Lexer+hexLit = approx "0x" <+> hexDigits --- Faster version of 'span' from the prelude (avoids unpacking)-export-fspan : (Char -> Bool) -> String -> (String, String)-fspan p xs-    = let (end, rest) = fspanEnd 0 p xs in-          (substr 0 end xs, rest)+||| Recognise `start`, then recognise all input until a newline is encountered,+||| and consume the newline. Will succeed if end-of-input is encountered before+||| a newline.+||| /`start`[\^\\r\\n]+(\\r\\n|[\\r\\n])?/+lineComment : (start : Lexer) -> Lexer+lineComment start = start <+> manyUntil newline any <+> opt newline -tokenise : (line : Int) -> (col : Int) ->-           List (TokenData a) -> TokenMap a ->-           StrLen -> (List (TokenData a), (Int, Int, StrLen))-tokenise line col acc tmap str-    = case getFirstToken tmap str of-           Just (tok, line', col', rest) =>-           -- assert total because getFirstToken must consume something-                assert_total (tokenise line' col' (tok :: acc) tmap rest)-           Nothing => (reverse acc, (line, col, str))+||| Recognise all input between `start` and `end` lexers.+||| Supports balanced nesting.+|||+||| For block comments that don't support nesting (such as C-style comments),+||| use `surround`+blockComment : (start : Lexer) -> (end : Lexer) -> Lexer+blockComment start end = start <+> middle <+> end   where-    countNLs : List Char -> Nat-    countNLs str = List.length (filter (== '\n') str)--    getCols : String -> Int -> Int-    getCols x c-         = case fspan (/= '\n') (reverse x) of-                (incol, "") => c + cast (length incol)-                (incol, _) => cast (length incol)--    getFirstToken : TokenMap a -> StrLen -> Maybe (TokenData a, Int, Int, StrLen)-    getFirstToken [] str = Nothing-    getFirstToken ((lex, fn) :: ts) str-        = case takeToken lex str of-               Just (tok, rest) => Just (MkToken line col (fn tok),-                                         line + cast (countNLs (unpack tok)),-                                         getCols tok col, rest)-               Nothing => getFirstToken ts str--||| Given a mapping from lexers to token generating functions (the-||| TokenMap a) and an input string, return a list of recognised tokens,-||| and the line, column, and remainder of the input at the first point in the-||| string where there are no recognised tokens.-export-lex : TokenMap a -> String -> (List (TokenData a), (Int, Int, String))-lex tmap str = let (ts, (l, c, str')) = tokenise 0 0 [] tmap (mkStr str) in-                   (ts, (l, c, getString str'))+    middle : Recognise False+    middle = manyUntil end (blockComment start end <|> any)
+ libs/contrib/Text/Lexer/Core.idr view
@@ -0,0 +1,193 @@+module Text.Lexer.Core++import Data.Bool.Extra++import public Control.Delayed++%default total++||| A language of token recognisers.+||| @ consumes If `True`, this recogniser is guaranteed to consume at+|||            least one character of input when it succeeds.+export+data Recognise : (consumes : Bool) -> Type where+     Empty : Recognise False+     Fail : Recognise c+     Lookahead : (positive : Bool) -> Recognise c -> Recognise False+     Pred : (Char -> Bool) -> Recognise True+     SeqEat : Recognise True -> Inf (Recognise e) -> Recognise True+     SeqEmpty : Recognise e1 -> Recognise e2 -> Recognise (e1 || e2)+     Alt : Recognise e1 -> Recognise e2 -> Recognise (e1 && e2)++||| A token recogniser. Guaranteed to consume at least one character.+public export+Lexer : Type+Lexer = Recognise True++||| Sequence two recognisers. If either consumes a character, the sequence+||| is guaranteed to consume a character.+export %inline+(<+>) : {c1 : Bool} ->+        Recognise c1 -> inf c1 (Recognise c2) -> Recognise (c1 || c2)+(<+>) {c1 = False} = SeqEmpty+(<+>) {c1 = True} = SeqEat++||| Alternative recognisers. If both consume, the combination is guaranteed+||| to consumer a character.+export+(<|>) : Recognise c1 -> Recognise c2 -> Recognise (c1 && c2)+(<|>) = Alt++||| A recogniser that always fails.+export+fail : Recognise c+fail = Fail++||| Recognise no input (doesn't consume any input)+export+empty : Recognise False+empty = Empty++||| Recognise a character that matches a predicate+export+pred : (Char -> Bool) -> Lexer+pred = Pred++||| Positive lookahead. Never consumes input.+export+expect : Recognise c -> Recognise False+expect = Lookahead True++||| Negative lookahead. Never consumes input.+export+reject : Recognise c -> Recognise False+reject = Lookahead False++||| Sequence the recognisers resulting from applying a function to each element+||| of a list. The resulting recogniser will consume input if the produced+||| recognisers consume and the list is non-empty.+export+concatMap : {c : Bool} ->+            (a -> Recognise c) -> (xs : List a) -> Recognise (c && isCons xs)+concatMap {c} _ [] = rewrite andFalseFalse c in Empty+concatMap {c} f (x :: xs) = rewrite andTrueNeutral c in+                            rewrite sym (orSameAndRightNeutral c (isCons xs)) in+                                    SeqEmpty (f x) (concatMap f xs)++data StrLen : Type where+     MkStrLen : String -> Nat -> StrLen++getString : StrLen -> String+getString (MkStrLen str n) = str++strIndex : StrLen -> Nat -> Maybe Char+strIndex (MkStrLen str len) i+    = if i >= len then Nothing+                  else Just (assert_total (prim__strIndex str (cast i)))++mkStr : String -> StrLen+mkStr str = MkStrLen str (length str)++strTail : Nat -> StrLen -> StrLen+strTail start (MkStrLen str len)+    = MkStrLen (substr start len str) (minus len start)++-- If the string is recognised, returns the index at which the token+-- ends+scan : Recognise c -> Nat -> StrLen -> Maybe Nat+scan Empty idx str = pure idx+scan Fail idx str = Nothing+scan (Lookahead positive r) idx str+    = if isJust (scan r idx str) == positive+         then Just idx+         else Nothing+scan (Pred f) idx str+    = do c <- strIndex str idx+         if f c+            then Just (idx + 1)+            else Nothing+scan (SeqEat r1 r2) idx str+    = do idx' <- scan r1 idx str+         -- TODO: Can we prove totality instead by showing idx has increased?+         assert_total (scan r2 idx' str)+scan (SeqEmpty r1 r2) idx str+    = do idx' <- scan r1 idx str+         scan r2 idx' str+scan (Alt r1 r2) idx str+    = case scan r1 idx str of+           Nothing => scan r2 idx str+           Just idx => Just idx++takeToken : Lexer -> StrLen -> Maybe (String, StrLen)+takeToken lex str+    = do i <- scan lex 0 str -- i must be > 0 if successful+         pure (substr 0 i (getString str), strTail i str)++||| A mapping from lexers to the tokens they produce.+||| This is a list of pairs `(Lexer, String -> tokenType)`+||| For each Lexer in the list, if a substring in the input matches, run+||| the associated function to produce a token of type `tokenType`+public export+TokenMap : (tokenType : Type) -> Type+TokenMap tokenType = List (Lexer, String -> tokenType)++||| A token, and the line and column where it was in the input+public export+record TokenData a where+  constructor MkToken+  line : Int+  col : Int+  tok : a++fspanEnd : Nat -> (Char -> Bool) -> String -> (Nat, String)+fspanEnd k p "" = (k, "")+fspanEnd k p xxs+    = assert_total $+      let x = prim__strHead xxs+          xs = prim__strTail xxs in+          if p x then fspanEnd (S k) p xs+                 else (k, xxs)++-- Faster version of 'span' from the prelude (avoids unpacking)+export+fspan : (Char -> Bool) -> String -> (String, String)+fspan p xs+    = let (end, rest) = fspanEnd 0 p xs in+          (substr 0 end xs, rest)++tokenise : (line : Int) -> (col : Int) ->+           List (TokenData a) -> TokenMap a ->+           StrLen -> (List (TokenData a), (Int, Int, StrLen))+tokenise line col acc tmap str+    = case getFirstToken tmap str of+           Just (tok, line', col', rest) =>+           -- assert total because getFirstToken must consume something+                assert_total (tokenise line' col' (tok :: acc) tmap rest)+           Nothing => (reverse acc, (line, col, str))+  where+    countNLs : List Char -> Nat+    countNLs str = List.length (filter (== '\n') str)++    getCols : String -> Int -> Int+    getCols x c+         = case fspan (/= '\n') (reverse x) of+                (incol, "") => c + cast (length incol)+                (incol, _) => cast (length incol)++    getFirstToken : TokenMap a -> StrLen -> Maybe (TokenData a, Int, Int, StrLen)+    getFirstToken [] str = Nothing+    getFirstToken ((lex, fn) :: ts) str+        = case takeToken lex str of+               Just (tok, rest) => Just (MkToken line col (fn tok),+                                         line + cast (countNLs (unpack tok)),+                                         getCols tok col, rest)+               Nothing => getFirstToken ts str++||| Given a mapping from lexers to token generating functions (the+||| TokenMap a) and an input string, return a list of recognised tokens,+||| and the line, column, and remainder of the input at the first point in the+||| string where there are no recognised tokens.+export+lex : TokenMap a -> String -> (List (TokenData a), (Int, Int, String))+lex tmap str = let (ts, (l, c, str')) = tokenise 0 0 [] tmap (mkStr str) in+                   (ts, (l, c, getString str'))
+ libs/contrib/Text/Literate.idr view
@@ -0,0 +1,155 @@+||| A simple module to process 'literate' documents.+|||+||| The module uses a lexer to split the document into code blocks,+||| delineated by user-defined markers, and code lines that are+||| indicated be a line marker. The lexer returns a document stripped+||| of non-code elements but preserving the original document's line+||| count. Column numbering of code lines are not preserved.+|||+||| The underlying tokeniser is greedy.+|||+||| Once it identifies a line marker it reads a prettifying space then+||| consumes until the end of line. Once identifies a starting code+||| block marker, the lexer will consume input until the next+||| identifiable end block is encountered. Any other content is+||| treated as part of the original document.+|||+||| Thus, the input literate files *must* be well-formed w.r.t+||| to code line markers and code blocks.+|||+||| A further restriction is that literate documents cannot contain+||| the markers within the document's main text: This will confuse the+||| lexer.+|||+module Text.Literate++import Text.Lexer++import Data.List.Views++%default total++untilEOL : Recognise False+untilEOL = manyUntil (is '\n') any++line : String -> Lexer+line s = exact s <+> space <+> untilEOL++block : String -> String -> Lexer+block s e = exact s <+> manyUntil (exact e) any ++data Token = CodeBlock String String String+           | Any String+           | CodeLine String String++Show Token where+  showPrec d (CodeBlock l r x) = showCon d "CodeBlock" $ showArg l ++ showArg r ++ showArg x+  showPrec d (Any x)           = showCon d "Any" $ showArg x+  showPrec d (CodeLine m x)    = showCon d "CodeLine" $ showArg m ++ showArg x++rawTokens : (delims  : List (String, String))+         -> (markers : List String)+         -> TokenMap (Token)+rawTokens delims ls =+          map (\(l,r) => (block l r, CodeBlock l r)) delims+       ++ map (\m => (line m, CodeLine m)) ls+       ++ [(any, Any)]++||| Merge the tokens into a single source file.+reduce : List (TokenData Token) -> String -> String+reduce [] acc = acc+reduce (MkToken _ _ (Any x) :: rest) acc = reduce rest (acc ++ blank_content)+  where+    -- Preserve the original document's line count.+    blank_content : String+    blank_content = if elem '\n' (unpack x)+      then concat $ replicate (length (lines x)) "\n"+      else ""+reduce (MkToken _ _ (CodeLine m src) :: rest) acc =+    reduce rest (acc ++ (substr+                           (length m + 1) -- remove space to right of marker.+                           (length src)+                           src))++reduce (MkToken _ _ (CodeBlock l r src) :: rest) acc with (lines src) -- Strip the deliminators surrounding the block.+  reduce (MkToken _ _ (CodeBlock l r src) :: rest) acc | [] = reduce rest acc -- 1+  reduce (MkToken _ _ (CodeBlock l r src) :: rest) acc | (s :: ys) with (snocList ys)+    reduce (MkToken _ _ (CodeBlock l r src) :: rest) acc | (s :: []) | Empty = reduce rest acc -- 2+    reduce (MkToken _ _ (CodeBlock l r src) :: rest) acc | (s :: (srcs ++ [f])) | (Snoc rec) =+        reduce rest (acc ++ "\n" ++ unlines srcs ++ "\n")++-- [ NOTE ] 1 & 2 shouldn't happen as code blocks are well formed i.e. have two deliminators.+++public export+record LiterateError where+  constructor MkLitErr+  line   : Int+  column : Int+  input  : String++||| Description of literate styles.+|||+||| A 'literate' style comprises of+|||+||| + a list of code block deliminators (`deliminators`);+||| + a list of code line markers (`line_markers`); and+||| + a list of known file extensions `file_extensions`.+|||+||| Some example specifications:+|||+||| + Bird Style+|||+|||```+|||MkLitStyle Nil [">", "<"] Nil+|||```+|||+||| + Literate Haskell (for LaTeX)+|||+|||```+|||MkLitStyle [("\\begin{code}", "\\end{code}"),("\\begin{spec}","\\end{spec}")]+|||           Nil+|||           ["lhs", "tex"]+|||```+|||+||| + OrgMode+|||+|||```+|||MkLitStyle [("#+BEGIN_SRC idris","#+END_SRC"), ("#+COMMENT idris","#+END_COMMENT")]+|||           ["#+IDRIS:"]+|||           ["org"]+|||```+|||+public export+record LiterateStyle where+  constructor MkLitStyle+  ||| The pairs of start and end tags for code blocks.+  deliminators : List (String, String)++  ||| Line markers that indicate a line contains code.+  line_markers : List String++  ||| Recognised file extensions. Not used by the module, but will be+  ||| of use when connecting to code that reads in the original source+  ||| files.+  file_extensions : List String++||| Given a 'literate specification' extract the code from the+||| literate source file (`litStr`) that follows the presented style.+|||+||| @specification The literate specification to use.+||| @litStr  The literate source file.+|||+||| Returns a `LiterateError` if the literate file contains malformed+||| code blocks or code lines.+|||+export+extractCode : (specification : LiterateStyle)+           -> (litStr        : String)+           -> Either LiterateError String+extractCode (MkLitStyle delims markers exts) str =+      case lex (rawTokens delims markers) str of+        (toks, (_,_,"")) => Right $ reduce toks ""+        (_, (l,c,i))     => Left (MkLitErr l c i)++-- --------------------------------------------------------------------- [ EOF ]
libs/contrib/Text/Parser.idr view
@@ -1,270 +1,226 @@ module Text.Parser -%default total+import Data.Bool.Extra --- TODO: Add some primitives for helping with error messages.--- e.g. perhaps set a string to state what we're currently trying to--- parse, or to say what the next expected token is in words+import public Text.Parser.Core+import public Text.Quantity+import public Text.Token -||| Description of a language's grammar. The `tok` parameter is the type-||| of tokens, and the `consumes` flag is True if the language is guaranteed-||| to be non-empty - that is, successfully parsing the language is guaranteed-||| to consume some input.-export-data Grammar : (tok : Type) -> (consumes : Bool) -> Type -> Type where-     Empty : (val : ty) -> Grammar tok False ty-     Terminal : (tok -> Maybe a) -> Grammar tok True a-     NextIs : (tok -> Bool) -> Grammar tok False tok-     EOF : Grammar tok False ()+%access export+%default total -     Fail : String -> Grammar tok c ty-     Commit : Grammar tok False ()+||| Parse a terminal based on a kind of token.+match : (Eq k, TokenKind k) =>+        (kind : k) ->+        Grammar (Token k) True (TokType kind)+match kind = terminal $+  \(Tok kind' text) => if kind' == kind+                          then Just $ tokValue kind text+                          else Nothing -     SeqEat : Grammar tok True a -> Inf (a -> Grammar tok c2 b) ->-              Grammar tok True b-     SeqEmpty : {c1, c2 : Bool} ->-                Grammar tok c1 a -> (a -> Grammar tok c2 b) ->-                Grammar tok (c1 || c2) b-     Alt : {c1, c2 : Bool} ->-           Grammar tok c1 ty -> Grammar tok c2 ty ->-           Grammar tok (c1 && c2) ty+||| Optionally parse a thing, with a default value if the grammar doesn't+||| match. May match the empty input.+option : {c : Bool} ->+         (def : a) -> (p : Grammar tok c a) ->+         Grammar tok False a+option {c = False} def p = p <|> pure def+option {c = True} def p = p <|> pure def -public export-inf : Bool -> Type -> Type-inf True t = Inf t-inf False t = t+||| Optionally parse a thing.+||| To provide a default value, use `option` instead.+optional : (p : Grammar tok c a) ->+           Grammar tok False (Maybe a)+optional p = option Nothing (map Just p) -||| Sequence two grammars. If either consumes some input, the sequence is-||| guaranteed to consume some input. If the first one consumes input, the-||| second is allowed to be recursive (because it means some input has been-||| consumed and therefore the input is smaller)-export %inline-(>>=) : {c1 : Bool} ->-        Grammar tok c1 a -> inf c1 (a -> Grammar tok c2 b) ->-        Grammar tok (c1 || c2) b-(>>=) {c1 = False} = SeqEmpty-(>>=) {c1 = True} = SeqEat+||| Try to parse one thing or the other, producing a value that indicates+||| which option succeeded. If both would succeed, the left option+||| takes priority.+choose : (l : Grammar tok c1 a) ->+         (r : Grammar tok c2 b) ->+         Grammar tok (c1 && c2) (Either a b)+choose l r = map Left l <|> map Right r -||| Give two alternative grammars. If both consume, the combination is-||| guaranteed to consume.-export-(<|>) : Grammar tok c1 ty -> Grammar tok c2 ty ->-        Grammar tok (c1 && c2) ty-(<|>) = Alt+||| Produce a grammar by applying a function to each element of a container,+||| then try each resulting grammar until the first one succeeds. Fails if the+||| container is empty.+choiceMap : {c : Bool} ->+            (a -> Grammar tok c b) ->+            Foldable t => t a ->+            Grammar tok c b+choiceMap {c} f xs = foldr (\x, acc => rewrite sym (andSameNeutral c) in+                                               f x <|> acc)+                           (fail "No more options") xs -export-pure : (val : ty) -> Grammar tok False ty-pure = Empty+||| Try each grammar in a container until the first one succeeds.+||| Fails if the container is empty.+choice : Foldable t => t (Grammar tok c a) ->+         Grammar tok c a+choice = choiceMap id -||| Check whether the next token satisfies a predicate-export-nextIs : (tok -> Bool) -> Grammar tok False tok-nextIs = NextIs+mutual+  ||| Parse one or more things+  some : Grammar tok True a ->+         Grammar tok True (List a)+  some p = pure (!p :: !(many p)) -||| Look at the next token in the input-export-peek : Grammar tok False tok-peek = nextIs (const True)+  ||| Parse zero or more things (may match the empty input)+  many : Grammar tok True a ->+         Grammar tok False (List a)+  many p = option [] (some p) -||| Succeeds if running the predicate on the next token returns Just x,-||| returning x. Otherwise fails.-export-terminal : (tok -> Maybe a) -> Grammar tok True a-terminal = Terminal+||| Parse one or more instances of `p`, returning the parsed items and proof+||| that the resulting list is non-empty.+some' : (p : Grammar tok True a) ->+        Grammar tok True (xs : List a ** NonEmpty xs)+some' p = pure (!p :: !(many p) ** IsNonEmpty) -||| Always fail with a message-export-fail : String -> Grammar tok c ty-fail = Fail+mutual+  private+  count1 : (q : Quantity) ->+           (p : Grammar tok True a) ->+           Grammar tok True (List a)+  count1 q p = do x <- p+                  seq (count q p)+                      (\xs => pure (x :: xs)) -||| Succeed if the input is empty-export-eof : Grammar tok False ()-eof = EOF+  ||| Parse `p`, repeated as specified by `q`, returning the list of values.+  count : (q : Quantity) ->+          (p : Grammar tok True a) ->+          Grammar tok (isSucc (min q)) (List a)+  count (Qty Z Nothing) p = many p+  count (Qty Z (Just Z)) _ = pure []+  count (Qty Z (Just (S max))) p = option [] $ count1 (atMost max) p+  count (Qty (S min) Nothing) p = count1 (atLeast min) p+  count (Qty (S min) (Just Z)) _ = fail "Quantity out of order"+  count (Qty (S min) (Just (S max))) p = count1 (between (S min) max) p -||| Commit to an alternative; if the current branch of an alternative-||| fails to parse, no more branches will be tried-export-commit : Grammar tok False ()-commit = Commit+mutual+  ||| Parse one or more instances of `p` until `end` succeeds, returning the+  ||| list of values from `p`. Guaranteed to consume input.+  someTill : {c : Bool} ->+             (end : Grammar tok c e) ->+             (p : Grammar tok True a) ->+             Grammar tok True (List a)+  someTill {c} end p = do x <- p+                          seq (manyTill end p)+                              (\xs => pure (x :: xs)) -data ParseResult : List tok -> (consumes : Bool) -> Type -> Type where-     Failure : {xs : List tok} ->-               (committed : Bool) ->-               (err : String) -> (rest : List tok) -> ParseResult xs c ty-     EmptyRes : (committed : Bool) ->-                (val : ty) -> (more : List tok) -> ParseResult more False ty-     NonEmptyRes : (committed : Bool) ->-                   (val : ty) -> (more : List tok) ->-                   ParseResult (x :: xs ++ more) c ty+  ||| Parse zero or more instances of `p` until `end` succeeds, returning the+  ||| list of values from `p`. Guaranteed to consume input if `end` consumes.+  manyTill : {c : Bool} ->+             (end : Grammar tok c e) ->+             (p : Grammar tok True a) ->+             Grammar tok c (List a)+  manyTill {c} end p = rewrite sym (andTrueNeutral c) in+                               map (const []) end <|> someTill end p -weakenRes : {whatever, c : Bool} -> {xs : List tok} ->-            ParseResult xs c ty -> ParseResult xs (whatever && c) ty-weakenRes (Failure com msg ts) = Failure com msg ts-weakenRes {whatever=True} (EmptyRes com val xs) = EmptyRes com val xs-weakenRes {whatever=False} (EmptyRes com val xs) = EmptyRes com val xs-weakenRes (NonEmptyRes com val more) = NonEmptyRes com val more+||| Parse one or more instances of `p` until `end` succeeds, returning the+||| list of values from `p`, along with a proof that the resulting list is+||| non-empty.+someTill' : {c : Bool} ->+            (end : Grammar tok c a) ->+            (p : Grammar tok True a) ->+            Grammar tok True (xs : List a ** NonEmpty xs)+someTill' end p+  = do x <- p+       seq (manyTill end p)+           (\xs => pure (x :: xs ** IsNonEmpty)) -shorter : (more : List tok) -> .(ys : List tok) ->-          LTE (S (length more)) (S (length (ys ++ more)))-shorter more [] = lteRefl-shorter more (x :: xs) = LTESucc (lteSuccLeft (shorter more xs))+mutual+  ||| Parse one or more instance of `skip` until `p` is encountered,+  ||| returning its value.+  afterSome : (skip : Grammar tok True s) ->+              (p : Grammar tok c a) ->+              Grammar tok True a+  afterSome skip p = do skip+                        afterMany skip p -doParse : {c : Bool} ->-          (commit : Bool) -> (xs : List tok) -> (act : Grammar tok c ty) ->-          ParseResult xs c ty-doParse com xs act with (sizeAccessible xs)-  doParse com xs (Empty val) | sml = EmptyRes com val xs-  doParse com [] (Fail str) | sml = Failure com str []-  doParse com (x :: xs) (Fail str) | sml = Failure com str (x :: xs)-  doParse com xs Commit | sml = EmptyRes True () xs+  ||| Parse zero or more instance of `skip` until `p` is encountered,+  ||| returning its value.+  afterMany : {c : Bool} ->+              (skip : Grammar tok True s) ->+              (p : Grammar tok c a) ->+              Grammar tok c a+  afterMany {c} skip p = rewrite sym (andTrueNeutral c) in+                                 p <|> afterSome skip p -  doParse com [] (Terminal f) | sml = Failure com "End of input" []-  doParse com (x :: xs) (Terminal f) | sml-        = maybe-             (Failure com "Unrecognised token" (x :: xs))-             (\a => NonEmptyRes com {xs=[]} a xs)-             (f x)-  doParse com [] EOF | sml = EmptyRes com () []-  doParse com (x :: xs) EOF | sml-        = Failure com "Expected end of input" (x :: xs)-  doParse com [] (NextIs f) | sml = Failure com "End of input" []-  doParse com (x :: xs) (NextIs f) | sml-        = if f x-             then EmptyRes com x (x :: xs)-             else Failure com "Unrecognised token" (x :: xs)-  doParse com xs (Alt x y) | sml with (doParse False xs x | sml)-    doParse com xs (Alt x y) | sml | Failure com' msg ts-          = if com' -- If the alternative had committed, don't try the-                    -- other branch (and reset commit flag)-               then Failure com msg ts-               else weakenRes (doParse False xs y | sml)-    -- Successfully parsed the first option, so use the outer commit flag-    doParse com xs (Alt x y) | sml | (EmptyRes _ val xs)-          = EmptyRes com val xs-    doParse com (z :: (ys ++ more)) (Alt x y) | sml | (NonEmptyRes _ val more)-          = NonEmptyRes com val more-  doParse com xs (SeqEmpty act next) | (Access morerec)-          = case doParse com xs act | Access morerec of-                 Failure com msg ts => Failure com msg ts-                 EmptyRes com val xs =>-                       case doParse com xs (next val) | (Access morerec) of-                            Failure com' msg ts => Failure com' msg ts-                            EmptyRes com' val xs => EmptyRes com' val xs-                            NonEmptyRes com' val more => NonEmptyRes com' val more-                 NonEmptyRes {x} {xs=ys} com val more =>-                       case (doParse com more (next val) | morerec _ (shorter more ys)) of-                            Failure com' msg ts => Failure com' msg ts-                            EmptyRes com' val _ => NonEmptyRes com' val more-                            NonEmptyRes {x=x1} {xs=xs1} com' val more' =>-                                 rewrite appendAssociative (x :: ys) (x1 :: xs1) more' in-                                         NonEmptyRes com' val more'-  doParse com xs (SeqEat act next) | sml with (doParse com xs act | sml)-    doParse com xs (SeqEat act next) | sml | Failure com' msg ts-         = Failure com' msg ts-    doParse com (x :: (ys ++ more)) (SeqEat act next) | (Access morerec) | (NonEmptyRes com' val more)-         = case doParse com' more (next val) | morerec _ (shorter more ys) of-                Failure com' msg ts => Failure com' msg ts-                EmptyRes com' val _ => NonEmptyRes com' val more-                NonEmptyRes {x=x1} {xs=xs1} com' val more' =>-                     rewrite appendAssociative (x :: ys) (x1 :: xs1) more' in-                             NonEmptyRes com' val more'-  -- This next line is not strictly necessary, but it stops the coverage-  -- checker taking a really long time and eating lots of memory...-  doParse _ _ _ | sml = Failure True "Help the coverage checker!" []+||| Parse one or more things, each separated by another thing.+sepBy1 : {c : Bool} ->+         (sep : Grammar tok True s) ->+         (p : Grammar tok c a) ->+         Grammar tok c (List a)+sepBy1 {c} sep p = rewrite sym (orFalseNeutral c) in+                           [| p :: many (sep *> p) |] -public export-data ParseError tok = Error String (List tok)+||| Parse zero or more things, each separated by another thing. May+||| match the empty input.+sepBy : (sep : Grammar tok True s) ->+        (p : Grammar tok c a) ->+        Grammar tok False (List a)+sepBy sep p = option [] $ sepBy1 sep p -||| Parse a list of tokens according to the given grammar. If successful,-||| returns a pair of the parse result and the unparsed tokens (the remaining-||| input).-export-parse : (xs : List tok) -> (act : Grammar tok c ty) ->-        Either (ParseError tok) (ty, List tok)-parse xs act-    = case doParse False xs act of-           Failure _ msg ts => Left (Error msg ts)-           EmptyRes _ val rest => pure (val, rest)-           NonEmptyRes _ val rest => pure (val, rest)+||| Parse one or more instances of `p` separated by `sep`, returning the+||| parsed items and proof that the resulting list is non-empty.+sepBy1' : {c : Bool} ->+         (sep : Grammar tok True s) ->+         (p : Grammar tok c a) ->+         Grammar tok c (xs : List a ** NonEmpty xs)+sepBy1' {c} sep p+  = rewrite sym (orFalseNeutral c) in+            seq p (\x => do xs <- many (sep *> p)+                            pure (x :: xs ** IsNonEmpty)) -||| Parse one or more things-export-some : Grammar tok True a ->-       Grammar tok True (List a)-some p = do x <- p-            (do xs <- some p-                pure (x :: xs)) <|> pure [x]+||| Parse one or more instances of `p` separated by and optionally terminated by+||| `sep`.+sepEndBy1 : {c : Bool} ->+            (sep : Grammar tok True s) ->+            (p : Grammar tok c a) ->+            Grammar tok c (List a)+sepEndBy1 {c} sep p = rewrite sym (orFalseNeutral c) in+                              sepBy1 sep p <* optional sep -||| Parse zero or more things (may match the empty input)-export-many : Grammar tok True a ->-       Grammar tok False (List a)-many p = some p-     <|> pure []+||| Parse zero or more instances of `p`, separated by and optionally terminated+||| by `sep`. Will not match a separator by itself.+sepEndBy : (sep : Grammar tok True s) ->+           (p : Grammar tok c a) ->+           Grammar tok False (List a)+sepEndBy sep p = option [] $ sepEndBy1 sep p -||| Parse one or more things, separated by another thing-export-sepBy1 : Grammar tok True () -> Grammar tok True a ->+||| Parse zero or more instances of `p`, separated by and optionally terminated+||| by `sep`, returning the parsed items and a proof that the resulting list+||| is non-empty.+sepEndBy1' : {c : Bool} ->+             (sep : Grammar tok True s) ->+             (p : Grammar tok c a) ->+             Grammar tok c (xs : List a ** NonEmpty xs)+sepEndBy1' {c} sep p = rewrite sym (orFalseNeutral c) in+                               sepBy1' sep p <* optional sep++||| Parse one or more instances of `p`, separated and terminated by `sep`.+endBy1 : {c : Bool} ->+         (sep : Grammar tok True s) ->+         (p : Grammar tok c a) ->          Grammar tok True (List a)-sepBy1 sep p = do x <- p-                  (do sep-                      xs <- sepBy1 sep p-                      pure (x :: xs)) <|> pure [x]+endBy1 {c} sep p = some $ rewrite sym (orTrueTrue c) in+                                  p <* sep -||| Parse zero or more things, separated by another thing. May-||| match the empty input.-export-sepBy : Grammar tok True () -> Grammar tok True a ->+endBy : (sep : Grammar tok True s) ->+        (p : Grammar tok c a) ->         Grammar tok False (List a)-sepBy sep p = sepBy1 sep p <|> pure []--||| Optionally parse a thing, with a default value if the grammar doesn't-||| match. May match the empty input.-export-optional : Grammar tok True a -> (ifNothing : a) ->-           Grammar tok False a-optional p def = p <|> pure def+endBy sep p = option [] $ endBy1 sep p +||| Parse zero or more instances of `p`, separated and terminated by `sep`,+||| returning the parsed items and a proof that the resulting list is non-empty.+endBy1' : {c : Bool} ->+          (sep : Grammar tok True s) ->+          (p : Grammar tok c a) ->+          Grammar tok True (xs : List a ** NonEmpty xs)+endBy1' {c} sep p = some' $ rewrite sym (orTrueTrue c) in+                                    p <* sep  ||| Parse an instance of `p` that is between `left` and `right`.-export-between : (left  : Grammar tok True ())-       -> (right : Grammar tok True ())-       -> (p     : Grammar tok True a)-       -> Grammar tok True a-between left right contents = do-   left-   res <- contents-   right-   pure res--||| Parse one or more instances of `p` separated by `s`, returning the-||| parsed items and proof the resulting list is non-empty.-export-sepBy1' : (sep : Grammar tok True ())-       -> (p   : Grammar tok True a)-       -> Grammar tok True (xs : List a ** NonEmpty xs)-sepBy1' sep p-    = do x <- p-         (do sep-             xs <- sepBy1 sep p-             pure (x :: xs ** IsNonEmpty)) <|> pure ([x] ** IsNonEmpty)--||| Parse one or more instances of `p`, returning the parsed items and proof the resulting list is non-empty.-export-some' : (p : Grammar tok True a)-     -> Grammar tok True (xs : List a ** NonEmpty xs)-some' p = do-   x <- p-   (do xs <- some p-       pure (x::xs ** IsNonEmpty)) <|> pure ([x] ** IsNonEmpty)---||| Optionally parse a thing. If the grammar provides a default use `optional` instead.-export-maybe : Grammar tok True a-     -> Grammar tok False (Maybe a)-maybe p =-      (do res <- p; pure $ Just res)-  <|> pure Nothing+between : (left : Grammar tok True l) ->+          (right : Grammar tok True r) ->+          (p : Grammar tok c a) ->+          Grammar tok True a+between left right contents = left *> contents <* right
+ libs/contrib/Text/Parser/Core.idr view
@@ -0,0 +1,265 @@+module Text.Parser.Core++import public Control.Delayed++%default total++-- TODO: Add some primitives for helping with error messages.+-- e.g. perhaps set a string to state what we're currently trying to+-- parse, or to say what the next expected token is in words++||| Description of a language's grammar. The `tok` parameter is the type+||| of tokens, and the `consumes` flag is True if the language is guaranteed+||| to be non-empty - that is, successfully parsing the language is guaranteed+||| to consume some input.+export+data Grammar : (tok : Type) -> (consumes : Bool) -> Type -> Type where+     Empty : (val : ty) -> Grammar tok False ty+     Terminal : (tok -> Maybe a) -> Grammar tok True a+     NextIs : (tok -> Bool) -> Grammar tok False tok+     EOF : Grammar tok False ()++     Fail : String -> Grammar tok c ty+     Commit : Grammar tok False ()++     SeqEat : Grammar tok True a -> Inf (a -> Grammar tok c2 b) ->+              Grammar tok True b+     SeqEmpty : {c1, c2 : Bool} ->+                Grammar tok c1 a -> (a -> Grammar tok c2 b) ->+                Grammar tok (c1 || c2) b+     Alt : {c1, c2 : Bool} ->+           Grammar tok c1 ty -> Grammar tok c2 ty ->+           Grammar tok (c1 && c2) ty++||| Sequence two grammars. If either consumes some input, the sequence is+||| guaranteed to consume some input. If the first one consumes input, the+||| second is allowed to be recursive (because it means some input has been+||| consumed and therefore the input is smaller)+export %inline+(>>=) : {c1 : Bool} ->+        Grammar tok c1 a ->+        inf c1 (a -> Grammar tok c2 b) ->+        Grammar tok (c1 || c2) b+(>>=) {c1 = False} = SeqEmpty+(>>=) {c1 = True} = SeqEat++||| Sequence two grammars. If either consumes some input, the sequence is+||| guaranteed to consume input. This is an explicitly non-infinite version+||| of `>>=`.+export+seq : Grammar tok c1 a ->+      (a -> Grammar tok c2 b) ->+      Grammar tok (c1 || c2) b+seq = SeqEmpty++||| Sequence a grammar followed by the grammar it returns.+export+join : {c1 : Bool} ->+       Grammar tok c1 (Grammar tok c2 a) ->+       Grammar tok (c1 || c2) a+join {c1 = False} p = SeqEmpty p id+join {c1 = True} p = SeqEat p id++||| Give two alternative grammars. If both consume, the combination is+||| guaranteed to consume.+export+(<|>) : Grammar tok c1 ty ->+        Grammar tok c2 ty ->+        Grammar tok (c1 && c2) ty+(<|>) = Alt++||| Allows the result of a grammar to be mapped to a different value.+export+Functor (Grammar tok c) where+  map f (Empty val)  = Empty (f val)+  map f (Fail msg)   = Fail msg+  map f (Terminal g) = Terminal (\t => map f (g t))+  map f (Alt x y)    = Alt (map f x) (map f y)+  map f (SeqEat act next)+      = SeqEat act (\val => map f (next val))+  map f (SeqEmpty act next)+      = SeqEmpty act (\val => map f (next val))+  -- The remaining constructors (NextIs, EOF, Commit) have a fixed type,+  -- so a sequence must be used.+  map {c = False} f p = SeqEmpty p (Empty . f)++||| Sequence a grammar with value type `a -> b` and a grammar+||| with value type `a`. If both succeed, apply the function+||| from the first grammar to the value from the second grammar.+||| Guaranteed to consume if either grammar consumes.+export+(<*>) : Grammar tok c1 (a -> b) ->+        Grammar tok c2 a ->+        Grammar tok (c1 || c2) b+(<*>) x y = SeqEmpty x (\f => map f y)++||| Sequence two grammars. If both succeed, use the value of the first one.+||| Guaranteed to consume if either grammar consumes.+export+(<*) : Grammar tok c1 a ->+       Grammar tok c2 b ->+       Grammar tok (c1 || c2) a+(<*) x y = map const x <*> y++||| Sequence two grammars. If both succeed, use the value of the second one.+||| Guaranteed to consume if either grammar consumes.+export+(*>) : Grammar tok c1 a ->+       Grammar tok c2 b ->+       Grammar tok (c1 || c2) b+(*>) x y = map (const id) x <*> y++||| Produce a grammar that can parse a different type of token by providing a+||| function converting the new token type into the original one.+export+mapToken : (a -> b) -> Grammar b c ty -> Grammar a c ty+mapToken f (Empty val) = Empty val+mapToken f (Terminal g) = Terminal (g . f)+mapToken f (NextIs g) = SeqEmpty (NextIs (g . f)) (Empty . f)+mapToken f EOF = EOF+mapToken f (Fail msg) = Fail msg+mapToken f Commit = Commit+mapToken f (SeqEat act next) = SeqEat (mapToken f act) (\x => mapToken f (next x))+mapToken f (SeqEmpty act next) = SeqEmpty (mapToken f act) (\x => mapToken f (next x))+mapToken f (Alt x y) = Alt (mapToken f x) (mapToken f y)++||| Always succeed with the given value.+export+pure : (val : ty) -> Grammar tok False ty+pure = Empty++||| Check whether the next token satisfies a predicate+export+nextIs : (tok -> Bool) -> Grammar tok False tok+nextIs = NextIs++||| Look at the next token in the input+export+peek : Grammar tok False tok+peek = nextIs (const True)++||| Succeeds if running the predicate on the next token returns Just x,+||| returning x. Otherwise fails.+export+terminal : (tok -> Maybe a) -> Grammar tok True a+terminal = Terminal++||| Always fail with a message+export+fail : String -> Grammar tok c ty+fail = Fail++||| Succeed if the input is empty+export+eof : Grammar tok False ()+eof = EOF++||| Commit to an alternative; if the current branch of an alternative+||| fails to parse, no more branches will be tried+export+commit : Grammar tok False ()+commit = Commit++data ParseResult : List tok -> (consumes : Bool) -> Type -> Type where+     Failure : {xs : List tok} ->+               (committed : Bool) ->+               (err : String) -> (rest : List tok) -> ParseResult xs c ty+     EmptyRes : (committed : Bool) ->+                (val : ty) -> (more : List tok) -> ParseResult more False ty+     NonEmptyRes : (committed : Bool) ->+                   (val : ty) -> (more : List tok) ->+                   ParseResult (x :: xs ++ more) c ty++-- Take the result of an alternative branch, reset the commit flag to+-- the commit flag from the outer alternative, and weaken the 'consumes'+-- flag to take both alternatives into account+weakenRes : {whatever, c : Bool} -> {xs : List tok} ->+            (com' : Bool) ->+						ParseResult xs c ty -> ParseResult xs (whatever && c) ty+weakenRes com' (Failure com msg ts) = Failure com' msg ts+weakenRes {whatever=True} com' (EmptyRes com val xs) = EmptyRes com' val xs+weakenRes {whatever=False} com' (EmptyRes com val xs) = EmptyRes com' val xs+weakenRes com' (NonEmptyRes com val more) = NonEmptyRes com' val more++shorter : (more : List tok) -> .(ys : List tok) ->+          LTE (S (length more)) (S (length (ys ++ more)))+shorter more [] = lteRefl+shorter more (x :: xs) = LTESucc (lteSuccLeft (shorter more xs))++doParse : {c : Bool} ->+          (commit : Bool) -> (xs : List tok) -> (act : Grammar tok c ty) ->+          ParseResult xs c ty+doParse com xs act with (sizeAccessible xs)+  doParse com xs (Empty val) | sml = EmptyRes com val xs+  doParse com [] (Fail str) | sml = Failure com str []+  doParse com (x :: xs) (Fail str) | sml = Failure com str (x :: xs)+  doParse com xs Commit | sml = EmptyRes True () xs++  doParse com [] (Terminal f) | sml = Failure com "End of input" []+  doParse com (x :: xs) (Terminal f) | sml+        = maybe+             (Failure com "Unrecognised token" (x :: xs))+             (\a => NonEmptyRes com {xs=[]} a xs)+             (f x)+  doParse com [] EOF | sml = EmptyRes com () []+  doParse com (x :: xs) EOF | sml+        = Failure com "Expected end of input" (x :: xs)+  doParse com [] (NextIs f) | sml = Failure com "End of input" []+  doParse com (x :: xs) (NextIs f) | sml+        = if f x+             then EmptyRes com x (x :: xs)+             else Failure com "Unrecognised token" (x :: xs)+  doParse com xs (Alt x y) | sml with (doParse False xs x | sml)+    doParse com xs (Alt x y) | sml | Failure com' msg ts+          = if com' -- If the alternative had committed, don't try the+                    -- other branch (and reset commit flag)+               then Failure com msg ts+               else weakenRes com (doParse False xs y | sml)+    -- Successfully parsed the first option, so use the outer commit flag+    doParse com xs (Alt x y) | sml | (EmptyRes _ val xs)+          = EmptyRes com val xs+    doParse com (z :: (ys ++ more)) (Alt x y) | sml | (NonEmptyRes _ val more)+          = NonEmptyRes com val more+  doParse com xs (SeqEmpty act next) | (Access morerec)+          = case doParse com xs act | Access morerec of+                 Failure com msg ts => Failure com msg ts+                 EmptyRes com val xs =>+                       case doParse com xs (next val) | (Access morerec) of+                            Failure com' msg ts => Failure com' msg ts+                            EmptyRes com' val xs => EmptyRes com' val xs+                            NonEmptyRes com' val more => NonEmptyRes com' val more+                 NonEmptyRes {x} {xs=ys} com val more =>+                       case (doParse com more (next val) | morerec _ (shorter more ys)) of+                            Failure com' msg ts => Failure com' msg ts+                            EmptyRes com' val _ => NonEmptyRes com' val more+                            NonEmptyRes {x=x1} {xs=xs1} com' val more' =>+                                 rewrite appendAssociative (x :: ys) (x1 :: xs1) more' in+                                         NonEmptyRes com' val more'+  doParse com xs (SeqEat act next) | sml with (doParse com xs act | sml)+    doParse com xs (SeqEat act next) | sml | Failure com' msg ts+         = Failure com' msg ts+    doParse com (x :: (ys ++ more)) (SeqEat act next) | (Access morerec) | (NonEmptyRes com' val more)+         = case doParse com' more (next val) | morerec _ (shorter more ys) of+                Failure com' msg ts => Failure com' msg ts+                EmptyRes com' val _ => NonEmptyRes com' val more+                NonEmptyRes {x=x1} {xs=xs1} com' val more' =>+                     rewrite appendAssociative (x :: ys) (x1 :: xs1) more' in+                             NonEmptyRes com' val more'+  -- This next line is not strictly necessary, but it stops the coverage+  -- checker taking a really long time and eating lots of memory...+  doParse _ _ _ | sml = Failure True "Help the coverage checker!" []++public export+data ParseError tok = Error String (List tok)++||| Parse a list of tokens according to the given grammar. If successful,+||| returns a pair of the parse result and the unparsed tokens (the remaining+||| input).+export+parse : (act : Grammar tok c ty) -> (xs : List tok) ->+        Either (ParseError tok) (ty, List tok)+parse act xs+    = case doParse False xs act of+           Failure _ msg ts => Left (Error msg ts)+           EmptyRes _ val rest => pure (val, rest)+           NonEmptyRes _ val rest => pure (val, rest)
libs/contrib/Text/PrettyPrint/WL/Core.idr view
@@ -16,7 +16,7 @@    Cat     : (x : Doc) -> (y : Doc) -> Doc   Nest    : (lvl : Int) -> (x : Doc) -> Doc-  Union   : (x : Doc) -> (y : Doc) -> Doc+  Union   : (x : Doc) -> (y : Lazy Doc) -> Doc    Column  : (f : Int -> Doc) -> Doc   Nesting : (f : Int -> Doc) -> Doc@@ -162,11 +162,12 @@     nicest : (lvl : Int)           -> (col : Int)           -> (x : PrettyDoc)-          -> (y : PrettyDoc)+          -> (y : Lazy PrettyDoc)           -> PrettyDoc     nicest n k x y =-      let width = min (w - k) (rwidth - k + n)-       in if fits width x then x else y+      if fits (min (w - k) (rwidth - k + n)) x+      then x+      else y      best : (lvl : Int)         -> (col : Int)
+ libs/contrib/Text/Quantity.idr view
@@ -0,0 +1,38 @@+module Text.Quantity++%access public export+%default total++record Quantity where+  constructor Qty+  min : Nat+  max : Maybe Nat++Show Quantity where+  show (Qty Z Nothing) = "*"+  show (Qty Z (Just (S Z))) = "?"+  show (Qty (S Z) Nothing) = "+"+  show (Qty min max) = "{" ++ show min ++ showMax ++ "}"+    where+      showMax : String+      showMax = case max of+                     Nothing => ","+                     Just max' => if min == max'+                                     then ""+                                     else "," ++ show max'++between : Nat -> Nat -> Quantity+between min max = Qty min (Just max)++atLeast : Nat -> Quantity+atLeast min = Qty min Nothing++atMost : Nat -> Quantity+atMost max = Qty 0 (Just max)++exactly : Nat -> Quantity+exactly n = Qty n (Just n)++inOrder : Quantity -> Bool+inOrder (Qty min Nothing) = True+inOrder (Qty min (Just max)) = min <= max
+ libs/contrib/Text/Token.idr view
@@ -0,0 +1,38 @@+module Text.Token++%access public export+%default total++||| For a type `kind`, specify a way of converting the recognised+||| string into a value.+|||+||| ```idris example+||| data SimpleKind = SKString | SKInt | SKComma+|||+||| TokenKind SimpleKind where+|||   TokType SKString = String+|||   TokType SKInt = Int+|||   TokType SKComma = ()+|||+|||   tokValue SKString x = x+|||   tokValue SKInt x = cast x+|||   tokValue SKComma x = ()+||| ```+interface TokenKind (k : Type) where+  ||| The type that a token of this kind converts to.+  TokType : k -> Type++  ||| Convert a recognised string into a value. The type is determined+  ||| by the kind of token.+  tokValue : (kind : k) -> String -> TokType kind++||| A token of a particular kind and the text that was recognised.+record Token k where+  constructor Tok+  kind : k+  text : String++||| Get the value of a `Token k`. The resulting type depends upon+||| the kind of token.+value : TokenKind k => (t : Token k) -> TokType (kind t)+value (Tok k x) = tokValue k x
libs/contrib/contrib.ipkg view
@@ -1,40 +1,101 @@ package contrib  opts = "--nobasepkgs --partial-eval --total -i ../prelude -i ../base"-modules = CFFI, CFFI.Types, CFFI.Memory, -          Control.Algebra,-          Control.Algebra.Lattice, Control.Algebra.VectorSpace,-          Control.Algebra.NumericImplementations,-          Control.Isomorphism.Primitives,-          Control.Partial,-          Control.Pipeline,-          Control.ST, Control.ST.ImplicitCall, Control.ST.Exception,+modules = CFFI+        , CFFI.Memory+        , CFFI.Types -          Interfaces.Verified,+        , Control.Algebra+        , Control.Algebra.Lattice+        , Control.Algebra.NumericImplementations+        , Control.Algebra.VectorSpace -          Data.Fun, Data.Rel,-          Data.Hash,-          Data.Matrix, Data.Matrix.Algebraic, Data.Matrix.Numeric,-          Data.Nat.DivMod, Data.Nat.DivMod.IteratedSubtraction,-          Data.ZZ, Data.Sign,-          Data.BoundedList,-          Data.Heap,-          Data.SortedMap, Data.SortedSet,-          Data.CoList, Data.Storable,-	  Data.List.Zipper,+        , Control.Delayed+        , Control.Isomorphism.Primitives+        , Control.Monad.Syntax+        , Control.Partial+        , Control.Pipeline -          Decidable.Decidable, Decidable.Order,+        , Control.ST+        , Control.ST.Exception+        , Control.ST.ImplicitCall+        , Control.ST.Random+        , Control.ST.File -          Network.Cgi, Network.Socket.Data, Network.Socket.Raw, Network.Socket,+        , Data.Bool.Extra+        , Data.BoundedList+        , Data.CoList+        , Data.Combinators+        , Data.Combinators.Applicative+        , Data.Combinators.Arrow+        , Data.Fin.Extra+        , Data.Fuel+        , Data.Fun+        , Data.Hash+        , Data.Heap+        , Data.IOArray+        , Data.List.Zipper -          System.Concurrency.Process,+        , Data.Matrix+        , Data.Matrix.Algebraic+        , Data.Matrix.Numeric -          Text.Lexer, Text.Parser,+        , Data.Nat.Parity+        , Data.Nat.DivMod+        , Data.Nat.DivMod.IteratedSubtraction -          Text.PrettyPrint.WL,-          Text.PrettyPrint.WL.Core,-          Text.PrettyPrint.WL.Characters,-          Text.PrettyPrint.WL.Combinators,+        , Data.Pairs.Implicit+        , Data.Rel+        , Data.Sign+        , Data.SortedMap+        , Data.SortedSet+        , Data.Storable+        , Data.Stream.Extra+        , Data.String.Extra+        , Data.ZZ -          Data.Fin.Extra+        , Decidable.Decidable+        , Decidable.Order++        , Interfaces.Correlative+        , Interfaces.Verified++        , Language.JSON+        , Language.JSON.Data+        , Language.JSON.Lexer+        , Language.JSON.Parser+        , Language.JSON.String+        , Language.JSON.String.Lexer+        , Language.JSON.String.Parser+        , Language.JSON.String.Tokens+        , Language.JSON.Tokens++        , Network.Cgi+        , Network.Socket+        , Network.Socket.Data+        , Network.Socket.Raw++        , System.Concurrency.Process++        , Test.Unit.Display+        , Test.Unit.Runners+        , Test.Unit.Generic+        , Test.Unit.Assertions+        , Test.Unit++        , Text.Lexer+        , Text.Lexer.Core++        , Text.Literate++        , Text.Parser+        , Text.Parser.Core++        , Text.PrettyPrint.WL.Core+        , Text.PrettyPrint.WL.Combinators+        , Text.PrettyPrint.WL.Characters+        , Text.PrettyPrint.WL++        , Text.Quantity+        , Text.Token
libs/effects/Effect/Logging/Level.idr view
@@ -58,15 +58,15 @@   cast {n} _ = n  implementation Show (LogLevel n) where-  show OFF        = "OFF"-  show TRACE      = "TRACE"-  show DEBUG      = "DEBUG"-  show INFO       = "INFO"-  show WARN       = "WARN"-  show FATAL      = "FATAL"-  show ERROR      = "ERROR"-  show ALL        = "ALL"-  show (CUSTOM n) = unwords ["CUSTOM", show n]+  showPrec d OFF        = "OFF"+  showPrec d TRACE      = "TRACE"+  showPrec d DEBUG      = "DEBUG"+  showPrec d INFO       = "INFO"+  showPrec d WARN       = "WARN"+  showPrec d FATAL      = "FATAL"+  showPrec d ERROR      = "ERROR"+  showPrec d ALL        = "ALL"+  showPrec d (CUSTOM n) = showCon d "CUSTOM" $ showArg n  implementation Eq (LogLevel n) where   (==) x y = lvlEq x y
libs/effects/Effects.idr view
@@ -303,15 +303,8 @@ toEff : .(xs' : List EFFECT) -> EffM m a xs (\v => xs') -> EffM m a xs (\v => xs') toEff xs' = id -infixl 2 <*>- pure : a -> EffM m a xs (\v => xs) pure = Value--return : a -> EffM m a xs (\v => xs)-return = pure--%deprecate Effects.return "Please use `pure`."  pureM : (val : a) -> EffM m a (xs val) xs pureM = Value
libs/effects/effects.ipkg view
@@ -1,21 +1,23 @@ package effects -opts    = "--nobasepkgs --partial-eval --typeintype -i ../prelude -i ../base"+opts = "--nobasepkgs --partial-eval --typeintype -i ../prelude -i ../base"  modules = Effects-        , Effect.Default-        , Effect.Monad +        , Effect.Default         , Effect.Exception         , Effect.File-        , Effect.State++        , Effect.Logging.Category+        , Effect.Logging.Default+        , Effect.Logging.Level++        , Effect.Memory+        , Effect.Monad+        , Effect.Perf         , Effect.Random-        , Effect.StdIO         , Effect.Select-        , Effect.Memory+        , Effect.State+        , Effect.StdIO         , Effect.System         , Effect.Trans-        , Effect.Logging.Level-        , Effect.Logging.Default-        , Effect.Logging.Category-        , Effect.Perf
− libs/oldeffects/Effect/Default.idr
@@ -1,44 +0,0 @@-module Default--interface Default a where-    default : a--implementation Default Int where-    default = 0--implementation Default Integer where-    default = 0--implementation Default Double where-    default = 0--implementation Default Nat where-    default = 0--implementation Default Char where-    default = '\0'--implementation Default String where-    default = ""--implementation Default Bool where-    default = False--implementation Default () where-    default = ()--implementation (Default a, Default b) => Default (a, b) where-    default = (default, default)--implementation Default (Maybe a) where-    default = Nothing--implementation Default (List a) where-    default = []--implementation Default a => Default (Vect n a) where-    default = mkDef _ where-      mkDef : (n : Nat) -> Vect n a-      mkDef Z = []-      mkDef (S k) = default :: mkDef k-
− libs/oldeffects/Effect/Exception.idr
@@ -1,41 +0,0 @@-module Effect.Exception--import Effects-import System-import Control.IOExcept--data Exception : Type -> Effect where-     Raise : a -> { () } Exception a b--implementation Handler (Exception a) Maybe where-     handle _ (Raise e) k = Nothing--implementation Handler (Exception a) List where-     handle _ (Raise e) k = []--implementation Show a => Handler (Exception a) IO where-     handle _ (Raise e) k = do printLn e-                               believe_me (exit 1)--implementation Handler (Exception a) (IOExcept a) where-     handle _ (Raise e) k = ioM (pure (Left e))--implementation Handler (Exception a) (Either a) where-     handle _ (Raise e) k = Left e--EXCEPTION : Type -> EFFECT-EXCEPTION t = MkEff () (Exception t)--raise : a -> { [EXCEPTION a ] } Eff m b-raise err = call $ Raise err--------- TODO: Catching exceptions mid program?--- probably need to invoke a new interpreter---- possibly add a 'handle' to the Eff language so that an alternative--- handler can be introduced mid interpretation?
− libs/oldeffects/Effect/File.idr
@@ -1,128 +0,0 @@--- -------------------------------------------------------- [ Effectful FileIO ]-module Effect.File--import Effects-import Control.IOExcept---||| A Dependent type to describe File Handles. File handles are-||| parameterised with the current state of the file: Closed; Open for-||| reading; and Open for writing.-||| -||| @ m The file mode. -data OpenFile : (m : Mode) -> Type where-     FH : File -> OpenFile m--openOK : Mode -> Bool -> Type-openOK m True = OpenFile m-openOK m False = ()---- ------------------------------------------------------------ [ The Protocol ]--||| Here the protocol for resource access is defined as an effect.-||| The state transitions diagram for the protocol is as follows:-||| -|||     digraph G {-||| -|||       empty; read; write; // States-||| -|||       empty -> read [label="Open R"];-|||       read -> empty [label="Close"];-|||       read -> read [label="ReadLine"];-|||       read -> read [label="EOF"];-|||           -|||       empty -> write [label="Open W"];-|||       write -> empty [label="Close"];-|||       write -> write [label="WriteLine"];-||| -|||     }-data FileIO : Effect where-  ||| Open a file with the specified mode.-  ||| -  ||| Opening a file successful moves the state from 'empty' to the-  ||| specified mode. If not successful the state is still 'empty'.-  ||| -  ||| @ fname The file name to be opened.-  ||| @ m The file mode.-  Open : (fname: String)-         -> (m : Mode)-         -> {() ==> {res} if res-                             then OpenFile m-                             else ()} FileIO Bool--  ||| Close a file.-  ||| -  ||| Closing a file moves the state from Open to closed.-  Close : {OpenFile m ==> ()} FileIO () --  ||| Read a line from the file.-  ||| -  ||| Only files that are open for reading can be read.-  ReadLine : {OpenFile Read}  FileIO String -  -  ||| Write a line to a file.-  ||| -  ||| Only file that are open for writing can be written to.-  WriteLine : String -> {OpenFile Write} FileIO ()--  ||| End of file?-  ||| -  ||| Only files open for reading can be tested for EOF-  EOF : {OpenFile Read}  FileIO Bool---- ------------------------------------------------------------ [ The Handlers ]----- An implementation of the resource access protocol for the IO Context.-implementation Handler FileIO IO where-    handle () (Open fname m) k = do h <- openFile fname m-                                    valid <- validFile h-                                    if valid then k True (FH h) -                                             else k False ()-    handle (FH h) Close      k = do closeFile h-                                    k () ()-    handle (FH h) ReadLine        k = do str <- fread h-                                         k str (FH h)-    handle (FH h) (WriteLine str) k = do fwrite h str-                                         k () (FH h)-    handle (FH h) EOF             k = do e <- feof h-                                         k e (FH h)---- -------------------------------------------------------------- [ The Effect ]-FILE_IO : Type -> EFFECT-FILE_IO t = MkEff t FileIO---- ------------------------------------------------------------ [ The Bindings ]------ Bind the IO context handlers to functions. These functions will run--- in the IO context.-----||| Open a file with the specified mode.-||| -||| @ fname The file name to be opened.-||| @ m The file mode.-open : (fname : String)-       -> (m : Mode)-       -> { [FILE_IO ()] ==> [FILE_IO (if result-                                          then OpenFile m-                                          else ())] } Eff e Bool-open f m = call $ Open f m---||| Close a file.-close : { [FILE_IO (OpenFile m)] ==> [FILE_IO ()] } Eff e ()-close = call $ Close--||| Read a line from the file.-readLine : { [FILE_IO (OpenFile Read)] } Eff e String -readLine = call $ ReadLine--||| Write a line to a file.-writeLine : String -> { [FILE_IO (OpenFile Write)] } Eff e ()-writeLine str = call $ WriteLine str--||| End of file?-eof : { [FILE_IO (OpenFile Read)] } Eff e Bool -eof = call $ EOF---- --------------------------------------------------------------------- [ EOF ]
− libs/oldeffects/Effect/Memory.idr
@@ -1,175 +0,0 @@-module Effect.Memory--import Effects-import Control.IOExcept--%access public--abstract-data MemoryChunk : Nat -> Nat -> Type where-     CH : Ptr -> MemoryChunk size initialized--abstract-data RawMemory : Effect where-     Allocate   : (n : Nat) ->-                  RawMemory () () (\v => MemoryChunk n 0)-     Free       : RawMemory () (MemoryChunk n i) (\v => ())-     Initialize : Bits8 ->-                  (size : Nat) ->-                  so (i + size <= n) ->-                  RawMemory () (MemoryChunk n i) (\v => MemoryChunk n (i + size))-     Peek       : (offset : Nat) ->-                  (size : Nat) ->-                  so (offset + size <= i) ->-                  RawMemory (Vect size Bits8)-                            (MemoryChunk n i) (\v => MemoryChunk n i) -     Poke       :  (offset : Nat) ->-                  (Vect size Bits8) ->-                  so (offset <= i && offset + size <= n) ->-                  RawMemory () (MemoryChunk n i) (\v => MemoryChunk n (max i (offset + size))) -     Move       : (src : MemoryChunk src_size src_init) ->-                  (dst_offset : Nat) ->-                  (src_offset : Nat) ->-                  (size : Nat) ->-                  so (dst_offset <= dst_init && dst_offset + size <= dst_size) ->-                  so (src_offset + size <= src_init) ->-                  RawMemory () (MemoryChunk dst_size dst_init)-                            (\v => MemoryChunk dst_size (max dst_init (dst_offset + size))) -     GetRawPtr  : RawMemory (MemoryChunk n i) (MemoryChunk n i) (\v => MemoryChunk n i) --private-do_malloc : Nat -> IOExcept String Ptr-do_malloc size with (fromInteger (cast size) == size)-  | True  = do ptr <- ioe_lift $ mkForeign (FFun "malloc" [FInt] FPtr) (fromInteger $ cast size)-               fail  <- ioe_lift $ nullPtr ptr-               if fail then ioe_fail "Cannot allocate memory"-               else pure ptr-  | False = ioe_fail "The target architecture does not support adressing enough memory"--private-do_memset : Ptr -> Nat -> Bits8 -> Nat -> IO ()-do_memset ptr offset c size-  = mkForeign (FFun "idris_memset" [FPtr, FInt, FByte, FInt] FUnit)-              ptr (fromInteger $ cast offset) c (fromInteger $ cast size)--private-do_free : Ptr -> IO ()-do_free ptr = mkForeign (FFun "free" [FPtr] FUnit) ptr--private-do_memmove : Ptr -> Ptr -> Nat -> Nat -> Nat -> IO ()-do_memmove dest src dest_offset src_offset size-  = mkForeign (FFun "idris_memmove" [FPtr, FPtr, FInt, FInt, FInt] FUnit)-              dest src (fromInteger $ cast dest_offset) (fromInteger $ cast src_offset) (fromInteger $ cast size)--private-do_peek : Ptr -> Nat -> (size : Nat) -> IO (Vect size Bits8)-do_peek _   _       Z = pure (Prelude.Vect.Nil)-do_peek ptr offset (S n)-  = do b <- mkForeign (FFun "idris_peek" [FPtr, FInt] FByte) ptr (fromInteger $ cast offset)-       bs <- do_peek ptr (S offset) n-       Prelude.Applicative.pure (Prelude.Vect.(::) b bs)--private-do_poke : Ptr -> Nat -> Vect size Bits8 -> IO ()-do_poke _   _      []     = pure ()-do_poke ptr offset (b::bs)-  = do mkForeign (FFun "idris_poke" [FPtr, FInt, FByte] FUnit) ptr (fromInteger $ cast offset) b-       do_poke ptr (S offset) bs--implementation Handler RawMemory (IOExcept String) where-  handle () (Allocate n) k-    = do ptr <- do_malloc n-         k () (CH ptr)-  handle {-{res = MemoryChunk _ offset}-} (CH ptr) (Initialize {i} c size _) k-    = ioe_lift (do_memset ptr i c size) $> k () (CH ptr)-  handle (CH ptr) (Free) k-    = ioe_lift (do_free ptr) $> k () ()-  handle (CH ptr) (Peek offset size _) k-    = do res <- ioe_lift (do_peek ptr offset size)-         k res (CH ptr)-  handle (CH ptr) (Poke offset content _) k-    = do ioe_lift (do_poke ptr offset content)-         k () (CH ptr)-  handle (CH dest_ptr) (Move (CH src_ptr) dest_offset src_offset size _ _) k-    = do ioe_lift (do_memmove dest_ptr src_ptr dest_offset src_offset size)-         k () (CH dest_ptr)-  handle chunk (GetRawPtr) k-    = k chunk chunk--RAW_MEMORY : Type -> EFFECT-RAW_MEMORY t = MkEff t RawMemory--allocate : (n : Nat) -> -           Eff m () [RAW_MEMORY ()] (\v => [RAW_MEMORY (MemoryChunk n 0)])-allocate size = call $ Allocate size--initialize : {i : Nat} ->-             {n : Nat} ->-             Bits8 ->-             (size : Nat) ->-             so (i + size <= n) ->-             Eff m () [RAW_MEMORY (MemoryChunk n i)] -                       (\v => [RAW_MEMORY (MemoryChunk n (i + size))])-initialize c size prf = call $ Initialize c size prf--free : Eff m () [RAW_MEMORY (MemoryChunk n i)] (\v => [RAW_MEMORY ()])-free = call Free--peek : {i : Nat} ->-       (offset : Nat) ->-       (size : Nat) ->-       so (offset + size <= i) ->-       { [RAW_MEMORY (MemoryChunk n i)] } Eff m (Vect size Bits8) -peek offset size prf = call $ Peek offset size prf--poke : {n : Nat} ->-       {i : Nat} ->-       (offset : Nat) ->-       Vect size Bits8 ->-       so (offset <= i && offset + size <= n) ->-       Eff m () [RAW_MEMORY (MemoryChunk n i)] -              (\v => [RAW_MEMORY (MemoryChunk n (max i (offset + size)))])-poke offset content prf = call $ Poke offset content prf--private-getRawPtr : { [RAW_MEMORY (MemoryChunk n i)] } Eff m (MemoryChunk n i) -getRawPtr = call $ GetRawPtr--private-move' : {dst_size : Nat} ->-        {dst_init : Nat} ->-        {src_init : Nat} ->-        (src_ptr : MemoryChunk src_size src_init) ->-        (dst_offset : Nat) ->-        (src_offset : Nat) ->-        (size : Nat) ->-        so (dst_offset <= dst_init && dst_offset + size <= dst_size) ->-        so (src_offset + size <= src_init) ->-        Eff m () [RAW_MEMORY (MemoryChunk dst_size dst_init)]-               (\v => [RAW_MEMORY (MemoryChunk dst_size (max dst_init (dst_offset + size)))])-move' src_ptr dst_offset src_offset size dst_bounds src_bounds-  = call $ Move src_ptr dst_offset src_offset size dst_bounds src_bounds--data MoveDescriptor = Dst | Src--move : {dst_size : Nat} ->-       {dst_init : Nat} ->-       {src_size : Nat} ->-       {src_init : Nat} ->-       (dst_offset : Nat) ->-       (src_offset : Nat) ->-       (size : Nat) ->-       so (dst_offset <= dst_init && dst_offset + size <= dst_size) ->-       so (src_offset + size <= src_init) ->-       Eff m ()-              [ Dst ::: RAW_MEMORY (MemoryChunk dst_size dst_init)-              , Src ::: RAW_MEMORY (MemoryChunk src_size src_init)]-              (\v =>-                [ Dst ::: RAW_MEMORY (MemoryChunk dst_size (max dst_init (dst_offset + size)))-                , Src ::: RAW_MEMORY (MemoryChunk src_size src_init)])-move dst_offset src_offset size dst_bounds src_bounds-  = do src_ptr <- Src :- getRawPtr-       Dst :- move' src_ptr dst_offset src_offset size dst_bounds src_bounds-       pure ()-
− libs/oldeffects/Effect/Monad.idr
@@ -1,21 +0,0 @@-module Effect.Monad--import Effects---- Eff is a monad too, so we can happily use it in a monad transformer.--using (xs : List EFFECT, m : Type -> Type)-  implementation Functor (\a => EffM m a xs (\v => xs)) where-    map f prog = do t <- prog-                    value (f t)--  implementation Applicative (\a => EffM m a xs (\v => xs)) where-    pure = value-    (<*>) f a = do f' <- f-                   a' <- a-                   value (f' a')--  implementation Monad (\a => Eff m a xs (\v => xs)) where-    (>>=) = Effects.(>>=)--
− libs/oldeffects/Effect/Random.idr
@@ -1,47 +0,0 @@-module Effect.Random--import Effects--data Random : Effect where -     getRandom : { Integer } Random Integer -     setSeed   : Integer -> { Integer } Random () --using (m : Type -> Type)-  implementation Handler Random m where-     handle seed getRandom k-              = let seed' = assert_total ((1664525 * seed + 1013904223) `prim__sremBigInt` (pow 2 32)) in-                    k seed' seed'-     handle seed (setSeed n) k = k () n--RND : EFFECT-RND = MkEff Integer Random--||| Generates a random Integer in a given range-rndInt : Integer -> Integer -> { [RND] } Eff m Integer-rndInt lower upper = do v <- call $ getRandom-                        pure (v `prim__sremBigInt` (upper - lower) + lower)--||| Generate a random number in Fin (S `k`)-||| -||| Note that rndFin k takes values 0, 1, ..., k.-rndFin : (k : Nat) -> { [RND] } Eff m (Fin (S k))-rndFin k = do let v = assert_total $ !(call getRandom) `prim__sremBigInt` (cast (S k))-              pure (toFin v)- where toFin : Integer -> Fin (S k) -       toFin x = case integerToFin x (S k) of-                      Just v => v-                      Nothing => toFin (assert_smaller x (x - cast (S k)))--||| Select a random element from a vector-rndSelect' : Vect (S k) a -> { [RND] } Eff IO a-rndSelect' {k} xs = pure (Vect.index !(rndFin k)  xs)--||| Select a random element from a list, or Nothing if the list is empty-rndSelect : List a -> { [RND] } Eff IO (Maybe a)-rndSelect []      = pure Nothing-rndSelect (x::xs) = pure (Just !(rndSelect' (x::(fromList xs))))--||| Sets the random seed-srand : Integer -> { [RND] } Eff m ()-srand n = call $ setSeed n-
− libs/oldeffects/Effect/Select.idr
@@ -1,23 +0,0 @@-module Effect.Select--import Effects--data Selection : Effect where-     Select : List a -> { () } Selection a --implementation Handler Selection Maybe where-     handle _ (Select xs) k = tryAll xs where-         tryAll [] = Nothing-         tryAll (x :: xs) = case k x () of-                                 Nothing => tryAll xs-                                 Just v => Just v--implementation Handler Selection List where-     handle r (Select xs) k = concatMap (\x => k x r) xs--SELECT : EFFECT-SELECT = MkEff () Selection--select : List a -> { [SELECT] } Eff m a -select xs = call $ Select xs-
− libs/oldeffects/Effect/State.idr
@@ -1,40 +0,0 @@-module Effect.State--import Effects--%access public--data State : Effect where-  Get :      { a }       State a-  Put : b -> { a ==> b } State () --using (m : Type -> Type)-  implementation Handler State m where-     handle st Get     k = k st st-     handle st (Put n) k = k () n--STATE : Type -> EFFECT-STATE t = MkEff t State--get : { [STATE x] } Eff m x-get = call $ Get--put : x -> { [STATE x] } Eff m () -put val = call $ Put val--putM : y -> { [STATE x] ==> [STATE y] } Eff m () -putM val = call $ Put val--update : (x -> x) -> { [STATE x] } Eff m () -update f = put (f !get)--updateM : (x -> y) -> { [STATE x] ==> [STATE y] } Eff m () -updateM f = putM (f !get)--locally : x -> ({ [STATE x] } Eff m t) -> { [STATE y] } Eff m t -locally newst prog = do st <- get-                        putM newst-                        val <- prog-                        putM st-                        pure val-
− libs/oldeffects/Effect/StdIO.idr
@@ -1,60 +0,0 @@-module Effect.StdIO--import Effects-import Control.IOExcept------------------------------------------------------------------ IO effects internals----------------------------------------------------------------||| The internal representation of StdIO effects-data StdIO : Effect where-     PutStr : String -> { () } StdIO () -     GetStr : { () } StdIO String -     PutCh : Char -> { () } StdIO ()-     GetCh : { () } StdIO Char------------------------------------------------------------------- IO effects handlers----------------------------------------------------------------implementation Handler StdIO IO where-    handle () (PutStr s) k = do putStr s; k () ()-    handle () GetStr     k = do x <- getLine; k x ()-    handle () (PutCh c)  k = do putChar c; k () () -    handle () GetCh      k = do x <- getChar; k x ()--implementation Handler StdIO (IOExcept a) where-    handle () (PutStr s) k = do ioe_lift $ putStr s; k () ()-    handle () GetStr     k = do x <- ioe_lift $ getLine; k x ()-    handle () (PutCh c)  k = do ioe_lift $ putChar c; k () () -    handle () GetCh      k = do x <- ioe_lift $ getChar; k x ()------------------------------------------------------------------- The Effect and associated functions----------------------------------------------------------------STDIO : EFFECT-STDIO = MkEff () StdIO--||| Write a string to standard output.-putStr : String -> { [STDIO] } Eff e ()-putStr s = call $ PutStr s--||| Write a character to standard output.-putChar : Char -> { [STDIO] } Eff e ()-putChar c = call $ PutCh c--||| Write a string to standard output, terminating with a newline.-putStrLn : String -> { [STDIO] } Eff e ()-putStrLn s = putStr (s ++ "\n")--||| Read a string from standard input.-getStr : { [STDIO] } Eff e String-getStr = call $ GetStr--||| Read a character from standard input.-getChar : { [STDIO] } Eff e Char-getChar = call $ GetCh-
− libs/oldeffects/Effect/System.idr
@@ -1,43 +0,0 @@-module Effect.System---- Various system interaction features (this is not necessarily the right way--- to split them up, I just need some of them now :))--import Effects-import System-import Control.IOExcept--data System : Effect where-     Args : { () } System (List String)-     Time : { () } System Int-     GetEnv : String -> { () } System (Maybe String)-     CSystem : String -> { () } System Int--implementation Handler System IO where-    handle () Args k = do x <- getArgs; k x ()-    handle () Time k = do x <- time; k x ()-    handle () (GetEnv s) k = do x <- getEnv s; k x ()-    handle () (CSystem s) k = do x <- system s; k x ()--implementation Handler System (IOExcept a) where-    handle () Args k = do x <- ioe_lift getArgs; k x ()-    handle () Time k = do x <- ioe_lift time; k x ()-    handle () (GetEnv s) k = do x <- ioe_lift $ getEnv s; k x ()-    handle () (CSystem s) k = do x <- ioe_lift $ system s; k x ()----- The Effect and associated functions--SYSTEM : EFFECT-SYSTEM = MkEff () System--getArgs : Handler System e => { [SYSTEM] } Eff e (List String)-getArgs = call Args--time : Handler System e => { [SYSTEM] } Eff e Int-time = call Time--getEnv : Handler System e => String -> { [SYSTEM] } Eff e (Maybe String)-getEnv s = call $ GetEnv s--system : Handler System e => String -> { [SYSTEM] } Eff e Int-system s = call $ CSystem s
− libs/oldeffects/Effects.idr
@@ -1,333 +0,0 @@-module Effects--import Language.Reflection-import Control.Catchable-import Effect.Default----- Effectful computations are described as algebraic data types that---- explain how an effect is interpreted in some underlying context.--%access public--- ----------------------------------------------------------------- [ Effects ]-||| The Effect type describes effectful computations.-|||-||| This type is parameterised by:-||| + The input resource.-||| + The return type of the computation.-||| + The computation to run on the resource.-Effect : Type-Effect = (x : Type) -> Type -> (x -> Type) -> Type--||| The `EFFECT` Data type describes how to promote the Effect-||| description into a concrete effect.-%error_reverse-data EFFECT : Type where-     MkEff : Type -> Effect -> EFFECT--||| Handler interfaces describe how an effect `e` is translated to the-||| underlying computation context `m` for execution.-interface Handler (e : Effect) (m : Type -> Type) where-  ||| How to handle the effect.-  |||-  ||| @ r The resource being handled.-  ||| @ eff The effect to be applied.-  ||| @ k The continuation to pass the result of the effect-  covering handle : (r : res) -> (eff : e t res resk) ->-                    (k : ((x : t) -> resk x -> m a)) -> m a--||| Get the resource type (handy at the REPL to find out about an effect)-resourceType : EFFECT -> Type-resourceType (MkEff t e) = t---- --------------------------------------------------------- [ Syntactic Sugar ]---- A bit of syntactic sugar ('syntax' is not very flexible so we only go--- up to a small number of parameters...)---- No state transition-syntax "{" [inst] "}" [eff] = eff inst (\result => inst)---- The state transition is dependent on a result `b`, a bound variable.-syntax "{" [inst] "==>" "{" {b} "}" [outst] "}" [eff]-       = eff inst (\b => outst)----- A simple state transition-syntax "{" [inst] "==>" [outst] "}" [eff] = eff inst (\result => outst)---- --------------------------------------- [ Properties and Proof Construction ]-using (xs : List a, ys : List a)-  data SubList : List a -> List a -> Type where-       SubNil : SubList {a} [] []-       Keep   : SubList xs ys -> SubList (x :: xs) (x :: ys)-       Drop   : SubList xs ys -> SubList xs (x :: ys)--  subListId : SubList xs xs-  subListId {xs = Nil} = SubNil-  subListId {xs = x :: xs} = Keep subListId--namespace Env-  data Env  : (m : Type -> Type) -> List EFFECT -> Type where-       Nil  : Env m Nil-       (::) : Handler eff m => a -> Env m xs -> Env m (MkEff a eff :: xs)--data EffElem : Effect -> Type ->-               List EFFECT -> Type where-     Here : EffElem x a (MkEff a x :: xs)-     There : EffElem x a xs -> EffElem x a (y :: xs)--||| make an environment corresponding to a sub-list-dropEnv : Env m ys -> SubList xs ys -> Env m xs-dropEnv [] SubNil = []-dropEnv (v :: vs) (Keep rest) = v :: dropEnv vs rest-dropEnv (v :: vs) (Drop rest) = dropEnv vs rest--updateWith : (ys' : List a) -> (xs : List a) ->-             SubList ys xs -> List a-updateWith (y :: ys) (x :: xs) (Keep rest) = y :: updateWith ys xs rest-updateWith ys        (x :: xs) (Drop rest) = x :: updateWith ys xs rest-updateWith []        []        SubNil      = []-updateWith (y :: ys) []        SubNil      = y :: ys-updateWith []        (x :: xs) (Keep rest) = []--||| Put things back, replacing old with new in the sub-environment-rebuildEnv : Env m ys' -> (prf : SubList ys xs) ->-             Env m xs -> Env m (updateWith ys' xs prf)-rebuildEnv []        SubNil      env = env-rebuildEnv (x :: xs) SubNil      env = x :: xs-rebuildEnv []        (Keep rest) (y :: env) = []-rebuildEnv (x :: xs) (Keep rest) (y :: env) = x :: rebuildEnv xs rest env-rebuildEnv xs        (Drop rest) (y :: env) = y :: rebuildEnv xs rest env----- -------------------------------------------------- [ The Effect EDSL itself ]--updateResTy : (val : t) ->-              (xs : List EFFECT) -> EffElem e a xs -> e t a b ->-              List EFFECT-updateResTy {b} val (MkEff a e :: xs) Here n = (MkEff (b val) e) :: xs-updateResTy     val (x :: xs)    (There p) n = x :: updateResTy val xs p n--infix 5 :::, :-, :=--data LRes : lbl -> Type -> Type where-     (:=) : (x : lbl) -> res -> LRes x res--(:::) : lbl -> EFFECT -> EFFECT-(:::) {lbl} x (MkEff r e) = MkEff (LRes x r) e--using (lbl : Type)-  implementation Default a => Default (LRes lbl a) where-    default = lbl := default--private-unlabel : {l : ty} -> Env m [l ::: x] -> Env m [x]-unlabel {m} {x = MkEff a eff} [l := v] = [v]--private-relabel : (l : ty) -> Env m xs -> Env m (map (\x => l ::: x) xs)-relabel {xs = []} l [] = []-relabel {xs = (MkEff a e :: xs)} l (v :: vs) = (l := v) :: relabel l vs---- ------------------------------------------------- [ The Language of Effects ]-||| Definition of an Effect.-|||-||| @ m The computation context-||| @ x The return type of the result.-||| @ es The list of allowed side-effects.-||| @ ce Function to compute a new list of allowed side-effects.-data Eff : (m : Type -> Type)-           -> (x : Type)-           -> (es : List EFFECT)-           -> (ce : x -> List EFFECT) -> Type where-     value    : a -> Eff m a xs (\v => xs)-     with_val : (val : a) -> Eff m () xs (\v => xs' val) ->-                Eff m a xs xs'-     ebind    : Eff m a xs xs' ->-                ((val : a) -> Eff m b (xs' val) xs'') -> Eff m b xs xs''-     callP    : (prf : EffElem e a xs) ->-                (eff : e t a b) ->-                Eff m t xs (\v => updateResTy v xs prf eff)--     liftP    : (prf : SubList ys xs) ->-                Eff m t ys ys' -> Eff m t xs (\v => updateWith (ys' v) xs prf)-     newInit  : Handler e m =>-                res ->-                Eff m a (MkEff res e :: xs) (\v => (MkEff res' e :: xs')) ->-                Eff m a xs (\v => xs')-     catch    : Catchable m err =>-                Eff m a xs xs' -> (err -> Eff m a xs xs') ->-                Eff m a xs xs'--     (:-)     : (l : ty) ->-                Eff m t [x] xs' -> -- [x] (\v => xs) ->-                Eff m t [l ::: x] (\v => map (l :::) (xs' v))--(>>=)   : Eff m a xs xs' ->-          ((val : a) -> Eff m b (xs' val) xs'') -> Eff m b xs xs''-(>>=) = ebind---- namespace SimpleBind---   (>>=) : Eff m a xs (\v => xs) ->---           ((val : a) -> Eff m b xs xs') -> Eff m b xs xs'---   (>>=) = ebind--||| Run a subprogram which results in an effect state the same as the input.-staticEff : Eff m a xs (\v => xs) -> Eff m a xs (\v => xs)-staticEff = id--||| Explicitly give the expected set of result effects for an effectful-||| operation.-toEff : .(xs' : List EFFECT) -> Eff m a xs (\v => xs') -> Eff m a xs (\v => xs')-toEff xs' = id--return : a -> Eff m a xs (\v => xs)-return x = value x---- ------------------------------------------------------ [ for idiom brackets ]--infixl 2 <*>--pure : a -> Eff m a xs (\v => xs)-pure = value--syntax pureM [val] = with_val val (pure ())--(<*>) : Eff m (a -> b) xs (\v => xs) ->-        Eff m a xs (\v => xs) -> Eff m b xs (\v => xs)-(<*>) prog v = do fn <- prog-                  arg <- v-                  return (fn arg)---- ---------------------------------------------------------- [ an interpreter ]--private-execEff : Env m xs -> (p : EffElem e res xs) ->-          (eff : e a res resk) ->-          ((v : a) -> Env m (updateResTy v xs p eff) -> m t) -> m t-execEff (val :: env) Here eff' k-    = handle val eff' (\v, res => k v (res :: env))--- FIXME: Teach the elaborator to propagate parameters here-execEff {e} {a} {res} {resk} (val :: env) (There p) eff k-    = execEff {e} {a} {res} {resk} env p eff (\v, env' => k v (val :: env'))---- Q: Instead of m b, implement as StateT (Env m xs') m b, so that state--- updates can be propagated even through failing computations?--eff : Env m xs -> Eff m a xs xs' -> ((x : a) -> Env m (xs' x) -> m b) -> m b-eff env (value x) k = k x env-eff env (with_val x prog) k = eff env prog (\p', env' => k x env')-eff env (prog `ebind` c) k-   = eff env prog (\p', env' => eff env' (c p') k)-eff env (callP prf effP) k = execEff env prf effP k-eff env (liftP prf effP) k-   = let env' = dropEnv env prf in-         eff env' effP (\p', envk => k p' (rebuildEnv envk prf env))-eff env (newInit r prog) k-   = eff (r :: env) prog (\p' => \ (v :: envk) => k p' envk)-eff env (catch prog handler) k-   = catch (eff env prog k)-           (\e => eff env (handler e) k)--- FIXME:--- xs is needed explicitly because otherwise the pattern binding for--- 'l' appears too late. Solution seems to be to reorder patterns at the--- end so that everything is in scope when it needs to be.-eff {xs = [l ::: x]} env (l :- prog) k-   = let env' = unlabel env in-         eff env' prog (\p', envk => k p' (relabel l envk))---- yuck :) Haven't got interface implementations working nicely in tactic--- proofs yet, and 'search' can't be told about any hints yet,--- so just brute force it.-syntax MkDefaultEnv = with Env-                       (| [], [default], [default, default],-                          [default, default, default],-                          [default, default, default, default],-                          [default, default, default, default, default],-                          [default, default, default, default, default, default],-                          [default, default, default, default, default, default, default],-                          [default, default, default, default, default, default, default, default] |)--call : {a, b: _} -> {e : Effect} ->-       (eff : e t a b) ->-       {auto prf : EffElem e a xs} ->-      Eff m t xs (\v => updateResTy v xs prf eff)-call e {prf} = callP prf e--implicit-lift : Eff m t ys ys' ->-       {auto prf : SubList ys xs} ->-       Eff m t xs (\v => updateWith (ys' v) xs prf)-lift e {prf} = liftP prf e---new : Handler e m =>-      {default default r : res} ->-      Eff m a (MkEff res e :: xs) (\v => (MkEff res' e :: xs')) ->-      Eff m a xs (\v => xs')-new {r} e = newInit r e---- --------------------------------------------------------- [ Running Effects ]--||| Run an effectful program.-|||-||| The content (`m`) in which to run the program is taken from the environment in which the program is called.-||| The `env` argument is implicit and initialised automatically.-|||-||| @prog The effectful program to run.-run : Applicative m => {default MkDefaultEnv env : Env m xs} -> (prog : Eff m a xs xs') -> m a-run {env} prog = eff env prog (\r, env => pure r)--||| Run an effectful program in the identity context `id`.-|||-||| A helper function useful for when the given context is 'pure'.-||| The `env` argument is implicit and initialised automatically.-|||-||| @prog The effectful program to run.-runPure : {default MkDefaultEnv env : Env id xs} -> (prog : Eff id a xs xs') -> a-runPure {env} prog = eff env prog (\r, env => r)--||| Run an effectful program with a default value for the environment context.-|||-||| This is useful for when no default value exists for a given resource type.-|||-||| @val The default value for the resource type.-||| @prog The effectful program to run.-runInit : Applicative m => (val : Env m xs) -> (prog : Eff m a xs xs') -> m a-runInit env prog = eff env prog (\r, env => pure r)--||| Run an effectful program in the identity context `id` with a given default value for the environment context.-|||-||| A helper function useful for when the given context is 'pure'.-|||-||| @val The default value for the resource type.-||| @prog The effectful program to run.-runPureInit : (val : Env id xs) -> (prog : Eff id a xs xs') -> a-runPureInit env prog = eff env prog (\r, env => r)--runWith : (a -> m a) -> Env m xs -> Eff m a xs xs' -> m a-runWith inj env prog = eff env prog (\r, env => inj r)--runEnv : Applicative m => Env m xs -> Eff m a xs xs' ->-         m (x : a ** Env m (xs' x))-runEnv env prog = eff env prog (\r, env => pure (r ** env))---- ----------------------------------------------- [ some higher order things ]--mapE : Applicative m => (a -> {xs} Eff m b) -> List a -> {xs} Eff m (List b)-mapE f []        = pure []-mapE f (x :: xs) = [| f x :: mapE f xs |]---mapVE : Applicative m =>-          (a -> {xs} Eff m b) ->-          Vect n a ->-          {xs} Eff m (Vect n b)-mapVE f []        = pure []-mapVE f (x :: xs) = [| f x :: mapVE f xs |]---when : Applicative m => Bool -> Lazy ({xs} Eff m ()) -> {xs} Eff m ()-when True  e = Force e-when False e = pure ()---- --------------------------------------------------------------------- [ EOF ]
− libs/oldeffects/Makefile
@@ -1,22 +0,0 @@-IDRIS := idris--PKG   := effects--build:-	$(IDRIS) --build ${PKG}.ipkg--clean:-	$(IDRIS) --clean ${PKG}.ipkg--install:-	$(IDRIS) --install ${PKG}.ipkg--rebuild: clean build--doc:-	$(IDRIS) --mkdoc ${PKG}.ipkg--doc_clean:-	rm -rf ${PKG}_doc--.PHONY: build clean install rebuild doc doc_clean
− libs/oldeffects/effects.ipkg
@@ -1,9 +0,0 @@-package oldeffects--opts    = "--nobasepkgs -i ../prelude -i ../base"-modules = Effects, Effect.Default,--          Effect.Exception, Effect.File, Effect.State,-          Effect.Random, Effect.StdIO, Effect.Select,-          Effect.Memory, Effect.System-
libs/prelude/Builtins.idr view
@@ -3,6 +3,7 @@ %access public export %default total %language UniquenessTypes+%language LinearTypes  ||| The canonical single-element type, also known as the trivially ||| true proposition.@@ -18,7 +19,7 @@      ||| A pair of elements      ||| @a the left element of the pair      ||| @b the right element of the pair-     MkPair : {A, B : Type} -> (a : A) -> (b : B) -> Pair A B+     MkPair : {A, B : Type} -> (1 a : A) -> (1 b : B) -> Pair A B    -- Usage hints for erasure analysis   %used MkPair a@@ -50,14 +51,6 @@   data DPair : (a : Type) -> (P : a -> Type) -> Type where       MkDPair : .{P : a -> Type} -> (x : a) -> (pf : P x) -> DPair a P -  Sigma : (a : Type) -> (P : a -> Type) -> Type-  Sigma wit prf = DPair wit prf-  %deprecate Sigma "This name is being deprecated in favour of `DPair`."--  MkSigma : .{P : a -> Type} -> (x : a) -> (prf : P x) -> DPair a P-  MkSigma wit prf = MkDPair wit prf-  %deprecate MkSigma "This constructor is being deprecated in favour of `MkDPair`."- ||| The empty type, also known as the trivially false proposition. ||| ||| Use `void` or `absurd` to prove anything if you have a variable of type `Void` in scope.@@ -129,14 +122,14 @@ Force : {t, a : _} -> Delayed t a -> a Force (Delay x) = x -||| Lazily evaluated values. +||| Lazily evaluated values. ||| At run time, the delayed value will only be computed when required by ||| a case split. %error_reverse Lazy : Type -> Type Lazy t = Delayed LazyValue t -||| Possibly infinite data. +||| Possibly infinite data. ||| A value which may be infinite is accepted by the totality checker if ||| it appears under a data constructor. At run time, the delayed value will ||| only be computed when required by a case split.@@ -186,21 +179,15 @@  ||| Subvert the type checker. This function is abstract, so it will not reduce in ||| the type checker. Use it with care - it can result in segfaults or worse!-export +export believe_me : a -> b believe_me x = assert_total (prim__believe_me _ _ x)  ||| Subvert the type checker. This function *will*  reduce in the type checker. ||| Use it with extreme care - it can result in segfaults or worse!-public export +public export really_believe_me : a -> b really_believe_me x = assert_total (prim__believe_me _ _ x)--||| Deprecated alias for `Double`, for the purpose of backwards-||| compatibility. Idris does not support 32 bit floats at present.-Float : Type-Float = Double-%deprecate Float  -- Pointers as external primitive; there's no literals for these, so no -- need for them to be part of the compiler.
libs/prelude/Decidable/Equality.idr view
@@ -169,7 +169,8 @@                      False => No primitiveNotEq        where primitiveEq : x = y              primitiveEq = really_believe_me (Refl {x})-             postulate primitiveNotEq : x = y -> Void+             primitiveNotEq : x = y -> Void+             primitiveNotEq = really_believe_me (id {a = x = y})  -------------------------------------------------------------------------------- -- Char@@ -181,7 +182,8 @@                      False => No primitiveNotEq        where primitiveEq : x = y              primitiveEq = really_believe_me (Refl {x})-             postulate primitiveNotEq : x = y -> Void+             primitiveNotEq : x = y -> Void+             primitiveNotEq = really_believe_me (id {a = x = y})  -------------------------------------------------------------------------------- -- Integer@@ -193,7 +195,8 @@                      False => No primitiveNotEq        where primitiveEq : x = y              primitiveEq = really_believe_me (Refl {x})-             postulate primitiveNotEq : x = y -> Void+             primitiveNotEq : x = y -> Void+             primitiveNotEq = really_believe_me (id {a = x = y})  -------------------------------------------------------------------------------- -- String@@ -205,7 +208,8 @@                      False => No primitiveNotEq        where primitiveEq : x = y              primitiveEq = really_believe_me (Refl {x})-             postulate primitiveNotEq : x = y -> Void+             primitiveNotEq : x = y -> Void+             primitiveNotEq = really_believe_me (id {a = x = y})  -------------------------------------------------------------------------------- -- Ptr@@ -217,7 +221,8 @@                      False => No primitiveNotEq        where primitiveEq : x = y              primitiveEq = really_believe_me (Refl {x})-             postulate primitiveNotEq : x = y -> Void+             primitiveNotEq : x = y -> Void+             primitiveNotEq = really_believe_me (id {a = x = y})  -------------------------------------------------------------------------------- -- ManagedPtr@@ -229,4 +234,5 @@                      False => No primitiveNotEq        where primitiveEq : x = y              primitiveEq = really_believe_me (Refl {x})-             postulate primitiveNotEq : x = y -> Void+             primitiveNotEq : x = y -> Void+             primitiveNotEq = really_believe_me (id {a = x = y})
libs/prelude/IO.idr view
@@ -101,9 +101,10 @@ prim_io_pure : a -> PrimIO a prim_io_pure x = Prim__IO x +-- Don't %inline; the compiler treats it specially io_bind : IO' l a -> (a -> IO' l b) -> IO' l b-io_bind (MkIO fn) k-   = MkIO (\w => prim_io_bind (fn w)+io_bind (MkIO fn) +   = \k => MkIO (\w => prim_io_bind (fn w)                     (\ b => case k b of                                  MkIO fkb => fkb w)) 
libs/prelude/Language/Reflection.idr view
@@ -74,14 +74,6 @@                    | MetaN TTName TTName   %name SpecialName sn, sn' -InstanceN : TTName -> (List String) -> SpecialName-InstanceN = ImplementationN-%deprecate InstanceN "`InstanceN` is deprecated, Please use `ImplementationN` instead."--InstanceCtorN : TTName ->  SpecialName-InstanceCtorN = ImplementationCtorN-%deprecate InstanceCtorN "`InstanceCtorN` is deprecated, Please use `ImplementationCtorN` instead."- -- Rather  than  implement  one-off  private functions,  we  make  the -- disjointness of  the constructors available to  all Idris programs, -- at the cost of a bit of scrolling here.@@ -410,7 +402,7 @@   private   implementationNInj : (ImplementationN n xs = ImplementationN n' ys) -> (n = n', xs = ys)   implementationNInj Refl = (Refl, Refl)-  +   private   parentNInj : (ParentN n x = ParentN n' y) -> (n = n', x = y)   parentNInj Refl = (Refl, Refl)
libs/prelude/Language/Reflection/Elab.idr view
@@ -560,11 +560,6 @@   addImplementation : (ifaceName, implName : TTName) -> Elab ()   addImplementation ifaceName implName = Prim__AddImplementation ifaceName implName -  export-  addInstance : (ifaceName, implName : TTName) -> Elab ()-  addInstance = addImplementation-  %deprecate addInstance "`addInstance` is deprecated, Please use `addImplementation` instead."-   ||| Determine whether a name denotes an interface.   |||   ||| @ name a name that might denote an interface.@@ -769,4 +764,3 @@   quotedTy = `(Datatype)   quote (MkDatatype name tyConArgs tyConRes constructors) =     `(MkDatatype ~(quote name) ~(quote tyConArgs) ~(quote tyConRes) ~(quote constructors))-
libs/prelude/Prelude.idr view
@@ -212,7 +212,7 @@           go : Integer -> Integer -> List Integer           go n m = go' n (natRange (S (cast {to = Nat} (m - n))))   enumFromThenTo n next m = if n == m then [n]-                            else if next - n == 0 || next - n < 0 /= m - n < 0 then []+                            else if next - n == 0 || (next - n < 0) /= (m - n < 0) then []                             else go (natRange (S (divNatNZ (fromInteger (abs (m - n))) (S (fromInteger ((abs (next - n)) - 1))) SIsNotZ)))     where go : List Nat -> List Integer           go [] = []@@ -234,7 +234,7 @@   enumFromThen n inc = countFrom n (inc - n)    enumFromThenTo n next m = if n == m then [n]-                            else if next - n == 0 || next - n < 0 /= m - n < 0 then []+                            else if next - n == 0 || (next - n < 0) /= (m - n < 0) then []                             else go (natRange (S (divNatNZ (cast {to=Nat} (abs (m - n))) (S (cast {to=Nat} ((abs (next - n)) - 1))) SIsNotZ)))     where go : List Nat -> List Int           go [] = []@@ -280,8 +280,7 @@  ||| Pointer equality eqPtr : Ptr -> Ptr -> IO Bool-eqPtr x y = do eq <- foreign FFI_C "idris_eqPtr" (Ptr -> Ptr -> IO Int) x y-               pure (eq /= 0)+eqPtr x y = pure $ prim__eqPtr x y /= 0  ||| Loop while some test is true |||
libs/prelude/Prelude/Applicative.idr view
@@ -12,17 +12,17 @@  ---- Applicative functors/Idioms -infixl 2 <*>+infixl 3 <*>  interface Functor f => Applicative (f : Type -> Type) where     pure  : a -> f a     (<*>) : f (a -> b) -> f a -> f b -infixl 2 <*+infixl 3 <* (<*) : Applicative f => f a -> f b -> f a a <* b = map const a <*> b -infixl 2 *>+infixl 3 *> (*>) : Applicative f => f a -> f b -> f b a *> b = map (const id) a <*> b @@ -38,7 +38,7 @@ liftA3 : Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d liftA3 f a b c = (map f a) <*> b <*> c -infixl 3 <|>+infixr 2 <|> interface Applicative f => Alternative (f : Type -> Type) where     empty : f a     (<|>) : f a -> f a -> f a
libs/prelude/Prelude/Basics.idr view
@@ -29,7 +29,7 @@ snd : (a, b) -> b snd (x, y) = y -infixl 9 .+infixr 9 .  ||| Function composition (.) : (b -> c) -> (a -> b) -> a -> c@@ -58,4 +58,3 @@   ||| The case where the property holding would be a contradiction   ||| @ contra a demonstration that prop would be a contradiction   No  : (contra : prop -> Void) -> Dec prop-
libs/prelude/Prelude/Bits.idr view
@@ -111,28 +111,3 @@ ||| Encode `Bits64` as a 64-character binary string. b64ToBinString : Bits64 -> String b64ToBinString c = concatMap b8ToBinString (b64ToBytes c)-------------------------------------------------------------------------------------- Deprecated String Functions-----------------------------------------------------------------------------------||| Encode `Bits8` as a 2-character hex string.-b8ToString : Bits8 -> String-b8ToString = b8ToHexString-%deprecate b8ToString "Please use `b8ToHexString` instead."--||| Encode `Bits16` as a 4-character hex string.-b16ToString : Bits16 -> String-b16ToString = b16ToHexString-%deprecate b16ToString "Please use `b16ToHexString` instead."--||| Encode `Bits32` as a 8-character hex string.-b32ToString : Bits32 -> String-b32ToString = b32ToHexString-%deprecate b32ToString "Please use `b32ToHexString` instead."--||| Encode `Bits64` as a 16-character hex string.-b64ToString : Bits64 -> String-b64ToString = b64ToHexString-%deprecate b64ToString "Please use `b64ToHexString` instead."
libs/prelude/Prelude/Bool.idr view
@@ -18,7 +18,8 @@ ifThenElse False t e = e  -- Boolean Operator Precedence-infixl 4 &&, ||+infixr 4 ||+infixr 5 &&  ||| Boolean OR only evaluates the second argument if the first is `False`. (||) : Bool -> Lazy Bool -> Bool
libs/prelude/Prelude/Chars.idr view
@@ -81,3 +81,8 @@ ||| Returns true if the character is an octal digit. isOctDigit : Char -> Bool isOctDigit x = (x >= '0' && x <= '7')++||| Returns true if the character is a control character.+isControl : Char -> Bool+isControl x = (x >= '\x0000' && x <= '\x001f')+           || (x >= '\x007f' && x <= '\x009f')
libs/prelude/Prelude/Doubles.idr view
@@ -43,7 +43,7 @@ atan x = prim__floatATan x  atan2 : Double -> Double -> Double-atan2 y x = atan (y/x)+atan2 y x = prim__floatATan2 y x  sinh : Double -> Double sinh x = (exp x - exp (-x)) / 2
libs/prelude/Prelude/File.idr view
@@ -21,13 +21,18 @@ data File : Type where   FHandle : (p : Ptr) -> File +||| A directory handle+data Directory : Type where+  DHandle : (p : Ptr) -> Directory+ -- Usage hints for erasure analysis %used FHandle p+%used DHandle p  ||| An error from a file operation -- This is built in idris_mkFileError() in rts/idris_stdfgn.c. Make sure -- the values correspond!-               + data FileError = GenericFileError Int -- errno                | FileReadError                | FileWriteError@@ -102,10 +107,6 @@ ||| Modes for opening files data Mode = Read | WriteTruncate | Append | ReadWrite | ReadWriteTruncate | ReadAppend -Write : Mode-Write = WriteTruncate-%deprecate Write "Please use WriteTruncate instead."- modeStr : Mode -> String modeStr Read              = "r" modeStr WriteTruncate     = "w"@@ -142,12 +143,12 @@  ||| Return the size of a File ||| Returns an error if the File is not an ordinary file (e.g. a directory)-||| Also note that this currently returns an Int, which may overflow if the +||| Also note that this currently returns an Int, which may overflow if the ||| file is very big export fileSize : File -> IO (Either FileError Int) fileSize (FHandle h) = do s <- do_getFileSize h-                          if (s < 0) +                          if (s < 0)                              then do err <- getFileError                                      pure (Left err)                              else pure (Right s)@@ -187,21 +188,16 @@ pclose : File -> IO () pclose (FHandle h) = foreign FFI_C "pclose" (Ptr -> IO ()) h --- mkForeign (FFun "idris_readStr" [FPtr, FPtr] (FAny String))---                        prim__vm h -export-fread : File -> IO (Either FileError String)-fread (FHandle h) = do str <- do_fread h-                       if !(ferror (FHandle h))-                          then pure (Left FileReadError)-                          else pure (Right str)- ||| Read a line from a file ||| @h a file handle which must be open for reading export fGetLine : (h : File) -> IO (Either FileError String)-fGetLine = fread+fGetLine (FHandle h) = do+  str <- do_fread h+  if !(ferror (FHandle h))+    then pure (Left FileReadError)+    else pure (Right str)  ||| Read up to a number of characters from a file ||| @h a file handle which must be open for reading@@ -212,7 +208,6 @@                                   then pure (Left FileReadError)                                   else pure (Right str) -%deprecate fread "Use fGetLine instead"  private do_fwrite : Ptr -> String -> IO (Either FileError ())@@ -225,10 +220,6 @@                                          pure (Left err)                       else pure (Right ()) -export-fwrite : File -> String -> IO (Either FileError ())-fwrite (FHandle h) s = do_fwrite h s- ||| Write a line to a file ||| @h a file handle which must be open for writing ||| @str the line to write to the file@@ -240,8 +231,6 @@ fPutStrLn : File -> String -> IO (Either FileError ()) fPutStrLn (FHandle h) s = do_fwrite h (s ++ "\n") -%deprecate fwrite "Use fPutStr instead"- private do_feof : Ptr -> IO Int do_feof h = foreign FFI_C "fileEOF" (Ptr -> IO Int) h@@ -252,14 +241,7 @@ fEOF (FHandle h) = do eof <- do_feof h                       pure (not (eof == 0)) -||| Check if a file handle has reached the end export-feof : File -> IO Bool-feof = fEOF--%deprecate feof "Use fEOF instead"--export fpoll : File -> IO Bool fpoll (FHandle h) = do p <- foreign FFI_C "fpoll" (Ptr -> IO Int) h                        pure (p > 0)@@ -303,3 +285,46 @@      Right () <- fPutStr h contents        | Left err => pure (Left err)      closeFile h      pure (Right ())+++export+dirOpen : (d : String) -> IO (Either FileError Directory)+dirOpen d+    = do dptr <- foreign FFI_C "idris_dirOpen" (String -> IO Ptr) d+         if !(nullPtr dptr)+            then do err <- getFileError+                    pure (Left err)+            else pure (Right (DHandle dptr))++export+dirClose : Directory -> IO ()+dirClose (DHandle d) = foreign FFI_C "idris_dirClose" (Ptr -> IO ()) d++export+dirError : Directory -> IO Bool+dirError (DHandle d)+    = do err <- foreign FFI_C "idris_dirError" (Ptr -> IO Int) d+         pure (not (err == 0))++export+dirEntry : Directory -> IO (Either FileError String)+dirEntry (DHandle d)+    = do fn <- foreign FFI_C "idris_nextDirEntry" (Ptr -> IO String) d+         if !(dirError (DHandle d))+            then pure (Left FileReadError)+            else pure (Right fn)++export+createDir : String -> IO (Either FileError ())+createDir d+    = do ok <- foreign FFI_C "idris_mkdir" (String -> IO Int) d+         if (ok == 0)+            then pure (Right ())+            else do err <- getFileError+                    pure (Left err)++export+changeDir : String -> IO Bool+changeDir dir +    = do ok <- foreign FFI_C "chdir" (String -> IO Int) dir+         pure (ok == 0)
libs/prelude/Prelude/Functor.idr view
@@ -6,15 +6,15 @@ %access public export  ||| Functors allow a uniform action over a parameterised type.-||| @ f a parameterised type +||| @ f a parameterised type interface Functor (f : Type -> Type) where-    ||| Apply a function across everything of type 'a' in a +    ||| Apply a function across everything of type 'a' in a     ||| parameterised type     ||| @ f the parameterised type     ||| @ func the function to apply     map : (func : a -> b) -> f a -> f b -infixl 4 <$>+infixr 4 <$>  ||| An infix alias for `map`, applying a function across everything of ||| type 'a' in a parameterised type
libs/prelude/Prelude/Interfaces.idr view
@@ -7,12 +7,13 @@ %access public export  -- Numerical Operator Precedence-infixl 5 ==, /=-infixl 6 <, <=, >, >=-infixl 7 <<, >>-infixl 8 +,--infixl 9 *,/+infix 6 ==, /=, <, <=, >, >=+infixl 7 <<, >> -- unused+infixl 8 +, -+infixl 9 *, / +infixl 9 `div`, `mod`+ -- ------------------------------------------------------------- [ Boolean Ops ] intToBool : Int -> Bool intToBool 0 = False@@ -204,22 +205,33 @@     ||| The underlying of unary minus. `-5` desugars to `negate (fromInteger 5)`.     negate : ty -> ty     (-) : ty -> ty -> ty-    ||| Absolute value-    abs : ty -> ty + Neg Integer where     negate x = prim__subBigInt 0 x     (-) = prim__subBigInt-    abs x = if x < 0 then -x else x  Neg Int where     negate x = prim__subInt 0 x     (-) = prim__subInt-    abs x = if x < (prim__truncBigInt_Int 0) then -x else x  Neg Double where     negate x = prim__negFloat x     (-) = prim__subFloat++-- ---------------------------------------------------- [ Absolute Value Interface ]+||| Numbers for which the absolute value is defined should implement `Abs`.+interface Num ty => Abs ty where+    ||| Absolute value+    abs : ty -> ty++Abs Integer where+    abs x = if x < 0 then -x else x++Abs Int where+    abs x = if x < (prim__truncBigInt_Int 0) then -x else x++Abs Double where     abs x = if x < (prim__toFloatBigInt 0) then -x else x  -- ------------------------------------------------------------
libs/prelude/Prelude/List.idr view
@@ -95,8 +95,8 @@ ||| ||| Runs in linear time length : List a -> Nat-length []      = 0-length (x::xs) = 1 + length xs+length []      = Z+length (x::xs) = S (length xs)  -------------------------------------------------------------------------------- -- Indexing into lists@@ -447,7 +447,7 @@ --------------------------------------------------------------------------------  ||| Check if something is a member of a list using a custom comparison.-elemBy : (a -> a -> Bool) -> a -> List a -> Bool+elemBy : %static (a -> a -> Bool) -> a -> List a -> Bool elemBy p e []      = False elemBy p e (x::xs) =   if p e x then@@ -460,7 +460,7 @@ elem = elemBy (==)  ||| Find associated information in a list using a custom comparison.-lookupBy : (a -> a -> Bool) -> a -> List (a, b) -> Maybe b+lookupBy : %static (a -> a -> Bool) -> a -> List (a, b) -> Maybe b lookupBy p e []      = Nothing lookupBy p e (x::xs) =   let (l, r) = x in@@ -475,7 +475,7 @@  ||| Check if any elements of the first list are found in the second, using ||| a custom comparison.-hasAnyBy : (a -> a -> Bool) -> List a -> List a -> Bool+hasAnyBy : %static (a -> a -> Bool) -> List a -> List a -> Bool hasAnyBy p elems []      = False hasAnyBy p elems (x::xs) =   if elemBy p x elems then@@ -527,7 +527,7 @@         findIndices' (S cnt) p xs  ||| Find the index of the first occurrence of an element in a list, using a custom equality test.-elemIndexBy : (a -> a -> Bool) -> a -> List a -> Maybe Nat+elemIndexBy : %static (a -> a -> Bool) -> a -> List a -> Maybe Nat elemIndexBy p e = findIndex $ p e  ||| Find the index of the first occurrence of an element in a list,@@ -536,7 +536,7 @@ elemIndex = elemIndexBy (==)  ||| Find all indices for an element in a list, using a custom equality test.-elemIndicesBy : (a -> a -> Bool) -> a -> List a -> List Nat+elemIndicesBy : %static (a -> a -> Bool) -> a -> List a -> List Nat elemIndicesBy p e = findIndices $ p e  ||| Find all indices for an element in a list, using the default equality test for the type of list elements.@@ -572,7 +572,7 @@  ||| The nubBy function behaves just like nub, except it uses a user-supplied ||| equality predicate instead of the overloaded == function.-nubBy : (a -> a -> Bool) -> List a -> List a+nubBy : %static (a -> a -> Bool) -> List a -> List a nubBy = nubBy' []   where     nubBy' : List a -> (a -> a -> Bool) -> List a -> List a@@ -595,7 +595,7 @@ nub = nubBy (==)  ||| The deleteBy function behaves like delete, but takes a user-supplied equality predicate.-deleteBy : (a -> a -> Bool) -> a -> List a -> List a+deleteBy : %static (a -> a -> Bool) -> a -> List a -> List a deleteBy _  _ []      = [] deleteBy eq x (y::ys) = if x `eq` y then ys else y :: deleteBy eq x ys @@ -622,7 +622,7 @@ (\\) =  foldl (flip delete)  ||| The unionBy function returns the union of two lists by user-supplied equality predicate.-unionBy : (a -> a -> Bool) -> List a -> List a -> List a+unionBy : %static (a -> a -> Bool) -> List a -> List a -> List a unionBy eq xs ys = xs ++ foldl (flip (deleteBy eq)) (nubBy eq ys) xs  ||| Compute the union of two lists according to their `Eq` implementation.@@ -747,7 +747,7 @@ ||| @ eq the equality comparison ||| @ left the potential prefix ||| @ right the list that may have `left` as its prefix-isPrefixOfBy : (eq : a -> a -> Bool) -> (left, right : List a) -> Bool+isPrefixOfBy : %static (eq : a -> a -> Bool) -> (left, right : List a) -> Bool isPrefixOfBy p [] right        = True isPrefixOfBy p left []         = False isPrefixOfBy p (x::xs) (y::ys) =@@ -760,7 +760,7 @@ isPrefixOf : Eq a => List a -> List a -> Bool isPrefixOf = isPrefixOfBy (==) -isSuffixOfBy : (a -> a -> Bool) -> List a -> List a -> Bool+isSuffixOfBy : %static (a -> a -> Bool) -> List a -> List a -> Bool isSuffixOfBy p left right = isPrefixOfBy p (reverse left) (reverse right)  ||| The isSuffixOf function takes two lists and returns True iff the first list is a suffix of the second.@@ -795,7 +795,7 @@ ||| Merge two sorted lists using an arbitrary comparison ||| predicate. Note that the lists must have been sorted using this ||| predicate already.-mergeBy : (a -> a -> Ordering) -> List a -> List a -> List a+mergeBy : %static (a -> a -> Ordering) -> List a -> List a -> List a mergeBy order []      right   = right mergeBy order left    []      = left mergeBy order (x::xs) (y::ys) =@@ -811,7 +811,7 @@ ||| ||| @ cmp how to compare elements ||| @ xs the list to sort-sortBy : (cmp : a -> a -> Ordering) -> (xs : List a) -> List a+sortBy : %static (cmp : a -> a -> Ordering) -> (xs : List a) -> List a sortBy cmp []  = [] sortBy cmp [x] = [x] sortBy cmp xs  = let (x, y) = split xs in
libs/prelude/Prelude/Maybe.idr view
@@ -27,6 +27,12 @@ -- Syntactic tests -------------------------------------------------------------------------------- +Uninhabited (Nothing = Just _) where+  uninhabited Refl impossible++Uninhabited (Just _ = Nothing) where+  uninhabited Refl impossible+ isNothing : Maybe a -> Bool isNothing Nothing  = True isNothing (Just j) = False
libs/prelude/Prelude/Monad.idr view
@@ -1,7 +1,6 @@+||| Monads and Functors module Prelude.Monad --- Monads and Functors- import Builtins import Prelude.Functor import public Prelude.Applicative@@ -11,7 +10,7 @@  %access public export -infixl 5 >>=+infixl 1 >>=  interface Applicative m => Monad (m : Type -> Type) where     ||| Also called `bind`.@@ -28,11 +27,7 @@ ||| define `return` and `pure` differently! return : Monad m => a -> m a return = pure-%deprecate return "Please use `pure`, which is equivalent."--flatten : Monad m => m (m a) -> m a-flatten = join-%deprecate flatten "Please use `join`, which is the standard name."+%fragile return "`return` is provided for those coming from Haskell. Please use `pure` instead, which is equivalent."  ||| Similar to `foldl`, but uses a function wrapping its result in a `Monad`. ||| Consequently, the final value is wrapped in the same `Monad`.
libs/prelude/Prelude/Nat.idr view
@@ -26,6 +26,9 @@ Uninhabited (Z = S n) where   uninhabited Refl impossible +Uninhabited (S n = Z) where+  uninhabited Refl impossible+ -------------------------------------------------------------------------------- -- Syntactic tests --------------------------------------------------------------------------------@@ -38,6 +41,19 @@ isSucc Z     = False isSucc (S n) = True ++||| Proof that `n` is not equal to Z+data IsSucc : (n : Nat) -> Type where+  ItIsSucc : IsSucc (S n)++Uninhabited (IsSucc Z) where+  uninhabited ItIsSucc impossible++||| A decision procedure for `IsSucc`+isItSucc : (n : Nat) -> Dec (IsSucc n)+isItSucc Z = No absurd+isItSucc (S n) = Yes ItIsSucc+ -------------------------------------------------------------------------------- -- Basic arithmetic functions --------------------------------------------------------------------------------@@ -147,7 +163,7 @@ lteSuccRight LTEZero     = LTEZero lteSuccRight (LTESucc x) = LTESucc (lteSuccRight x) -||| n + 1 < m implies n < m +||| n + 1 < m implies n < m lteSuccLeft : LTE (S n) m -> LTE n m lteSuccLeft (LTESucc x) = lteSuccRight x @@ -160,6 +176,11 @@ lteAddRight Z = LTEZero lteAddRight (S k) = LTESucc (lteAddRight k) +||| If a number is not less than another, it is greater than or equal to it+notLTImpliesGTE : Not (LT a b) -> GTE a b+notLTImpliesGTE {b = Z} _ = LTEZero+notLTImpliesGTE {a = Z} {b = S k} notLt = absurd (notLt (LTESucc LTEZero))+notLTImpliesGTE {a = S k} {b = S j} notLt = LTESucc (notLTImpliesGTE (notLt . LTESucc))  ||| Boolean test than one Nat is less than or equal to another total lte : Nat -> Nat -> Bool@@ -223,6 +244,9 @@    fromInteger = fromIntegerNat +Abs Nat where+  abs = id+ MinBound Nat where   minBound = Z @@ -231,7 +255,10 @@   cast = fromInteger  Cast String Nat where-    cast str = cast (the Integer (cast str))+  cast str = cast (the Integer (cast str))++Cast Nat String where+  cast n = cast (the Integer (cast n))  ||| A wrapper for Nat that specifies the semigroup and monoid implementations that use (*) record Multiplicative where
libs/prelude/Prelude/Pairs.idr view
@@ -41,13 +41,5 @@     snd : (x : DPair a P) -> P (fst x)     snd (x ** pf) = pf -    getWitness : DPair a P -> a-    getWitness = fst-    %deprecate DPair.getWitness "This is being deprecated in favour of `fst`."--    getProof : (x : DPair a P) -> P (fst x)-    getProof = snd-    %deprecate DPair.getProof "This is being deprecated in favour of `snd`."-   -- Polymorphic (interface-based) projections have been removed   -- because type-directed name disambiguation works better.
libs/prelude/prelude.ipkg view
@@ -1,17 +1,42 @@ package prelude  opts = "--nobuiltins --total --no-elim-deprecation-warnings --partial-eval"-modules = Builtins, Prelude, IO, -          Prelude.Algebra, Prelude.Basics, Prelude.Bool, Prelude.Cast,-          Prelude.Interfaces, Prelude.Nat, Prelude.List,-          Prelude.Maybe, Prelude.Monad, Prelude.Applicative, Prelude.Either,-          Prelude.Strings, Prelude.Chars, Prelude.Show, Prelude.Functor,-          Prelude.Foldable, Prelude.Traversable, Prelude.Bits, Prelude.Stream,-          Prelude.Uninhabited, Prelude.Pairs, Prelude.Providers,-          Prelude.Interactive, Prelude.File, Prelude.Doubles,-          Prelude.WellFounded,+modules = Builtins -          Language.Reflection, Language.Reflection.Errors, Language.Reflection.Elab,+        , Decidable.Equality -          Decidable.Equality+        , IO++        , Language.Reflection+        , Language.Reflection.Elab+        , Language.Reflection.Errors++        , Prelude++        , Prelude.Algebra+        , Prelude.Applicative+        , Prelude.Basics+        , Prelude.Bits+        , Prelude.Bool+        , Prelude.Cast+        , Prelude.Chars+        , Prelude.Doubles+        , Prelude.Either+        , Prelude.File+        , Prelude.Foldable+        , Prelude.Functor+        , Prelude.Interactive+        , Prelude.Interfaces+        , Prelude.List+        , Prelude.Maybe+        , Prelude.Monad+        , Prelude.Nat+        , Prelude.Pairs+        , Prelude.Providers+        , Prelude.Show+        , Prelude.Stream+        , Prelude.Strings+        , Prelude.Traversable+        , Prelude.Uninhabited+        , Prelude.WellFounded
libs/pruviloj/Pruviloj/Core.idr view
@@ -256,6 +256,25 @@        try (unproduct (Var n1))        try (unproduct (Var n2)) +||| Try to apply the constructors of the goal data type one by one,+||| and apply the first one that works. If one of the constructors work,+||| the explicit arguments to the constructor are created as new holes and+||| the hole names are returned in a list. The parameters of the type and+||| the implicit arguments of the constructor will be solved by unification.+||| Similar to `constructor` in Coq.+construct : Elab (List TTName)+construct = case headName !goalType of+    Nothing =>+      fail [TextPart "Goal is not of a type declared with the data keyword"]+    Just h =>+      choiceMap (\(n, xs, _) => apply (Var n) (map shouldUnify xs) <* solve)+                !(constructors <$> lookupDatatypeExact h)+      <|> fail [TextPart "No constructors apply"]+  where+    shouldUnify : CtorArg -> Bool+    shouldUnify (CtorField (MkFunArg _ _ Explicit _)) = False+    shouldUnify _ = True+ ||| A special-purpose tactic that attempts to solve a goal using ||| `Refl`. This is useful for ensuring that goals in fact are trivial ||| when developing or testing other tactics; otherwise, consider
libs/pruviloj/Pruviloj/Derive/Eliminators.idr view
@@ -130,8 +130,8 @@ data ElimArg = IHArgument TTName | NormalArgument TTName  implementation Show ElimArg where-  show (IHArgument x) = "IHArgument " ++ show x-  show (NormalArgument x) = "NormalArgument " ++ show x+  showPrec d (IHArgument x) = showCon d "IHArgument" $ showArg x+  showPrec d (NormalArgument x) = showCon d "NormalArgument" $ showArg x  getElimClause : TyConInfo -> (elimn : TTName) -> (methCount : Nat) ->                 (TTName, List CtorArg, Raw) -> Nat -> Elab (FunClause Raw)
libs/pruviloj/Pruviloj/Disjoint.idr view
@@ -19,6 +19,34 @@ disjointName l r = NS (SN (MetaN (UN "disjoint") (SN (MetaN l r))))                       ["Disjoint", "Pruviloj"] +||| Compute the type to use for a disjointness lemma.+covering+disjointnessType : (l, r : TTName) -> Elab (TTName, List FunArg, Raw)+disjointnessType l r =+   do (l', DCon _ _, lty) <- lookupTyExact l+        | _ => notConstructor l+      (r', DCon _ _, rty) <- lookupTyExact r+        | _ => notConstructor r+      let fn = disjointName l' r'+      when (l' == r') $+        fail [ NamePart l', TextPart "and"+             , NamePart r', TextPart "are clearly not disjoint!"+             ]+      (argsl, resl) <- stealBindings !(forget lty) noRenames+      (argsr, resr) <- stealBindings !(forget rty) noRenames+      let args = map {b=FunArg}+                    (\(n, b) => MkFunArg n (binderTy b) Implicit NotErased)+                    (argsl ++ argsr)+      let eq : Raw = `((=) {A=~resl}+                          {B=~resr}+                          ~(mkApp (Var l') (map (Var . fst) argsl))+                          ~(mkApp (Var r') (map (Var . fst) argsr)))+      h <- gensym "h"+      pure (fn, args ++ [MkFunArg h eq Explicit NotErased], `(Void))+  where+    notConstructor : TTName -> Elab a+    notConstructor c = fail [NamePart c, TextPart "is not a constructor"]+ ||| Return the name of the disjointness lemma for two constructors, ||| defining it if necessary. |||@@ -27,36 +55,13 @@ covering getDisjointness : (l, r : TTName) -> Elab TTName getDisjointness l r = exists <|> declare-   where exists : Elab TTName         exists = do (yep, _, _) <- lookupTyExact (disjointName l r)                     pure yep--        notConstructor : TTName -> Elab a-        notConstructor c = fail [NamePart c, TextPart "is not a constructor"]-         covering         declare : Elab TTName-        declare = do (l', DCon _ _, lty) <- lookupTyExact l-                       | _ => notConstructor l-                     (r', DCon _ _, rty) <- lookupTyExact r-                       | _ => notConstructor r-                     let fn = disjointName l' r'-                     when (l' == r') $-                       fail [ NamePart l', TextPart "and"-                            , NamePart r', TextPart "are clearly not disjoint!"-                            ]-                     (argsl, resl) <- stealBindings !(forget lty) noRenames-                     (argsr, resr) <- stealBindings !(forget rty) noRenames-                     let args = map {b=FunArg}-                                    (\(n, b) => MkFunArg n (binderTy b) Implicit NotErased)-                                    (argsl ++ argsr)-                     let eq : Raw = `((=) {A=~resl}-                                          {B=~resr}-                                          ~(mkApp (Var l') (map (Var . fst) argsl))-                                          ~(mkApp (Var r') (map (Var . fst) argsr)))-                     h <- gensym "h"-                     declareType $ Declare fn (args ++ [MkFunArg h eq Explicit NotErased]) `(Void)+        declare = do (fn, args, ret) <- disjointnessType l r+                     declareType $ Declare fn args ret                      defineFunction $ DefineFun fn []                      pure fn @@ -83,3 +88,38 @@             skip        ty =>          fail [NamePart `{disjoint}, TextPart "is not applicable to goal", TermPart ty]++||| Solve a goal when there is an hypothesis of the form+||| `(C1 x1 x2 ... xn = C2 x1 x2 ... xn)`+||| for disjoint constructors `C1` and `C2`.+||| Similar to `discriminate` in Coq.+public export covering+discriminate : Elab ()+discriminate =+   do compute+      g <- goalType+      -- for each thing in the context, until we find one that succeeds+      flip choiceMap !getEnv $ \(n, b) =>+        do -- 1) check if it is an equality+           `(((=) {A=~A} {B=~B} ~a ~b)) <- forget (binderTy b)+             | _ => fail [TextPart "Not equality type"]+           -- 2) check if both sides of the equality have heads+           case (headName a, headName b) of+             (Just lHead, Just rHead) =>+               do lemma <- Var <$> getDisjointness lHead rHead+                  -- 3) learn how many arguments the lemma takes+                  (_, x :: xs, _) <- disjointnessType lHead rHead+                    | _ => fail [TextPart "Disjointness type takes no argument"]+                  -- 4) try to apply and focus on the last hole+                  apply `(void {a=~g}) [False]+                  solve+                  -- 5) try to call the disjointness lemma+                  -- We only want to pass the last arg explicitly to the lemma+                  let bools = map (const True) xs ++ [False]+                  (h :: hs) <- apply lemma bools+                    | _ => fail [TextPart "Disjointness lemma produces no holes"]+                  solve+                  -- 6) try to pass the current equality as an argument+                  focus (last (h :: hs))+                  exact (Var n)+             _ => fail [TextPart "Equality sides don't have a name at the head"]
libs/pruviloj/pruviloj.ipkg view
@@ -1,13 +1,19 @@ package pruviloj -opts    = "--nobasepkgs --partial-eval -i ../prelude -i ../base"+opts = "--nobasepkgs --partial-eval -i ../prelude -i ../base"+ modules = Pruviloj+         , Pruviloj.Core+         , Pruviloj.Derive.DecEq         , Pruviloj.Derive.Eliminators+         , Pruviloj.Disjoint         , Pruviloj.Induction         , Pruviloj.Injective+         , Pruviloj.Internals         , Pruviloj.Internals.TyConInfo+         , Pruviloj.Renamers
main/Main.hs view
@@ -2,9 +2,7 @@  import System.Exit (ExitCode(..), exitSuccess, exitWith) -import Control.Monad (unless, when, (>=>))-import Data.Foldable (foldrM)-import Data.Maybe (fromMaybe)+import Control.Monad (unless, when)  import Idris.AbsSyntax import Idris.CmdOptions@@ -14,9 +12,6 @@ import Idris.Options import Idris.Package -import Util.System (setupBundledCC)--import System.Exit (ExitCode(..), exitWith) import Util.System (setupBundledCC)  processShowOptions :: [Opt] -> Idris ()
man/idris.1 view
@@ -1,6 +1,6 @@ .\" Manpage for Idris. .\" Contact <> to correct errors or typos.-.TH man 1 "1 April 2017" "1.0" "Idris man page"+.TH man 1 "7 January 2018" "1.2.0" "Idris man page" .SH NAME idris -\ a general purpose pure functional programming language with dependent types. .SH SYNOPSIS
rts/Makefile view
@@ -2,7 +2,7 @@  OBJS = idris_rts.o idris_heap.o idris_gc.o idris_gmp.o idris_bitstring.o \        idris_opts.o idris_stats.o idris_utf8.o idris_stdfgn.o mini-gmp.o \-       idris_buffer.o getline.o+       idris_buffer.o getline.o idris_net.o HDRS = idris_rts.h idris_heap.h idris_gc.h idris_gmp.h idris_bitstring.h \        idris_opts.h idris_stats.h mini-gmp.h idris_stdfgn.h idris_net.h \        idris_buffer.h idris_utf8.h getline.h@@ -20,10 +20,9 @@ endif  ifeq ($(OS), windows)-	OBJS += windows/idris_net.o windows/win_utils.o+	OBJS += windows/win_utils.o else 	CFLAGS += -fPIC-	OBJS += idris_net.o endif  LIBTARGET = libidris_rts.a@@ -31,7 +30,7 @@ build: $(LIBTARGET) $(DYLIBTARGET)  $(LIBTARGET) : $(OBJS)-	$(AR) r $(LIBTARGET) $(OBJS)+	$(AR) rc $(LIBTARGET) $(OBJS) 	$(RANLIB) $(LIBTARGET)  install :
rts/idris_buffer.c view
@@ -39,6 +39,16 @@     } } +void idris_setBufferInt(void* buffer, int loc, int val) {+    Buffer* b = buffer;+    if (loc >= 0 && loc+3 < b->size) {+        b->data[loc] = val & 0xff;+        b->data[loc+1] = (val >> 8) & 0xff;+        b->data[loc+2] = (val >> 16) & 0xff;+        b->data[loc+3] = (val >> 24) & 0xff;+    }+}+ void idris_setBufferString(void* buffer, int loc, char* str) {     Buffer* b = buffer;     int len = strlen(str);@@ -55,6 +65,38 @@     } else {         return 0;     }+}++int idris_getBufferInt(void* buffer, int loc) {+    Buffer* b = buffer;+    if (loc >= 0 && loc+3 < b->size) {+        return b->data[loc] + +               (b->data[loc+1] << 8) ++               (b->data[loc+2] << 16) + +               (b->data[loc+3] << 24);+    } else {+        return 0;+    }+}++VAL idris_getBufferString(void* buffer, int loc, int len) {+    Buffer* b = buffer;++    Closure* cl = allocate(sizeof(Closure) + // Type) + sizeof(char*) ++                           sizeof(char)*(len+1), 0);+    SETTY(cl, CT_STRING);+    cl->info.str.str = (char*)cl + sizeof(Closure);++    if (loc >= 0 && loc+len <= b->size) {+        memcpy(cl->info.str.str, (b->data)+loc, len);+        cl->info.str.str[len]='\0';+        cl->info.str.len = len;+    } else {+        cl->info.str.str[0] = '\0';+        cl->info.str.len = 0;+    }++    return cl; }  int idris_readBuffer(FILE* h, void* buffer, int loc, int max) {
rts/idris_buffer.h view
@@ -4,12 +4,14 @@ #include <stdlib.h> #include <stdio.h> #include <stdint.h>+#include "idris_rts.h"  void* idris_newBuffer(int bytes);  int idris_getBufferSize(void* buffer);  void idris_setBufferByte(void* buffer, int loc, uint8_t byte);+void idris_setBufferInt(void* buffer, int loc, int byte); void idris_setBufferString(void* buffer, int loc, char* str);  void idris_copyBuffer(void* from, int start, int len,@@ -19,5 +21,7 @@ void idris_writeBuffer(FILE* h, void* buffer, int loc, int len);  uint8_t idris_getBufferByte(void* buffer, int loc);+int idris_getBufferInt(void* buffer, int loc);+VAL idris_getBufferString(void* buffer, int loc, int len);  #endif
rts/idris_gc.c view
@@ -5,7 +5,7 @@ #include <assert.h>  VAL copy(VM* vm, VAL x) {-    int ar;+    int ar, len;     Closure* cl = NULL;     if (x==NULL || ISINT(x)) {         return x;@@ -20,6 +20,11 @@             memcpy(&(cl->info.c.args), &(x->info.c.args), sizeof(VAL)*ar);         }         break;+    case CT_ARRAY:+        len = x->info.arr.length;+	allocArray(cl, vm, len, 1);+        memcpy(&(cl->info.arr.content), &(x->info.arr.content), sizeof(VAL)*len);+        break;     case CT_FLOAT:         cl = MKFLOATc(vm, x->info.f);         break;@@ -50,12 +55,15 @@     case CT_BITS64:         cl = idris_b64CopyForGC(vm, x);         break;+    case CT_REF:+        cl = idris_newRefLock((VAL)(x->info.ptr), 1);+        break;     case CT_FWD:         return x->info.ptr;     case CT_RAWDATA:         {             size_t size = x->info.size + sizeof(Closure);-            cl = allocate(size, 0);+            cl = allocate(size, 1);             memcpy(cl, x, size);         }         break;@@ -73,13 +81,13 @@  void cheney(VM *vm) {     int i;-    int ar;+    int ar, len;     char* scan = aligned_heap_pointer(vm->heap.heap);      while(scan < vm->heap.next) {        size_t inc = *((size_t*)scan);        VAL heap_item = (VAL)(scan+sizeof(size_t));-       // If it's a CT_CON or CT_STROFFSET, copy its arguments+       // If it's a CT_CON, CT_REF or CT_STROFFSET, copy its arguments        switch(GETTY(heap_item)) {        case CT_CON:            ar = ARITY(heap_item);@@ -87,6 +95,16 @@                VAL newptr = copy(vm, heap_item->info.c.args[i]);                heap_item->info.c.args[i] = newptr;            }+           break;+       case CT_ARRAY:+           len = heap_item->info.arr.length;+           for(i = 0; i < len; ++i) {+               VAL newptr = copy(vm, heap_item->info.arr.content[i]);+               heap_item->info.arr.content[i] = newptr;+           }+           break;+       case CT_REF:+           heap_item->info.ptr = copy(vm, (VAL)(heap_item->info.ptr));            break;        case CT_STROFFSET:            heap_item->info.str_offset->str
rts/idris_gmp.c view
@@ -195,7 +195,7 @@     VAL cl = allocate(sizeof(Closure) + sizeof(mpz_t), 0);     idris_doneAlloc();     bigint = (mpz_t*)(((char*)cl) + sizeof(Closure));-    mpz_mod(*bigint, GETMPZ(GETBIG(vm,x)), GETMPZ(GETBIG(vm,y)));+    mpz_tdiv_r(*bigint, GETMPZ(GETBIG(vm,x)), GETMPZ(GETBIG(vm,y)));     SETTY(cl, CT_BIGINT);     cl -> info.ptr = (void*)bigint;     return cl;@@ -344,7 +344,7 @@     if (ISINT(x) && ISINT(y)) {         return INTOP(<<, x, y);     } else {-        return bigShiftLeft(vm, GETBIG(vm, x), GETBIG(vm, y));+        return bigShiftLeft(vm, GETBIG(vm, x), y);     } } @@ -352,7 +352,7 @@     if (ISINT(x) && ISINT(y)) {         return INTOP(>>, x, y);     } else {-        return bigAShiftRight(vm, GETBIG(vm, x), GETBIG(vm, y));+        return bigAShiftRight(vm, GETBIG(vm, x), y);     } } @@ -360,7 +360,7 @@     if (ISINT(x) && ISINT(y)) {         return INTOP(>>, x, y);     } else {-        return bigLShiftRight(vm, GETBIG(vm, x), GETBIG(vm, y));+        return bigLShiftRight(vm, GETBIG(vm, x), y);     } } @@ -501,8 +501,8 @@         return mpz_get_ui(bi);     }     int64_t out = mpz_get_ui(bi);-    if (bi->_mp_size > 1 ) {-        out |= (uint64_t)bi->_mp_d[1] << 32;+    if (mpz_size(bi) > 1) {+        out |= mpz_getlimbn(bi, 1) << 32;     }     return out; }
rts/idris_gmp.h view
@@ -43,7 +43,8 @@ VAL idris_bigAnd(VM* vm, VAL x, VAL y); VAL idris_bigOr(VM* vm, VAL x, VAL y); VAL idris_bigShiftLeft(VM* vm, VAL x, VAL y);-VAL idris_bigShiftRight(VM* vm, VAL x, VAL y);+VAL idris_bigAShiftRight(VM* vm, VAL x, VAL y);+VAL idris_bigLShiftRight(VM* vm, VAL x, VAL y);  uint64_t idris_truncBigB64(const mpz_t bi); 
rts/idris_net.c view
@@ -3,16 +3,35 @@ // MIT Licensed. Have fun! #include "idris_net.h" #include <errno.h>-#include <netdb.h> #include <stdbool.h> #include <stdlib.h> #include <stdio.h> #include <string.h>-#include <sys/types.h>-#include <sys/socket.h>++#ifndef WIN32 #include <netinet/in.h> #include <arpa/inet.h>+#else+static int socket_inited = 0;+static WSADATA wsa_data; +static void clean_sockets(void) {+    WSACleanup();+}++static int check_init(void) {+    if (!socket_inited) {+        int result = WSAStartup(MAKEWORD(2, 2), &wsa_data);+        if (result == NO_ERROR) {+            socket_inited = 1;+            atexit(clean_sockets);+        }+    }+    return socket_inited;+}+#endif++ void buf_htonl(void* buf, int len) {     int* buf_i = (int*) buf;     int i;@@ -37,6 +56,16 @@     free(ptr); } ++int idrnet_socket(int domain, int type, int protocol) {+#ifdef WIN32+    if (!check_init()) {+        return -1;+    }+#endif+    return socket(domain, type, protocol);+}+ // We call this from quite a few functions. Given a textual host and an int port, // populates a struct addrinfo. int idrnet_getaddrinfo(struct addrinfo** address_res, char* host, int port,@@ -65,7 +94,7 @@ int idrnet_bind(int sockfd, int family, int socket_type, char* host, int port) {     struct addrinfo* address_res;     int addr_res = idrnet_getaddrinfo(&address_res, host, port, family, socket_type);-    if (addr_res == -1) {+    if (addr_res != 0) {         //printf("Lib err: bind getaddrinfo\n");         return -1;     }@@ -82,7 +111,7 @@ int idrnet_connect(int sockfd, int family, int socket_type, char* host, int port) {     struct addrinfo* remote_host;     int addr_res = idrnet_getaddrinfo(&remote_host, host, port, family, socket_type);-    if (addr_res == -1) {+    if (addr_res != 0) {         return -1;     } @@ -121,7 +150,7 @@  int idrnet_accept(int sockfd, void* sockaddr) {     struct sockaddr* addr = (struct sockaddr*) sockaddr;-    socklen_t addr_size = 0;+    socklen_t addr_size = sizeof(struct sockaddr_storage);     return accept(sockfd, addr, &addr_size); } @@ -189,7 +218,7 @@      struct addrinfo* remote_host;     int addr_res = idrnet_getaddrinfo(&remote_host, host, port, family, SOCK_DGRAM);-    if (addr_res == -1) {+    if (addr_res != 0) {         return -1;     } @@ -203,7 +232,7 @@      struct addrinfo* remote_host;     int addr_res = idrnet_getaddrinfo(&remote_host, host, port, family, SOCK_DGRAM);-    if (addr_res == -1) {+    if (addr_res != 0) {         //printf("lib err: sendto getaddrinfo \n");         return -1;     }
rts/idris_net.h view
@@ -1,6 +1,17 @@ #ifndef IDRISNET_H #define IDRISNET_H +// Includes used by the idris-file.+#ifdef WIN32+#include <winsock2.h>+#include <Ws2tcpip.h>+#else+#include <netdb.h>+#include <unistd.h>+#include <sys/types.h>+#include <sys/socket.h>+#endif+ struct sockaddr_storage; struct addrinfo; @@ -23,6 +34,8 @@  // Gets value of errno int idrnet_errno(); ++int idrnet_socket(int domain, int type, int protocol);  // Bind int idrnet_bind(int sockfd, int family, int socket_type, char* host, int port);
rts/idris_rts.c view
@@ -714,7 +714,7 @@     int xval = GETINT(x);     int xlen = GETSTRLEN(xs); -    if ((xval & 0x80) == 0) { // ASCII char+    if (xval < 0x80) { // ASCII char         Closure* cl = allocate(sizeof(Closure) +                                xlen + 2, 0);         SETTY(cl, CT_STRING);@@ -776,6 +776,44 @@     return cl; } +VAL idris_newRefLock(VAL x, int outerlock) {+    Closure* cl = allocate(sizeof(Closure), outerlock);+    SETTY(cl, CT_REF);+    cl->info.ptr = (void*)x;+    return cl;+}++VAL idris_newRef(VAL x) {+    return idris_newRefLock(x, 0);+}++void idris_writeRef(VAL ref, VAL x) {+    ref->info.ptr = (void*)x;+    SETTY(ref, CT_REF);+}++VAL idris_readRef(VAL ref) {+    return (VAL)(ref->info.ptr);+}++VAL idris_newArray(VM* vm, int size, VAL def) {+    Closure* cl;+    int i;+    allocArray(cl, vm, size, 0);+    for(i=0; i<size; ++i) {+	cl->info.arr.content[i] = def;+    }+    return cl;+}++void idris_arraySet(VAL arr, int index, VAL newval) {+     arr->info.arr.content[index] = newval;+}++VAL idris_arrayGet(VAL arr, int index) {+     return arr->info.arr.content[index];+}+ VAL idris_systemInfo(VM* vm, VAL index) {     int i = GETINT(index);     switch(i) {@@ -857,7 +895,7 @@ // VM is assumed to be a different vm from the one x lives on  VAL doCopyTo(VM* vm, VAL x) {-    int i, ar;+    int i, ar, len;     VAL* argptr;     Closure* cl;     if (x==NULL || ISINT(x)) {@@ -877,6 +915,16 @@                 argptr++;             }         }+        break;+    case CT_ARRAY:+        len = x->info.arr.length;+	allocArray(cl, vm, len, 1);++	argptr = (VAL*)(cl->info.arr.content);+	for(i = 0; i < len; ++i) {+	    *argptr = doCopyTo(vm, *((VAL*)(x->info.arr.content)+i)); // recursive version+	    argptr++;+	}         break;     case CT_FLOAT:         cl = MKFLOATc(vm, x->info.f);
rts/idris_rts.h view
@@ -25,19 +25,29 @@  // Closures typedef enum {-    CT_CON, CT_INT, CT_BIGINT, CT_FLOAT, CT_STRING, CT_STROFFSET,-    CT_BITS8, CT_BITS16, CT_BITS32, CT_BITS64, CT_UNIT, CT_PTR, CT_FWD,-    CT_MANAGEDPTR, CT_RAWDATA, CT_CDATA+    CT_CON, CT_ARRAY, CT_INT, CT_BIGINT, CT_FLOAT, CT_STRING, CT_STROFFSET,+    CT_BITS8, CT_BITS16, CT_BITS32, CT_BITS64, CT_UNIT, CT_PTR, CT_REF,+    CT_FWD, CT_MANAGEDPTR, CT_RAWDATA, CT_CDATA } ClosureType;  typedef struct Closure *VAL; +// A constructor, consisting of a tag, an arity (16 bits each of the+// tag_arity field) and arguments typedef struct {     uint32_t tag_arity;     VAL args[]; } con; +// An array; similar to a constructor but with a length, and contents+// initialised to NULL (high level Idris programs are responsible for+// initialising them properly) typedef struct {+    uint32_t length;+    VAL content[];+} array;++typedef struct {     VAL str;     size_t offset; } StrOffset;@@ -62,6 +72,7 @@     uint32_t ty;     union {         con c;+        array arr;         int i;         double f;         String str;@@ -183,9 +194,6 @@ #define TOP(x) (*(vm->valstack_top + (x))) #define REG1 (vm->reg1) -// align pointer-#define ALIGN(__p, __alignment) ((__p + __alignment - 1) & ~(__alignment - 1))- // Retrieving values #define GETSTR(x) (ISSTR(x) ? (((VAL)(x))->info.str.str) : GETSTROFF(x)) #define GETSTRLEN(x) (ISSTR(x) ? (((VAL)(x))->info.str.len) : GETSTROFFLEN(x))@@ -206,14 +214,9 @@ #define CTAG(x) (((x)->info.c.tag_arity) >> 8) #define CARITY(x) ((x)->info.c.tag_arity & 0x000000ff) -// Use top 16 bits for saying which heap value is in-// Bottom 16 bits for closure type -#define GETTY(x) ((x)->ty & 0x0000ffff)-#define SETTY(x,t) (x)->ty = (((x)->ty & 0xffff0000) | (t))--#define GETHEAP(x) ((x)->ty >> 16)-#define SETHEAP(x,y) (x)->ty = (((x)->ty & 0x0000ffff) | ((y) << 16))+#define GETTY(x) ((x)->ty)+#define SETTY(x,t) ((x)->ty = t)  // Integers, floats and operators @@ -317,6 +320,11 @@  #define NULL_CON(x) nullary_cons[x] +#define allocArray(cl, vm, len, o) \+  cl = allocate(sizeof(Closure) + sizeof(VAL)*len, o); \+  SETTY(cl, CT_ARRAY); \+  cl->info.arr.length = len;+ int idris_errno(void); char* idris_showerror(int err); @@ -405,6 +413,17 @@ VAL idris_strIndex(VM* vm, VAL str, VAL i); VAL idris_strRev(VM* vm, VAL str); VAL idris_substr(VM* vm, VAL offset, VAL length, VAL str);++// Support for IORefs+VAL idris_newRefLock(VAL x, int outerlock);+VAL idris_newRef(VAL x);+void idris_writeRef(VAL ref, VAL x);+VAL idris_readRef(VAL ref);++// Support for IOArrays+VAL idris_newArray(VM* vm, int size, VAL def);+void idris_arraySet(VAL arr, int index, VAL newval);+VAL idris_arrayGet(VAL arr, int index);  // system infox // used indices:
rts/idris_stdfgn.c view
@@ -8,6 +8,7 @@ #include <sys/stat.h> #include <stdio.h> #include <time.h>+#include <dirent.h>  #if defined(WIN32) || defined(__WIN32) || defined(__WIN32__) int win_fpoll(void* h);@@ -59,6 +60,54 @@     } } +typedef struct {+    DIR* dirptr;+    int error;+} DirInfo;++void* idris_dirOpen(char* dname) {+    DIR *d = opendir(dname);+    if (d == NULL) {+        return NULL;+    } else {+        DirInfo* di = malloc(sizeof(DirInfo));+        di->dirptr = d;++        return (void*)di;+    }+}++void idris_dirClose(void* h) {+    DirInfo* di = (DirInfo*)h;+    +    closedir(di->dirptr);+    free(di);+}++char* idris_nextDirEntry(void* h) {+    DirInfo* di = (DirInfo*)h;+    struct dirent* de = readdir(di->dirptr);++    if (de == NULL) {+        di->error = -1;+        return NULL;+    } else {+        return de->d_name;+    }+}++int idris_mkdir(char* dname) {+#if defined(WIN32) || defined(__WIN32) || defined(__WIN32__)+    return mkdir(dname);+#else+    return mkdir(dname, S_IRWXU | S_IRGRP | S_IROTH);+#endif+}++int idris_dirError(void *dptr) {+    return ((DirInfo*)dptr)->error;+}+ int idris_writeStr(void* h, char* str) {     FILE* f = (FILE*)h;     if (fputs(str, f) >= 0) {@@ -101,10 +150,6 @@  int isNull(void* ptr) {     return ptr==NULL;-}--int idris_eqPtr(void* x, void* y) {-    return x==y; }  void* idris_stdin() {
rts/idris_stdfgn.h view
@@ -15,6 +15,17 @@ // Returns a negative number if not a file (e.g. directory or device) int fileSize(void* h); +void* idris_dirOpen(char* dname);+void idris_dirClose(void* h);+char* idris_nextDirEntry(void* h);++// Create a directory; return 0 on success or -1 on failure+int idris_mkdir(char* dname);++// Return 0 if ok, or -1 if there was an error with the given directory+// (like ferror)+int idris_dirError(void *dptr);+ // return 0 on success int idris_writeStr(void*h, char* str); // construct a file error structure (see Prelude.File) from errno@@ -29,8 +40,6 @@ void* do_popen(const char* cmd, const char* mode); int fpoll(void* h); --int idris_eqPtr(void* x, void* y); int isNull(void* ptr); void* idris_stdin(); 
rts/idris_utf8.c view
@@ -119,7 +119,7 @@     char* str;     int bytes = 0, top = 0; -    if ((x & 0x80) == 0) {+    if (x < 0x80) {         str = malloc(2);         str[0] = (char)x;         str[1] = '\0';
− rts/windows/idris_net.c
@@ -1,200 +0,0 @@-// C-Side of the Idris network library-// (C) Simon Fowler, 2014-// MIT Licensed. Have fun!-#include "../idris_net.h"--#include <errno.h>-#include <stdbool.h>-#include <stdlib.h>-#include <stdio.h>-#include <string.h>-#include <Winsock2.h>-#include <Ws2tcpip.h>---// inet_ntop isn't defined in the old mingw delivered with GHC,-// so put the prototype here, cribbed from a newer version of it-WINSOCK_API_LINKAGE LPCSTR WSAAPI InetNtopA(INT Family, PVOID pAddr,-        LPSTR pStringBuf, size_t StringBufSize);--static int socket_inited = 0;-static WSADATA wsa_data;--void* idrnet_malloc(int size) {-    return malloc(size);-}--void idrnet_free(void* ptr) {-    free(ptr);-}--static void clean_sockets(void) {-    WSACleanup();-}--static int check_init(void)-{-    if (!socket_inited) {-        int result = WSAStartup(MAKEWORD(2, 2), &wsa_data);-        if (result == NO_ERROR) {-            socket_inited = 1;-            atexit(clean_sockets);-        }-    }-    return socket_inited;-}--int idrnet_bind(int sockfd, int family, int socket_type, char* host, int port) {-    struct addrinfo hints;-    struct addrinfo* address_res;-    // Convert port into string-    char str_port[8];-    sprintf(str_port, "%d", port);--    if (!check_init()) {-        return -1;-    }-    // Set up hints structure-    memset(&hints, 0, sizeof(hints)); // zero out hints-    hints.ai_family = family;-    hints.ai_socktype = socket_type;--    // If the length of the hostname is 0 (i.e, it was set to Nothing in Idris)-    // then we want to instruct the C library to fill in the IP automatically-    if (strlen(host) == 0) {-        hints.ai_flags = AI_PASSIVE; // fill in IP automatically-    }--    int addr_res = getaddrinfo(host, str_port, &hints, &address_res);-    if (addr_res == -1) {-        return -1;-    }--    int bind_res = bind(sockfd, address_res->ai_addr, address_res->ai_addrlen);-    if (bind_res == -1) {-        return -1;-    }--    return 0;-}--int idrnet_connect(int sockfd, int family, int socket_type, char* host, int port) {-    char str_port[8];-    sprintf(str_port, "%d", port);-    struct addrinfo hints;-    struct addrinfo* remote_host;--    if (!check_init()) {-        return -1;-    }-    // Set up hints structure for getaddrinfo-    memset(&hints, 0, sizeof(hints));-    hints.ai_family = family;-    hints.ai_socktype = socket_type;--    // Get info about the remote host (DNS lookup etc)-    int addr_res = getaddrinfo(host, str_port, &hints, &remote_host);-    if (addr_res == -1) {-        return -1;-    }--    int connect_res = connect(sockfd, remote_host->ai_addr, remote_host->ai_addrlen);-    if (connect_res == -1) {-        return -1;-    }--    return 0;-}---int idrnet_sockaddr_family(void* sockaddr) {-    struct sockaddr* addr = (struct sockaddr*) sockaddr;-    return (int) addr->sa_family;-}--char* idrnet_sockaddr_ipv4(void* sockaddr) {-    struct sockaddr_in* addr = (struct sockaddr_in*) sockaddr;-    char* ip_addr = (char*) malloc(sizeof(char) * INET_ADDRSTRLEN);-    InetNtopA(AF_INET, &(addr->sin_addr), ip_addr, INET_ADDRSTRLEN);-    return ip_addr;-}--void* idrnet_create_sockaddr() {-    return malloc(sizeof(struct sockaddr_storage));-}---int idrnet_accept(int sockfd, void* sockaddr) {-    struct sockaddr* addr = (struct sockaddr*) sockaddr;-    socklen_t addr_size = 0;-    if (!check_init()) {-        return -1;-    }-    return accept(sockfd, addr, &addr_size);-}--int idrnet_send(int sockfd, char* data) {-    int len = strlen(data); // For now.-    if (!check_init()) {-        return -1;-    }-    return send(sockfd, (void*) data, len, 0);-}--int idrnet_send_buf(int sockfd, void* data, int len) {-    if (!check_init()) {-        return -1;-    }-    return send(sockfd, data, len, 0);-}--void* idrnet_recv(int sockfd, int len) {-    if (!check_init()) {-        return NULL;-    }-    idrnet_recv_result* res_struct =-        (idrnet_recv_result*) malloc(sizeof(idrnet_recv_result));--    char* buf = malloc(len + 1);-    int recv_res = recv(sockfd, buf, len, 0);-    res_struct->result = recv_res;--    if (recv_res > 0) { // Data was received-        buf[recv_res + 1] = 0x00; // Null-term, so Idris can interpret it-    }-    res_struct->payload = (void*) buf;-    return (void*) res_struct;-}--int idrnet_recv_buf(int sockfd, void* buf, int len) {-    if (!check_init()) {-        return -1;-    }-    return recv(sockfd, buf, len, 0);-}--int idrnet_get_recv_res(void* res_struct) {-    return (((idrnet_recv_result*) res_struct)->result);-}--char* idrnet_get_recv_payload(void* res_struct) {-    return (((idrnet_recv_result*) res_struct)->payload);-}--void idrnet_free_recv_struct(void* res_struct) {-    idrnet_recv_result* i_res_struct =-        (idrnet_recv_result*) res_struct;-    if (i_res_struct->payload != NULL) {-        free(i_res_struct->payload);-    }-    free(res_struct);-}--int idrnet_errno() {-    return errno;-}--int idrnet_geteagain() {-    return EAGAIN;-}-
samples/ST/Login.idr view
@@ -41,7 +41,7 @@    disconnect store = delete store -  readSecret store = readSecret store+  readSecret store = read store    login store = do putStr "Enter password: "                    p <- getStr
samples/tutorial/BTreeMod.idr view
@@ -1,20 +1,20 @@ module btree -abstract data BTree a = Leaf-                      | Node (BTree a) a (BTree a)+export data BTree a = Leaf+                    | Node (BTree a) a (BTree a) -abstract+export insert : Ord a => a -> BTree a -> BTree a insert x Leaf = Node Leaf x Leaf insert x (Node l v r) = if (x < v) then (Node (insert x l) v r)                                    else (Node l v (insert x r)) -abstract+export toList : BTree a -> List a toList Leaf = [] toList (Node l v r) = btree.toList l ++ (v :: btree.toList r) -abstract+export toTree : Ord a => List a -> BTree a toTree [] = Leaf toTree (x :: xs) = insert x (toTree xs)
− src/IRTS/BCImp.hs
@@ -1,23 +0,0 @@-{-|-Module      : IRTS.BCImp-Description : Bytecode for a register/variable based VM (e.g. for generating code in an imperative language where we let the language deal with GC)-Copyright   :-License     : BSD3-Maintainer  : The Idris Community.--}-module IRTS.BCImp where--import Idris.Core.TT-import IRTS.Lang-import IRTS.Simplified--data Reg = RVal | L Int--data BC = NOP--toBC :: (Name, SDecl) -> (Name, [BC])-toBC (n, SFun n' args locs exp)-   = (n, bc RVal exp)--bc :: Reg -> SExp -> [BC]-bc = undefined
src/IRTS/Bytecode.hs view
@@ -2,7 +2,7 @@ Module      : IRTS.Bytecode Description : Bytecode for a stack based VM (e.g. for generating C code with an accurate hand written GC) -Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. @@ -23,7 +23,6 @@  import Idris.Core.TT import IRTS.Defunctionalise-import IRTS.Lang import IRTS.Simplified  import Data.Maybe
src/IRTS/CodegenC.hs view
@@ -1,7 +1,7 @@ {-| Module      : IRTS.CodegenC Description : The default code generator for Idris, generating C code.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -9,12 +9,10 @@  module IRTS.CodegenC (codegenC) where -import Idris.AbsSyntax import Idris.Core.TT import IRTS.Bytecode import IRTS.CodegenCommon import IRTS.Defunctionalise-import IRTS.Lang import IRTS.Simplified import IRTS.System @@ -24,9 +22,7 @@ import Data.Bits import Data.Char import Data.List (intercalate, nubBy)-import Debug.Trace import Numeric-import System.Directory import System.Exit import System.FilePath ((<.>), (</>)) import System.IO@@ -84,7 +80,7 @@              incFlags <- getIncFlags              envFlags <- getEnvFlags              let stackFlag = if isWindows then ["-Wl,--stack,16777216"] else []-             let args = [gccDbg dbg] +++             let args = gccDbg dbg ++                         gccFlags iface ++                         -- # Any flags defined here which alter the RTS API must also be added to config.mk                         ["-DHAS_PTHREAD", "-DIDRIS_ENABLE_STATS",@@ -116,9 +112,12 @@ gccFlags i = if i then ["-fwrapv"]                   else ["-fwrapv", "-fno-strict-overflow"] -gccDbg DEBUG = "-g"-gccDbg TRACE = "-O2"-gccDbg _ = "-O2"+gccDbg DEBUG = ["-g"]+-- clang optimises sibling calls in O1, but gcc doesn't+-- on the other hand, O1 compiles significantly faster in clang without+-- any noticeable performance hit.+gccDbg TRACE = ["-O1", "-foptimize-sibling-calls"]+gccDbg _ = ["-O1", "-foptimize-sibling-calls"]  cname :: Name -> String cname n = "_idris_" ++ concatMap cchar (showCG n)@@ -183,8 +182,10 @@     = indent i ++ creg l ++ " = " ++ mkConst c ++ ";\n"   where     mkConst (I i) = "MKINT(" ++ show i ++ ")"-    mkConst (BI i) | i < (2^30) = "MKINT(" ++ show i ++ ")"-                   | otherwise = "MKBIGC(vm,\"" ++ show i ++ "\")"+    mkConst (BI i) = let maxInt = 2^30+                     in if i >= -maxInt && i < maxInt+                        then "MKINT(" ++ show i ++ ")"+                        else "MKBIGC(vm,\"" ++ show i ++ "\")"     mkConst (Fl f) = "MKFLOAT(vm, " ++ (map toUpper $ show f) ++ ")"     mkConst (Ch c) = "MKINT(" ++ show (fromEnum c) ++ ")"     mkConst (Str s) = "MKSTR(vm, " ++ showCStr s ++ ")"@@ -205,11 +206,7 @@     = indent i ++ alloc loc tag ++       indent i ++ setArgs 0 args ++ "\n" ++       indent i ++ creg l ++ " = " ++ creg Tmp ++ ";\n"----         "MKCON(vm, " ++ creg l ++ ", " ++ show tag ++ ", " ++---         show (length args) ++ concatMap showArg args ++ ");\n"-  where showArg r = ", " ++ creg r-        setArgs i [] = ""+  where setArgs i [] = ""         setArgs i (x : xs) = "SETARG(" ++ creg Tmp ++ ", " ++ show i ++ ", " ++ creg x ++                              "); " ++ setArgs (i + 1) xs         alloc Nothing tag@@ -223,8 +220,14 @@                                       ", " ++ show a ++ ");\n" bcc i (PROJECTINTO r t idx)     = indent i ++ creg r ++ " = GETARG(" ++ creg t ++ ", " ++ show idx ++ ");\n"+bcc i (CASE True r [(_, alt)] Nothing)+    = indent i ++ showCode i alt+  where+    showCode :: Int -> [BC] -> String+    showCode i bc = "{\n" ++ concatMap (bcc (i + 1)) bc +++                    indent i ++ "}\n" bcc i (CASE True r code def)-    | length code < 4 = showCase i def code+    | length code < 6 && length code > 1 = showCase i def code   where     showCode :: Int -> [BC] -> String     showCode i bc = "{\n" ++ concatMap (bcc (i + 1)) bc ++@@ -305,13 +308,6 @@     iCase v (B64 w, bc) =         indent i ++ "if (GETBITS64(" ++ v ++ ") == " ++ show (fromEnum w) ++ ") {\n"            ++ concatMap (bcc (i+1)) bc ++ indent i ++ "} else\n"-    showCase i (t, bc) = indent i ++ "case " ++ show t ++ ":\n"-                         ++ concatMap (bcc (i+1)) bc ++-                            indent (i + 1) ++ "break;\n"-    showDef i Nothing = ""-    showDef i (Just c) = indent i ++ "default:\n"-                         ++ concatMap (bcc (i+1)) c ++-                            indent (i + 1) ++ "break;\n"     showDefS i Nothing = ""     showDefS i (Just c) = concatMap (bcc (i+1)) c @@ -327,6 +323,9 @@ bcc i (BASETOP n) = indent i ++ "BASETOP(" ++ show n ++ ");\n" bcc i STOREOLD = indent i ++ "STOREOLD;\n" bcc i (OP l fn args) = indent i ++ doOp (creg l ++ " = ") fn args ++ ";\n"+bcc i (FOREIGNCALL l rty (FStr ('#':name)) [])+      = indent i +++        c_irts (toFType rty) (creg l ++ " = ") name ++ ";\n" bcc i (FOREIGNCALL l rty (FStr fn@('&':name)) [])       = indent i ++         c_irts (toFType rty) (creg l ++ " = ") fn ++ ";\n"@@ -589,6 +588,7 @@ doOp v LFFloor [x] = v ++ flUnOp "floor" (creg x) doOp v LFCeil [x] = v ++ flUnOp "ceil" (creg x) doOp v LFNegate [x] = v ++ "MKFLOAT(vm, -GETFLOAT(" ++ (creg x) ++ "))"+doOp v LFATan2 [y, x] = v ++ "MKFLOAT(vm, atan2(GETFLOAT(" ++ creg y ++ "), GETFLOAT(" ++ creg x ++ ")))"  -- String functions which don't need to know we're UTF8 doOp v LStrConcat [l,r] = v ++ "idris_concat(vm, " ++ creg l ++ ", " ++ creg r ++ ")"@@ -703,29 +703,26 @@          argNames = zipWith (++) (repeat "arg") (map show [0..]) -mkBody n as t = indent 1 ++ "INITFRAME;\n" ++-                indent 1 ++ "RESERVE(" ++ show (max (length as) 3) ++ ");\n" ++-                push 0 as ++ call n ++ retval t-  where push i [] = ""-        push i ((n, t) : ts) = indent 1 ++ c_irts (toFType t)-                                      ("TOP(" ++ show i ++ ") = ") n-                                   ++ ";\n" ++ push (i + 1) ts--        call _ = indent 1 ++ "STOREOLD;\n" ++-                 indent 1 ++ "BASETOP(0);\n" ++-                 indent 1 ++ "ADDTOP(" ++ show (length as) ++ ");\n" ++-                 indent 1 ++ "CALL(" ++ cname n ++ ");\n"+mkBody n as_in t+     = indent 1 ++ "INITFRAME;\n" +++       indent 1 ++ "RESERVE(" ++ show (max (length as) 3) ++ ");\n" +++       push 0 as ++ call n ++ retval t+  where+    as = case t of+              FIO t -> as_in ++ [("NULL", FUnknown)] -- add world token+              _ -> as_in+    push i [] = ""+    push i ((n, t) : ts) = indent 1 ++ c_irts (toFType t)+                                  ("TOP(" ++ show i ++ ") = ") n+                               ++ ";\n" ++ push (i + 1) ts -        retval (FIO t)-           = indent 1 ++ "TOP(0) = NULL;\n" ++-             indent 1 ++ "TOP(1) = NULL;\n" ++-             indent 1 ++ "TOP(2) = RVAL;\n" ++-             indent 1 ++ "STOREOLD;\n" +++    call _ = indent 1 ++ "STOREOLD;\n" ++              indent 1 ++ "BASETOP(0);\n" ++-             indent 1 ++ "ADDTOP(3);\n" ++-             indent 1 ++ "CALL(" ++ cname (sUN "call__IO") ++ ");\n" ++-             retval t-        retval t = indent 1 ++ "return " ++ irts_c (toFType t) "RVAL" ++ ";\n"+             indent 1 ++ "ADDTOP(" ++ show (length as) ++ ");\n" +++             indent 1 ++ "CALL(" ++ cname n ++ ");\n"++    retval (FIO t) = retval t+    retval t = indent 1 ++ "return " ++ irts_c (toFType t) "RVAL" ++ ";\n"  ctype (FCon c)   | c == sUN "C_Str" = "char*"
src/IRTS/CodegenCommon.hs view
@@ -2,7 +2,7 @@ {-| Module      : IRTS.CodegenCommon Description : Common data structures required for all code generators.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}
src/IRTS/CodegenJavaScript.hs view
@@ -1,7 +1,7 @@ {-| Module      : IRTS.CodegenJavaScript Description : The JavaScript code generator.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -55,15 +55,24 @@  codegenNode :: CodeGenerator codegenNode ci =-  do-    codegenJs (CGConf { header = "#!/usr/bin/env node\n"+  if interfaces ci then+    codegenJs (CGConf { header = ""                       , footer = ""                       , jsbnPath = "jsbn/jsbn-browser.js"                       , extraRunTime = "Runtime-node.js"                       }               )               ci-    setPermissions (outputFile ci) (emptyPermissions { readable   = True-                                                     , executable = True-                                                     , writable   = True-                                                     })+    else+      do+        codegenJs (CGConf { header = "#!/usr/bin/env node\n"+                          , footer = ""+                          , jsbnPath = "jsbn/jsbn-browser.js"+                          , extraRunTime = "Runtime-node.js"+                          }+                  )+                  ci+        setPermissions (outputFile ci) (emptyPermissions { readable   = True+                                                         , executable = True+                                                         , writable   = True+                                                         })
src/IRTS/Compiler.hs view
@@ -1,7 +1,7 @@ {-| Module      : IRTS.Compiler Description : Coordinates the compilation process.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -10,7 +10,6 @@ module IRTS.Compiler(compile, generate) where  import Idris.AbsSyntax-import Idris.AbsSyntaxTree import Idris.ASTUtils import Idris.Core.CaseTree import Idris.Core.Evaluate@@ -21,33 +20,24 @@ import Idris.Output import IRTS.CodegenC import IRTS.CodegenCommon-import IRTS.CodegenJavaScript import IRTS.Defunctionalise import IRTS.DumpBC import IRTS.Exports import IRTS.Inliner-import IRTS.Lang import IRTS.LangOpts import IRTS.Portable import IRTS.Simplified  import Prelude hiding (id, (.)) -import Control.Applicative import Control.Category import Control.Monad.State-import Data.IntSet (IntSet)-import qualified Data.IntSet as IS import Data.List import qualified Data.Map as M-import Data.Maybe import Data.Ord import qualified Data.Set as S-import Debug.Trace import System.Directory-import System.Environment import System.Exit-import System.FilePath (addTrailingPathSeparator, (</>)) import System.IO import System.Process @@ -76,7 +66,7 @@         libs <- getLibs codegen         flags <- getFlags codegen         hdrs <- getHdrs codegen-        impdirs <- allImportDirs+        impdirs <- rankedImportDirs f         ttDeclarations <- getDeclarations reachableNames         defsIn <- mkDecls reachableNames         -- if no 'main term' given, generate interface files@@ -91,7 +81,14 @@         let defsUniq = map (allocUnique (addAlist defsInlined emptyContext))                            defsInlined -        let (nexttag, tagged) = addTags 65536 (liftAll defsUniq)+        logCodeGen 1 "Inlining"++        dumpCases <- getDumpCases+        case dumpCases of+            Nothing -> return ()+            Just f -> runIO $ writeFile f (showCaseTrees defsUniq)++        let (nexttag, tagged) = addTags 65536 (liftAll defsInlined)         let ctxtIn = addAlist tagged emptyContext          logCodeGen 1 "Defunctionalising"@@ -106,11 +103,7 @@          let checked = simplifyDefs defuns (toAlist defuns)         outty <- outputTy-        dumpCases <- getDumpCases         dumpDefun <- getDumpDefun-        case dumpCases of-            Nothing -> return ()-            Just f -> runIO $ writeFile f (showCaseTrees defs)         case dumpDefun of             Nothing -> return ()             Just f -> runIO $ writeFile f (dumpDefuns defuns)@@ -152,7 +145,7 @@                                         return fn                        let cmd = "idris-codegen-" ++ cg                            args = [input, "-o", outputFile ir] ++ compilerFlags ir-                       exit <- rawSystem cmd args+                       exit <- rawSystem cmd (if interfaces ir then "--interface" : args else args)                        when (exit /= ExitSuccess) $                             putStrLn ("FAILURE: " ++ show cmd ++ " " ++ show args)        Bytecode -> dumpBC (simpleDecls ir) (outputFile ir)@@ -178,9 +171,13 @@ showCaseTrees :: [(Name, LDecl)] -> String showCaseTrees = showSep "\n\n" . map showCT . sortBy (comparing defnRank)   where-    showCT (n, LFun _ f args lexp)-       = show n ++ " " ++ showSep " " (map show args) ++ " =\n\t"+    showCT (n, LFun opts f args lexp)+       = showOpts +++         show n ++ " " ++ showSep " " (map show args) ++ " =\n\t"             ++ show lexp+      where+        showOpts | Inline `elem` opts = "%inline "+                 | otherwise = ""     showCT (n, LConstructor c t a) = "data " ++ show n ++ " " ++ show a      defnRank :: (Name, LDecl) -> String@@ -214,7 +211,7 @@               Just (ar, op) ->                   let args = map (\x -> sMN x "op") [0..] in                       return (n, (LFun [] n (take ar args)-                                         (LOp op (map (LV . Glob) (take ar args)))))+                                         (LOp op (map LV (take ar args)))))               _ -> do def <- mkLDecl n d                       logCodeGen 3 $ "Compiled " ++ show n ++ " =\n\t" ++ show def                       return (n, def)@@ -398,7 +395,7 @@                 -> irTerm top vs env (head argsPruned)                  | otherwise  -- not newtype, plain data ctor-                -> buildApp (LV $ Glob n) argsPruned+                -> buildApp (LV n) argsPruned              -- not saturated, underapplied             LT  | isNewtype               -- newtype@@ -407,11 +404,11 @@                     <$> irTerm top vs env (head argsPruned)                  | isNewtype  -- newtype but the value is not among args yet-                -> return . padLams $ \[vn] -> LApp False (LV $ Glob n) [LV $ Glob vn]+                -> return . padLams $ \[vn] -> LApp False (LV n) [LV vn]                  -- not a newtype, just apply to a constructor                 | otherwise-                -> padLams . applyToNames <$> buildApp (LV $ Glob n) argsPruned+                -> padLams . applyToNames <$> buildApp (LV n) argsPruned      -- type constructor     (P (TCon t a) n _, args) -> return LNothing@@ -446,7 +443,7 @@      applyToNames :: LExp -> [Name] -> LExp     applyToNames tm [] = tm-    applyToNames tm ns = LApp False tm $ map (LV . Glob) ns+    applyToNames tm ns = LApp False tm $ map LV ns      padLambdas :: [Int] -> Int -> Int -> ([Name] -> LExp) -> LExp     padLambdas used startIdx endSIdx mkTerm@@ -457,7 +454,7 @@      applyName :: Name -> IState -> [Term] -> Idris LExp     applyName n ist args =-        LApp False (LV $ Glob n) <$> mapM (irTerm top vs env . erase) (zip [0..] args)+        LApp False (LV n) <$> mapM (irTerm top vs env . erase) (zip [0..] args)       where         erase (i, x)             | i >= arity || i `elem` used = x@@ -479,16 +476,16 @@         used = maybe [] (map fst . usedpos) $ lookupCtxtExact uName (idris_callgraph ist)         fst4 (x,_,_,_,_,_) = x -irTerm top vs env (P _ n _) = return $ LV (Glob n)+irTerm top vs env (P _ n _) = return $ LV n irTerm top vs env (V i)-    | i >= 0 && i < length env = return $ LV (Glob (env!!i))+    | i >= 0 && i < length env = return $ LV (env!!i)     | otherwise = ifail $ "bad de bruijn index: " ++ show i  irTerm top vs env (Bind n (Lam _ _) sc) = LLam [n'] <$> irTerm top vs (n':env) sc   where     n' = uniqueName n env -irTerm top vs env (Bind n (Let _ v) sc)+irTerm top vs env (Bind n (Let _ _ v) sc)     = LLet n <$> irTerm top vs env v <*> irTerm top vs (n : env) sc  irTerm top vs env (Bind _ _ _) = return $ LNothing@@ -516,8 +513,10 @@         = do let l' = toFDesc l              r' <- irTerm (sMN 0 "__foreignCall") vs env r              return (l', r')-    splitArg _ = ifail "Badly formed foreign function call"+    splitArg _ = ifail $ "Badly formed foreign function call: " +++                         show (ret : fname : world : args) +     toFDesc (Constant (Str str)) = FStr str     toFDesc tm        | (P _ n _, []) <- unApply tm = FCon (deNS n)@@ -535,7 +534,7 @@  irSC :: Name -> Vars -> SC -> Idris LExp irSC top vs (STerm t) = irTerm top vs [] t-irSC top vs (UnmatchedCase str) = return $ LError str+irSC top vs (UnmatchedCase str) = return $ LLazyExp $ LError str  irSC top vs (ProjCase tm alts) = do     tm'   <- irTerm top vs [] tm@@ -546,7 +545,7 @@ irSC top vs (Case up n [ConCase (UN delay) i [_, _, n'] sc])     | delay == txt "Delay"     = do sc' <- irSC top vs sc -- mkForce n' n sc-         return $ lsubst n' (LForce (LV (Glob n))) sc'+         return $ lsubst n' (LForce (LV n)) sc'  -- There are two transformations in this case: --@@ -583,10 +582,10 @@     case replacement of         Just sc -> irSC top vs sc         _ -> do-            alt' <- irAlt top vs (LV (Glob n)) alt+            alt' <- irAlt top vs (LV n) alt             return $ case namesBoundIn alt' `usedIn` subexpr alt' of                 [] -> subexpr alt'  -- strip the unused top-most case-                _  -> LCase up (LV (Glob n)) [alt']+                _  -> LCase up (LV n) [alt']   where     namesBoundIn :: LAlt -> [Name]     namesBoundIn (LConCase cn i ns sc) = ns@@ -618,7 +617,7 @@     detag <- fgetState (opt_detaggable . ist_optimisation cn)     if detag         then irSC top vs (Case up n [ConCase cn a ns sc])-        else LCase up (LV (Glob n)) <$> mapM (irAlt top vs (LV (Glob n))) alts+        else LCase up (LV n) <$> mapM (irAlt top vs (LV n)) alts  irSC top vs sc@(Case up n alts) = do     -- check that neither alternative needs the newtype optimisation,@@ -628,7 +627,7 @@         $ ifail ("irSC: non-trivial case-match on detaggable data: " ++ show sc)      -- everything okay-    LCase up (LV (Glob n)) <$> mapM (irAlt top vs (LV (Glob n))) alts+    LCase up (LV n) <$> mapM (irAlt top vs (LV n)) alts   where     isDetaggable (ConCase cn _ _ _) = fgetState $ opt_detaggable . ist_optimisation cn     isDetaggable  _                 = return False
src/IRTS/Defunctionalise.hs view
@@ -1,7 +1,7 @@ {-| Module      : IRTS.Defunctionalise Description : Defunctionalise Idris' IR.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. @@ -32,14 +32,13 @@ import Control.Monad.State import Data.List import Data.Maybe-import Debug.Trace -data DExp = DV LVar+data DExp = DV Name           | DApp Bool Name [DExp] -- True = tail call           | DLet Name DExp DExp -- name just for pretty printing           | DUpdate Name DExp -- eval expression, then update var with it           | DProj DExp Int-          | DC (Maybe LVar) Int Name [DExp]+          | DC (Maybe Name) Int Name [DExp]           | DCase CaseType DExp [DAlt]           | DChkCase DExp [DAlt] -- a case where the type is unknown (for EVAL/APPLY)           | DConst Const@@ -90,27 +89,27 @@          return (n, DFun n args e')   where     aa :: [Name] -> LExp -> State ([Name], [(Name, Int)]) DExp-    aa env (LV (Glob n)) | n `elem` env = return $ DV (Glob n)-                         | otherwise = aa env (LApp False (LV (Glob n)) [])-    aa env (LApp tc (LV (Glob n)) args)+    aa env (LV n) | n `elem` env = return $ DV n+                         | otherwise = aa env (LApp False (LV n) [])+    aa env (LApp tc (LV n) args)        = do args' <- mapM (aa env) args             case lookupCtxtExact n defs of                 Just (LConstructor _ i ar) -> return $ DApp tc n args'                 Just (LFun _ _ as _) -> let arity = length as in                                                fixApply tc n args' arity-                Nothing -> return $ chainAPPLY (DV (Glob n)) args'+                Nothing -> return $ chainAPPLY (DV n) args'     aa env (LLazyApp n args)        = do args' <- mapM (aa env) args             case lookupCtxtExact n defs of                 Just (LConstructor _ i ar) -> return $ DApp False n args'                 Just (LFun _ _ as _) -> let arity = length as in                                            fixLazyApply n args' arity-                Nothing -> return $ chainAPPLY (DV (Glob n)) args'-    aa env (LForce (LLazyApp n args)) = aa env (LApp False (LV (Glob n)) args)+                Nothing -> return $ chainAPPLY (DV n) args'+    aa env (LForce (LLazyApp n args)) = aa env (LApp False (LV n) args)     aa env (LForce e) = liftM eEVAL (aa env e)     aa env (LLet n v sc) = liftM2 (DLet n) (aa env v) (aa (n : env) sc)     aa env (LCon loc i n args) = liftM (DC loc i n) (mapM (aa env) args)-    aa env (LProj t@(LV (Glob n)) i)+    aa env (LProj t@(LV n) i)         | n `elem` env = do t' <- aa env t                             return $ DProj (DUpdate n t') i     aa env (LProj t i) = do t' <- aa env t@@ -165,32 +164,6 @@ --          = chainAPPLY (DApp False (sMN 0 "APPLY2") [f, a, b]) as     chainAPPLY f (a : as) = chainAPPLY (DApp False (sMN 0 "APPLY") [f, a]) as -    -- if anything in the DExp is projected from, we'll need to evaluate it,-    -- but we only want to do it once, rather than every time we project.--    preEval [] t = t-    preEval (x : xs) t-       | needsEval x t = DLet x (DV (Glob x)) (preEval xs t)-       | otherwise = preEval xs t--    needsEval x (DApp _ _ args) = any (needsEval x) args-    needsEval x (DC _ _ _ args) = any (needsEval x) args-    needsEval x (DCase up e alts) = needsEval x e || any nec alts-      where nec (DConCase _ _ _ e) = needsEval x e-            nec (DConstCase _ e) = needsEval x e-            nec (DDefaultCase e) = needsEval x e-    needsEval x (DChkCase e alts) = needsEval x e || any nec alts-      where nec (DConCase _ _ _ e) = needsEval x e-            nec (DConstCase _ e) = needsEval x e-            nec (DDefaultCase e) = needsEval x e-    needsEval x (DLet n v e)-          | x == n = needsEval x v-          | otherwise = needsEval x v || needsEval x e-    needsEval x (DForeign _ _ args) = any (needsEval x) (map snd args)-    needsEval x (DOp op args) = any (needsEval x) args-    needsEval x (DProj (DV (Glob x')) _) = x == x'-    needsEval x _ = False- eEVAL x = DApp False (sMN 0 "EVAL") [x]  data EvalApply a = EvalCase (Name -> a)@@ -207,7 +180,7 @@           EvalCase (\tlarg ->             (DConCase (-1) (mkFnCon n) (take i (genArgs 0))               (dupdate tlarg-                (DApp False n (map (DV . Glob) (take i (genArgs 0))))))))+                (DApp False n (map DV (take i (genArgs 0))))))))           : [] -- mkApplyCase n 0 i     | otherwise = []   where dupdate tlarg x = DUpdate tlarg x@@ -219,23 +192,22 @@ --           EvalCase (\tlarg -> --             (DConCase (-1) (mkFnCon n) (take i (genArgs 0)) --               (dupdate tlarg---                 (DApp False n (map (DV . Glob) (take i (genArgs 0))))))))+--                 (DApp False n (map DV (take i (genArgs 0))))))))           = mkApplyCase n ar i     | otherwise = []-  where dupdate tlarg x = x  mkApplyCase fname n ar | n == ar = [] mkApplyCase fname n ar         = let nm = mkUnderCon fname (ar - n) in               (nm, n, ApplyCase (DConCase (-1) nm (take n (genArgs 0))                   (DApp False (mkUnderCon fname (ar - (n + 1)))-                       (map (DV . Glob) (take n (genArgs 0) +++                       (map DV (take n (genArgs 0) ++                          [sMN 0 "arg"])))))                             :               if (ar - (n + 2) >=0 )                  then (nm, n, Apply2Case (DConCase (-1) nm (take n (genArgs 0))                       (DApp False (mkUnderCon fname (ar - (n + 2)))-                       (map (DV . Glob) (take n (genArgs 0) +++                       (map DV (take n (genArgs 0) ++                          [sMN 0 "arg0", sMN 0 "arg1"])))))                             :                             mkApplyCase fname (n + 1) ar@@ -243,9 +215,9 @@  mkEval :: [(Name, Int, EvalApply DAlt)] -> (Name, DDecl) mkEval xs = (sMN 0 "EVAL", DFun (sMN 0 "EVAL") [sMN 0 "arg"]-               (mkBigCase (sMN 0 "EVAL") 256 (DV (Glob (sMN 0 "arg")))+               (mkBigCase (sMN 0 "EVAL") 256 (DV (sMN 0 "arg"))                   (mapMaybe evalCase xs ++-                      [DDefaultCase (DV (Glob (sMN 0 "arg")))])))+                      [DDefaultCase (DV (sMN 0 "arg"))])))   where     evalCase (n, t, EvalCase x) = Just (x (sMN 0 "arg"))     evalCase _ = Nothing@@ -256,7 +228,7 @@                                 [] -> DNothing                                 cases ->                                     mkBigCase (sMN 0 "APPLY") 256-                                               (DV (Glob (sMN 0 "fn")))+                                               (DV (sMN 0 "fn"))                                               (cases ++                                     [DDefaultCase DNothing])))   where@@ -269,14 +241,14 @@                                 [] -> DNothing                                 cases ->                                     mkBigCase (sMN 0 "APPLY") 256-                                               (DV (Glob (sMN 0 "fn")))+                                               (DV (sMN 0 "fn"))                                               (cases ++                                     [DDefaultCase                                        (DApp False (sMN 0 "APPLY")                                        [DApp False (sMN 0 "APPLY")-                                              [DV (Glob (sMN 0 "fn")),-                                               DV (Glob (sMN 0 "arg0"))],-                                               DV (Glob (sMN 0 "arg1"))])+                                              [DV (sMN 0 "fn"),+                                               DV (sMN 0 "arg0")],+                                               DV (sMN 0 "arg1")])                                                ])))   where     applyCase (n, t, Apply2Case x) = Just x@@ -297,8 +269,7 @@  instance Show DExp where    show e = show' [] e where-     show' env (DV (Loc i)) = "var " ++ env!!i-     show' env (DV (Glob n)) = "GLOB " ++ show n+     show' env (DV n) = show n      show' env (DApp _ e args) = show e ++ "(" ++                                    showSep ", " (map (show' env) args) ++")"      show' env (DLet n v e) = "let " ++ show n ++ " = " ++ show' env v ++ " in " ++@@ -332,30 +303,7 @@ -- 'max' branches mkBigCase cn max arg branches    | length branches <= max = DChkCase arg branches-   | otherwise = -- DChkCase arg branches -- until I think of something...-       -- divide the branches into groups of at most max (by tag),-       -- generate a new case and shrink, recursively-       let bs = sortBy tagOrd branches-           (all, def) = case (last bs) of-                    DDefaultCase t -> (init all, Just (DDefaultCase t))-                    _ -> (all, Nothing)-           bss = groupsOf max all-           cs = map mkCase bss in-           DChkCase arg branches--    where mkCase bs = DChkCase arg bs--          tagOrd (DConCase t _ _ _) (DConCase t' _ _ _) = compare t t'-          tagOrd (DConstCase c _) (DConstCase c' _) = compare c c'-          tagOrd (DDefaultCase _) (DDefaultCase _) = EQ--          tagOrd (DConCase _ _ _ _) (DDefaultCase _) = LT-          tagOrd (DConCase _ _ _ _) (DConstCase _ _) = LT-          tagOrd (DConstCase _ _) (DDefaultCase _) = LT--          tagOrd (DDefaultCase _) (DConCase _ _ _ _) = GT-          tagOrd (DConstCase _ _) (DConCase _ _ _ _) = GT-          tagOrd (DDefaultCase _) (DConstCase _ _) = GT+   | otherwise = DChkCase arg branches  groupsOf :: Int -> [DAlt] -> [[DAlt]] groupsOf x [] = []
src/IRTS/DumpBC.hs view
@@ -1,7 +1,7 @@ {-| Module      : IRTS.DumpBC Description : Serialise Idris to its IBC format.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -9,7 +9,6 @@  import Idris.Core.TT import IRTS.Bytecode-import IRTS.Lang import IRTS.Simplified  import Data.List
src/IRTS/Exports.hs view
@@ -1,7 +1,7 @@ {-| Module      : IRTS.Exports Description : Deal with external things.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}
src/IRTS/Inliner.hs view
@@ -1,7 +1,7 @@ {-| Module      : IRTS.Inliner Description : Inline expressions.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}
src/IRTS/JavaScript/AST.hs view
@@ -1,7 +1,7 @@ {-| Module      : IRTS.JavaScript.AST Description : The JavaScript AST.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}
src/IRTS/JavaScript/Codegen.hs view
@@ -1,7 +1,7 @@ {-| Module      : IRTS.JavaScript.Codegen Description : The JavaScript common code generator.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -14,21 +14,23 @@  import Idris.Core.TT import IRTS.CodegenCommon+import IRTS.Exports import IRTS.JavaScript.AST import IRTS.JavaScript.LangTransforms import IRTS.JavaScript.Name import IRTS.JavaScript.PrimOp import IRTS.JavaScript.Specialize import IRTS.Lang-import IRTS.LangOpts import IRTS.System +import Control.Applicative (pure, (<$>)) import Control.Monad import Control.Monad.Trans.State-import Data.List (nub)+import Data.Foldable (foldMap)+import Data.Generics.Uniplate.Data+import Data.List import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map-import Data.Maybe (fromJust) import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text)@@ -38,24 +40,27 @@ import System.Environment import System.FilePath -import Control.Applicative (pure, (<$>))-import Data.Char-import Data.Data-import Data.Generics.Uniplate.Data-import Data.List-import GHC.Generics (Generic)-+-- | Code generation stats hold information about the generated user+-- code. Based on that information we add additional code to make+-- things work. data CGStats = CGStats { usedBigInt :: Bool                        , partialApplications :: Set Partial                        , hiddenClasses :: Set HiddenClass                        } -emptyStats :: CGStats-emptyStats = CGStats { partialApplications = Set.empty-                     , hiddenClasses = Set.empty-                     , usedBigInt = False-                     }+-- If we generate code for two declarations we want to merge their code+-- generation stats.+instance Monoid CGStats where+  mempty = CGStats { partialApplications = Set.empty+                   , hiddenClasses = Set.empty+                   , usedBigInt = False+                   }+  mappend x y = CGStats { partialApplications = partialApplications x `Set.union` partialApplications y+                        , hiddenClasses = hiddenClasses x `Set.union` hiddenClasses y+                        , usedBigInt = usedBigInt x || usedBigInt y+                        } + data CGConf = CGConf { header :: Text                      , footer :: Text                      , jsbnPath :: String@@ -84,6 +89,7 @@     repl '\\' = '_'     repl '/' = '_'     repl '.' = '_'+    repl '-' = '_'     repl c   = c   in     concatMap (\lib -> "var " ++ (repl <$> lib) ++ " = require(\"" ++ lib ++"\");\n")@@ -93,21 +99,44 @@ isYes (Just "y") = True isYes _ = False +makeExportDecls :: Map Name LDecl -> ExportIFace -> [Text]+makeExportDecls defs (Export _ _ e) =+  concatMap makeExport e+  where+    uncurryF name argTy (Just args) =+      if length argTy == length args then name+        else T.concat [ "function(){ return "+                      , name+                      , ".apply(this, Array.prototype.slice.call(arguments, 0,", T.pack $ show $ length args,"))"+                      , T.concat $ map (\x -> T.concat ["(arguments[", T.pack $ show x , "])"]) [length args .. (length argTy - 1)]+                      , "}"+                      ]+    uncurryF name argTy Nothing = name +    makeExport (ExportData _) =+      []+    makeExport (ExportFun name (FStr exportname) retTy argTy) =+      [T.concat [ T.pack $ exportname+                ,  ": "+                , uncurryF (jsName name) argTy (getArgList' name defs)+                ]+      ]+ codegenJs :: CGConf -> CodeGenerator codegenJs conf ci =   do     debug <- isYes <$> lookupEnv "IDRISJS_DEBUG"     let defs' = Map.fromList $ liftDecls ci     let defs = globlToCon defs'-    let used = Map.elems $ removeDeadCode defs [sMN 0 "runMain"]-    if debug then-      do+    let iface = interfaces ci+    let used = if iface then+                  Map.elems $ removeDeadCode defs (getExpNames $ exportDecls ci)+                  else Map.elems $ removeDeadCode defs [sMN 0 "runMain"]+    when debug $ do         writeFile (outputFile ci ++ ".LDeclsDebug") $ (unlines $ intersperse "" $ map show used) ++ "\n\n\n"         putStrLn $ "Finished calculating used"-      else pure () -    let (out, stats) = doCodegen conf defs used+    let (out, stats) = doCodegen defs used      path <- getIdrisJSRTSDir     jsbn <- if usedBigInt stats@@ -133,7 +162,8 @@                                              , doPartials (partialApplications stats), "\n"                                              , doHiddenClasses (hiddenClasses stats), "\n"                                              , out, "\n"-                                             , jsName (sMN 0 "runMain"), "();\n"+                                             , if iface then T.concat ["module.exports = {\n", T.intercalate ",\n" $ concatMap (makeExportDecls defs) (exportDecls ci), "\n};\n"]+                                                  else jsName (sMN 0 "runMain") `T.append` "();\n"                                              , "}.call(this))"                                              , footer conf                                              ]@@ -160,21 +190,22 @@              JsFun (jsNameHiddenClass p) vars $ JsSeq (JsSet (JsProp JsThis "type") (JsInt id)) $ seqJs                $ map (\tv -> JsSet (JsProp JsThis tv) (JsVar tv)) vars -doCodegen :: CGConf -> Map Name LDecl -> [LDecl] -> (Text, CGStats)-doCodegen conf defs decls =-  let xs = map (doCodegenDecl conf defs) decls-      groupCGStats x y = CGStats { partialApplications = partialApplications x `Set.union` partialApplications y-                                 , hiddenClasses = hiddenClasses x `Set.union` hiddenClasses y-                                 , usedBigInt = usedBigInt x || usedBigInt y-                                 }-  in (T.intercalate "\n" $ map fst xs, foldl' groupCGStats emptyStats (map snd xs) ) -doCodegenDecl :: CGConf -> Map Name LDecl -> LDecl -> (Text, CGStats)-doCodegenDecl conf defs (LFun _ n args def) =-  let (ast, stats) = cgFun conf defs n args def-  in (T.concat [jsStmt2Text (JsComment $ T.pack $ show n), "\n", jsStmt2Text ast], stats)-doCodegenDecl conf defs (LConstructor n i sz) = ("", emptyStats)+-- | Generate code for each declaration and collect stats.+-- LFunctions are turned into JS function declarations. They are+-- preceded by a comment that gives their name. Constructor+-- declarations are ignored.+doCodegen :: Map Name LDecl -> [LDecl] -> (Text, CGStats)+doCodegen defs = foldMap (doCodegenDecl defs)+  where+    doCodegenDecl :: Map Name LDecl -> LDecl -> (Text, CGStats)+    doCodegenDecl defs (LFun _ name args def) =+      let (ast, stats) = cgFun defs name args def+          fnComment = jsStmt2Text (JsComment $ T.pack $ show name)+      in (T.concat [fnComment, "\n", jsStmt2Text ast, "\n"], stats)+    doCodegenDecl defs (LConstructor n i sz) = ("", mempty) + seqJs :: [JsStmt] -> JsStmt seqJs [] = JsEmpty seqJs (x:xs) = JsSeq x (seqJs xs)@@ -186,7 +217,6 @@                                , currentFnNameAndArgs :: (Text, [Text])                                , usedArgsTailCallOptim :: Set (Text, Text)                                , isTailRec :: Bool-                               , conf :: CGConf                                , usedITBig :: Bool                                , partialApps :: Set Partial                                , hiddenCls :: Set HiddenClass@@ -212,10 +242,6 @@ addUsedArgsTailCallOptim p =   modify (\s -> s {usedArgsTailCallOptim = Set.union p (usedArgsTailCallOptim s) }) -getNewCGNames :: Int -> State CGBodyState [Text]-getNewCGNames n =-  mapM (\_ -> getNewCGName) [1..n]- getConsId :: Name -> State CGBodyState (Int, Int) getConsId n =     do@@ -224,13 +250,17 @@         Just (LConstructor _ conId arity) -> pure (conId, arity)         _ -> error $ "Internal JS Backend error " ++ showCG n ++ " is not a constructor." +getArgList' :: Name -> Map Name LDecl -> Maybe [Name]+getArgList' n defs =+    case Map.lookup n defs of+      Just (LFun _ _ a _) -> Just a+      _ -> Nothing+ getArgList :: Name -> State CGBodyState (Maybe [Name]) getArgList n =   do     st <- get-    case Map.lookup n (defs st) of-      Just (LFun _ _ a _) -> pure $ Just a-      _ -> pure Nothing+    pure $ getArgList' n (defs st)  data BodyResTarget = ReturnBT                    | DecBT Text@@ -238,8 +268,8 @@                    | DecConstBT Text                    | GetExpBT -cgFun :: CGConf -> Map Name LDecl -> Name -> [Name] -> LExp -> (JsStmt, CGStats)-cgFun cnf dfs n args def = do+cgFun :: Map Name LDecl -> Name -> [Name] -> LExp -> (JsStmt, CGStats)+cgFun dfs n args def = do   let fnName = jsName n   let argNames = map jsName args   let ((decs, res),st) = runState@@ -250,7 +280,6 @@                                        , currentFnNameAndArgs = (fnName, argNames)                                        , usedArgsTailCallOptim = Set.empty                                        , isTailRec = False-                                       , conf = cnf                                        , usedITBig = False                                        , partialApps = Set.empty                                        , hiddenCls = Set.empty@@ -264,16 +293,6 @@                        }   (fn, state') -getSwitchJs :: JsExpr -> [LAlt] -> JsExpr-getSwitchJs x alts =-  if any conCase alts then JsArrayProj (JsInt 0) x-    else if any constBigIntCase alts then JsForeign "%0.toString()" [x]-            else x-  where conCase (LConCase _ _ _ _) = True-        conCase _ = False-        constBigIntCase (LConstCase (BI _) _) = True-        constBigIntCase _ = False- addRT :: BodyResTarget -> JsExpr -> JsStmt addRT ReturnBT x = JsReturn x addRT (DecBT n) x = JsDecLet n x@@ -345,15 +364,15 @@     expr -> cgBody' rt expr  cgBody' :: BodyResTarget -> LExp -> State CGBodyState ([JsStmt], JsStmt)-cgBody' rt (LV (Glob n)) =+cgBody' rt (LV n) =   do     argsFn <- getArgList n     case argsFn of-      Just a -> cgBody' rt (LApp False (LV (Glob n)) [])+      Just a -> cgBody' rt (LApp False (LV n) [])       Nothing -> do         n' <- cgName n         pure $ ([], addRT rt n')-cgBody' rt (LApp tailcall (LV (Glob fn)) args) =+cgBody' rt (LApp tailcall (LV fn) args) =   do     let fname = jsName fn     st <- get@@ -372,10 +391,10 @@         app <- formApp fn argVals         pure (preDecs, addRT rt app) -cgBody' rt (LForce (LLazyApp n args)) = cgBody rt (LApp False (LV (Glob n)) args)+cgBody' rt (LForce (LLazyApp n args)) = cgBody rt (LApp False (LV n) args) cgBody' rt (LLazyApp n args) =   do-    (d,v) <- cgBody ReturnBT (LApp False (LV (Glob n)) args)+    (d,v) <- cgBody ReturnBT (LApp False (LV n) args)     pure ([], addRT rt $ jsLazy $ jsStmt2Expr $ JsSeq (seqJs d) v) cgBody' rt (LForce e) =   do
src/IRTS/JavaScript/LangTransforms.hs view
@@ -1,7 +1,7 @@ {-| Module      : IRTS.JavaScript.LangTransforms Description : The JavaScript LDecl Transformations.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -12,23 +12,18 @@                                      ) where  -import Control.DeepSeq-import Control.Monad.Trans.State import Data.List import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Maybe import Data.Set (Set) import qualified Data.Set as Set-import Data.Text (Text)-import qualified Data.Text as T import Idris.Core.CaseTree import Idris.Core.TT import IRTS.Lang  import Data.Data import Data.Generics.Uniplate.Data-import GHC.Generics (Generic)  deriving instance Typeable FDesc deriving instance Data FDesc@@ -49,15 +44,10 @@ restrictKeys :: Ord k => Map k a -> Set k -> Map k a restrictKeys m s = Map.filterWithKey (\k _ -> k `Set.member` s) m -mapMapListKeys :: Ord k => (a->a) -> [k] -> Map k a -> Map k a-mapMapListKeys _ [] x = x-mapMapListKeys f (t:r) x = mapMapListKeys f r $ Map.adjust f t x-- extractGlobs :: Map Name LDecl -> LDecl -> [Name] extractGlobs defs (LConstructor _ _ _) = [] extractGlobs defs (LFun _ _ _ e) =-  let f (LV (Glob x)) = Just x+  let f (LV x) = Just x       f (LLazyApp x _) = Just x       f _ = Nothing   in [x | Just x <- map f $ universe e, Map.member x defs]@@ -102,7 +92,7 @@   transformBi (f x) x   where     f :: Map Name LDecl -> LExp -> LExp-    f y x@(LV (Glob n)) =+    f y x@(LV n) =       case Map.lookup n y of         Just (LConstructor _ conId arity) -> LCon Nothing conId n []         _ -> x
src/IRTS/JavaScript/Name.hs view
@@ -1,7 +1,7 @@ {-| Module      : IRTS.JavaScript.Name Description : The JavaScript name mangler.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -20,12 +20,9 @@   ) where  import Data.Char-import Data.List-import qualified Data.Map.Strict as Map import Data.Text (Text) import qualified Data.Text as T import Idris.Core.TT-import IRTS.JavaScript.AST  jsEscape :: String -> String jsEscape = concatMap jschar
src/IRTS/JavaScript/PrimOp.hs view
@@ -1,7 +1,7 @@ {-| Module      : IRTS.JavaScript.PrimOp Description : The JavaScript primitive operations.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -16,11 +16,7 @@   , jsPrimCoerce   ) where -import Data.Char-import Data.List import qualified Data.Map.Strict as Map-import Data.Text (Text)-import qualified Data.Text as T import Idris.Core.TT import IRTS.JavaScript.AST import IRTS.Lang@@ -30,8 +26,6 @@ type PrimF = [JsExpr] -> JsExpr type PrimDec = (Bool, JsPrimTy, PrimF) -- the bool indicates if bigint library is used or not -deriving instance Ord PrimFn- primDB :: Map.Map PrimFn PrimDec primDB =   Map.fromList [@@ -119,6 +113,10 @@   , item (LASHR (ITFixed IT16)) False PTAny $ JsForeign "%0 >> %1"   , item (LASHR (ITFixed IT32)) False PTAny $ JsForeign "%0 >> %1|0"   , item (LASHR (ITFixed IT64)) True PTAny $ JsForeign "%0.shiftRight(%1)"+  , item (LCompl (ITFixed IT8)) False PTAny $ JsForeign "~%0"+  , item (LCompl (ITFixed IT16)) False PTAny $ JsForeign "~%0"+  , item (LCompl (ITFixed IT32)) False PTAny $ JsForeign "~%0|0"+  , item (LCompl (ITFixed IT64)) True PTAny $ method "not"   , item (LEq ATFloat) False PTBool $ binop "==="   , item (LEq (ATInt ITNative)) False PTBool $ binop "==="   , item (LEq (ATInt ITChar)) False PTBool $ binop "==="@@ -217,6 +215,7 @@   , item LFASin False PTAny $ jsAppN "Math.asin"   , item LFACos False PTAny $ jsAppN "Math.acos"   , item LFATan False PTAny $ jsAppN "Math.atan"+  , item LFATan2 False PTAny $ jsAppN "Math.atan2"   , item LFSqrt False PTAny $ jsAppN "Math.sqrt"   , item LFFloor False PTAny $ jsAppN "Math.floor"   , item LFCeil False PTAny $ jsAppN "Math.ceil"
src/IRTS/JavaScript/Specialize.hs view
@@ -1,7 +1,7 @@ {-| Module      : IRTS.JavaScript.Specialize Description : The JavaScript specializer.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -17,10 +17,7 @@   , qualifyN   ) where -import Data.Char-import Data.List import qualified Data.Map.Strict as Map-import Data.Text (Text) import qualified Data.Text as T import Idris.Core.TT import IRTS.JavaScript.AST@@ -62,23 +59,12 @@     ]     -- constructors   where-    nil = const $ JsArray []-    cons [h, t] = JsMethod (JsArray [h]) "concat" [t]-    -- tests-    --trueTest e = JsUniOp (T.pack "!") $ JsUniOp (T.pack "!") e     trueTest = id     falseTest e = JsUniOp (T.pack "!") e-    emptyList e = JsBinOp "===" (JsProp e "length") (JsInt 0)-    fillList e = JsBinOp ">" (JsProp e "length") (JsInt 0)     ltTest e = JsBinOp "<" e (JsInt 0)     eqTest e = JsBinOp "===" e (JsInt 0)     gtTest e = JsBinOp ">" e (JsInt 0)-    noneTest e = JsBinOp "===" e JsUndefined-    notNoneTest e = JsBinOp "!==" e JsUndefined     -- projections-    justProj x n = x-    uncons x 1 = JsArrayProj (JsInt 0) x-    uncons x 2 = JsMethod x "slice" [JsInt 1]     cantProj x j = error $ "This type should be projected"     item :: String          -> String
src/IRTS/Lang.hs view
@@ -1,7 +1,7 @@ {-| Module      : IRTS.Lang Description : Internal representation of Idris' constructs.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -13,12 +13,11 @@ import Idris.Core.CaseTree import Idris.Core.TT -import Control.Applicative hiding (Const) import Control.Monad.State hiding (lift) import Data.Data (Data) import Data.List+import qualified Data.Map.Strict as Map import Data.Typeable (Typeable)-import Debug.Trace import GHC.Generics (Generic)  data Endianness = Native | BE | LE deriving (Show, Eq)@@ -28,7 +27,7 @@  -- ASSUMPTION: All variable bindings have unique names here -- Constructors commented as lifted are not present in the LIR provided to the different backends.-data LExp = LV LVar+data LExp = LV Name           | LApp Bool LExp [LExp]    -- True = tail call           | LLazyApp Name [LExp]     -- True = tail call           | LLazyExp LExp            -- lifted out before compiling@@ -36,7 +35,7 @@           | LLet Name LExp LExp      -- name just for pretty printing           | LLam [Name] LExp         -- lambda, lifted out before compiling           | LProj LExp Int           -- projection-          | LCon (Maybe LVar)        -- Location to reallocate, if available+          | LCon (Maybe Name)        -- Location to reallocate, if available                  Int Name [LExp]           | LCase CaseType LExp [LAlt]           | LConst Const@@ -46,26 +45,26 @@           | LOp PrimFn [LExp]           | LNothing           | LError String-  deriving Eq+  deriving (Eq, Ord)  data FDesc = FCon Name            | FStr String            | FUnknown            | FIO FDesc            | FApp Name [FDesc]-  deriving (Show, Eq)+  deriving (Show, Eq, Ord)  data Export = ExportData FDesc -- Exported data descriptor (usually string)             | ExportFun Name -- Idris name                         FDesc -- Exported function descriptor                         FDesc -- Return type descriptor                         [FDesc] -- Argument types-  deriving (Show, Eq)+  deriving (Show, Eq, Ord)  data ExportIFace = Export Name -- FFI descriptor                           String -- interface file                           [Export]-  deriving (Show, Eq)+  deriving (Show, Eq, Ord)  -- Primitive operators. Backends are not *required* to implement all -- of these, but should report an error if they are unable@@ -83,7 +82,7 @@             | LBitCast ArithTy ArithTy -- Only for values of equal width              | LFExp | LFLog | LFSin | LFCos | LFTan | LFASin | LFACos | LFATan-            | LFSqrt | LFFloor | LFCeil | LFNegate+            | LFATan2 | LFSqrt | LFFloor | LFCeil | LFNegate              | LStrHead | LStrTail | LStrCons | LStrIndex | LStrRev | LStrSubstr             | LReadStr | LWriteStr@@ -98,12 +97,12 @@             | LCrash              | LNoOp-  deriving (Show, Eq, Generic)+  deriving (Show, Eq, Ord, Generic)  -- Supported target languages for foreign calls  data FCallType = FStatic | FObject | FConstructor-  deriving (Show, Eq)+  deriving (Show, Eq, Ord)  data FType = FArith ArithTy            | FFunction@@ -114,24 +113,24 @@            | FManagedPtr            | FCData            | FAny-  deriving (Show, Eq)+  deriving (Show, Eq, Ord)  -- FIXME: Why not use this for all the IRs now? data LAlt' e = LConCase Int Name [Name] e              | LConstCase Const e              | LDefaultCase e-  deriving (Show, Eq, Functor, Data, Typeable)+  deriving (Show, Eq, Ord, Functor, Data, Typeable)  type LAlt = LAlt' LExp  data LDecl = LFun [LOpt] Name [Name] LExp -- options, name, arg names, def            | LConstructor Name Int Int -- constructor name, tag, arity-  deriving (Show, Eq)+  deriving (Show, Eq, Ord)  type LDefs = Ctxt LDecl  data LOpt = Inline | NoInline-  deriving (Show, Eq)+  deriving (Show, Eq, Ord)  addTags :: Int -> [(Name, LDecl)] -> (Int, [(Name, LDecl)]) addTags i ds = tag i ds []@@ -142,39 +141,73 @@         tag i (x : as) acc = tag i as (x : acc)         tag i [] acc  = (i, reverse acc) -data LiftState = LS Name Int [(Name, LDecl)]+data LiftState = LS (Maybe Name) Int [(Name, LDecl)]+                    (Map.Map ([Name], LExp) Name) -- map from args/expressions+                          -- to names, so we don't create the same function+                          -- multiple times +setBaseName :: Name -> State LiftState ()+setBaseName n+    = do LS _ i ds done <- get+         put (LS (Just n) i ds done)+ lname (NS n x) i = NS (lname n i) x lname (UN n) i = MN i n lname x i = sMN i (showCG x ++ "_lam") -liftAll :: [(Name, LDecl)] -> [(Name, LDecl)]-liftAll xs = concatMap (\ (x, d) -> lambdaLift x d) xs--lambdaLift :: Name -> LDecl -> [(Name, LDecl)]-lambdaLift n (LFun opts _ args e)-      = let (e', (LS _ _ decls)) = runState (lift args e) (LS n 0 []) in-            (n, LFun opts n args e') : decls-lambdaLift n x = [(n, x)]- getNextName :: State LiftState Name-getNextName = do LS n i ds <- get-                 put (LS n (i + 1) ds)-                 return (lname n i)+getNextName+    = do LS mn i ds done <- get+         let newn = case mn of+                         Nothing -> lname (sUN "_") i+                         Just n -> lname n i+         put (LS mn (i + 1) ds done)+         return newn +renameArgs :: [Name] -> LExp -> ([Name], LExp)+renameArgs args e+   = let newargNames = map (\i -> sMN i "lift") [0..]+         newargs = zip args newargNames in+         (map snd newargs, rename newargs e)+ addFn :: Name -> LDecl -> State LiftState ()-addFn fn d = do LS n i ds <- get-                put (LS n i ((fn, d) : ds))+addFn fn d+    = do LS n i ds done <- get+         put (LS n i ((fn, d) : ds) done) +makeFn :: [Name] -> LExp -> State LiftState Name+makeFn args exp+    = do fn <- getNextName+         let (args', exp') = renameArgs args exp+         LS n i ds done <- get+         case Map.lookup (args', exp') done of+              Just fn -> return fn+              Nothing ->+                do addFn fn (LFun [Inline] fn args' exp')+                   LS n i ds done <- get+                   put (LS n i ds (Map.insert (args', exp') fn done))+                   return fn++liftAll :: [(Name, LDecl)] -> [(Name, LDecl)]+liftAll xs =+  let (LS _ _ decls _) = execState (mapM_ liftDef xs) (LS Nothing 0 [] Map.empty) in+      decls++liftDef :: (Name, LDecl) -> State LiftState ()+liftDef (n, LFun opts _ args e) =+    do setBaseName n+       e' <- lift args e+       addFn n (LFun opts n args e')+liftDef (n, x) = addFn n x+ lift :: [Name] -> LExp -> State LiftState LExp lift env (LV v) = return (LV v) -- Lifting happens before these can exist...-lift env (LApp tc (LV (Glob n)) args) = do args' <- mapM (lift env) args-                                           return (LApp tc (LV (Glob n)) args')+lift env (LApp tc (LV n) args) = do args' <- mapM (lift env) args+                                    return (LApp tc (LV n) args') lift env (LApp tc f args) = do f' <- lift env f-                               fn <- getNextName-                               addFn fn (LFun [Inline] fn env f')+                               fn <- makeFn env f'                                args' <- mapM (lift env) args-                               return (LApp tc (LV (Glob fn)) (map (LV . Glob) env ++ args'))+                               return (LApp tc (LV fn) (map LV env ++ args')) lift env (LLazyApp n args) = do args' <- mapM (lift env) args                                 return (LLazyApp n args') lift env (LLazyExp (LConst c)) = return (LConst c)@@ -182,19 +215,18 @@ --                       = lift env (LLazyApp f args) lift env (LLazyExp e) = do e' <- lift env e                            let usedArgs = nub $ usedIn env e'-                           fn <- getNextName-                           addFn fn (LFun [NoInline] fn usedArgs e')-                           return (LLazyApp fn (map (LV . Glob) usedArgs))+                           fn <- makeFn usedArgs e'+                           return (LLazyApp fn (map LV usedArgs)) lift env (LForce e) = do e' <- lift env e                          return (LForce e') lift env (LLet n v e) = do v' <- lift env v                            e' <- lift (env ++ [n]) e                            return (LLet n v' e')+lift env (LLam args (LLam args' e)) = lift env (LLam (args ++ args') e) lift env (LLam args e) = do e' <- lift (env ++ args) e                             let usedArgs = nub $ usedIn env e'-                            fn <- getNextName-                            addFn fn (LFun [Inline] fn (usedArgs ++ args) e')-                            return (LApp False (LV (Glob fn)) (map (LV . Glob) usedArgs))+                            fn <- makeFn (usedArgs ++ args) e'+                            return (LApp False (LV fn) (map LV usedArgs)) lift env (LProj t i) = do t' <- lift env t                           return (LProj t' i) lift env (LCon loc i n args) = do args' <- mapM (lift env) args@@ -229,11 +261,11 @@     -- Keep track of 'updatable' names in the state, i.e. names whose heap     -- entry may be reused, along with the arity which was there     findUp :: LExp -> State [(Name, Int)] LExp-    findUp (LApp t (LV (Glob n)) as)+    findUp (LApp t (LV n) as)        | Just (LConstructor _ i ar) <- lookupCtxtExact n defs,          ar == length as           = findUp (LCon Nothing i n as)-    findUp (LV (Glob n))+    findUp (LV n)        | Just (LConstructor _ i 0) <- lookupCtxtExact n defs           = return $ LCon Nothing i n [] -- nullary cons are global, no need to update     findUp (LApp t f as) = LApp t <$> findUp f <*> mapM findUp as@@ -253,7 +285,7 @@            = LForeign t s <$> mapM (\ (t, e) -> do e' <- findUp e                                                    return (t, e')) es     findUp (LOp o es) = LOp o <$> mapM findUp es-    findUp (LCase Updatable e@(LV (Glob n)) as)+    findUp (LCase Updatable e@(LV n) as)            = LCase Updatable e <$> mapM (doUpAlt n) as     findUp (LCase t e as)            = LCase t <$> findUp e <*> mapM findUpAlt as@@ -277,7 +309,7 @@      findVar _ [] i = return Nothing     findVar acc ((n, l) : ns) i | l == i = do put (reverse acc ++ ns)-                                              return (Just (Glob n))+                                              return (Just n)     findVar acc (n : ns) i = findVar (n : acc) ns i  @@ -287,7 +319,7 @@               | otherwise = []  usedIn :: [Name] -> LExp -> [Name]-usedIn env (LV (Glob n)) = usedArg env n+usedIn env (LV n) = usedArg env n usedIn env (LApp _ e args) = usedIn env e ++ concatMap (usedIn env) args usedIn env (LLazyApp n args) = concatMap (usedIn env) args ++ usedArg env n usedIn env (LLazyExp e) = usedIn env e@@ -297,7 +329,7 @@ usedIn env (LCon v i n args) = let rest = concatMap (usedIn env) args in                                    case v of                                       Nothing -> rest-                                      Just (Glob n) -> usedArg env n ++ rest+                                      Just n -> usedArg env n ++ rest usedIn env (LProj t i) = usedIn env t usedIn env (LCase up e alts) = usedIn env e ++ concatMap (usedInA env) alts   where usedInA env (LConCase i n ns e) = usedIn env e@@ -308,7 +340,7 @@ usedIn env _ = []  lsubst :: Name -> LExp -> LExp -> LExp-lsubst n new (LV (Glob x)) | n == x = new+lsubst n new (LV x) | n == x = new lsubst n new (LApp t e args) = let e' = lsubst n new e                                    args' = map (lsubst n new) args in                                    LApp t e' args'@@ -331,10 +363,38 @@                                     LCase t e' alts' lsubst n new tm = tm +rename :: [(Name, Name)] -> LExp -> LExp+rename ns tm@(LV x)+   = case lookup x ns of+          Just n -> LV n+          _ -> tm+rename ns (LApp t e args)+    = let e' = rename ns e+          args' = map (rename ns) args in+          LApp t e' args'+rename ns (LLazyApp fn args)+    = let args' = map (rename ns) args in+          LLazyApp fn args'+rename ns (LLazyExp e) = LLazyExp (rename ns e)+rename ns (LForce e) = LForce (rename ns e)+rename ns (LLet v val sc) = LLet v (rename ns val) (rename ns sc)+rename ns (LLam args sc) = LLam args (rename ns sc)+rename ns (LProj e i) = LProj (rename ns e) i+rename ns (LCon lv t cn args) = let args' = map (rename ns) args in+                                    LCon lv t cn args'+rename ns (LOp op args) = let args' = map (rename ns) args in+                              LOp op args'+rename ns (LForeign fd rd args)+     = let args' = map (\(d, a) -> (d, rename ns a)) args in+           LForeign fd rd args'+rename ns (LCase t e alts) = let e' = rename ns e+                                 alts' = map (fmap (rename ns)) alts in+                                 LCase t e' alts'+rename ns tm = tm+ instance Show LExp where    show e = show' [] "" e where-     show' env ind (LV (Loc i)) = env!!i-     show' env ind (LV (Glob n)) = show n+     show' env ind (LV n) = show n       show' env ind (LLazyApp e args)         = show e ++ "|(" ++ showSep ", " (map (show' env ind) args) ++")"@@ -349,8 +409,8 @@             ++ " in " ++ show' (env ++ [show n]) ind e       show' env ind (LLam args e)-        = "\\ " ++ showSep "," (map show args)-            ++ " => " ++ show' (env ++ (map show args)) ind e+        = "(\\ " ++ showSep "," (map show args)+            ++ " => " ++ show' (env ++ (map show args)) ind e ++ ") "       show' env ind (LProj t i) = show t ++ "!" ++ show i @@ -360,7 +420,7 @@              atloc (Just l) = "@" ++ show (LV l) ++ ":"       show' env ind (LCase up e alts)-        = "case" ++ update ++ show' env ind e ++ " of \n" ++ fmt alts+        = "case" ++ update ++ "(" ++ show' env ind e ++ ") of \n" ++ fmt alts        where          update = case up of                        Shared -> " "
src/IRTS/LangOpts.hs view
@@ -1,21 +1,21 @@ {-| Module      : IRTS.LangOpts Description : Transformations to apply to Idris' IR.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -} {-# LANGUAGE DeriveFunctor, PatternGuards #-} -module IRTS.LangOpts where+module IRTS.LangOpts(inlineAll) where  import Idris.Core.CaseTree import Idris.Core.TT import IRTS.Lang -import Control.Applicative hiding (Const) import Control.Monad.State hiding (lift) import Data.List+ import Debug.Trace  inlineAll :: [(Name, LDecl)] -> [(Name, LDecl)]@@ -35,53 +35,264 @@ doInline :: LDefs -> LDecl -> LDecl doInline defs d@(LConstructor _ _ _) = d doInline defs (LFun opts topn args exp)-      = let res = evalState (inlineWith [topn] (map (\n -> (n, LV (Glob n))) args) exp) 0 in-            LFun opts topn args res+      = let inl = evalState (eval [] initEnv [topn] defs exp)+                             (length args)+            -- do some case floating, which might arise as a result+            -- then, eta contract+            res = eta $ caseFloats 10 inl in+            case res of+                 LLam args' body -> LFun opts topn (map snd initNames ++ args') body+                 _ -> LFun opts topn (map snd initNames) res   where-    inlineWith :: [Name] -> [(Name, LExp)] -> LExp -> State Int LExp-    inlineWith done env var@(LV (Glob n))-                                     = case lookup n env of-                                            Just t -> return t-                                            Nothing -> return var-    inlineWith done env (LLazyApp n es) = LLazyApp n <$> (mapM (inlineWith done env) es)-    inlineWith done env (LForce e) = LForce <$> inlineWith done env e-    inlineWith done env (LLazyExp e) = LLazyExp <$> inlineWith done env e-    -- Extend the environment for Let and Lam so that bound names aren't-    -- expanded with any top level argument definitions they shadow-    inlineWith done env (LLet n val sc)-       = do n' <- nextN-            LLet n' <$> inlineWith done env val <*>-                        inlineWith done ((n, LV (Glob n')) : env) sc-    inlineWith done env (LLam args sc)-       = do ns' <- mapM (\n -> do n' <- nextN-                                  return (n, n')) args-            LLam (map snd ns') <$>-                 inlineWith done (map (\ (n,n') -> (n, LV (Glob n'))) ns' ++ env) sc-    inlineWith done env (LProj exp i) = LProj <$> inlineWith done env exp <*> return i-    inlineWith done env (LCon loc i n es)-       = LCon loc i n <$> mapM (inlineWith done env) es-    inlineWith done env (LCase ty e alts)-       = LCase ty <$> inlineWith done env e <*> mapM (inlineWithAlt done env) alts-    inlineWith done env (LOp f es) = LOp f <$> mapM (inlineWith done env) es-    -- the interesting case!-    inlineWith done env (LApp t (LV (Glob n)) es)-       | n `notElem` done,-         [LFun opts _ args body] <- lookupCtxt n defs,-         Inline `elem` opts,-         length es == length args-           = do es' <- mapM (inlineWith done env) es-                inlineWith (n : done) (zip args es' ++ env) body-    inlineWith done env (LApp t f es)-       = LApp t <$> inlineWith done env f <*> mapM (inlineWith done env) es-    inlineWith done env (LForeign t s args)-       = LForeign t s <$> mapM (\(t, e) -> do e' <- inlineWith done env e-                                              return (t, e')) args-    inlineWith done env t = return t+    caseFloats 0 tm = tm+    caseFloats n tm+        = let res = caseFloat tm in+              if res == tm+                 then res+                 else caseFloats (n-1) res -    inlineWithAlt done env (LConCase i n es rhs)-       = do ns' <- mapM (\n -> do n' <- nextN-                                  return (n, n')) es-            LConCase i n (map snd ns') <$>-              inlineWith done (map (\ (n,n') -> (n, LV (Glob n'))) ns' ++ env) rhs-    inlineWithAlt done env (LConstCase c e) = LConstCase c <$> inlineWith done env e-    inlineWithAlt done env (LDefaultCase e) = LDefaultCase <$> inlineWith done env e+    initNames = zipWith (\n i -> (n, newn n i)) args [0..]+    initEnv = map (\(n, n') -> (n, LV n')) initNames+    newn (UN n) i = MN i n+    newn _ i = sMN i "arg"++unload :: [LExp] -> LExp -> LExp+unload [] e = e+unload stk (LApp tc e args) = LApp tc e (args ++ stk)+unload stk e = LApp False e stk++takeStk :: [(Name, LExp)] -> [Name] -> [LExp] ->+           ([(Name, LExp)], [Name], [LExp])+takeStk env (a : args) (v : stk) = takeStk ((a, v) : env) args stk+takeStk env args stk = (env, args, stk)++eval :: [LExp] -> [(Name, LExp)] -> [Name] -> LDefs -> LExp -> State Int LExp+eval stk env rec defs (LLazyApp n es)+    = unload stk <$> LLazyApp n <$> (mapM (eval [] env rec defs) es)+eval stk env rec defs (LForce e)+    = do e' <- eval [] env rec defs e+         case e' of+              LLazyExp forced -> return $ unload stk forced+              LLazyApp n es -> return $ unload stk (LApp False (LV n) es)+              _ -> return (unload stk (LForce e'))+eval stk env rec defs (LLazyExp e)+    = unload stk <$> LLazyExp <$> eval [] env rec defs e+-- Special case for io_bind, because it needs to keep executing the first+-- action, and is worth inlining to avoid the thunk+eval [] env rec defs (LApp t (LV n) [_, _, _, act, (LLam [arg] k)])+    | n == sUN "io_bind"+    = do w <- nextN+         let env' = (w, LV w) : env+         act' <- eval [] env' rec defs (LApp False act [LV w])+         argn <- nextN+         k' <- eval [] ((arg, LV argn) : env') rec defs (LApp False k [LV w])+         return $ LLam [w] (LLet argn act' k')+eval (world : stk) env rec defs (LApp t (LV n) [_, _, _, act, (LLam [arg] k)])+    | n == sUN "io_bind"+    = do act' <- eval [] env rec defs (LApp False act [world])+         argn <- nextN+         k' <- eval stk ((arg, LV argn) : env) rec defs (LApp False k [world])+         return $ LLet argn act' k'++eval stk env rec defs (LApp t f es)+    = do es' <- mapM (eval [] env rec defs) es+         eval (es' ++ stk) env rec defs f+eval stk env rec defs (LLet n val sc)+    = do n' <- nextN+         LLet n' <$> eval [] env rec defs val+                 <*> eval stk ((n, LV n') : env) rec defs sc+eval stk env rec defs (LProj exp i)+    = unload stk <$> (LProj <$> eval [] env rec defs exp <*> return i)+eval stk env rec defs (LCon loc i n es)+    = unload stk <$> (LCon loc i n <$> mapM (eval [] env rec defs) es)+eval stk env rec defs (LCase ty e alts)+    = do alts' <- mapM (evalAlt stk env rec defs) alts+         e' <- eval [] env rec defs e+         -- If they're all lambdas, bind the lambda at the top+         let prefix = getLams (map getRHS alts')+         case prefix of+              [] -> return $ conOpt $ LCase ty e' (replaceInAlts e' alts')+              args -> do alts_red <- mapM (dropArgs args) alts'+                         return $ LLam args+                            (conOpt (LCase ty e' (replaceInAlts e' alts_red)))+eval stk env rec defs (LOp f es)+    = unload stk <$> LOp f <$> mapM (eval [] env rec defs) es+eval stk env rec defs (LForeign t s args)+    = unload stk <$>+        LForeign t s <$> mapM (\(t, e) -> do e' <- eval [] env rec defs e+                                             return (t, e')) args+-- save the interesting cases for the end:+-- lambdas, and names to reduce+eval stk env rec defs (LLam args sc)+    | (env', args', stk') <- takeStk env args stk+        = case args' of+               [] -> eval stk' env' rec defs sc+               as -> do ns' <- mapM (\n -> do n' <- nextN+                                              return (n, n')) args'+                        unload stk' <$> LLam (map snd ns') <$>+                            eval [] (map (\ (n, n') -> (n, LV n')) ns' ++ env')+                                    rec defs sc+eval stk env rec defs var@(LV n)+    = case lookup n env of+           Just t+               | t /= LV n && n `notElem` rec ->+                       eval stk env (n : rec) defs t+               | otherwise -> return (unload stk t)+           Nothing+               | n `notElem` rec,+                 Just (LFun opts _ args body) <- lookupCtxtExact n defs,+                 Inline `elem` opts ->+                         apply stk env (n : rec) defs var args body+               | Just (LConstructor n t a) <- lookupCtxtExact n defs ->+                         return (LCon Nothing t n stk)+               | otherwise -> return (unload stk var)+eval stk env rec defs t = return (unload stk t)++evalAlt stk env rec defs (LConCase i n es rhs)+    = do ns' <- mapM (\n -> do n' <- nextN+                               return (n, n')) es+         LConCase i n (map snd ns') <$>+            eval stk (map (\ (n, n') -> (n, LV n')) ns' ++ env) rec defs rhs+evalAlt stk env rec defs (LConstCase c e)+    = LConstCase c <$> eval stk env rec defs e+evalAlt stk env rec defs (LDefaultCase e)+    = LDefaultCase <$> eval stk env rec defs e++apply :: [LExp] -> [(Name, LExp)] -> [Name] -> LDefs -> LExp ->+         [Name] -> LExp -> State Int LExp+apply stk env rec defs var args body+    = eval stk env rec defs (LLam args body)++dropArgs :: [Name] -> LAlt -> State Int LAlt+dropArgs as (LConCase i n es (LLam args rhs))+    = do let old = take (length as) args+         rhs' <- eval [] (zipWith (\ o n -> (o, LV n)) old as) [] emptyContext rhs+         return (LConCase i n es rhs')+dropArgs as (LConstCase c (LLam args rhs))+    = do let old = take (length as) args+         rhs' <- eval [] (zipWith (\ o n -> (o, LV n)) old as) [] emptyContext rhs+         return (LConstCase c rhs')+dropArgs as (LDefaultCase (LLam args rhs))+    = do let old = take (length as) args+         rhs' <- eval [] (zipWith (\ o n -> (o, LV n)) old as) [] emptyContext rhs+         return (LDefaultCase rhs')++caseFloat :: LExp -> LExp+caseFloat (LApp tc e es) = LApp tc (caseFloat e) (map caseFloat es)+caseFloat (LLazyExp e) = LLazyExp (caseFloat e)+caseFloat (LForce e) = LForce (caseFloat e)+caseFloat (LCon up i n es) = LCon up i n (map caseFloat es)+caseFloat (LOp f es) = LOp f (map caseFloat es)+caseFloat (LLam ns sc) = LLam ns (caseFloat sc)+caseFloat (LLet v val sc) = LLet v (caseFloat val) (caseFloat sc)+caseFloat (LCase _ (LCase ct exp alts) alts')+    | all conRHS alts || length alts == 1+    = conOpt $ replaceInCase (LCase ct (caseFloat exp) (map (updateWith alts') alts))+  where+    conRHS (LConCase _ _ _ (LCon _ _ _ _)) = True+    conRHS (LConstCase _ (LCon _ _ _ _)) = True+    conRHS (LDefaultCase (LCon _ _ _ _)) = True+    conRHS _ = False++    updateWith alts (LConCase i n es rhs) =+        LConCase i n es (caseFloat (conOpt (LCase Shared (caseFloat rhs) alts)))+    updateWith alts (LConstCase c rhs) =+        LConstCase c (caseFloat (conOpt (LCase Shared (caseFloat rhs) alts)))+    updateWith alts (LDefaultCase rhs) =+        LDefaultCase (caseFloat (conOpt (LCase Shared (caseFloat rhs) alts)))++caseFloat (LCase ct exp alts')+    = conOpt $ replaceInCase (LCase ct (caseFloat exp) (map cfAlt alts'))+  where+    cfAlt (LConCase i n es rhs) = LConCase i n es (caseFloat rhs)+    cfAlt (LConstCase c rhs) = LConstCase c (caseFloat rhs)+    cfAlt (LDefaultCase rhs) = LDefaultCase (caseFloat rhs)+caseFloat exp = exp++-- Case of constructor+conOpt :: LExp -> LExp+conOpt (LCase ct (LCon _ t n args) alts)+    = pickAlt n args alts+  where+    pickAlt n args (LConCase i n' es rhs : as) | n == n'+        = substAll (zip es args) rhs+    pickAlt _ _ (LDefaultCase rhs : as) = rhs+    pickAlt n args (_ : as) = pickAlt n args as+    pickAlt n args [] = error "Can't happen pickAlt - impossible case found"++    substAll [] rhs = rhs+    substAll ((n, tm) : ss) rhs = lsubst n tm (substAll ss rhs)+conOpt tm = tm++replaceInCase :: LExp -> LExp+replaceInCase (LCase ty e alts)+    = LCase ty e (replaceInAlts e alts)+replaceInCase exp = exp++replaceInAlts :: LExp -> [LAlt] -> [LAlt]+replaceInAlts exp alts = dropDups $ concatMap (replaceInAlt exp) alts++-- Drop overlapping case (arising from case merging of overlapping+-- patterns)+dropDups (alt@(LConCase _ i n ns) : alts)+    = alt : dropDups (filter (notTag i) alts)+  where+    notTag i (LConCase _ j n ns) = i /= j+    notTag _ _ = True+dropDups (c : alts) = c : dropDups alts+dropDups [] = []+++replaceInAlt :: LExp -> LAlt -> [LAlt]+-- In an alternative, if the case appears on the right hand side, replace+-- it with the given expression, to preserve sharing+replaceInAlt exp@(LV _) (LConCase i con args rhs)+    = [LConCase i con args $+          replaceExp (LCon Nothing i con (map LV args)) exp rhs]+-- if a default case inspects the same variable as the case it's in,+-- remove the inspection and replace with the alternatives+-- (i.e. merge the inner case block)+replaceInAlt exp@(LV var) (LDefaultCase (LCase ty (LV var') alts))+    | var == var' = alts+replaceInAlt exp a = [a]++replaceExp :: LExp -> LExp -> LExp -> LExp+replaceExp (LCon _ t n args) new (LCon _ t' n' args')+    | n == n' && args == args' = new+replaceExp (LCon _ t n args) new (LApp _ (LV n') args')+    | n == n' && args == args' = new+replaceExp old new tm = tm++-- dropArgs as (LConstCase c rhs) = LConstCase c (dropRHS as rhs)+-- dropArgs as (LDefaultCase rhs) = LDefaultCase (dropRHS as rhs)++getRHS (LConCase i n es rhs) = rhs+getRHS (LConstCase _ rhs) = rhs+getRHS (LDefaultCase rhs) = rhs++getLams [] = []+getLams (LLam args tm : cs) = getLamPrefix args cs+getLams _ = []++getLamPrefix as [] = as+getLamPrefix as (LLam args tm : cs)+    | length args < length as = getLamPrefix args cs+    | otherwise = getLamPrefix as cs+getLamPrefix as (_ : cs) = []++-- eta contract ('\x -> f x' can just be compiled as 'f' when f is local)+eta :: LExp -> LExp+eta (LApp tc a es) = LApp tc (eta a) (map eta es)+eta (LLazyApp n es) = LLazyApp n (map eta es)+eta (LLazyExp e) = LLazyExp (eta e)+eta (LForce e) = LForce (eta e)+eta (LLet n val sc) = LLet n (eta val) (eta sc)+eta (LLam args (LApp tc f args'))+    | args' == map LV args = eta f+eta (LLam args e) = LLam args (eta e)+eta (LProj e i) = LProj (eta e) i+eta (LCon a t n es) = LCon a t n (map eta es)+eta (LCase ct e alts) = LCase ct (eta e) (map (fmap eta) alts)+eta (LOp f es) = LOp f (map eta es)+eta tm = tm+
src/IRTS/Portable.hs view
@@ -1,7 +1,7 @@ {-| Module      : IRTS.Portable Description : Serialise Idris' IR to JSON.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -14,12 +14,10 @@ import IRTS.Bytecode import IRTS.CodegenCommon import IRTS.Defunctionalise-import IRTS.Lang import IRTS.Simplified  import Data.Aeson import qualified Data.ByteString.Lazy as B-import qualified Data.Text as T import System.IO  data CodegenFile = CGFile {@@ -186,6 +184,7 @@     toJSON LFASin = object ["LFASin" .= Null]     toJSON LFACos = object ["LFACos" .= Null]     toJSON LFATan = object ["LFATan" .= Null]+    toJSON LFATan2 = object ["LFATan2" .= Null]     toJSON LFSqrt = object ["LFSqrt" .= Null]     toJSON LFFloor = object ["LFFloor" .= Null]     toJSON LFCeil = object ["LFCeil" .= Null]@@ -322,7 +321,7 @@ instance (ToJSON t) => ToJSON (Binder t) where     toJSON (Lam rc bty) = object ["Lam" .= (rc, bty)]     toJSON (Pi c i t k) = object ["Pi" .= (c, i, t, k)]-    toJSON (Let t v) = object ["Let" .= (t, v)]+    toJSON (Let rc t v) = object ["Let" .= (t, v)]     toJSON (NLet t v) = object ["NLet" .= (t, v)]     toJSON (Hole t) = object ["Hole" .= (t)]     toJSON (GHole l ns t) = object ["GHole" .= (l, ns, t)]
src/IRTS/Simplified.hs view
@@ -1,7 +1,7 @@ {-| Module      : IRTS.Simplified Description : Simplified expressions, where functions/constructors can only be applied to variables.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -10,12 +10,9 @@  import Idris.Core.CaseTree import Idris.Core.TT-import Idris.Core.Typecheck import IRTS.Defunctionalise  import Control.Monad.State-import Data.Maybe-import Debug.Trace  data SExp = SV LVar           | SApp Bool Name [LVar]@@ -53,8 +50,7 @@ -- The boolean parameter indicates whether the expression is at tail -- call position. simplify :: Bool -> DExp -> State (DDefs, Int) SExp-simplify tl (DV (Loc i)) = return (SV (Loc i))-simplify tl (DV (Glob x))+simplify tl (DV x)     = do ctxt <- ldefs          case lookupCtxtExact x ctxt of               Just (DConstructor _ t 0) -> return $ SCon Nothing t x []@@ -68,7 +64,7 @@                               return (SLet (Glob n) v' e') simplify tl (DUpdate n e) = do e' <- simplify False e                                return (SUpdate (Glob n) e')-simplify tl (DC loc i n args) = bindExprs args (SCon loc i n)+simplify tl (DC loc i n args) = bindExprs args (SCon (Glob <$> loc) i n) simplify tl (DProj t i) = bindExpr t (\var -> SProj var i) simplify tl (DCase up e alts)     = do alts' <- mapM (sAlt tl) alts@@ -97,12 +93,11 @@ bindExpr e f = bindExprM e (return . f)  bindExprM :: DExp -> (LVar -> State (DDefs, Int) SExp) -> State (DDefs, Int) SExp-bindExprM (DV (Glob x)) f+bindExprM (DV x) f     = do ctxt <- ldefs          case lookupCtxtExact x ctxt of               Just (DConstructor _ t 0) -> bindExprM (DC Nothing t x []) f               _ -> f (Glob x)-bindExprM (DV var) f = f var bindExprM e f =     do e' <- simplify False e        var <- freshVar
src/IRTS/System.hs view
@@ -1,7 +1,7 @@ {-| Module      : IRTS.System Description : Utilities for interacting with the System.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}
src/Idris/ASTUtils.hs view
@@ -2,7 +2,7 @@ {-| Module      : Idris.ASTUtils Description : This implements just a few basic lens-like concepts to ease state updates. Similar to fclabels in approach, just without the extra dependency.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. @@ -52,7 +52,6 @@  import Prelude hiding (id, (.)) -import Control.Applicative import Control.Category import Control.Monad.State.Class import Data.Maybe
src/Idris/AbsSyntax.hs view
@@ -1,12 +1,13 @@ {-| Module      : Idris.AbsSyntax Description : Provides Idris' core data definitions and utility code.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}  {-# LANGUAGE DeriveFunctor, FlexibleContexts, PatternGuards #-}+{-# OPTIONS_GHC -fwarn-unused-imports #-}  module Idris.AbsSyntax(     module Idris.AbsSyntax@@ -39,7 +40,6 @@  import Data.Generics.Uniplate.Data (descend, descendM) -import Debug.Trace import Util.DynamicLinker import Util.Pretty import Util.System@@ -58,19 +58,19 @@ getObjectFiles tgt = do i <- getIState; return (forCodegen tgt $ idris_objs i)  addObjectFile :: Codegen -> FilePath -> Idris ()-addObjectFile tgt f = do i <- getIState; putIState $ i { idris_objs = nub $ (tgt, f) : idris_objs i }+addObjectFile tgt f = do i <- getIState; putIState $ i { idris_objs = nub $ idris_objs i ++ [(tgt, f)] }  getLibs :: Codegen -> Idris [String] getLibs tgt = do i <- getIState; return (forCodegen tgt $ idris_libs i)  addLib :: Codegen -> String -> Idris ()-addLib tgt f = do i <- getIState; putIState $ i { idris_libs = nub $ (tgt, f) : idris_libs i }+addLib tgt f = do i <- getIState; putIState $ i { idris_libs = nub $ idris_libs i ++ [(tgt, f)] }  getFlags :: Codegen -> Idris [String] getFlags tgt = do i <- getIState; return (forCodegen tgt $ idris_cgflags i)  addFlag :: Codegen -> String -> Idris ()-addFlag tgt f = do i <- getIState; putIState $ i { idris_cgflags = nub $ (tgt, f) : idris_cgflags i }+addFlag tgt f = do i <- getIState; putIState $ i { idris_cgflags = nub $ idris_cgflags i ++ [(tgt, f)] }  addDyLib :: [String] -> Idris (Either DynamicLib String) addDyLib libs = do i <- getIState@@ -143,6 +143,12 @@                     idris_language_extensions = e : idris_language_extensions i                   } +dropLangExt :: LanguageExt -> Idris ()+dropLangExt e = do i <- getIState+                   putIState $ i {+                     idris_language_extensions = idris_language_extensions i \\ [e]+                   }+ -- | Transforms are organised by the function being applied on the lhs -- of the transform, to make looking up appropriate transforms quicker addTrans :: Name -> (Term, Term) -> Idris ()@@ -597,7 +603,7 @@ getHdrs tgt = do i <- getIState; return (forCodegen tgt $ idris_hdrs i)  getImported ::  Idris [(FilePath, Bool)]-getImported = do i <- getIState; return (idris_imported i)+getImported = idris_imported `fmap` getIState  setErrSpan :: FC -> Idris () setErrSpan x = do i <- getIState;@@ -1108,6 +1114,14 @@                    let optdirs = opt_importdirs (idris_options i)                    return ("." : reverse optdirs) +-- Like allImportDirs but the dirs that are a prefix of+-- the files path first. This makes it look in the current+-- package first.+rankedImportDirs :: FilePath -> Idris [FilePath]+rankedImportDirs fp = do ids <- allImportDirs+                         let (prefixes, rest) = partition (`isPrefixOf`fp) ids+                         return $ prefixes ++ rest+ addSourceDir :: FilePath -> Idris () addSourceDir fp = do i <- getIState                      let opts = idris_options i@@ -1276,11 +1290,11 @@                = let n' = mkShadow n in -- TODO THINK SHADOWING TacImp?                      PPi (enTacImp 0 p) n' nfc (en 0 t) (en 0 (shadow n n' s))        | otherwise = PPi (enTacImp 0 p) n nfc (en 0 t) (en 0 s)-    en 0 (PLet fc n nfc ty v s)+    en 0 (PLet fc rc n nfc ty v s)        | n `elem` (map fst ps ++ ns)                = let n' = mkShadow n in-                     PLet fc n' nfc (en 0 ty) (en 0 v) (en 0 (shadow n n' s))-       | otherwise = PLet fc n nfc (en 0 ty) (en 0 v) (en 0 s)+                     PLet fc rc n' nfc (en 0 ty) (en 0 v) (en 0 (shadow n n' s))+       | otherwise = PLet fc rc n nfc (en 0 ty) (en 0 v) (en 0 s)     -- FIXME: Should only do this in a type signature!     en 0 (PDPair f hls p (PRef f' fcs n) t r)        | n `elem` (map fst ps ++ ns) && t /= Placeholder@@ -1457,28 +1471,7 @@ -- * if there's a function type, next (2) -- * finally, everything else (3) getPriority :: IState -> PTerm -> Int-getPriority i tm = 1 -- pri tm-  where-    pri (PRef _ _ n) =-        case lookupP n (tt_ctxt i) of-            ((P (DCon _ _ _) _ _):_) -> 1-            ((P (TCon _ _) _ _):_) -> 1-            ((P Ref _ _):_) -> 1-            [] -> 0 -- must be locally bound, if it's not an error...-    pri (PPi _ _ _ x y) = max 5 (max (pri x) (pri y))-    pri (PTrue _ _) = 0-    pri (PRewrite _ _ l r _) = max 1 (max (pri l) (pri r))-    pri (PApp _ f as) = max 1 (max (pri f) (foldr (max . pri . getTm) 0 as))-    pri (PAppBind _ f as) = max 1 (max (pri f) (foldr (max . pri . getTm) 0 as))-    pri (PCase _ f as) = max 1 (max (pri f) (foldr (max . pri . snd) 0 as))-    pri (PTyped l r) = pri l-    pri (PPair _ _ _ l r) = max 1 (max (pri l) (pri r))-    pri (PDPair _ _ _ l t r) = max 1 (max (pri l) (max (pri t) (pri r)))-    pri (PAlternative _ a as) = maximum (map pri as)-    pri (PConstant _ _) = 0-    pri Placeholder = 1-    pri _ = 3-+getPriority i tm = 1  addStatics :: Name -> Term -> PTerm -> Idris () addStatics n tm ptm =@@ -1942,13 +1935,13 @@              else let ty' = ai inpat qq env ds ty                       sc' = ai inpat qq ((n, Just ty):env) ds sc in                       PLam fc n nfc ty' sc'-    ai inpat qq env ds (PLet fc n nfc ty val sc)+    ai inpat qq env ds (PLet fc rc n nfc ty val sc)       = if canBeDConName n (tt_ctxt ist)            then ai inpat qq env ds (PCase fc val [(PRef fc [] n, sc)])            else let ty' = ai inpat qq env ds ty                     val' = ai inpat qq env ds val                     sc' = ai inpat qq ((n, Just ty):env) ds sc in-                    PLet fc n nfc ty' val' sc'+                    PLet fc rc n nfc ty' val' sc'     ai inpat qq env ds (PPi p n nfc ty sc)       = let ty' = ai inpat qq env ds ty             env' = if n `elem` imp_meths then env@@ -2005,9 +1998,6 @@           unqualified (NS _ _) = False           unqualified _ = True -          constructor (TyDecl (DCon _ _ _) _) = True-          constructor _ = False-           conCaf ctxt (n, cia) = (isDConName n ctxt || (qq && isTConName n ctxt)) && allImp cia            vname (UN n) = True -- non qualified@@ -2194,12 +2184,8 @@        -- check will not necessarily fully resolve constructor names,        -- and these bare names will otherwise get in the way of        -- impossbility checking.-       | -- Just fn <- getFn f,-         canBeDConName fn ctxt+       | canBeDConName fn ctxt           = PApp fc f (fmap (fmap su) args)-      where getFn (PRef _ _ fn) = Just fn-            getFn (PApp _ f args) = getFn f-            getFn _ = Nothing     su (PApp fc f args)           = PHidden (PApp fc f args)     su (PAlternative ms b alts)@@ -2256,8 +2242,6 @@                               (ns, ss)         fs _ = ([], []) -        inOne n ns = length (filter id (map (elem n) ns)) == 1-         pos ns ss (PPi p n fc t sc)             | elem n ss = do sc' <- pos ns ss sc                              spos <- get@@ -2367,10 +2351,11 @@     match (PLam _ _ _ t s) (PLam _ _ _ t' s') = do mt <- match' t t'                                                    ms <- match' s s'                                                    return (mt ++ ms)-    match (PLet _ _ _ t ty s) (PLet _ _ _ t' ty' s') = do mt <- match' t t'-                                                          mty <- match' ty ty'-                                                          ms <- match' s s'-                                                          return (mt ++ mty ++ ms)+    match (PLet _ _ _ _ t ty s) (PLet _ _ _ _ t' ty' s')+         = do mt <- match' t t'+              mty <- match' ty ty'+              ms <- match' s s'+              return (mt ++ mty ++ ms)     match (PHidden x) (PHidden y)           | RightOK xs <- match x y = return xs -- to collect variables           | otherwise = return [] -- Otherwise hidden things are unmatchable@@ -2423,8 +2408,8 @@                    PPi p x' fc (sm (x':xs) (substMatch x (PRef emptyFC [] x') t))                                (sm (x':xs) (substMatch x (PRef emptyFC [] x') sc))          | otherwise = PPi p x fc (sm xs t) (sm (x : xs) sc)-    sm xs (PLet fc x xfc val t sc)-         = PLet fc x xfc (sm xs val) (sm xs t) (sm xs sc)+    sm xs (PLet fc rc x xfc val t sc)+         = PLet fc rc x xfc (sm xs val) (sm xs t) (sm xs sc)     sm xs (PApp f x as) = fullApp $ PApp f (sm xs x) (map (fmap (sm xs)) as)     sm xs (PCase f x as) = PCase f (sm xs x) (map (pmap (sm xs)) as)     sm xs (PIfThenElse fc c t f) = PIfThenElse fc (sm xs c) (sm xs t) (sm xs f)@@ -2451,8 +2436,8 @@                             | otherwise = PLam fc x xfc (sm 0 t) sc     sm 0 (PPi p x fc t sc) | n /= x = PPi p x fc (sm 0 t) (sm 0 sc)                          | otherwise = PPi p x fc (sm 0 t) sc-    sm 0 (PLet fc x xfc t v sc) | n /= x = PLet fc x xfc (sm 0 t) (sm 0 v) (sm 0 sc)-                              | otherwise = PLet fc x xfc (sm 0 t) (sm 0 v) sc+    sm 0 (PLet fc rc x xfc t v sc) | n /= x = PLet fc rc x xfc (sm 0 t) (sm 0 v) (sm 0 sc)+                              | otherwise = PLet fc rc x xfc (sm 0 t) (sm 0 v) sc     sm 0 (PApp f x as) = PApp f (sm 0 x) (map (fmap (sm 0)) as)     sm 0 (PAppBind f x as) = PAppBind f (sm 0 x) (map (fmap (sm 0)) as)     sm 0 (PCase f x as) = PCase f (sm 0 x) (map (pmap (sm 0)) as)@@ -2529,7 +2514,7 @@               ty' <- mkUniq 0 nmap ty               sc'' <- mkUniq 0 nmap' sc'               return $! PPi p n' fc ty' sc''-  mkUniq 0 nmap (PLet fc n nfc ty val sc)+  mkUniq 0 nmap (PLet fc rc n nfc ty val sc)          = do env <- get               (n', sc') <-                     if n `S.member` env@@ -2541,7 +2526,7 @@               let nmap' = M.insert n n' nmap               ty' <- mkUniq 0 nmap ty; val' <- mkUniq 0 nmap val               sc'' <- mkUniq 0 nmap' sc'-              return $! PLet fc n' nfc ty' val' sc''+              return $! PLet fc rc n' nfc ty' val' sc''   mkUniq 0 nmap (PApp fc t args)          = do t' <- mkUniq 0 nmap t               args' <- mapM (mkUniqA 0 nmap) args
src/Idris/AbsSyntaxTree.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.AbsSyntaxTree Description : Core data definitions used in Idris.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -46,7 +46,6 @@ import Data.Traversable (Traversable) import Data.Typeable import GHC.Generics (Generic)-import Network.Socket (PortNumber)   data ElabWhat = ETypes | EDefns | EAll@@ -147,6 +146,7 @@   , ppopt_desugarnats :: Bool   , ppopt_pinames     :: Bool -- ^ whether to show names in pi bindings   , ppopt_depth       :: Maybe Int+  , ppopt_displayrig  :: Bool -- ^ whether to display multiplicities in binders   } deriving (Show)  @@ -161,6 +161,7 @@   , ppopt_desugarnats = False   , ppopt_pinames = False   , ppopt_depth = Nothing+  , ppopt_displayrig = False   }  -- | Pretty printing options with the most verbosity.@@ -170,6 +171,7 @@   , ppopt_desugarnats = True   , ppopt_pinames = True   , ppopt_depth = Nothing+  , ppopt_displayrig = False   }  -- | Get pretty printing options from the big options record.@@ -179,6 +181,7 @@   , ppopt_pinames = False   , ppopt_depth = opt_printdepth opt   , ppopt_desugarnats = opt_desugarnats opt+  , ppopt_displayrig = False   }  -- | Get pretty printing options from an idris state record.@@ -266,7 +269,6 @@   , lastParse                    :: Maybe Name   , indent_stack                 :: [Int]   , brace_stack                  :: [Maybe Int]-  , lastTokenSpan                :: Maybe FC                      -- ^ What was the span of the latest token parsed?   , idris_parsedSpan             :: Maybe FC   , hide_list                    :: Ctxt Accessibility   , default_access               :: Accessibility@@ -404,7 +406,7 @@                    emptyContext emptyContext emptyContext emptyContext                    emptyContext                    [] [] [] defaultOpts 6 [] [] [] [] [] emptySyntaxRules [] [] [] [] [] [] []-                   [] [] Nothing [] Nothing [] [] Nothing Nothing emptyContext Private DefaultCheckingPartial [] Nothing [] []+                   [] [] Nothing [] Nothing [] [] Nothing emptyContext Private DefaultCheckingPartial [] Nothing [] []                    (RawOutput stdout) True defaultTheme [] (0, emptyContext) emptyContext M.empty                    AutomaticWidth S.empty S.empty [] [] [] M.empty [] [] []                    emptyContext S.empty M.empty emptyContext initialInteractiveOpts@@ -530,6 +532,8 @@ expl              = Exp [] Dynamic False RigW expl_param        :: Plicity expl_param        = Exp [] Dynamic True RigW+expl_linear       :: Plicity+expl_linear       = Exp [] Dynamic False Rig1  constraint        :: Plicity constraint        = Constraint [] Static RigW@@ -923,17 +927,6 @@   where updateRef (PRef fc fcs f) = PRef fc fcs (updateN ns f)         updateRef t = t --- updateDNs :: [(Name, Name)] -> PDecl -> PDecl--- updateDNs [] t = t--- updateDNs ns (PTy s f n t)    | Just n' <- lookup n ns = PTy s f n' t--- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c)---   where updateCNs ns (PClause n l ts r ds)---             = PClause (updateN ns n) (fmap (updateNs ns) l)---                                      (map (fmap (updateNs ns)) ts)---                                      (fmap (updateNs ns) r)---                                      (map (updateDNs ns) ds)--- updateDNs ns c = c- data PunInfo = IsType              | IsTerm              | TypeOrTerm@@ -950,7 +943,7 @@            | PPatvar FC Name                     -- ^ A pattern variable            | PLam FC Name FC PTerm PTerm         -- ^ A lambda abstraction. Second FC is name span.            | PPi  Plicity Name FC PTerm PTerm    -- ^ (n : t1) -> t2, where the FC is for the precise location of the variable-           | PLet FC Name FC PTerm PTerm PTerm   -- ^ A let binding (second FC is precise name location)+           | PLet FC RigCount Name FC PTerm PTerm PTerm   -- ^ A let binding (second FC is precise name location)            | PTyped PTerm PTerm                  -- ^ Term with explicit type            | PApp FC PTerm [PArg]                -- ^ e.g. IO (), List Char, length x            | PWithApp FC PTerm PTerm             -- ^ Application plus a 'with' argument@@ -1020,7 +1013,7 @@ mapPTermFC f g (PPatvar fc n)                 = PPatvar (g fc) n mapPTermFC f g (PLam fc n fc' t1 t2)          = PLam (f fc) n (g fc') (mapPTermFC f g t1) (mapPTermFC f g t2) mapPTermFC f g (PPi plic n fc t1 t2)          = PPi plic n (g fc) (mapPTermFC f g t1) (mapPTermFC f g t2)-mapPTermFC f g (PLet fc n fc' t1 t2 t3)       = PLet (f fc) n (g fc') (mapPTermFC f g t1) (mapPTermFC f g t2) (mapPTermFC f g t3)+mapPTermFC f g (PLet fc rc n fc' t1 t2 t3)    = PLet (f fc) rc n (g fc') (mapPTermFC f g t1) (mapPTermFC f g t2) (mapPTermFC f g t3) mapPTermFC f g (PTyped t1 t2)                 = PTyped (mapPTermFC f g t1) (mapPTermFC f g t2) mapPTermFC f g (PApp fc t args)               = PApp (f fc) (mapPTermFC f g t) (map (fmap (mapPTermFC f g)) args) mapPTermFC f g (PWithApp fc t arg)            = PWithApp (f fc) (mapPTermFC f g t) (mapPTermFC f g arg)@@ -1047,8 +1040,9 @@         mapPDoFC (DoBind fc n nfc t) = DoBind (f fc) n (g nfc) (mapPTermFC f g t)         mapPDoFC (DoBindP fc t1 t2 alts) =           DoBindP (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (map (\(l,r)-> (mapPTermFC f g l, mapPTermFC f g r)) alts)-        mapPDoFC (DoLet fc n nfc t1 t2) = DoLet (f fc) n (g nfc) (mapPTermFC f g t1) (mapPTermFC f g t2)-        mapPDoFC (DoLetP fc t1 t2) = DoLetP (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2)+        mapPDoFC (DoLet fc rc n nfc t1 t2) = DoLet (f fc) rc n (g nfc) (mapPTermFC f g t1) (mapPTermFC f g t2)+        mapPDoFC (DoLetP fc t1 t2 alts) =+          DoLetP (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (map (\(l,r) -> (mapPTermFC f g l, mapPTermFC f g r)) alts)         mapPDoFC (DoRewrite fc h) = DoRewrite (f fc) (mapPTermFC f g h) mapPTermFC f g (PIdiom fc t)                  = PIdiom (f fc) (mapPTermFC f g t) mapPTermFC f g (PMetavar fc n)                = PMetavar (g fc) n@@ -1074,7 +1068,7 @@ mapPT f t = f (mpt t) where   mpt (PLam fc n nfc t s)     = PLam fc n nfc (mapPT f t) (mapPT f s)   mpt (PPi p n nfc t s)       = PPi p n nfc (mapPT f t) (mapPT f s)-  mpt (PLet fc n nfc ty v s)  = PLet fc n nfc (mapPT f ty) (mapPT f v) (mapPT f s)+  mpt (PLet fc rc n nfc ty v s) = PLet fc rc n nfc (mapPT f ty) (mapPT f v) (mapPT f s)   mpt (PRewrite fc by t s g)  = PRewrite fc by (mapPT f t) (mapPT f s) (fmap (mapPT f) g)   mpt (PApp fc t as)          = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)   mpt (PWithApp fc t a)       = PWithApp fc (mapPT f t) (mapPT f a)@@ -1172,8 +1166,8 @@ data PDo' t = DoExp  FC t             | DoBind FC Name FC t     -- ^ second FC is precise name location             | DoBindP FC t t [(t,t)]-            | DoLet  FC Name FC t t   -- ^ second FC is precise name location-            | DoLetP FC t t+            | DoLet  FC RigCount Name FC t t   -- ^ second FC is precise name location+            | DoLetP FC t t [(t,t)]             | DoRewrite FC t          -- rewrite in do block     deriving (Eq, Ord, Functor, Data, Generic, Typeable) {-!@@ -1184,8 +1178,8 @@   size (DoExp fc t)           = 1 + size fc + size t   size (DoBind fc nm nfc t)   = 1 + size fc + size nm + size nfc + size t   size (DoBindP fc l r alts)  = 1 + size fc + size l  + size r   + size alts-  size (DoLet fc nm nfc l r)  = 1 + size fc + size nm + size l   + size r-  size (DoLetP fc l r)        = 1 + size fc + size l  + size r+  size (DoLet fc rc nm nfc l r)  = 1 + size fc + size nm + size l   + size r+  size (DoLetP fc l r alts)   = 1 + size fc + size l  + size r + size alts   size (DoRewrite fc h)       = 1 + size fc + size h  type PDo = PDo' PTerm@@ -1249,7 +1243,7 @@ highestFC (PPatvar fc _)          = Just fc highestFC (PLam fc _ _ _ _)       = Just fc highestFC (PPi _ _ _ _ _)         = Nothing-highestFC (PLet fc _ _ _ _ _)     = Just fc+highestFC (PLet fc _ _ _ _ _ _)   = Just fc highestFC (PTyped tm ty)          = highestFC tm <|> highestFC ty highestFC (PApp fc _ _)           = Just fc highestFC (PAppBind fc _ _)       = Just fc@@ -1280,8 +1274,8 @@     getDoFC (DoExp fc t)          = fc     getDoFC (DoBind fc nm nfc t)  = fc     getDoFC (DoBindP fc l r alts) = fc-    getDoFC (DoLet fc nm nfc l r) = fc-    getDoFC (DoLetP fc l r)       = fc+    getDoFC (DoLet fc rc nm nfc l r) = fc+    getDoFC (DoLetP fc l r alts)  = fc     getDoFC (DoRewrite fc h)      = fc  highestFC (PIdiom fc _)           = Just fc@@ -1505,7 +1499,7 @@ inferDecl = PDatadecl inferTy primfc                       (PType bi)                       [(emptyDocstring, [], inferCon, primfc, PPi impl (sMN 0 "iType") primfc (PType bi) (-                                                   PPi expl (sMN 0 "ival") primfc (PRef bi [] (sMN 0 "iType"))+                                                   PPi expl_linear (sMN 0 "ival") primfc (PRef bi [] (sMN 0 "iType"))                                                    (PRef bi [] inferTy)), bi, [])] inferOpts = [] @@ -1674,7 +1668,11 @@  -- | Do the right thing for rendering a term in an IState prettyIst ::  IState -> PTerm -> Doc OutputAnnotation-prettyIst ist = pprintPTerm (ppOptionIst ist) [] [] (idris_infixes ist)+prettyIst ist = pprintPTerm opt [] [] (idris_infixes ist)+  where+    opt = if LinearTypes `elem` idris_language_extensions ist+             then (ppOptionIst ist) { ppopt_displayrig = True }+             else ppOptionIst ist  -- | Pretty-print a high-level Idris term in some bindings context -- with infix info.@@ -1688,6 +1686,9 @@   where     startPrec = 0     funcAppPrec = 10+    lbrace = annotate (AnnSyntax "{") (text "{")+    rbrace = annotate (AnnSyntax "}") (text "}")+    percent = annotate (AnnSyntax "%") (text "%")      prettySe :: Maybe Int -> Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation     prettySe d p bnd (PQuote r) =@@ -1700,7 +1701,8 @@     prettySe d p bnd (PLam fc n nfc ty sc) =       let (ns, sc') = getLamNames [n] sc in           depth d . bracket p startPrec . group . align . hang 2 $-          text "\\" <> prettyBindingsOf ns False <+> text "=>" <$>+          (annotate (AnnSyntax "\\") (text "\\"))+          <> prettyBindingsOf ns False <+> text "=>" <$>           prettySe (decD d) startPrec ((n, False):bnd) sc'       where         getLamNames acc (PLam fc n nfc ty sc) = getLamNames (n : acc) sc@@ -1710,16 +1712,16 @@         prettyBindingsOf [n] t = prettyBindingOf n t         prettyBindingsOf (n : ns) t = prettyBindingOf n t <> text "," <+>                                       prettyBindingsOf ns t-    prettySe d p bnd (PLet fc n nfc ty v sc) =+    prettySe d p bnd (PLet fc rc n nfc ty v sc) =       depth d . bracket p startPrec . group . align $       kwd "let" <+> (group . align . hang 2 $ prettyBindingOf n False <+> text "=" <$> prettySe (decD d) startPrec bnd v) </>       kwd "in" <+> (group . align . hang 2 $ prettySe (decD d) startPrec ((n, False):bnd) sc)     prettySe d p bnd (PPi (Exp l s _ rig) n _ ty sc)-      | Rig0 <- rig =+      | Rig0 <- rig, ppopt_displayrig ppo =           depth d . bracket p startPrec . group $           enclose lparen rparen (group . align $ text "0" <+> prettyBindingOf n False <+> colon <+> prettySe (decD d) startPrec bnd ty) <+>           st <> text "->" <$> prettySe (decD d) startPrec ((n, False):bnd) sc-      | Rig1 <- rig =+      | Rig1 <- rig, ppopt_displayrig ppo =           depth d . bracket p startPrec . group $           enclose lparen rparen (group . align $ text "1" <+> prettyBindingOf n False <+> colon <+> prettySe (decD d) startPrec bnd ty) <+>           st <> text "->" <$> prettySe (decD d) startPrec ((n, False):bnd) sc@@ -1740,7 +1742,7 @@          st =           case s of-            Static -> text "%static" <> space+            Static -> percent <> text "static" <> space             _      -> empty     prettySe d p bnd (PPi (Imp l s _ fa _ rig) n _ ty sc)       | ppopt_impl ppo =@@ -1760,7 +1762,7 @@          st =           case s of-            Static -> text "%static" <> space+            Static -> percent <> text "static" <> space             _      -> empty     prettySe d p bnd (PPi (Constraint _ _ rig) n _ ty sc) =       depth d . bracket p startPrec $@@ -1867,7 +1869,7 @@         , kwd "else" <+> prettySe (decD d) startPrec bnd f         ]     prettySe d p bnd (PHidden tm)         = text "." <> prettySe (decD d) funcAppPrec bnd tm-    prettySe d p bnd (PResolveTC _)       = kwd "%implementation"+    prettySe d p bnd (PResolveTC _)       = percent <> kwd "implementation"     prettySe d p bnd (PTrue _ IsType)     = annName unitTy $ text "()"     prettySe d p bnd (PTrue _ IsTerm)     = annName unitCon $ text "()"     prettySe d p bnd (PTrue _ TypeOrTerm) = text "()"@@ -1947,14 +1949,14 @@              ppdo bnd (DoBindP _ _ _ _ : dos) = -- ok because never made by delab                text "no pretty printer for pattern-matching do binding" :                ppdo bnd dos-             ppdo bnd (DoLet _ ln _ ty v : dos) =+             ppdo bnd (DoLet _ _ ln _ ty v : dos) =                (kwd "let" <+> prettyBindingOf ln False <+>                 (if ty /= Placeholder                    then colon <+> prettySe (decD d) startPrec bnd ty <+> text "="                    else text "=") <+>                 group (align (hang 2 (prettySe (decD d) startPrec bnd v)))) :                ppdo ((ln, False):bnd) dos-             ppdo bnd (DoLetP _ _ _ : dos) = -- ok because never made by delab+             ppdo bnd (DoLetP _ _ _ _ : dos) = -- ok because never made by delab                text "no pretty printer for pattern-matching do binding" :                ppdo bnd dos              ppdo bnd (DoRewrite _ _ : dos) = -- ok because never made by delab@@ -1972,7 +1974,7 @@             end = if res then "}" else "}}"     prettySe d p bnd (PRunElab _ tm _)        =       bracket p funcAppPrec . group . align . hang 2 $-      text "%runElab" <$>+      (percent <> text "runElab") <$>       prettySe (decD d) funcAppPrec bnd tm     prettySe d p bnd (PConstSugar fc tm)      = prettySe d p bnd tm -- should never occur, but harmless     prettySe d p bnd _                        = text "missing pretty-printer for term"@@ -2201,7 +2203,6 @@           showbasic (MN i s)  = str s           showbasic (NS n s)  = showSep "." (map str (reverse s)) ++ "." ++ showbasic n           showbasic (SN s)    = show s-          fst3 (x, _, _) = x           colourise n t = let ctxt' = fmap tt_ctxt ist in                           case ctxt' of                             Nothing -> name@@ -2236,7 +2237,7 @@   size (PRef fc _ name)               = size name   size (PLam fc name _ ty bdy)        = 1 + size ty + size bdy   size (PPi plicity name fc ty bdy)   = 1 + size ty + size fc + size bdy-  size (PLet fc name nfc ty def bdy)  = 1 + size ty + size def + size bdy+  size (PLet fc _ name nfc ty def bdy) = 1 + size ty + size def + size bdy   size (PTyped trm ty)                = 1 + size trm + size ty   size (PApp fc name args)            = 1 + size args   size (PAppBind fc name args)        = 1 + size args@@ -2282,7 +2283,7 @@     ni 0 env (PIfThenElse _ c t f)    = ni 0 env c ++ ni 0 env t ++ ni 0 env f     ni 0 env (PLam fc n _ ty sc)      = ni 0 env ty ++ ni 0 (n:env) sc     ni 0 env (PPi p n _ ty sc)        = niTacImp 0 env p ++ ni 0 env ty ++ ni 0 (n:env) sc-    ni 0 env (PLet _ n _ ty val sc)   = ni 0 env ty ++ ni 0 env val ++ ni 0 (n:env) sc+    ni 0 env (PLet _ _ n _ ty val sc) = ni 0 env ty ++ ni 0 env val ++ ni 0 (n:env) sc     ni 0 env (PHidden tm)             = ni 0 env tm     ni 0 env (PRewrite _ _ l r _)     = ni 0 env l ++ ni 0 env r     ni 0 env (PTyped l r)             = ni 0 env l ++ ni 0 env r@@ -2313,7 +2314,7 @@     ni 0 set (PCase _ c os)             = niTms 0 (ni 0 set c) (map snd os)     ni 0 set (PIfThenElse _ c t f)      = niTms 0 set [c, t, f]     ni 0 set (PLam fc n _ ty sc)        = S.insert n $ ni 0 (ni 0 set ty) sc-    ni 0 set (PLet fc n nfc ty val sc)  = S.insert n $ ni 0 (ni 0 (ni 0 set ty) val) sc+    ni 0 set (PLet fc rc n nfc ty val sc) = S.insert n $ ni 0 (ni 0 (ni 0 set ty) val) sc     ni 0 set (PPi p n _ ty sc)          = niTacImp 0 (S.insert n $ ni 0 (ni 0 set ty) sc) p     ni 0 set (PRewrite _ _ l r _)       = ni 0 (ni 0 set l) r     ni 0 set (PTyped l r)               = ni 0 (ni 0 set l) r@@ -2349,20 +2350,6 @@     addFn n = do (imps, fns) <- get                  put (imps, n: fns) -    notCAF []                 = False-    notCAF (PExp _ _ _ _ : _) = True-    notCAF (_ : xs)           = notCAF xs--    notHidden (n, _) = case getAccessibility n of-                            Hidden  -> False-                            Private -> False-                            _       -> True--    getAccessibility n-             = case lookupDefAccExact n False (tt_ctxt ist) of-                    Just (n,t)  -> t-                    _           -> Public-     ni 0 env (PRef _ _ n@(NS _ _))         | not (n `elem` env)           -- Never implicitly bind if there's a namespace@@ -2391,7 +2378,7 @@     ni 0 env (PIfThenElse _ c t f)            = mapM_ (ni 0 env) [c, t, f]     ni 0 env (PLam fc n _ ty sc)              = do ni 0 env ty; ni 0 (n:env) sc     ni 0 env (PPi p n _ ty sc)                = do ni 0 env ty; ni 0 (n:env) sc-    ni 0 env (PLet fc n _ ty val sc)          = do ni 0 env ty;+    ni 0 env (PLet fc rc n _ ty val sc)       = do ni 0 env ty;                                                    ni 0 env val; ni 0 (n:env) sc     ni 0 env (PRewrite _ _ l r _)             = do ni 0 env l; ni 0 env r     ni 0 env (PTyped l r)                     = do ni 0 env l; ni 0 env r
src/Idris/Apropos.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Apropos Description : Search loaded Idris code and named modules for things.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -11,7 +11,7 @@ import Idris.AbsSyntax import Idris.Core.Evaluate (Def(..), ctxtAlist) import Idris.Core.TT (Binder(..), Const(..), Name(..), NameType(..), TT(..),-                      Type, lookupCtxtExact, toAlist)+                      toAlist) import Idris.Docstrings (DocTerm, Docstring, containsText)  import Data.List (intersperse, nub, nubBy)@@ -75,7 +75,7 @@ instance Apropos (Binder (TT Name)) where   isApropos str (Lam _ ty)    = str == T.pack "\\" || isApropos str ty   isApropos str (Pi _ _ ty _) = str == T.pack "->" || isApropos str ty-  isApropos str (Let ty val)  = str == T.pack "let" || isApropos str ty || isApropos str val+  isApropos str (Let _ ty val)  = str == T.pack "let" || isApropos str ty || isApropos str val   isApropos str (NLet ty val) = str == T.pack "let" || isApropos str ty || isApropos str val   isApropos str _             = False -- these shouldn't occur in defined libraries @@ -104,9 +104,3 @@  instance (Apropos a) => Apropos [a] where   isApropos str xs = any (isApropos str) xs--defType :: Def -> Type-defType (Function t _) = t-defType (TyDecl _ t) = t-defType (Operator t _ _) = t-defType (CaseOp _ t _ _ _ _) = t
src/Idris/CaseSplit.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.CaseSplit Description : Module to provide case split functionality.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. 
src/Idris/Chaser.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Chaser Description : Module chaser to determine cycles and import modules.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -16,19 +16,15 @@ import Idris.AbsSyntax import Idris.Core.TT import Idris.Error-import Idris.IBC import Idris.Imports import Idris.Parser import Idris.Unlit  import Control.Monad.State-import Control.Monad.Trans import Data.List import Data.Time.Clock-import Debug.Trace import System.Directory-import System.FilePath-import Util.System (readSource, writeSource)+import Util.System (readSource)  data ModuleTree = MTree { mod_path :: IFileType,                           mod_needsRecheck :: Bool,@@ -36,10 +32,18 @@                           mod_deps :: [ModuleTree] }   deriving Show -latest :: UTCTime -> [ModuleTree] -> UTCTime-latest tm [] = tm-latest tm (m : ms) = latest (max tm (mod_time m)) (ms ++ mod_deps m)+latest :: UTCTime -> [IFileType] -> [ModuleTree] -> UTCTime+latest tm done [] = tm+latest tm done (m : ms)+    | mod_path m `elem` done = latest tm done ms+    | otherwise = latest (max tm (mod_time m)) (mod_path m : done)+                         (ms ++ mod_deps m) +modName :: IFileType -> String+modName (IDR fp) = fp+modName (LIDR fp) = fp+modName (IBC fp src) = modName src+ -- | Given a module tree, return the list of files to be loaded. If -- any module has a descendent which needs reloading, return its -- source, otherwise return the IBC@@ -50,20 +54,17 @@    modList (m : ms) = do modTree [] m; modList ms     modTree path (MTree p rechk tm deps)-           = do let file = chkReload rechk p-                -- Needs rechecking if 'rechk' is true, or if any of the-                -- modification times in 'deps' are later than tm-                let depMod = latest tm deps-                let needsRechk = rechk || depMod > tm--                st <- get-                if needsRechk then put $ nub (getSrc file : updateToSrc path st)-                              else put $ nub (file : st)---                 when (not (ibc p) || rechk) $-                mapM_ (modTree (getSrc p : path)) deps+       = do let file = chkReload rechk p+            -- Needs rechecking if 'rechk' is true, or if any of the+            -- modification times in 'deps' are later than tm+            let depMod = latest tm [] deps+            let needsRechk = rechk || depMod > tm -   ibc (IBC _ _) = True-   ibc _ = False+            st <- get+            if needsRechk then put $ nub (getSrc file : updateToSrc path st)+                          else put $ nub (file : st)+            st <- get+            mapM_ (modTree (getSrc p : path)) deps     chkReload False p = p    chkReload True (IBC fn src) = chkReload True src
src/Idris/CmdOptions.hs view
@@ -9,11 +9,8 @@ {-# LANGUAGE Arrows #-}  module Idris.CmdOptions-  (-    module Idris.CmdOptions-  , opt-  , getClient, getPkg, getPkgCheck, getPkgClean, getPkgMkDoc-  , getPkgREPL, getPkgTest, getPort, getIBCSubDir+  ( opt, getClient, getPkg, getPkgCheck, getPkgClean, getPkgMkDoc,+    getPkgREPL, getPkgTest, getPort, getIBCSubDir, pureArgParser, runArgParser   ) where  import Idris.Info (getIdrisVersion)
src/Idris/Colours.hs view
@@ -2,7 +2,7 @@ {-| Module      : Idris.Colours Description : Support for colours within Idris.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}
src/Idris/Completion.hs view
@@ -1,22 +1,26 @@ {-| Module      : Idris.Completion Description : Support for command-line completion at the REPL and in the prover.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}++{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}+{-# OPTIONS_GHC -fwarn-unused-imports #-}+ module Idris.Completion (replCompletion, proverCompletion) where -import Idris.AbsSyntax (runIO)+import Idris.AbsSyntax (getIState, runIO) import Idris.AbsSyntaxTree import Idris.Colours-import Idris.Core.Evaluate (ctxtAlist, definitions)+import Idris.Core.Evaluate (ctxtAlist, visibleDefinitions) import Idris.Core.TT import Idris.Help import Idris.Imports (installedPackages) import Idris.Parser.Expr (TacticArg(..)) import qualified Idris.Parser.Expr (constants, tactics)-import Idris.Parser.Helpers (opChars)+import Idris.Parser.Ops (opChars) import Idris.REPL.Parser (allHelp, setOptions)  import Control.Monad.State.Strict@@ -28,19 +32,21 @@ import System.Console.ANSI (Color) import System.Console.Haskeline +commands :: [String] commands = [ n | (names, _, _) <- allHelp ++ extraHelp, n <- names ]  tacticArgs :: [(String, Maybe TacticArg)] tacticArgs = [ (name, args) | (names, args, _) <- Idris.Parser.Expr.tactics                             , name <- names ]++tactics :: [String] tactics = map fst tacticArgs  -- | Get the user-visible names from the current interpreter state. names :: Idris [String]-names = do i <- get-           let ctxt = tt_ctxt i+names = do ctxt <- tt_ctxt <$> getIState            return $-             mapMaybe nameString (allNames $ definitions ctxt) +++             mapMaybe nameString (allNames $ visibleDefinitions ctxt) ++              "Type" : map fst Idris.Parser.Expr.constants   where     -- We need both fully qualified names and identifiers that map to them@@ -60,11 +66,6 @@ metavars :: Idris [String] metavars = do i <- get               return . map (show . nsroot) $ map fst (filter (\(_, (_,_,_,t,_)) -> not t) (idris_metavars i)) \\ primDefs---modules :: Idris [String]-modules = do i <- get-             return $ map show $ imported i  namespaces :: Idris [String] namespaces = do
src/Idris/Core/Binary.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Core.Binary Description : Binary instances for the core datatypes-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -13,67 +13,14 @@ import Idris.Core.TT  import Control.Applicative ((<$>), (<*>))-import Control.DeepSeq (($!!))-import Control.Monad (liftM2) import Data.Binary import Data.Binary.Get import Data.Binary.Put-import qualified Data.Text as T-import qualified Data.Text.Encoding as E-import Data.Vector.Binary -instance Binary ErrorReportPart where-  put (TextPart msg) = do putWord8 0 ; put msg-  put (NamePart n) = do putWord8 1 ; put n-  put (TermPart t) = do putWord8 2 ; put t-  put (SubReport ps) = do putWord8 3 ; put ps-  put (RawPart r) = do putWord8 4 ; put r--  get = do i <- getWord8-           case i of-             0 -> fmap TextPart get-             1 -> fmap NamePart get-             2 -> fmap TermPart get-             3 -> fmap SubReport get-             4 -> fmap RawPart get-             _ -> error "Corrupted binary data for ErrorReportPart"--instance Binary Provenance where-  put ExpectedType = putWord8 0-  put (SourceTerm t) = do putWord8 1-                          put t-  put InferredVal = putWord8 2-  put GivenVal = putWord8 3-  put (TooManyArgs t) = do putWord8 4-                           put t--  get = do i <- getWord8-           case i of-             0 -> return ExpectedType-             1 -> do x1 <- get-                     return (SourceTerm x1)-             2 -> return InferredVal-             3 -> return GivenVal-             4 -> do x1 <- get-                     return (TooManyArgs x1)-             _ -> error "Corrupted binary data for Provenance"--instance Binary UConstraint where-  put (ULT x1 x2) = putWord8 0 >> put x1 >> put x2-  put (ULE x1 x2) = putWord8 1 >> put x1 >> put x2-  get = do i <- getWord8-           case i of-             0 -> ULT <$> get <*> get-             1 -> ULE <$> get <*> get-             _ -> error "Corrupted binary data for UConstraint"--instance Binary ConstraintFC where-  put (ConstraintFC x1 x2) = putWord8 0 >> put x1 >> put x2-  get = do i <- getWord8-           case i of-             0 -> liftM2 ConstraintFC get get-             _ -> error "Corrupted binary data for ConstraintFC"-+instance Binary ErrorReportPart+instance Binary Provenance+instance Binary UConstraint+instance Binary ConstraintFC instance Binary a => Binary (Err' a) where   put (Msg str) = do putWord8 0                      put str@@ -281,119 +228,10 @@              _ -> error "Corrupted binary data for Err'" ----- Generated by 'derive' -instance Binary FC where-        put x =-          case x of-            (FC x1 (x2, x3) (x4, x5)) -> do putWord8 0-                                            put x1-                                            put (x2 * 65536 + x3)-                                            put (x4 * 65536 + x5)-            NoFC -> putWord8 1-            FileFC x1 -> do putWord8 2-                            put x1-        get-          = do i <- getWord8-               case i of-                 0 -> do x1 <- get-                         x2x3 <- get-                         x4x5 <- get-                         return (FC x1 (x2x3 `div` 65536, x2x3 `mod` 65536) (x4x5 `div` 65536, x4x5 `mod` 65536))-                 1 -> return NoFC-                 2 -> do x1 <- get-                         return (FileFC x1)-                 _ -> error "Corrupted binary data for FC"--instance Binary FC' where-    put (FC' fc) = put fc-    get = fmap FC' get--instance Binary Name where-        put x-          = case x of-                UN x1 -> do putWord8 0-                            put x1-                NS x1 x2 -> do putWord8 1-                               put x1-                               put x2-                MN x1 x2 -> do putWord8 2-                               put x1-                               put x2-                SN x1 -> do putWord8 3-                            put x1-                SymRef x1 -> do putWord8 4-                                put x1-        get-          = do i <- getWord8-               case i of-                   0 -> do x1 <- get-                           return (UN x1)-                   1 -> do x1 <- get-                           x2 <- get-                           return (NS x1 x2)-                   2 -> do x1 <- get-                           x2 <- get-                           return (MN x1 x2)-                   3 -> do x1 <- get-                           return (SN x1)-                   4 -> do x1 <- get-                           return (SymRef x1)-                   _ -> error "Corrupted binary data for Name"--instance Binary SpecialName where-        put x-          = case x of-                WhereN x1 x2 x3 -> do putWord8 0-                                      put x1-                                      put x2-                                      put x3-                ImplementationN x1 x2 -> do putWord8 1-                                            put x1-                                            put x2-                ParentN x1 x2 -> do putWord8 2-                                    put x1-                                    put x2-                MethodN x1 -> do putWord8 3-                                 put x1-                CaseN x1 x2 -> do putWord8 4; put x1; put x2-                ElimN x1 -> do putWord8 5; put x1-                ImplementationCtorN x1 -> do putWord8 6; put x1-                WithN x1 x2 -> do putWord8 7-                                  put x1-                                  put x2-                MetaN x1 x2 -> do putWord8 8-                                  put x1-                                  put x2-        get-          = do i <- getWord8-               case i of-                   0 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           return (WhereN x1 x2 x3)-                   1 -> do x1 <- get-                           x2 <- get-                           return (ImplementationN x1 x2)-                   2 -> do x1 <- get-                           x2 <- get-                           return (ParentN x1 x2)-                   3 -> do x1 <- get-                           return (MethodN x1)-                   4 -> do x1 <- get-                           x2 <- get-                           return (CaseN x1 x2)-                   5 -> do x1 <- get-                           return (ElimN x1)-                   6 -> do x1 <- get-                           return (ImplementationCtorN x1)-                   7 -> do x1 <- get-                           x2 <- get-                           return (WithN x1 x2)-                   8 -> do x1 <- get-                           x2 <- get-                           return (MetaN x1 x2)-                   _ -> error "Corrupted binary data for SpecialName"--+instance Binary FC+instance Binary FC'+instance Binary Name+instance Binary SpecialName instance Binary Const where         put x           = case x of@@ -457,56 +295,8 @@                    29 -> return TheWorld                    _ -> error "Corrupted binary data for Const" --instance Binary Raw where-        put x-          = case x of-                Var x1 -> do putWord8 0-                             put x1-                RBind x1 x2 x3 -> do putWord8 1-                                     put x1-                                     put x2-                                     put x3-                RApp x1 x2 -> do putWord8 2-                                 put x1-                                 put x2-                RType -> putWord8 3-                RConstant x1 -> do putWord8 4-                                   put x1-                RUType x1 -> do putWord8 5-                                put x1-        get-          = do i <- getWord8-               case i of-                   0 -> do x1 <- get-                           return (Var x1)-                   1 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           return (RBind x1 x2 x3)-                   2 -> do x1 <- get-                           x2 <- get-                           return (RApp x1 x2)-                   3 -> return RType-                   4 -> do x1 <- get-                           return (RConstant x1)-                   5 -> do x1 <- get-                           return (RUType x1)-                   _ -> error "Corrupted binary data for Raw"--instance Binary RigCount where-        put x = case x of-                     Rig0 -> putWord8 0-                     Rig1 -> putWord8 1-                     RigW -> putWord8 2-        get = do i <- getWord8-                 case i of-                     0 -> return Rig0-                     1 -> return Rig1-                     2 -> return RigW-                     _ -> error "Corrupted binary data for RigCount"--+instance Binary Raw+instance Binary RigCount instance Binary ImplicitInfo where         put x           = case x of@@ -516,124 +306,11 @@                x2 <- get                return (Impl x1 x2 False) -instance (Binary b) => Binary (Binder b) where-        put x-          = case x of-                Lam x1 x2 -> do putWord8 0-                                put x1-                                put x2-                Pi x1 x2 x3 x4 -> do putWord8 1-                                     put x1-                                     put x2-                                     put x3-                                     put x4-                Let x1 x2 -> do putWord8 2-                                put x1-                                put x2-                NLet x1 x2 -> do putWord8 3-                                 put x1-                                 put x2-                Hole x1 -> do putWord8 4-                              put x1-                GHole x1 x2 x3 -> do putWord8 5-                                     put x1-                                     put x2-                                     put x3-                Guess x1 x2 -> do putWord8 6-                                  put x1-                                  put x2-                PVar x1 x2 -> do putWord8 7-                                 put x1-                                 put x2-                PVTy x1 -> do putWord8 8-                              put x1-        get-          = do i <- getWord8-               case i of-                   0 -> do x1 <- get-                           x2 <- get-                           return (Lam x1 x2)-                   1 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           return (Pi x1 x2 x3 x4)-                   2 -> do x1 <- get-                           x2 <- get-                           return (Let x1 x2)-                   3 -> do x1 <- get-                           x2 <- get-                           return (NLet x1 x2)-                   4 -> do x1 <- get-                           return (Hole x1)-                   5 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           return (GHole x1 x2 x3)-                   6 -> do x1 <- get-                           x2 <- get-                           return (Guess x1 x2)-                   7 -> do x1 <- get-                           x2 <- get-                           return (PVar x1 x2)-                   8 -> do x1 <- get-                           return (PVTy x1)-                   _ -> error "Corrupted binary data for Binder"---instance Binary Universe where-        put x = case x of-                     UniqueType -> putWord8 0-                     AllTypes -> putWord8 1-                     NullType -> putWord8 2-        get = do i <- getWord8-                 case i of-                     0 -> return UniqueType-                     1 -> return AllTypes-                     2 -> return NullType-                     _ -> error "Corrupted binary data for Universe"--instance Binary NameType where-        put x-          = case x of-                Bound -> putWord8 0-                Ref -> putWord8 1-                DCon x1 x2 x3 -> do putWord8 2-                                    put (x1 * 65536 + x2)-                                    put x3-                TCon x1 x2 -> do putWord8 3-                                 put (x1 * 65536 + x2)-        get-          = do i <- getWord8-               case i of-                   0 -> return Bound-                   1 -> return Ref-                   2 -> do x1x2 <- get-                           x3 <- get-                           return (DCon (x1x2 `div` 65536) (x1x2 `mod` 65536) x3)-                   3 -> do x1x2 <- get-                           return (TCon (x1x2 `div` 65536) (x1x2 `mod` 65536))-                   _ -> error "Corrupted binary data for NameType"---- record concrete levels only, for now-instance Binary UExp where-    put x = case x of-                 UVar ns t -> do putWord8 0-                                 put ns-                                 put t-                 UVal t -> do putWord8 1-                              put t--    get = do i <- getWord8-             case i of-                 0 -> do x1 <- get-                         x2 <- get-                         return (UVar x1 x2)-                 1 -> do x1 <- get-                         return (UVal x1)-                 _ -> error "Corrupted binary data for UExp"--instance {- (Binary n) => -} Binary (TT Name) where+instance (Binary b) => Binary (Binder b)+instance Binary Universe+instance Binary NameType+instance Binary UExp+instance Binary (TT Name) where         put x           = {-# SCC "putTT" #-}             case x of
src/Idris/Core/CaseTree.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Core.CaseTree Description : Module to define and interact with case trees.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. @@ -18,6 +18,7 @@ in order to allow for better optimisation opportunities.  -}+ {-# LANGUAGE DeriveFunctor, DeriveGeneric, FlexibleContexts, FlexibleInstances,              PatternGuards, TypeSynonymInstances #-} @@ -30,14 +31,11 @@  import Idris.Core.TT -import Control.Applicative hiding (Const) import Control.Monad.Reader import Control.Monad.State import Data.List hiding (partition) import qualified Data.List (partition)-import Data.Maybe import qualified Data.Set as S-import Debug.Trace import GHC.Generics (Generic)  data CaseDef = CaseDef [Name] !SC [Term]@@ -124,7 +122,7 @@ small :: Name -> [Name] -> SC -> Bool small n args t = let as = findAllUsedArgs t args in                      length as == length (nub as) &&-                     termsize n t < 10+                     termsize n t < 20  namesUsed :: SC -> [Name] namesUsed sc = nub $ nu' [] sc where@@ -143,7 +141,7 @@                      | otherwise = [n]     nut ps (App _ f a) = nut ps f ++ nut ps a     nut ps (Proj t _) = nut ps t-    nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc+    nut ps (Bind n (Let _ t v) sc) = nut ps v ++ nut (n:ps) sc     nut ps (Bind n b sc) = nut (n:ps) sc     nut ps _ = [] @@ -178,7 +176,7 @@                                    (S.unions $ map (nut ps) args)         | (P (TCon _ _) n _, _) <- unApply fn = S.empty         | otherwise = S.union (nut ps f) (nut ps a)-    nut ps (Bind n (Let t v) sc) = S.union (nut ps v) (nut (n:ps) sc)+    nut ps (Bind n (Let _ t v) sc) = S.union (nut ps v) (nut (n:ps) sc)     nut ps (Proj t _) = nut ps t     nut ps (Bind n b sc) = nut (n:ps) sc     nut ps _ = S.empty@@ -190,7 +188,7 @@  directUse :: TT Name -> [Name] directUse (P _ n _) = [n]-directUse (Bind n (Let t v) sc) = nub $ directUse v ++ (directUse sc \\ [n])+directUse (Bind n (Let _ t v) sc) = nub $ directUse v ++ (directUse sc \\ [n])                                         ++ directUse t directUse (Bind n b sc) = nub $ directUse (binderTy b) ++ (directUse sc \\ [n]) directUse fn@(App _ f a)@@ -270,7 +268,6 @@                  = return $ CaseDef [] (UnmatchedCase (show fc ++ ":No pattern clauses")) []  sc' tc defcase phase fc cs       = let proj       = phase == RunTime-            vnames     = fstT (head cs)             pats       = map (\ (avs, l, r) ->                                    (avs, toPats reflect tc l, (l, r))) cs             chkPats    = mapM chkAccessible pats in@@ -282,15 +279,13 @@                         (tree, st) = runCaseBuilder erInfo                                          (match ns' ps' defcase)                                          ([], numargs, [])-                        t          = CaseDef ns (prune proj (depatt ns' tree)) (fstT st) in+                        sc         = removeUnreachable (prune proj (depatt ns' tree))+                        t          = CaseDef ns sc (fstT st) in                         if proj then return (stripLambdas t)                                 else return t                 Error err -> Error (At fc err)     where args = map (\i -> sMN i "e") [0..]-          defaultCase True = STerm Erased-          defaultCase False = UnmatchedCase "Error"           fstT (x, _, _) = x-          lstT (_, _, x) = x            -- Check that all pattern variables are reachable by a case split           -- Otherwise, they won't make sense on the RHS.@@ -305,48 +300,6 @@           acc (PSuc p : xs) n = acc (p : xs) n           acc (_ : xs) n = acc xs n --- For each 'Case', make sure every choice is in the same type family,--- as directed by the variable type (i.e. there is no implicit type casing--- going on).--checkSameTypes :: [(Name, Type)] -> SC -> Bool-checkSameTypes tys (Case _ n alts)-        = case lookup n tys of-               Just t -> and (map (checkAlts t) alts)-               _ -> and (map ((checkSameTypes tys).getSC) alts)-  where-    checkAlts t (ConCase n _ _ sc) = isType n t && checkSameTypes tys sc-    checkAlts (Constant t) (ConstCase c sc) = isConstType c t && checkSameTypes tys sc-    checkAlts _ (ConstCase c sc) = False-    checkAlts _ _ = True--    getSC (ConCase _ _ _ sc) = sc-    getSC (FnCase _ _ sc) = sc-    getSC (ConstCase _ sc) = sc-    getSC (SucCase _ sc) = sc-    getSC (DefaultCase sc) = sc-checkSameTypes _ _ = True---- FIXME: All we're actually doing here is checking that we haven't arrived--- at a specific constructor for a polymorphic argument. I *think* this--- is sufficient, but if it turns out not to be, fix it!------ Issue #1718 on the issue tracker: https://github.com/idris-lang/Idris-dev/issues/1718-isType n t | (P (TCon _ _) _ _, _) <- unApply t = True-isType n t | (P Ref _ _, _) <- unApply t = True-isType n t = False--isConstType (I _) (AType (ATInt ITNative)) = True-isConstType (BI _) (AType (ATInt ITBig)) = True-isConstType (Fl _) (AType ATFloat) = True-isConstType (Ch _) (AType (ATInt ITChar)) = True-isConstType (Str _) StrType = True-isConstType (B8 _) (AType (ATInt _)) = True-isConstType (B16 _) (AType (ATInt _)) = True-isConstType (B32 _) (AType (ATInt _)) = True-isConstType (B64 _) (AType (ATInt _)) = True-isConstType _ _ = False- data Pat = PCon Bool Name Int [Pat]          | PConst Const          | PInferred Pat@@ -402,12 +355,6 @@      toPat' _ t = PAny -    fixedN IT8 = "Bits8"-    fixedN IT16 = "Bits16"-    fixedN IT32 = "Bits32"-    fixedN IT64 = "Bits64"-- data Partition = Cons [Clause]                | Vars [Clause]     deriving Show@@ -665,9 +612,6 @@       where         (acc, inacc) = partitionAcc r -    uniq i (UN n) = MN i n-    uniq i n = n- getVar :: String -> CaseBuilder Name getVar b = do (t, v, ntys) <- get; put (t, v+1, ntys); return (sMN v b) @@ -822,6 +766,56 @@  prune _ t = t +-- Remove any branches we can't reach because of variables we've already+-- tested+removeUnreachable :: SC -> SC+removeUnreachable sc = ru [] sc+  where+    -- keep a mapping from variable names, to the constructor tag we've+    -- already checked it as in this branch+    ru :: [(Name, Int)] -> SC -> SC+    ru checked (Case t n alts)+        = let alts' = map (ruAlt checked n) (dropImpossible (lookup n checked) alts) in+              Case t n alts'+    ru checked t = t++    dropImpossible Nothing alts = alts+    dropImpossible (Just t) [] = []+    dropImpossible (Just t) (ConCase con tag args sc : rest)+        | t == tag = [ConCase con tag args sc] -- must be this case+        | otherwise = dropImpossible (Just t) rest -- can't be this case+    dropImpossible (Just t) (c : rest)+        = c : dropImpossible (Just t) rest++    ruAlt :: [(Name, Int)] -> Name -> CaseAlt -> CaseAlt+    ruAlt checked var (ConCase con tag args sc)+        = let checked' = dropChecked args (updateChecked var tag checked)+              sc' = ru checked' sc in+              ConCase con tag args sc'+    ruAlt checked var (FnCase n args sc)+        = let checked' = dropChecked [var] checked+              sc' = ru checked' sc in+              FnCase n args sc'+    ruAlt checked var (ConstCase c sc)+        = let checked' = dropChecked [var] checked+              sc' = ru checked' sc in+              ConstCase c sc'+    ruAlt checked var (SucCase n sc)+        = let checked' = dropChecked [var] checked+              sc' = ru checked' sc in+              SucCase n sc'+    ruAlt checked var (DefaultCase sc)+        = let checked' = dropChecked [var] checked+              sc' = ru checked' sc in+              DefaultCase sc'++    updateChecked :: Name -> Int -> [(Name, Int)] -> [(Name, Int)]+    updateChecked n i checked+        = (n, i) : filter (\x -> fst x /= n) checked++    dropChecked :: [Name] -> [(Name, Int)] -> [(Name, Int)]+    dropChecked ns checked = filter (\x -> fst x `notElem` ns) checked+ stripLambdas :: CaseDef -> CaseDef stripLambdas (CaseDef ns (STerm (Bind x (Lam _ _) sc)) tm)     = stripLambdas (CaseDef (ns ++ [x]) (STerm (instantiate (P Bound x Erased) sc)) tm)@@ -871,5 +865,3 @@         = SucCase sn (mkForceSC n arg rhs)     mkForceAlt n arg (DefaultCase rhs)         = DefaultCase (mkForceSC n arg rhs)--    forceTm n arg t = subst n arg t
src/Idris/Core/Constraints.hs view
@@ -2,21 +2,19 @@ {-| Module      : Idris.Core.Constraints Description : Check universe constraints.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -} module Idris.Core.Constraints ( ucheck ) where -import Idris.Core.TT (ConstraintFC(..), Err'(..), FC(..), TC(..),-                      UConstraint(..), UExp(..))+import Idris.Core.TT (ConstraintFC(..), Err'(..), TC(..), UConstraint(..),+                      UExp(..)) -import Control.Applicative import Control.Monad.State.Strict import Data.List (partition) import qualified Data.Map.Strict as M import qualified Data.Set as S-import Debug.Trace  -- | Check that a list of universe constraints can be satisfied. ucheck :: S.Set ConstraintFC -> TC ()
src/Idris/Core/DeepSeq.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Core.DeepSeq Description : NFData instances for TT.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}
src/Idris/Core/Elaborate.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Core.Elaborate Description : A high level language of tactic composition, for building elaborators from a high level language into the core theory.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. @@ -16,7 +16,6 @@   , module Idris.Core.ProofState   ) where -import Idris.Core.DeepSeq import Idris.Core.Evaluate import Idris.Core.ProofState import Idris.Core.ProofTerm (bound_in, bound_in_term, getProofTerm, mkProofTerm,@@ -24,15 +23,9 @@ import Idris.Core.TT import Idris.Core.Typecheck import Idris.Core.Unify-import Idris.Core.WHNF -import Util.Pretty hiding (fill)--import Control.DeepSeq import Control.Monad.State.Strict-import Data.Char import Data.List-import Debug.Trace  data ElabState aux = ES (ProofState, aux) String (Maybe (ElabState aux))   deriving Show@@ -444,8 +437,8 @@ forall :: Name -> RigCount -> Maybe ImplicitInfo -> Raw -> Elab' aux () forall n r i t = processTactic' (Forall n r i t) -letbind :: Name -> Raw -> Raw -> Elab' aux ()-letbind n t v = processTactic' (LetBind n t v)+letbind :: Name -> RigCount -> Raw -> Raw -> Elab' aux ()+letbind n rig t v = processTactic' (LetBind n rig t v)  expandLet :: Name -> Term -> Elab' aux () expandLet n v = processTactic' (ExpandLet n v)@@ -510,7 +503,7 @@       = union (foB b)               (findOuter h env (instantiate (P Bound n (binderTy b)) sc))      where foB (Guess t v) = union (findOuter h env t) (findOuter h (n:env) v)-           foB (Let t v) = union (findOuter h env t) (findOuter h env v)+           foB (Let _ t v) = union (findOuter h env t) (findOuter h env v)            foB b = findOuter h env (binderTy b)   findOuter h env (App _ f a)       = union (findOuter h env f) (findOuter h env a)@@ -534,10 +527,11 @@ unifyProblems :: Elab' aux () unifyProblems = processTactic' UnifyProblems -defer :: [Name] -> Name -> Elab' aux Name-defer ds n = do n' <- unique_hole n-                processTactic' (Defer ds n')-                return n'+defer :: [Name] -> [Name] -> Name -> Elab' aux Name+defer ds ls n+    = do n' <- unique_hole n+         processTactic' (Defer ds ls n')+         return n'  deferType :: Name -> Raw -> [Name] -> Elab' aux () deferType n ty ns = processTactic' (DeferType n ty ns)@@ -614,9 +608,6 @@                         lift $ tfail $ TooManyArguments n             | otherwise = fail $ "Too many arguments for " ++ show fn -    doClaim ((i, _), n, t) = do claim n t-                                when i (movelast n)-     mkMN n@(MN i _) = n     mkMN n@(UN x) = MN 99999 x     mkMN n@(SN s) = sMN 99999 (show s)@@ -673,16 +664,13 @@            | i = getNonUnify acc is as            | otherwise = getNonUnify (t : acc) is as ---         getNonUnify imps args = map fst (filter (not . snd) (zip (map snd args) (map fst imps))) - apply2 :: Raw -> [Maybe (Elab' aux ())] -> Elab' aux () apply2 fn elabs =     do args <- prepare_apply fn (map isJust elabs)        fill (raw_apply fn (map (Var . snd) args))        elabArgs (map snd args) elabs        ES (p, a) s prev <- get-       let (n, hs) = unified p        end_unify        solve   where elabArgs [] [] = return $! ()@@ -700,16 +688,10 @@        env <- get_env        claims <- doClaims (normalise ctxt env ty) args []        prep_fill n (map fst claims)-       let eclaims = sortBy (\ (_, x) (_,y) -> priOrder x y) claims        elabClaims [] False claims        complete_fill        end_unify   where-    priOrder Nothing Nothing = EQ-    priOrder Nothing _ = LT-    priOrder _ Nothing = GT-    priOrder (Just (x, _)) (Just (y, _)) = compare x y-     doClaims (Bind n' (Pi _ _ t _) sc) (i : is) claims =         do n <- unique_hole (mkMN n')            when (null claims) (start_unify n)
src/Idris/Core/Evaluate.hs view
@@ -1,13 +1,15 @@ {-| Module      : Idris.Core.Evaluate Description : Evaluate Idris expressions.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}+ {-# LANGUAGE BangPatterns, DeriveGeneric, FlexibleInstances,              MultiParamTypeClasses, PatternGuards #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-}+{-# OPTIONS_GHC -fwarn-unused-imports #-}  module Idris.Core.Evaluate(normalise, normaliseTrace, normaliseC,                 normaliseAll, normaliseBlocking, toValue, quoteTerm,@@ -28,20 +30,19 @@                 isCanonical, isDConName, canBeDConName, isTConName, isConName, isFnName,                 conGuarded,                 Value(..), Quote(..), initEval, uniqueNameCtxt, uniqueBindersCtxt, definitions,+                visibleDefinitions,                 isUniverse, linearCheck, linearCheckArg) where  import Idris.Core.CaseTree import Idris.Core.TT -import Control.Applicative hiding (Const) import Control.Monad.State-import Data.Binary hiding (get, put)-import qualified Data.Binary as B import Data.List import Data.Maybe (listToMaybe)-import Debug.Trace import GHC.Generics (Generic) +import qualified Data.Map.Strict as Map+ data EvalState = ES { limited :: [(Name, Int)],                       nexthole :: Int,                       blocking :: Bool }@@ -65,7 +66,7 @@              -- True for Bool indicates safe to reduce            | VBind Bool Name (Binder Value) (Value -> Eval Value)              -- For frozen let bindings when simplifying-           | VBLet Int Name Value Value Value+           | VBLet RigCount Int Name Value Value Value            | VApp Value Value            | VType UExp            | VUType Universe@@ -205,16 +206,6 @@ finalEntry :: (Name, RigCount, Binder (TT Name)) -> (Name, RigCount, Binder (TT Name)) finalEntry (n, r, b) = (n, r, fmap finalise b) -bindEnv :: EnvTT n -> TT n -> TT n-bindEnv [] tm = tm-bindEnv ((n, r, Let t v):bs) tm = Bind n (NLet t v) (bindEnv bs tm)-bindEnv ((n, r, b):bs)       tm = Bind n b (bindEnv bs tm)--unbindEnv :: EnvTT n -> TT n -> TT n-unbindEnv [] tm = tm-unbindEnv (_:bs) (Bind n b sc) = unbindEnv bs sc-unbindEnv env tm = error "Impossible case occurred: couldn't unbind env."- usable :: Bool -- specialising           -> Bool -- unfolding only           -> Int -- Reduction depth limit (when simplifying/at REPL)@@ -287,7 +278,7 @@                 | otherwise = cases_compiletime cd      ev ntimes stk top env (P _ n ty)-        | Just (Let t v) <- lookupBinder n genv = ev ntimes stk top env v+        | Just (Let _ t v) <- lookupBinder n genv = ev ntimes stk top env v     ev ntimes_in stk top env (P Ref n ty)          = do let limit = if simpl then 100 else 10000               (u, ntimes) <- usable spec unfold limit n ntimes_in@@ -320,7 +311,7 @@     ev ntimes stk top env (V i)         | i < length env && i >= 0 = return $ snd (env !! i)         | otherwise      = return $ VV i-    ev ntimes stk top env (Bind n (Let t v) sc)+    ev ntimes stk top env (Bind n (Let c t v) sc)         | (not (runtime || simpl_inline || unfold)) || occurrences n sc < 2            = do v' <- ev ntimes stk top env v --(finalise v)                 sc' <- ev ntimes stk top ((n, v') : env) sc@@ -334,12 +325,12 @@                 let vd = nexthole hs                 put (hs { nexthole = vd + 1 })                 sc' <- ev ntimes stk top ((n, VP Bound (sMN vd "vlet") VErased) : env) sc-                return $ VBLet vd n t' v' sc'+                return $ VBLet c vd n t' v' sc'     ev ntimes stk top env (Bind n (NLet t v) sc)            = do t' <- ev ntimes stk top env (finalise t)                 v' <- ev ntimes stk top env (finalise v)                 sc' <- ev ntimes stk top ((n, v') : env) sc-                return $ VBind True n (Let t' v') (\x -> return sc')+                return $ VBind True n (Let RigW t' v') (\x -> return sc')     ev ntimes stk top env (Bind n b sc)            = do b' <- vbind env b                 let n' = uniqueName n (map fstEnv genv ++ map fst env)@@ -392,22 +383,6 @@     evApply ntimes stk top env args f           = apply ntimes stk top env f args -    reapply ntimes stk top env f@(VP Ref n ty) args-       = let val = lookupDefAccExact n (spec || (atRepl && noFree env) || runtime) ctxt in-         case val of-              Just (CaseOp ci _ _ _ _ cd, acc) ->-                 let (ns, tree) = getCases cd in-                     do c <- evCase ntimes n (n:stk) top env ns args tree-                        case c of-                             (Nothing, _) -> return $ unload env (VP Ref n ty) args-                             (Just v, rest) -> evApply ntimes stk top env rest v-              _ -> case args of-                        (a : as) -> return $ unload env f (a : as)-                        [] -> return f-    reapply ntimes stk top env (VApp f a) args-            = reapply ntimes stk top env f (a : args)-    reapply ntimes stk top env v args = return v-     apply ntimes stk top env (VBind True n (Lam _ t) sc) (a:as)          = do a' <- sc a               app <- apply ntimes stk top env a' as@@ -599,12 +574,12 @@                                   b' <- quoteB b                                   liftM (Bind n b') (quote (i+1) sc')        where quoteB t = fmapMB (quote i) t-    quote i (VBLet vd n t v sc)+    quote i (VBLet c vd n t v sc)                            = do sc' <- quote i sc                                 t' <- quote i t                                 v' <- quote i v                                 let sc'' = pToV (sMN vd "vlet") (addBinder sc')-                                return (Bind n (Let t' v') sc'')+                                return (Bind n (Let c t' v') sc'')     quote i (VApp f a)     = liftM2 (App MaybeHoles) (quote i f) (quote i a)     quote i (VType u)      = return (TType u)     quote i (VUType u)     = return (UType u)@@ -657,7 +632,7 @@     ceq ps (Bind n xb xs) (Bind n' yb ys)                              = liftM2 (&&) (ceqB ps xb yb) (ceq ((n,n'):ps) xs ys)         where-            ceqB ps (Let v t) (Let v' t') = liftM2 (&&) (ceq ps v v') (ceq ps t t')+            ceqB ps (Let c v t) (Let c' v' t') = liftM2 (&&) (ceq ps v v') (ceq ps t t')             ceqB ps (Guess v t) (Guess v' t') = liftM2 (&&) (ceq ps v v') (ceq ps t t')             ceqB ps (Pi r i v t) (Pi r' i' v' t') = liftM2 (&&) (ceq ps v v') (ceq ps t t')             ceqB ps b b' = ceq ps (binderTy b) (binderTy b')@@ -740,13 +715,6 @@                                   (caseeq ((x,y):ps) xdef ydef)                  _ -> return False --- SPECIALISATION -------------------------------------------------------------- We need too much control to be able to do this by tweaking the main--- evaluator--spec :: Context -> Ctxt [Bool] -> Env -> TT Name -> Eval (TT Name)-spec ctxt statics genv tm = error "spec undefined"- -- CONTEXTS -----------------------------------------------------------------  {-| A definition is either a simple function (just an expression with a type),@@ -983,8 +951,7 @@                     ( CaseDef args_ct sc_ct _,                      CaseDef args_rt sc_rt _) ->                        let inl = alwaysInline -- tcdict-                           inlc = (inl || small n args_ct sc_ct) && (not asserted)-                           inlr = inl || small n args_rt sc_rt+                           inlc = (inl || small n args_rt sc_rt) && (not asserted)                            cdef = CaseDefs (args_ct, sc_ct)                                            (args_rt, sc_rt)                            op = (CaseOp (ci { case_inlinable = inlc })@@ -1047,7 +1014,7 @@                        getNames under f ++ concatMap (getNames under') args         getNames (Just under) (P _ ref _)             = if ref `elem` inames then [under] else []-        getNames under (Bind n (Let t v) sc)+        getNames under (Bind n (Let c t v) sc)             = getNames Nothing t ++               getNames Nothing v ++               getNames Nothing sc@@ -1152,6 +1119,14 @@           isConName f ctxt = any (guarded n) as     guarded _ _ = False +visibleDefinitions :: Context -> Ctxt TTDecl+visibleDefinitions ctxt =+  Map.filter (\m -> length m > 0) . Map.map onlyVisible . definitions $ ctxt+  where+    onlyVisible = Map.filter visible+    visible (_def, _rigCount, _injectivity, accessibility, _totality, _metaInformation) =+      accessibility `notElem` [Hidden, Private]+ lookupP :: Name -> Context -> [Term] lookupP = lookupP_all False False @@ -1239,13 +1214,6 @@               Just Rig1 ->                   tfail $ Msg $ show f ++ " can only appear in a linear binding"               _ -> return ()--    checkArgs (Bind n (Pi RigW _ ty _) sc)-        = do mapM_ checkNameOK (allTTNames ty)-             checkArgs (substV (P Bound n Erased) sc)-    checkArgs (Bind n (Pi _ _ _ _) sc)-          = checkArgs (substV (P Bound n Erased) sc)-    checkArgs _ = return ()  -- Check if a name is reducible in the type checker. Partial definitions -- are not reducible (so treated as a constant)
src/Idris/Core/Execute.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Core.Execute Description : Execute Idris code and deal with FFI.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -11,7 +11,6 @@ module Idris.Core.Execute (execute) where  import Idris.AbsSyntax-import Idris.AbsSyntaxTree import Idris.Core.CaseTree import Idris.Core.Evaluate import Idris.Core.TT@@ -22,15 +21,11 @@ import Util.DynamicLinker import Util.System -import Control.Applicative hiding (Const) import Control.Exception-import Control.Monad hiding (forM) import Control.Monad.Trans import Control.Monad.Trans.Except (ExceptT, runExceptT, throwE) import Control.Monad.Trans.State.Strict-import Data.Bits import Data.IORef-import qualified Data.Map as M import Data.Maybe import Data.Time.Clock.POSIX (getPOSIXTime) import Data.Traversable (forM)@@ -42,7 +37,6 @@ #ifdef IDRIS_FFI import Foreign.C.String import Foreign.LibFFI-import Foreign.Marshal.Alloc (free) import Foreign.Ptr #endif @@ -51,10 +45,6 @@ execute tm = fail "libffi not supported, rebuild Idris with -f FFI" #else -- else is rest of file-readMay :: (Read a) => String -> Maybe a-readMay s = case reads s of-              [(x, "")] -> Just x-              _         -> Nothing  data Lazy = Delayed ExecEnv Context Term | Forced ExecVal deriving Show @@ -123,7 +113,7 @@                            Bind n' b' <$> toTT body'     where fixBinder (Lam rig t)    = Lam rig  <$> toTT t           fixBinder (Pi rig i t k) = Pi rig i <$> toTT t <*> toTT k-          fixBinder (Let t1 t2)   = Let     <$> toTT t1 <*> toTT t2+          fixBinder (Let rig t1 t2)   = Let rig <$> toTT t1 <*> toTT t2           fixBinder (NLet t1 t2)  = NLet    <$> toTT t1 <*> toTT t2           fixBinder (Hole t)      = Hole    <$> toTT t           fixBinder (GHole i ns t) = GHole i ns <$> toTT t@@ -144,7 +134,7 @@ toTT (EThunk ctxt env tm) = do env' <- mapM toBinder env                                return $ normalise ctxt env' tm   where toBinder (n, v) = do v' <- toTT v-                             return (n, RigW, Let Erased v')+                             return (n, RigW, Let RigW Erased v') toTT (EHandle _) = execFail $ Msg "Can't convert handles back to TT after execution." toTT (EPtr ptr) = execFail $ Msg "Can't convert pointers back to TT after execution." toTT (EStringBuf ptr) = execFail $ Msg "Can't convert string buffers back to TT after execution."@@ -170,9 +160,6 @@ getExecState :: Exec ExecState getExecState = lift get -putExecState :: ExecState -> Exec ()-putExecState = lift . put- execFail :: Err -> Exec a execFail = throwE @@ -220,8 +207,9 @@ doExec env ctxt (P (TCon a b) n _) = return (EP (TCon a b) n EErased) doExec env ctxt v@(V i) | i < length env = return (snd (env !! i))                         | otherwise      = execFail . Msg $ "env too small"-doExec env ctxt (Bind n (Let t v) body) = do v' <- doExec env ctxt v-                                             doExec ((n, v'):env) ctxt body+doExec env ctxt (Bind n (Let rig t v) body)+     = do v' <- doExec env ctxt v+          doExec ((n, v'):env) ctxt body doExec env ctxt (Bind n (NLet t v) body) = undefined doExec env ctxt tm@(Bind n b body) = do b' <- forM b (doExec env ctxt)                                         return $@@ -481,8 +469,8 @@ execForeign env ctxt arity ty fn xs onfail    = case foreignFromTT arity ty fn xs of         Just ffun@(FFun f argTs retT) | length xs >= arity ->-           do let (args', xs') = (take arity xs, -- foreign args-                                  drop arity xs) -- rest+           do let (_, xs') = (take arity xs, -- foreign args+                              drop arity xs) -- rest               res <- call ffun (map snd argTs)               case res of                    Nothing -> fail $ "Could not call foreign function \"" ++ f ++@@ -710,26 +698,6 @@          return $ FFun name argFTyVals (toFDesc ty) foreignFromTT arity ty fn args = trace ("failed to construct ffun from " ++ show (ty,fn,args)) Nothing -getFTy :: ExecVal -> Maybe FType-getFTy (EApp (EP _ (UN fi) _) (EP _ (UN intTy) _))-  | fi == txt "FIntT" =-    case str intTy of-      "ITNative" -> Just (FArith (ATInt ITNative))-      "ITChar" -> Just (FArith (ATInt ITChar))-      "IT8" -> Just (FArith (ATInt (ITFixed IT8)))-      "IT16" -> Just (FArith (ATInt (ITFixed IT16)))-      "IT32" -> Just (FArith (ATInt (ITFixed IT32)))-      "IT64" -> Just (FArith (ATInt (ITFixed IT64)))-      _ -> Nothing-getFTy (EP _ (UN t) _) =-    case str t of-      "FFloat"  -> Just (FArith ATFloat)-      "FString" -> Just FString-      "FPtr"    -> Just FPtr-      "FUnit"   -> Just FUnit-      _         -> Nothing-getFTy _ = Nothing- unEList :: ExecVal -> Maybe [ExecVal] unEList tm = case unApplyV tm of                (nil, [_]) -> Just []@@ -738,10 +706,6 @@                       return $ x:rest                (f, args) -> Nothing --toConst :: Term -> Maybe Const-toConst (Constant c) = Just c-toConst _ = Nothing  mapMaybeM :: (Functor m, Monad m) => (a -> m (Maybe b)) -> [a] -> m [b] mapMaybeM f [] = return []
src/Idris/Core/ProofState.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Core.ProofState Description : Proof state implementation.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. @@ -28,11 +28,9 @@  import Util.Pretty hiding (fill) -import Control.Applicative hiding (empty) import Control.Arrow ((***)) import Control.Monad.State.Strict import Data.List-import Debug.Trace  data ProofState = PS { thname            :: Name,                        holes             :: [Name], -- ^ holes still to be solved@@ -90,7 +88,7 @@             | Intro (Maybe Name)             | IntroTy Raw (Maybe Name)             | Forall Name RigCount (Maybe ImplicitInfo) Raw-            | LetBind Name Raw Raw+            | LetBind Name RigCount Raw Raw             | ExpandLet Name Term             | Rewrite Raw             | Induction Raw@@ -99,7 +97,7 @@             | PatVar Name             | PatBind Name RigCount             | Focus Name-            | Defer [Name] Name+            | Defer [Name] [Name] Name             | DeferType Name Raw [Name]             | Implementation Name             | AutoArg Name@@ -130,7 +128,7 @@                 ") -------\n  " ++                 show h ++ " : " ++ showG wkenv (goalType g) ++ "\n"          where showPs env [] = ""-               showPs env ((n, _, Let t v):bs)+               showPs env ((n, _, Let _ t v):bs)                    = "  " ++ show n ++ " : " ++                      showEnv env ({- normalise ctxt env -} t) ++ "   =   " ++                      showEnv env ({- normalise ctxt env -} v) ++@@ -161,7 +159,7 @@       prettyGoal ps b = prettyEnv ps $ binderTy b        prettyPs env [] = empty-      prettyPs env ((n, _, Let t v):bs) =+      prettyPs env ((n, _, Let _ t v):bs) =         nest nestingSize (pretty n <+> colon <+>         prettyEnv env t <+> text "=" <+> prettyEnv env v <+>         nest nestingSize (prettyPs env bs))@@ -181,7 +179,6 @@ match_unify' ctxt env (topx, xfrom) (topy, yfrom) =    do ps <- get       let while = while_elaborating ps-      let dont = dontunify ps       let inj = injective ps       traceWhen (unifylog ps)                 ("Matching " ++ show (topx, topy) ++@@ -361,9 +358,9 @@  computeLet :: Context -> Name -> Term -> Term computeLet ctxt n tm = cl [] tm where-   cl env (Bind n' (Let t v) sc)+   cl env (Bind n' (Let r t v) sc)        | n' == n = let v' = normalise ctxt env v in-                       Bind n' (Let t v') sc+                       Bind n' (Let r t v') sc    cl env (Bind n' b sc) = Bind n' (fmap (cl env) b) (cl ((n, Rig0, b):env) sc)    cl env (App s f a) = App s (cl env f) (cl env a)    cl env t = t@@ -415,7 +412,7 @@         insertB x (y:ys) | all (noOcc x) (y:ys) = x : y : ys                          | otherwise = y : insertB x ys -        noOcc (n, _) (_, Let t v) = noOccurrence n t && noOccurrence n v+        noOcc (n, _) (_, Let _ t v) = noOccurrence n t && noOccurrence n v         noOcc (n, _) (_, Guess t v) = noOccurrence n t && noOccurrence n v         noOcc (n, _) (_, b) = noOccurrence n (binderTy b) @@ -462,8 +459,8 @@                             ps { injective = n : is })          return (Bind x b sc) -defer :: [Name] -> Name -> RunTactic-defer dropped n ctxt env (Bind x (Hole t) (P nt x' ty)) | x == x' =+defer :: [Name] -> [Name] -> Name -> RunTactic+defer dropped linused n ctxt env (Bind x (Hole t) (P nt x' ty)) | x == x' =     do let env' = filter (\(n, _, t) -> n `notElem` dropped) env        action (\ps -> let hs = holes ps in                           ps { usedns = n : usedns ps,@@ -473,10 +470,13 @@                       (mkApp (P Ref n ty) (map getP (reverse env'))))   where     mkTy []           t = t-    mkTy ((n,rig,b) : bs) t = Bind n (Pi RigW Nothing (binderTy b) (TType (UVar [] 0))) (mkTy bs t)+    mkTy ((n,rig,b) : bs) t = Bind n (Pi (setRig rig n) Nothing (binderTy b) (TType (UVar [] 0))) (mkTy bs t) +    setRig Rig1 n | n `elem` linused = Rig0+    setRig rig n = rig+     getP (n, rig, b) = P Bound n (binderTy b)-defer dropped n ctxt env _ = fail "Can't defer a non-hole focus."+defer dropped linused n ctxt env _ = fail "Can't defer a non-hole focus."  -- as defer, but build the type and application explicitly deferType :: Name -> Raw -> [Name] -> RunTactic@@ -494,15 +494,6 @@                   Nothing -> error ("deferType can't find " ++ show n) deferType _ _ _ _ _ _ = fail "Can't defer a non-hole focus." -regret :: RunTactic-regret ctxt env (Bind x (Hole t) sc) | noOccurrence x sc =-    do action (\ps -> let hs = holes ps in-                          ps { holes = hs \\ [x] })-       return sc-regret ctxt env (Bind x (Hole t) _)-    = fail $ show x ++ " : " ++ show t ++ " is not solved..."-regret _ _ _ = fail "The current focus is not a hole."- unifyGoal :: Raw -> RunTactic unifyGoal tm ctxt env h@(Bind x b sc) =     do (tmv, _) <- lift $ check ctxt env tm@@ -529,14 +520,8 @@ fill :: Raw -> RunTactic fill guess ctxt env (Bind x (Hole ty) sc) =     do (val, valty) <- lift $ check ctxt env guess---        let valtyn = normalise ctxt env valty---        let tyn = normalise ctxt env ty-       ns <- unify' ctxt env (valty, Just $ SourceTerm val)-                             (ty, Just (chkPurpose val ty))-       ps <- get-       let (uh, uns) = unified ps---        put (ps { unified = (uh, uns ++ ns) })---        addLog (show (uh, uns ++ ns))+       unify' ctxt env (valty, Just $ SourceTerm val)+                       (ty, Just (chkPurpose val ty))        return $ Bind x (Guess ty val) sc   where     -- some expected types show up commonly in errors and indicate a@@ -552,14 +537,8 @@ match_fill :: Raw -> RunTactic match_fill guess ctxt env (Bind x (Hole ty) sc) =     do (val, valty) <- lift $ check ctxt env guess---        let valtyn = normalise ctxt env valty---        let tyn = normalise ctxt env ty-       ns <- match_unify' ctxt env (valty, Just $ SourceTerm val)-                                   (ty, Just ExpectedType)-       ps <- get-       let (uh, uns) = unified ps---        put (ps { unified = (uh, uns ++ ns) })---        addLog (show (uh, uns ++ ns))+       match_unify' ctxt env (valty, Just $ SourceTerm val)+                             (ty, Just ExpectedType)        return $ Bind x (Guess ty val) sc match_fill _ _ _ _ = fail "Can't fill here." @@ -573,11 +552,8 @@ complete_fill ctxt env (Bind x (Guess ty val) sc) =     do let guess = forget val        (val', valty) <- lift $ check ctxt env guess-       ns <- unify' ctxt env (valty, Just $ SourceTerm val')-                             (ty, Just ExpectedType)-       ps <- get-       let (uh, uns) = unified ps---        put (ps { unified = (uh, uns ++ ns) })+       unify' ctxt env (valty, Just $ SourceTerm val')+                       (ty, Just ExpectedType)        return $ Bind x (Guess ty val) sc complete_fill ctxt env t = fail $ "Can't complete fill at " ++ show t @@ -588,7 +564,6 @@ solve :: RunTactic solve ctxt env (Bind x (Guess ty val) sc)    = do ps <- get-        let (uh, uns) = unified ps         dropdots <-              case lookup x (notunified ps) of                 Just tm -> -- trace ("NEED MATCH: " ++ show (x, tm, val) ++ "\nIN " ++ show (pterm ps)) $@@ -605,7 +580,7 @@                             recents = x : recents ps,                             implementations = implementations ps \\ [x],                             dotted = dropUnified dropdots (dotted ps) })-        let (locked, did) = tryLock (holes ps \\ [x]) (updsubst x val sc) in+        let (locked, _) = tryLock (holes ps \\ [x]) (updsubst x val sc) in             return locked   where dropUnified ddots [] = []         dropUnified ddots ((x, es) : ds)@@ -623,14 +598,13 @@         tryLock hs t@(P _ n _) = (t, not $ n `elem` hs)         tryLock hs t@(Bind n (Hole _) sc) = (t, False)         tryLock hs t@(Bind n (Guess _ _) sc) = (t, False)-        tryLock hs t@(Bind n (Let ty val) sc)+        tryLock hs t@(Bind n (Let r ty val) sc)             = let (ty', tyl) = tryLock hs ty                   (val', vall) = tryLock hs val                   (sc', scl) = tryLock hs sc in-                  (Bind n (Let ty' val') sc', tyl && vall && scl)+                  (Bind n (Let r ty' val') sc', tyl && vall && scl)         tryLock hs t@(Bind n b sc)             = let (bt', btl) = tryLock hs (binderTy b)-                  (val', vall) = tryLock hs val                   (sc', scl) = tryLock hs sc in                   (Bind n (b { binderTy = bt' }) sc', btl && scl)         tryLock hs t = (t, True)@@ -640,7 +614,7 @@         case findType x sc of              Just t -> lift $ tfail (CantInferType (show t))              _ -> lift $ tfail (IncompleteTerm h)-   where findType x (Bind n (Let t v) sc)+   where findType x (Bind n (Let r t v) sc)               = findType x v `mplus` findType x sc          findType x (Bind n t sc)               | P _ x' _ <- binderTy t, x == x' = Just n@@ -656,13 +630,9 @@                     x@(Bind y (Pi _ _ s _) _) -> x                     _ -> normalise ctxt env t        (tyv, tyt) <- lift $ check ctxt env ty---        ns <- lift $ unify ctxt env tyv t'        case t' of            Bind y (Pi rig _ s _) t -> let t' = updsubst y (P Bound n s) t in-                                        do ns <- unify' ctxt env (s, Nothing) (tyv, Nothing)-                                           ps <- get-                                           let (uh, uns) = unified ps---                                            put (ps { unified = (uh, uns ++ ns) })+                                        do unify' ctxt env (s, Nothing) (tyv, Nothing)                                            return $ Bind n (Lam rig tyv) (Bind x (Hole t') (P Bound x t'))            _ -> lift $ tfail $ CantIntroduce t' introTy ty n ctxt env _ = fail "Can't introduce here."@@ -708,13 +678,13 @@                       | otherwise = ps patvar n ctxt env tm = fail $ "Can't add pattern var at " ++ show tm -letbind :: Name -> Raw -> Raw -> RunTactic-letbind n ty val ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =+letbind :: Name -> RigCount -> Raw -> Raw -> RunTactic+letbind n rig ty val ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =     do (tyv,  tyt)  <- lift $ check ctxt env ty        (valv, valt) <- lift $ check ctxt env val        lift $ isType ctxt env tyt-       return $ Bind n (Let tyv valv) (Bind x (Hole t) (P Bound x t))-letbind n ty val ctxt env _ = fail "Can't let bind here"+       return $ Bind n (Let rig tyv valv) (Bind x (Hole t) (P Bound x t))+letbind n rig ty val ctxt env _ = fail "Can't let bind here"  expandLet :: Name -> Term -> RunTactic expandLet n v ctxt env tm =@@ -748,9 +718,9 @@                      = let b' = mkPB b                            sc' = if (r /= sc) then mkP lt l r sc else sc in                            Bind n b' sc'-    where mkPB (Let t v) = let t' = if (r /= t) then mkP lt l r t else t-                               v' = if (r /= v) then mkP lt l r v else v in-                               Let t' v'+    where mkPB (Let c t v) = let t' = if (r /= t) then mkP lt l r t else t+                                 v' = if (r /= v) then mkP lt l r v else v in+                                 Let c t' v'           mkPB b = let ty = binderTy b                        ty' = if (r /= ty) then mkP lt l r ty else ty in                              b { binderTy = ty' }@@ -760,7 +730,7 @@ casetac tm induction ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' = do   (tmv, tmt) <- lift $ check ctxt env tm   let tmt' = normalise ctxt env tmt-  let (tacn, tacstr, tactt) = if induction+  let (tacn, tacstr, _) = if induction               then (ElimN, "eliminator", "Induction")               else (CaseN (FC' emptyFC), "case analysis", "Case analysis")   case unApply tmt' of@@ -773,13 +743,9 @@                                _ -> return []              let (params, indicies) = splitTyArgs param_pos tyargs              let args     = getArgTys elimTy-             let pmargs   = take (length params) args              let args'    = drop (length params) args-             let propTy   = head args'              let restargs = init $ tail args'              let consargs = take (length restargs - length indicies) restargs-             let indxargs = drop (length restargs - length indicies) restargs-             let scr      = last $ tail args'              let indxnames = makeIndexNames indicies              currentNames <- query $ allTTNames . getProofTerm . pterm              let tmnm = case tm of@@ -801,8 +767,7 @@           xs -> lift $ tfail $ Msg $ "Multiple definitions found when searching for " ++ tacstr ++ "of " ++ show tnm     _ -> lift $ tfail $ NoEliminator (if induction then "induction" else "case analysis")                                      tmt'-    where scname = sMN 0 "scarg"-          makeConsArg (nm, ty) = P Bound nm ty+    where makeConsArg (nm, ty) = P Bound nm ty           bindConsArgs ((nm, ty):args) v = Bind nm (Hole ty) $ bindConsArgs args v           bindConsArgs [] v = v           addConsHole (nm, ty) =@@ -881,8 +846,6 @@ start_unify n ctxt env tm = do -- action (\ps -> ps { unified = (n, []) })                                return tm -tmap f (a, b, c) = (f a, b, c)- solve_unified :: RunTactic solve_unified ctxt env tm =     do ps <- get@@ -931,14 +894,6 @@                (updateSolvedTerm ns r, fmap (updateProv ns) rp) (updateError ns e) xs sc updateError ns e = e -updateRes ns [] = []-updateRes ns ((x, t) : ts) = (x, updateSolvedTerm ns t) : updateRes ns ts--solveInProblems x val [] = []-solveInProblems x val ((l, r, env, err) : ps)-   = ((psubst x val l, psubst x val r,-       updateEnv [(x, val)] env, err) : solveInProblems x val ps)- mergeNotunified :: Env -> [Name] -> [(Name, Term)] -> ([(Name, Term)], Fails) mergeNotunified env holes ns = mnu ns [] [] where   mnu [] ns_acc ps_acc = (reverse ns_acc, reverse ps_acc)@@ -1151,7 +1106,7 @@          mktac (Intro n)         = intro n          mktac (IntroTy ty n)    = introTy ty n          mktac (Forall n r i t)  = forall n r i t-         mktac (LetBind n t v)   = letbind n t v+         mktac (LetBind n r t v) = letbind n r t v          mktac (ExpandLet n b)   = expandLet n b          mktac (Rewrite t)       = rewrite t          mktac (Induction t)     = casetac t True@@ -1162,7 +1117,7 @@          mktac (CheckIn r)       = check_in r          mktac (EvalIn r)        = eval_in r          mktac (Focus n)         = focus n-         mktac (Defer ns n)      = defer ns n+         mktac (Defer ns ls n)   = defer ns ls n          mktac (DeferType n t a) = deferType n t a          mktac (Implementation n)= implementationArg n          mktac (AutoArg n)       = autoArg n
src/Idris/Core/ProofTerm.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Core.ProofTerm Description : Proof term. implementation and utilities.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -18,11 +18,8 @@  import Idris.Core.Evaluate import Idris.Core.TT-import Idris.Core.Typecheck  import Control.Monad.State.Strict-import Data.List-import Debug.Trace  -- | A zipper over terms, in order to efficiently update proof terms. data TermPath = Top@@ -34,8 +31,8 @@  -- | A zipper over binders, because terms and binders are mutually defined. data BinderPath = Binder (Binder TermPath)-                | LetT TermPath Term-                | LetV Term TermPath+                | LetT RigCount TermPath Term+                | LetV RigCount Term TermPath                 | GuessT TermPath Term                 | GuessV Term TermPath   deriving Show@@ -49,8 +46,8 @@ replaceTop p (InBind n bp sc) = InBind n (replaceTopB p bp) sc   where     replaceTopB p (Binder b) = Binder (fmap (replaceTop p) b)-    replaceTopB p (LetT t v) = LetT (replaceTop p t) v-    replaceTopB p (LetV t v) = LetV t (replaceTop p v)+    replaceTopB p (LetT c t v) = LetT c (replaceTop p t) v+    replaceTopB p (LetV c t v) = LetV c t (replaceTop p v)     replaceTopB p (GuessT t v) = GuessT (replaceTop p t) v     replaceTopB p (GuessV t v) = GuessV t (replaceTop p v) replaceTop p (InScope n b sc) = InScope n b (replaceTop p sc)@@ -66,8 +63,8 @@ -- | Build a binder from a zipper, given something to put in the hole. rebuildBinder :: Term -> BinderPath -> Binder Term rebuildBinder tm (Binder p) = fmap (rebuildTerm tm) p-rebuildBinder tm (LetT p t) = Let (rebuildTerm tm p) t-rebuildBinder tm (LetV v p) = Let v (rebuildTerm tm p)+rebuildBinder tm (LetT c p t) = Let c (rebuildTerm tm p) t+rebuildBinder tm (LetV c v p) = Let c v (rebuildTerm tm p) rebuildBinder tm (GuessT p t) = Guess (rebuildTerm tm p) t rebuildBinder tm (GuessV v p) = Guess v (rebuildTerm tm p) @@ -84,12 +81,12 @@       | Just (p, env', tm) <- fh' env path f = Just (AppL s p a, env', tm)   fh' env path (Bind x b sc)       | Just (bp, env', tm) <- fhB env path b = Just (InBind x bp sc, env', tm)-      | Just (p, env', tm) <- fh' ((x,RigW,b):env) path sc = Just (InScope x b p, env', tm)+      | Just (p, env', tm) <- fh' ((x,getRig b,b):env) path sc = Just (InScope x b p, env', tm)   fh' _ _ _ = Nothing -  fhB env path (Let t v)-      | Just (p, env', tm) <- fh' env path t = Just (LetT p v, env', tm)-      | Just (p, env', tm) <- fh' env path v = Just (LetV t p, env', tm)+  fhB env path (Let c t v)+      | Just (p, env', tm) <- fh' env path t = Just (LetT c p v, env', tm)+      | Just (p, env', tm) <- fh' env path v = Just (LetV c t p, env', tm)   fhB env path (Guess t v)       | Just (p, env', tm) <- fh' env path t = Just (GuessT p v, env', tm)       | Just (p, env', tm) <- fh' env path v = Just (GuessV t p, env', tm)@@ -187,10 +184,10 @@               if ut then (P nt n ty', True) else (t, False)     updateSolved' xs t = (t, False) -    updateSolvedB' xs b@(Let t v) = let (t', ut) = updateSolved' xs t-                                        (v', uv) = updateSolved' xs v in-                                        if ut || uv then (Let t' v', True)-                                                    else (b, False)+    updateSolvedB' xs b@(Let c t v) = let (t', ut) = updateSolved' xs t+                                          (v', uv) = updateSolved' xs v in+                                          if ut || uv then (Let c t' v', True)+                                                      else (b, False)     updateSolvedB' xs b@(Guess t v) = let (t', ut) = updateSolved' xs t                                           (v', uv) = updateSolved' xs v in                                           if ut || uv then (Guess t' v', True)@@ -198,16 +195,6 @@     updateSolvedB' xs b = let (ty', u) = updateSolved' xs (binderTy b) in                               if u then (b { binderTy = ty' }, u) else (b, False) -    noneOf ns (P _ n _) | n `elem` ns = False-    noneOf ns (App s f a) = noneOf ns a && noneOf ns f-    noneOf ns (Bind n (Hole ty) t) = n `notElem` ns && noneOf ns ty && noneOf ns t-    noneOf ns (Bind n b t) = noneOf ns t && noneOfB ns b-      where-        noneOfB ns (Let t v) = noneOf ns t && noneOf ns v-        noneOfB ns (Guess t v) = noneOf ns t && noneOf ns v-        noneOfB ns b = noneOf ns (binderTy b)-    noneOf ns _ = True- -- | As 'subst', in TT, but takes advantage of knowing not to substitute -- under Complete applications. updsubst :: Eq n => n {-^ The id to replace -} ->@@ -239,10 +226,10 @@                                   if u then (Proj x' idx, u) else (t, False)     subst' i t = (t, False) -    substB' i b@(Let t v) = let (t', ut) = subst' i t-                                (v', uv) = subst' i v in-                                if ut || uv then (Let t' v', True)-                                            else (b, False)+    substB' i b@(Let c t v) = let (t', ut) = subst' i t+                                  (v', uv) = subst' i v in+                                  if ut || uv then (Let c t' v', True)+                                              else (b, False)     substB' i b@(Guess t v) = let (t', ut) = subst' i t                                   (v', uv) = subst' i v in                                   if ut || uv then (Guess t' v', True)@@ -269,8 +256,8 @@     = InBind n (updateSolvedPathB b) (updateSolvedTerm ns sc)   where     updateSolvedPathB (Binder b) = Binder (fmap (updateSolvedPath ns) b)-    updateSolvedPathB (LetT p v) = LetT (updateSolvedPath ns p) (updateSolvedTerm ns v)-    updateSolvedPathB (LetV v p) = LetV (updateSolvedTerm ns v) (updateSolvedPath ns p)+    updateSolvedPathB (LetT c p v) = LetT c (updateSolvedPath ns p) (updateSolvedTerm ns v)+    updateSolvedPathB (LetV c v p) = LetV c (updateSolvedTerm ns v) (updateSolvedPath ns p)     updateSolvedPathB (GuessT p v) = GuessT (updateSolvedPath ns p) (updateSolvedTerm ns v)     updateSolvedPathB (GuessV v p) = GuessV (updateSolvedTerm ns v) (updateSolvedPath ns p) updateSolvedPath ns (InScope n (Hole ty) t)@@ -288,6 +275,13 @@           (updateSolvedTerm xs sub)           (ups ++ xs) +getRig :: Binder Term -> RigCount+getRig (Pi rig _ _ _) = rig+getRig (PVar rig _) = rig+getRig (Lam rig _) = rig+getRig (Let rig _ _) = rig+getRig _ = RigW+ goal :: Hole -> ProofTerm -> TC Goal goal h pt@(PT path env sub ups) --      | OK ginf <- g env sub = return ginf@@ -300,12 +294,13 @@                            = gb env b `mplus` g ((n, RigW, b):env) sc     g env (Bind n b sc) | hole b && same h n = return $ GD env b                         | otherwise-                           = g ((n, RigW, b):env) sc `mplus` gb env b+                           = g ((n, getRig b, b):env) sc `mplus` gb env b+     g env (App Complete f a) = fail "Can't find hole"     g env (App _ f a) = g env a `mplus` g env f     g env t           = fail "Can't find hole" -    gb env (Let t v) = g env v `mplus` g env t+    gb env (Let c t v) = g env v `mplus` g env t     gb env (Guess t v) = g env v `mplus` g env t     gb env t = g env (binderTy t) @@ -343,14 +338,14 @@     atH f c env binder@(Bind n b sc)         | hole b && same h n = updated (f c env binder)         | otherwise -- scope first-            = do (sc', u) <- atH f c ((n, RigW, b) : env) sc+            = do (sc', u) <- atH f c ((n, getRig b, b) : env) sc                  if u then return (Bind n b sc', True)                       else do (b', u) <- atHb f c env b                               return (Bind n b' sc', u)     atH tac c env (App s f a)  = ulift2 tac c env (App s) f a     atH tac c env t            = return (t, False) -    atHb f c env (Let t v)   = ulift2 f c env Let t v+    atHb f c env (Let rc t v)   = ulift2 f c env (Let rc) t v     atHb f c env (Guess t v) = ulift2 f c env Guess t v     atHb f c env t           = do (ty', u) <- atH f c env (binderTy t)                                   return (t { binderTy = ty' }, u)@@ -361,7 +356,7 @@ bound_in_term :: Term -> [Name] bound_in_term (Bind n b sc) = n : bi b ++ bound_in_term sc   where-    bi (Let t v) = bound_in_term t ++ bound_in_term v+    bi (Let c t v) = bound_in_term t ++ bound_in_term v     bi (Guess t v) = bound_in_term t ++ bound_in_term v     bi b = bound_in_term (binderTy b) bound_in_term (App _ f a) = bound_in_term f ++ bound_in_term a
src/Idris/Core/TT.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Core.TT Description : The core language of Idris, TT.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. @@ -47,7 +47,7 @@   , pEraseType, pmap, pprintRaw, pprintTT, pprintTTClause, prettyEnv, psubst   , pToV, pToVs, pureTerm, raw_apply, raw_unapply, refsIn, safeForget   , safeForgetEnv, showCG, showEnv, showEnvDbg, showSep-  , sImplementationN, sMN, sNS, spanFC, str, subst, substNames, substTerm+  , sImplementationN, sMN, sNS, str, subst, substNames, substTerm   , substV, sUN, tcname, termSmallerThan, tfail, thead, tnull   , toAlist, traceWhen, txt, unApply, uniqueBinders, uniqueName   , uniqueNameFrom, uniqueNameSet, unList, updateDef, vToP, weakenTm@@ -59,32 +59,26 @@  -- Work around AMP without CPP import Prelude (Bool(..), Double, Enum(..), Eq(..), FilePath, Functor(..), Int,-                Integer, Maybe(..), Monad(..), Num(..), Ord(..), Ordering(..),-                Read(..), Show(..), String, div, error, flip, fst, mod, not,-                otherwise, read, snd, ($), (&&), (.), (||))+                Integer, Maybe(..), Monad(..), Monoid(..), Num(..), Ord(..),+                Ordering(..), Show(..), String, div, error, fst, max, min, mod,+                not, otherwise, read, snd, ($), (&&), (.), (||))  import Control.Applicative (Alternative, Applicative(..)) import qualified Control.Applicative as A (Alternative(..)) import Control.DeepSeq (($!!)) import Control.Monad.State.Strict-import Control.Monad.Trans.Except (Except(..)) import Data.Binary hiding (get, put)-import qualified Data.Binary as B import Data.Char import Data.Data (Data) import Data.Foldable (Foldable) import Data.List hiding (group, insert) import qualified Data.Map.Strict as Map import Data.Maybe (listToMaybe)-import Data.Monoid (mconcat) import Data.Set (Set, fromList, insert, member) import qualified Data.Text as T import Data.Traversable (Traversable) import Data.Typeable (Typeable)-import Data.Vector.Unboxed (Vector)-import qualified Data.Vector.Unboxed as V import Debug.Trace-import Foreign.Storable (sizeOf) import GHC.Generics (Generic) import Numeric (showIntAtBase) import Numeric.IEEE (IEEE(identicalIEEE))@@ -93,7 +87,7 @@             | CheckConv   deriving Eq --- | Source location. These are typically produced by the parser 'Idris.Parser.getFC'+-- | Source location. These are typically produced by 'Idris.Parser.Stack.withExtent' data FC = FC { _fc_fname :: String, -- ^ Filename                _fc_start :: (Int, Int), -- ^ Line and column numbers for the start of the location span                _fc_end :: (Int, Int) -- ^ Line and column numbers for the end of the location span@@ -123,30 +117,23 @@ fc_end NoFC = (0, 0) fc_end (FileFC f) = (0, 0) --- | Get the largest span containing the two FCs-spanFC :: FC -> FC -> FC-spanFC (FC f start end) (FC f' start' end')-    | f == f' = FC f (minLocation start start') (maxLocation end end')-    | otherwise = NoFC-  where minLocation (l, c) (l', c') =-          case compare l l' of-            LT -> (l, c)-            EQ -> (l, min c c')-            GT -> (l', c')-        maxLocation (l, c) (l', c') =-          case compare l l' of-            LT -> (l', c')-            EQ -> (l, max c c')-            GT -> (l, c)-spanFC fc@(FC f _ _) (FileFC f') | f == f' = fc-                                 | otherwise = NoFC-spanFC (FileFC f') fc@(FC f _ _) | f == f' = fc+instance Monoid FC where+  mempty = NoFC++  -- | Get the largest span containing the two FCs+  mappend (FC f start end) (FC f' start' end')+      | f == f' = FC f (min start start') (max end end')+      | otherwise = NoFC+  mappend fc@(FC f _ _) (FileFC f') | f == f' = fc+                                    | otherwise = NoFC+  mappend (FileFC f') fc@(FC f _ _) | f == f' = fc+                                    | otherwise = NoFC+  mappend (FileFC f) (FileFC f') | f == f' = FileFC f                                  | otherwise = NoFC-spanFC (FileFC f) (FileFC f') | f == f' = FileFC f-                              | otherwise = NoFC-spanFC NoFC fc = fc-spanFC fc NoFC = fc+  mappend NoFC fc = fc+  mappend fc NoFC = fc + -- | Determine whether the first argument is completely contained in the second fcIn :: FC -> FC -> Bool fcIn NoFC   _ = False@@ -230,6 +217,7 @@                         -- from that file.                       | AnnQuasiquote                       | AnnAntiquote+                      | AnnSyntax String -- ^ type of syntax element: backslash or braces etc.   deriving (Show, Eq, Generic)  -- | Used for error reflection@@ -436,13 +424,6 @@ tfail :: Err -> TC a tfail e = Error e -failMsg :: String -> TC a-failMsg str = Error (Msg str)--trun :: FC -> TC a -> TC a-trun fc (OK a)    = OK a-trun fc (Error e) = Error (At fc e)- discard :: Monad m => m a -> m () discard f = f >> return () @@ -515,9 +496,6 @@ sImplementationN :: Name -> [String] -> SpecialName sImplementationN n ss = ImplementationN n (map T.pack ss) -sParentN :: Name -> String -> SpecialName-sParentN n s = ParentN n (T.pack s)- instance Sized Name where   size (UN n)     = 1   size (NS n els) = 1 + length els@@ -704,13 +682,6 @@ nativeTyWidth IT32 = 32 nativeTyWidth IT64 = 64 -{-# DEPRECATED intTyWidth "Non-total function, use nativeTyWidth and appropriate casing" #-}-intTyWidth :: IntTy -> Int-intTyWidth (ITFixed n) = nativeTyWidth n-intTyWidth ITNative = 8 * sizeOf (0 :: Int)-intTyWidth ITChar = error "IRTS.Lang.intTyWidth: Characters have platform and backend dependent width"-intTyWidth ITBig = error "IRTS.Lang.intTyWidth: Big integers have variable width"- data Const = I Int | BI Integer | Fl Double | Ch Char | Str String            | B8 Word8 | B16 Word16 | B32 Word32 | B64 Word64            | AType ArithTy | StrType@@ -867,7 +838,8 @@                 -- flag says whether it was a scoped implicit                 -- (i.e. forall bound) in the high level Idris, but                 -- otherwise has no relevance in TT.-              | Let   { binderTy  :: !b,+              | Let   { binderCount :: RigCount,+                        binderTy  :: !b,                         binderVal :: b {-^ value for bound variable-}}                 -- ^ A binding that occurs in a @let@ expression               | NLet  { binderTy  :: !b,@@ -905,7 +877,7 @@ instance Sized a => Sized (Binder a) where   size (Lam _ ty) = 1 + size ty   size (Pi _ _ ty _) = 1 + size ty-  size (Let ty val) = 1 + size ty + size val+  size (Let _ ty val) = 1 + size ty + size val   size (NLet ty val) = 1 + size ty + size val   size (Hole ty) = 1 + size ty   size (GHole _ _ ty) = 1 + size ty@@ -914,7 +886,7 @@   size (PVTy ty) = 1 + size ty  fmapMB :: Monad m => (a -> m b) -> Binder a -> m (Binder b)-fmapMB f (Let t v)   = liftM2 Let (f t) (f v)+fmapMB f (Let c t v)   = liftM2 (Let c) (f t) (f v) fmapMB f (NLet t v)  = liftM2 NLet (f t) (f v) fmapMB f (Guess t v) = liftM2 Guess (f t) (f v) fmapMB f (Lam c t)   = liftM (Lam c) (f t)@@ -1042,7 +1014,7 @@     -- "recursive => really big" if the name of the bound     -- variable is the same as the name we're using     -- So generate a different name in that case.-    termsize n (Bind n' (Let t v) sc)+    termsize n (Bind n' (Let c t v) sc)        = let rn = if n == n' then sMN 0 "noname" else n in              termsize rn v + termsize rn sc     termsize n (Bind n' b sc)@@ -1162,15 +1134,6 @@ isInjective (App _ f a)        = isInjective f isInjective _                  = False --- | Count the number of instances of a de Bruijn index in a term-vinstances :: Int -> TT n -> Int-vinstances i (V x) | i == x = 1-vinstances i (App _ f a) = vinstances i f + vinstances i a-vinstances i (Bind x b sc) = instancesB b + vinstances (i + 1) sc-  where instancesB (Let t v) = vinstances i v-        instancesB _ = 0-vinstances i t = 0- -- | Replace the outermost (index 0) de Bruijn variable with the given term instantiate :: TT n -> TT n -> TT n instantiate e = subst 0 where@@ -1294,10 +1257,10 @@                                   if u then (Proj x' idx, u) else (t, False)     subst' i t = (t, False) -    substB' i b@(Let t v) = let (t', ut) = subst' i t-                                (v', uv) = subst' i v in-                                if ut || uv then (Let t' v', True)-                                            else (b, False)+    substB' i b@(Let c t v) = let (t', ut) = subst' i t+                                  (v', uv) = subst' i v in+                                  if ut || uv then (Let c t' v', True)+                                              else (b, False)     substB' i b@(Guess t v) = let (t', ut) = subst' i t                                   (v', uv) = subst' i v in                                   if ut || uv then (Guess t' v', True)@@ -1344,7 +1307,7 @@   eqAlpha as (App _ fx ax) (App _ fy ay) = eqAlpha as fx fy && eqAlpha as ax ay   eqAlpha as x y = x == y -  eqAlphaB as (Let xt xv) (Let yt yv)+  eqAlphaB as (Let xc xt xv) (Let yc yt yv)        = eqAlpha as xt yt && eqAlpha as xv yv   eqAlphaB as (Guess xt xv) (Guess yt yv)        = eqAlpha as xt yt && eqAlpha as xv yv@@ -1357,7 +1320,7 @@     no' i (V x) | i == x = do num <- get; put (num + 1)     no' i (P Bound x _) | n == x = do num <- get; put (num + 1)     no' i (Bind n b sc) = do noB' i b; no' (i+1) sc-       where noB' i (Let t v) = do no' i t; no' i v+       where noB' i (Let c t v) = do no' i t; no' i v              noB' i (Guess t v) = do no' i t; no' i v              noB' i b = no' i (binderTy b)     no' i (App _ f a) = do no' i f; no' i a@@ -1371,7 +1334,7 @@     no' i (V x) = not (i == x)     no' i (P Bound x _) = not (n == x)     no' i (Bind n b sc) = noB' i b && no' (i+1) sc-       where noB' i (Let t v) = no' i t && no' i v+       where noB' i (Let c t v) = no' i t && no' i v              noB' i (Guess t v) = no' i t && no' i v              noB' i b = no' i (binderTy b)     no' i (App _ f a) = no' i f && no' i a@@ -1383,7 +1346,7 @@ freeNames t = nub $ freeNames' t   where     freeNames' (P _ n _) = [n]-    freeNames' (Bind n (Let t v) sc) = freeNames' v ++ (freeNames' sc \\ [n])+    freeNames' (Bind n (Let c t v) sc) = freeNames' v ++ (freeNames' sc \\ [n])                                             ++ freeNames' t     freeNames' (Bind n b sc) = freeNames' (binderTy b) ++ (freeNames' sc \\ [n])     freeNames' (App _ f a) = freeNames' f ++ freeNames' a@@ -1457,8 +1420,8 @@           b' <- safeForgetEnvB env b           sc' <- safeForgetEnv (n':env) sc           Just $ RBind n' b' sc'-  where safeForgetEnvB env (Let t v) = liftM2 Let (safeForgetEnv env t)-                                                  (safeForgetEnv env v)+  where safeForgetEnvB env (Let c t v) = liftM2 (Let c) (safeForgetEnv env t)+                                                        (safeForgetEnv env v)         safeForgetEnvB env (Guess t v) = liftM2 Guess (safeForgetEnv env t)                                                       (safeForgetEnv env v)         safeForgetEnvB env b = do ty' <- safeForgetEnv env (binderTy b)@@ -1646,7 +1609,8 @@     prettySb env n (PVar Rig1 t) = prettyB env "pat 1 " "." n t     prettySb env n (PVar _ t) = prettyB env "pat" "." n t     prettySb env n (PVTy t) = prettyB env "pty" "." n t-    prettySb env n (Let t v) = prettyBv env "let" "in" n t v+    prettySb env n (Let Rig1 t v) = prettyBv env "let 1 " "in" n t v+    prettySb env n (Let _ t v) = prettyBv env "let" "in" n t v     prettySb env n (NLet t v) = prettyBv env "nlet" "in" n t v     prettySb env n (Guess t v) = prettyBv env "??" "in" n t v @@ -1674,7 +1638,7 @@          = bracket p 2 $ sb env n b ++ se 10 ((n, rig, b):env) sc     se p env (Bind n b@(Pi rig _ t k) sc)         | noOccurrence n sc && not dbg = bracket p 2 $ se 1 env t ++ arrow rig ++ se 10 ((n,Rig0,b):env) sc-       where arrow Rig0 = " -> "+       where arrow Rig0 = " 0-> "              arrow Rig1 = " -o "              arrow RigW = " -> "     se p env (Bind n b sc) = bracket p 2 $ sb env n b ++ se 10 ((n,Rig0,b):env) sc@@ -1699,7 +1663,9 @@     sb env n (PVar Rig1 t) = showb env "pat 1 " ". " n t     sb env n (PVar _ t) = showb env "pat " ". " n t     sb env n (PVTy t) = showb env "pty " ". " n t-    sb env n (Let t v)   = showbv env "let " " in " n t v+    sb env n (Let Rig0 t v)   = showbv env "let 0 " " in " n t v+    sb env n (Let Rig1 t v)   = showbv env "let 1 " " in " n t v+    sb env n (Let _ t v)   = showbv env "let " " in " n t v     sb env n (NLet t v)   = showbv env "nlet " " in " n t v     sb env n (Guess t v) = showbv env "?? " " in " n t v @@ -1716,7 +1682,7 @@ pureTerm (Bind n b sc) = notInterfaceName n && pureBinder b && pureTerm sc where     pureBinder (Hole _) = False     pureBinder (Guess _ _) = False-    pureBinder (Let t v) = pureTerm t && pureTerm v+    pureBinder (Let c t v) = pureTerm t && pureTerm v     pureBinder t = pureTerm (binderTy t)      notInterfaceName (MN _ c) | c == txt "__interface" = False@@ -1740,7 +1706,7 @@ weakenEnv env = wk (length env - 1) env   where wk i [] = []         wk i ((n, c, b) : bs) = (n, c, weakenTmB i b) : wk (i - 1) bs-        weakenTmB i (Let   t v) = Let (weakenTm i t) (weakenTm i v)+        weakenTmB i (Let c t v) = Let c (weakenTm i t) (weakenTm i v)         weakenTmB i (Guess t v) = Guess (weakenTm i t) (weakenTm i v)         weakenTmB i t           = t { binderTy = weakenTm i (binderTy t) } @@ -1751,7 +1717,7 @@ refsIn :: TT Name -> [Name] refsIn (P _ n _) = [n] refsIn (Bind n b t) = nub $ nb b ++ refsIn t-  where nb (Let   t v) = nub (refsIn t) ++ nub (refsIn v)+  where nb (Let _ t v) = nub (refsIn t) ++ nub (refsIn v)         nb (Guess t v) = nub (refsIn t) ++ nub (refsIn v)         nb t = refsIn (binderTy t) refsIn (App s f a) = nub (refsIn f ++ refsIn a)@@ -1761,7 +1727,7 @@ allTTNames = nub . allNamesIn   where allNamesIn (P _ n _) = [n]         allNamesIn (Bind n b t) = [n] ++ nb b ++ allNamesIn t-          where nb (Let   t v) = allNamesIn t ++ allNamesIn v+          where nb (Let _ t v) = allNamesIn t ++ allNamesIn v                 nb (Guess t v) = allNamesIn t ++ allNamesIn v                 nb t = allNamesIn (binderTy t)         allNamesIn (App _ f a) = allNamesIn f ++ allNamesIn a@@ -1813,7 +1779,7 @@         where mkArrow Rig1 = text "⇴"               mkArrow Rig0 = text "⥛"               mkArrow _ = text "→"-    ppb p bound n (Let ty val) sc =+    ppb p bound n (Let _ ty val) sc =       bracket p startPrec . group . align $       (group . hang 2) (annotate AnnKeyword (text "let") <+>                         bindingOf n False <+> colon <+>@@ -1895,8 +1861,8 @@                      text "Lam" <$> pprintRaw bound ty     ppb (Pi _ _ ty k) = enclose lparen rparen . group . align . hang 2 $                         vsep [text "Pi", pprintRaw bound ty, pprintRaw bound k]-    ppb (Let ty v) = enclose lparen rparen . group . align . hang 2 $-                     vsep [text "Let", pprintRaw bound ty, pprintRaw bound v]+    ppb (Let c ty v) = enclose lparen rparen . group . align . hang 2 $+                       vsep [text "Let", pprintRaw bound ty, pprintRaw bound v]     ppb (NLet ty v) = enclose lparen rparen . group . align . hang 2 $                       vsep [text "NLet", pprintRaw bound ty, pprintRaw bound v]     ppb (Hole ty) = enclose lparen rparen . group . align . hang 2 $
src/Idris/Core/Typecheck.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Core.Typecheck Description : Idris' type checker.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -13,11 +13,8 @@  import Idris.Core.Evaluate import Idris.Core.TT-import Idris.Core.WHNF  import Control.Monad.State-import qualified Data.Vector.Unboxed as V (length)-import Debug.Trace  -- To check conversion, normalise each term wrt the current environment. -- Since we haven't converted everything to de Bruijn indices yet, we'll have to@@ -101,7 +98,9 @@   astate | holes = MaybeHoles          | otherwise = Complete -  chk :: RigCount -> -- multiplicity (need enough in context to produce this many of the term)+  chk :: RigCount -> -- 'sigma' in Bob Atkey's QTT paper, except that+               -- for implementation purposes it could be 0, 1 or omega when+               -- checking variable usage.          Type -> -- uniqueness level          Maybe UExp -> -- universe for kind          Env -> Raw -> StateT UCs TC (Term, Type, [Name])@@ -121,6 +120,7 @@     where rigSafe True _    _    n = Nothing           rigSafe _    Rig1 RigW n = Just ("Trying to use linear name " ++ show n ++ " in non-linear context")           rigSafe _    Rig0 RigW n = Just ("Trying to use irrelevant name " ++ show n ++ " in relevant context")+          rigSafe _    Rig0 Rig1 n = Just ("Trying to use irrelevant name " ++ show n ++ " in relevant context")           rigSafe _    _    _    n = Nothing            used Rig0 n = []@@ -140,13 +140,13 @@                do (v, cs) <- get                   put (v+1, ULT (UVar tcns v) v' : cs)                   let apty = simplify initContext env-                                 (Bind x (Let (TType v') (TType (UVar tcns v))) t)+                                 (Bind x (Let rig (TType v') (TType (UVar tcns v))) t)                   return (App Complete fv (TType (UVar tcns v)), apty, fns)              Bind x (Pi rig i s k) t ->                  do (av, aty, _) <- chk rigc u Nothing env RType                     convertsC ctxt env aty s                     let apty = simplify initContext env-                                        (Bind x (Let aty av) t)+                                        (Bind x (Let rig aty av) t)                     return (App astate fv av, apty, fns)              t -> lift $ tfail $ NonFunctionType fv fty   chk rigc u lvl env ap@(RApp f a)@@ -159,12 +159,16 @@                                      (rig, uniqueBinders (map fstEnv env) ty)                                   _ -> (RigW, uniqueBinders (map fstEnv env)                                                     (normalise ctxt env fty)) -- This is an error, caught below...-           (av, aty, ans) <- chk (rigMult rigc rigf) u Nothing env a+           (av, aty, ans_in) <- chk (rigMult rigf rigc) u Nothing env a+           -- usage in 'a' doesn't count if the binder has multiplicity 0+           let ans = case rigf of+                          Rig0 -> []+                          _ -> ans_in            case fty' of              Bind x (Pi rig i s k) t ->                  do convertsC ctxt env aty s                     let apty = simplify initContext env-                                        (Bind x (Let aty av) t)+                                        (Bind x (Let rig aty av) t)                     return (App astate fv av, apty, fns ++ ans)              t -> lift $ tfail $ NonFunctionType fv fty   chk rigc u lvl env RType@@ -198,8 +202,6 @@           constType _       = TType (UVal 0)   chk rigc u lvl env (RBind n (Pi rig i s k) t)       = do (sv, st, sns) <- chk Rig0 u Nothing (envZero env) s-           when (rig == RigW) $-                lift $ linearCheckArg ctxt (normalise ctxt env sv)            (v, cs) <- get            (kv, kt, _) <- chk Rig0 u Nothing (envZero env) k -- no need to validate these constraints, they are independent            put (v+1, cs)@@ -208,12 +210,6 @@                            Just v' -> v'            (tv, tt, tns) <- chk Rig0 st (Just maxu) ((n, Rig0, Pi Rig0 i sv kv) : envZero env) t ---            convertsC ctxt env st (TType maxu)---            convertsC ctxt env tt (TType maxu)---            when holes $ put (v, cs)---            return (Bind n (Pi i (uniqueBinders (map fst env) sv) (TType maxu))---                      (pToV n tv), TType maxu)-            case (normalise ctxt env st, normalise ctxt env tt) of                 (TType su, TType tu) -> do                     when (not holes) $ do (v, cs) <- get@@ -227,31 +223,22 @@                     return (Bind n (Pi rig i (uniqueBinders (map fstEnv env) sv) k')                                 (pToV n tv), k', sns ++ tns) -      where mkUniquePi kv (Bind n (Pi rig i s k) sc)-                    = let k' = smaller kv k in-                          Bind n (Pi rig i s k') (mkUniquePi k' sc)-            mkUniquePi kv (Bind n (Lam rig t) sc)-                    = Bind n (Lam rig (mkUniquePi kv t)) (mkUniquePi kv sc)-            mkUniquePi kv (Bind n (Let t v) sc)-                    = Bind n (Let (mkUniquePi kv t) v) (mkUniquePi kv sc)-            mkUniquePi kv t = t--            -- Kind of the whole thing is the kind of the most unique thing-            -- in the environment (because uniqueness taints everything...)-            mostUnique [] k = k-            mostUnique (Pi _ _ _ pk : es) k = mostUnique es (smaller pk k)-            mostUnique (_ : es) k = mostUnique es k--  chk rigc u lvl env (RBind n b sc)+  chk rigc_in u lvl env (RBind n b sc)       = do (b', bt', bns) <- checkBinder b            (scv, sct, scns) <- chk rigc (smaller bt' u) Nothing ((n, getCount b, b'):env) sc-           when (getCount b == RigW) $-             lift $ linearCheckArg ctxt (normalise ctxt env (binderTy b'))            checkUsageOK (getCount b) scns            discharge n b' bt' (pToV n scv) (pToV n sct) (bns ++ scns)-    where getCount (Pi rig _ _ _) = rigMult rigc rig+    where -- should only check at 0 or 1 (as in Bob's paper) but rigc_in+          -- might be RigW, since that's how we check in the Var rule that+          -- a linearly bound name is only used in a linear context.+          -- So, here, check the scope at multiplicity 1+          rigc = case rigc_in of+                      Rig0 -> Rig0+                      _ -> Rig1+          getCount (Pi rig _ _ _) = rigMult rigc rig           getCount (PVar rig _) = rigMult rigc rig           getCount (Lam rig _) = rigMult rigc rig+          getCount (Let rig _ _) = rigMult rigc rig           getCount _ = rigMult rigc RigW            checkUsageOK Rig0 _ = return ()@@ -264,23 +251,17 @@            checkBinder (Lam rig t)             = do (tv, tt, _) <- chk Rig0 u Nothing (envZero env) t-                 let tv' = normalise ctxt env tv                  convType tcns ctxt env tt                  return (Lam rig tv, tt, [])-          checkBinder (Let t v)+          checkBinder (Let rig t v)             = do (tv, tt, _) <- chk Rig0 u Nothing (envZero env) t-                 -- May have multiple uses, check at RigW-                 -- (or rather, like an application of a lambda, multiply)-                 -- (Consider: adding a single use let?)-                 (vv, vt, vns) <- chk (rigMult rigc RigW) u Nothing env v-                 let tv' = normalise ctxt env tv+                 (vv, vt, vns) <- chk (rigMult rig rigc) u Nothing env v                  convertsC ctxt env vt tv                  convType tcns ctxt env tt-                 return (Let tv vv, tt, vns)+                 return (Let rig tv vv, tt, vns)           checkBinder (NLet t v)             = do (tv, tt, _) <- chk Rig0 u Nothing (envZero env) t                  (vv, vt, vns) <- chk rigc u Nothing env v-                 let tv' = normalise ctxt env tv                  convertsC ctxt env vt tv                  convType tcns ctxt env tt                  return (NLet tv vv, tt, vns)@@ -288,12 +269,10 @@             | not holes = lift $ tfail (IncompleteTerm undefined)             | otherwise                    = do (tv, tt, _) <- chk Rig0 u Nothing (envZero env) t-                        let tv' = normalise ctxt env tv                         convType tcns ctxt env tt                         return (Hole tv, tt, [])           checkBinder (GHole i ns t)             = do (tv, tt, _) <- chk Rig0 u Nothing (envZero env) t-                 let tv' = normalise ctxt env tv                  convType tcns ctxt env tt                  return (GHole i ns tv, tt, [])           checkBinder (Guess t v)@@ -301,20 +280,15 @@             | otherwise                    = do (tv, tt, _) <- chk Rig0 u Nothing (envZero env) t                         (vv, vt, vns) <- chk rigc u Nothing env v-                        let tv' = normalise ctxt env tv                         convertsC ctxt env vt tv                         convType tcns ctxt env tt                         return (Guess tv vv, tt, vns)           checkBinder (PVar rig t)             = do (tv, tt, _) <- chk Rig0 u Nothing (envZero env) t-                 let tv' = normalise ctxt env tv                  convType tcns ctxt env tt-                 -- Normalised version, for erasure purposes (it's easier-                 -- to tell if it's a collapsible variable)                  return (PVar rig tv, tt, [])           checkBinder (PVTy t)             = do (tv, tt, _) <- chk Rig0 u Nothing (envZero env) t-                 let tv' = normalise ctxt env tv                  convType tcns ctxt env tt                  return (PVTy tv, tt, []) @@ -322,10 +296,10 @@             = return (Bind n (Lam r t) scv, Bind n (Pi r Nothing t bt) sct, ns)           discharge n (Pi r i t k) bt scv sct ns             = return (Bind n (Pi r i t k) scv, sct, ns)-          discharge n (Let t v) bt scv sct ns-            = return (Bind n (Let t v) scv, Bind n (Let t v) sct, ns)+          discharge n (Let r t v) bt scv sct ns+            = return (Bind n (Let r t v) scv, Bind n (Let r t v) sct, ns)           discharge n (NLet t v) bt scv sct ns-            = return (Bind n (NLet t v) scv, Bind n (Let t v) sct, ns)+            = return (Bind n (NLet t v) scv, Bind n (Let RigW t v) sct, ns)           discharge n (Hole t) bt scv sct ns             = return (Bind n (Hole t) scv, sct, ns)           discharge n (GHole i ns t) bt scv sct uns@@ -373,7 +347,7 @@        = do chkBinderName env n b             st <- get             case b of-                 Let t v -> chkBinders env v+                 Let _ t v -> chkBinders env v                  _ -> return ()             chkBinders ((n, Rig0, b) : env) t     chkBinders env t = return ()
src/Idris/Core/Unify.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Core.Unify Description : Idris' unification code.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. @@ -22,11 +22,9 @@ import Idris.Core.Evaluate import Idris.Core.TT -import Control.Monad import Control.Monad.State.Strict import Data.List import Data.Maybe-import Debug.Trace  -- terms which need to be injective, with the things we're trying to unify -- at the time@@ -39,7 +37,6 @@                                }   deriving (Eq, Show) -type Injs = [(TT Name, TT Name, TT Name)] type Fails = [(TT Name, TT Name, -- unification error                Bool, -- ready to retry yet                Env, Err, [FailContext], FailAt)]@@ -57,10 +54,6 @@ data UInfo = UI Int Fails      deriving Show -data UResult a = UOK a-               | UPartOK a-               | UFail Err- -- | Smart constructor for unification errors that takes into account the FailContext cantUnify :: [FailContext] -> Bool -> (t, Maybe Provenance) -> (t, Maybe Provenance) -> (Err' t) -> [(Name, t)] -> Int -> Err' t cantUnify [] r t1 t2 e ctxt i = CantUnify r t1 t2 e ctxt i@@ -137,9 +130,10 @@                                    lift $ tfail err  -    uB bnames (Let tx vx) (Let ty vy) = do h1 <- un bnames tx ty-                                           h2 <- un bnames vx vy-                                           combine bnames h1 h2+    uB bnames (Let _ tx vx) (Let _ ty vy)+         = do h1 <- un bnames tx ty+              h2 <- un bnames vx vy+              combine bnames h1 h2     uB bnames (Lam _ tx) (Lam _ ty) = un bnames tx ty     uB bnames (Pi r i tx _) (Pi r' i' ty _) = un bnames tx ty     uB bnames x y = do UI s f <- get@@ -191,16 +185,10 @@         | otherwise = checkScope ns (x, tm)      checkScope ns (x, tm) =---           case boundVs (envPos x 0 env) tm of---                [] -> return [(x, tm)]---                (i:_) -> lift $ tfail (UnifyScope x (fst (fst (ns!!i)))---                                      (impl ns tm) (errEnv env))         let v = highV (-1) tm in             if v >= length ns                then lift $ tfail (Msg "SCOPE ERROR")                else return [(x, bind v ns tm)]-      where impl [] tm = tm-            impl ((n, _) : ns) tm = impl ns (substV (P Bound n Erased) tm)      bind i ns tm       | i < 0 = tm@@ -257,20 +245,6 @@         followSols vs (n : ns) = do ns' <- followSols vs ns                                     return $ n : ns' -expandLets env (x, tm) = (x, doSubst (reverse env) tm)-  where-    doSubst [] tm = tm-    doSubst ((n, Let v t) : env) tm-        = doSubst env (subst n v tm)-    doSubst (_ : env) tm-        = doSubst env tm--hasv :: TT Name -> Bool-hasv (V x) = True-hasv (App _ f a) = hasv f || hasv a-hasv (Bind x b sc) = hasv (binderTy b) || hasv sc-hasv _ = False- unify :: Context -> Env ->          (TT Name, Maybe Provenance) ->          (TT Name, Maybe Provenance) ->@@ -297,10 +271,6 @@ --         Error e@(CantUnify False _ _ _ _ _)  -> tfail e                        Error e -> tfail e   where-    headDiff (P (DCon _ _ _) x _) (P (DCon _ _ _) y _) = x /= y-    headDiff (P (TCon _ _) x _) (P (TCon _ _) y _) = x /= y-    headDiff _ _ = False-     injective (P (DCon _ _ _) _ _) = True     injective (P (TCon _ _) _ _) = True --     injective (P Ref n _)@@ -327,10 +297,6 @@     sc i = do UI s f <- get               put (UI (s+i) f) -    errors :: StateT UInfo TC Bool-    errors = do UI s f <- get-                return (not (null f))-     uplus u1 u2 = do UI s f <- get                      r <- u1                      UI s f' <- get@@ -342,12 +308,6 @@           StateT UInfo           TC [(Name, TT Name)]     un = un' env---     un fn names x y---         = let (xf, _) = unApply x---               (yf, _) = unApply y in---               if headDiff xf yf then unifyFail x y else---                   uplus (un' fn names x y)---                         (un' fn names (hnf ctxt env x) (hnf ctxt env y))      un' :: Env -> Bool -> [((Name, Name), TT Name)] -> TT Name -> TT Name ->            StateT UInfo@@ -577,27 +537,12 @@                 = unifyFail appx appy             checkHeads _ _ = return [] -            numArgs tm = let (f, args) = unApply tm in length args-             metavarApp tm = let (f, args) = unApply tm in                                 (metavar f &&                                  all (\x -> metavarApp x) args                                     && nub args == args) ||                                        globmetavar tm-            metavarArgs tm = let (f, args) = unApply tm in-                                 all (\x -> metavar x || inenv x) args-                                   && nub args == args-            metavarApp' tm = let (f, args) = unApply tm in-                                 all (\x -> pat x || metavar x) (f : args)-                                   && nub args == args -            rigid (P (DCon _ _ _) _ _) = True-            rigid (P (TCon _ _) _ _) = True-            rigid t@(P Ref _ _)  = inenv t || globmetavar t-            rigid (Constant _)       = True-            rigid (App _ f a)        = rigid f && rigid a-            rigid t                  = not (metavar t) || globmetavar t-             globmetavar t = case unApply t  of                                 (P _ x _, _) ->                                    case lookupDef x ctxt of@@ -610,15 +555,7 @@                                              (x `elem` holes || holeIn env x))                                           || globmetavar t                              _ -> False-            pat t = case t of-                         P _ x _ -> x `elem` holes || patIn env x-                         _ -> False-            inenv t = case t of-                           P _ x _ -> x `elem` (map fstEnv env)-                           _ -> False -            notFn t = injective t || metavar t || inenv t-             injectiveTC t@(P Ref n _) t'@(P Ref n' _)                 | Just ni <- lookupInjectiveExact n ctxt,                   Just ni' <- lookupInjectiveExact n' ctxt@@ -649,7 +586,7 @@                        lift $ tfail err  -    uB env bnames (Let tx vx) (Let ty vy)+    uB env bnames (Let _ tx vx) (Let _ ty vy)         = do h1 <- un' env False bnames tx ty              h2 <- un' env False bnames vx vy              sc 1@@ -682,16 +619,10 @@         | otherwise = checkScope ns (x, tm)      checkScope ns (x, tm) | pureTerm tm =---           case boundVs (envPos x 0 env) tm of---                [] -> return [(x, tm)]---                (i:_) -> lift $ tfail (UnifyScope x (fst (fst (ns!!i)))---                                      (impl ns tm) (errEnv env))         let v = highV (-1) tm in             if v >= length ns                then lift $ tfail (Msg "SCOPE ERROR")                else return [(x, bind v ns tm)]-      where impl [] tm = tm-            impl (((n, _), _) : ns) tm = impl ns (substV (P Bound n Erased) tm)     checkScope ns (x, tm) = lift $ tfail (Msg "HOLE ERROR")      bind i ns tm@@ -710,15 +641,6 @@                           sc 1                           combine env bnames as (ns' ++ bs) -boundVs :: Int -> Term -> [Int]-boundVs i (V j) | j < i = []-                | otherwise = [j]-boundVs i (Bind n b sc) = boundVs (i + 1) sc-boundVs i (App _ f x) = let fs = boundVs i f-                            xs = boundVs i x in-                            nub (fs ++ xs)-boundVs i _ = []- highV :: Int -> Term -> Int highV i (V j) | j > i = j                 | otherwise = i@@ -726,11 +648,6 @@ highV i (App _ f x) = max (highV i f) (highV i x) highV i _ = i -envPos x i [] = 0-envPos x i ((y, _) : ys) | x == y = i-                         | otherwise = envPos x (i + 1) ys-- -- If there are any clashes of constructors, deem it unrecoverable, otherwise some -- more work may help. -- FIXME: Depending on how overloading gets used, this may cause problems. Better@@ -795,10 +712,4 @@ holeIn env n = case lookupBinder n env of                     Just (Hole _) -> True                     Just (Guess _ _) -> True-                    _ -> False--patIn :: Env -> Name -> Bool-patIn env n = case lookupBinder n env of-                    Just (PVar _ _) -> True-                    Just (PVTy _) -> True                     _ -> False
src/Idris/Core/WHNF.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Core.WHNF Description : Reduction to Weak Head Normal Form-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -12,11 +12,8 @@  import Idris.Core.CaseTree import Idris.Core.Evaluate hiding (quote)-import qualified Idris.Core.Evaluate as Evaluate import Idris.Core.TT -import Debug.Trace- -- | A stack entry consists of a term and the environment it is to be -- evaluated in (i.e. it's a thunk) type StackEntry = (Term, WEnv)@@ -88,7 +85,7 @@          | i < length env = let (tm, env') = env !! i in                                 eval env' stk tm          | otherwise = WV i-    eval wenv@(WEnv d env) stk (Bind n (Let t v) sc)+    eval wenv@(WEnv d env) stk (Bind n (Let c t v) sc)          = eval (WEnv d ((v, wenv) : env)) stk sc     eval (WEnv d env) ((tm, tenv) : stk) (Bind n b@(Lam _ _) sc)          = eval (WEnv d ((tm, tenv) : env)) stk sc@@ -97,7 +94,7 @@               WBind n' (fmap (\t -> (t, wenv)) b) (sc, WEnv (d + 1) env)      eval env stk (P nt n ty)-         | Just (Let t v) <- lookupBinder n genv = eval env stk v+         | Just (Let c t v) <- lookupBinder n genv = eval env stk v     eval env stk (P nt n ty) = apply env nt n ty stk     eval env stk (App _ f a) = eval env ((a, env) : stk) f     eval env stk (Constant c) = unload (WConstant c) stk
src/Idris/Coverage.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Coverage Description : Clause generation for coverage checking-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -16,14 +16,11 @@ import Idris.Delaborate import Idris.Elab.Utils import Idris.Error-import Idris.Output (iWarn, iputStrLn)  import Control.Monad.State.Strict import Data.Char-import Data.Either import Data.List import Data.Maybe-import Debug.Trace  -- | Generate a pattern from an 'impossible' LHS. --@@ -284,10 +281,6 @@     collectConsts (ConstCase c sc) = Just c     collectConsts _ = Nothing -    hasDefault (DefaultCase (UnmatchedCase _)) = False-    hasDefault (DefaultCase _) = True-    hasDefault _ = False-     getConType n = do ty <- lookupTyExact n (tt_ctxt ist)                       case unApply (getRetTy (normalise (tt_ctxt ist) [] ty)) of                            (P _ tyn _, _) -> Just tyn@@ -335,9 +328,6 @@         = SucCase n (trim cs nots sc) : trimAlts cs nots vn rest     trimAlts cs nots vn (DefaultCase sc : rest)         = DefaultCase (trim cs nots sc) : trimAlts cs nots vn rest--    isConMatch c (ConCase cn t args sc) = c == cn-    isConMatch _ _ = False      substMatch :: (Name, [Name]) -> [CaseAlt] -> [CaseAlt]     substMatch ca [] = []
src/Idris/DSL.hs view
@@ -1,22 +1,20 @@ {-| Module      : Idris.DSL Description : Code to deal with DSL blocks.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}  {-# LANGUAGE PatternGuards #-} -module Idris.DSL where+module Idris.DSL (debindApp, desugar) where  import Idris.AbsSyntax-import Idris.Core.Evaluate import Idris.Core.TT  import Control.Monad.State.Strict import Data.Generics.Uniplate.Data (transform)-import Debug.Trace  debindApp :: SyntaxInfo -> PTerm -> PTerm debindApp syn t = debind (dsl_bind (dsl_info syn)) t@@ -56,12 +54,12 @@         = PApp fc lam [ pexp (mkTTName fc n)                       , pexp (expandSugar dsl (var dsl n tm 0))] expandSugar dsl (PLam fc n nfc ty tm) = PLam fc n nfc (expandSugar dsl ty) (expandSugar dsl tm)-expandSugar dsl (PLet fc n nfc ty v tm)+expandSugar dsl (PLet fc rc n nfc ty v tm)     | Just letb <- dsl_let dsl         = PApp (fileFC "(dsl)") letb [ pexp (mkTTName fc n)                                      , pexp (expandSugar dsl v)                                      , pexp (expandSugar dsl (var dsl n tm 0))]-expandSugar dsl (PLet fc n nfc ty v tm) = PLet fc n nfc (expandSugar dsl ty) (expandSugar dsl v) (expandSugar dsl tm)+expandSugar dsl (PLet fc rc n nfc ty v tm) = PLet fc rc n nfc (expandSugar dsl ty) (expandSugar dsl v) (expandSugar dsl tm) expandSugar dsl (PPi p n fc ty tm)     | Just pi <- dsl_pi dsl         = PApp (fileFC "(dsl)") pi [ pexp (mkTTName (fileFC "(dsl)") n)@@ -105,10 +103,10 @@         = PApp fc b [pexp tm, pexp (PLam fc (sMN 0 "__bpat") NoFC Placeholder                                    (PCase fc (PRef fc [] (sMN 0 "__bpat"))                                              ((p, block b rest) : alts)))]-    block b (DoLet fc n nfc ty tm : rest)-        = PLet fc n nfc ty tm (block b rest)-    block b (DoLetP fc p tm : rest)-        = PCase fc tm [(p, block b rest)]+    block b (DoLet fc rc n nfc ty tm : rest)+        = PLet fc rc n nfc ty tm (block b rest)+    block b (DoLetP fc p tm alts : rest)+        = PCase fc tm ((p, block b rest) : alts)     block b (DoRewrite fc h : rest)         = PRewrite fc Nothing h (block b rest) Nothing     block b (DoExp fc tm : rest)@@ -136,10 +134,10 @@         | Nothing <- dsl_lambda dsl             = PLam fc n nfc ty (v' i sc)         | otherwise = PLam fc n nfc (v' i ty) (v' (i + 1) sc)-    v' i (PLet fc n nfc ty val sc)+    v' i (PLet fc rc n nfc ty val sc)         | Nothing <- dsl_let dsl-            = PLet fc n nfc (v' i ty) (v' i val) (v' i sc)-        | otherwise = PLet fc n nfc (v' i ty) (v' i val) (v' (i + 1) sc)+            = PLet fc rc n nfc (v' i ty) (v' i val) (v' i sc)+        | otherwise = PLet fc rc n nfc (v' i ty) (v' i val) (v' (i + 1) sc)     v' i (PPi p n fc ty sc)         | Nothing <- dsl_pi dsl             = PPi p n fc (v' i ty) (v' i sc)@@ -169,8 +167,7 @@     setFC fc t = t  unIdiom :: PTerm -> PTerm -> FC -> PTerm -> PTerm-unIdiom ap pure fc e@(PApp _ _ _) = let f = getFn e in-                                        mkap (getFn e)+unIdiom ap pure fc e@(PApp _ _ _) = mkap (getFn e)   where     getFn (PApp fc f args) = (PApp fc pure [pexp f], args)     getFn f = (f, [])@@ -203,8 +200,9 @@               arg' <- db' arg               return (PWithApp fc t' arg')     db' (PLam fc n nfc ty sc) = return (PLam fc n nfc ty (debind b sc))-    db' (PLet fc n nfc ty v sc) = do v' <- db' v-                                     return (PLet fc n nfc ty v' (debind b sc))+    db' (PLet fc rc n nfc ty v sc)+        = do v' <- db' v+             return (PLet fc rc n nfc ty v' (debind b sc))     db' (PCase fc s opts) = do s' <- db' s                                return (PCase fc s' (map (pmap (debind b)) opts))     db' (PPair fc hls p l r) = do l' <- db' l
src/Idris/DataOpts.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.DataOpts Description : Optimisations for Idris code i.e. Forcing, detagging and collapsing.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -10,14 +10,8 @@ module Idris.DataOpts(applyOpts) where  import Idris.AbsSyntax-import Idris.AbsSyntaxTree import Idris.Core.TT -import Control.Applicative-import Data.List-import Data.Maybe-import Debug.Trace- class Optimisable term where     applyOpts :: term -> Idris term @@ -49,7 +43,7 @@  -- Erase types (makes ibc smaller, and we don't need them) instance Optimisable (Binder (TT Name)) where-    applyOpts (Let t v) = Let <$> return Erased <*> applyOpts v+    applyOpts (Let r t v) = Let r <$> return Erased <*> applyOpts v     applyOpts b = return (b { binderTy = Erased })  instance Optimisable (Binder Raw) where
src/Idris/DeepSeq.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.DeepSeq Description : NFData instances for Idris' types-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -24,7 +24,6 @@  import Util.DynamicLinker -import qualified Cheapskate.Types as CT import Control.DeepSeq import Network.Socket (PortNumber) 
src/Idris/Delaborate.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Delaborate Description : Convert core TT back into high level syntax, primarily for display purposes.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -26,10 +26,9 @@ import Control.Applicative (Alternative((<|>))) import Control.Monad.State import Data.Generics.Uniplate.Data (transform)-import Data.List (intersperse, nub)+import Data.List (nub) import Data.Maybe (mapMaybe) import qualified Data.Text as T-import Debug.Trace  bugaddr = "https://github.com/idris-lang/Idris-dev/issues" @@ -56,13 +55,13 @@       = PConstant fc (BI i)     resugarApp tm = tm -    flattenDoLet (PLet _ ln _ ty v bdy)+    flattenDoLet (PLet _ rc ln _ ty v bdy)       | PDoBlock dos <- flattenDoLet bdy-      = PDoBlock (DoLet NoFC ln NoFC ty v : dos)+      = PDoBlock (DoLet NoFC rc ln NoFC ty v : dos)     flattenDoLet (PDoBlock dos) =       PDoBlock $ concatMap fixExp dos-        where fixExp (DoExp _ (PLet _ ln _ ty v bdy)) =-                DoLet NoFC ln NoFC ty v : fixExp (DoExp NoFC bdy)+        where fixExp (DoExp _ (PLet _ rc ln _ ty v bdy)) =+                DoLet NoFC rc ln NoFC ty v : fixExp (DoExp NoFC bdy)               fixExp d = [d]     flattenDoLet tm = tm @@ -173,13 +172,13 @@           = PPi (expl { pcount = rig }) n NoFC (de tys env [] ty)                 (de ((n, ty) : tys) ((n,n):env) [] sc) -    de tys env imps (Bind n (Let ty val) sc)+    de tys env imps (Bind n (Let rc ty val) sc)           | docases           , isCaseApp sc           , (P _ cOp _, args) <- unApply sc           , Just caseblock    <- delabCase tys env imps val cOp args = caseblock           | otherwise    =-              PLet un n NoFC (de tys env [] ty)+              PLet un rc n NoFC (de tys env [] ty)                    (de tys env [] val) (de ((n, ty) : tys) ((n,n):env) [] sc)     de tys env _ (Bind n (Hole ty) sc) = de ((n, ty) : tys) ((n, sUN "[__]"):env) [] sc     de tys env _ (Bind n (Guess ty val) sc) = de ((n, ty) : tys) ((n, sUN "[__]"):env) [] sc@@ -192,13 +191,6 @@     de tys env _ (TType i) = PType un     de tys env _ (UType u) = PUniverse un u -    dens x | fullname = x-    dens ns@(NS n _) = case lookupCtxt n (idris_implicits ist) of-                              [_] -> n -- just one thing-                              [] -> n -- metavariables have no implicits-                              _ -> ns-    dens n = n-     deFn tys env (App _ f a) args = deFn tys env f (a:args)     deFn tys env (P _ n _) [l,r]          | n == pairTy    = PPair un [] IsType (de tys env [] l) (de tys env [] r)@@ -354,7 +346,7 @@              then text "Unification failure" <$> showSc i sc              else empty pprintErr' i (CantConvert x_in y_in env) =- let (x_ns, y_ns, nms) = renameMNs x_in y_in+ let (x_ns, y_ns, _) = renameMNs x_in y_in      (x, y) = addImplicitDiffs (delabSugared i (flagUnique x_ns))                                (delabSugared i (flagUnique y_ns)) in   text "Type mismatch between" <>@@ -449,7 +441,7 @@        = getMissing (n : hs) (n : env) sc    getMissing hs env (Bind n (Guess _ _) sc)        = getMissing (n : hs) (n : env) sc-   getMissing hs env (Bind n (Let t v) sc)+   getMissing hs env (Bind n (Let rc t v) sc)        = getMissing hs env t ++          getMissing hs env v ++          getMissing hs (n : env) sc
src/Idris/Directives.hs view
@@ -1,14 +1,13 @@ {-| Module      : Idris.Directives Description : Act upon Idris directives.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -} module Idris.Directives(directiveAction) where  import Idris.AbsSyntax-import Idris.ASTUtils import Idris.Core.Evaluate import Idris.Core.TT import Idris.Imports
src/Idris/Docs.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Docs Description : Data structures and utilities to work with Idris Documentation.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -239,10 +239,6 @@      updateRef nm (PRef fc _ _) = PRef fc [] nm     updateRef _  pt          = pt--    isSubInterface (PPi (Constraint _ _ _) _ _ (PApp _ _ args) (PApp _ (PRef _ _ nm) args')) = nm == n && map getTm args == map getTm args'-    isSubInterface (PPi _   _            _ _ pt)                                           = isSubInterface pt-    isSubInterface _                                                                       = False      prettyConstraints =       cat (punctuate (comma <> space) (map (pprintPTerm ppo params' [] infixes) constraints))
src/Idris/Docstrings.hs view
@@ -1,7 +1,7 @@ {-| Module      :  Idris.Docstrings Description : Wrapper around Markdown library.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}
src/Idris/Elab/AsPat.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Elab.AsPat Description : Code to elaborate pattern variables.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -10,20 +10,31 @@ import Idris.AbsSyntax import Idris.Core.TT -import Control.Applicative import Control.Monad.State.Strict-import Data.Generics.Uniplate.Data (transformM)+import Data.Generics.Uniplate.Data (transformM, universe)  -- | Desugar by changing x@y on lhs to let x = y in ... or rhs-desugarAs :: PTerm -> PTerm -> (PTerm, PTerm)-desugarAs lhs rhs-    = let (lhs', pats) = runState (collectAs (replaceUnderscore lhs)) [] in-          (lhs', bindPats pats rhs)+desugarAs :: PTerm -> PTerm -> [PDecl] -> (PTerm, PTerm, [PDecl])+desugarAs lhs rhs whereblock+    = (lhs', bindOnRight rhs pats, map (bindInWhereDecl pats) whereblock)   where-    bindPats :: [(Name, FC, PTerm)] -> PTerm -> PTerm-    bindPats [] rhs = rhs-    bindPats ((n, fc, tm) : ps) rhs-       = PLet fc n NoFC Placeholder tm (bindPats ps rhs)+    (lhs', pats) = runState (collectAs (replaceUnderscore lhs)) []++    bindOnRight :: PTerm -> [(Name, FC, PTerm)] -> PTerm+    bindOnRight = foldr (\(n, fc, tm) -> PLet fc RigW n NoFC Placeholder tm)++    bindInWhereDecl :: [(Name, FC, PTerm)] -> PDecl -> PDecl+    bindInWhereDecl pats (PClauses fc opts n clauses)+       = PClauses fc opts n $ map (bindInWhereClause pats) clauses+    bindInWhereDecl _ d = d++    bindInWhereClause :: [(Name, FC, PTerm)] -> PClause -> PClause+    bindInWhereClause pats (PClause fc n lhs ws rhs wb)+       = let bound = [ n | (PRef _ _ n) <- universe lhs ]+             pats' = filter (not . (`elem` bound) . \(n,_,_) -> n) pats+             rhs'  = bindOnRight rhs pats' in+         PClause fc n lhs ws rhs' $ map (bindInWhereDecl pats') wb+    bindInWhereClause _ c = c  collectAs :: PTerm -> State [(Name, FC, PTerm)] PTerm collectAs (PAs fc n tm) = do tm' <- collectAs tm
src/Idris/Elab/Clause.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Elab.Clause Description : Code to elaborate clauses.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -13,51 +13,37 @@ import Idris.Core.CaseTree import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Evaluate-import Idris.Core.Execute import Idris.Core.TT import Idris.Core.Typecheck import Idris.Core.WHNF import Idris.Coverage import Idris.DataOpts-import Idris.DeepSeq+import Idris.DeepSeq () import Idris.Delaborate import Idris.Docstrings hiding (Unchecked)-import Idris.DSL import Idris.Elab.AsPat import Idris.Elab.Term import Idris.Elab.Transform import Idris.Elab.Type import Idris.Elab.Utils import Idris.Error-import Idris.Imports-import Idris.Inliner import Idris.Options-import Idris.Output (iRenderResult, iWarn, iputStrLn, pshow, sendHighlighting)+import Idris.Output (iWarn, pshow, sendHighlighting) import Idris.PartialEval-import Idris.Primitives-import Idris.Providers import Idris.Termination import Idris.Transforms-import IRTS.Lang  import Util.Pretty hiding ((<$>))-import Util.Pretty (pretty, text)  import Prelude hiding (id, (.)) -import Control.Applicative hiding (Const) import Control.Category import Control.DeepSeq import Control.Monad import qualified Control.Monad.State.Lazy as LState import Control.Monad.State.Strict as State-import Data.Char (isLetter, toLower) import Data.List-import Data.List.Split (splitOn)-import qualified Data.Map as Map import Data.Maybe-import qualified Data.Set as S-import qualified Data.Text as T import Data.Word import Debug.Trace import Numeric@@ -153,12 +139,6 @@            -- optimisation applied to LHS            let pdef = map (\(ns, lhs, rhs) -> (map fst ns, lhs, rhs)) $                           map debind pats_forced-           -- pdef_cov is the pattern definition without forcing, which-           -- we feed to the coverage checker (we need to know what the-           -- programmer wrote before forcing erasure)-           let pdef_cov-                    = map (\(ns, lhs, rhs) -> (map fst ns, lhs, rhs)) $-                          map debind pats_raw            -- pdef_pe is the one which will get further optimised            -- for run-time, with no forcing optimisation of the LHS because            -- the affects erasure. Also, it's partially evaluated@@ -173,8 +153,6 @@            -- help with later inlinings.             ist <- getIState-           let pdef_inl = inlineDef ist pdef-            numArgs <- tclift $ sameLength pdef             case specNames opts of@@ -197,7 +175,6 @@                               missing' <- checkPossibles info fc True n missing                               -- Filter out the ones which match one of the                               -- given cases (including impossible ones)-                              let clhs = map getLHS pdef                               logElab 2 $ "Must be unreachable (" ++ show (length missing') ++ "):\n" ++                                           showSep "\n" (map showTmImpls missing') ++                                          "\nAgainst: " ++@@ -228,9 +205,8 @@            case tree of                CaseDef _ _ [] -> return ()                CaseDef _ _ xs -> mapM_ (\x ->-                   iputStrLn $ show fc ++-                                ":warning - Unreachable case: " ++-                                   show (delab ist x)) xs+                   iWarn fc $ text "Unreachable case:" </> text (show (delab ist x))+                   ) xs            let knowncovering = (pcover && cov) || AssertTotal `elem` opts            let defaultcase = if knowncovering                                 then STerm Erased@@ -245,7 +221,6 @@            logElab 3 $ "Optimised: " ++ show tree'            ctxt <- getContext            ist <- getIState-           let opt = idris_optimisation ist            putIState (ist { idris_patdefs = addDef n (force pdef_pe, force pmissing)                                                 (idris_patdefs ist) })            let caseInfo = CaseInfo (inlinable opts) (inlinable opts) (dictionary opts)@@ -315,15 +290,6 @@                                   return ()    where-    noMatch i cs tm = all (\x -> case trim_matchClause i (delab' i x True True) tm of-                                      Right _ -> False-                                      Left miss -> True) cs-      where-        trim_matchClause i (PApp fcl fl ls) (PApp fcr fr rs)-            = let args = min (length ls) (length rs) in-                  matchClause i (PApp fcl fl (take args ls))-                                (PApp fcr fr (take args rs))-     checkUndefined n ctxt = case lookupDef n ctxt of                                  [] -> return ()                                  [TyDecl _ _] -> return ()@@ -371,7 +337,7 @@      sameLength ((_, x, _) : xs)         = do l <- sameLength xs-             let (f, as) = unApply x+             let (_, as) = unApply x              if (null xs || l == length as) then return (length as)                 else tfail (At fc (Msg "Clauses have differing numbers of arguments "))     sameLength [] = return 0@@ -542,7 +508,7 @@     concreteTm ist (Constant _) = True     concreteTm ist (Bind n (Lam _ _) sc) = True     concreteTm ist (Bind n (Pi _ _ _ _) sc) = True-    concreteTm ist (Bind n (Let _ _) sc) = concreteTm ist sc+    concreteTm ist (Bind n (Let _ _ _) sc) = concreteTm ist sc     concreteTm ist _ = False      -- get the type of a specialised application@@ -683,11 +649,10 @@                           logElab 5 $ "Elaborated impossible case " ++ showTmImpls lhs ++                                       "\n" ++ show ptm                           return (Left ptm, lhs)-elabClause info opts (cnum, PClause fc fname lhs_in_as withs rhs_in_as whereblock)-   = do let tcgen = Dictionary `elem` opts-        push_estack fname False+elabClause info opts (cnum, PClause fc fname lhs_in_as withs rhs_in_as whereblock_as)+   = do push_estack fname False         ctxt <- getContext-        let (lhs_in, rhs_in) = desugarAs lhs_in_as rhs_in_as+        let (lhs_in, rhs_in, whereblock) = desugarAs lhs_in_as rhs_in_as whereblock_as          -- Build the LHS as an "Infer", and pull out its type and         -- pattern bindings@@ -696,8 +661,9 @@          -- Check if we have "with" patterns outside of "with" block         when (isOutsideWith lhs_in && (not $ null withs)) $-            ierror (At fc (Elaborating "left hand side of " fname Nothing-                          (Msg "unexpected patterns outside of \"with\" block")))+            ierror (At (fromMaybe NoFC $ highestFC lhs_in_as)+                       (Elaborating "left hand side of " fname Nothing+                        (Msg "unexpected patterns outside of \"with\" block")))          -- get the parameters first, to pass through to any where block         let fn_ty = case lookupTy fname ctxt of@@ -723,7 +689,8 @@         ((ElabResult lhs' dlhs [] ctxt' newDecls highlights newGName, probs, inj), _) <-            tclift $ elaborate (constraintNS info) ctxt (idris_datatypes i) (idris_name i) (sMN 0 "patLHS") infP initEState                     (do res <- errAt "left hand side of " fname Nothing-                                 (erun fc (buildTC i info ELHS opts fname+                                 (erun (fromMaybe NoFC $ highestFC lhs_in_as)+                                       (buildTC i info ELHS opts fname                                           (allNamesIn lhs_in)                                           (infTerm lhs)))                         probs <- get_probs@@ -916,8 +883,7 @@     pinfo info ns ds i           = let newps = params info ++ ns                 dsParams = map (\n -> (n, map fst newps)) ds-                newb = addAlist dsParams (inblock info)-                l = liftname info in+                newb = addAlist dsParams (inblock info) in                 info { params = newps,                        inblock = newb,                        liftname = id -- (\n -> case lookupCtxt n newb of@@ -937,7 +903,7 @@          getVs _ = []     borrowedNames env (App _ f a) = nub $ borrowedNames env f ++ borrowedNames env a     borrowedNames env (Bind n b sc) = nub $ borrowedB b ++ borrowedNames (n:env) sc-       where borrowedB (Let t v) = nub $ borrowedNames env t ++ borrowedNames env v+       where borrowedB (Let _ t v) = nub $ borrowedNames env t ++ borrowedNames env v              borrowedB b = borrowedNames env (binderTy b)     borrowedNames _ _ = [] @@ -966,8 +932,7 @@     isOutsideWith _ = True  elabClause info opts (_, PWith fc fname lhs_in withs wval_in pn_in withblock)-   = do let tcgen = Dictionary `elem` opts-        ctxt <- getContext+   = do ctxt <- getContext         -- Build the LHS as an "Infer", and pull out its type and         -- pattern bindings         i <- getIState@@ -986,7 +951,8 @@         (ElabResult lhs' dlhs [] ctxt' newDecls highlights newGName, _) <-             tclift $ elaborate (constraintNS info) ctxt (idris_datatypes i) (idris_name i) (sMN 0 "patLHS") infP initEState               (errAt "left hand side of with in " fname Nothing-                (erun fc (buildTC i info ELHS opts fname+                (erun (fromMaybe NoFC $ highestFC lhs_in)+                      (buildTC i info ELHS opts fname                                   (allNamesIn lhs_in)                                   (infTerm lhs))) )         setContext ctxt'@@ -1189,9 +1155,6 @@     mkAux pn wname toplhs ns ns' c         = ifail $ show fc ++ ":badly formed with clause" -    addArg (PApp fc f args) w = PApp fc f (args ++ [pexp w])-    addArg (PRef fc hls f) w = PApp fc (PRef fc hls f) [pexp w]-     -- ns, arguments which don't depend on the with argument     -- ns', arguments which do     updateLHS n pn wname mvars ns_in ns_in' (PApp fc (PRef fc' hls' n') args) w@@ -1215,11 +1178,6 @@     updateWithTerm ist pn wname toplhs ns_in ns_in' tm           = mapPT updateApp tm        where-         arity (PApp _ _ as) = length as-         arity _ = 0--         lhs_arity = arity toplhs-          currentFn fname (PAlternative _ _ as)               | Just tm <- getApp as = tm             where getApp (tm@(PApp _ (PRef _ _ f) _) : as)
src/Idris/Elab/Data.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Elab.Data Description : Code to elaborate data structures.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -10,49 +10,30 @@  import Idris.AbsSyntax import Idris.ASTUtils-import Idris.Core.CaseTree-import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Evaluate-import Idris.Core.Execute import Idris.Core.TT import Idris.Core.Typecheck-import Idris.Coverage-import Idris.DataOpts-import Idris.DeepSeq import Idris.Delaborate import Idris.Docstrings-import Idris.DSL import Idris.Elab.Rewrite-import Idris.Elab.Term import Idris.Elab.Type import Idris.Elab.Utils import Idris.Elab.Value import Idris.Error-import Idris.Imports-import Idris.Inliner-import Idris.Output (iWarn, iputStrLn, pshow, sendHighlighting)-import Idris.PartialEval-import Idris.Primitives-import Idris.Providers-import IRTS.Lang+import Idris.Output (iWarn, sendHighlighting)  import Util.Pretty  import Prelude hiding (id, (.)) -import Control.Applicative hiding (Const) import Control.Category-import Control.DeepSeq import Control.Monad import Control.Monad.State.Strict as State import Data.Char (isLetter, toLower) import Data.List-import Data.List.Split (splitOn) import qualified Data.Map as Map import Data.Maybe-import qualified Data.Set as S import qualified Data.Text as T-import Debug.Trace  warnLC :: FC -> Name -> Idris () warnLC fc n@@ -61,8 +42,7 @@  elabData :: ElabInfo -> SyntaxInfo -> Docstring (Either Err PTerm)-> [(Name, Docstring (Either Err PTerm))] -> FC -> DataOpts -> PData -> Idris () elabData info syn doc argDocs fc opts (PLaterdecl n nfc t_in)-    = do let codata = Codata `elem` opts-         logElab 1 (show (fc, doc))+    = do logElab 1 (show (fc, doc))          checkUndefined fc n          when (implicitable (nsroot n)) $ warnLC fc n          (cty, _, t, inacc) <- buildType info syn fc [] n t_in@@ -92,7 +72,6 @@                         rt -> tclift $ tfail (At fc (Elaborating "type constructor " n Nothing (Msg "Not a valid type constructor")))          cons <- mapM (elabCon cnameinfo syn n codata (getRetTy cty) ckind) dcons          ttag <- getName-         let as = map (const (Left (Msg ""))) (getArgTys cty)           ctxt <- getContext          let params = findParams n (normalise ctxt [] cty) (map snd cons)@@ -120,8 +99,6 @@          -- TMP HACK! Make this a data option          updateContext (addDatatype (Data n ttag cty unique cons))          updateContext (setMetaInformation n metainf)-         when (any linearArg (map snd cons)) $-            updateContext (setRigCount n Rig1)           mapM_ totcheck (zip (repeat fc) (map fst cons)) --          mapM_ (checkPositive n) cons@@ -170,8 +147,7 @@         cinfo info ds           = let newps = params info                 dsParams = map (\n -> (n, [])) ds-                newb = addAlist dsParams (inblock info)-                l = liftname info in+                newb = addAlist dsParams (inblock info) in                 info { params = newps,                        inblock = newb,                        liftname = id -- Is this appropriate?@@ -245,12 +221,6 @@     getTyName (PRef _ _ n) = n == nsroot tn     getTyName _ = False --    getNamePos :: Int -> PTerm -> Name -> Maybe Int-    getNamePos i (PPi _ n _ _ sc) x | n == x = Just i-                                    | otherwise = getNamePos (i + 1) sc x-    getNamePos _ _ _ = Nothing-     -- if the constructor is a UniqueType, the datatype must be too     -- (AnyType is fine, since that is checked for uniqueness too)     -- if hte contructor is AnyType, the datatype must be at least AnyType@@ -358,7 +328,7 @@   elimLog "Elaborating case function"   put (Map.fromList $ zip (concatMap (\(_, p, _, _, ty, _, _) -> (map show $ boundNamesIn ty) ++ map (show . fst) p) cons ++ (map show $ boundNamesIn ty)) (repeat 0))   let (cnstrs, _) = splitPi ty-  let (splittedTy@(pms, idxs)) = splitPms cnstrs+  let (pms, idxs) = splitPms cnstrs   generalParams <- namePis False pms   motiveIdxs    <- namePis False idxs   let motive = mkMotive n paramPos generalParams motiveIdxs@@ -396,10 +366,6 @@         elimDeclName :: Name         elimDeclName = if ind then SN . ElimN $ n else SN . CaseN (FC' elimFC) $ n -        applyNS :: Name -> [String] -> Name-        applyNS n []  = n-        applyNS n ns  = sNS n ns-         splitPi :: PTerm -> ([(Name, Plicity, PTerm)], PTerm)         splitPi = splitPi' []           where splitPi' :: [(Name, Plicity, PTerm)] -> PTerm -> ([(Name, Plicity, PTerm)], PTerm)@@ -439,10 +405,6 @@         simpleName (NS n _) = simpleName n         simpleName (MN i n) = str n ++ show i         simpleName n        = show n--        nameSpaces :: Name -> [String]-        nameSpaces (NS _ ns) = map str ns-        nameSpaces _         = []          freshName :: String -> EliminatorState Name         freshName key = do
src/Idris/Elab/Implementation.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Elab.Implementation Description : Code to elaborate instances.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -9,51 +9,28 @@ module Idris.Elab.Implementation(elabImplementation) where  import Idris.AbsSyntax-import Idris.ASTUtils import Idris.Core.CaseTree import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Evaluate-import Idris.Core.Execute import Idris.Core.TT-import Idris.Core.Typecheck-import Idris.Coverage-import Idris.DataOpts-import Idris.DeepSeq import Idris.Delaborate import Idris.Docstrings-import Idris.DSL-import Idris.Elab.Data import Idris.Elab.Term import Idris.Elab.Type import Idris.Elab.Utils import Idris.Error-import Idris.Imports-import Idris.Inliner-import Idris.Output (iWarn, iputStrLn, pshow, sendHighlighting)-import Idris.PartialEval-import Idris.Primitives-import Idris.Providers-import IRTS.Lang+import Idris.Output (iWarn, sendHighlighting) -import Util.Pretty (pretty, text)+import Util.Pretty (text)  import Prelude hiding (id, (.)) -import Control.Applicative hiding (Const) import Control.Category-import Control.DeepSeq import Control.Monad-import Control.Monad.State.Strict as State-import Data.Char (isLetter, toLower) import Data.List-import Data.List.Split (splitOn)-import qualified Data.Map as Map import Data.Maybe-import qualified Data.Set as S import qualified Data.Text as T-import Debug.Trace - elabImplementation :: ElabInfo                    -> SyntaxInfo                    -> Docstring (Either Err PTerm)@@ -79,7 +56,6 @@                   [] -> ifail $ show fc ++ ":" ++ show n ++ " is not an interface"                   cs -> tclift $ tfail $ At fc                            (CantResolveAlts (map fst cs))-    let constraint = PApp fc (PRef fc [] n) (map pexp ps)     let iname = mkiname n (namespace info) ps expn     putIState (ist { hide_list = addDef iname acc (hide_list ist) })     ist <- getIState@@ -101,7 +77,8 @@             _ -> addImplementation intImpl False n iname      ist <- getIState-    checkInjectiveArgs fc n (interface_determiners ci) (lookupTyExact iname (tt_ctxt ist))+    when (isNothing expn) $+      checkInjectiveArgs fc n (interface_determiners ci) (lookupTyExact iname (tt_ctxt ist))      when (what /= ETypes && (not (null ds && not emptyinterface))) $ do          -- Add the parent implementation names to the privileged set@@ -167,7 +144,6 @@          let wbVals_orig = map (decorateid (decorate ns iname)) ds'          ist <- getIState          let wbVals = map (expandParamsD False ist id pextra (map methName mtys)) wbVals_orig-         let wb = wbTys ++ wbVals           logElab 3 $ "Method types " ++ showSep "\n" (map (show . showDeclImp verbosePPOption . mkTyDecl) mtys)          logElab 3 $ "Implementation is " ++ show ps ++ " implicits " ++ show (concat (nub wparams))@@ -300,8 +276,6 @@     mkMethApp ps (n, _, _, ty)               = lamBind 0 ty (papp fc (PRef fc [] n)                      (ps ++ map (toExp . fst) pextra ++ methArgs 0 ty))-       where-          needed is p = pname p `elem` map pname is      lamBind i (PPi (Constraint _ _ _) _ _ _ sc) sc'           = PLam fc (sMN i "meth") NoFC Placeholder (lamBind (i+1) sc sc')
src/Idris/Elab/Interface.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Elab.Interface Description : Code to elaborate interfaces.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -10,52 +10,23 @@ module Idris.Elab.Interface(elabInterface) where  import Idris.AbsSyntax-import Idris.ASTUtils-import Idris.Core.CaseTree-import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Evaluate-import Idris.Core.Execute import Idris.Core.TT-import Idris.Core.Typecheck-import Idris.Coverage-import Idris.DataOpts-import Idris.DeepSeq import Idris.Delaborate import Idris.Docstrings-import Idris.DSL import Idris.Elab.Data-import Idris.Elab.Term-import Idris.Elab.Type import Idris.Elab.Utils import Idris.Error-import Idris.Imports-import Idris.Inliner-import Idris.Output (iWarn, iputStrLn, pshow, sendHighlighting)-import Idris.PartialEval-import Idris.Primitives-import Idris.Providers-import IRTS.Lang--import Util.Pretty (pretty, text)+import Idris.Output (sendHighlighting)  import Prelude hiding (id, (.)) -import Control.Applicative hiding (Const) import Control.Category-import Control.DeepSeq import Control.Monad-import Control.Monad.State.Strict as State-import Data.Char (isLetter, toLower) import Data.Generics.Uniplate.Data (transform) import Data.List-import Data.List.Split (splitOn)-import qualified Data.Map as Map import Data.Maybe-import qualified Data.Set as S-import qualified Data.Text as T-import Debug.Trace - data MArgTy = IA Name | EA Name | CA deriving Show  elabInterface :: ElabInfo@@ -123,8 +94,7 @@              ims <- mapM (tdecl impps mnames) mdecls              defs <- mapM (defdecl (map (\ (x,y,z) -> z) ims) constraint)                           (filter clause ds)-             let (methods, imethods)-                  = unzip (map (\ (x, y, z) -> (x, y)) ims)+             let imethods = map (\ (x, y, z) -> y) ims              let defaults = map (\ (x, (y, z)) -> (x,y)) defs               addInterface tn (CI cn (map nodoc imethods) defaults idecls@@ -270,11 +240,20 @@         = do when (not $ null cs) . tclift                 $ tfail (At fc (Msg "Default super interface implementations can't have constraints."))              i <- getIState-             let t = PApp fc (PRef fc [] n) (map pexp ps)-             let isConstrained = any (== t) (map snd constraints)+             let isConstrained = any (checkConstrained i n (map pexp ps)) (map snd constraints)              when (not isConstrained) . tclift                 $ tfail (At fc (Msg "Default implementations must be for a super interface constraint on the containing interface."))              return ()+            where+                -- First, Check that interface "constraint" has same name & args as default implementation name & args (not checking FC)+                -- If not the case, recursively lookup in context for parent interface & recheck the same with parent constraints+                checkConstrained i n args constraint =+                    if (n == cn && args == cargs)+                        then True+                        else any (id) (map (checkConstrained i n args) parentConstraints)+                    where+                        PApp _ (PRef _ _ cn) cargs = constraint+                        parentConstraints = concatMap interface_constraints (lookupCtxt cn (idris_interfaces i))      checkConstraintName :: [Name] -> Name -> Idris ()     checkConstraintName bound cname@@ -387,13 +366,6 @@              return (PTy doc [] syn fc o m mfc ty',                      PClauses fc [Inlinable] m [PClause fc m lhs [] rhs []]) -    updateIMethod :: [(Name, PTerm)] ->-                     (Name, (a, b, c, d, PTerm)) ->-                     (Name, (a, b, c, d, PTerm))-    updateIMethod ns tm@(n, (isf, mfc, doc, o, ty))-       | Just ty' <- lookup (nsroot n) ns = (n, (isf, mfc, doc, o, ty'))-       | otherwise = tm-     getMArgs (PPi (Imp _ _ _ _ _ _) n _ ty sc) = IA n : getMArgs sc     getMArgs (PPi (Exp _ _ _ _) n _ ty sc) = EA n : getMArgs sc     getMArgs (PPi (Constraint _ _ _) n _ ty sc) = CA : getMArgs sc@@ -442,12 +414,6 @@         | otherwise = PPi (e l s p r) n fc ty (toExp ns e sc)     toExp ns e (PPi p n fc ty sc) = PPi p n fc ty (toExp ns e sc)     toExp ns e sc = sc---- | Get the method declaration name corresponding to a user-provided name-mdec :: Name -> Name-mdec (UN n) = SN (MethodN (UN n))-mdec (NS x n) = NS (mdec x) n-mdec x = x  -- | Get the docstring corresponding to a member, if one exists memberDocs :: PDecl -> Maybe (Name, Docstring (Either Err PTerm))
src/Idris/Elab/Provider.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Elab.Provider Description : Code to elaborate type providers.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -9,51 +9,24 @@ module Idris.Elab.Provider(elabProvider) where  import Idris.AbsSyntax-import Idris.ASTUtils-import Idris.Core.CaseTree-import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Evaluate import Idris.Core.Execute import Idris.Core.TT import Idris.Core.Typecheck-import Idris.Coverage-import Idris.DataOpts-import Idris.DeepSeq import Idris.Delaborate import Idris.Docstrings-import Idris.DSL import Idris.Elab.Clause import Idris.Elab.Term import Idris.Elab.Type-import Idris.Elab.Utils import Idris.Elab.Value import Idris.Error-import Idris.Imports-import Idris.Inliner import Idris.Options-import Idris.Output (iWarn, iputStrLn, pshow)-import Idris.PartialEval-import Idris.Primitives import Idris.Providers-import IRTS.Lang -import Util.Pretty (pretty, text)- import Prelude hiding (id, (.)) -import Control.Applicative hiding (Const) import Control.Category-import Control.DeepSeq import Control.Monad-import Control.Monad.State.Strict as State-import Data.Char (isLetter, toLower)-import Data.List-import Data.List.Split (splitOn)-import qualified Data.Map as Map-import Data.Maybe-import qualified Data.Set as S-import qualified Data.Text as T-import Debug.Trace  -- | Elaborate a type provider elabProvider :: Docstring (Either Err PTerm) -> ElabInfo -> SyntaxInfo -> FC -> FC -> ProvideWhat -> Name -> Idris ()
src/Idris/Elab/Quasiquote.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Elab.Quasiquote Description : Code to elaborate quasiquotations.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -70,11 +70,11 @@        return (DoBind fc n nfc tm', ex) extractDoUnquotes d (DoBindP fc t t' alts)   = fail "Pattern-matching binds cannot be quasiquoted"-extractDoUnquotes d (DoLet  fc n nfc v b)+extractDoUnquotes d (DoLet  fc rc n nfc v b)   = do (v', ex1) <- extractUnquotes d v        (b', ex2) <- extractUnquotes d b-       return (DoLet fc n nfc v' b', ex1 ++ ex2)-extractDoUnquotes d (DoLetP fc t t') = fail "Pattern-matching lets cannot be quasiquoted"+       return (DoLet fc rc n nfc v' b', ex1 ++ ex2)+extractDoUnquotes d (DoLetP fc t t' alts) = fail "Pattern-matching lets cannot be quasiquoted" extractDoUnquotes d (DoRewrite fc h) = fail "Rewrites in Do block cannot be quasiquoted"  @@ -87,11 +87,11 @@   = do (ty', ex1) <- extractUnquotes n ty        (body', ex2) <- extractUnquotes n body        return (PPi plicity name fc ty' body', ex1 ++ ex2)-extractUnquotes n (PLet fc name nfc ty val body)+extractUnquotes n (PLet fc rc name nfc ty val body)   = do (ty', ex1) <- extractUnquotes n ty        (val', ex2) <- extractUnquotes n val        (body', ex3) <- extractUnquotes n body-       return (PLet fc name nfc ty' val' body', ex1 ++ ex2 ++ ex3)+       return (PLet fc rc name nfc ty' val' body', ex1 ++ ex2 ++ ex3) extractUnquotes n (PTyped tm ty)   = do (tm', ex1) <- extractUnquotes n tm        (ty', ex2) <- extractUnquotes n ty
src/Idris/Elab/Record.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Elab.Record Description : Code to elaborate records.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -11,25 +11,11 @@ import Idris.AbsSyntax import Idris.Core.Evaluate import Idris.Core.TT-import Idris.Coverage-import Idris.DataOpts-import Idris.DeepSeq import Idris.Delaborate import Idris.Docstrings import Idris.Elab.Data-import Idris.Elab.Data-import Idris.Elab.Term-import Idris.Elab.Type-import Idris.Elab.Utils import Idris.Error-import Idris.Imports-import Idris.Inliner-import Idris.Output (iWarn, iputStrLn, pshow, sendHighlighting)-import Idris.Parser.Expr (tryFullExpr)-import Idris.PartialEval-import Idris.Primitives-import Idris.Providers-import IRTS.Lang+import Idris.Output (sendHighlighting)  import Control.Monad import Data.List@@ -225,15 +211,6 @@     isFieldOrParam' :: (Name, a) -> Bool     isFieldOrParam' = isFieldOrParam . fst -    isField :: Name -> Bool-    isField = flip elem fieldNames--    isField' :: (Name, a, b, c, d, f) -> Bool-    isField' (n, _, _, _, _, _) = isField n--    fieldTerms :: [PTerm]-    fieldTerms = [t | (_, _, _, t, _) <- fields]-     -- Delabs the TT to PTerm     -- This is not good.     -- However, for machine generated implicits, there seems to be no PTerm available.@@ -252,13 +229,6 @@     freeName (NS n s) = NS (freeName n) s     freeName n = n -    -- | Zips together parameters with their documentation. If no documentation for a given field exists, an empty docstring is used.-    zipParams :: IState -> [(Name, Plicity, PTerm)] -> [(Name, Docstring (Either Err PTerm))] -> [(Name, PTerm, Docstring (Either Err PTerm))]-    zipParams i ((n, _, t) : rest) ((_, d) : rest') = (n, t, d) : (zipParams i rest rest')-    zipParams i ((n, _, t) : rest) [] = (n, t, emptyDoc) : (zipParams i rest [])-      where emptyDoc = annotCode (tryFullExpr rsyn i) emptyDocstring-    zipParams _ [] [] = []-     paramName :: Name -> Name     paramName (UN n) = sUN ("param_" ++ str n)     paramName (MN i n) = sMN i ("param_" ++ str n)@@ -294,15 +264,6 @@       where         fieldDep :: Name -> PTerm -> (Name, [Name])         fieldDep n t = ((nsroot n), paramNames ++ fieldNames `intersect` allNamesIn t)--    -- | A list of fields depending on another field.-    dependentFields :: [Name]-    dependentFields = filter depends fieldNames-      where-        depends :: Name -> Bool-        depends n = case lookup n fieldDependencies of-                      Just xs -> not $ null xs-                      Nothing -> False      -- | A list of fields depended on by other fields.     dependedOn :: [Name]
src/Idris/Elab/Rewrite.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Elab.Rewrite Description : Code to elaborate rewrite rules.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -10,7 +10,6 @@ module Idris.Elab.Rewrite(elabRewrite, elabRewriteLemma) where  import Idris.AbsSyntax-import Idris.AbsSyntaxTree import Idris.Core.Elaborate import Idris.Core.Evaluate import Idris.Core.TT@@ -20,8 +19,6 @@  import Control.Monad import Control.Monad.State.Strict-import Data.List-import Debug.Trace  elabRewrite :: (PTerm -> ElabD ()) -> IState ->                FC -> Maybe Name -> PTerm -> PTerm -> Maybe PTerm -> ElabD ()@@ -53,14 +50,14 @@                       Nothing -> return sc_in                       Just t -> do                          letn <- getNameFrom (sMN 0 "rewrite_result")-                         return $ PLet fc letn fc t sc_in+                         return $ PLet fc RigW letn fc t sc_in                                        (PRef fc [] letn)              tyn <- getNameFrom (sMN 0 "rty")              claim tyn RType              valn <- getNameFrom (sMN 0 "rval")              claim valn (Var tyn)              letn <- getNameFrom (sMN 0 "_rewrite_rule")-             letbind letn (Var tyn) (Var valn)+             letbind letn RigW (Var tyn) (Var valn)              focus valn              elab rule              compute@@ -98,9 +95,10 @@              = let b' = mkPB b                    sc' = if (r /= sc) then mkP lt l r sc else sc in                    Bind n b' sc'-            where mkPB (Let t v) = let t' = if (r /= t) then mkP lt l r t else t-                                       v' = if (r /= v) then mkP lt l r v else v in-                                       Let t' v'+            where mkPB (Let rig t v)+                       = let t' = if (r /= t) then mkP lt l r t else t+                             v' = if (r /= v) then mkP lt l r v else v in+                             Let rig t' v'                   mkPB b = let ty = binderTy b                                ty' = if (r /= ty) then mkP lt l r ty else ty in                                      b { binderTy = ty' }
src/Idris/Elab/RunElab.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Elab.RunElab Description : Code to run the elaborator process.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -9,14 +9,12 @@  import Idris.AbsSyntax import Idris.Core.Elaborate hiding (Tactic(..))-import Idris.Core.Evaluate-import Idris.Core.Execute import Idris.Core.TT import Idris.Core.Typecheck import Idris.Elab.Term import Idris.Elab.Value (elabVal) import Idris.Error-import Idris.Output (iWarn, iputStrLn, pshow, sendHighlighting)+import Idris.Output (sendHighlighting)  elabScriptTy :: Type elabScriptTy = App Complete (P Ref (sNS (sUN "Elab") ["Elab", "Reflection", "Language"]) Erased)
src/Idris/Elab/Term.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Elab.Term Description : Code to elaborate terms.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -10,40 +10,34 @@ module Idris.Elab.Term where  import Idris.AbsSyntax-import Idris.AbsSyntaxTree-import Idris.Core.CaseTree (SC, SC'(STerm), findCalls, findUsedArgs)+import Idris.Core.CaseTree (SC'(STerm), findCalls) import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Evaluate import Idris.Core.ProofTerm (getProofTerm) import Idris.Core.TT import Idris.Core.Typecheck (check, converts, isType, recheck) import Idris.Core.Unify-import Idris.Core.WHNF (whnf, whnfArgs)-import Idris.Coverage (genClauses, recoverableCoverage, validCoverageCase)+import Idris.Core.WHNF (whnf)+import Idris.Coverage (genClauses, recoverableCoverage) import Idris.Delaborate-import Idris.DSL import Idris.Elab.Quasiquote (extractUnquotes) import Idris.Elab.Rewrite import Idris.Elab.Utils import Idris.Error import Idris.ErrReverse (errReverse) import Idris.Options-import Idris.Output (pshow) import Idris.ProofSearch import Idris.Reflection import Idris.Termination (buildSCG, checkDeclTotality, checkPositive) -import qualified Util.Pretty as U- import Control.Applicative ((<$>)) import Control.Monad import Control.Monad.State.Strict import Data.Foldable (for_) import Data.List import qualified Data.Map as M-import Data.Maybe (catMaybes, fromMaybe, mapMaybe, maybeToList)+import Data.Maybe (fromMaybe, mapMaybe, maybeToList) import qualified Data.Set as S-import qualified Data.Text as T import Debug.Trace  data ElabMode = ETyDecl | ETransLHS | ELHS | EImpossible | ERHS@@ -85,7 +79,6 @@       -> ElabD ElabResult build ist info emode opts fn tm     = do elab ist info emode opts fn tm-         let tmIn = tm          let inf = case lookupCtxt fn (idris_tyinfodata ist) of                         [TIPartial] -> True                         _ -> False@@ -163,8 +156,7 @@          PTerm ->          ElabD ElabResult buildTC ist info emode opts fn ns tm-    = do let tmIn = tm-         let inf = case lookupCtxt fn (idris_tyinfodata ist) of+    = do let inf = case lookupCtxt fn (idris_tyinfodata ist) of                         [TIPartial] -> True                         _ -> False          -- set name supply to begin after highest index in tm@@ -190,7 +182,6 @@          if (log /= "")             then trace log $ return (ElabResult tm ds (map snd is) ctxt impls highlights g_nextname)             else return (ElabResult tm ds (map snd is) ctxt impls highlights g_nextname)-  where pattern = emode == ELHS || emode == EImpossible  -- | return whether arguments of the given constructor name can be -- matched on. If they're polymorphic, no, unless the type has beed@@ -247,7 +238,6 @@     = do let loglvl = opt_logLevel (idris_options ist)          when (loglvl > 5) $ unifyLog True          compute -- expand type synonyms, etc-         let fc = maybe "(unknown)"          elabE initElabCtxt (elabFC info) tm -- (in argument, guarded, in type, in qquote)          est <- getAux          sequence_ (get_delayed_elab est)@@ -262,7 +252,7 @@          ptm <- get_term          when pattern $               -- Look for Rig1 (linear) pattern bindings-              do let pnms = findLinear ist [] ptm+              do let pnms = findLinear Rig1 ist [] ptm                  update_term (setLinear pnms)   where     pattern = emode == ELHS || emode == EImpossible@@ -283,14 +273,6 @@         Placeholder -> (True, priority arg)         tm -> (False, priority arg) -    toElab ina arg = case getTm arg of-        Placeholder -> Nothing-        v -> Just (priority arg, elabE ina (elabFC info) v)--    toElab' ina arg = case getTm arg of-        Placeholder -> Nothing-        v -> Just (elabE ina (elabFC info) v)-     mkPat = do hs <- get_holes                tm <- get_term                case hs of@@ -356,18 +338,6 @@     notDelay t@(PApp _ (PRef _ _ (UN l)) _) | l == txt "Delay" = False     notDelay _ = True -    local f = do e <- get_env-                 return (f `elem` map fstEnv e)--    -- | Is a constant a type?-    constType :: Const -> Bool-    constType (AType _) = True-    constType StrType = True-    constType VoidType = True-    constType _ = False--    -- "guarded" means immediately under a constructor, to help find patvars-     elab' :: ElabCtxt  -- ^ (in an argument, guarded, in a type, in a quasiquote)           -> Maybe FC -- ^ The closest FC in the syntax tree, if applicable           -> PTerm -- ^ The term to elaborate@@ -603,13 +573,6 @@                          (P _ n' _, _) -> n == n'                          _ -> False -        showQuick (CantUnify _ (l, _) (r, _) _ _ _)-            = show (l, r)-        showQuick (ElaboratingArg _ _ _ e) = showQuick e-        showQuick (At _ e) = showQuick e-        showQuick (ProofSearchFail (Msg _)) = "search fail"-        showQuick _ = "No chance"-     elab' ina _ (PPatvar fc n) | bindfree         = do patvar n              update_term liftPats@@ -627,8 +590,6 @@         = do ty <- goal              testImplicitWarning fc n ty              let ina = e_inarg ec-                 guarded = e_guarded ec-                 inty = e_intype ec              ctxt <- get_context              env <- get_env @@ -734,7 +695,7 @@                elabE ec' fc sc                solve                highlightSource nfc (AnnBoundName n False)-    elab' ina _ tm@(PLet fc n nfc ty val sc)+    elab' ina _ tm@(PLet fc rig n nfc ty val sc)           = do attack                ivs <- get_implementations                tyn <- getNameFrom (sMN 0 "letty")@@ -742,7 +703,7 @@                valn <- getNameFrom (sMN 0 "letval")                claim valn (Var tyn)                explicit valn-               letbind n (Var tyn) (Var valn)+               letbind n rig (Var tyn) (Var valn)                addPSname n                case ty of                    Placeholder -> return ()@@ -769,7 +730,7 @@                -- HACK: If the name leaks into its type, it may leak out of                -- scope outside, so substitute in the outer scope.                expandLet n (case lookupBinder n env of-                                 Just (Let t v) -> v+                                 Just (Let rig t v) -> v                                  other -> error ("Value not a let binding: " ++ show other))                solve                highlightSource nfc (AnnBoundName n False)@@ -780,7 +741,7 @@          claim tyn RType          valn <- getNameFrom (sMN 0 "letval")          claim valn (Var tyn)-         letbind n (Var tyn) (Var valn)+         letbind n RigW (Var tyn) (Var valn)          focus valn          elabE (ina { e_inarg = True, e_intype = True }) (Just fc) (PApp fc r [pexp (delab ist rty)])          env <- get_env@@ -890,7 +851,6 @@                         _ -> do mapM_ setInjective (map getTm args)                                 -- maybe more things are solvable now                                 unifyProblems-                    let guarded = isConName f ctxt --                    trace ("args is " ++ show args) $ return ()                     ns <- apply (Var f) (map isph args) --                    trace ("ns is " ++ show ns) $ return ()@@ -1000,10 +960,6 @@             getDets i ds (a : as) | i `elem` ds = a : getDets (i + 1) ds as                                   | otherwise = getDets (i + 1) ds as -            tacTm (PTactics _) = True-            tacTm (PProof _) = True-            tacTm _ = False-             setInjective (PRef _ _ n) = setinj n             setInjective (PApp _ (PRef _ _ n) _) = setinj n             setInjective _ = return ()@@ -1035,11 +991,13 @@              -- When building the metavar application, leave out the unique              -- names which have been used elsewhere in the term, since we              -- won't be able to use them in the resulting application.+             env <- get_env              let unique_used = getUniqueUsed (tt_ctxt ist) ptm+             let lin_used = getLinearUsed (tt_ctxt ist) ptm              let n' = metavarName (namespace info) n              attack              psns <- getPSnames-             n' <- defer unique_used n'+             n' <- defer unique_used lin_used n'              solve              highlightSource nfc (AnnName n' (Just MetavarOutput) Nothing Nothing)     elab' ina fc (PProof ts) = do compute; mapM_ (runTac True ist (elabFC info) fn) ts@@ -1060,8 +1018,11 @@              valn <- getNameFrom (sMN 0 "scval")              scvn <- getNameFrom (sMN 0 "scvar")              claim valn (Var tyn)-             letbind scvn (Var tyn) (Var valn)+             env <- get_env +             let scrnames = allNamesIn scr+             letbind scvn (letrig scrnames env) (Var tyn) (Var valn)+              -- Start filling in the scrutinee type, if we can work one              -- out from the case options              let scrTy = getScrType (map fst opts)@@ -1078,7 +1039,6 @@              matchProblems True              args <- get_env              envU <- mapM (getKind args) args-             let namesUsedInRHS = nub $ scvn : concatMap (\(_,rhs) -> allNamesIn rhs) opts               -- Drop the unique arguments used in the term already              -- and in the scrutinee (since it's@@ -1092,13 +1052,15 @@              let inOpts = (filter (/= scvn) (map fstEnv args)) \\ (concatMap (\x -> allNamesIn (snd x)) opts)               let argsDropped = filter (\t -> isUnique envU t || isNotLift args t)-                                   (nub $ allNamesIn scr ++ inApp ptm +++                                   (nub $ scrnames ++ inApp ptm ++                                     inOpts)+             let lin_used = getLinearUsed (tt_ctxt ist) ptm               let args' = filter (\(n, _, _) -> n `notElem` argsDropped) args +             -- trace (show lin_used ++ "\n" ++ show args ++ "\n" ++ show ptm) attack              attack-             cname' <- defer argsDropped (mkN (mkCaseName fc fn))+             cname' <- defer argsDropped lin_used (mkN (mkCaseName fc fn))              solve               -- if the scrutinee is one of the 'args' in env, we should@@ -1120,6 +1082,17 @@                         xs@(_:_) -> sNS n xs                         _ -> n +              -- If any variables in the scrutinee are in the environment with+              -- multiplicity other than RigW, let bind the scrutinee variable+              -- with the smallest multiplicity+              letrig ns [] = RigW+              letrig ns env = letrig' Rig1 ns env++              letrig' def ns [] = def+              letrig' def ns ((n, r, _) : env)+                   | n `elem` ns = letrig' (rigMult def r) ns env+                   | otherwise = letrig' def ns env+               getScrType [] = Nothing               getScrType (f : os) = maybe (getScrType os) Just (getAppType f) @@ -1137,7 +1110,7 @@                inApp (P _ n _) = [n]               inApp (App _ f a) = inApp f ++ inApp a-              inApp (Bind n (Let _ v) sc) = inApp v ++ inApp sc+              inApp (Bind n (Let _ _ v) sc) = inApp v ++ inApp sc               inApp (Bind n (Guess _ v) sc) = inApp v ++ inApp sc               inApp (Bind n b sc) = inApp sc               inApp _ = []@@ -1156,12 +1129,6 @@                                     UType AllTypes -> return (n, True)                                     _ -> return (n, False) -              tcName tm | (P _ n _, _) <- unApply tm-                  = case lookupCtxt n (idris_interfaces ist) of-                         [_] -> True-                         _ -> False-              tcName _ = False-               isNotLift env n                  = case lookupBinder n env of                         Just ty ->@@ -1170,10 +1137,6 @@                                   _ -> False                         _ -> False -              usedIn ns (n, b)-                 = n `elem` ns-                     || any (\x -> x `elem` ns) (allTTNames (binderTy b))-     elab' ina fc (PUnifyLog t) = do unifyLog True                                     elab' ina fc t                                     unifyLog False@@ -1218,7 +1181,7 @@              -- Let-bind the result of elaborating the contained term, so that              -- the hole doesn't disappear              nTm <- getNameFrom (sMN 0 "quotedTerm")-             letbind nTm (Var qTy) (Var qTm)+             letbind nTm RigW (Var qTy) (Var qTm)               -- Fill out the goal type, if relevant              case goalt of@@ -1345,7 +1308,7 @@          -- In order to intercept the elaborated value, we need to          -- let-bind it.          attack-         letbind n g (Var n')+         letbind n RigW g (Var n')          focus n'          elab' ina fc tm          env <- get_env@@ -1374,8 +1337,10 @@     delayElab pri t        = updateAux (\e -> e { delayed_elab = delayed_elab e ++ [(pri, t)] }) +    -- If the variable in the environment is the scrutinee of the case,+    -- and has multiplicity W, keep it available     isScr :: PTerm -> (Name, RigCount, Binder Term) -> (Name, (Bool, Binder Term))-    isScr (PRef _ _ n) (n', _, b) = (n', (n == n', b))+    isScr (PRef _ _ n) (n', RigW, b) = (n', (n == n', b))     isScr _ (n', _, b) = (n', (False, b))      caseBlock :: FC -> Name@@ -1387,8 +1352,8 @@               map (mkClause args) opts         where -- Find the variable we want as the scrutinee and mark it as-             -- 'True'. If the scrutinee is in the environment, match on that-             -- otherwise match on the new argument we're adding.+             -- 'True'. If the scrutinee is available in the environment,+             -- match on that otherwise match on the new argument we're adding.              findScr ((n, (True, t)) : xs)                         = (n, (True, t)) : scrName n xs              findScr [(n, (_, t))] = [(n, (True, t))]@@ -1776,7 +1741,7 @@               t' <- cd ((n, b) : env) t               return (Bind n b' t')       where-        cdb (Let t v)   = liftM2 Let (cd env t) (cd env v)+        cdb (Let rig t v) = liftM2 (Let rig) (cd env t) (cd env v)         cdb (Guess t v) = liftM2 Guess (cd env t) (cd env v)         cdb b           = do ty' <- cd env (binderTy b)                              return (b { binderTy = ty' })@@ -1792,7 +1757,7 @@   valn <- getNameFrom (sMN 0 "ival")   claim valn (Var tyn)   letn <- getNameFrom (sMN 0 "irule")-  letbind letn (Var tyn) (Var valn)+  letbind letn RigW (Var tyn) (Var valn)   focus valn   elab ist toplevel ERHS [] (sMN 0 "tac") tm   env <- get_env@@ -2170,7 +2135,7 @@            n' <- reifyTTName n            ty' <- reifyRaw ty            tm' <- reifyRaw tm-           letbind n' ty' tm'+           letbind n' RigW ty' tm'            returnUnit       | n == tacN "Prim__Compute"       = do ~[] <- tacTmArgs 0 tac args; compute ; returnUnit@@ -2325,9 +2290,10 @@            ptm <- get_term            -- See documentation above in the elab case for PMetavar            let unique_used = getUniqueUsed ctxt ptm+           let lin_used = getLinearUsed ctxt ptm            let mvn = metavarName ns n'            attack-           defer unique_used mvn+           defer unique_used lin_used mvn            solve            returnUnit       | n == tacN "Prim__Fixity"@@ -2432,7 +2398,7 @@                    valn <- getNameFrom (sMN 0 "eqval")                    claim valn (Var tyn)                    letn <- getNameFrom (sMN 0 "equiv_val")-                   letbind letn (Var tyn) (Var valn)+                   letbind letn RigW (Var tyn) (Var valn)                    focus tyn                    elab ist toplevel ERHS [] (sMN 0 "tac") tm                    focus valn@@ -2445,7 +2411,7 @@                    valn <- getNameFrom (sMN 0 "rval")                    claim valn (Var tyn)                    letn <- getNameFrom (sMN 0 "rewrite_rule")-                   letbind letn (Var tyn) (Var valn)+                   letbind letn RigW (Var tyn) (Var valn)                    focus valn                    elab ist toplevel ERHS [] (sMN 0 "tac") tm                    rewrite (Var letn)@@ -2461,7 +2427,7 @@                    valn <- getNameFrom (sMN 0 "letval")                    claim valn (Var tyn)                    letn <- unique_hole n-                   letbind letn (Var tyn) (Var valn)+                   letbind letn RigW (Var tyn) (Var valn)                    focus valn                    elab ist toplevel ERHS [] (sMN 0 "tac") tm                    when autoSolve solveAll@@ -2472,7 +2438,7 @@                    valn <- getNameFrom (sMN 0 "letval")                    claim valn (Var tyn)                    letn <- unique_hole n-                   letbind letn (Var tyn) (Var valn)+                   letbind letn RigW (Var tyn) (Var valn)                    focus tyn                    elab ist toplevel ERHS [] (sMN 0 "tac") ty                    focus valn@@ -2498,7 +2464,7 @@                                script <- getNameFrom (sMN 0 "script")                                claim script scriptTy                                scriptvar <- getNameFrom (sMN 0 "scriptvar" )-                               letbind scriptvar scriptTy (Var script)+                               letbind scriptvar RigW scriptTy (Var script)                                focus script                                elab ist toplevel ERHS [] (sMN 0 "tac") tm                                (script', _) <- get_type_val (Var scriptvar)@@ -2530,7 +2496,7 @@              script <- getNameFrom (sMN 0 "script")              claim script scriptTy              scriptvar <- getNameFrom (sMN 0 "scriptvar" )-             letbind scriptvar scriptTy (Var script)+             letbind scriptvar RigW scriptTy (Var script)              focus script              ptm <- get_term              env <- get_env@@ -2561,7 +2527,7 @@                           valn <- getNameFrom (sMN 0 "letval")                           claim valn (Var tyn)                           letn <- getNameFrom (sMN 0 "letvar")-                          letbind letn (Var tyn) (Var valn)+                          letbind letn RigW (Var tyn) (Var valn)                           focus valn                           elab ist toplevel ERHS [] (sMN 0 "tac") v                           (value, _) <- get_type_val (Var letn)@@ -2575,7 +2541,7 @@                        valn <- getNameFrom (sMN 0 "letval")                        claim valn (Var tyn)                        letn <- getNameFrom (sMN 0 "letvar")-                       letbind letn (Var tyn) (Var valn)+                       letbind letn RigW (Var tyn) (Var valn)                        focus valn                        elab ist toplevel ERHS [] (sMN 0 "tac") v                        (value, _) <- get_type_val (Var letn)@@ -2716,7 +2682,6 @@      RDatatypeDefnInstrs tyn tyconTy ctors ->       do let cn (n, _, _) = n-             cimpls (_, impls, _) = impls              cty (_, _, t) = t          addIBC (IBCDef tyn)          mapM_ (addIBC . IBCDef . cn) ctors
src/Idris/Elab/Transform.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Elab.Transform Description : Transformations for elaborate terms.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -9,47 +9,19 @@ module Idris.Elab.Transform where  import Idris.AbsSyntax-import Idris.ASTUtils-import Idris.Core.CaseTree import Idris.Core.Elaborate hiding (Tactic(..))-import Idris.Core.Evaluate-import Idris.Core.Execute import Idris.Core.TT import Idris.Core.Typecheck-import Idris.Coverage-import Idris.DataOpts-import Idris.DeepSeq-import Idris.Delaborate-import Idris.Docstrings-import Idris.DSL import Idris.Elab.Term import Idris.Elab.Utils import Idris.Error-import Idris.Imports-import Idris.Inliner-import Idris.Output (iWarn, iputStrLn, pshow, sendHighlighting)-import Idris.PartialEval-import Idris.Primitives-import Idris.Providers-import IRTS.Lang--import Util.Pretty (pretty, text)+import Idris.Output (sendHighlighting)  import Prelude hiding (id, (.)) -import Control.Applicative hiding (Const) import Control.Category-import Control.DeepSeq import Control.Monad import Control.Monad.State.Strict as State-import Data.Char (isLetter, toLower)-import Data.List-import Data.List.Split (splitOn)-import qualified Data.Map as Map-import Data.Maybe-import qualified Data.Set as S-import qualified Data.Text as T-import Debug.Trace  elabTransform :: ElabInfo -> FC -> Bool -> PTerm -> PTerm -> Idris (Term, Term) elabTransform info fc safe lhs_in@(PApp _ (PRef _ _ tf) _) rhs_in@@ -66,7 +38,6 @@          sendHighlighting highlights          updateIState $ \i -> i { idris_name = newGName }          let lhs_tm = orderPats (getInferTerm lhs')-         let lhs_ty = getInferType lhs'          let newargs = pvars i lhs_tm           (clhs_tm_in, clhs_ty) <- recheckC_borrowing False False [] (constraintNS info) fc id [] lhs_tm
src/Idris/Elab/Type.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Elab.Type Description : Code to elaborate types.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -13,50 +13,22 @@  import Idris.AbsSyntax import Idris.ASTUtils-import Idris.Core.CaseTree import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Evaluate-import Idris.Core.Execute import Idris.Core.TT-import Idris.Core.Typecheck-import Idris.Core.WHNF-import Idris.Coverage-import Idris.DataOpts-import Idris.DeepSeq-import Idris.Delaborate import Idris.Docstrings (Docstring)-import Idris.DSL import Idris.Elab.Term import Idris.Elab.Utils import Idris.Elab.Value import Idris.Error-import Idris.Imports-import Idris.Inliner import Idris.Options-import Idris.Output (iWarn, iputStrLn, pshow, sendHighlighting)-import Idris.PartialEval-import Idris.Primitives-import Idris.Providers-import IRTS.Lang--import Util.Pretty (pretty, text)+import Idris.Output (sendHighlighting)  import Prelude hiding (id, (.)) -import Control.Applicative hiding (Const) import Control.Category-import Control.DeepSeq import Control.Monad-import Control.Monad.State.Strict as State-import Data.Char (isLetter, toLower)-import Data.List-import Data.List.Split (splitOn)-import qualified Data.Map as Map-import Data.Maybe import qualified Data.Set as S-import qualified Data.Text as T-import qualified Data.Traversable as Traversable-import Debug.Trace  buildType :: ElabInfo           -> SyntaxInfo@@ -135,10 +107,6 @@              setFnInfo n fninfo              addIBC (IBCFnInfo n fninfo) -         -- If we use any types with linear constructor arguments, we'd better-         -- make sure they are use-once-         tcliftAt fc $ linearCheck ctxt (whnfArgs ctxt [] cty)-          return (cty, ckind, ty, inacc)   where     patToImp (Bind n (PVar rig t) sc) = Bind n (Pi rig Nothing t (TType (UVar [] 0))) (patToImp sc)@@ -196,11 +164,6 @@          addIBC (IBCLineApp (fc_fname fc) (fst . fc_start $ fc) (PTyped (PRef fc [] n) ty')) -- (mergeTy ty' (delab i nty')))           let (fam, _) = unApply (getRetTy nty')-         let corec = case fam of-                        P _ rcty _ -> case lookupCtxt rcty (idris_datatypes i) of-                                        [TI _ True _ _ _ _] -> True-                                        _ -> False-                        _ -> False          -- Productivity checking now via checking for guarded 'Delay'          let opts' = opts -- if corec then (Coinductive : opts) else opts          let usety = if norm then nty' else nty@@ -251,14 +214,6 @@               _ -> return ()          return usety   where-    -- for making an internalapp, we only want the explicit ones, and don't-    -- want the parameters, so just take the arguments which correspond to the-    -- user declared explicit ones-    mergeTy (PPi e n fc ty sc) (PPi e' n' _ _ sc')-         | e == e' = PPi e n fc ty (mergeTy sc sc')-         | otherwise = mergeTy sc sc'-    mergeTy _ sc = sc-     ffiexport = sNS (sUN "FFI_Export") ["FFI_Export"]      err = txt "Err"
src/Idris/Elab/Utils.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Elab.Utils Description : Elaborator utilities.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -14,7 +14,6 @@ import Idris.Core.TT import Idris.Core.Typecheck import Idris.Core.WHNF-import Idris.DeepSeq import Idris.Delaborate import Idris.Docstrings import Idris.Error@@ -22,14 +21,11 @@  import Util.Pretty -import Control.Applicative hiding (Const) import Control.Monad import Control.Monad.State import Data.List import qualified Data.Map as Map import Data.Maybe-import qualified Data.Traversable as Traversable-import Debug.Trace  recheckC = recheckC_borrowing False True [] @@ -122,7 +118,6 @@ elabCaseBlock info opts d@(PClauses f o n ps)         = do addIBC (IBCDef n)              logElab 5 $ "CASE BLOCK: " ++ show (n, d)-             let opts' = nub (o ++ opts)              -- propagate totality assertion to the new definitions              let opts' = filter propagatable opts              setFlags n opts'@@ -291,6 +286,40 @@                           _ -> paramNames args env ps    | otherwise = paramNames args env ps +-- Get all the names with multiplicity '1' used in a partial proof term+getLinearUsed :: Context -> Term -> [Name]+getLinearUsed ctxt tm = execState (getLin [] [] tm) []+  where+    getLin :: Env -> [(Name, Bool)] -> Term -> State [Name] ()+    getLin env us (Bind n b sc)+        = do getLinB env us b+             let r = getRig b+             let lin = case r of+                            Rig1 -> True+                            _ -> False+             getLin ((n, getRig b, b) : env) ((n, lin) : us) sc+    getLin env us (App _ f a) = do getLin env us f; getLin env us a+    getLin env us (V i)+       | i < length us = if snd (us!!i) then use (fst (us!!1)) else return ()+    getLin env us (P _ n _)+       | Just u <- lookup n us = if u then use n else return ()+    getLin env us _ = return ()++    getLinB env us (Let Rig0 t v) = return ()+    getLinB env us (Let rig t v) = getLin env us v+    getLinB env us (Guess t v) = getLin env us v+    getLinB env us (NLet t v) = getLin env us v+    getLinB env us b = return ()++    use n = do ns <- get; put (n : ns)++    getRig :: Binder Term -> RigCount+    getRig (Pi rig _ _ _) = rig+    getRig (PVar rig _) = rig+    getRig (Lam rig _) = rig+    getRig (Let rig _ _) = rig+    getRig _ = RigW+ getUniqueUsed :: Context -> Term -> [Name] getUniqueUsed ctxt tm = execState (getUniq [] [] tm) []   where@@ -312,7 +341,7 @@      use n = do ns <- get; put (n : ns) -    getUniqB env us (Let t v) = getUniq env us v+    getUniqB env us (Let rig t v) = getUniq env us v     getUniqB env us (Guess t v) = getUniq env us v --     getUniqB env us (Pi _ _ t v) = do getUniq env us t; getUniq env us v     getUniqB env us (NLet t v) = getUniq env us v@@ -528,10 +557,10 @@                                          v' <- getPats v                                          sc' <- getPats sc                                          return (Bind n (Guess t' v') sc')-    getPats (Bind n (Let t v) sc) = do t' <- getPats t-                                       v' <- getPats v-                                       sc' <- getPats sc-                                       return (Bind n (Let t' v') sc')+    getPats (Bind n (Let rig t v) sc) = do t' <- getPats t+                                           v' <- getPats v+                                           sc' <- getPats sc+                                           return (Bind n (Let rig t' v') sc')     getPats (Bind n (Pi rig i t k) sc) = do t' <- getPats t                                             k' <- getPats k                                             sc' <- getPats sc@@ -579,25 +608,44 @@     = isEmpty ctxt tyctxt ty || hasEmptyPat ctxt tyctxt sc hasEmptyPat ctxt tyctxt _ = False --- Find names which are applied to a function in a Rig1 position-findLinear :: IState -> [Name] -> Term -> [(Name, RigCount)]-findLinear ist env tm | (P _ f _, args) <- unApply tm,-                        f `notElem` env,-                        Just ty_in <- lookupTyExact f (tt_ctxt ist)+-- Find names which are applied to a function in a Rig1/Rig0 position+-- 'rig' is the multiplicity of the outer argument. When we go under a+-- function application, multiply them (it only needs to be Rig1 if it's+-- a linear argument to a linear argument; it needs to be a Rig0 if it's+-- Rig0 at any level)+findLinear :: RigCount -> IState -> [Name] -> Term -> [(Name, RigCount)]+findLinear rig ist env tm+      | (P _ f _, args) <- unApply tm,+        f `notElem` env,+        Just ty_in <- lookupTyExact f (tt_ctxt ist)     = let ty = whnfArgs (tt_ctxt ist) [] ty_in in-          nub $ concatMap (findLinear ist env) args ++ findLinArg ty args+           combineRig $ findLinArg ty args   where     findLinArg (Bind n (Pi c _ _ _) sc) (P _ a _ : as)-         | Rig0 <- c = (a, c) : findLinArg sc as-         | Rig1 <- c = (a, c) : findLinArg sc as-    findLinArg (Bind n (Pi _ _ _ _) sc) (a : as)-          = findLinArg (whnf (tt_ctxt ist) [] (substV a sc)) as-    findLinArg _ _ = []-findLinear ist env (App _ f a)-    = nub $ findLinear ist env f ++ findLinear ist env a-findLinear ist env (Bind n b sc) = findLinear ist (n : env) sc-findLinear ist _ _ = []+          = (a, rigMult rig c) : findLinArg sc as+    findLinArg (Bind n (Pi c _ _ _) sc) (a : as)+          = findLinear (rigMult c rig) ist env a +++               findLinArg (whnf (tt_ctxt ist) [] (substV a sc)) as+    findLinArg ty (a : as)+          = findLinear rig ist env a ++ findLinArg ty as+    findLinArg _ [] = [] +    -- If a name is used multiple times in a pattern, take the least restrictive+    -- use of it+    combineRig [] = []+    combineRig ((n, r) : rs)+        = let (rs', rig) = findRestrictive n r [] rs in+              (n, rig) : combineRig rs'+    findRestrictive n r acc [] = (acc, r)+    findRestrictive n r acc ((n', r') : rs)+        | n == n' = findRestrictive n (max r r') acc rs+        | otherwise = findRestrictive n r ((n', r') : acc) rs++findLinear rig ist env (App _ f a)+    = nub $ findLinear rig ist env f ++ findLinear rig ist env a+findLinear rig ist env (Bind n b sc) = findLinear rig ist (n : env) sc+findLinear rig ist _ _ = []+ setLinear :: [(Name, RigCount)] -> Term -> Term setLinear ns (Bind n b@(PVar r t) sc)    | Just r <- lookup n ns = Bind n (PVar r t) (setLinear ns sc)@@ -750,7 +798,7 @@ -- to it later - just returns 'var' for now. EB) isPlausible :: IState -> Bool -> Env -> Name -> Type -> Bool isPlausible ist var env n ty-    = let (hvar, interfaces) = collectConstraints [] [] ty in+    = let (hvar, _) = collectConstraints [] [] ty in           case hvar of                Nothing -> True                Just rth -> var -- trace (show (rth, interfaces)) var
src/Idris/Elab/Value.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Elab.Value Description : Code to elaborate values.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -13,48 +13,20 @@   ) where  import Idris.AbsSyntax-import Idris.ASTUtils-import Idris.Core.CaseTree import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Evaluate hiding (Unchecked)-import Idris.Core.Execute import Idris.Core.TT-import Idris.Core.Typecheck-import Idris.Coverage-import Idris.DataOpts-import Idris.DeepSeq-import Idris.Delaborate import Idris.Docstrings-import Idris.DSL import Idris.Elab.Term import Idris.Elab.Utils import Idris.Error-import Idris.Imports-import Idris.Inliner-import Idris.Output (iWarn, iputStrLn, pshow, sendHighlighting)-import Idris.PartialEval-import Idris.Primitives-import Idris.Providers-import IRTS.Lang--import Util.Pretty (pretty, text)+import Idris.Output (sendHighlighting)  import Prelude hiding (id, (.)) -import Control.Applicative hiding (Const) import Control.Category-import Control.DeepSeq-import Control.Monad-import Control.Monad.State.Strict as State-import Data.Char (isLetter, toLower)-import Data.List-import Data.List.Split (splitOn)-import qualified Data.Map as Map-import Data.Maybe-import qualified Data.Set as S-import qualified Data.Text as T+import Data.Char (toLower) import qualified Data.Traversable as Traversable-import Debug.Trace  -- | Elaborate a value, returning any new bindings created (this will only -- happen if elaborating as a pattern clause)
src/Idris/ElabDecls.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.ElabDecls Description : Code to elaborate declarations.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -9,23 +9,14 @@ {-# LANGUAGE DeriveFunctor, FlexibleInstances, MultiParamTypeClasses,              PatternGuards #-} -module Idris.ElabDecls where+module Idris.ElabDecls(elabDecl, elabDecl', elabDecls, elabMain, elabPrims,+                       recinfo) where  import Idris.AbsSyntax-import Idris.ASTUtils-import Idris.Core.CaseTree-import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Evaluate-import Idris.Core.Execute import Idris.Core.TT-import Idris.Core.Typecheck-import Idris.Coverage-import Idris.DataOpts-import Idris.DeepSeq-import Idris.Delaborate import Idris.Directives import Idris.Docstrings hiding (Unchecked)-import Idris.DSL import Idris.Elab.Clause import Idris.Elab.Data import Idris.Elab.Implementation@@ -36,36 +27,21 @@ import Idris.Elab.Term import Idris.Elab.Transform import Idris.Elab.Type-import Idris.Elab.Utils import Idris.Elab.Value import Idris.Error-import Idris.Imports-import Idris.Inliner import Idris.Options-import Idris.Output (iWarn, iputStrLn, pshow, sendHighlighting)-import Idris.PartialEval+import Idris.Output (sendHighlighting) import Idris.Primitives-import Idris.Providers import Idris.Termination import IRTS.Lang -import Util.Pretty (pretty, text)- import Prelude hiding (id, (.)) -import Control.Applicative hiding (Const) import Control.Category-import Control.DeepSeq import Control.Monad import Control.Monad.State.Strict as State-import Data.Char (isLetter, toLower)-import Data.List-import Data.List.Split (splitOn)-import qualified Data.Map as Map import Data.Maybe-import qualified Data.Set as S import qualified Data.Text as T-import Debug.Trace  -- | Top level elaborator info, supporting recursive elaboration recinfo :: FC -> ElabInfo@@ -86,7 +62,11 @@                let mkdec opt decl docs argdocs =                        PData docs argdocs defaultSyntax (fileFC "builtin")                              opt decl+               -- need to temporarily add linearity for this since the+               -- argument may be of restricted type+               addLangExt LinearTypes                elabDecl' EAll (recinfo primfc) (mkdec inferOpts inferDecl emptyDocstring [])+               dropLangExt LinearTypes                -- We don't want the constraints generated by 'Infer' since                -- it's only scaffolding for the elaborator                i <- getIState@@ -269,12 +249,6 @@          let nblock = pblock i          mapM_ (elabDecl' what info) nblock   where-    pinfo = let ds = concatMap tldeclared ps-                newps = params info ++ ns-                dsParams = map (\n -> (n, map fst newps)) ds-                newb = addAlist dsParams (inblock info) in-                info { params = newps,-                       inblock = newb }     pblock i = map (expandParamsD False i id ns                       (concatMap tldeclared ps)) ps @@ -311,6 +285,8 @@            ifail "You must turn on the DSLNotation extension to use a dsl block"          putIState (i { idris_dsls = addDef n dsl (idris_dsls i) })          addIBC (IBCDSL n)+elabDecl' what info (PDirective i@(DLogging _))+  = directiveAction i elabDecl' what info (PDirective i)   | what /= EDefns = directiveAction i elabDecl' what info (PProvider doc syn fc nfc provWhat n)
src/Idris/Erasure.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Erasure Description : Utilities to erase stuff not necessary for runtime.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -20,7 +20,6 @@  import Prelude hiding (id, (.)) -import Control.Applicative import Control.Arrow import Control.Category import Control.Monad.State@@ -36,8 +35,6 @@ import qualified Data.Set as S import Data.Text (pack) import qualified Data.Text as T-import Debug.Trace-import System.IO.Unsafe  -- | UseMap maps names to the set of used (reachable) argument -- positions.@@ -290,7 +287,6 @@         -- mini-DSL for postulates         (==>) ds rs = (S.fromList ds, M.fromList [(r, S.empty) | r <- rs])         it n is = [(sUN n, Arg i) | i <- is]-        mn n is = [(MN 0 $ pack n, Arg i) | i <- is]          -- believe_me is special because it does not use all its arguments         specialPrims = S.fromList [sUN "prim__believe_me"]@@ -480,7 +476,7 @@          -- let-bound variables can get partially evaluated         -- it is sufficient just to plug the Cond in when the bound names are used-        |  Let ty t <- bdr = var t cd `union` getDepsTerm vs ((n, const M.empty) : bs) cd body+        | Let rig ty t <- bdr = var t cd `union` getDepsTerm vs ((n, const M.empty) : bs) cd body         | NLet ty t <- bdr = var t cd `union` getDepsTerm vs ((n, const M.empty) : bs) cd body       where         var t cd = getDepsTerm vs bs cd t@@ -533,7 +529,7 @@             Bind n (Lam _ ty) t -> getDepsTerm vs bs cd (lamToLet app)              -- and we interpret applied lets as lambdas-            Bind n ( Let ty t') t -> getDepsTerm vs bs cd (App Complete (Bind n (Lam RigW ty) t) t')+            Bind n (Let _ ty t') t -> getDepsTerm vs bs cd (App Complete (Bind n (Lam RigW ty) t) t')             Bind n (NLet ty t') t -> getDepsTerm vs bs cd (App Complete (Bind n (Lam RigW ty) t) t')              Proj t i@@ -613,7 +609,7 @@         (f, args) = unApply tm      lamToLet' :: [Term] -> Term -> Term-    lamToLet' (v:vs) (Bind n (Lam _ ty) tm) = Bind n (Let ty v) $ lamToLet' vs tm+    lamToLet' (v:vs) (Bind n (Lam rig ty) tm) = Bind n (Let rig ty v) $ lamToLet' vs tm     lamToLet'    []  tm = tm     lamToLet'    vs  tm = error $         "Erasure.hs:lamToLet': unexpected input: "@@ -626,9 +622,6 @@      union :: Deps -> Deps -> Deps     union = M.unionWith (M.unionWith S.union)--    unions :: [Deps] -> Deps-    unions = M.unionsWith (M.unionWith S.union)      unionMap :: (a -> Deps) -> [a] -> Deps     unionMap f = M.unionsWith (M.unionWith S.union) . map f
src/Idris/ErrReverse.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.ErrReverse Description : Utility to make errors readable using transformations.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -12,10 +12,8 @@ import Idris.AbsSyntax import Idris.Core.Evaluate (unfold) import Idris.Core.TT-import Util.Pretty  import Data.List-import Debug.Trace  -- | For display purposes, apply any 'error reversal' transformations -- so that errors will be more readable,@@ -73,13 +71,3 @@                                              Just (fs ++ as)     -- no matching Binds, for now...     match' ns x y = if x == y then Just [] else Nothing--    -- if the term under a lambda is huge, there's no much point in showing-    -- it as it won't be very enlightening.--    elideLambdas (App s f a) = App s (elideLambdas f) (elideLambdas a)-    elideLambdas (Bind n (Lam _ t) sc)-       | size sc > 200 = P Ref (sUN "...") Erased-    elideLambdas (Bind n b sc)-       = Bind n (fmap elideLambdas b) (elideLambdas sc)-    elideLambdas t = t
src/Idris/Error.hs view
@@ -1,36 +1,30 @@ {-| Module      : Idris.Error Description : Utilities to deal with error reporting.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -} {-# LANGUAGE DeriveDataTypeable #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} -module Idris.Error where+module Idris.Error (getErrSpan, idrisCatch, ierror, ifail, iucheck, report,+                    setAndReport, showErr, tclift, tcliftAt, tctry, warnDisamb) where  import Idris.AbsSyntax import Idris.Core.Constraints import Idris.Core.Evaluate (ctxtAlist) import Idris.Core.TT-import Idris.Core.Typecheck import Idris.Delaborate import Idris.Output  import Prelude hiding (catch)  import Control.Monad (when)-import Control.Monad.State.Strict-import Data.Char import qualified Data.Foldable as Foldable import Data.List (intercalate, isPrefixOf) import qualified Data.Set as S import qualified Data.Text as T-import qualified Data.Traversable as Traversable-import Data.Typeable-import System.Console.Haskeline-import System.Console.Haskeline.MonadException import System.IO.Error (ioeGetErrorString, isUserError)  iucheck :: Idris ()@@ -107,7 +101,7 @@ warnDisamb ist (PPatvar _ _) = return () warnDisamb ist (PLam _ _ _ t b) = warnDisamb ist t >> warnDisamb ist b warnDisamb ist (PPi _ _ _ t b) = warnDisamb ist t >> warnDisamb ist b-warnDisamb ist (PLet _ _ _ x t b) = warnDisamb ist x >> warnDisamb ist t >> warnDisamb ist b+warnDisamb ist (PLet _ _ _ _ x t b) = warnDisamb ist x >> warnDisamb ist t >> warnDisamb ist b warnDisamb ist (PTyped x t) = warnDisamb ist x >> warnDisamb ist t warnDisamb ist (PApp _ t args) = warnDisamb ist t >>                                  mapM_ (warnDisamb ist . getTm) args@@ -136,8 +130,9 @@         wStep (DoBind _ _ _ x) = warnDisamb ist x         wStep (DoBindP _ x y cs) = warnDisamb ist x >> warnDisamb ist y >>                                    mapM_ (\(x,y) -> warnDisamb ist x >> warnDisamb ist y) cs-        wStep (DoLet _ _ _ x y) = warnDisamb ist x >> warnDisamb ist y-        wStep (DoLetP _ x y) = warnDisamb ist x >> warnDisamb ist y+        wStep (DoLet _ _ _ _ x y) = warnDisamb ist x >> warnDisamb ist y+        wStep (DoLetP _ x y cs) = warnDisamb ist x >> warnDisamb ist y >>+                                  mapM_ (\(x,y) -> warnDisamb ist x >> warnDisamb ist y) cs         wStep (DoRewrite _ h) = warnDisamb ist h warnDisamb ist (PIdiom _ x) = warnDisamb ist x warnDisamb ist (PMetavar _ _) = return ()
src/Idris/Help.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Help Description : Utilities to aid with the REPL's HELP system.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}
src/Idris/IBC.hs view
@@ -1,2566 +1,1044 @@ {-| Module      : Idris.IBC Description : Core representations and code to generate IBC files.-Copyright   :-License     : BSD3-Maintainer  : The Idris Community.--}-{-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-}-{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}--module Idris.IBC (loadIBC, loadPkgIndex,-                  writeIBC, writePkgIndex,-                  hasValidIBCVersion, IBCPhase(..)) where--import Idris.AbsSyntax-import Idris.Core.Binary-import Idris.Core.CaseTree-import Idris.Core.Evaluate-import Idris.Core.TT-import Idris.DeepSeq-import Idris.Delaborate-import Idris.Docstrings (Docstring)-import qualified Idris.Docstrings as D-import Idris.Error-import Idris.Imports-import Idris.Options-import Idris.Output-import IRTS.System (getIdrisLibDir)--import Paths_idris--import qualified Cheapskate.Types as CT-import Codec.Archive.Zip-import Control.DeepSeq-import Control.Monad-import Control.Monad.State.Strict hiding (get, put)-import qualified Control.Monad.State.Strict as ST-import Data.Binary-import Data.ByteString.Lazy as B hiding (elem, length, map)-import Data.Functor-import Data.List as L-import Data.Maybe (catMaybes)-import qualified Data.Set as S-import qualified Data.Text as T-import Data.Vector.Binary-import Debug.Trace-import System.Directory-import System.FilePath--ibcVersion :: Word16-ibcVersion = 162---- | When IBC is being loaded - we'll load different things (and omit--- different structures/definitions) depending on which phase we're in.-data IBCPhase = IBC_Building  -- ^ when building the module tree-              | IBC_REPL Bool -- ^ when loading modules for the REPL Bool = True for top level module-  deriving (Show, Eq)--data IBCFile = IBCFile {-    ver                        :: Word16-  , sourcefile                 :: FilePath-  , ibc_reachablenames         :: ![Name]-  , ibc_imports                :: ![(Bool, FilePath)]-  , ibc_importdirs             :: ![FilePath]-  , ibc_sourcedirs             :: ![FilePath]-  , ibc_implicits              :: ![(Name, [PArg])]-  , ibc_fixes                  :: ![FixDecl]-  , ibc_statics                :: ![(Name, [Bool])]-  , ibc_interfaces             :: ![(Name, InterfaceInfo)]-  , ibc_records                :: ![(Name, RecordInfo)]-  , ibc_implementations        :: ![(Bool, Bool, Name, Name)]-  , ibc_dsls                   :: ![(Name, DSL)]-  , ibc_datatypes              :: ![(Name, TypeInfo)]-  , ibc_optimise               :: ![(Name, OptInfo)]-  , ibc_syntax                 :: ![Syntax]-  , ibc_keywords               :: ![String]-  , ibc_objs                   :: ![(Codegen, FilePath)]-  , ibc_libs                   :: ![(Codegen, String)]-  , ibc_cgflags                :: ![(Codegen, String)]-  , ibc_dynamic_libs           :: ![String]-  , ibc_hdrs                   :: ![(Codegen, String)]-  , ibc_totcheckfail           :: ![(FC, String)]-  , ibc_flags                  :: ![(Name, [FnOpt])]-  , ibc_fninfo                 :: ![(Name, FnInfo)]-  , ibc_cg                     :: ![(Name, CGInfo)]-  , ibc_docstrings             :: ![(Name, (Docstring D.DocTerm, [(Name, Docstring D.DocTerm)]))]-  , ibc_moduledocs             :: ![(Name, Docstring D.DocTerm)]-  , ibc_transforms             :: ![(Name, (Term, Term))]-  , ibc_errRev                 :: ![(Term, Term)]-  , ibc_errReduce              :: ![Name]-  , ibc_coercions              :: ![Name]-  , ibc_lineapps               :: ![(FilePath, Int, PTerm)]-  , ibc_namehints              :: ![(Name, Name)]-  , ibc_metainformation        :: ![(Name, MetaInformation)]-  , ibc_errorhandlers          :: ![Name]-  , ibc_function_errorhandlers :: ![(Name, Name, Name)] -- fn, arg, handler-  , ibc_metavars               :: ![(Name, (Maybe Name, Int, [Name], Bool, Bool))]-  , ibc_patdefs                :: ![(Name, ([([(Name, Term)], Term, Term)], [PTerm]))]-  , ibc_postulates             :: ![Name]-  , ibc_externs                :: ![(Name, Int)]-  , ibc_parsedSpan             :: !(Maybe FC)-  , ibc_usage                  :: ![(Name, Int)]-  , ibc_exports                :: ![Name]-  , ibc_autohints              :: ![(Name, Name)]-  , ibc_deprecated             :: ![(Name, String)]-  , ibc_defs                   :: ![(Name, Def)]-  , ibc_total                  :: ![(Name, Totality)]-  , ibc_injective              :: ![(Name, Injectivity)]-  , ibc_access                 :: ![(Name, Accessibility)]-  , ibc_fragile                :: ![(Name, String)]-  , ibc_constraints            :: ![(FC, UConstraint)]-  }-  deriving Show-{-!-deriving instance Binary IBCFile-!-}--initIBC :: IBCFile-initIBC = IBCFile ibcVersion "" [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] Nothing [] [] [] [] [] [] [] [] [] []--hasValidIBCVersion :: FilePath -> Idris Bool-hasValidIBCVersion fp = do-  archiveFile <- runIO $ B.readFile fp-  case toArchiveOrFail archiveFile of-    Left _ -> return False-    Right archive -> do ver <- getEntry 0 "ver" archive-                        return (ver == ibcVersion)---loadIBC :: Bool -- ^ True = reexport, False = make everything private-        -> IBCPhase-        -> FilePath -> Idris ()-loadIBC reexport phase fp-           = do imps <- getImported-                case lookup fp imps of-                    Nothing -> load True-                    Just p -> if (not p && reexport) then load False else return ()-        where-            load fullLoad = do-                    logIBC 1 $ "Loading ibc " ++ fp ++ " " ++ show reexport-                    archiveFile <- runIO $ B.readFile fp-                    case toArchiveOrFail archiveFile of-                        Left _ -> do-                            ifail $ fp  ++ " isn't loadable, it may have an old ibc format.\n"-                                        ++ "Please clean and rebuild it."-                        Right archive -> do-                            if fullLoad-                                then process reexport phase archive fp-                                else unhide phase archive-                            addImported reexport fp---- | Load an entire package from its index file-loadPkgIndex :: String -> Idris ()-loadPkgIndex pkg = do ddir <- runIO getIdrisLibDir-                      addImportDir (ddir </> pkg)-                      fp <- findPkgIndex pkg-                      loadIBC True IBC_Building fp---makeEntry :: (Binary b) => String -> [b] -> Maybe Entry-makeEntry name val = if L.null val-                        then Nothing-                        else Just $ toEntry name 0 (encode val)---entries :: IBCFile -> [Entry]-entries i = catMaybes [Just $ toEntry "ver" 0 (encode $ ver i),-                       makeEntry "sourcefile"  (sourcefile i),-                       makeEntry "ibc_imports"  (ibc_imports i),-                       makeEntry "ibc_importdirs"  (ibc_importdirs i),-                       makeEntry "ibc_sourcedirs"  (ibc_sourcedirs i),-                       makeEntry "ibc_implicits"  (ibc_implicits i),-                       makeEntry "ibc_fixes"  (ibc_fixes i),-                       makeEntry "ibc_statics"  (ibc_statics i),-                       makeEntry "ibc_interfaces"  (ibc_interfaces i),-                       makeEntry "ibc_records"  (ibc_records i),-                       makeEntry "ibc_implementations"  (ibc_implementations i),-                       makeEntry "ibc_dsls"  (ibc_dsls i),-                       makeEntry "ibc_datatypes"  (ibc_datatypes i),-                       makeEntry "ibc_optimise"  (ibc_optimise i),-                       makeEntry "ibc_syntax"  (ibc_syntax i),-                       makeEntry "ibc_keywords"  (ibc_keywords i),-                       makeEntry "ibc_objs"  (ibc_objs i),-                       makeEntry "ibc_libs"  (ibc_libs i),-                       makeEntry "ibc_cgflags"  (ibc_cgflags i),-                       makeEntry "ibc_dynamic_libs"  (ibc_dynamic_libs i),-                       makeEntry "ibc_hdrs"  (ibc_hdrs i),-                       makeEntry "ibc_totcheckfail"  (ibc_totcheckfail i),-                       makeEntry "ibc_flags"  (ibc_flags i),-                       makeEntry "ibc_fninfo"  (ibc_fninfo i),-                       makeEntry "ibc_cg"  (ibc_cg i),-                       makeEntry "ibc_docstrings"  (ibc_docstrings i),-                       makeEntry "ibc_moduledocs"  (ibc_moduledocs i),-                       makeEntry "ibc_transforms"  (ibc_transforms i),-                       makeEntry "ibc_errRev"  (ibc_errRev i),-                       makeEntry "ibc_errReduce"  (ibc_errReduce i),-                       makeEntry "ibc_coercions"  (ibc_coercions i),-                       makeEntry "ibc_lineapps"  (ibc_lineapps i),-                       makeEntry "ibc_namehints"  (ibc_namehints i),-                       makeEntry "ibc_metainformation"  (ibc_metainformation i),-                       makeEntry "ibc_errorhandlers"  (ibc_errorhandlers i),-                       makeEntry "ibc_function_errorhandlers"  (ibc_function_errorhandlers i),-                       makeEntry "ibc_metavars"  (ibc_metavars i),-                       makeEntry "ibc_patdefs"  (ibc_patdefs i),-                       makeEntry "ibc_postulates"  (ibc_postulates i),-                       makeEntry "ibc_externs"  (ibc_externs i),-                       toEntry "ibc_parsedSpan" 0 . encode <$> ibc_parsedSpan i,-                       makeEntry "ibc_usage"  (ibc_usage i),-                       makeEntry "ibc_exports"  (ibc_exports i),-                       makeEntry "ibc_autohints"  (ibc_autohints i),-                       makeEntry "ibc_deprecated"  (ibc_deprecated i),-                       makeEntry "ibc_defs"  (ibc_defs i),-                       makeEntry "ibc_total"  (ibc_total i),-                       makeEntry "ibc_injective"  (ibc_injective i),-                       makeEntry "ibc_access"  (ibc_access i),-                       makeEntry "ibc_fragile" (ibc_fragile i)]--- TODO: Put this back in shortly after minimising/pruning constraints---                        makeEntry "ibc_constraints" (ibc_constraints i)]--writeArchive :: FilePath -> IBCFile -> Idris ()-writeArchive fp i = do let a = L.foldl (\x y -> addEntryToArchive y x) emptyArchive (entries i)-                       runIO $ B.writeFile fp (fromArchive a)--writeIBC :: FilePath -> FilePath -> Idris ()-writeIBC src f-    = do-         logIBC  2 $ "Writing IBC for: " ++ show f-         iReport 2 $ "Writing IBC for: " ++ show f-         i <- getIState---          case (Data.List.map fst (idris_metavars i)) \\ primDefs of---                 (_:_) -> ifail "Can't write ibc when there are unsolved metavariables"---                 [] -> return ()-         resetNameIdx-         ibcf <- mkIBC (ibc_write i) (initIBC { sourcefile = src })-         idrisCatch (do runIO $ createDirectoryIfMissing True (dropFileName f)-                        writeArchive f ibcf-                        logIBC 2 "Written")-            (\c -> do logIBC 2 $ "Failed " ++ pshow i c)-         return ()---- | Write a package index containing all the imports in the current--- IState Used for ':search' of an entire package, to ensure--- everything is loaded.-writePkgIndex :: FilePath -> Idris ()-writePkgIndex f-    = do i <- getIState-         let imps = map (\ (x, y) -> (True, x)) $ idris_imported i-         logIBC 2 $ "Writing package index " ++ show f ++ " including\n" ++-                show (map snd imps)-         resetNameIdx-         let ibcf = initIBC { ibc_imports = imps }-         idrisCatch (do runIO $ createDirectoryIfMissing True (dropFileName f)-                        writeArchive f ibcf-                        logIBC 2 "Written")-            (\c -> do logIBC 2 $ "Failed " ++ pshow i c)-         return ()--mkIBC :: [IBCWrite] -> IBCFile -> Idris IBCFile-mkIBC [] f = return f-mkIBC (i:is) f = do ist <- getIState-                    logIBC 5 $ show i ++ " " ++ show (L.length is)-                    f' <- ibc ist i f-                    mkIBC is f'--ibc :: IState -> IBCWrite -> IBCFile -> Idris IBCFile-ibc i (IBCFix d) f = return f { ibc_fixes = d : ibc_fixes f }-ibc i (IBCImp n) f = case lookupCtxtExact n (idris_implicits i) of-                        Just v -> return f { ibc_implicits = (n,v): ibc_implicits f     }-                        _ -> ifail "IBC write failed"-ibc i (IBCStatic n) f-                   = case lookupCtxtExact n (idris_statics i) of-                        Just v -> return f { ibc_statics = (n,v): ibc_statics f     }-                        _ -> ifail "IBC write failed"-ibc i (IBCInterface n) f-                   = case lookupCtxtExact n (idris_interfaces i) of-                        Just v -> return f { ibc_interfaces = (n,v): ibc_interfaces f     }-                        _ -> ifail "IBC write failed"-ibc i (IBCRecord n) f-                   = case lookupCtxtExact n (idris_records i) of-                        Just v -> return f { ibc_records = (n,v): ibc_records f     }-                        _ -> ifail "IBC write failed"-ibc i (IBCImplementation int res n ins) f-                   = return f { ibc_implementations = (int, res, n, ins) : ibc_implementations f }-ibc i (IBCDSL n) f-                   = case lookupCtxtExact n (idris_dsls i) of-                        Just v -> return f { ibc_dsls = (n,v): ibc_dsls f     }-                        _ -> ifail "IBC write failed"-ibc i (IBCData n) f-                   = case lookupCtxtExact n (idris_datatypes i) of-                        Just v -> return f { ibc_datatypes = (n,v): ibc_datatypes f     }-                        _ -> ifail "IBC write failed"-ibc i (IBCOpt n) f = case lookupCtxtExact n (idris_optimisation i) of-                        Just v -> return f { ibc_optimise = (n,v): ibc_optimise f     }-                        _ -> ifail "IBC write failed"-ibc i (IBCSyntax n) f = return f { ibc_syntax = n : ibc_syntax f }-ibc i (IBCKeyword n) f = return f { ibc_keywords = n : ibc_keywords f }-ibc i (IBCImport n) f = return f { ibc_imports = n : ibc_imports f }-ibc i (IBCImportDir n) f = return f { ibc_importdirs = n : ibc_importdirs f }-ibc i (IBCSourceDir n) f = return f { ibc_sourcedirs = n : ibc_sourcedirs f }-ibc i (IBCObj tgt n) f = return f { ibc_objs = (tgt, n) : ibc_objs f }-ibc i (IBCLib tgt n) f = return f { ibc_libs = (tgt, n) : ibc_libs f }-ibc i (IBCCGFlag tgt n) f = return f { ibc_cgflags = (tgt, n) : ibc_cgflags f }-ibc i (IBCDyLib n) f = return f {ibc_dynamic_libs = n : ibc_dynamic_libs f }-ibc i (IBCHeader tgt n) f = return f { ibc_hdrs = (tgt, n) : ibc_hdrs f }-ibc i (IBCDef n) f-   = do f' <- case lookupDefExact n (tt_ctxt i) of-                   Just v -> return f { ibc_defs = (n,v) : ibc_defs f }-                   _ -> ifail "IBC write failed"-        case lookupCtxtExact n (idris_patdefs i) of-                   Just v -> return f' { ibc_patdefs = (n,v) : ibc_patdefs f }-                   _ -> return f' -- Not a pattern definition--ibc i (IBCDoc n) f = case lookupCtxtExact n (idris_docstrings i) of-                        Just v -> return f { ibc_docstrings = (n,v) : ibc_docstrings f }-                        _ -> ifail "IBC write failed"-ibc i (IBCCG n) f = case lookupCtxtExact n (idris_callgraph i) of-                        Just v -> return f { ibc_cg = (n,v) : ibc_cg f     }-                        _ -> ifail "IBC write failed"-ibc i (IBCCoercion n) f = return f { ibc_coercions = n : ibc_coercions f }-ibc i (IBCAccess n a) f = return f { ibc_access = (n,a) : ibc_access f }-ibc i (IBCFlags n) f-    = case lookupCtxtExact n (idris_flags i) of-           Just a -> return f { ibc_flags = (n,a): ibc_flags f }-           _ -> ifail "IBC write failed"-ibc i (IBCFnInfo n a) f = return f { ibc_fninfo = (n,a) : ibc_fninfo f }-ibc i (IBCTotal n a) f = return f { ibc_total = (n,a) : ibc_total f }-ibc i (IBCInjective n a) f = return f { ibc_injective = (n,a) : ibc_injective f }-ibc i (IBCTrans n t) f = return f { ibc_transforms = (n, t) : ibc_transforms f }-ibc i (IBCErrRev t) f = return f { ibc_errRev = t : ibc_errRev f }-ibc i (IBCErrReduce t) f = return f { ibc_errReduce = t : ibc_errReduce f }-ibc i (IBCLineApp fp l t) f-     = return f { ibc_lineapps = (fp,l,t) : ibc_lineapps f }-ibc i (IBCNameHint (n, ty)) f-     = return f { ibc_namehints = (n, ty) : ibc_namehints f }-ibc i (IBCMetaInformation n m) f = return f { ibc_metainformation = (n,m) : ibc_metainformation f }-ibc i (IBCErrorHandler n) f = return f { ibc_errorhandlers = n : ibc_errorhandlers f }-ibc i (IBCFunctionErrorHandler fn a n) f =-  return f { ibc_function_errorhandlers = (fn, a, n) : ibc_function_errorhandlers f }-ibc i (IBCMetavar n) f =-     case lookup n (idris_metavars i) of-          Nothing -> return f-          Just t -> return f { ibc_metavars = (n, t) : ibc_metavars f }-ibc i (IBCPostulate n) f = return f { ibc_postulates = n : ibc_postulates f }-ibc i (IBCExtern n) f = return f { ibc_externs = n : ibc_externs f }-ibc i (IBCTotCheckErr fc err) f = return f { ibc_totcheckfail = (fc, err) : ibc_totcheckfail f }-ibc i (IBCParsedRegion fc) f = return f { ibc_parsedSpan = Just fc }-ibc i (IBCModDocs n) f = case lookupCtxtExact n (idris_moduledocs i) of-                           Just v -> return f { ibc_moduledocs = (n,v) : ibc_moduledocs f }-                           _ -> ifail "IBC write failed"-ibc i (IBCUsage n) f = return f { ibc_usage = n : ibc_usage f }-ibc i (IBCExport n) f = return f { ibc_exports = n : ibc_exports f }-ibc i (IBCAutoHint n h) f = return f { ibc_autohints = (n, h) : ibc_autohints f }-ibc i (IBCDeprecate n r) f = return f { ibc_deprecated = (n, r) : ibc_deprecated f }-ibc i (IBCFragile n r)   f = return f { ibc_fragile    = (n,r)  : ibc_fragile f }-ibc i (IBCConstraint fc u)  f = return f { ibc_constraints = (fc, u) : ibc_constraints f }--getEntry :: (Binary b, NFData b) => b -> FilePath -> Archive -> Idris b-getEntry alt f a = case findEntryByPath f a of-                Nothing -> return alt-                Just e -> return $! (force . decode . fromEntry) e--unhide :: IBCPhase -> Archive -> Idris ()-unhide phase ar = do-    processImports True phase ar-    processAccess True phase ar--process :: Bool -- ^ Reexporting-           -> IBCPhase-           -> Archive -> FilePath -> Idris ()-process reexp phase archive fn = do-                ver <- getEntry 0 "ver" archive-                when (ver /= ibcVersion) $ do-                                    logIBC 2 "ibc out of date"-                                    let e = if ver < ibcVersion-                                            then "an earlier" else "a later"-                                    ldir <- runIO $ getIdrisLibDir-                                    let start = if ldir `L.isPrefixOf` fn-                                                  then "This external module"-                                                  else "This module"-                                    let end = case L.stripPrefix ldir fn of-                                                Nothing -> "Please clean and rebuild."--                                                Just ploc -> unwords ["Please reinstall:", L.head $ splitDirectories ploc]-                                    ifail $ unlines [ unwords ["Incompatible ibc version for:", show fn]-                                                    , unwords [start-                                                              , "was built with"-                                                              , e-                                                              , "version of Idris."]-                                                    , end-                                                    ]-                source <- getEntry "" "sourcefile" archive-                srcok <- runIO $ doesFileExist source-                when srcok $ timestampOlder source fn-                processImportDirs archive-                processSourceDirs archive-                processImports reexp phase archive-                processImplicits archive-                processInfix archive-                processStatics archive-                processInterfaces archive-                processRecords archive-                processImplementations archive-                processDSLs archive-                processDatatypes  archive-                processOptimise  archive-                processSyntax archive-                processKeywords archive-                processObjectFiles archive-                processLibs archive-                processCodegenFlags archive-                processDynamicLibs archive-                processHeaders archive-                processPatternDefs archive-                processFlags archive-                processFnInfo archive-                processTotalityCheckError archive-                processCallgraph archive-                processDocs archive-                processModuleDocs archive-                processCoercions archive-                processTransforms archive-                processErrRev archive-                processErrReduce archive-                processLineApps archive-                processNameHints archive-                processMetaInformation archive-                processErrorHandlers archive-                processFunctionErrorHandlers archive-                processMetaVars archive-                processPostulates archive-                processExterns archive-                processParsedSpan archive-                processUsage archive-                processExports archive-                processAutoHints archive-                processDeprecate archive-                processDefs archive-                processTotal archive-                processInjective archive-                processAccess reexp phase archive-                processFragile archive-                processConstraints archive--timestampOlder :: FilePath -> FilePath -> Idris ()-timestampOlder src ibc = do-  srct <- runIO $ getModificationTime src-  ibct <- runIO $ getModificationTime ibc-  if (srct > ibct)-    then ifail $ unlines [ "Module needs reloading:"-                         , unwords ["\tSRC :", show src]-                         , unwords ["\tModified at:", show srct]-                         , unwords ["\tIBC :", show ibc]-                         , unwords ["\tModified at:", show ibct]-                         ]-    else return ()--processPostulates :: Archive -> Idris ()-processPostulates ar = do-    ns <- getEntry [] "ibc_postulates" ar-    updateIState (\i -> i { idris_postulates = idris_postulates i `S.union` S.fromList ns })--processExterns :: Archive -> Idris ()-processExterns ar = do-    ns <-  getEntry [] "ibc_externs" ar-    updateIState (\i -> i{ idris_externs = idris_externs i `S.union` S.fromList ns })--processParsedSpan :: Archive -> Idris ()-processParsedSpan ar = do-    fc <- getEntry Nothing "ibc_parsedSpan" ar-    updateIState (\i -> i { idris_parsedSpan = fc })--processUsage :: Archive -> Idris ()-processUsage ar = do-    ns <- getEntry [] "ibc_usage" ar-    updateIState (\i -> i { idris_erasureUsed = ns ++ idris_erasureUsed i })--processExports :: Archive -> Idris ()-processExports ar = do-    ns <- getEntry [] "ibc_exports" ar-    updateIState (\i -> i { idris_exports = ns ++ idris_exports i })--processAutoHints :: Archive -> Idris ()-processAutoHints ar = do-    ns <- getEntry [] "ibc_autohints" ar-    mapM_ (\(n,h) -> addAutoHint n h) ns--processDeprecate :: Archive -> Idris ()-processDeprecate ar = do-    ns <-  getEntry [] "ibc_deprecated" ar-    mapM_ (\(n,reason) -> addDeprecated n reason) ns--processFragile :: Archive -> Idris ()-processFragile ar = do-    ns <- getEntry [] "ibc_fragile" ar-    mapM_ (\(n,reason) -> addFragile n reason) ns--processConstraints :: Archive -> Idris ()-processConstraints ar = do-    cs <- getEntry [] "ibc_constraints" ar-    mapM_ (\ (fc, c) -> addConstraints fc (0, [c])) cs--processImportDirs :: Archive -> Idris ()-processImportDirs ar = do-    fs <- getEntry [] "ibc_importdirs" ar-    mapM_ addImportDir fs--processSourceDirs :: Archive -> Idris ()-processSourceDirs ar = do-    fs <- getEntry [] "ibc_sourcedirs" ar-    mapM_ addSourceDir fs--processImports :: Bool -> IBCPhase -> Archive -> Idris ()-processImports reexp phase ar = do-    fs <- getEntry [] "ibc_imports" ar-    mapM_ (\(re, f) -> do-        i <- getIState-        ibcsd <- valIBCSubDir i-        ids <- allImportDirs-        fp <- findImport ids ibcsd f---                        if (f `elem` imported i)---                         then logLvl 1 $ "Already read " ++ f-        putIState (i { imported = f : imported i })-        let phase' = case phase of-                         IBC_REPL _ -> IBC_REPL False-                         p -> p-        case fp of-            LIDR fn -> do-                logIBC 2 $ "Failed at " ++ fn-                ifail "Must be an ibc"-            IDR fn -> do-                logIBC 2 $ "Failed at " ++ fn-                ifail "Must be an ibc"-            IBC fn src -> loadIBC (reexp && re) phase' fn) fs--processImplicits :: Archive -> Idris ()-processImplicits ar = do-    imps <- getEntry [] "ibc_implicits" ar-    mapM_ (\ (n, imp) -> do-        i <- getIState-        case lookupDefAccExact n False (tt_ctxt i) of-            Just (n, Hidden) -> return ()-            Just (n, Private) -> return ()-            _ -> putIState (i { idris_implicits = addDef n imp (idris_implicits i) })) imps--processInfix :: Archive -> Idris ()-processInfix ar = do-    f <- getEntry [] "ibc_fixes" ar-    updateIState (\i -> i { idris_infixes = sort $ f ++ idris_infixes i })--processStatics :: Archive -> Idris ()-processStatics ar = do-    ss <- getEntry [] "ibc_statics" ar-    mapM_ (\ (n, s) ->-        updateIState (\i -> i { idris_statics = addDef n s (idris_statics i) })) ss--processInterfaces :: Archive -> Idris ()-processInterfaces ar = do-    cs <- getEntry [] "ibc_interfaces" ar-    mapM_ (\ (n, c) -> do-        i <- getIState-        -- Don't lose implementations from previous IBCs, which-        -- could have loaded in any order-        let is = case lookupCtxtExact n (idris_interfaces i) of-                    Just ci -> interface_implementations ci-                    _ -> []-        let c' = c { interface_implementations = interface_implementations c ++ is }-        putIState (i { idris_interfaces = addDef n c' (idris_interfaces i) })) cs--processRecords :: Archive -> Idris ()-processRecords ar = do-    rs <- getEntry [] "ibc_records" ar-    mapM_ (\ (n, r) ->-        updateIState (\i -> i { idris_records = addDef n r (idris_records i) })) rs--processImplementations :: Archive -> Idris ()-processImplementations ar = do-    cs <- getEntry [] "ibc_implementations" ar-    mapM_ (\ (i, res, n, ins) -> addImplementation i res n ins) cs--processDSLs :: Archive -> Idris ()-processDSLs ar = do-    cs <- getEntry [] "ibc_dsls" ar-    mapM_ (\ (n, c) -> updateIState (\i ->-                        i { idris_dsls = addDef n c (idris_dsls i) })) cs--processDatatypes :: Archive -> Idris ()-processDatatypes ar = do-    cs <- getEntry [] "ibc_datatypes" ar-    mapM_ (\ (n, c) -> updateIState (\i ->-                        i { idris_datatypes = addDef n c (idris_datatypes i) })) cs--processOptimise :: Archive -> Idris ()-processOptimise ar = do-    cs <- getEntry [] "ibc_optimise" ar-    mapM_ (\ (n, c) -> updateIState (\i ->-                        i { idris_optimisation = addDef n c (idris_optimisation i) })) cs--processSyntax :: Archive -> Idris ()-processSyntax ar = do-    s <- getEntry [] "ibc_syntax" ar-    updateIState (\i -> i { syntax_rules = updateSyntaxRules s (syntax_rules i) })--processKeywords :: Archive -> Idris ()-processKeywords ar = do-    k <- getEntry [] "ibc_keywords" ar-    updateIState (\i -> i { syntax_keywords = k ++ syntax_keywords i })--processObjectFiles :: Archive -> Idris ()-processObjectFiles ar = do-    os <- getEntry [] "ibc_objs" ar-    mapM_ (\ (cg, obj) -> do-        dirs <- allImportDirs-        o <- runIO $ findInPath dirs obj-        addObjectFile cg o) os--processLibs :: Archive -> Idris ()-processLibs ar = do-    ls <- getEntry [] "ibc_libs" ar-    mapM_ (uncurry addLib) ls--processCodegenFlags :: Archive -> Idris ()-processCodegenFlags ar = do-    ls <- getEntry [] "ibc_cgflags" ar-    mapM_ (uncurry addFlag) ls--processDynamicLibs :: Archive -> Idris ()-processDynamicLibs ar = do-        ls <- getEntry [] "ibc_dynamic_libs" ar-        res <- mapM (addDyLib . return) ls-        mapM_ checkLoad res-    where-        checkLoad (Left _) = return ()-        checkLoad (Right err) = ifail err--processHeaders :: Archive -> Idris ()-processHeaders ar = do-    hs <- getEntry [] "ibc_hdrs" ar-    mapM_ (uncurry addHdr) hs--processPatternDefs :: Archive -> Idris ()-processPatternDefs ar = do-    ds <- getEntry [] "ibc_patdefs" ar-    mapM_ (\ (n, d) -> updateIState (\i ->-            i { idris_patdefs = addDef n (force d) (idris_patdefs i) })) ds--processDefs :: Archive -> Idris ()-processDefs ar = do-        ds <- getEntry [] "ibc_defs" ar-        mapM_ (\ (n, d) -> do-            d' <- updateDef d-            case d' of-                TyDecl _ _ -> return ()-                _ -> do-                    logIBC 2 $ "SOLVING " ++ show n-                    solveDeferred emptyFC n-            updateIState (\i -> i { tt_ctxt = addCtxtDef n d' (tt_ctxt i) })) ds-    where-        updateDef (CaseOp c t args o s cd) = do-            o' <- mapM updateOrig o-            cd' <- updateCD cd-            return $ CaseOp c t args o' s cd'-        updateDef t = return t--        updateOrig (Left t) = liftM Left (update t)-        updateOrig (Right (l, r)) = do-            l' <- update l-            r' <- update r-            return $ Right (l', r')--        updateCD (CaseDefs (cs, c) (rs, r)) = do-            c' <- updateSC c-            r' <- updateSC r-            return $ CaseDefs (cs, c') (rs, r')--        updateSC (Case t n alts) = do-            alts' <- mapM updateAlt alts-            return (Case t n alts')-        updateSC (ProjCase t alts) = do-            alts' <- mapM updateAlt alts-            return (ProjCase t alts')-        updateSC (STerm t) = do-            t' <- update t-            return (STerm t')-        updateSC c = return c--        updateAlt (ConCase n i ns t) = do-            t' <- updateSC t-            return (ConCase n i ns t')-        updateAlt (FnCase n ns t) = do-            t' <- updateSC t-            return (FnCase n ns t')-        updateAlt (ConstCase c t) = do-            t' <- updateSC t-            return (ConstCase c t')-        updateAlt (SucCase n t) = do-            t' <- updateSC t-            return (SucCase n t')-        updateAlt (DefaultCase t) = do-            t' <- updateSC t-            return (DefaultCase t')--        -- We get a lot of repetition in sub terms and can save a fair chunk-        -- of memory if we make sure they're shared. addTT looks for a term-        -- and returns it if it exists already, while also keeping stats of-        -- how many times a subterm is repeated.-        update t = do-            tm <- addTT t-            case tm of-                Nothing -> update' t-                Just t' -> return t'--        update' (P t n ty) = do-            n' <- getSymbol n-            return $ P t n' ty-        update' (App s f a) = liftM2 (App s) (update' f) (update' a)-        update' (Bind n b sc) = do-            b' <- updateB b-            sc' <- update sc-            return $ Bind n b' sc'-                where-                    updateB (Let t v) = liftM2 Let (update' t) (update' v)-                    updateB b = do-                        ty' <- update' (binderTy b)-                        return (b { binderTy = ty' })-        update' (Proj t i) = do-                  t' <- update' t-                  return $ Proj t' i-        update' t = return t--processDocs :: Archive -> Idris ()-processDocs ar = do-    ds <- getEntry [] "ibc_docstrings" ar-    mapM_ (\(n, a) -> addDocStr n (fst a) (snd a)) ds--processModuleDocs :: Archive -> Idris ()-processModuleDocs ar = do-    ds <- getEntry [] "ibc_moduledocs" ar-    mapM_  (\ (n, d) -> updateIState (\i ->-            i { idris_moduledocs = addDef n d (idris_moduledocs i) })) ds--processAccess :: Bool -- ^ Reexporting?-           -> IBCPhase-           -> Archive -> Idris ()-processAccess reexp phase ar = do-    ds <- getEntry [] "ibc_access" ar-    mapM_ (\ (n, a_in) -> do-        let a = if reexp then a_in else Hidden-        logIBC 3 $ "Setting " ++ show (a, n) ++ " to " ++ show a-        updateIState (\i -> i { tt_ctxt = setAccess n a (tt_ctxt i) })--        if (not reexp)-            then do-                logIBC 2 $ "Not exporting " ++ show n-                setAccessibility n Hidden-            else logIBC 2 $ "Exporting " ++ show n-        -- Everything should be available at the REPL from-        -- things imported publicly-        when (phase == IBC_REPL True) $ setAccessibility n Public) ds--processFlags :: Archive -> Idris ()-processFlags ar = do-    ds <- getEntry [] "ibc_flags" ar-    mapM_ (\ (n, a) -> setFlags n a) ds--processFnInfo :: Archive -> Idris ()-processFnInfo ar = do-    ds <- getEntry [] "ibc_fninfo" ar-    mapM_ (\ (n, a) -> setFnInfo n a) ds--processTotal :: Archive -> Idris ()-processTotal ar = do-    ds <- getEntry [] "ibc_total" ar-    mapM_ (\ (n, a) -> updateIState (\i -> i { tt_ctxt = setTotal n a (tt_ctxt i) })) ds--processInjective :: Archive -> Idris ()-processInjective ar = do-    ds <- getEntry [] "ibc_injective" ar-    mapM_ (\ (n, a) -> updateIState (\i -> i { tt_ctxt = setInjective n a (tt_ctxt i) })) ds--processTotalityCheckError :: Archive -> Idris ()-processTotalityCheckError ar = do-    es <- getEntry [] "ibc_totcheckfail" ar-    updateIState (\i -> i { idris_totcheckfail = idris_totcheckfail i ++ es })--processCallgraph :: Archive -> Idris ()-processCallgraph ar = do-    ds <- getEntry [] "ibc_cg" ar-    mapM_ (\ (n, a) -> addToCG n a) ds--processCoercions :: Archive -> Idris ()-processCoercions ar = do-    ns <- getEntry [] "ibc_coercions" ar-    mapM_ (\ n -> addCoercion n) ns--processTransforms :: Archive -> Idris ()-processTransforms ar = do-    ts <- getEntry [] "ibc_transforms" ar-    mapM_ (\ (n, t) -> addTrans n t) ts--processErrRev :: Archive -> Idris ()-processErrRev ar = do-    ts <- getEntry [] "ibc_errRev" ar-    mapM_ addErrRev ts--processErrReduce :: Archive -> Idris ()-processErrReduce ar = do-    ts <- getEntry [] "ibc_errReduce" ar-    mapM_ addErrReduce ts--processLineApps :: Archive -> Idris ()-processLineApps ar = do-    ls <- getEntry [] "ibc_lineapps" ar-    mapM_ (\ (f, i, t) -> addInternalApp f i t) ls--processNameHints :: Archive -> Idris ()-processNameHints ar = do-    ns <- getEntry [] "ibc_namehints" ar-    mapM_ (\ (n, ty) -> addNameHint n ty) ns--processMetaInformation :: Archive -> Idris ()-processMetaInformation ar = do-    ds <- getEntry [] "ibc_metainformation" ar-    mapM_ (\ (n, m) -> updateIState (\i ->-                               i { tt_ctxt = setMetaInformation n m (tt_ctxt i) })) ds--processErrorHandlers :: Archive -> Idris ()-processErrorHandlers ar = do-    ns <- getEntry [] "ibc_errorhandlers" ar-    updateIState (\i -> i { idris_errorhandlers = idris_errorhandlers i ++ ns })--processFunctionErrorHandlers :: Archive -> Idris ()-processFunctionErrorHandlers ar = do-    ns <- getEntry [] "ibc_function_errorhandlers" ar-    mapM_ (\ (fn,arg,handler) -> addFunctionErrorHandlers fn arg [handler]) ns--processMetaVars :: Archive -> Idris ()-processMetaVars ar = do-    ns <- getEntry [] "ibc_metavars" ar-    updateIState (\i -> i { idris_metavars = L.reverse ns ++ idris_metavars i })------- For Cheapskate and docstrings--instance Binary a => Binary (D.Docstring a) where-  put (D.DocString opts lines) = do put opts ; put lines-  get = do opts <- get-           lines <- get-           return (D.DocString opts lines)--instance Binary CT.Options where-  put (CT.Options x1 x2 x3 x4) = do put x1 ; put x2 ; put x3 ; put x4-  get = do x1 <- get-           x2 <- get-           x3 <- get-           x4 <- get-           return (CT.Options x1 x2 x3 x4)--instance Binary D.DocTerm where-  put D.Unchecked = putWord8 0-  put (D.Checked t) = putWord8 1 >> put t-  put (D.Example t) = putWord8 2 >> put t-  put (D.Failing e) = putWord8 3 >> put e--  get = do i <- getWord8-           case i of-             0 -> return D.Unchecked-             1 -> fmap D.Checked get-             2 -> fmap D.Example get-             3 -> fmap D.Failing get-             _ -> error "Corrupted binary data for DocTerm"--instance Binary a => Binary (D.Block a) where-  put (D.Para lines) = do putWord8 0 ; put lines-  put (D.Header i lines) = do putWord8 1 ; put i ; put lines-  put (D.Blockquote bs) = do putWord8 2 ; put bs-  put (D.List b t xs) = do putWord8 3 ; put b ; put t ; put xs-  put (D.CodeBlock attr txt src) = do putWord8 4 ; put attr ; put txt ; put src-  put (D.HtmlBlock txt) = do putWord8 5 ; put txt-  put D.HRule = putWord8 6-  get = do i <- getWord8-           case i of-             0 -> fmap D.Para get-             1 -> liftM2 D.Header get get-             2 -> fmap D.Blockquote get-             3 -> liftM3 D.List get get get-             4 -> liftM3 D.CodeBlock get get get-             5 -> liftM D.HtmlBlock get-             6 -> return D.HRule-             _ -> error "Corrupted binary data for Block"--instance Binary a => Binary (D.Inline a) where-  put (D.Str txt) = do putWord8 0 ; put txt-  put D.Space = putWord8 1-  put D.SoftBreak = putWord8 2-  put D.LineBreak = putWord8 3-  put (D.Emph xs) = putWord8 4 >> put xs-  put (D.Strong xs) = putWord8 5 >> put xs-  put (D.Code xs tm) = putWord8 6 >> put xs >> put tm-  put (D.Link a b c) = putWord8 7 >> put a >> put b >> put c-  put (D.Image a b c) = putWord8 8 >> put a >> put b >> put c-  put (D.Entity a) = putWord8 9 >> put a-  put (D.RawHtml x) = putWord8 10 >> put x-  get = do i <- getWord8-           case i of-             0 -> liftM D.Str get-             1 -> return D.Space-             2 -> return D.SoftBreak-             3 -> return D.LineBreak-             4 -> liftM D.Emph get-             5 -> liftM D.Strong get-             6 -> liftM2 D.Code get get-             7 -> liftM3 D.Link get get get-             8 -> liftM3 D.Image get get get-             9 -> liftM D.Entity get-             10 -> liftM D.RawHtml get-             _ -> error "Corrupted binary data for Inline"--instance Binary CT.ListType where-  put (CT.Bullet c) = putWord8 0 >> put c-  put (CT.Numbered nw i) = putWord8 1 >> put nw >> put i-  get = do i <- getWord8-           case i of-             0 -> liftM CT.Bullet get-             1 -> liftM2 CT.Numbered get get-             _ -> error "Corrupted binary data for ListType"--instance Binary CT.CodeAttr where-  put (CT.CodeAttr a b) = put a >> put b-  get = liftM2 CT.CodeAttr get get--instance Binary CT.NumWrapper where-  put (CT.PeriodFollowing) = putWord8 0-  put (CT.ParenFollowing) = putWord8 1-  get = do i <- getWord8-           case i of-             0 -> return CT.PeriodFollowing-             1 -> return CT.ParenFollowing-             _ -> error "Corrupted binary data for NumWrapper"------- Generated by 'derive'--instance Binary SizeChange where-        put x-          = case x of-                Smaller -> putWord8 0-                Same -> putWord8 1-                Bigger -> putWord8 2-                Unknown -> putWord8 3-        get-          = do i <- getWord8-               case i of-                   0 -> return Smaller-                   1 -> return Same-                   2 -> return Bigger-                   3 -> return Unknown-                   _ -> error "Corrupted binary data for SizeChange"--instance Binary CGInfo where-        put (CGInfo x1 x2 x3 x4)-          = do put x1---                put x3 -- Already used SCG info for totality check-               put x2-               put x4-        get-          = do x1 <- get-               x2 <- get-               x3 <- get-               return (CGInfo x1 x2 [] x3)--instance Binary CaseType where-        put x = case x of-                     Updatable -> putWord8 0-                     Shared -> putWord8 1-        get = do i <- getWord8-                 case i of-                     0 -> return Updatable-                     1 -> return Shared-                     _ -> error "Corrupted binary data for CaseType"--instance Binary SC where-        put x-          = case x of-                Case x1 x2 x3 -> do putWord8 0-                                    put x1-                                    put x2-                                    put x3-                ProjCase x1 x2 -> do putWord8 1-                                     put x1-                                     put x2-                STerm x1 -> do putWord8 2-                               put x1-                UnmatchedCase x1 -> do putWord8 3-                                       put x1-                ImpossibleCase -> do putWord8 4-        get-          = do i <- getWord8-               case i of-                   0 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           return (Case x1 x2 x3)-                   1 -> do x1 <- get-                           x2 <- get-                           return (ProjCase x1 x2)-                   2 -> do x1 <- get-                           return (STerm x1)-                   3 -> do x1 <- get-                           return (UnmatchedCase x1)-                   4 -> return ImpossibleCase-                   _ -> error "Corrupted binary data for SC"---instance Binary CaseAlt where-        put x-          = {-# SCC "putCaseAlt" #-}-            case x of-                ConCase x1 x2 x3 x4 -> do putWord8 0-                                          put x1-                                          put x2-                                          put x3-                                          put x4-                ConstCase x1 x2 -> do putWord8 1-                                      put x1-                                      put x2-                DefaultCase x1 -> do putWord8 2-                                     put x1-                FnCase x1 x2 x3 -> do putWord8 3-                                      put x1-                                      put x2-                                      put x3-                SucCase x1 x2 -> do putWord8 4-                                    put x1-                                    put x2-        get-          = do i <- getWord8-               case i of-                   0 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           return (ConCase x1 x2 x3 x4)-                   1 -> do x1 <- get-                           x2 <- get-                           return (ConstCase x1 x2)-                   2 -> do x1 <- get-                           return (DefaultCase x1)-                   3 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           return (FnCase x1 x2 x3)-                   4 -> do x1 <- get-                           x2 <- get-                           return (SucCase x1 x2)-                   _ -> error "Corrupted binary data for CaseAlt"--instance Binary CaseDefs where-        put (CaseDefs x1 x2)-          = do put x1-               put x2-        get-          = do x1 <- get-               x2 <- get-               return (CaseDefs x1 x2)--instance Binary CaseInfo where-        put x@(CaseInfo x1 x2 x3) = do put x1-                                       put x2-                                       put x3-        get = do x1 <- get-                 x2 <- get-                 x3 <- get-                 return (CaseInfo x1 x2 x3)--instance Binary Def where-        put x-          = {-# SCC "putDef" #-}-            case x of-                Function x1 x2 -> do putWord8 0-                                     put x1-                                     put x2-                TyDecl x1 x2 -> do putWord8 1-                                   put x1-                                   put x2-                -- all primitives just get added at the start, don't write-                Operator x1 x2 x3 -> do return ()-                -- no need to add/load original patterns, because they're not-                -- used again after totality checking-                CaseOp x1 x2 x3 _ _ x4 -> do putWord8 3-                                             put x1-                                             put x2-                                             put x3-                                             put x4-        get-          = do i <- getWord8-               case i of-                   0 -> do x1 <- get-                           x2 <- get-                           return (Function x1 x2)-                   1 -> do x1 <- get-                           x2 <- get-                           return (TyDecl x1 x2)-                   -- Operator isn't written, don't read-                   3 -> do x1 <- get-                           x2 <- get-                           x3 <- get---                            x4 <- get-                           -- x3 <- get always []-                           x5 <- get-                           return (CaseOp x1 x2 x3 [] [] x5)-                   _ -> error "Corrupted binary data for Def"--instance Binary Accessibility where-        put x-          = case x of-                Public -> putWord8 0-                Frozen -> putWord8 1-                Private -> putWord8 2-                Hidden -> putWord8 3-        get-          = do i <- getWord8-               case i of-                   0 -> return Public-                   1 -> return Frozen-                   2 -> return Private-                   3 -> return Hidden-                   _ -> error "Corrupted binary data for Accessibility"--safeToEnum :: (Enum a, Bounded a, Integral int) => String -> int -> a-safeToEnum label x' = result-  where-    x = fromIntegral x'-    result-        |  x < fromEnum (minBound `asTypeOf` result)-        || x > fromEnum (maxBound `asTypeOf` result)-            = error $ label ++ ": corrupted binary representation in IBC"-        | otherwise = toEnum x--instance Binary PReason where-        put x-          = case x of-                Other x1 -> do putWord8 0-                               put x1-                Itself -> putWord8 1-                NotCovering -> putWord8 2-                NotPositive -> putWord8 3-                Mutual x1 -> do putWord8 4-                                put x1-                NotProductive -> putWord8 5-                BelieveMe -> putWord8 6-                UseUndef x1 -> do putWord8 7-                                  put x1-                ExternalIO -> putWord8 8-        get-          = do i <- getWord8-               case i of-                   0 -> do x1 <- get-                           return (Other x1)-                   1 -> return Itself-                   2 -> return NotCovering-                   3 -> return NotPositive-                   4 -> do x1 <- get-                           return (Mutual x1)-                   5 -> return NotProductive-                   6 -> return BelieveMe-                   7 -> do x1 <- get-                           return (UseUndef x1)-                   8 -> return ExternalIO-                   _ -> error "Corrupted binary data for PReason"--instance Binary Totality where-        put x-          = case x of-                Total x1 -> do putWord8 0-                               put x1-                Partial x1 -> do putWord8 1-                                 put x1-                Unchecked -> do putWord8 2-                Productive -> do putWord8 3-                Generated -> do putWord8 4-        get-          = do i <- getWord8-               case i of-                   0 -> do x1 <- get-                           return (Total x1)-                   1 -> do x1 <- get-                           return (Partial x1)-                   2 -> return Unchecked-                   3 -> return Productive-                   4 -> return Generated-                   _ -> error "Corrupted binary data for Totality"--instance Binary MetaInformation where-  put x-    = case x of-      EmptyMI   -> do putWord8 0-      DataMI x1 -> do putWord8 1-                      put x1-  get = do i <- getWord8-           case i of-             0 -> return EmptyMI-             1 -> do x1 <- get-                     return (DataMI x1)-             _ -> error "Corrupted binary data for MetaInformation"--instance Binary DataOpt where-  put x = case x of-    Codata -> putWord8 0-    DefaultEliminator -> putWord8 1-    DataErrRev -> putWord8 2-    DefaultCaseFun -> putWord8 3-  get = do i <- getWord8-           case i of-            0 -> return Codata-            1 -> return DefaultEliminator-            2 -> return DataErrRev-            3 -> return DefaultCaseFun-            _ -> error "Corrupted binary data for DataOpt"--instance Binary FnOpt where-        put x-          = case x of-                Inlinable -> putWord8 0-                TotalFn -> putWord8 1-                Dictionary -> putWord8 2-                AssertTotal -> putWord8 3-                Specialise x -> do putWord8 4-                                   put x-                AllGuarded -> putWord8 5-                PartialFn -> putWord8 6-                Implicit -> putWord8 7-                Reflection -> putWord8 8-                ErrorHandler -> putWord8 9-                ErrorReverse -> putWord8 10-                CoveringFn -> putWord8 11-                NoImplicit -> putWord8 12-                Constructor -> putWord8 13-                CExport x1 -> do putWord8 14-                                 put x1-                AutoHint -> putWord8 15-                PEGenerated -> putWord8 16-                StaticFn -> putWord8 17-                OverlappingDictionary -> putWord8 18-                ErrorReduce -> putWord8 20-        get-          = do i <- getWord8-               case i of-                   0 -> return Inlinable-                   1 -> return TotalFn-                   2 -> return Dictionary-                   3 -> return AssertTotal-                   4 -> do x <- get-                           return (Specialise x)-                   5 -> return AllGuarded-                   6 -> return PartialFn-                   7 -> return Implicit-                   8 -> return Reflection-                   9 -> return ErrorHandler-                   10 -> return ErrorReverse-                   11 -> return CoveringFn-                   12 -> return NoImplicit-                   13 -> return Constructor-                   14 -> do x1 <- get-                            return $ CExport x1-                   15 -> return AutoHint-                   16 -> return PEGenerated-                   17 -> return StaticFn-                   18 -> return OverlappingDictionary-                   20 -> return ErrorReduce-                   _ -> error "Corrupted binary data for FnOpt"--instance Binary Fixity where-        put x-          = case x of-                Infixl x1 -> do putWord8 0-                                put x1-                Infixr x1 -> do putWord8 1-                                put x1-                InfixN x1 -> do putWord8 2-                                put x1-                PrefixN x1 -> do putWord8 3-                                 put x1-        get-          = do i <- getWord8-               case i of-                   0 -> do x1 <- get-                           return (Infixl x1)-                   1 -> do x1 <- get-                           return (Infixr x1)-                   2 -> do x1 <- get-                           return (InfixN x1)-                   3 -> do x1 <- get-                           return (PrefixN x1)-                   _ -> error "Corrupted binary data for Fixity"---instance Binary FixDecl where-        put (Fix x1 x2)-          = do put x1-               put x2-        get-          = do x1 <- get-               x2 <- get-               return (Fix x1 x2)---instance Binary ArgOpt where-        put x-          = case x of-                HideDisplay -> putWord8 0-                InaccessibleArg -> putWord8 1-                AlwaysShow -> putWord8 2-                UnknownImp -> putWord8 3-        get-          = do i <- getWord8-               case i of-                   0 -> return HideDisplay-                   1 -> return InaccessibleArg-                   2 -> return AlwaysShow-                   3 -> return UnknownImp-                   _ -> error "Corrupted binary data for Static"--instance Binary Static where-        put x-          = case x of-                Static -> putWord8 0-                Dynamic -> putWord8 1-        get-          = do i <- getWord8-               case i of-                   0 -> return Static-                   1 -> return Dynamic-                   _ -> error "Corrupted binary data for Static"---instance Binary Plicity where-        put x-          = case x of-                Imp x1 x2 x3 x4 _ x5 ->-                             do putWord8 0-                                put x1-                                put x2-                                put x3-                                put x4-                                put x5-                Exp x1 x2 x3 x4 ->-                             do putWord8 1-                                put x1-                                put x2-                                put x3-                                put x4-                Constraint x1 x2 x3 ->-                                    do putWord8 2-                                       put x1-                                       put x2-                                       put x3-                TacImp x1 x2 x3 x4 ->-                                   do putWord8 3-                                      put x1-                                      put x2-                                      put x3-                                      put x4-        get-          = do i <- getWord8-               case i of-                   0 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           x5 <- get-                           return (Imp x1 x2 x3 x4 False x5)-                   1 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           return (Exp x1 x2 x3 x4)-                   2 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           return (Constraint x1 x2 x3)-                   3 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           return (TacImp x1 x2 x3 x4)-                   _ -> error "Corrupted binary data for Plicity"---instance (Binary t) => Binary (PDecl' t) where-        put x-          = case x of-                PFix x1 x2 x3 -> do putWord8 0-                                    put x1-                                    put x2-                                    put x3-                PTy x1 x2 x3 x4 x5 x6 x7 x8-                                   -> do putWord8 1-                                         put x1-                                         put x2-                                         put x3-                                         put x4-                                         put x5-                                         put x6-                                         put x7-                                         put x8-                PClauses x1 x2 x3 x4 -> do putWord8 2-                                           put x1-                                           put x2-                                           put x3-                                           put x4-                PData x1 x2 x3 x4 x5 x6 ->-                                     do putWord8 3-                                        put x1-                                        put x2-                                        put x3-                                        put x4-                                        put x5-                                        put x6-                PParams x1 x2 x3 -> do putWord8 4-                                       put x1-                                       put x2-                                       put x3-                PNamespace x1 x2 x3 -> do putWord8 5-                                          put x1-                                          put x2-                                          put x3-                PRecord x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 ->-                                             do putWord8 6-                                                put x1-                                                put x2-                                                put x3-                                                put x4-                                                put x5-                                                put x6-                                                put x7-                                                put x8-                                                put x9-                                                put x10-                                                put x11-                                                put x12-                PInterface x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12-                                         -> do putWord8 7-                                               put x1-                                               put x2-                                               put x3-                                               put x4-                                               put x5-                                               put x6-                                               put x7-                                               put x8-                                               put x9-                                               put x10-                                               put x11-                                               put x12-                PImplementation x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 ->-                  do putWord8 8-                     put x1-                     put x2-                     put x3-                     put x4-                     put x5-                     put x6-                     put x7-                     put x8-                     put x9-                     put x10-                     put x11-                     put x12-                     put x13-                     put x14-                     put x15-                PDSL x1 x2 -> do putWord8 9-                                 put x1-                                 put x2-                PCAF x1 x2 x3 -> do putWord8 10-                                    put x1-                                    put x2-                                    put x3-                PMutual x1 x2  -> do putWord8 11-                                     put x1-                                     put x2-                PPostulate x1 x2 x3 x4 x5 x6 x7 x8-                                   -> do putWord8 12-                                         put x1-                                         put x2-                                         put x3-                                         put x4-                                         put x5-                                         put x6-                                         put x7-                                         put x8-                PSyntax x1 x2 -> do putWord8 13-                                    put x1-                                    put x2-                PDirective x1 -> error "Cannot serialize PDirective"-                PProvider x1 x2 x3 x4 x5 x6 ->-                  do putWord8 15-                     put x1-                     put x2-                     put x3-                     put x4-                     put x5-                     put x6-                PTransform x1 x2 x3 x4 -> do putWord8 16-                                             put x1-                                             put x2-                                             put x3-                                             put x4-                PRunElabDecl x1 x2 x3 -> do putWord8 17-                                            put x1-                                            put x2-                                            put x3-                POpenInterfaces x1 x2 x3 -> do putWord8 18-                                               put x1-                                               put x2-                                               put x3-        get-          = do i <- getWord8-               case i of-                   0 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           return (PFix x1 x2 x3)-                   1 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           x5 <- get-                           x6 <- get-                           x7 <- get-                           x8 <- get-                           return (PTy x1 x2 x3 x4 x5 x6 x7 x8)-                   2 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           return (PClauses x1 x2 x3 x4)-                   3 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           x5 <- get-                           x6 <- get-                           return (PData x1 x2 x3 x4 x5 x6)-                   4 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           return (PParams x1 x2 x3)-                   5 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           return (PNamespace x1 x2 x3)-                   6 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           x5 <- get-                           x6 <- get-                           x7 <- get-                           x8 <- get-                           x9 <- get-                           x10 <- get-                           x11 <- get-                           x12 <- get-                           return (PRecord x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12)-                   7 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           x5 <- get-                           x6 <- get-                           x7 <- get-                           x8 <- get-                           x9 <- get-                           x10 <- get-                           x11 <- get-                           x12 <- get-                           return (PInterface x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12)-                   8 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           x5 <- get-                           x6 <- get-                           x7 <- get-                           x8 <- get-                           x9 <- get-                           x10 <- get-                           x11 <- get-                           x12 <- get-                           x13 <- get-                           x14 <- get-                           x15 <- get-                           return (PImplementation x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15)-                   9 -> do x1 <- get-                           x2 <- get-                           return (PDSL x1 x2)-                   10 -> do x1 <- get-                            x2 <- get-                            x3 <- get-                            return (PCAF x1 x2 x3)-                   11 -> do x1 <- get-                            x2 <- get-                            return (PMutual x1 x2)-                   12 -> do x1 <- get-                            x2 <- get-                            x3 <- get-                            x4 <- get-                            x5 <- get-                            x6 <- get-                            x7 <- get-                            x8 <- get-                            return (PPostulate x1 x2 x3 x4 x5 x6 x7 x8)-                   13 -> do x1 <- get-                            x2 <- get-                            return (PSyntax x1 x2)-                   14 -> do error "Cannot deserialize PDirective"-                   15 -> do x1 <- get-                            x2 <- get-                            x3 <- get-                            x4 <- get-                            x5 <- get-                            x6 <- get-                            return (PProvider x1 x2 x3 x4 x5 x6)-                   16 -> do x1 <- get-                            x2 <- get-                            x3 <- get-                            x4 <- get-                            return (PTransform x1 x2 x3 x4)-                   17 -> do x1 <- get-                            x2 <- get-                            x3 <- get-                            return (PRunElabDecl x1 x2 x3)-                   18 -> do x1 <- get-                            x2 <- get-                            x3 <- get-                            return (POpenInterfaces x1 x2 x3)-                   _ -> error "Corrupted binary data for PDecl'"--instance Binary t => Binary (ProvideWhat' t) where-  put (ProvTerm x1 x2) = do putWord8 0-                            put x1-                            put x2-  put (ProvPostulate x1) = do putWord8 1-                              put x1-  get = do y <- getWord8-           case y of-             0 -> do x1 <- get-                     x2 <- get-                     return (ProvTerm x1 x2)-             1 -> do x1 <- get-                     return (ProvPostulate x1)-             _ -> error "Corrupted binary data for ProvideWhat"--instance Binary Using where-        put (UImplicit x1 x2) = do putWord8 0; put x1; put x2-        put (UConstraint x1 x2) = do putWord8 1; put x1; put x2--        get = do i <- getWord8-                 case i of-                    0 -> do x1 <- get; x2 <- get; return (UImplicit x1 x2)-                    1 -> do x1 <- get; x2 <- get; return (UConstraint x1 x2)-                    _ -> error "Corrupted binary data for Using"--instance Binary SyntaxInfo where-        put (Syn x1 x2 x3 x4 _ _ x5 x6 x7 _ _ x8 _ _ _)-          = do put x1-               put x2-               put x3-               put x4-               put x5-               put x6-               put x7-               put x8-        get-          = do x1 <- get-               x2 <- get-               x3 <- get-               x4 <- get-               x5 <- get-               x6 <- get-               x7 <- get-               x8 <- get-               return (Syn x1 x2 x3 x4 [] id x5 x6 x7 Nothing 0 x8 0 True True)--instance (Binary t) => Binary (PClause' t) where-        put x-          = case x of-                PClause x1 x2 x3 x4 x5 x6 -> do putWord8 0-                                                put x1-                                                put x2-                                                put x3-                                                put x4-                                                put x5-                                                put x6-                PWith x1 x2 x3 x4 x5 x6 x7 -> do putWord8 1-                                                 put x1-                                                 put x2-                                                 put x3-                                                 put x4-                                                 put x5-                                                 put x6-                                                 put x7-                PClauseR x1 x2 x3 x4 -> do putWord8 2-                                           put x1-                                           put x2-                                           put x3-                                           put x4-                PWithR x1 x2 x3 x4 x5 -> do putWord8 3-                                            put x1-                                            put x2-                                            put x3-                                            put x4-                                            put x5-        get-          = do i <- getWord8-               case i of-                   0 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           x5 <- get-                           x6 <- get-                           return (PClause x1 x2 x3 x4 x5 x6)-                   1 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           x5 <- get-                           x6 <- get-                           x7 <- get-                           return (PWith x1 x2 x3 x4 x5 x6 x7)-                   2 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           return (PClauseR x1 x2 x3 x4)-                   3 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           x5 <- get-                           return (PWithR x1 x2 x3 x4 x5)-                   _ -> error "Corrupted binary data for PClause'"--instance (Binary t) => Binary (PData' t) where-        put x-          = case x of-                PDatadecl x1 x2 x3 x4 -> do putWord8 0-                                            put x1-                                            put x2-                                            put x3-                                            put x4-                PLaterdecl x1 x2 x3 -> do putWord8 1-                                          put x1-                                          put x2-                                          put x3-        get-          = do i <- getWord8-               case i of-                   0 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           return (PDatadecl x1 x2 x3 x4)-                   1 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           return (PLaterdecl x1 x2 x3)-                   _ -> error "Corrupted binary data for PData'"--instance Binary PunInfo where-        put x-          = case x of-              TypeOrTerm -> putWord8 0-              IsType     -> putWord8 1-              IsTerm     -> putWord8 2-        get-          = do i <- getWord8-               case i of-                 0 -> return TypeOrTerm-                 1 -> return IsType-                 2 -> return IsTerm-                 _ -> error "Corrupted binary data for PunInfo"--instance Binary PTerm where-        put x-          = case x of-                PQuote x1 -> do putWord8 0-                                put x1-                PRef x1 x2 x3 -> do putWord8 1-                                    put x1-                                    put x2-                                    put x3-                PInferRef x1 x2 x3 -> do putWord8 2-                                         put x1-                                         put x2-                                         put x3-                PPatvar x1 x2 -> do putWord8 3-                                    put x1-                                    put x2-                PLam x1 x2 x3 x4 x5 -> do putWord8 4-                                          put x1-                                          put x2-                                          put x3-                                          put x4-                                          put x5-                PPi x1 x2 x3 x4 x5 -> do putWord8 5-                                         put x1-                                         put x2-                                         put x3-                                         put x4-                                         put x5-                PLet x1 x2 x3 x4 x5 x6 -> do putWord8 6-                                             put x1-                                             put x2-                                             put x3-                                             put x4-                                             put x5-                                             put x6-                PTyped x1 x2 -> do putWord8 7-                                   put x1-                                   put x2-                PAppImpl x1 x2 -> error "PAppImpl in final term"-                PApp x1 x2 x3 -> do putWord8 8-                                    put x1-                                    put x2-                                    put x3-                PAppBind x1 x2 x3 -> do putWord8 9-                                        put x1-                                        put x2-                                        put x3-                PMatchApp x1 x2 -> do putWord8 10-                                      put x1-                                      put x2-                PCase x1 x2 x3 -> do putWord8 11-                                     put x1-                                     put x2-                                     put x3-                PTrue x1 x2 -> do putWord8 12-                                  put x1-                                  put x2-                PResolveTC x1 -> do putWord8 15-                                    put x1-                PRewrite x1 x2 x3 x4 x5 -> do putWord8 17-                                              put x1-                                              put x2-                                              put x3-                                              put x4-                                              put x5-                PPair x1 x2 x3 x4 x5 -> do putWord8 18-                                           put x1-                                           put x2-                                           put x3-                                           put x4-                                           put x5-                PDPair x1 x2 x3 x4 x5 x6 -> do putWord8 19-                                               put x1-                                               put x2-                                               put x3-                                               put x4-                                               put x5-                                               put x6-                PAlternative x1 x2 x3 -> do putWord8 20-                                            put x1-                                            put x2-                                            put x3-                PHidden x1 -> do putWord8 21-                                 put x1-                PType x1 -> do putWord8 22-                               put x1-                PGoal x1 x2 x3 x4 -> do putWord8 23-                                        put x1-                                        put x2-                                        put x3-                                        put x4-                PConstant x1 x2 -> do putWord8 24-                                      put x1-                                      put x2-                Placeholder -> putWord8 25-                PDoBlock x1 -> do putWord8 26-                                  put x1-                PIdiom x1 x2 -> do putWord8 27-                                   put x1-                                   put x2-                PMetavar x1 x2 -> do putWord8 29-                                     put x1-                                     put x2-                PProof x1 -> do putWord8 30-                                put x1-                PTactics x1 -> do putWord8 31-                                  put x1-                PImpossible -> putWord8 33-                PCoerced x1 -> do putWord8 34-                                  put x1-                PUnifyLog x1 -> do putWord8 35-                                   put x1-                PNoImplicits x1 -> do putWord8 36-                                      put x1-                PDisamb x1 x2 -> do putWord8 37-                                    put x1-                                    put x2-                PUniverse x1 x2 -> do putWord8 38-                                      put x1-                                      put x2-                PRunElab x1 x2 x3 -> do putWord8 39-                                        put x1-                                        put x2-                                        put x3-                PAs x1 x2 x3 -> do putWord8 40-                                   put x1-                                   put x2-                                   put x3-                PElabError x1 -> do putWord8 41-                                    put x1-                PQuasiquote x1 x2 -> do putWord8 42-                                        put x1-                                        put x2-                PUnquote x1 -> do putWord8 43-                                  put x1-                PQuoteName x1 x2 x3 -> do putWord8 44-                                          put x1-                                          put x2-                                          put x3-                PIfThenElse x1 x2 x3 x4 -> do putWord8 45-                                              put x1-                                              put x2-                                              put x3-                                              put x4-                PConstSugar x1 x2 -> do putWord8 46-                                        put x1-                                        put x2-                PWithApp x1 x2 x3 -> do putWord8 47-                                        put x1-                                        put x2-                                        put x3--        get-          = do i <- getWord8-               case i of-                   0 -> do x1 <- get-                           return (PQuote x1)-                   1 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           return (PRef x1 x2 x3)-                   2 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           return (PInferRef x1 x2 x3)-                   3 -> do x1 <- get-                           x2 <- get-                           return (PPatvar x1 x2)-                   4 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           x5 <- get-                           return (PLam x1 x2 x3 x4 x5)-                   5 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           x5 <- get-                           return (PPi x1 x2 x3 x4 x5)-                   6 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           x5 <- get-                           x6 <- get-                           return (PLet x1 x2 x3 x4 x5 x6)-                   7 -> do x1 <- get-                           x2 <- get-                           return (PTyped x1 x2)-                   8 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           return (PApp x1 x2 x3)-                   9 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           return (PAppBind x1 x2 x3)-                   10 -> do x1 <- get-                            x2 <- get-                            return (PMatchApp x1 x2)-                   11 -> do x1 <- get-                            x2 <- get-                            x3 <- get-                            return (PCase x1 x2 x3)-                   12 -> do x1 <- get-                            x2 <- get-                            return (PTrue x1 x2)-                   15 -> do x1 <- get-                            return (PResolveTC x1)-                   17 -> do x1 <- get-                            x2 <- get-                            x3 <- get-                            x4 <- get-                            x5 <- get-                            return (PRewrite x1 x2 x3 x4 x5)-                   18 -> do x1 <- get-                            x2 <- get-                            x3 <- get-                            x4 <- get-                            x5 <- get-                            return (PPair x1 x2 x3 x4 x5)-                   19 -> do x1 <- get-                            x2 <- get-                            x3 <- get-                            x4 <- get-                            x5 <- get-                            x6 <- get-                            return (PDPair x1 x2 x3 x4 x5 x6)-                   20 -> do x1 <- get-                            x2 <- get-                            x3 <- get-                            return (PAlternative x1 x2 x3)-                   21 -> do x1 <- get-                            return (PHidden x1)-                   22 -> do x1 <- get-                            return (PType x1)-                   23 -> do x1 <- get-                            x2 <- get-                            x3 <- get-                            x4 <- get-                            return (PGoal x1 x2 x3 x4)-                   24 -> do x1 <- get-                            x2 <- get-                            return (PConstant x1 x2)-                   25 -> return Placeholder-                   26 -> do x1 <- get-                            return (PDoBlock x1)-                   27 -> do x1 <- get-                            x2 <- get-                            return (PIdiom x1 x2)-                   29 -> do x1 <- get-                            x2 <- get-                            return (PMetavar x1 x2)-                   30 -> do x1 <- get-                            return (PProof x1)-                   31 -> do x1 <- get-                            return (PTactics x1)-                   33 -> return PImpossible-                   34 -> do x1 <- get-                            return (PCoerced x1)-                   35 -> do x1 <- get-                            return (PUnifyLog x1)-                   36 -> do x1 <- get-                            return (PNoImplicits x1)-                   37 -> do x1 <- get-                            x2 <- get-                            return (PDisamb x1 x2)-                   38 -> do x1 <- get-                            x2 <- get-                            return (PUniverse x1 x2)-                   39 -> do x1 <- get-                            x2 <- get-                            x3 <- get-                            return (PRunElab x1 x2 x3)-                   40 -> do x1 <- get-                            x2 <- get-                            x3 <- get-                            return (PAs x1 x2 x3)-                   41 -> do x1 <- get-                            return (PElabError x1)-                   42 -> do x1 <- get-                            x2 <- get-                            return (PQuasiquote x1 x2)-                   43 -> do x1 <- get-                            return (PUnquote x1)-                   44 -> do x1 <- get-                            x2 <- get-                            x3 <- get-                            return (PQuoteName x1 x2 x3)-                   45 -> do x1 <- get-                            x2 <- get-                            x3 <- get-                            x4 <- get-                            return (PIfThenElse x1 x2 x3 x4)-                   46 -> do x1 <- get-                            x2 <- get-                            return (PConstSugar x1 x2)-                   47 -> do x1 <- get-                            x2 <- get-                            x3 <- get-                            return (PWithApp x1 x2 x3)-                   _ -> error "Corrupted binary data for PTerm"--instance Binary PAltType where-        put x-          = case x of-                ExactlyOne x1 -> do putWord8 0-                                    put x1-                FirstSuccess -> putWord8 1-                TryImplicit -> putWord8 2-        get-          = do i <- getWord8-               case i of-                   0 -> do x1 <- get-                           return (ExactlyOne x1)-                   1 -> return FirstSuccess-                   2 -> return TryImplicit-                   _ -> error "Corrupted binary data for PAltType"---instance (Binary t) => Binary (PTactic' t) where-        put x-          = case x of-                Intro x1 -> do putWord8 0-                               put x1-                Focus x1 -> do putWord8 1-                               put x1-                Refine x1 x2 -> do putWord8 2-                                   put x1-                                   put x2-                Rewrite x1 -> do putWord8 3-                                 put x1-                LetTac x1 x2 -> do putWord8 4-                                   put x1-                                   put x2-                Exact x1 -> do putWord8 5-                               put x1-                Compute -> putWord8 6-                Trivial -> putWord8 7-                Solve -> putWord8 8-                Attack -> putWord8 9-                ProofState -> putWord8 10-                ProofTerm -> putWord8 11-                Undo -> putWord8 12-                Try x1 x2 -> do putWord8 13-                                put x1-                                put x2-                TSeq x1 x2 -> do putWord8 14-                                 put x1-                                 put x2-                Qed -> putWord8 15-                ApplyTactic x1 -> do putWord8 16-                                     put x1-                Reflect x1 -> do putWord8 17-                                 put x1-                Fill x1 -> do putWord8 18-                              put x1-                Induction x1 -> do putWord8 19-                                   put x1-                ByReflection x1 -> do putWord8 20-                                      put x1-                ProofSearch x1 x2 x3 x4 x5 x6 -> do putWord8 21-                                                    put x1-                                                    put x2-                                                    put x3-                                                    put x4-                                                    put x5-                                                    put x6-                DoUnify -> putWord8 22-                CaseTac x1 -> do putWord8 23-                                 put x1-                SourceFC -> putWord8 24-                Intros -> putWord8 25-                Equiv x1 -> do putWord8 26-                               put x1-                Claim x1 x2 -> do putWord8 27-                                  put x1-                                  put x2-                Unfocus -> putWord8 28-                MatchRefine x1 -> do putWord8 29-                                     put x1-                LetTacTy x1 x2 x3 -> do putWord8 30-                                        put x1-                                        put x2-                                        put x3-                TCImplementation -> putWord8 31-                GoalType x1 x2 -> do putWord8 32-                                     put x1-                                     put x2-                TCheck x1 -> do putWord8 33-                                put x1-                TEval x1 -> do putWord8 34-                               put x1-                TDocStr x1 -> do putWord8 35-                                 put x1-                TSearch x1 -> do putWord8 36-                                 put x1-                Skip -> putWord8 37-                TFail x1 -> do putWord8 38-                               put x1-                Abandon -> putWord8 39-        get-          = do i <- getWord8-               case i of-                   0 -> do x1 <- get-                           return (Intro x1)-                   1 -> do x1 <- get-                           return (Focus x1)-                   2 -> do x1 <- get-                           x2 <- get-                           return (Refine x1 x2)-                   3 -> do x1 <- get-                           return (Rewrite x1)-                   4 -> do x1 <- get-                           x2 <- get-                           return (LetTac x1 x2)-                   5 -> do x1 <- get-                           return (Exact x1)-                   6 -> return Compute-                   7 -> return Trivial-                   8 -> return Solve-                   9 -> return Attack-                   10 -> return ProofState-                   11 -> return ProofTerm-                   12 -> return Undo-                   13 -> do x1 <- get-                            x2 <- get-                            return (Try x1 x2)-                   14 -> do x1 <- get-                            x2 <- get-                            return (TSeq x1 x2)-                   15 -> return Qed-                   16 -> do x1 <- get-                            return (ApplyTactic x1)-                   17 -> do x1 <- get-                            return (Reflect x1)-                   18 -> do x1 <- get-                            return (Fill x1)-                   19 -> do x1 <- get-                            return (Induction x1)-                   20 -> do x1 <- get-                            return (ByReflection x1)-                   21 -> do x1 <- get-                            x2 <- get-                            x3 <- get-                            x4 <- get-                            x5 <- get-                            x6 <- get-                            return (ProofSearch x1 x2 x3 x4 x5 x6)-                   22 -> return DoUnify-                   23 -> do x1 <- get-                            return (CaseTac x1)-                   24 -> return SourceFC-                   25 -> return Intros-                   26 -> do x1 <- get-                            return (Equiv x1)-                   27 -> do x1 <- get-                            x2 <- get-                            return (Claim x1 x2)-                   28 -> return Unfocus-                   29 -> do x1 <- get-                            return (MatchRefine x1)-                   30 -> do x1 <- get-                            x2 <- get-                            x3 <- get-                            return (LetTacTy x1 x2 x3)-                   31 -> return TCImplementation-                   32 -> do x1 <- get-                            x2 <- get-                            return (GoalType x1 x2)-                   33 -> do x1 <- get-                            return (TCheck x1)-                   34 -> do x1 <- get-                            return (TEval x1)-                   35 -> do x1 <- get-                            return (TDocStr x1)-                   36 -> do x1 <- get-                            return (TSearch x1)-                   37 -> return Skip-                   38 -> do x1 <- get-                            return (TFail x1)-                   39 -> return Abandon-                   _ -> error "Corrupted binary data for PTactic'"---instance (Binary t) => Binary (PDo' t) where-        put x-          = case x of-                DoExp x1 x2 -> do putWord8 0-                                  put x1-                                  put x2-                DoBind x1 x2 x3 x4 -> do putWord8 1-                                         put x1-                                         put x2-                                         put x3-                                         put x4-                DoBindP x1 x2 x3 x4 -> do putWord8 2-                                          put x1-                                          put x2-                                          put x3-                                          put x4-                DoLet x1 x2 x3 x4 x5 -> do putWord8 3-                                           put x1-                                           put x2-                                           put x3-                                           put x4-                                           put x5-                DoLetP x1 x2 x3 -> do putWord8 4-                                      put x1-                                      put x2-                                      put x3-                DoRewrite x1 x2 -> do putWord8 5-                                      put x1-                                      put x2-        get-          = do i <- getWord8-               case i of-                   0 -> do x1 <- get-                           x2 <- get-                           return (DoExp x1 x2)-                   1 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           return (DoBind x1 x2 x3 x4)-                   2 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           return (DoBindP x1 x2 x3 x4)-                   3 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           x5 <- get-                           return (DoLet x1 x2 x3 x4 x5)-                   4 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           return (DoLetP x1 x2 x3)-                   5 -> do-                           x1 <- get-                           x2 <- get-                           return (DoRewrite x1 x2)-                   _ -> error "Corrupted binary data for PDo'"---instance (Binary t) => Binary (PArg' t) where-        put x-          = case x of-                PImp x1 x2 x3 x4 x5 ->-                                    do putWord8 0-                                       put x1-                                       put x2-                                       put x3-                                       put x4-                                       put x5-                PExp x1 x2 x3 x4 ->-                                 do putWord8 1-                                    put x1-                                    put x2-                                    put x3-                                    put x4-                PConstraint x1 x2 x3 x4 ->-                                        do putWord8 2-                                           put x1-                                           put x2-                                           put x3-                                           put x4-                PTacImplicit x1 x2 x3 x4 x5 ->-                                               do putWord8 3-                                                  put x1-                                                  put x2-                                                  put x3-                                                  put x4-                                                  put x5-        get-          = do i <- getWord8-               case i of-                   0 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           x5 <- get-                           return (PImp x1 x2 x3 x4 x5)-                   1 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           return (PExp x1 x2 x3 x4)-                   2 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           return (PConstraint x1 x2 x3 x4)-                   3 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           x4 <- get-                           x5 <- get-                           return (PTacImplicit x1 x2 x3 x4 x5)-                   _ -> error "Corrupted binary data for PArg'"---instance Binary InterfaceInfo where-        put (CI x1 x2 x3 x4 x5 x6 x7 _ x8)-          = do put x1-               put x2-               put x3-               put x4-               put x5-               put x6-               put x7-               put x8-        get-          = do x1 <- get-               x2 <- get-               x3 <- get-               x4 <- get-               x5 <- get-               x6 <- get-               x7 <- get-               x8 <- get-               return (CI x1 x2 x3 x4 x5 x6 x7 [] x8)--instance Binary RecordInfo where-        put (RI x1 x2 x3)-          = do put x1-               put x2-               put x3-        get-          = do x1 <- get-               x2 <- get-               x3 <- get-               return (RI x1 x2 x3)--instance Binary OptInfo where-        put (Optimise x1 x2 x3)-          = do put x1-               put x2-               put x3-        get-          = do x1 <- get-               x2 <- get-               x3 <- get-               return (Optimise x1 x2 x3)--instance Binary FnInfo where-        put (FnInfo x1)-          = put x1-        get-          = do x1 <- get-               return (FnInfo x1)--instance Binary TypeInfo where-        put (TI x1 x2 x3 x4 x5 x6) = do put x1-                                        put x2-                                        put x3-                                        put x4-                                        put x5-                                        put x6-        get = do x1 <- get-                 x2 <- get-                 x3 <- get-                 x4 <- get-                 x5 <- get-                 x6 <- get-                 return (TI x1 x2 x3 x4 x5 x6)--instance Binary SynContext where-        put x-          = case x of-                PatternSyntax -> putWord8 0-                TermSyntax -> putWord8 1-                AnySyntax -> putWord8 2-        get-          = do i <- getWord8-               case i of-                   0 -> return PatternSyntax-                   1 -> return TermSyntax-                   2 -> return AnySyntax-                   _ -> error "Corrupted binary data for SynContext"---instance Binary Syntax where-        put (Rule x1 x2 x3)-          = do putWord8 0-               put x1-               put x2-               put x3-        put (DeclRule x1 x2)-          = do putWord8 1-               put x1-               put x2-        get-          = do i <- getWord8-               case i of-                   0 -> do x1 <- get-                           x2 <- get-                           x3 <- get-                           return (Rule x1 x2 x3)-                   1 -> do x1 <- get-                           x2 <- get-                           return (DeclRule x1 x2)-                   _ -> error "Corrupted binary data for Syntax"--instance (Binary t) => Binary (DSL' t) where-        put (DSL x1 x2 x3 x4 x5 x6 x7 x8 x9)-          = do put x1-               put x2-               put x3-               put x4-               put x5-               put x6-               put x7-               put x8-               put x9-        get-          = do x1 <- get-               x2 <- get-               x3 <- get-               x4 <- get-               x5 <- get-               x6 <- get-               x7 <- get-               x8 <- get-               x9 <- get-               return (DSL x1 x2 x3 x4 x5 x6 x7 x8 x9)--instance Binary SSymbol where-        put x-          = case x of-                Keyword x1 -> do putWord8 0-                                 put x1-                Symbol x1 -> do putWord8 1-                                put x1-                Expr x1 -> do putWord8 2-                              put x1-                SimpleExpr x1 -> do putWord8 3-                                    put x1-                Binding x1 -> do putWord8 4-                                 put x1-        get-          = do i <- getWord8-               case i of-                   0 -> do x1 <- get-                           return (Keyword x1)-                   1 -> do x1 <- get-                           return (Symbol x1)-                   2 -> do x1 <- get-                           return (Expr x1)-                   3 -> do x1 <- get-                           return (SimpleExpr x1)-                   4 -> do x1 <- get-                           return (Binding x1)-                   _ -> error "Corrupted binary data for SSymbol"--instance Binary Codegen where-        put x-          = case x of-                Via ir str -> do putWord8 0-                                 put ir-                                 put str-                Bytecode -> putWord8 1-        get-          = do i <- getWord8-               case i of-                  0 -> do x1 <- get-                          x2 <- get-                          return (Via x1 x2)-                  1 -> return Bytecode-                  _ -> error  "Corrupted binary data for Codegen"--instance Binary IRFormat where-    put x = case x of-                IBCFormat -> putWord8 0-                JSONFormat -> putWord8 1-    get = do i <- getWord8-             case i of-                0 -> return IBCFormat-                1 -> return JSONFormat-                _ -> error  "Corrupted binary data for IRFormat"++License     : BSD3+Maintainer  : The Idris Community.+-}++{-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-}+{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}+{-# OPTIONS_GHC -fwarn-unused-imports #-}++module Idris.IBC (loadIBC, loadPkgIndex,+                  writeIBC, writePkgIndex,+                  hasValidIBCVersion, IBCPhase(..)) where++import Idris.AbsSyntax+import Idris.Core.CaseTree+import Idris.Core.Evaluate+import Idris.Core.TT+import Idris.DeepSeq ()+import Idris.Docstrings (Docstring)+import qualified Idris.Docstrings as D+import Idris.Error+import Idris.Imports+import Idris.Options+import Idris.Output+import IRTS.System (getIdrisLibDir)++import qualified Cheapskate.Types as CT+import Codec.Archive.Zip+import Control.DeepSeq+import Control.Monad+import Data.Binary+import Data.ByteString.Lazy as B hiding (elem, length, map)+import Data.List as L+import Data.Maybe (catMaybes)+import qualified Data.Set as S+import System.Directory+import System.FilePath++ibcVersion :: Word16+ibcVersion = 164++-- | When IBC is being loaded - we'll load different things (and omit+-- different structures/definitions) depending on which phase we're in.+data IBCPhase = IBC_Building  -- ^ when building the module tree+              | IBC_REPL Bool -- ^ when loading modules for the REPL Bool = True for top level module+  deriving (Show, Eq)++data IBCFile = IBCFile {+    ver                        :: Word16+  , sourcefile                 :: FilePath+  , ibc_imports                :: ![(Bool, FilePath)]+  , ibc_importdirs             :: ![FilePath]+  , ibc_sourcedirs             :: ![FilePath]+  , ibc_implicits              :: ![(Name, [PArg])]+  , ibc_fixes                  :: ![FixDecl]+  , ibc_statics                :: ![(Name, [Bool])]+  , ibc_interfaces             :: ![(Name, InterfaceInfo)]+  , ibc_records                :: ![(Name, RecordInfo)]+  , ibc_implementations        :: ![(Bool, Bool, Name, Name)]+  , ibc_dsls                   :: ![(Name, DSL)]+  , ibc_datatypes              :: ![(Name, TypeInfo)]+  , ibc_optimise               :: ![(Name, OptInfo)]+  , ibc_syntax                 :: ![Syntax]+  , ibc_keywords               :: ![String]+  , ibc_objs                   :: ![(Codegen, FilePath)]+  , ibc_libs                   :: ![(Codegen, String)]+  , ibc_cgflags                :: ![(Codegen, String)]+  , ibc_dynamic_libs           :: ![String]+  , ibc_hdrs                   :: ![(Codegen, String)]+  , ibc_totcheckfail           :: ![(FC, String)]+  , ibc_flags                  :: ![(Name, [FnOpt])]+  , ibc_fninfo                 :: ![(Name, FnInfo)]+  , ibc_cg                     :: ![(Name, CGInfo)]+  , ibc_docstrings             :: ![(Name, (Docstring D.DocTerm, [(Name, Docstring D.DocTerm)]))]+  , ibc_moduledocs             :: ![(Name, Docstring D.DocTerm)]+  , ibc_transforms             :: ![(Name, (Term, Term))]+  , ibc_errRev                 :: ![(Term, Term)]+  , ibc_errReduce              :: ![Name]+  , ibc_coercions              :: ![Name]+  , ibc_lineapps               :: ![(FilePath, Int, PTerm)]+  , ibc_namehints              :: ![(Name, Name)]+  , ibc_metainformation        :: ![(Name, MetaInformation)]+  , ibc_errorhandlers          :: ![Name]+  , ibc_function_errorhandlers :: ![(Name, Name, Name)] -- fn, arg, handler+  , ibc_metavars               :: ![(Name, (Maybe Name, Int, [Name], Bool, Bool))]+  , ibc_patdefs                :: ![(Name, ([([(Name, Term)], Term, Term)], [PTerm]))]+  , ibc_postulates             :: ![Name]+  , ibc_externs                :: ![(Name, Int)]+  , ibc_parsedSpan             :: !(Maybe FC)+  , ibc_usage                  :: ![(Name, Int)]+  , ibc_exports                :: ![Name]+  , ibc_autohints              :: ![(Name, Name)]+  , ibc_deprecated             :: ![(Name, String)]+  , ibc_defs                   :: ![(Name, Def)]+  , ibc_total                  :: ![(Name, Totality)]+  , ibc_injective              :: ![(Name, Injectivity)]+  , ibc_access                 :: ![(Name, Accessibility)]+  , ibc_fragile                :: ![(Name, String)]+  , ibc_constraints            :: ![(FC, UConstraint)]+  , ibc_langexts               :: ![LanguageExt]+  }+  deriving Show+{-!+deriving instance Binary IBCFile+!-}++initIBC :: IBCFile+initIBC = IBCFile ibcVersion "" [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] Nothing [] [] [] [] [] [] [] [] [] [] []++hasValidIBCVersion :: FilePath -> Idris Bool+hasValidIBCVersion fp = do+  archiveFile <- runIO $ B.readFile fp+  case toArchiveOrFail archiveFile of+    Left _ -> return False+    Right archive -> do ver <- getEntry 0 "ver" archive+                        return (ver == ibcVersion)+++loadIBC :: Bool -- ^ True = reexport, False = make everything private+        -> IBCPhase+        -> FilePath -> Idris ()+loadIBC reexport phase fp+           = do logIBC 1 $ "loadIBC (reexport, phase, fp)" ++ show (reexport, phase, fp)+                imps <- getImported+                logIBC 3 $ "loadIBC imps" ++ show imps+                case lookup fp imps of+                    Nothing -> load True+                    Just p -> if (not p && reexport) then load False else return ()+        where+            load fullLoad = do+                    logIBC 1 $ "Loading ibc " ++ fp ++ " " ++ show reexport+                    archiveFile <- runIO $ B.readFile fp+                    case toArchiveOrFail archiveFile of+                        Left _ -> do+                            ifail $ fp  ++ " isn't loadable, it may have an old ibc format.\n"+                                        ++ "Please clean and rebuild it."+                        Right archive -> do+                            if fullLoad+                                then process reexport phase archive fp+                                else unhide phase fp archive+                            addImported reexport fp++-- | Load an entire package from its index file+loadPkgIndex :: PkgName -> Idris ()+loadPkgIndex pkg = do ddir <- runIO getIdrisLibDir+                      addImportDir (ddir </> unPkgName pkg)+                      fp <- findPkgIndex pkg+                      loadIBC True IBC_Building fp+++makeEntry :: (Binary b) => String -> [b] -> Maybe Entry+makeEntry name val = if L.null val+                        then Nothing+                        else Just $ toEntry name 0 (encode val)+++entries :: IBCFile -> [Entry]+entries i = catMaybes [Just $ toEntry "ver" 0 (encode $ ver i),+                       makeEntry "sourcefile"  (sourcefile i),+                       makeEntry "ibc_imports"  (ibc_imports i),+                       makeEntry "ibc_importdirs"  (ibc_importdirs i),+                       makeEntry "ibc_sourcedirs"  (ibc_sourcedirs i),+                       makeEntry "ibc_implicits"  (ibc_implicits i),+                       makeEntry "ibc_fixes"  (ibc_fixes i),+                       makeEntry "ibc_statics"  (ibc_statics i),+                       makeEntry "ibc_interfaces"  (ibc_interfaces i),+                       makeEntry "ibc_records"  (ibc_records i),+                       makeEntry "ibc_implementations"  (ibc_implementations i),+                       makeEntry "ibc_dsls"  (ibc_dsls i),+                       makeEntry "ibc_datatypes"  (ibc_datatypes i),+                       makeEntry "ibc_optimise"  (ibc_optimise i),+                       makeEntry "ibc_syntax"  (ibc_syntax i),+                       makeEntry "ibc_keywords"  (ibc_keywords i),+                       makeEntry "ibc_objs"  (ibc_objs i),+                       makeEntry "ibc_libs"  (ibc_libs i),+                       makeEntry "ibc_cgflags"  (ibc_cgflags i),+                       makeEntry "ibc_dynamic_libs"  (ibc_dynamic_libs i),+                       makeEntry "ibc_hdrs"  (ibc_hdrs i),+                       makeEntry "ibc_totcheckfail"  (ibc_totcheckfail i),+                       makeEntry "ibc_flags"  (ibc_flags i),+                       makeEntry "ibc_fninfo"  (ibc_fninfo i),+                       makeEntry "ibc_cg"  (ibc_cg i),+                       makeEntry "ibc_docstrings"  (ibc_docstrings i),+                       makeEntry "ibc_moduledocs"  (ibc_moduledocs i),+                       makeEntry "ibc_transforms"  (ibc_transforms i),+                       makeEntry "ibc_errRev"  (ibc_errRev i),+                       makeEntry "ibc_errReduce"  (ibc_errReduce i),+                       makeEntry "ibc_coercions"  (ibc_coercions i),+                       makeEntry "ibc_lineapps"  (ibc_lineapps i),+                       makeEntry "ibc_namehints"  (ibc_namehints i),+                       makeEntry "ibc_metainformation"  (ibc_metainformation i),+                       makeEntry "ibc_errorhandlers"  (ibc_errorhandlers i),+                       makeEntry "ibc_function_errorhandlers"  (ibc_function_errorhandlers i),+                       makeEntry "ibc_metavars"  (ibc_metavars i),+                       makeEntry "ibc_patdefs"  (ibc_patdefs i),+                       makeEntry "ibc_postulates"  (ibc_postulates i),+                       makeEntry "ibc_externs"  (ibc_externs i),+                       toEntry "ibc_parsedSpan" 0 . encode <$> ibc_parsedSpan i,+                       makeEntry "ibc_usage"  (ibc_usage i),+                       makeEntry "ibc_exports"  (ibc_exports i),+                       makeEntry "ibc_autohints"  (ibc_autohints i),+                       makeEntry "ibc_deprecated"  (ibc_deprecated i),+                       makeEntry "ibc_defs"  (ibc_defs i),+                       makeEntry "ibc_total"  (ibc_total i),+                       makeEntry "ibc_injective"  (ibc_injective i),+                       makeEntry "ibc_access"  (ibc_access i),+                       makeEntry "ibc_fragile" (ibc_fragile i),+                       makeEntry "ibc_langexts" (ibc_langexts i)]+-- TODO: Put this back in shortly after minimising/pruning constraints+--                        makeEntry "ibc_constraints" (ibc_constraints i)]++writeArchive :: FilePath -> IBCFile -> Idris ()+writeArchive fp i = do let a = L.foldl (\x y -> addEntryToArchive y x) emptyArchive (entries i)+                       runIO $ B.writeFile fp (fromArchive a)++writeIBC :: FilePath -> FilePath -> Idris ()+writeIBC src f+    = do+         logIBC  2 $ "Writing IBC for: " ++ show f+         iReport 2 $ "Writing IBC for: " ++ show f+         i <- getIState+         resetNameIdx+         ibcf <- mkIBC (ibc_write i) (initIBC { sourcefile = src,+                                                ibc_langexts = idris_language_extensions i })+         idrisCatch (do runIO $ createDirectoryIfMissing True (dropFileName f)+                        writeArchive f ibcf+                        logIBC 2 "Written")+            (\c -> do logIBC 2 $ "Failed " ++ pshow i c)+         return ()++-- | Write a package index containing all the imports in the current+-- IState Used for ':search' of an entire package, to ensure+-- everything is loaded.+writePkgIndex :: FilePath -> Idris ()+writePkgIndex f+    = do i <- getIState+         let imps = map (\ (x, y) -> (True, x)) $ idris_imported i+         logIBC 2 $ "Writing package index " ++ show f ++ " including\n" +++                show (map snd imps)+         resetNameIdx+         let ibcf = initIBC { ibc_imports = imps,+                              ibc_langexts = idris_language_extensions i }+         idrisCatch (do runIO $ createDirectoryIfMissing True (dropFileName f)+                        writeArchive f ibcf+                        logIBC 2 "Written")+            (\c -> do logIBC 2 $ "Failed " ++ pshow i c)+         return ()++mkIBC :: [IBCWrite] -> IBCFile -> Idris IBCFile+mkIBC [] f = return f+mkIBC (i:is) f = do ist <- getIState+                    logIBC 5 $ show i ++ " " ++ show (L.length is)+                    f' <- ibc ist i f+                    mkIBC is f'++ibc :: IState -> IBCWrite -> IBCFile -> Idris IBCFile+ibc i (IBCFix d) f = return f { ibc_fixes = d : ibc_fixes f }+ibc i (IBCImp n) f = case lookupCtxtExact n (idris_implicits i) of+                        Just v -> return f { ibc_implicits = (n,v): ibc_implicits f     }+                        _ -> ifail "IBC write failed"+ibc i (IBCStatic n) f+                   = case lookupCtxtExact n (idris_statics i) of+                        Just v -> return f { ibc_statics = (n,v): ibc_statics f     }+                        _ -> ifail "IBC write failed"+ibc i (IBCInterface n) f+                   = case lookupCtxtExact n (idris_interfaces i) of+                        Just v -> return f { ibc_interfaces = (n,v): ibc_interfaces f     }+                        _ -> ifail "IBC write failed"+ibc i (IBCRecord n) f+                   = case lookupCtxtExact n (idris_records i) of+                        Just v -> return f { ibc_records = (n,v): ibc_records f     }+                        _ -> ifail "IBC write failed"+ibc i (IBCImplementation int res n ins) f+                   = return f { ibc_implementations = (int, res, n, ins) : ibc_implementations f }+ibc i (IBCDSL n) f+                   = case lookupCtxtExact n (idris_dsls i) of+                        Just v -> return f { ibc_dsls = (n,v): ibc_dsls f     }+                        _ -> ifail "IBC write failed"+ibc i (IBCData n) f+                   = case lookupCtxtExact n (idris_datatypes i) of+                        Just v -> return f { ibc_datatypes = (n,v): ibc_datatypes f     }+                        _ -> ifail "IBC write failed"+ibc i (IBCOpt n) f = case lookupCtxtExact n (idris_optimisation i) of+                        Just v -> return f { ibc_optimise = (n,v): ibc_optimise f     }+                        _ -> ifail "IBC write failed"+ibc i (IBCSyntax n) f = return f { ibc_syntax = n : ibc_syntax f }+ibc i (IBCKeyword n) f = return f { ibc_keywords = n : ibc_keywords f }+ibc i (IBCImport n) f = return f { ibc_imports = n : ibc_imports f }+ibc i (IBCImportDir n) f = return f { ibc_importdirs = n : ibc_importdirs f }+ibc i (IBCSourceDir n) f = return f { ibc_sourcedirs = n : ibc_sourcedirs f }+ibc i (IBCObj tgt n) f = return f { ibc_objs = (tgt, n) : ibc_objs f }+ibc i (IBCLib tgt n) f = return f { ibc_libs = (tgt, n) : ibc_libs f }+ibc i (IBCCGFlag tgt n) f = return f { ibc_cgflags = (tgt, n) : ibc_cgflags f }+ibc i (IBCDyLib n) f = return f {ibc_dynamic_libs = n : ibc_dynamic_libs f }+ibc i (IBCHeader tgt n) f = return f { ibc_hdrs = (tgt, n) : ibc_hdrs f }+ibc i (IBCDef n) f+   = do f' <- case lookupDefExact n (tt_ctxt i) of+                   Just v -> return f { ibc_defs = (n,v) : ibc_defs f }+                   _ -> ifail "IBC write failed"+        case lookupCtxtExact n (idris_patdefs i) of+                   Just v -> return f' { ibc_patdefs = (n,v) : ibc_patdefs f }+                   _ -> return f' -- Not a pattern definition++ibc i (IBCDoc n) f = case lookupCtxtExact n (idris_docstrings i) of+                        Just v -> return f { ibc_docstrings = (n,v) : ibc_docstrings f }+                        _ -> ifail "IBC write failed"+ibc i (IBCCG n) f = case lookupCtxtExact n (idris_callgraph i) of+                        Just v -> return f { ibc_cg = (n,v) : ibc_cg f     }+                        _ -> ifail "IBC write failed"+ibc i (IBCCoercion n) f = return f { ibc_coercions = n : ibc_coercions f }+ibc i (IBCAccess n a) f = return f { ibc_access = (n,a) : ibc_access f }+ibc i (IBCFlags n) f+    = case lookupCtxtExact n (idris_flags i) of+           Just a -> return f { ibc_flags = (n,a): ibc_flags f }+           _ -> ifail "IBC write failed"+ibc i (IBCFnInfo n a) f = return f { ibc_fninfo = (n,a) : ibc_fninfo f }+ibc i (IBCTotal n a) f = return f { ibc_total = (n,a) : ibc_total f }+ibc i (IBCInjective n a) f = return f { ibc_injective = (n,a) : ibc_injective f }+ibc i (IBCTrans n t) f = return f { ibc_transforms = (n, t) : ibc_transforms f }+ibc i (IBCErrRev t) f = return f { ibc_errRev = t : ibc_errRev f }+ibc i (IBCErrReduce t) f = return f { ibc_errReduce = t : ibc_errReduce f }+ibc i (IBCLineApp fp l t) f+     = return f { ibc_lineapps = (fp,l,t) : ibc_lineapps f }+ibc i (IBCNameHint (n, ty)) f+     = return f { ibc_namehints = (n, ty) : ibc_namehints f }+ibc i (IBCMetaInformation n m) f = return f { ibc_metainformation = (n,m) : ibc_metainformation f }+ibc i (IBCErrorHandler n) f = return f { ibc_errorhandlers = n : ibc_errorhandlers f }+ibc i (IBCFunctionErrorHandler fn a n) f =+  return f { ibc_function_errorhandlers = (fn, a, n) : ibc_function_errorhandlers f }+ibc i (IBCMetavar n) f =+     case lookup n (idris_metavars i) of+          Nothing -> return f+          Just t -> return f { ibc_metavars = (n, t) : ibc_metavars f }+ibc i (IBCPostulate n) f = return f { ibc_postulates = n : ibc_postulates f }+ibc i (IBCExtern n) f = return f { ibc_externs = n : ibc_externs f }+ibc i (IBCTotCheckErr fc err) f = return f { ibc_totcheckfail = (fc, err) : ibc_totcheckfail f }+ibc i (IBCParsedRegion fc) f = return f { ibc_parsedSpan = Just fc }+ibc i (IBCModDocs n) f = case lookupCtxtExact n (idris_moduledocs i) of+                           Just v -> return f { ibc_moduledocs = (n,v) : ibc_moduledocs f }+                           _ -> ifail "IBC write failed"+ibc i (IBCUsage n) f = return f { ibc_usage = n : ibc_usage f }+ibc i (IBCExport n) f = return f { ibc_exports = n : ibc_exports f }+ibc i (IBCAutoHint n h) f = return f { ibc_autohints = (n, h) : ibc_autohints f }+ibc i (IBCDeprecate n r) f = return f { ibc_deprecated = (n, r) : ibc_deprecated f }+ibc i (IBCFragile n r)   f = return f { ibc_fragile    = (n,r)  : ibc_fragile f }+ibc i (IBCConstraint fc u)  f = return f { ibc_constraints = (fc, u) : ibc_constraints f }++getEntry :: (Binary b, NFData b) => b -> FilePath -> Archive -> Idris b+getEntry alt f a = case findEntryByPath f a of+                Nothing -> return alt+                Just e -> return $! (force . decode . fromEntry) e++unhide :: IBCPhase -> FilePath -> Archive -> Idris ()+unhide phase fp ar = do+    processImports True phase fp ar+    processAccess True phase ar++process :: Bool -- ^ Reexporting+           -> IBCPhase+           -> Archive -> FilePath -> Idris ()+process reexp phase archive fn = do+                ver <- getEntry 0 "ver" archive+                when (ver /= ibcVersion) $ do+                                    logIBC 2 "ibc out of date"+                                    let e = if ver < ibcVersion+                                            then "an earlier" else "a later"+                                    ldir <- runIO $ getIdrisLibDir+                                    let start = if ldir `L.isPrefixOf` fn+                                                  then "This external module"+                                                  else "This module"+                                    let end = case L.stripPrefix ldir fn of+                                                Nothing -> "Please clean and rebuild."++                                                Just ploc -> unwords ["Please reinstall:", L.head $ splitDirectories ploc]+                                    ifail $ unlines [ unwords ["Incompatible ibc version for:", show fn]+                                                    , unwords [start+                                                              , "was built with"+                                                              , e+                                                              , "version of Idris."]+                                                    , end+                                                    ]+                source <- getEntry "" "sourcefile" archive+                srcok <- runIO $ doesFileExist source+                when srcok $ timestampOlder source fn+                processImportDirs archive+                processSourceDirs archive+                processImports reexp phase fn archive+                processImplicits archive+                processInfix archive+                processStatics archive+                processInterfaces archive+                processRecords archive+                processImplementations archive+                processDSLs archive+                processDatatypes  archive+                processOptimise  archive+                processSyntax archive+                processKeywords archive+                processObjectFiles fn archive+                processLibs archive+                processCodegenFlags archive+                processDynamicLibs archive+                processHeaders archive+                processPatternDefs archive+                processFlags archive+                processFnInfo archive+                processTotalityCheckError archive+                processCallgraph archive+                processDocs archive+                processModuleDocs archive+                processCoercions archive+                processTransforms archive+                processErrRev archive+                processErrReduce archive+                processLineApps archive+                processNameHints archive+                processMetaInformation archive+                processErrorHandlers archive+                processFunctionErrorHandlers archive+                processMetaVars archive+                processPostulates archive+                processExterns archive+                processParsedSpan archive+                processUsage archive+                processExports archive+                processAutoHints archive+                processDeprecate archive+                processDefs archive+                processTotal archive+                processInjective archive+                processAccess reexp phase archive+                processFragile archive+                processConstraints archive+                processLangExts phase archive++timestampOlder :: FilePath -> FilePath -> Idris ()+timestampOlder src ibc = do+  srct <- runIO $ getModificationTime src+  ibct <- runIO $ getModificationTime ibc+  if (srct > ibct)+    then ifail $ unlines [ "Module needs reloading:"+                         , unwords ["\tSRC :", show src]+                         , unwords ["\tModified at:", show srct]+                         , unwords ["\tIBC :", show ibc]+                         , unwords ["\tModified at:", show ibct]+                         ]+    else return ()++processPostulates :: Archive -> Idris ()+processPostulates ar = do+    ns <- getEntry [] "ibc_postulates" ar+    updateIState (\i -> i { idris_postulates = idris_postulates i `S.union` S.fromList ns })++processExterns :: Archive -> Idris ()+processExterns ar = do+    ns <-  getEntry [] "ibc_externs" ar+    updateIState (\i -> i{ idris_externs = idris_externs i `S.union` S.fromList ns })++processParsedSpan :: Archive -> Idris ()+processParsedSpan ar = do+    fc <- getEntry Nothing "ibc_parsedSpan" ar+    updateIState (\i -> i { idris_parsedSpan = fc })++processUsage :: Archive -> Idris ()+processUsage ar = do+    ns <- getEntry [] "ibc_usage" ar+    updateIState (\i -> i { idris_erasureUsed = ns ++ idris_erasureUsed i })++processExports :: Archive -> Idris ()+processExports ar = do+    ns <- getEntry [] "ibc_exports" ar+    updateIState (\i -> i { idris_exports = ns ++ idris_exports i })++processAutoHints :: Archive -> Idris ()+processAutoHints ar = do+    ns <- getEntry [] "ibc_autohints" ar+    mapM_ (\(n,h) -> addAutoHint n h) ns++processDeprecate :: Archive -> Idris ()+processDeprecate ar = do+    ns <-  getEntry [] "ibc_deprecated" ar+    mapM_ (\(n,reason) -> addDeprecated n reason) ns++processFragile :: Archive -> Idris ()+processFragile ar = do+    ns <- getEntry [] "ibc_fragile" ar+    mapM_ (\(n,reason) -> addFragile n reason) ns++processConstraints :: Archive -> Idris ()+processConstraints ar = do+    cs <- getEntry [] "ibc_constraints" ar+    mapM_ (\ (fc, c) -> addConstraints fc (0, [c])) cs++processImportDirs :: Archive -> Idris ()+processImportDirs ar = do+    fs <- getEntry [] "ibc_importdirs" ar+    mapM_ addImportDir fs++processSourceDirs :: Archive -> Idris ()+processSourceDirs ar = do+    fs <- getEntry [] "ibc_sourcedirs" ar+    mapM_ addSourceDir fs++processImports :: Bool -> IBCPhase -> FilePath -> Archive -> Idris ()+processImports reexp phase fname ar = do+    fs <- getEntry [] "ibc_imports" ar+    mapM_ (\(re, f) -> do+        i <- getIState+        ibcsd <- valIBCSubDir i+        ids <- rankedImportDirs fname+        putIState (i { imported = f : imported i })+        let (phase', reexp') =+              case phase of+                IBC_REPL True -> (IBC_REPL False, reexp)+                IBC_REPL False -> (IBC_Building, reexp && re)+                p -> (p, reexp && re)+        fp <- findIBC ids ibcsd f+        logIBC 4 $ "processImports (fp, phase')" ++ show (fp, phase')+        case fp of+            Nothing -> do logIBC 2 $ "Failed to load ibc " ++ f+            Just fn -> do loadIBC reexp' phase' fn) fs++processImplicits :: Archive -> Idris ()+processImplicits ar = do+    imps <- getEntry [] "ibc_implicits" ar+    mapM_ (\ (n, imp) -> do+        i <- getIState+        case lookupDefAccExact n False (tt_ctxt i) of+            Just (n, Hidden) -> return ()+            Just (n, Private) -> return ()+            _ -> putIState (i { idris_implicits = addDef n imp (idris_implicits i) })) imps++processInfix :: Archive -> Idris ()+processInfix ar = do+    f <- getEntry [] "ibc_fixes" ar+    updateIState (\i -> i { idris_infixes = sort $ f ++ idris_infixes i })++processStatics :: Archive -> Idris ()+processStatics ar = do+    ss <- getEntry [] "ibc_statics" ar+    mapM_ (\ (n, s) ->+        updateIState (\i -> i { idris_statics = addDef n s (idris_statics i) })) ss++processInterfaces :: Archive -> Idris ()+processInterfaces ar = do+    cs <- getEntry [] "ibc_interfaces" ar+    mapM_ (\ (n, c) -> do+        i <- getIState+        -- Don't lose implementations from previous IBCs, which+        -- could have loaded in any order+        let is = case lookupCtxtExact n (idris_interfaces i) of+                    Just ci -> interface_implementations ci+                    _ -> []+        let c' = c { interface_implementations = interface_implementations c ++ is }+        putIState (i { idris_interfaces = addDef n c' (idris_interfaces i) })) cs++processRecords :: Archive -> Idris ()+processRecords ar = do+    rs <- getEntry [] "ibc_records" ar+    mapM_ (\ (n, r) ->+        updateIState (\i -> i { idris_records = addDef n r (idris_records i) })) rs++processImplementations :: Archive -> Idris ()+processImplementations ar = do+    cs <- getEntry [] "ibc_implementations" ar+    mapM_ (\ (i, res, n, ins) -> addImplementation i res n ins) cs++processDSLs :: Archive -> Idris ()+processDSLs ar = do+    cs <- getEntry [] "ibc_dsls" ar+    mapM_ (\ (n, c) -> updateIState (\i ->+                        i { idris_dsls = addDef n c (idris_dsls i) })) cs++processDatatypes :: Archive -> Idris ()+processDatatypes ar = do+    cs <- getEntry [] "ibc_datatypes" ar+    mapM_ (\ (n, c) -> updateIState (\i ->+                        i { idris_datatypes = addDef n c (idris_datatypes i) })) cs++processOptimise :: Archive -> Idris ()+processOptimise ar = do+    cs <- getEntry [] "ibc_optimise" ar+    mapM_ (\ (n, c) -> updateIState (\i ->+                        i { idris_optimisation = addDef n c (idris_optimisation i) })) cs++processSyntax :: Archive -> Idris ()+processSyntax ar = do+    s <- getEntry [] "ibc_syntax" ar+    updateIState (\i -> i { syntax_rules = updateSyntaxRules s (syntax_rules i) })++processKeywords :: Archive -> Idris ()+processKeywords ar = do+    k <- getEntry [] "ibc_keywords" ar+    updateIState (\i -> i { syntax_keywords = k ++ syntax_keywords i })++processObjectFiles :: FilePath -> Archive -> Idris ()+processObjectFiles fn ar = do+    os <- getEntry [] "ibc_objs" ar+    mapM_ (\ (cg, obj) -> do+        dirs <- rankedImportDirs fn+        o <- runIO $ findInPath dirs obj+        addObjectFile cg o) os++processLibs :: Archive -> Idris ()+processLibs ar = do+    ls <- getEntry [] "ibc_libs" ar+    mapM_ (uncurry addLib) ls++processCodegenFlags :: Archive -> Idris ()+processCodegenFlags ar = do+    ls <- getEntry [] "ibc_cgflags" ar+    mapM_ (uncurry addFlag) ls++processDynamicLibs :: Archive -> Idris ()+processDynamicLibs ar = do+        ls <- getEntry [] "ibc_dynamic_libs" ar+        res <- mapM (addDyLib . return) ls+        mapM_ checkLoad res+    where+        checkLoad (Left _) = return ()+        checkLoad (Right err) = ifail err++processHeaders :: Archive -> Idris ()+processHeaders ar = do+    hs <- getEntry [] "ibc_hdrs" ar+    mapM_ (uncurry addHdr) hs++processPatternDefs :: Archive -> Idris ()+processPatternDefs ar = do+    ds <- getEntry [] "ibc_patdefs" ar+    mapM_ (\ (n, d) -> updateIState (\i ->+            i { idris_patdefs = addDef n (force d) (idris_patdefs i) })) ds++processDefs :: Archive -> Idris ()+processDefs ar = do+        ds <- getEntry [] "ibc_defs" ar+        logIBC 4 $ "processDefs ds" ++ show ds+        mapM_ (\ (n, d) -> do+            d' <- updateDef d+            case d' of+                TyDecl _ _ -> return ()+                _ -> do+                    logIBC 2 $ "SOLVING " ++ show n+                    solveDeferred emptyFC n+            updateIState (\i -> i { tt_ctxt = addCtxtDef n d' (tt_ctxt i) })) ds+    where+        updateDef (CaseOp c t args o s cd) = do+            o' <- mapM updateOrig o+            cd' <- updateCD cd+            return $ CaseOp c t args o' s cd'+        updateDef t = return t++        updateOrig (Left t) = liftM Left (update t)+        updateOrig (Right (l, r)) = do+            l' <- update l+            r' <- update r+            return $ Right (l', r')++        updateCD (CaseDefs (cs, c) (rs, r)) = do+            c' <- updateSC c+            r' <- updateSC r+            return $ CaseDefs (cs, c') (rs, r')++        updateSC (Case t n alts) = do+            alts' <- mapM updateAlt alts+            return (Case t n alts')+        updateSC (ProjCase t alts) = do+            alts' <- mapM updateAlt alts+            return (ProjCase t alts')+        updateSC (STerm t) = do+            t' <- update t+            return (STerm t')+        updateSC c = return c++        updateAlt (ConCase n i ns t) = do+            t' <- updateSC t+            return (ConCase n i ns t')+        updateAlt (FnCase n ns t) = do+            t' <- updateSC t+            return (FnCase n ns t')+        updateAlt (ConstCase c t) = do+            t' <- updateSC t+            return (ConstCase c t')+        updateAlt (SucCase n t) = do+            t' <- updateSC t+            return (SucCase n t')+        updateAlt (DefaultCase t) = do+            t' <- updateSC t+            return (DefaultCase t')++        -- We get a lot of repetition in sub terms and can save a fair chunk+        -- of memory if we make sure they're shared. addTT looks for a term+        -- and returns it if it exists already, while also keeping stats of+        -- how many times a subterm is repeated.+        update t = do+            tm <- addTT t+            case tm of+                Nothing -> update' t+                Just t' -> return t'++        update' (P t n ty) = do+            n' <- getSymbol n+            return $ P t n' ty+        update' (App s f a) = liftM2 (App s) (update' f) (update' a)+        update' (Bind n b sc) = do+            b' <- updateB b+            sc' <- update sc+            return $ Bind n b' sc'+                where+                    updateB (Let rig t v) = liftM2 (Let rig) (update' t) (update' v)+                    updateB b = do+                        ty' <- update' (binderTy b)+                        return (b { binderTy = ty' })+        update' (Proj t i) = do+                  t' <- update' t+                  return $ Proj t' i+        update' t = return t++processDocs :: Archive -> Idris ()+processDocs ar = do+    ds <- getEntry [] "ibc_docstrings" ar+    mapM_ (\(n, a) -> addDocStr n (fst a) (snd a)) ds++processModuleDocs :: Archive -> Idris ()+processModuleDocs ar = do+    ds <- getEntry [] "ibc_moduledocs" ar+    mapM_  (\ (n, d) -> updateIState (\i ->+            i { idris_moduledocs = addDef n d (idris_moduledocs i) })) ds++processAccess :: Bool -- ^ Reexporting?+           -> IBCPhase+           -> Archive -> Idris ()+processAccess reexp phase ar = do+    logIBC 3 $ "processAccess (reexp, phase)" ++ show (reexp, phase)+    ds <- getEntry [] "ibc_access" ar+    logIBC 3 $ "processAccess ds" ++ show ds+    mapM_ (\ (n, a_in) -> do++        let a = if reexp then a_in else Hidden+        logIBC 3 $ "Setting " ++ show (a, n) ++ " to " ++ show a+        updateIState (\i -> i { tt_ctxt = setAccess n a (tt_ctxt i) })++        if (not reexp)+            then do+                logIBC 2 $ "Not exporting " ++ show n+                setAccessibility n Hidden+            else+                logIBC 2 $ "Exporting " ++ show n++        -- Everything should be available at the REPL from+        -- things imported publicly.+        when (phase == IBC_REPL True) $ do+            logIBC 2 $ "Top level, exporting " ++ show n+            setAccessibility n Public+      ) ds++processFlags :: Archive -> Idris ()+processFlags ar = do+    ds <- getEntry [] "ibc_flags" ar+    mapM_ (\ (n, a) -> setFlags n a) ds++processFnInfo :: Archive -> Idris ()+processFnInfo ar = do+    ds <- getEntry [] "ibc_fninfo" ar+    mapM_ (\ (n, a) -> setFnInfo n a) ds++processTotal :: Archive -> Idris ()+processTotal ar = do+    ds <- getEntry [] "ibc_total" ar+    mapM_ (\ (n, a) -> updateIState (\i -> i { tt_ctxt = setTotal n a (tt_ctxt i) })) ds++processInjective :: Archive -> Idris ()+processInjective ar = do+    ds <- getEntry [] "ibc_injective" ar+    mapM_ (\ (n, a) -> updateIState (\i -> i { tt_ctxt = setInjective n a (tt_ctxt i) })) ds++processTotalityCheckError :: Archive -> Idris ()+processTotalityCheckError ar = do+    es <- getEntry [] "ibc_totcheckfail" ar+    updateIState (\i -> i { idris_totcheckfail = idris_totcheckfail i ++ es })++processCallgraph :: Archive -> Idris ()+processCallgraph ar = do+    ds <- getEntry [] "ibc_cg" ar+    mapM_ (\ (n, a) -> addToCG n a) ds++processCoercions :: Archive -> Idris ()+processCoercions ar = do+    ns <- getEntry [] "ibc_coercions" ar+    mapM_ (\ n -> addCoercion n) ns++processTransforms :: Archive -> Idris ()+processTransforms ar = do+    ts <- getEntry [] "ibc_transforms" ar+    mapM_ (\ (n, t) -> addTrans n t) ts++processErrRev :: Archive -> Idris ()+processErrRev ar = do+    ts <- getEntry [] "ibc_errRev" ar+    mapM_ addErrRev ts++processErrReduce :: Archive -> Idris ()+processErrReduce ar = do+    ts <- getEntry [] "ibc_errReduce" ar+    mapM_ addErrReduce ts++processLineApps :: Archive -> Idris ()+processLineApps ar = do+    ls <- getEntry [] "ibc_lineapps" ar+    mapM_ (\ (f, i, t) -> addInternalApp f i t) ls++processNameHints :: Archive -> Idris ()+processNameHints ar = do+    ns <- getEntry [] "ibc_namehints" ar+    mapM_ (\ (n, ty) -> addNameHint n ty) ns++processMetaInformation :: Archive -> Idris ()+processMetaInformation ar = do+    ds <- getEntry [] "ibc_metainformation" ar+    mapM_ (\ (n, m) -> updateIState (\i ->+                               i { tt_ctxt = setMetaInformation n m (tt_ctxt i) })) ds++processErrorHandlers :: Archive -> Idris ()+processErrorHandlers ar = do+    ns <- getEntry [] "ibc_errorhandlers" ar+    updateIState (\i -> i { idris_errorhandlers = idris_errorhandlers i ++ ns })++processFunctionErrorHandlers :: Archive -> Idris ()+processFunctionErrorHandlers ar = do+    ns <- getEntry [] "ibc_function_errorhandlers" ar+    mapM_ (\ (fn,arg,handler) -> addFunctionErrorHandlers fn arg [handler]) ns++processMetaVars :: Archive -> Idris ()+processMetaVars ar = do+    ns <- getEntry [] "ibc_metavars" ar+    updateIState (\i -> i { idris_metavars = L.reverse ns ++ idris_metavars i })++-- We only want the language extensions when reading the top level thing+processLangExts :: IBCPhase -> Archive -> Idris ()+processLangExts (IBC_REPL True) ar+    = do ds <- getEntry [] "ibc_langexts" ar+         mapM_ addLangExt ds+processLangExts _ _ = return ()++----- For Cheapskate and docstrings++instance Binary a => Binary (D.Docstring a)+instance Binary CT.Options+instance Binary D.DocTerm+instance Binary a => Binary (D.Block a)+instance Binary a => Binary (D.Inline a)+instance Binary CT.ListType+instance Binary CT.CodeAttr+instance Binary CT.NumWrapper++----- Generated by 'derive'++instance Binary SizeChange+instance Binary CGInfo where+        put (CGInfo x1 x2 x3 x4)+          = do put x1+--                put x3 -- Already used SCG info for totality check+               put x2+               put x4+        get+          = do x1 <- get+               x2 <- get+               x3 <- get+               return (CGInfo x1 x2 [] x3)++instance Binary CaseType+instance Binary SC+instance Binary CaseAlt+instance Binary CaseDefs+instance Binary CaseInfo+instance Binary Def where+        put x+          = {-# SCC "putDef" #-}+            case x of+                Function x1 x2 -> do putWord8 0+                                     put x1+                                     put x2+                TyDecl x1 x2 -> do putWord8 1+                                   put x1+                                   put x2+                -- all primitives just get added at the start, don't write+                Operator x1 x2 x3 -> do return ()+                -- no need to add/load original patterns, because they're not+                -- used again after totality checking+                CaseOp x1 x2 x3 _ _ x4 -> do putWord8 3+                                             put x1+                                             put x2+                                             put x3+                                             put x4+        get+          = do i <- getWord8+               case i of+                   0 -> do x1 <- get+                           x2 <- get+                           return (Function x1 x2)+                   1 -> do x1 <- get+                           x2 <- get+                           return (TyDecl x1 x2)+                   -- Operator isn't written, don't read+                   3 -> do x1 <- get+                           x2 <- get+                           x3 <- get+--                            x4 <- get+                           -- x3 <- get always []+                           x5 <- get+                           return (CaseOp x1 x2 x3 [] [] x5)+                   _ -> error "Corrupted binary data for Def"++instance Binary Accessibility+instance Binary PReason+instance Binary Totality+instance Binary MetaInformation+instance Binary DataOpt+instance Binary FnOpt+instance Binary Fixity+instance Binary FixDecl+instance Binary ArgOpt+instance Binary Static+instance Binary Plicity where+        put x+          = case x of+                Imp x1 x2 x3 x4 _ x5 ->+                             do putWord8 0+                                put x1+                                put x2+                                put x3+                                put x4+                                put x5+                Exp x1 x2 x3 x4 ->+                             do putWord8 1+                                put x1+                                put x2+                                put x3+                                put x4+                Constraint x1 x2 x3 ->+                                    do putWord8 2+                                       put x1+                                       put x2+                                       put x3+                TacImp x1 x2 x3 x4 ->+                                   do putWord8 3+                                      put x1+                                      put x2+                                      put x3+                                      put x4+        get+          = do i <- getWord8+               case i of+                   0 -> do x1 <- get+                           x2 <- get+                           x3 <- get+                           x4 <- get+                           x5 <- get+                           return (Imp x1 x2 x3 x4 False x5)+                   1 -> do x1 <- get+                           x2 <- get+                           x3 <- get+                           x4 <- get+                           return (Exp x1 x2 x3 x4)+                   2 -> do x1 <- get+                           x2 <- get+                           x3 <- get+                           return (Constraint x1 x2 x3)+                   3 -> do x1 <- get+                           x2 <- get+                           x3 <- get+                           x4 <- get+                           return (TacImp x1 x2 x3 x4)+                   _ -> error "Corrupted binary data for Plicity"++instance Binary DefaultTotality+instance Binary LanguageExt+instance Binary Directive+instance (Binary t) => Binary (PDecl' t)+instance Binary t => Binary (ProvideWhat' t)+instance Binary Using+instance Binary SyntaxInfo where+        put (Syn x1 x2 x3 x4 _ _ x5 x6 x7 _ _ x8 _ _ _)+          = do put x1+               put x2+               put x3+               put x4+               put x5+               put x6+               put x7+               put x8+        get+          = do x1 <- get+               x2 <- get+               x3 <- get+               x4 <- get+               x5 <- get+               x6 <- get+               x7 <- get+               x8 <- get+               return (Syn x1 x2 x3 x4 [] id x5 x6 x7 Nothing 0 x8 0 True True)++instance (Binary t) => Binary (PClause' t)+instance (Binary t) => Binary (PData' t)+instance Binary PunInfo+instance Binary PTerm+instance Binary PAltType+instance (Binary t) => Binary (PTactic' t)+instance (Binary t) => Binary (PDo' t)+instance (Binary t) => Binary (PArg' t)+instance Binary InterfaceInfo where+        put (CI x1 x2 x3 x4 x5 x6 x7 _ x8)+          = do put x1+               put x2+               put x3+               put x4+               put x5+               put x6+               put x7+               put x8+        get+          = do x1 <- get+               x2 <- get+               x3 <- get+               x4 <- get+               x5 <- get+               x6 <- get+               x7 <- get+               x8 <- get+               return (CI x1 x2 x3 x4 x5 x6 x7 [] x8)++instance Binary RecordInfo+instance Binary OptInfo+instance Binary FnInfo+instance Binary TypeInfo+instance Binary SynContext+instance Binary Syntax+instance (Binary t) => Binary (DSL' t)+instance Binary SSymbol+instance Binary Codegen+instance Binary IRFormat
src/Idris/IdeMode.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.IdeMode Description : Idris' IDE Mode-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -11,10 +11,11 @@  module Idris.IdeMode(parseMessage, convSExp, WhatDocs(..), IdeModeCommand(..), sexpToCommand, toSExp, SExp(..), SExpable, Opt(..), ideModeEpoch, getLen, getNChar, sExpToString) where -import Idris.Core.Binary+import Idris.Core.Binary () import Idris.Core.TT  import Control.Applicative hiding (Const)+import Control.Arrow (left) import qualified Data.Binary as Binary import qualified Data.ByteString.Base64 as Base64 import qualified Data.ByteString.Lazy as Lazy@@ -24,9 +25,9 @@ import qualified Data.Text as T import Numeric import System.IO+import qualified Text.Megaparsec as P+import qualified Text.Megaparsec.Char as P import Text.Printf-import Text.Trifecta hiding (Err)-import Text.Trifecta.Delta  getNChar :: Handle -> Int -> String -> IO (String) getNChar _ 0 s = return (reverse s)@@ -172,13 +173,11 @@              maybeProps [("source-file", file)]   toSExp AnnQuasiquote = toSExp [(SymbolAtom "quasiquotation", True)]   toSExp AnnAntiquote = toSExp [(SymbolAtom "antiquotation", True)]+  toSExp (AnnSyntax c) = SexpList []  encodeName :: Name -> String encodeName n = UTF8.toString . Base64.encode . Lazy.toStrict . Binary.encode $ n -decodeName :: String -> Name-decodeName = Binary.decode . Lazy.fromStrict . Base64.decodeLenient . UTF8.fromString- encodeTerm :: [(Name, Bool)] -> Term -> String encodeTerm bnd tm = UTF8.toString . Base64.encode . Lazy.toStrict . Binary.encode $                     (bnd, tm)@@ -207,28 +206,30 @@     escapeChar '"'  = "\\\""     escapeChar c    = [c] -pSExp = do xs <- between (char '(') (char ')') (pSExp `sepBy` (char ' '))-           return (SexpList xs)+type Parser a = P.Parsec () String a++sexp :: Parser SExp+sexp = SexpList <$> P.between (P.char '(') (P.char ')') (sexp `P.sepBy` (P.char ' '))     <|> atom -atom = do string "nil"; return (SexpList [])-   <|> do char ':'; x <- atomC; return x-   <|> do char '"'; xs <- many quotedChar; char '"'; return (StringAtom xs)-   <|> do ints <- some digit+atom :: Parser SExp+atom = SexpList [] <$ P.string "nil"+   <|> P.char ':' *> atomC+   <|> StringAtom <$> P.between (P.char '"') (P.char '"') (P.many quotedChar)+   <|> do ints <- some P.digitChar           case readDec ints of             ((num, ""):_) -> return (IntegerAtom (toInteger num))             _ -> return (StringAtom ints) -atomC = do string "True"; return (BoolAtom True)-    <|> do string "False"; return (BoolAtom False)-    <|> do xs <- many (noneOf " \n\t\r\"()"); return (SymbolAtom xs)--quotedChar = try (string "\\\\" >> return '\\')-         <|> try (string "\\\"" >> return '"')-         <|> noneOf "\""+atomC :: Parser SExp+atomC = BoolAtom True  <$ P.string "True"+    <|> BoolAtom False <$ P.string "False"+    <|> SymbolAtom <$> many (P.noneOf " \n\t\r\"()") -parseSExp :: String -> Result SExp-parseSExp = parseString pSExp (Directed (UTF8.fromString "(unknown)") 0 0 0 0)+quotedChar :: Parser Char+quotedChar = P.try ('\\' <$ P.string "\\\\")+         <|> P.try ('"' <$ P.string "\\\"")+         <|> P.noneOf "\""  data Opt = ShowImpl | ErrContext deriving Show @@ -324,10 +325,7 @@                    Left err -> Left err  receiveString :: String -> Either Err SExp-receiveString x =-  case parseSExp x of-    Failure _ -> Left . Msg $ "parse failure"-    Success r -> Right r+receiveString = left (const $ Msg "parse failure") . P.parse sexp "(unknown)"  convSExp :: SExpable a => String -> a -> Integer -> String convSExp pre s id =
src/Idris/IdrisDoc.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.IdrisDoc Description : Generation of HTML documentation for Idris code-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -10,33 +10,28 @@ module Idris.IdrisDoc (generateDocs) where  import Idris.AbsSyntax-import Idris.Core.Evaluate (Accessibility(..), Def(..), ctxtAlist, isDConName,-                            isFnName, isTConName, lookupDefAcc)-import Idris.Core.TT (Name(..), OutputAnnotation(..), SpecialName(..),-                      TextFormatting(..), constIsType, nsroot, sUN, str,-                      toAlist, txt)+import Idris.Core.Evaluate (Accessibility(..), ctxtAlist, isDConName, isFnName,+                            isTConName, lookupDefAcc)+import Idris.Core.TT (Name(..), OutputAnnotation(..), TextFormatting(..),+                      constIsType, nsroot, sUN, str, toAlist, txt) import Idris.Docs import Idris.Docstrings (nullDocstring) import qualified Idris.Docstrings as Docstrings import Idris.Options-import Idris.Parser.Helpers (opChars)+import Idris.Parser.Ops (opChars) import IRTS.System (getIdrisDataFileByName)  import Control.Applicative ((<|>)) import Control.Monad (forM_) import Control.Monad.Trans.Except import Control.Monad.Trans.State.Strict-import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BS2 import qualified Data.List as L-import qualified Data.List.Split as LS import qualified Data.Map as M hiding ((!)) import Data.Maybe import Data.Monoid (mempty)-import qualified Data.Ord (compare) import qualified Data.Set as S import qualified Data.Text as T-import qualified Data.Text.Encoding as E import System.Directory import System.FilePath import System.IO@@ -253,13 +248,6 @@      [(_, acc)] -> acc      _          -> Private --- | Simple predicate for whether an NsItem has Docs-hasDoc :: NsItem -- ^ The NsItem to test-       -> Bool   -- ^ The result-hasDoc (_, Just _, _) = True-hasDoc _              = False-- -- | Predicate saying whether a Name possibly may have docs defined --   Without this, getDocs from Idris.Docs may fail a pattern match. mayHaveDocs :: Name -- ^ The Name to test@@ -291,7 +279,7 @@ extractPTermNames (PPatvar _ n)      = [n] extractPTermNames (PLam _ n _ p1 p2) = n : concatMap extract [p1, p2] extractPTermNames (PPi _ n _ p1 p2)  = n : concatMap extract [p1, p2]-extractPTermNames (PLet _ n _ p1 p2 p3) = n : concatMap extract [p1, p2, p3]+extractPTermNames (PLet _ _ n _ p1 p2 p3) = n : concatMap extract [p1, p2, p3] extractPTermNames (PTyped p1 p2)     = concatMap extract [p1, p2] extractPTermNames (PApp _ p pas)     = let names = concatMap extractPArg pas                                        in  (extract p) ++ names@@ -342,8 +330,10 @@ extractPDo (DoBindP _ p1 p2 ps)  = let (ps1, ps2) = unzip ps                                        ps'        = ps1 ++ ps2                                    in  concatMap extract (p1 : p2 : ps')-extractPDo (DoLet   _ n _ p1 p2) = n : concatMap extract [p1, p2]-extractPDo (DoLetP  _ p1 p2)     = concatMap extract [p1, p2]+extractPDo (DoLet _ _ n _ p1 p2) = n : concatMap extract [p1, p2]+extractPDo (DoLetP  _ p1 p2 ps)  = let (ps1, ps2) = unzip ps+                                       ps'        = ps1 ++ ps2+                                   in  concatMap extract (p1 : p2 : ps') extractPDo (DoRewrite  _ p)      = extract p  -- | Helper function for extractPTermNames@@ -653,6 +643,8 @@       indexPage  = base ++ "index.html" :: String   in  H.docTypeHtml $ do     H.head $ do+      H.meta ! charset "utf-8"+      H.meta ! name "viewport" ! content "width=device-width, initial-scale=1, shrink-to-fit=no"       H.title $ do         "IdrisDoc"         if index then " Index" else do
src/Idris/Imports.hs view
@@ -1,13 +1,14 @@ {-| Module      : Idris.Imports Description : Code to handle import declarations.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -} module Idris.Imports(-    IFileType(..), findImport, findInPath, findPkgIndex+    IFileType(..), findIBC, findImport, findInPath, findPkgIndex   , ibcPathNoFallback, installedPackages, pkgIndex+  , PkgName, pkgName, unPkgName, unInitializedPkgName   ) where  import Idris.AbsSyntax@@ -17,6 +18,7 @@  import Control.Applicative ((<$>)) import Control.Monad.State.Strict+import Data.Char (isAlpha, isDigit, toLower) import Data.List (isSuffixOf) import System.Directory import System.FilePath@@ -24,18 +26,40 @@ data IFileType = IDR FilePath | LIDR FilePath | IBC FilePath IFileType     deriving (Show, Eq) +newtype PkgName = PkgName String++unPkgName :: PkgName -> String+unPkgName (PkgName s) = map toLower s++instance Show PkgName where+    show (PkgName pkg) = pkg+instance Eq PkgName where+    a == b = unPkgName a == unPkgName b++unInitializedPkgName :: PkgName+unInitializedPkgName = PkgName ""++pkgName :: String -> Either String PkgName+pkgName ""      = Left "empty package name"+pkgName s@(f:l)+    | not $ isAlpha f =+        Left "package name need to start by a letter"+    | not $ all (\c -> isAlpha c || isDigit c || c `elem` "-_") l =+        Left "package name need to contain only letter, digits, and -_"+    | otherwise = Right $ PkgName s+ -- | Get the index file name for a package name-pkgIndex :: String -> FilePath-pkgIndex s = "00" ++ s ++ "-idx.ibc"+pkgIndex :: PkgName -> FilePath+pkgIndex s = "00" ++ unPkgName s ++ "-idx.ibc"  srcPath :: FilePath -> FilePath-srcPath fp = let (n, ext) = splitExtension fp in+srcPath fp = let (_, ext) = splitExtension fp in                  case ext of                     ".idr" -> fp                     _ -> fp ++ ".idr"  lsrcPath :: FilePath -> FilePath-lsrcPath fp = let (n, ext) = splitExtension fp in+lsrcPath fp = let (_, ext) = splitExtension fp in                   case ext of                      ".lidr" -> fp                      _ -> fp ++ ".lidr"@@ -77,6 +101,17 @@                                        then return isrc                                        else findImport ds ibcsd fp +-- Only look for IBCs and not source+findIBC :: [FilePath] -> FilePath -> FilePath -> Idris (Maybe FilePath)+findIBC [] _ fp = return Nothing+findIBC (d:ds) ibcsd fp = do let fp_full = d </> fp+                             ibcp <- runIO $ ibcPathWithFallback ibcsd fp_full+                             ibc <- runIO $ doesFileExist' ibcp+                             if ibc+                                then return $ Just ibcp+                                else findIBC ds ibcsd fp++ -- find a specific filename somewhere in a path  findInPath :: [FilePath] -> FilePath -> IO FilePath@@ -85,7 +120,7 @@                           e <- doesFileExist' p                           if e then return p else findInPath ds fp -findPkgIndex :: String -> Idris FilePath+findPkgIndex :: PkgName -> Idris FilePath findPkgIndex p = do let idx = pkgIndex p                     ids <- allImportDirs                     runIO $ findInPath ids idx
src/Idris/Info.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Info Description : Get information about Idris.-Copyright   : 2016 The Idris Community+ 2016 The Idris Community License     : BSD3 Maintainer  : The Idris Community. -}@@ -29,7 +29,6 @@ import Idris.Options (loggingCatsStr) import qualified IRTS.System as S -import Paths_idris import Version_idris (gitHash)  import Data.Version
src/Idris/Inliner.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Inliner Description : Idris' Inliner.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -29,7 +29,7 @@   inl orig@(P _ n _) = inlApp n [] orig   inl orig@(App _ f a)       | (P _ fn _, args) <- unApply orig = inlApp fn args orig-  inl (Bind n (Let t v) sc) = Bind n (Let t (inl v)) (inl sc)+  inl (Bind n (Let rc t v) sc) = Bind n (Let rc t (inl v)) (inl sc)   inl (Bind n b sc) = Bind n b (inl sc)   inl tm = tm 
src/Idris/Interactive.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Interactive Description : Bits and pieces for editing source files interactively, called from the REPL-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -261,7 +261,7 @@             else iPrintResult newmv     where dropCtxt 0 sc = sc           dropCtxt i (PPi _ _ _ _ sc) = dropCtxt (i - 1) sc-          dropCtxt i (PLet _ _ _ _ _ sc) = dropCtxt (i - 1) sc+          dropCtxt i (PLet _ _ _ _ _ _ sc) = dropCtxt (i - 1) sc           dropCtxt i (PLam _ _ _ _ sc) = dropCtxt (i - 1) sc           dropCtxt _ t = t @@ -382,9 +382,7 @@                                                                  StringAtom lem_app]]]                         in runIO . hPutStrLn h $ convSExp "return" good n -  where getIndent s = length (takeWhile isSpace s)--        appArgs skip 0 _ = ""+  where appArgs skip 0 _ = ""         appArgs skip i (Bind n@(UN c) (Pi _ _ _ _) sc)            | (thead c /= '_' && n `notElem` skip)                 = " " ++ show n ++ appArgs skip (i - 1) sc
src/Idris/Main.hs view
@@ -47,7 +47,6 @@ import System.FilePath import System.IO import System.IO.CodePage (withCP65001)-import Text.Trifecta.Result (ErrInfo(..), Result(..))  -- | How to run Idris programs. runMain :: Idris () -> IO ()@@ -157,10 +156,10 @@         mapM_ addPkgDir pkgdirs        elabPrims-       when (not (NoBuiltins `elem` opts)) $ do x <- loadModule "Builtins" (IBC_REPL True)+       when (not (NoBuiltins `elem` opts)) $ do x <- loadModule "Builtins" (IBC_REPL False)                                                 addAutoImport "Builtins"                                                 return ()-       when (not (NoPrelude `elem` opts)) $ do x <- loadModule "Prelude" (IBC_REPL True)+       when (not (NoPrelude `elem` opts)) $ do x <- loadModule "Prelude" (IBC_REPL False)                                                addAutoImport "Prelude"                                                return ()        when (runrepl && not idesl) initScript@@ -196,9 +195,9 @@                      mapM_ (\str -> do ist <- getIState                                        c <- colourise                                        case parseExpr ist str of-                                         Failure (ErrInfo err _) -> do iputStrLn $ show (fixColour c err)-                                                                       runIO $ exitWith (ExitFailure 1)-                                         Success e -> process "" (Eval e))+                                         Left err -> do emitWarning err+                                                        runIO $ exitWith (ExitFailure 1)+                                         Right e -> process "" (Eval e))                            exprs                      runIO exitSuccess @@ -273,12 +272,12 @@ execScript expr = do i <- getIState                      c <- colourise                      case parseExpr i expr of-                          Failure (ErrInfo err _) -> do iputStrLn $ show (fixColour c err)-                                                        runIO $ exitWith (ExitFailure 1)-                          Success term -> do ctxt <- getContext-                                             (tm, _) <- elabVal (recinfo (fileFC "toplevel")) ERHS term-                                             res <- execute tm-                                             runIO $ exitSuccess+                          Left err -> do emitWarning err+                                         runIO $ exitWith (ExitFailure 1)+                          Right term -> do ctxt <- getContext+                                           (tm, _) <- elabVal (recinfo (fileFC "toplevel")) ERHS term+                                           res <- execute tm+                                           runIO $ exitSuccess  -- | Run the initialisation script initScript :: Idris ()@@ -300,12 +299,12 @@                            runInit h           processLine i cmd input clr =               case parseCmd i input cmd of-                   Failure (ErrInfo err _) -> runIO $ print (fixColour clr err)-                   Success (Right Reload) -> iPrintError "Init scripts cannot reload the file"-                   Success (Right (Load f _)) -> iPrintError "Init scripts cannot load files"-                   Success (Right (ModImport f)) -> iPrintError "Init scripts cannot import modules"-                   Success (Right Edit) -> iPrintError "Init scripts cannot invoke the editor"-                   Success (Right Proofs) -> proofs i-                   Success (Right Quit) -> iPrintError "Init scripts cannot quit Idris"-                   Success (Right cmd ) -> process [] cmd-                   Success (Left err) -> runIO $ print err+                   Left err -> emitWarning err+                   Right (Right Reload) -> iPrintError "Init scripts cannot reload the file"+                   Right (Right (Load f _)) -> iPrintError "Init scripts cannot load files"+                   Right (Right (ModImport f)) -> iPrintError "Init scripts cannot import modules"+                   Right (Right Edit) -> iPrintError "Init scripts cannot invoke the editor"+                   Right (Right Proofs) -> proofs i+                   Right (Right Quit) -> iPrintError "Init scripts cannot quit Idris"+                   Right (Right cmd ) -> process [] cmd+                   Right (Left err) -> runIO $ print err
src/Idris/ModeCommon.hs view
@@ -4,8 +4,13 @@ License     : BSD3 Maintainer  : The Idris Community. -}-module Idris.ModeCommon where +{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}+{-# OPTIONS_GHC -fwarn-unused-binds #-}+{-# OPTIONS_GHC -fwarn-unused-imports #-}++module Idris.ModeCommon (banner, defaultPort, loadInputs, warranty) where+ import Idris.AbsSyntax import Idris.Chaser import Idris.Core.TT@@ -25,16 +30,11 @@ import Control.Category import Control.DeepSeq import Control.Monad-import Control.Monad.Trans.State.Strict (get)-import Data.List hiding (group)-import Data.Maybe import Network.Socket (PortNumber)-import System.Directory  defaultPort :: PortNumber defaultPort = fromIntegral 4294 - loadInputs :: [FilePath] -> Maybe Int -> Idris [FilePath] loadInputs inputs toline -- furthest line to read in input source files   = idrisCatch@@ -49,6 +49,8 @@                                [] -> not (NoREPL `elem` opts)                                _ -> True +           logParser 3 $ show "loadInputs loadCode" ++ show loadCode+            -- For each ifile list, check it and build ibcs in the same clean IState            -- so that they don't interfere with each other when checking @@ -59,13 +61,14 @@            let ninputs = zip [1..] inputs            ifiles <- mapWhileOK (\(num, input) ->                 do putIState ist+                   logParser 3 $ show "loadInputs (num, input)" ++ show (num, input)                    modTree <- buildTree                                    (map snd (take (num-1) ninputs))                                    importlists                                    input                    let ifiles = getModuleFiles modTree-                   logParser 1 ("MODULE TREE : " ++ show modTree)-                   logParser 1 ("RELOAD: " ++ show ifiles)+                   logParser 2 ("MODULE TREE : " ++ show modTree)+                   logParser 2 ("RELOAD: " ++ show ifiles)                    when (not (all ibc ifiles) || loadCode) $                         tryLoad False IBC_Building (filter (not . ibc) ifiles)                    -- return the files that need rechecking@@ -77,9 +80,18 @@            case errSpan inew of               Nothing ->                 do putIState $!! ist { idris_tyinfodata = tidata }-                   ibcfiles <- mapM findNewIBC (nub (concatMap snd ifiles))---                    logLvl 0 $ "Loading from " ++ show ibcfiles-                   tryLoad True (IBC_REPL True) (mapMaybe id ibcfiles)+                   logParser 3 $ "loadInputs ifiles" ++ show ifiles++                   let fileToIFileType :: FilePath -> Idris IFileType+                       fileToIFileType file = do+                         ibcsd <- valIBCSubDir ist+                         ids <- rankedImportDirs file+                         findImport ids ibcsd file++                   ibcfiles <- mapM fileToIFileType inputs+                   logParser 3 $ show "loadInputs ibcfiles" ++ show ibcfiles++                   tryLoad True (IBC_REPL True) ibcfiles               _ -> return ()            exports <- findExports @@ -103,6 +115,8 @@          tryLoad keepstate phase [] = warnTotality >> return ()          tryLoad keepstate phase (f : fs)                  = do ist <- getIState+                      logParser 3 $ "tryLoad (keepstate, phase, f : fs)" +++                        show (keepstate, phase, f : fs)                       let maxline                             = case toline of                                 Nothing -> Nothing@@ -141,21 +155,6 @@          fmatch ('.':'/':xs) ys = fmatch xs ys          fmatch xs ('.':'/':ys) = fmatch xs ys          fmatch xs ys = xs == ys--         findNewIBC :: IFileType -> Idris (Maybe IFileType)-         findNewIBC i@(IBC _ _) = return (Just i)-         findNewIBC s@(IDR f) = do ist <- get-                                   ibcsd <- valIBCSubDir ist-                                   let ibc = ibcPathNoFallback ibcsd f-                                   ok <- runIO $ doesFileExist ibc-                                   if ok then return (Just (IBC ibc s))-                                         else return Nothing-         findNewIBC s@(LIDR f) = do ist <- get-                                    ibcsd <- valIBCSubDir ist-                                    let ibc = ibcPathNoFallback ibcsd f-                                    ok <- runIO $ doesFileExist ibc-                                    if ok then return (Just (IBC ibc s))-                                          else return Nothing           -- Like mapM, but give up when there's an error          mapWhileOK f [] = return []
src/Idris/Options.hs view
@@ -1,13 +1,21 @@ {-| Module      : Idris.Options Description : Compiler options for Idris.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -} {-# LANGUAGE DeriveDataTypeable, DeriveFunctor, DeriveGeneric, PatternGuards #-} -module Idris.Options where+module Idris.Options (Codegen(..), ConsoleWidth(..), HowMuchDocs(..), IRFormat(..),+                      LanguageExt(..), LogCat(..), Opt(..), Optimisation(..),+                      OutputFmt(..), REPLPort(..), codegenCats, elabCats, getBC,+                      getClient, getCodegen, getCodegenArgs, getColour, getConsoleWidth,+                      getEvalExpr, getExecScript, getFile, getIBCSubDir, getImportDir,+                      getLanguageExt, getOptLevel, getOptimisation, getOutput,+                      getOutputTy, getPkg, getPkgCheck, getPkgClean, getPkgDir,+                      getPkgIndex, getPkgMkDoc, getPkgREPL, getPkgTest, getPort,+                      getSourceDir, loggingCatsStr, opt, parserCats, strLogCat) where  import Data.Maybe import GHC.Generics (Generic)
src/Idris/Output.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Output Description : Utilities to display Idris' internals and other informtation to the user.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -9,11 +9,17 @@ {-# LANGUAGE FlexibleInstances #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} -module Idris.Output where+module Idris.Output (clearHighlights, emitWarning, formatMessage, idemodePutSExp,+                     iPrintError, iPrintFunTypes, iPrintResult, iPrintTermWithType,+                     iputGoal, iputStr, iputStrLn, iRender, iRenderError,+                     iRenderOutput, iRenderResult, iWarn, prettyDocumentedIst,+                     printUndefinedNames, pshow, renderExternal, sendHighlighting,+                     sendParserHighlighting, warnTotality, writeHighlights,+                     OutputDoc(..), Message(..)) where  import Idris.AbsSyntax import Idris.Colours (hEndColourise, hStartColourise)-import Idris.Core.Evaluate (isDConName, isFnName, isTConName, normaliseAll)+import Idris.Core.Evaluate (normaliseAll) import Idris.Core.TT import Idris.Delaborate import Idris.Docstrings@@ -26,14 +32,15 @@  import Prelude hiding ((<$>)) +import Control.Arrow (first) import Control.Monad.Trans.Except (ExceptT(ExceptT), runExceptT)-import Data.Char (isAlpha) import Data.List (intersperse, nub)-import Data.Maybe (fromMaybe)+import Data.Maybe (fromJust, fromMaybe, isJust, listToMaybe) import System.Console.Haskeline.MonadException (MonadException(controlIO),                                                 RunIO(RunIO)) import System.FilePath (replaceExtension)-import System.IO (Handle, hPutStr, hPutStrLn, stdout)+import System.IO (Handle, hPutStr, hPutStrLn)+import System.IO.Error (tryIOError)  instance MonadException m => MonadException (ExceptT Err m) where     controlIO f = ExceptT $ controlIO $ \(RunIO run) -> let@@ -45,18 +52,141 @@                 renderPretty 1.0 80 .                 fmap (fancifyAnnots ist True) $ pprintErr ist err -iWarn :: FC -> Doc OutputAnnotation -> Idris ()-iWarn fc err =+type OutputDoc = Doc OutputAnnotation++class Message a where+  messageExtent :: a -> FC+  messageText :: a -> OutputDoc+  messageSource :: a -> Maybe String++data Ann = AText String | ATagged OutputAnnotation Ann | ASplit Ann Ann++data SimpleWarning = SimpleWarning FC OutputDoc+instance Message SimpleWarning where+  messageExtent (SimpleWarning extent _) = extent+  messageText (SimpleWarning _ msg) = msg+  messageSource _ = Nothing++formatMessage :: Message w => w -> Idris OutputDoc+formatMessage w = do+    i <- getIState+    maybeSource <- case messageSource w of+                     Just src -> pure (Just src)+                     Nothing  -> readSource fc+    let maybeFormattedSource = maybeSource >>= layoutSource fc (idris_highlightedRegions i)+    return $ layoutMessage (layoutFC fc) maybeFormattedSource (messageText w)+  where+    fc :: FC+    fc = messageExtent w++    layoutFC :: FC -> OutputDoc+    layoutFC fc@(FC fn _ _) | fn /= "" = text (show $ fc) <> colon+    layoutFC _                         = empty++    readSource :: FC -> Idris (Maybe String)+    readSource (FC fn _ _) = do+      result <- runIO $ tryIOError (readFile fn)+      case result of+        Left _  -> pure Nothing+        Right v -> pure (Just v)+    readSource _           = pure Nothing++    layoutSource :: FC -> [(FC, OutputAnnotation)] -> String -> Maybe OutputDoc+    layoutSource (FC fn (si, sj) (ei, ej)) highlights src =+        if haveSource+        then Just source+        else Nothing+      where+        sourceLine :: Maybe String+        sourceLine = listToMaybe . drop (si - 1) . (++ ["<end of file>"]) . lines $ src++        haveSource :: Bool+        haveSource = isJust sourceLine++        line1 :: OutputDoc+        line1 = text $ replicate (length (show si)) ' ' ++ " |"++        lineFC :: FC+        lineFC = FC fn (si, 1) (si, length (fromJust sourceLine))++        intersects :: FC -> FC -> Bool+        intersects (FC fn1 s1 e1) (FC fn2 s2 e2)+          | fn1 /= fn2 = False+          | e1 < s2    = False+          | e2 < s1    = False+          | otherwise  = True+        intersects _ _ = False++        intersection :: FC -> FC -> FC+        intersection fc1@(FC fn1 s1 e1) fc2@(FC _ s2 e2)+          | intersects fc1 fc2 = FC fn1 (max s1 s2) (min e1 e2)+          | otherwise          = NoFC+        intersection _ _       = NoFC++        width :: Ann -> Int+        width (AText s)     = length s+        width (ATagged _ n) = width n+        width (ASplit l r)  = width l + width r++        sourceDoc :: Ann -> OutputDoc+        sourceDoc (AText s)     = text s+        sourceDoc (ATagged a n) = annotate a (sourceDoc n)+        sourceDoc (ASplit l r)  = sourceDoc l <> sourceDoc r++        insertAnnotation :: ((Int, Int), OutputAnnotation) -> Ann -> Ann+        insertAnnotation ((sj, ej), oa) (ATagged tag n) = ATagged tag (insertAnnotation ((sj, ej), oa) n)+        insertAnnotation ((sj, ej), oa) (ASplit l r)+          | w <- width l                   = ASplit (insertAnnotation ((sj, ej), oa) l) (insertAnnotation ((sj - w, ej - w), oa) r)+        insertAnnotation ((sj, ej), oa) a@(AText t)+          | sj <= 1, ej >= width a         = ATagged oa a+          | sj > 1,  sj <= width a         = ASplit (AText $ take (sj - 1) t) (insertAnnotation ((1, ej - sj + 1), oa) (AText $ drop (sj - 1) t))+          | sj == 1, ej >= 1, ej < width a = ASplit (insertAnnotation ((1, ej), oa) (AText $ take ej t)) (AText $ drop ej t)+          | otherwise                      = a++        highlightedSource :: OutputDoc+        highlightedSource = sourceDoc .+                            foldr insertAnnotation (AText $ fromJust sourceLine) .+                            map (\(FC _ (_, sj) (_, ej), ann) -> ((sj, ej), ann)) .+                            map (first (intersection lineFC)) .+                            filter (intersects lineFC . fst) $+                            highlights++        line2 :: OutputDoc+        line2 = text (show si ++ " | ") <> highlightedSource++        indicator :: OutputDoc+        indicator = text (replicate (end - sj + 1) ch) <> ellipsis+          where+            (end, ch, ellipsis) = case (si == ei, sj == ej) of+              (True , True ) -> (ej, '^', empty)+              (True , False) -> (ej, '~', empty)+              (False, _    ) -> (length (fromJust sourceLine), '~', text " ...")++        line3 :: OutputDoc+        line3 = line1 <> text (replicate sj ' ') <> indicator++        source :: OutputDoc+        source = line1 <$$> line2 <$$> line3+    layoutSource _ _ _                                    = Nothing++    layoutMessage :: OutputDoc -> Maybe OutputDoc -> OutputDoc -> OutputDoc+    layoutMessage loc (Just src) err = loc <$$> src <$$> err <$$> empty+    layoutMessage loc Nothing    err = loc </> err++iWarn :: FC -> OutputDoc -> Idris ()+iWarn fc err = emitWarning $ SimpleWarning fc err++emitWarning :: Message w => w -> Idris ()+emitWarning w =   do i <- getIState      case idris_outputmode i of        RawOutput h ->-         do err' <- iRender . fmap (fancifyAnnots i True) $-                      case fc of-                        FC fn _ _ | fn /= "" -> text (show fc) <> colon <//> err-                        _ -> err+         do formattedErr <- formatMessage w+            err' <- iRender . fmap (fancifyAnnots i True) $ formattedErr             hWriteDoc h i err'        IdeMode n h ->-         do err' <- iRender . fmap (fancifyAnnots i True) $ err+         do err' <- iRender . fmap (fancifyAnnots i True) $ messageText w+            let fc = messageExtent w             let (str, spans) = displaySpans err'             runIO . hPutStrLn h $               convSExp "warning" (fc_fname fc, fc_start fc, fc_end fc, str, spans) n@@ -314,6 +444,7 @@       \txt -> "<a href=\"" ++ url ++ "\">" ++ txt ++ "</a>"     decorate HTMLOutput AnnQuasiquote = id     decorate HTMLOutput AnnAntiquote = id+    decorate HTMLOutput (AnnSyntax c) = \txt -> c      decorate LaTeXOutput (AnnName _ (Just TypeOutput) _ _) =       latex "IdrisType"@@ -345,6 +476,13 @@     decorate LaTeXOutput (AnnLink url) = (++ "(\\url{" ++ url ++ "})")     decorate LaTeXOutput AnnQuasiquote = id     decorate LaTeXOutput AnnAntiquote = id+    decorate LaTeXOutput (AnnSyntax c) = \txt ->+      case c of+        "\\" -> "\\textbackslash"+        "{" -> "\\{"+        "}" -> "\\}"+        "%" -> "\\%"+        _ -> c      tag cls docs str = "<span class=\""++cls++"\""++title++">" ++ str ++ "</span>"       where title = maybe "" (\d->" title=\"" ++ d ++ "\"") docs@@ -358,6 +496,7 @@                     [".idris-data { color: red; } ",                      ".idris-type { color: blue; }",                      ".idris-function {color: green; }",+                     ".idris-metavar {color: turquoise; }",                      ".idris-keyword { font-weight: bold; }",                      ".idris-bound { color: purple; }",                      ".idris-implicit { font-style: italic; }",@@ -371,7 +510,8 @@                "\\newcommand{\\"++ cmd ++                "}[1]{\\textcolor{"++ color ++"}{#1}}")              [("IdrisData", "red"), ("IdrisType", "blue"),-              ("IdrisBound", "magenta"), ("IdrisFunction", "green")] +++              ("IdrisBound", "magenta"), ("IdrisFunction", "green"),+              ("IdrisMetavar", "cyan")] ++         ["\\newcommand{\\IdrisKeyword}[1]{{\\underline{#1}}}",          "\\newcommand{\\IdrisImplicit}[1]{{\\itshape \\IdrisBound{#1}}}",          "\n",
src/Idris/Package.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Package Description : Functionality for working with Idris packages.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -10,9 +10,10 @@  import System.Directory import System.Directory (copyFile, createDirectoryIfMissing)+import System.Environment import System.Exit import System.FilePath (addExtension, addTrailingPathSeparator, dropExtension,-                        hasExtension, normalise, takeDirectory, takeExtension,+                        hasExtension, takeDirectory, takeExtension,                         takeFileName, (</>)) import System.IO import System.Process@@ -23,10 +24,8 @@ import Control.Monad.Trans.Except (runExceptT) import Control.Monad.Trans.State.Strict (execStateT) import Data.Either (partitionEithers)-import Data.Either (partitionEithers) import Data.List import Data.List.Split (splitOn)-import Data.Maybe (fromMaybe)  import Idris.AbsSyntax import Idris.Core.TT@@ -38,7 +37,6 @@ import Idris.Options import Idris.Output import Idris.Parser (loadModule)-import Idris.REPL  import Idris.Package.Common import Idris.Package.Parser@@ -204,7 +202,7 @@   pkgdesc        <- parseDesc fp   cd             <- getCurrentDirectory   let pkgDir      = cd </> takeDirectory fp-      outputDir   = cd </> pkgname pkgdesc ++ "_doc"+      outputDir   = cd </> unPkgName (pkgname pkgdesc) ++ "_doc"       popts       = NoREPL : Verbose 1 : idris_opts pkgdesc       mods        = modules pkgdesc       fs          = map (foldl1' (</>) . splitOn "." . showCG) mods@@ -231,10 +229,10 @@           exitWith (ExitFailure 1)         Right ist -> do           iDocDir   <- getIdrisDocDir-          pkgDocDir <- makeAbsolute (iDocDir </> pkgname pkgdesc)+          pkgDocDir <- makeAbsolute (iDocDir </> unPkgName (pkgname pkgdesc))           let out_dir = if install then pkgDocDir else outputDir           when install $ do-              putStrLn $ unwords ["Attempting to install IdrisDocs for", pkgname pkgdesc, "in:", out_dir]+              putStrLn $ unwords ["Attempting to install IdrisDocs for", show $ pkgname pkgdesc, "in:", out_dir]            docRes <- generateDocs ist mods out_dir           case docRes of@@ -336,11 +334,9 @@     getIdrisFiles :: FilePath -> IO [FilePath]     getIdrisFiles dir = do       contents <- getDirectoryContents dir-      let contents' = filter (\fname -> fname /= "." && fname /= "..") contents        -- [ NOTE ] Directory >= 1.2.5.0 introduced `listDirectory` but later versions of directory appear to be causing problems with ghc 7.10.3 and cabal 1.22 in travis. Let's reintroduce the old ranges for directory to be sure. -       files <- forM contents (findRest dir)       return $ filter (isIdrisFile) (concat files) @@ -361,7 +357,7 @@     where       toPath n = foldl1' (</>) $ splitOn "." n -testLib :: Bool -> String -> String -> IO Bool+testLib :: Bool -> PkgName -> String -> IO Bool testLib warn p f     = do d <- getIdrisCRTSDir          gcc <- getCC@@ -372,7 +368,7 @@          case e of             ExitSuccess -> return True             _ -> do if warn-                       then do putStrLn $ "Not building " ++ p +++                       then do putStrLn $ "Not building " ++ show p ++                                           " due to missing library " ++ f                                return False                        else fail $ "Missing library " ++ f@@ -380,7 +376,7 @@ rmIBC :: Name -> IO () rmIBC m = rmFile $ toIBCFile m -rmIdx :: String -> IO ()+rmIdx :: PkgName -> IO () rmIdx p = do let f = pkgIndex p              ex <- doesFileExist f              when ex $ rmFile f@@ -394,10 +390,10 @@ toIBCFile (UN n) = str n ++ ".ibc" toIBCFile (NS n ns) = foldl1' (</>) (reverse (toIBCFile n : map str ns)) -installIBC :: String -> String -> Name -> IO ()+installIBC :: String -> PkgName -> Name -> IO () installIBC dest p m = do     let f = toIBCFile m-    let destdir = dest </> p </> getDest m+    let destdir = dest </> unPkgName p </> getDest m     putStrLn $ "Installing " ++ f ++ " to " ++ destdir     createDirectoryIfMissing True destdir     copyFile f (destdir </> takeFileName f)@@ -406,18 +402,18 @@     getDest (UN n) = ""     getDest (NS n ns) = foldl1' (</>) (reverse (getDest n : map str ns)) -installIdx :: String -> String -> IO ()+installIdx :: String -> PkgName -> IO () installIdx dest p = do   let f = pkgIndex p-  let destdir = dest </> p+  let destdir = dest </> unPkgName p   putStrLn $ "Installing " ++ f ++ " to " ++ destdir   createDirectoryIfMissing True destdir   copyFile f (destdir </> takeFileName f)   return () -installObj :: String -> String -> String -> IO ()+installObj :: String -> PkgName -> String -> IO () installObj dest p o = do-  let destdir = addTrailingPathSeparator (dest </> p)+  let destdir = addTrailingPathSeparator (dest </> unPkgName p)   putStrLn $ "Installing " ++ o ++ " to " ++ destdir   createDirectoryIfMissing True destdir   copyFile o (destdir </> takeFileName o)@@ -442,17 +438,28 @@      return res  -- ------------------------------------------------------- [ Makefile Commands ]+-- | Invoke a Makefile's target with an enriched system environment+makeTarget :: Maybe String -> Maybe String -> IO ()+makeTarget _ Nothing = return ()+makeTarget mtgt (Just s) = do incFlags <- intercalate " " <$> getIncFlags+                              libFlags <- intercalate " " <$> getLibFlags+                              newEnv <- (++ [("IDRIS_INCLUDES", incFlags),+                                             ("IDRIS_LDFLAGS", libFlags)]) <$> getEnvironment+                              let cmdLine = case mtgt of+                                              Nothing -> "make -f " ++ s+                                              Just tgt -> "make -f " ++ s ++ " " ++ tgt+                              (_, _, _, r) <- createProcess (shell cmdLine) { env = Just newEnv }+                              waitForProcess r+                              return ()++ -- | Invoke a Makefile's default target. make :: Maybe String -> IO ()-make Nothing = return ()-make (Just s) = do rawSystem "make" ["-f", s]-                   return ()+make = makeTarget Nothing  -- | Invoke a Makefile's clean target. clean :: Maybe String -> IO ()-clean Nothing = return ()-clean (Just s) = do rawSystem "make" ["-f", s, "clean"]-                    return ()+clean = makeTarget (Just "clean")  -- | Merge an option list representing the command line options into -- those specified for a package description.
src/Idris/Package/Common.hs view
@@ -7,12 +7,13 @@ module Idris.Package.Common where  import Idris.Core.TT (Name)+import Idris.Imports import Idris.Options (Opt(..))  -- | Description of an Idris package. data PkgDesc = PkgDesc {-    pkgname       :: String       -- ^ Name associated with a package.-  , pkgdeps       :: [String]     -- ^ List of packages this package depends on.+    pkgname       :: PkgName      -- ^ Name associated with a package.+  , pkgdeps       :: [PkgName]    -- ^ List of packages this package depends on.   , pkgbrief      :: Maybe String -- ^ Brief description of the package.   , pkgversion    :: Maybe String -- ^ Version string to associate with the package.   , pkgreadme     :: Maybe String -- ^ Location of the README file.@@ -35,6 +36,6 @@  -- | Default settings for package descriptions. defaultPkg :: PkgDesc-defaultPkg = PkgDesc "" [] Nothing Nothing Nothing Nothing+defaultPkg = PkgDesc unInitializedPkgName [] Nothing Nothing Nothing Nothing                         Nothing Nothing Nothing Nothing                         Nothing [] [] Nothing [] "" [] Nothing Nothing []
src/Idris/Package/Parser.hs view
@@ -1,55 +1,32 @@ {-| Module      : Idris.Package.Parser Description : `iPKG` file parser and package description information.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}-{-# LANGUAGE CPP, ConstraintKinds, FlexibleInstances, TypeSynonymInstances #-}+{-# LANGUAGE FlexibleContexts #-} module Idris.Package.Parser where -import Idris.AbsSyntaxTree import Idris.CmdOptions-import Idris.Core.TT+import Idris.Imports import Idris.Package.Common-import Idris.Parser.Helpers hiding (stringLiteral)-import Idris.REPL--import Util.System+import Idris.Parser.Helpers (Parser, Parsing, eol, iName, identifier, isEol,+                             lchar, packageName, parseErrorDoc, reserved,+                             runparser, someSpace, stringLiteral)  import Control.Applicative import Control.Monad.State.Strict import Data.List (union)-import Data.Maybe (fromJust, isNothing) import System.Directory (doesFileExist) import System.Exit import System.FilePath (isValid, takeExtension, takeFileName)+import Text.Megaparsec ((<?>))+import qualified Text.Megaparsec as P+import qualified Text.Megaparsec.Char as P import qualified Text.PrettyPrint.ANSI.Leijen as PP-import Text.Trifecta hiding (char, charLiteral, natural, span, string, symbol,-                      whiteSpace) -type PParser = StateT PkgDesc IdrisInnerParser--instance HasLastTokenSpan PParser where-  getLastTokenSpan = return Nothing--#if MIN_VERSION_base(4,9,0)-instance {-# OVERLAPPING #-} DeltaParsing PParser where-  line = lift line-  {-# INLINE line #-}-  position = lift position-  {-# INLINE position #-}-  slicedWith f (StateT m) = StateT $ \s -> slicedWith (\(a,s') b -> (f a b, s')) $ m s-  {-# INLINE slicedWith #-}-  rend = lift rend-  {-# INLINE rend #-}-  restOfLine = lift restOfLine-  {-# INLINE restOfLine #-}-#endif--instance {-# OVERLAPPING #-} TokenParsing PParser where-  someSpace = many (simpleWhiteSpace <|> singleLineComment <|> multiLineComment) *> pure ()-+type PParser = Parser PkgDesc  parseDesc :: FilePath -> IO PkgDesc parseDesc fp = do@@ -61,8 +38,8 @@       then do         p <- readFile fp         case runparser pPkg defaultPkg fp p of-          Failure (ErrInfo err _) -> fail (show $ PP.plain err)-          Success x -> return x+          Left err -> fail (show $ PP.plain $ parseErrorDoc err)+          Right x -> return x       else do         putStrLn $ unwords [ "The presented iPKG file does not exist:", show fp]         exitWith (ExitFailure 1)@@ -70,30 +47,30 @@ pPkg :: PParser PkgDesc pPkg = do     reserved "package"-    p <- filename-    st <- get-    put (st { pkgname = p })+    p <- pPkgName+    someSpace+    modify $ \st -> st { pkgname = p }     some pClause     st <- get-    eof+    P.eof     return st +pPkgName :: PParser PkgName+pPkgName = (either fail pure . pkgName =<< packageName) <?> "PkgName"  -- | Parses a filename. -- | -- | Treated for now as an identifier or a double-quoted string.-filename :: (MonadicParsing m, HasLastTokenSpan m) => m String+filename :: Parsing m => m String filename = (do-    filename <- token $-        -- Treat a double-quoted string as a filename to support spaces.-        -- This also moves away from tying filenames to identifiers, so-        -- it will also accept hyphens-        -- (https://github.com/idris-lang/Idris-dev/issues/2721)-        stringLiteral-        <|>-        -- Through at least version 0.9.19.1, IPKG executable values were-        -- possibly namespaced identifiers, like foo.bar.baz.-        show <$> fst <$> iName []+                -- Treat a double-quoted string as a filename to support spaces.+                -- This also moves away from tying filenames to identifiers, so+                -- it will also accept hyphens+                -- (https://github.com/idris-lang/Idris-dev/issues/2721)+    filename <- stringLiteral+                -- Through at least version 0.9.19.1, IPKG executable values were+                -- possibly namespaced identifiers, like foo.bar.baz.+            <|> show <$> iName []     case filenameErrorMessage filename of       Just errorMessage -> fail errorMessage       Nothing -> return filename)@@ -121,126 +98,36 @@                     checkThat (path == takeFileName path)                         "filename must contain no directory component" --pClause :: PParser ()-pClause = do reserved "executable"; lchar '=';-             exec <- filename-             st <- get-             put (st { execout = Just exec })--      <|> do reserved "main"; lchar '=';-             main <- fst <$> iName []-             st <- get-             put (st { idris_main = Just main })--      <|> do reserved "sourcedir"; lchar '=';-             src <- fst <$> identifier-             st <- get-             put (st { sourcedir = src })--      <|> do reserved "opts"; lchar '=';-             opts <- stringLiteral-             st <- get-             let args = pureArgParser (words opts)-             put (st { idris_opts = args ++ idris_opts st })--      <|> do reserved "pkgs"; lchar '=';-             ps <- sepBy1 (fst <$> identifier) (lchar ',')-             st <- get-             let pkgs = pureArgParser $ concatMap (\x -> ["-p", x]) ps--             put (st { pkgdeps    = ps `union` (pkgdeps st)-                     , idris_opts = pkgs ++ idris_opts st})--      <|> do reserved "modules"; lchar '=';-             ms <- sepBy1 (fst <$> iName []) (lchar ',')-             st <- get-             put (st { modules = modules st ++ ms })--      <|> do reserved "libs"; lchar '=';-             ls <- sepBy1 (fst <$> identifier) (lchar ',')-             st <- get-             put (st { libdeps = libdeps st ++ ls })--      <|> do reserved "objs"; lchar '=';-             ls <- sepBy1 (fst <$> identifier) (lchar ',')-             st <- get-             put (st { objs = objs st ++ ls })--      <|> do reserved "makefile"; lchar '=';-             mk <- fst <$> iName []-             st <- get-             put (st { makefile = Just (show mk) })--      <|> do reserved "tests"; lchar '=';-             ts <- sepBy1 (fst <$> iName []) (lchar ',')-             st <- get-             put st { idris_tests = idris_tests st ++ ts }--      <|> do reserved "version"-             lchar '='-             vStr <- many (satisfy (not . isEol))-             eol-             someSpace-             st <- get-             put st {pkgversion = Just vStr}--      <|> do reserved "readme"-             lchar '='-             rme <- many (satisfy (not . isEol))-             eol-             someSpace-             st <- get-             put (st { pkgreadme = Just rme })--      <|> do reserved "license"-             lchar '='-             lStr <- many (satisfy (not . isEol))-             eol-             st <- get-             put st {pkglicense = Just lStr}--      <|> do reserved "homepage"-             lchar '='-             www <- many (satisfy (not . isEol))-             eol-             someSpace-             st <- get-             put st {pkghomepage = Just www}--      <|> do reserved "sourceloc"-             lchar '='-             srcpage <- many (satisfy (not . isEol))-             eol-             someSpace-             st <- get-             put st {pkgsourceloc = Just srcpage}--      <|> do reserved "bugtracker"-             lchar '='-             src <- many (satisfy (not . isEol))-             eol-             someSpace-             st <- get-             put st {pkgbugtracker = Just src}+textUntilEol :: Parsing m => m String+textUntilEol = many (P.satisfy (not . isEol)) <* eol <* someSpace -      <|> do reserved "brief"-             lchar '='-             brief <- stringLiteral-             st <- get-             someSpace-             put st {pkgbrief = Just brief}+clause          :: String -> PParser a -> (PkgDesc -> a -> PkgDesc) -> PParser ()+clause name p f = do value <- reserved name *> lchar '=' *> p <* someSpace+                     modify $ \st -> f st value -      <|> do reserved "author"; lchar '=';-             author <- many (satisfy (not . isEol))-             eol-             someSpace-             st <- get-             put st {pkgauthor = Just author}+commaSep   :: Parsing m => m a -> m [a]+commaSep p = P.sepBy1 p (lchar ',') -      <|> do reserved "maintainer"; lchar '=';-             maintainer <- many (satisfy (not . isEol))-             eol-             someSpace-             st <- get-             put st {pkgmaintainer = Just maintainer}+pClause :: PParser ()+pClause = clause "executable" filename (\st v -> st { execout = Just v })+      <|> clause "main" (iName []) (\st v -> st { idris_main = Just v })+      <|> clause "sourcedir" identifier (\st v -> st { sourcedir = v })+      <|> clause "opts" (pureArgParser . words <$> stringLiteral) (\st v -> st { idris_opts = v ++ idris_opts st })+      <|> clause "pkgs" (commaSep (pPkgName <* someSpace)) (\st ps ->+             let pkgs = pureArgParser $ concatMap (\x -> ["-p", show x]) ps+             in st { pkgdeps    = ps `union` pkgdeps st+                   , idris_opts = pkgs ++ idris_opts st })+      <|> clause "modules" (commaSep (iName [])) (\st v -> st { modules = modules st ++ v })+      <|> clause "libs" (commaSep identifier) (\st v -> st { libdeps = libdeps st ++ v })+      <|> clause "objs" (commaSep identifier) (\st v -> st { objs = objs st ++ v })+      <|> clause "makefile" (iName []) (\st v -> st { makefile = Just (show v) })+      <|> clause "tests" (commaSep (iName [])) (\st v -> st { idris_tests = idris_tests st ++ v })+      <|> clause "version" textUntilEol (\st v -> st { pkgversion = Just v })+      <|> clause "readme" textUntilEol (\st v -> st { pkgreadme = Just v })+      <|> clause "license" textUntilEol (\st v -> st { pkglicense = Just v })+      <|> clause "homepage" textUntilEol (\st v -> st { pkghomepage = Just v })+      <|> clause "sourceloc" textUntilEol (\st v -> st { pkgsourceloc = Just v })+      <|> clause "bugtracker" textUntilEol (\st v -> st { pkgbugtracker = Just v })+      <|> clause "brief" stringLiteral (\st v -> st { pkgbrief = Just v })+      <|> clause "author" textUntilEol (\st v -> st { pkgauthor = Just v })+      <|> clause "maintainer" textUntilEol (\st v -> st { pkgmaintainer = Just v })
src/Idris/Parser.hs view
@@ -1,27 +1,27 @@ {-| Module      : Idris.Parser Description : Idris' parser.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}+ {-# LANGUAGE ConstraintKinds, FlexibleContexts, GeneralizedNewtypeDeriving,              PatternGuards #-} {-# OPTIONS_GHC -O0 #-}-module Idris.Parser(module Idris.Parser,-                    module Idris.Parser.Expr,-                    module Idris.Parser.Data,-                    module Idris.Parser.Helpers,-                    module Idris.Parser.Ops) where+-- FIXME: {-# OPTIONS_GHC -fwarn-incomplete-patterns #-}+{-# OPTIONS_GHC -fwarn-unused-imports #-} +module Idris.Parser(IdrisParser(..), ImportInfo(..), addReplSyntax, clearParserWarnings,+                    decl, fixColour, loadFromIFile, loadModule, name, opChars, parseElabShellStep, parseConst, parseExpr, parseImports, parseTactic,+                    runparser, ParseError, parseErrorDoc) where+ import Idris.AbsSyntax hiding (namespace, params) import Idris.Core.Evaluate import Idris.Core.TT-import Idris.Coverage import Idris.Delaborate import Idris.Docstrings hiding (Unchecked) import Idris.DSL-import Idris.Elab.Term import Idris.Elab.Value import Idris.ElabDecls import Idris.Error@@ -33,49 +33,33 @@ import Idris.Parser.Expr import Idris.Parser.Helpers import Idris.Parser.Ops-import Idris.Providers import Idris.Termination import Idris.Unlit -import Util.DynamicLinker-import qualified Util.Pretty as P-import Util.System (readSource, writeSource)--import Paths_idris+import Util.System (readSource)  import Prelude hiding (pi)  import Control.Applicative hiding (Const) import Control.Monad import Control.Monad.State.Strict-import qualified Data.ByteString.UTF8 as UTF8 import Data.Char import Data.Foldable (asum) import Data.Function import Data.Generics.Uniplate.Data (descendM)-import qualified Data.HashSet as HS import Data.List+import qualified Data.List.NonEmpty as NonEmpty import qualified Data.List.Split as Spl import qualified Data.Map as M import Data.Maybe-import Data.Monoid import Data.Ord-import qualified Data.Set as S import qualified Data.Text as T-import Debug.Trace import qualified System.Directory as Dir (makeAbsolute) import System.FilePath-import System.IO-import qualified Text.Parser.Char as Chr-import Text.Parser.Expression-import Text.Parser.LookAhead-import qualified Text.Parser.Token as Tok-import qualified Text.Parser.Token.Highlight as Hi-import Text.PrettyPrint.ANSI.Leijen (Doc, plain)-import qualified Text.PrettyPrint.ANSI.Leijen as ANSI-import Text.Trifecta hiding (Err, char, charLiteral, natural, span, string,-                      stringLiteral, symbol, whiteSpace)-import Text.Trifecta.Delta+import Text.Megaparsec ((<?>))+import qualified Text.Megaparsec as P+import qualified Text.Megaparsec.Char as P+import qualified Text.PrettyPrint.ANSI.Leijen as PP  {- @@@ -98,17 +82,17 @@ @ -} moduleHeader :: IdrisParser (Maybe (Docstring ()), [String], [(FC, OutputAnnotation)])-moduleHeader =     try (do docs <- optional docComment-                           noArgs docs-                           reservedHL "module"-                           (i, ifc) <- identifier-                           option ';' (lchar ';')-                           let modName = moduleName i-                           return (fmap fst docs,-                                   modName,-                                   [(ifc, AnnNamespace (map T.pack modName) Nothing)]))-               <|> try (do lchar '%'; reserved "unqualified"-                           return (Nothing, [], []))+moduleHeader =     P.try (do docs <- optional docComment+                             noArgs docs+                             keyword "module"+                             (i, ifc) <- withExtent identifier+                             P.option ';' (lchar ';')+                             let modName = moduleName i+                             return (fmap fst docs,+                                     modName,+                                     [(ifc, AnnNamespace (map T.pack modName) Nothing)]))+               <|> P.try (do lchar '%'; reserved "unqualified"+                             return (Nothing, [], []))                <|> return (Nothing, moduleName "Main", [])   where moduleName x = case span (/='.') x of                            (x, "")    -> [x]@@ -131,14 +115,12 @@ @  -} import_ :: IdrisParser ImportInfo-import_ = do fc <- getFC-             reservedHL "import"-             reexport <- option False (do reservedHL "public"-                                          return True)-             (id, idfc) <- identifier-             newName <- optional (do reservedHL "as"-                                     identifier)-             option ';' (lchar ';')+import_ = do fc <- extent $ keyword "import"+             reexport <- P.option False (True <$ keyword "public")+             (id, idfc) <- withExtent identifier+             newName <- optional (do keyword "as"+                                     withExtent identifier)+             P.option ';' (lchar ';')              return $ ImportInfo reexport (toPath id)                         (fmap (\(n, fc) -> (toPath n, fc)) newName)                         (map T.pack $ ns id) fc idfc@@ -153,17 +135,17 @@ @  -} prog :: SyntaxInfo -> IdrisParser [PDecl]-prog syn = do whiteSpace-              decls <- many (decl syn)-              let c = concat decls-              case maxline syn of-                   Nothing -> do notOpenBraces; eof-                   _ -> return ()+prog syn = do (decls, fc) <- withExtent $ do+                  whiteSpace+                  decls <- concat <$> many (decl syn)+                  case maxline syn of+                       Nothing -> do notOpenBraces; P.eof+                       _ -> return ()+                  return decls               ist <- get-              fc <- getFC               put ist { idris_parsedSpan = Just (FC (fc_fname fc) (0,0) (fc_end fc)),                         ibc_write = IBCParsedRegion fc : ibc_write ist }-              return c+              return decls  {-| Parses a top-level declaration @@ -186,7 +168,7 @@ @ -} decl :: SyntaxInfo -> IdrisParser [PDecl]-decl syn = try (externalDecl syn)+decl syn = P.try (externalDecl syn)            <|> internalDecl syn            <?> "declaration" @@ -209,13 +191,13 @@               if continue then                  do notEndBlock                     declBody continue-                else try (do notEndBlock-                             declBody continue)+                else P.try (do notEndBlock+                               declBody continue)                      <|> fail "End of readable input"   where declBody :: Bool -> IdrisParser [PDecl]         declBody b =-                   try (implementation True syn)-                   <|> try (openInterface syn)+                   P.try (implementation syn)+                   <|> P.try (openInterface syn)                    <|> declBody' b                    <|> using_ syn                    <|> params syn@@ -264,13 +246,8 @@ externalDecl :: SyntaxInfo -> IdrisParser [PDecl] externalDecl syn = do i <- get                       notEndBlock-                      FC fn start _ <- getFC-                      decls <- declExtensions syn (syntaxRulesList $ syntax_rules i)-                      FC _ _ end <- getFC-                      let outerFC = FC fn start end-                      return $ map (mapPDeclFC (fixFC outerFC)-                                               (fixFCH fn outerFC))-                                   decls+                      (decls, fc@(FC fn _ _)) <- withExtent $ declExtensions syn (syntaxRulesList $ syntax_rules i)+                      return $ map (mapPDeclFC (fixFC fc) (fixFCH fn fc)) decls   where     -- | Fix non-highlighting FCs to prevent spurious error location reports     fixFC :: FC -> FC -> FC@@ -290,9 +267,9 @@ declExtension :: SyntaxInfo -> [Maybe (Name, SynMatch)] -> [Syntax]                  -> IdrisParser [PDecl] declExtension syn ns rules =-  choice $ flip map (groupBy (ruleGroup `on` syntaxSymbols) rules) $ \rs ->+  P.choice $ flip map (groupBy (ruleGroup `on` syntaxSymbols) rules) $ \rs ->     case head rs of -- can never be []-      DeclRule (symb:_) _ -> try $ do+      DeclRule (symb:_) _ -> P.try $ do         n <- extSymbol symb         declExtension syn (n : ns) [DeclRule ss t | (DeclRule (_:ss) t) <- rs]       -- If we have more than one Rule in this bucket, our grammar is@@ -376,18 +353,14 @@     ruleGroup _ _ = False      extSymbol :: SSymbol -> IdrisParser (Maybe (Name, SynMatch))-    extSymbol (Keyword n) = do fc <- reservedFC (show n)-                               highlightP fc AnnKeyword-                               return Nothing+    extSymbol (Keyword n) = Nothing <$ keyword (show n)     extSymbol (Expr n) = do tm <- expr syn                             return $ Just (n, SynTm tm)     extSymbol (SimpleExpr n) = do tm <- simpleExpr syn                                   return $ Just (n, SynTm tm)-    extSymbol (Binding n) = do (b, fc) <- name+    extSymbol (Binding n) = do (b, fc) <- withExtent name                                return $ Just (n, SynBind fc b)-    extSymbol (Symbol s) = do fc <- symbolFC s-                              highlightP fc AnnKeyword-                              return Nothing+    extSymbol (Symbol s) = Nothing <$ highlight AnnKeyword (symbol s)  {-| Parses a syntax extension declaration (and adds the rule to parser state) @@ -396,10 +369,8 @@ @ -} syntaxDecl :: SyntaxInfo -> IdrisParser PDecl-syntaxDecl syn = do s <- syntaxRule syn-                    i <- get-                    put (i `addSyntax` s)-                    fc <- getFC+syntaxDecl syn = do (s, fc) <- withExtent $ syntaxRule syn+                    modify $ \i -> i `addSyntax` s                     return (PSyntax fc s)  -- | Extend an 'IState' with a new syntax extension. See also 'addReplSyntax'.@@ -441,28 +412,28 @@ -} syntaxRule :: SyntaxInfo -> IdrisParser Syntax syntaxRule syn-    = do sty <- try (do+    = do sty <- P.try (do             pushIndent-            sty <- option AnySyntax-                          (do reservedHL "term"; return TermSyntax-                           <|> do reservedHL "pattern"; return PatternSyntax)-            reservedHL "syntax"+            sty <- P.option AnySyntax+                            (TermSyntax <$ keyword "term"+                             <|> PatternSyntax <$ keyword "pattern")+            keyword "syntax"             return sty)          syms <- some syntaxSym-         when (all isExpr syms) $ unexpected "missing keywords in syntax rule"+         when (all isExpr syms) $ P.unexpected . P.Label . NonEmpty.fromList $ "missing keywords in syntax rule"          let ns = mapMaybe getName syms          when (length ns /= length (nub ns))-            $ unexpected "repeated variable in syntax rule"+            $ P.unexpected . P.Label . NonEmpty.fromList $ "repeated variable in syntax rule"          lchar '='          tm <- typeExpr (allowImp syn) >>= uniquifyBinders [n | Binding n <- syms]          terminator          return (Rule (mkSimple syms) tm sty)-  <|> do reservedHL "decl"; reservedHL "syntax"+  <|> do keyword "decl"; keyword "syntax"          syms <- some syntaxSym-         when (all isExpr syms) $ unexpected "missing keywords in syntax rule"+         when (all isExpr syms) $ P.unexpected . P.Label . NonEmpty.fromList $ "missing keywords in syntax rule"          let ns = mapMaybe getName syms          when (length ns /= length (nub ns))-            $ unexpected "repeated variable in syntax rule"+            $ P.unexpected . P.Label . NonEmpty.fromList $ "repeated variable in syntax rule"          lchar '='          openBlock          dec <- some (decl syn)@@ -515,8 +486,8 @@                n' <- gensym n                body' <- fixBind 0 ((n,n'):rens) body                return $ (PPi plic n' nfc ty' body')-        fixBind 0 rens (PLet fc n nfc ty val body)-          | n `elem` userNames = liftM3 (PLet fc n nfc)+        fixBind 0 rens (PLet fc rig n nfc ty val body)+          | n `elem` userNames = liftM3 (PLet fc rig n nfc)                                         (fixBind 0 rens ty)                                         (fixBind 0 rens val)                                         (fixBind 0 rens body)@@ -525,7 +496,7 @@                val' <- fixBind 0 rens val                n' <- gensym n                body' <- fixBind 0 ((n,n'):rens) body-               return $ PLet fc n' nfc ty' val' body'+               return $ PLet fc rig n' nfc ty' val' body'         fixBind 0 rens (PMatchApp fc n) | Just n' <- lookup n rens =           return $ PMatchApp fc n'         -- Also rename resolved quotations, to allow syntax rules to@@ -558,13 +529,13 @@ @  -} syntaxSym :: IdrisParser SSymbol-syntaxSym =    try (do lchar '['; n <- fst <$> name; lchar ']'-                       return (Expr n))-            <|> try (do lchar '{'; n <- fst <$> name; lchar '}'-                        return (Binding n))-            <|> do n <- fst <$> iName []+syntaxSym =    P.try (do lchar '['; n <- name; lchar ']'+                         return (Expr n))+            <|> P.try (do lchar '{'; n <- name; lchar '}'+                          return (Binding n))+            <|> do n <- iName []                    return (Keyword n)-            <|> do sym <- fmap fst stringLiteral+            <|> do sym <- stringLiteral                    return (Symbol sym)             <?> "syntax symbol" @@ -575,11 +546,11 @@ @ -} fnDecl :: SyntaxInfo -> IdrisParser [PDecl]-fnDecl syn = try (do notEndBlock-                     d <- fnDecl' syn-                     i <- get-                     let d' = fmap (desugar syn i) d-                     return [d']) <?> "function declaration"+fnDecl syn = P.try (do notEndBlock+                       d <- fnDecl' syn+                       i <- get+                       let d' = fmap (debindApp syn . desugar syn i) d+                       return [d']) <?> "function declaration"  {-| Parses a function declaration @@ -593,15 +564,14 @@ @ -} fnDecl' :: SyntaxInfo -> IdrisParser PDecl-fnDecl' syn = checkDeclFixity $-              do (doc, argDocs, fc, opts', n, nfc, acc) <- try (do+fnDecl' syn = (checkDeclFixity $+              do (doc, argDocs, fc, opts', n, nfc, acc) <- P.try (do                         pushIndent                         (doc, argDocs) <- docstring syn                         (opts, acc) <- fnOpts-                        (n_in, nfc) <- fnName+                        (n_in, nfc) <- withExtent fnName                         let n = expandNS syn n_in-                        fc <- getFC-                        lchar ':'+                        fc <- extent $ lchar ':'                         return (doc, argDocs, fc, opts, n, nfc, acc))                  ty <- typeExpr (allowImp syn)                  terminator@@ -611,7 +581,7 @@                  return (PTy doc argDocs syn fc opts' n nfc ty)             <|> postulate syn             <|> caf syn-            <|> pattern syn+            <|> pattern syn)             <?> "function declaration"  {-| Parses a series of function and accessbility options@@ -671,42 +641,29 @@ @ -} fnOpt :: IdrisParser FnOpt-fnOpt = do reservedHL "total"; return TotalFn-        <|> do reservedHL "partial"; return PartialFn-        <|> do reservedHL "covering"; return CoveringFn-        <|> do try (lchar '%' *> reserved "export"); c <- fmap fst stringLiteral;-                    return $ CExport c-        <|> do try (lchar '%' *> reserved "no_implicit");-                    return NoImplicit-        <|> do try (lchar '%' *> reserved "inline");-                    return Inlinable-        <|> do try (lchar '%' *> reserved "static");-                    return StaticFn-        <|> do try (lchar '%' *> reserved "assert_total");-               fc <- getFC-               parserWarning fc Nothing (Msg "%assert_total is deprecated. Use the 'assert_total' function instead.")-               return AssertTotal-        <|> do try (lchar '%' *> reserved "error_handler");-                    return ErrorHandler-        <|> do try (lchar '%' *> reserved "error_reverse");-                    return ErrorReverse-        <|> do try (lchar '%' *> reserved "error_reduce");-                    return ErrorReduce-        <|> do try (lchar '%' *> reserved "reflection");-                    return Reflection-        <|> do try (lchar '%' *> reserved "hint");-                    return AutoHint-        <|> do try (lchar '%' *> reserved "overlapping");-                    return OverlappingDictionary+fnOpt = do keyword "total"; return TotalFn+        <|> PartialFn <$ keyword "partial"+        <|> CoveringFn <$ keyword "covering"+        <|> do P.try (lchar '%' *> reserved "export"); c <- stringLiteral;+                      return $ CExport c+        <|> NoImplicit <$ P.try (lchar '%' *> reserved "no_implicit")+        <|> Inlinable <$ P.try (lchar '%' *> reserved "inline")+        <|> StaticFn <$ P.try (lchar '%' *> reserved "static")+        <|> ErrorHandler <$ P.try (lchar '%' *> reserved "error_handler")+        <|> ErrorReverse <$ P.try (lchar '%' *> reserved "error_reverse")+        <|> ErrorReduce  <$ P.try (lchar '%' *> reserved "error_reduce")+        <|> Reflection   <$ P.try (lchar '%' *> reserved "reflection")+        <|> AutoHint     <$ P.try (lchar '%' *> reserved "hint")+        <|> OverlappingDictionary <$ P.try (lchar '%' *> reserved "overlapping")         <|> do lchar '%'; reserved "specialise";-               lchar '['; ns <- sepBy nameTimes (lchar ','); lchar ']';+               lchar '['; ns <- P.sepBy nameTimes (lchar ','); lchar ']';                return $ Specialise ns-        <|> do reservedHL "implicit"; return Implicit+        <|> Implicit <$ keyword "implicit"         <?> "function modifier"   where nameTimes :: IdrisParser (Name, Maybe Int)-        nameTimes = do n <- fst <$> fnName-                       t <- option Nothing (do reds <- fmap fst natural-                                               return (Just (fromInteger reds)))+        nameTimes = do n <- fnName+                       t <- P.option Nothing (do reds <- natural+                                                 return (Just (fromInteger reds)))                        return (n, t)  {-| Parses a postulate@@ -719,22 +676,21 @@ -} postulate :: SyntaxInfo -> IdrisParser PDecl postulate syn = do (doc, ext)-                       <- try $ do (doc, _) <- docstring syn-                                   pushIndent-                                   ext <- ppostDecl-                                   return (doc, ext)+                       <- P.try $ do (doc, _) <- docstring syn+                                     pushIndent+                                     ext <- ppostDecl+                                     return (doc, ext)                    ist <- get                    (opts, acc) <- fnOpts-                   (n_in, nfc) <- fnName+                   (n_in, nfc) <- withExtent fnName                    let n = expandNS syn n_in                    lchar ':'                    ty <- typeExpr (allowImp syn)-                   fc <- getFC-                   terminator+                   fc <- extent $ terminator                    addAcc n acc                    return (PPostulate ext doc syn fc nfc opts n ty)                  <?> "postulate"-   where ppostDecl = do fc <- reservedHL "postulate"; return False+   where ppostDecl = do fc <- keyword "postulate"; return False                  <|> do lchar '%'; reserved "extern"; return True  {-| Parses a using declaration@@ -747,7 +703,7 @@  -} using_ :: SyntaxInfo -> IdrisParser [PDecl] using_ syn =-    do reservedHL "using"+    do keyword "using"        lchar '('; ns <- usingDeclList syn; lchar ')'        openBlock        let uvars = using syn@@ -766,23 +722,24 @@ -} params :: SyntaxInfo -> IdrisParser [PDecl] params syn =-    do reservedHL "parameters"; lchar '('; ns <- typeDeclList syn; lchar ')'+    do (ns, fc) <- withExtent $ do+          keyword "parameters"+          lchar '(' *> typeDeclList syn <* lchar ')'        let ns' = [(n, ty) | (_, n, _, ty) <- ns]        openBlock        let pvars = syn_params syn        ds <- many (decl syn { syn_params = pvars ++ ns' })        closeBlock-       fc <- getFC        return [PParams fc ns' (concat ds)]     <?> "parameters declaration"  -- | Parses an open block openInterface :: SyntaxInfo -> IdrisParser [PDecl] openInterface syn =-    do reservedHL "using"-       reservedHL "implementation"-       fc <- getFC-       ns <- sepBy1 fnName (lchar ',')+    do (ns, fc) <- withExtent $ do+         keyword "using"+         keyword "implementation"+         P.sepBy1 (withExtent fnName) (lchar ',')         openBlock        ds <- many (decl syn)@@ -804,12 +761,10 @@ -} mutual :: SyntaxInfo -> IdrisParser [PDecl] mutual syn =-    do reservedHL "mutual"+    do fc <- extent $ keyword "mutual"        openBlock-       let pvars = syn_params syn        ds <- many (decl (syn { mut_nesting = mut_nesting syn + 1 } ))        closeBlock-       fc <- getFC        return [PMutual fc (concat ds)]     <?> "mutual block" @@ -823,8 +778,8 @@ -} namespace :: SyntaxInfo -> IdrisParser [PDecl] namespace syn =-    do reservedHL "namespace"-       (n, nfc) <- identifier+    do keyword "namespace"+       (n, nfc) <- withExtent identifier        openBlock        ds <- some (decl syn { syn_namespace = n : syn_namespace syn })        closeBlock@@ -838,7 +793,7 @@ @ -} implementationBlock :: SyntaxInfo -> IdrisParser [PDecl]-implementationBlock syn = do reservedHL "where"+implementationBlock syn = do keyword "where"                              openBlock                              ds <- many (fnDecl syn)                              closeBlock@@ -861,16 +816,16 @@ @ -} interfaceBlock :: SyntaxInfo -> IdrisParser (Maybe (Name, FC), Docstring (Either Err PTerm), [PDecl])-interfaceBlock syn = do reservedHL "where"+interfaceBlock syn = do keyword "where"                         openBlock-                        (cn, cd) <- option (Nothing, emptyDocstring) $-                                    try (do (doc, _) <- option noDocs docComment-                                            n <- constructor-                                            return (Just n, doc))+                        (cn, cd) <- P.option (Nothing, emptyDocstring) $+                                    P.try (do (doc, _) <- P.option noDocs docComment+                                              n <- constructor+                                              return (Just n, doc))                         ist <- get                         let cd' = annotate syn ist cd -                        ds <- many (notEndBlock >> try (implementation True syn)+                        ds <- many (notEndBlock >> P.try (implementation syn)                                                    <|> do x <- data_ syn                                                           return [x]                                                    <|> fnDecl syn)@@ -879,7 +834,7 @@                      <?> "interface block"   where     constructor :: IdrisParser (Name, FC)-    constructor = reservedHL "constructor" *> fnName+    constructor = keyword "constructor" *> withExtent fnName      annotate :: SyntaxInfo -> IState -> Docstring () -> Docstring (Either Err PTerm)     annotate syn ist = annotCode $ tryFullExpr syn ist@@ -901,37 +856,42 @@ -} interface_ :: SyntaxInfo -> IdrisParser [PDecl] interface_ syn = do (doc, argDocs, acc)-                      <- try (do (doc, argDocs) <- docstring syn-                                 acc <- accessibility-                                 interfaceKeyword-                                 return (doc, argDocs, acc))-                    fc <- getFC-                    cons <- constraintList syn-                    let cons' = [(c, ty) | (_, c, _, ty) <- cons]-                    (n_in, nfc) <- fnName-                    let n = expandNS syn n_in-                    cs <- many carg-                    fds <- option [(cn, NoFC) | (cn, _, _) <- cs] fundeps-                    (cn, cd, ds) <- option (Nothing, fst noDocs, []) (interfaceBlock syn)+                      <- P.try (do (doc, argDocs) <- docstring syn+                                   acc <- accessibility+                                   interfaceKeyword+                                   return (doc, argDocs, acc))+                    ((cons', n, nfc, cs, fds), fc) <- withExtent $ do+                        cons <- constraintList syn+                        let cons' = [(c, ty) | (_, c, _, ty) <- cons]+                        (n_in, nfc) <- withExtent fnName+                        let n = expandNS syn n_in+                        cs <- many carg+                        fds <- P.option [(cn, NoFC) | (cn, _, _) <- cs] fundeps+                        return (cons', n, nfc, cs, fds)++                    (cn, cd, ds) <- P.option (Nothing, fst noDocs, []) (interfaceBlock syn)                     accData acc n (concatMap declared ds)                     return [PInterface doc syn fc cons' n nfc cs argDocs fds ds cn cd]                  <?> "interface declaration"   where     fundeps :: IdrisParser [(Name, FC)]-    fundeps = do lchar '|'; sepBy name (lchar ',')+    fundeps = do lchar '|'; P.sepBy (withExtent name) (lchar ',') +    classWarning :: String+    classWarning = "Use of a fragile keyword `class`. " +++                   "`class` is provided for those coming from Haskell. " +++                   "Please use `interface` instead, which is equivalent."+     interfaceKeyword :: IdrisParser ()-    interfaceKeyword = reservedHL "interface"-               <|> do reservedHL "class"-                      fc <- getFC-                      parserWarning fc Nothing (Msg "The 'class' keyword is deprecated. Use 'interface' instead.")+    interfaceKeyword = keyword "interface"+               <|> do fc <- extent $ keyword "class"+                      parserWarning fc Nothing (Msg classWarning)      carg :: IdrisParser (Name, FC, PTerm)-    carg = do lchar '('; (i, ifc) <- name; lchar ':'; ty <- expr syn; lchar ')'+    carg = do lchar '('; (i, ifc) <- withExtent name; lchar ':'; ty <- expr syn; lchar ')'               return (i, ifc, ty)-       <|> do (i, ifc) <- name-              fc <- getFC-              return (i, ifc, PType fc)+       <|> do (i, ifc) <- withExtent name+              return (i, ifc, PType ifc)  {-| Parses an interface implementation declaration @@ -945,41 +905,45 @@ ImplementationName ::= '[' Name ']'; @ -}-implementation :: Bool -> SyntaxInfo -> IdrisParser [PDecl]-implementation kwopt syn-                   = do ist <- get-                        (doc, argDocs) <- docstring syn+implementation :: SyntaxInfo -> IdrisParser [PDecl]+implementation syn = do (doc, argDocs) <- docstring syn                         (opts, acc) <- fnOpts-                        if kwopt then optional implementationKeyword-                                 else do implementationKeyword-                                         return (Just ())+                        optional implementationKeyword -                        fc <- getFC-                        en <- optional implementationName-                        cs <- constraintList syn-                        let cs' = [(c, ty) | (_, c, _, ty) <- cs]-                        (cn, cnfc) <- fnName-                        args <- many (simpleExpr syn)+                        ((en, cs, cs', cn, cnfc, args, pnames), fc) <- withExtent $ do+                            en <- optional implementationName+                            cs <- constraintList syn+                            let cs' = [(c, ty) | (_, c, _, ty) <- cs]+                            (cn, cnfc) <- withExtent fnName+                            args <- many (simpleExpr syn)+                            pnames <- implementationUsing+                            return (en, cs, cs', cn, cnfc, args, pnames)+                         let sc = PApp fc (PRef cnfc [cnfc] cn) (map pexp args)                         let t = bindList (\r -> PPi constraint { pcount = r }) cs sc-                        pnames <- implementationUsing+                         ds <- implementationBlock syn                         return [PImplementation doc argDocs syn fc cs' pnames acc opts cn cnfc args [] t en ds]                       <?> "implementation declaration"   where implementationName :: IdrisParser Name-        implementationName = do lchar '['; n_in <- fst <$> fnName; lchar ']'+        implementationName = do lchar '['; n_in <- fnName; lchar ']'                                 let n = expandNS syn n_in                                 return n                              <?> "implementation name"++        instanceWarning :: String+        instanceWarning = "Use of fragile keyword `instance`. " +++                          "`instance` is provided for those coming from Haskell. " +++                          "Please use `implementation` (which is equivalent) instead, or omit it."+         implementationKeyword :: IdrisParser ()-        implementationKeyword = reservedHL "implementation"-                         <|> do reservedHL "instance"-                                fc <- getFC-                                parserWarning fc Nothing (Msg "The 'instance' keyword is deprecated. Use 'implementation' (or omit it) instead.")+        implementationKeyword = keyword "implementation"+                         <|> do fc <- extent $ keyword "instance"+                                parserWarning fc Nothing (Msg instanceWarning)          implementationUsing :: IdrisParser [Name]-        implementationUsing = do reservedHL "using"-                                 ns <- sepBy1 fnName (lchar ',')+        implementationUsing = do keyword "using"+                                 ns <- P.sepBy1 (withExtent fnName) (lchar ',')                                  return (map fst ns)                               <|> return [] @@ -987,7 +951,7 @@ docstring :: SyntaxInfo           -> IdrisParser (Docstring (Either Err PTerm),                           [(Name,Docstring (Either Err PTerm))])-docstring syn = do (doc, argDocs) <- option noDocs docComment+docstring syn = do (doc, argDocs) <- P.option noDocs docComment                    ist <- get                    let doc' = annotCode (tryFullExpr syn ist) doc                        argDocs' = [ (n, annotCode (tryFullExpr syn ist) d)@@ -1020,8 +984,8 @@ -} usingDeclList :: SyntaxInfo -> IdrisParser [Using] usingDeclList syn-               = try (sepBy1 (usingDecl syn) (lchar ','))-             <|> do ns <- sepBy1 (fst <$> name) (lchar ',')+               = P.try (P.sepBy1 (usingDecl syn) (lchar ','))+             <|> do ns <- P.sepBy1 name (lchar ',')                     lchar ':'                     t <- typeExpr (disallowImp syn)                     return (map (\x -> UImplicit x t) ns)@@ -1037,12 +1001,12 @@ @ -} usingDecl :: SyntaxInfo -> IdrisParser Using-usingDecl syn = try (do x <- fst <$> fnName-                        lchar ':'-                        t <- typeExpr (disallowImp syn)-                        return (UImplicit x t))-            <|> do c <- fst <$> fnName-                   xs <- many (fst <$> fnName)+usingDecl syn = P.try (do x <- fnName+                          lchar ':'+                          t <- typeExpr (disallowImp syn)+                          return (UImplicit x t))+            <|> do c <- fnName+                   xs <- many fnName                    return (UConstraint c xs)             <?> "using declaration" @@ -1053,8 +1017,7 @@ @ -} pattern :: SyntaxInfo -> IdrisParser PDecl-pattern syn = do fc <- getFC-                 clause <- clause syn+pattern syn = do (clause, fc) <- withExtent (clause syn)                  return (PClauses fc [] (sMN 2 "_") [clause]) -- collect together later               <?> "pattern" @@ -1065,13 +1028,12 @@ @ -} caf :: SyntaxInfo -> IdrisParser PDecl-caf syn = do reservedHL "let"-             n_in <- fst <$> fnName; let n = expandNS syn n_in+caf syn = do keyword "let"+             (n, fc) <- withExtent (expandNS syn <$> fnName)              pushIndent              lchar '='              t <- indented $ expr syn              terminator-             fc <- getFC              return (PCAF fc n t)            <?> "constant applicative form declaration" @@ -1083,7 +1045,7 @@ -} argExpr :: SyntaxInfo -> IdrisParser PTerm argExpr syn = let syn' = syn { inPattern = True } in-                  try (hsimpleExpr syn') <|> simpleExternalExpr syn'+                  P.try (hsimpleExpr syn') <|> simpleExternalExpr syn'               <?> "argument expression"  {-| Parse a right hand side of a function@@ -1099,17 +1061,15 @@ RHSName ::= '{' FnName '}'; @ -}-rhs :: SyntaxInfo -> Name -> IdrisParser PTerm+rhs :: SyntaxInfo -> Name -> IdrisParser (PTerm, FC) rhs syn n = do lchar '='-               indentPropHolds gtProp-               expr syn+               indentGt+               withExtent $ expr syn         <|> do symbol "?=";-               fc <- getFC-               name <- option n' (do symbol "{"; n <- fst <$> fnName; symbol "}";-                                     return n)+               (name, fc) <- withExtent $ P.option n' (symbol "{" *> fnName <* symbol "}")                r <- expr syn-               return (addLet fc name r)-        <|> impossible+               return (addLet fc name r, fc)+        <|> withExtent impossible         <?> "function right hand side"   where mkN :: Name -> Name         mkN (UN x)   = if (tnull x || not (isAlpha (thead x)))@@ -1119,10 +1079,10 @@         n' :: Name         n' = mkN n         addLet :: FC -> Name -> PTerm -> PTerm-        addLet fc nm (PLet fc' n nfc ty val r) = PLet fc' n nfc ty val (addLet fc nm r)+        addLet fc nm (PLet fc' rig n nfc ty val r) = PLet fc' rig n nfc ty val (addLet fc nm r)         addLet fc nm (PCase fc' t cs) = PCase fc' t (map addLetC cs)           where addLetC (l, r) = (l, addLet fc nm r)-        addLet fc nm r = (PLet fc (sUN "value") NoFC Placeholder r (PMetavar NoFC nm))+        addLet fc nm r = (PLet fc RigW (sUN "value") NoFC Placeholder r (PMetavar NoFC nm))  {-|Parses a function clause @@ -1150,123 +1110,94 @@ -} clause :: SyntaxInfo -> IdrisParser PClause clause syn-         = do wargs <- try (do pushIndent; some (wExpr syn))-              fc <- getFC+           -- unnamed with or function clause (inside a with)+         = do wargs <- P.try (do pushIndent; some (wExpr syn))               ist <- get               n <- case lastParse ist of                         Just t -> return t                         Nothing -> fail "Invalid clause"-              (do r <- rhs syn n-                  let ctxt = tt_ctxt ist+              (do (r, fc) <- rhs syn n                   let wsyn = syn { syn_namespace = [], syn_toplevel = False }-                  (wheres, nmap) <- choice [do x <- whereBlock n wsyn-                                               popIndent-                                               return x,-                                            do terminator-                                               return ([], [])]+                  (wheres, nmap) <-     whereBlock n wsyn <* popIndent+                                    <|> ([], []) <$ terminator                   return $ PClauseR fc wargs r wheres) <|> (do                   popIndent-                  reservedHL "with"-                  wval <- simpleExpr syn-                  pn <- optProof+                  ((wval, pn), fc) <- withExtent $ do+                      keyword "with"+                      wval <- bracketed syn+                      pn <- optProof+                      return (wval, pn)                   openBlock                   ds <- some $ fnDecl syn                   let withs = concat ds                   closeBlock                   return $ PWithR fc wargs wval pn withs)-       <|> do ty <- try (do pushIndent-                            ty <- simpleExpr syn-                            symbol "<=="-                            return ty)-              fc <- getFC-              n_in <- fst <$> fnName; let n = expandNS syn n_in-              r <- rhs syn n-              ist <- get-              let ctxt = tt_ctxt ist+           -- <==+       <|> do ty <- P.try (do pushIndent+                              ty <- simpleExpr syn+                              symbol "<=="+                              return ty)+              (n, fc) <- withExtent (expandNS syn <$> fnName)+              (r, _) <- rhs syn n               let wsyn = syn { syn_namespace = [] }-              (wheres, nmap) <- choice [do x <- whereBlock n wsyn-                                           popIndent-                                           return x,-                                        do terminator-                                           return ([], [])]-              let capp = PLet fc (sMN 0 "match") NoFC+              (wheres, nmap) <-   whereBlock n wsyn <* popIndent+                                <|> ([], []) <$ terminator+              let capp = PLet fc RigW (sMN 0 "match") NoFC                               ty                               (PMatchApp fc n)                               (PRef fc [] (sMN 0 "match"))               ist <- get               put (ist { lastParse = Just n })               return $ PClause fc n capp [] r wheres-       <|> do (l, op, nfc) <- try (do-                pushIndent-                l <- argExpr syn-                (op, nfc) <- operatorFC-                when (op == "=" || op == "?=" ) $-                     fail "infix clause definition with \"=\" and \"?=\" not supported "-                return (l, op, nfc))-              let n = expandNS syn (sUN op)-              r <- argExpr syn-              fc <- getFC-              wargs <- many (wExpr syn)-              (do rs <- rhs syn n+           -- lhs application "with" clause or function clause+       <|> do pushIndent+              (n, nfc, capp, wargs) <- lhs+              modify $ \ist -> ist { lastParse = Just n }+              (do (rs, fc) <- rhs syn n                   let wsyn = syn { syn_namespace = [] }-                  (wheres, nmap) <- choice [do x <- whereBlock n wsyn-                                               popIndent-                                               return x,-                                            do terminator-                                               return ([], [])]-                  ist <- get-                  let capp = PApp fc (PRef nfc [nfc] n) [pexp l, pexp r]-                  put (ist { lastParse = Just n })+                  (wheres, nmap) <-     whereBlock n wsyn <* popIndent+                                    <|> ([], []) <$ terminator                   return $ PClause fc n capp wargs rs wheres) <|> (do                    popIndent-                   reservedHL "with"-                   wval <- bracketed syn-                   pn <- optProof+                   ((wval, pn), fc) <- withExtent $ do+                       keyword "with"+                       wval <- bracketed syn+                       pn <- optProof+                       return (wval, pn)                    openBlock                    ds <- some $ fnDecl syn                    closeBlock-                   ist <- get-                   let capp = PApp fc (PRef fc [] n) [pexp l, pexp r]                    let withs = map (fillLHSD n capp wargs) $ concat ds-                   put (ist { lastParse = Just n })                    return $ PWith fc n capp wargs wval pn withs)-       <|> do pushIndent-              (n_in, nfc) <- fnName; let n = expandNS syn n_in-              fc <- getFC-              args <- many (try (implicitArg (syn { inPattern = True } ))-                            <|> try (constraintArg (syn { inPattern = True }))-                            <|> (fmap pexp (argExpr syn)))-              wargs <- many (wExpr syn)-              let capp = PApp fc (PRef nfc [nfc] n) args-              (do r <- rhs syn n-                  ist <- get-                  let ctxt = tt_ctxt ist-                  let wsyn = syn { syn_namespace = [] }-                  (wheres, nmap) <- choice [do x <- whereBlock n wsyn-                                               popIndent-                                               return x,-                                            do terminator-                                               return ([], [])]-                  ist <- get-                  put (ist { lastParse = Just n })-                  return $ PClause fc n capp wargs r wheres) <|> (do-                   reservedHL "with"-                   ist <- get-                   put (ist { lastParse = Just n })-                   wval <- bracketed syn-                   pn <- optProof-                   openBlock-                   ds <- some $ fnDecl syn-                   let withs = map (fillLHSD n capp wargs) $ concat ds-                   closeBlock-                   popIndent-                   return $ PWith fc n capp wargs wval pn withs)       <?> "function clause"   where-    optProof = option Nothing (do reservedHL "proof"-                                  n <- fnName-                                  return (Just n))+    lhsInfixApp :: IdrisParser (Name, FC, [PArg], [PTerm])+    lhsInfixApp = do l <- argExpr syn+                     (op, nfc) <- withExtent symbolicOperator+                     when (op == "=" || op == "?=" ) $+                          fail "infix clause definition with \"=\" and \"?=\" not supported "+                     let n = expandNS syn (sUN op)+                     r <- argExpr syn+                     wargs <- many (wExpr syn)+                     return (n, nfc, [pexp l, pexp r], wargs) +    lhsPrefixApp :: IdrisParser (Name, FC, [PArg], [PTerm])+    lhsPrefixApp = do (n, nfc) <- withExtent (expandNS syn <$> fnName)+                      args <- many (P.try (implicitArg (syn { inPattern = True } ))+                                    <|> P.try (constraintArg (syn { inPattern = True }))+                                    <|> (fmap pexp (argExpr syn)))+                      wargs <- many (wExpr syn)+                      return (n, nfc, args, wargs)++    lhs :: IdrisParser (Name, FC, PTerm, [PTerm])+    lhs = do ((n, nfc, args, wargs), lhs_fc) <- withExtent (P.try lhsInfixApp <|> lhsPrefixApp)+             let capp = PApp lhs_fc (PRef nfc [nfc] n) args+             return (n, nfc, capp, wargs)++    optProof = P.option Nothing (do keyword "proof"+                                    n <- withExtent fnName+                                    return (Just n))+     fillLHS :: Name -> PTerm -> [PTerm] -> PClause -> PClause     fillLHS n capp owargs (PClauseR fc wargs v ws)        = PClause fc n capp (owargs ++ wargs) v ws@@ -1298,7 +1229,7 @@ -} whereBlock :: Name -> SyntaxInfo -> IdrisParser ([PDecl], [(Name, Name)]) whereBlock n syn-    = do reservedHL "where"+    = do keyword "where"          ds <- indentedBlock1 (decl syn)          let dns = concatMap (concatMap declared) ds          return (concat ds, map (\x -> (x, decoration syn x)) dns)@@ -1317,7 +1248,7 @@ @ -} codegen_ :: IdrisParser Codegen-codegen_ = do n <- fst <$> identifier+codegen_ = do n <- identifier               return (Via IBCFormat (map toLower n))        <|> do reserved "Bytecode"; return Bytecode        <?> "code generation language"@@ -1356,74 +1287,73 @@ @ -} directive :: SyntaxInfo -> IdrisParser [PDecl]-directive syn = do try (lchar '%' *> reserved "lib")+directive syn = do P.try (lchar '%' *> reserved "lib")                    cgn <- codegen_-                   lib <- fmap fst stringLiteral+                   lib <- stringLiteral                    return [PDirective (DLib cgn lib)]-             <|> do try (lchar '%' *> reserved "link")-                    cgn <- codegen_; obj <- fst <$> stringLiteral+             <|> do P.try (lchar '%' *> reserved "link")+                    cgn <- codegen_; obj <- stringLiteral                     return [PDirective (DLink cgn obj)]-             <|> do try (lchar '%' *> reserved "flag")-                    cgn <- codegen_; flag <- fst <$> stringLiteral+             <|> do P.try (lchar '%' *> reserved "flag")+                    cgn <- codegen_; flag <- stringLiteral                     return [PDirective (DFlag cgn flag)]-             <|> do try (lchar '%' *> reserved "include")+             <|> do P.try (lchar '%' *> reserved "include")                     cgn <- codegen_-                    hdr <- fst <$> stringLiteral+                    hdr <- stringLiteral                     return [PDirective (DInclude cgn hdr)]-             <|> do try (lchar '%' *> reserved "hide"); n <- fst <$> fnName+             <|> do P.try (lchar '%' *> reserved "hide"); n <- fnName                     return [PDirective (DHide n)]-             <|> do try (lchar '%' *> reserved "freeze"); n <- fst <$> iName []+             <|> do P.try (lchar '%' *> reserved "freeze"); n <- iName []                     return [PDirective (DFreeze n)]-             <|> do try (lchar '%' *> reserved "thaw"); n <- fst <$> iName []+             <|> do P.try (lchar '%' *> reserved "thaw"); n <- iName []                     return [PDirective (DThaw n)]              -- injectivity assertins are intended for debugging purposes              -- only, and won't be documented/could be removed at any point-             <|> do try (lchar '%' *> reserved "assert_injective"); n <- fst <$> fnName+             <|> do P.try (lchar '%' *> reserved "assert_injective"); n <- fnName                     return [PDirective (DInjective n)]              -- Assert totality of something after definition. This is              -- here as a debugging aid, so commented out...---              <|> do try (lchar '%' *> reserved "assert_set_total"); n <- fst <$> fnName+--              <|> do P.try (lchar '%' *> reserved "assert_set_total"); n <- fst <$> fnName --                     return [PDirective (DSetTotal n)]-             <|> do try (lchar '%' *> reserved "access")+             <|> do P.try (lchar '%' *> reserved "access")                     acc <- accessibility                     ist <- get                     put ist { default_access = acc }                     return [PDirective (DAccess acc)]-             <|> do try (lchar '%' *> reserved "default"); tot <- totality+             <|> do P.try (lchar '%' *> reserved "default"); tot <- totality                     i <- get                     put (i { default_total = tot } )                     return [PDirective (DDefault tot)]-             <|> do try (lchar '%' *> reserved "logging")-                    i <- fst <$> natural+             <|> do P.try (lchar '%' *> reserved "logging")+                    i <- natural                     return [PDirective (DLogging i)]-             <|> do try (lchar '%' *> reserved "dynamic")-                    libs <- sepBy1 (fmap fst stringLiteral) (lchar ',')+             <|> do P.try (lchar '%' *> reserved "dynamic")+                    libs <- P.sepBy1 stringLiteral (lchar ',')                     return [PDirective (DDynamicLibs libs)]-             <|> do try (lchar '%' *> reserved "name")-                    (ty, tyFC) <- fnName-                    ns <- sepBy1 name (lchar ',')+             <|> do P.try (lchar '%' *> reserved "name")+                    (ty, tyFC) <- withExtent fnName+                    ns <- P.sepBy1 (withExtent name) (lchar ',')                     return [PDirective (DNameHint ty tyFC ns)]-             <|> do try (lchar '%' *> reserved "error_handlers")-                    (fn, nfc) <- fnName-                    (arg, afc) <- fnName-                    ns <- sepBy1 name (lchar ',')+             <|> do P.try (lchar '%' *> reserved "error_handlers")+                    (fn, nfc) <- withExtent fnName+                    (arg, afc) <- withExtent fnName+                    ns <- P.sepBy1 (withExtent name) (lchar ',')                     return [PDirective (DErrorHandlers fn nfc arg afc ns) ]-             <|> do try (lchar '%' *> reserved "language"); ext <- pLangExt;+             <|> do P.try (lchar '%' *> reserved "language"); ext <- pLangExt;                     return [PDirective (DLanguage ext)]-             <|> do try (lchar '%' *> reserved "deprecate")-                    n <- fst <$> fnName-                    alt <- option "" (fst <$> stringLiteral)+             <|> do P.try (lchar '%' *> reserved "deprecate")+                    n <- fnName+                    alt <- P.option "" stringLiteral                     return [PDirective (DDeprecate n alt)]-             <|> do try (lchar '%' *> reserved "fragile")-                    n <- fst <$> fnName-                    alt <- option "" (fst <$> stringLiteral)+             <|> do P.try (lchar '%' *> reserved "fragile")+                    n <- fnName+                    alt <- P.option "" stringLiteral                     return [PDirective (DFragile n alt)]-             <|> do fc <- getFC-                    try (lchar '%' *> reserved "used")-                    fn <- fst <$> fnName-                    arg <- fst <$> iName []+             <|> do fc <- extent $ P.try (lchar '%' *> reserved "used")+                    fn <- fnName+                    arg <- iName []                     return [PDirective (DUsed fc fn arg)]-             <|> do try (lchar '%' *> reserved "auto_implicits")+             <|> do P.try (lchar '%' *> reserved "auto_implicits")                     b <- on_off                     return [PDirective (DAutoImplicits b)]              <?> "directive"@@ -1448,9 +1378,9 @@ -} totality :: IdrisParser DefaultTotality totality-        = do reservedHL "total";   return DefaultCheckingTotal-      <|> do reservedHL "partial"; return DefaultCheckingPartial-      <|> do reservedHL "covering"; return DefaultCheckingCovering+        = do keyword "total";   return DefaultCheckingTotal+      <|> do keyword "partial"; return DefaultCheckingPartial+      <|> do keyword "covering"; return DefaultCheckingCovering  {-| Parses a type provider @@ -1460,26 +1390,21 @@ @  -} provider :: SyntaxInfo -> IdrisParser [PDecl]-provider syn = do doc <- try (do (doc, _) <- docstring syn-                                 fc1 <- getFC-                                 lchar '%'-                                 fc2 <- reservedFC "provide"-                                 highlightP (spanFC fc1 fc2) AnnKeyword-                                 return doc)+provider syn = do doc <- P.try (do (doc, _) <- docstring syn+                                   highlight AnnKeyword $ lchar '%' *> reserved "provide"+                                   return doc)                   provideTerm doc <|> providePostulate doc                <?> "type provider"   where provideTerm doc =-          do lchar '('; (n, nfc) <- fnName; lchar ':'; t <- typeExpr syn; lchar ')'-             fc <- getFC-             reservedHL "with"-             e <- expr syn <?> "provider expression"+          do lchar '('; (n, nfc) <- withExtent fnName; lchar ':'; t <- typeExpr syn; lchar ')'+             keyword "with"+             (e, fc) <- withExtent (expr syn) <?> "provider expression"              return  [PProvider doc syn fc nfc (ProvTerm t e) n]         providePostulate doc =-          do reservedHL "postulate"-             (n, nfc) <- fnName-             fc <- getFC-             reservedHL "with"-             e <- expr syn <?> "provider expression"+          do keyword "postulate"+             (n, nfc) <- withExtent fnName+             keyword "with"+             (e, fc) <- withExtent (expr syn) <?> "provider expression"              return [PProvider doc syn fc nfc (ProvPostulate e) n]  {-| Parses a transform@@ -1489,14 +1414,13 @@ @ -} transform :: SyntaxInfo -> IdrisParser [PDecl]-transform syn = do try (lchar '%' *> reserved "transform")+transform syn = do P.try (lchar '%' *> reserved "transform")                     -- leave it unchecked, until we work out what this should                     -- actually mean... --                     safety <- option True (do reserved "unsafe" --                                               return False)                    l <- expr syn-                   fc <- getFC-                   symbol "==>"+                   fc <- extent $ symbol "==>"                    r <- expr syn                    return [PTransform fc False l r]                 <?> "transform"@@ -1509,31 +1433,27 @@ -} runElabDecl :: SyntaxInfo -> IdrisParser PDecl runElabDecl syn =-  do kwFC <- try (do fc <- getFC-                     lchar '%'-                     fc' <- reservedFC "runElab"-                     return (spanFC fc fc'))+  do kwFC <- P.try (highlight AnnKeyword (extent $ lchar '%' *> reserved "runElab"))      script <- expr syn <?> "elaborator script"-     highlightP kwFC AnnKeyword      return $ PRunElabDecl kwFC script (syn_namespace syn)   <?> "top-level elaborator script"  {- * Loading and parsing -} {-| Parses an expression from input -}-parseExpr :: IState -> String -> Result PTerm+parseExpr :: IState -> String -> Either ParseError PTerm parseExpr st = runparser (fullExpr defaultSyntax) st "(input)"  {-| Parses a constant form input -}-parseConst :: IState -> String -> Result Const-parseConst st = runparser (fmap fst constant) st "(input)"+parseConst :: IState -> String -> Either ParseError Const+parseConst st = runparser constant st "(input)"  {-| Parses a tactic from input -}-parseTactic :: IState -> String -> Result PTactic+parseTactic :: IState -> String -> Either ParseError PTactic parseTactic st = runparser (fullTactic defaultSyntax) st "(input)"  {-| Parses a do-step from input (used in the elab shell) -}-parseElabShellStep :: IState -> String -> Result (Either ElabShellCmd PDo)-parseElabShellStep ist = runparser (fmap Right (do_ defaultSyntax) <|> fmap Left elabShellCmd) ist "(input)"+parseElabShellStep :: IState -> String -> Either ParseError (Either ElabShellCmd PDo)+parseElabShellStep ist = runparser (Right <$> do_ defaultSyntax <|> Left <$> elabShellCmd) ist "(input)"   where elabShellCmd = char ':' >>                        (reserved "qed"     >> pure EQED       ) <|>                        (reserved "abandon" >> pure EAbandon   ) <|>@@ -1544,8 +1464,8 @@                        (expressionTactic ["t", "type"] ECheck) <|>                        (expressionTactic ["search"] ESearch   ) <|>                        (do reserved "doc"-                           doc <- (Right . fst <$> constant) <|> (Left . fst <$> fnName)-                           eof+                           doc <- (Right <$> constant) <|> (Left <$> fnName)+                           P.eof                            return (EDocStr doc))                        <?> "elab command"         expressionTactic cmds tactic =@@ -1553,29 +1473,29 @@               t <- spaced (expr defaultSyntax)               i <- get               return $ tactic (desugar defaultSyntax i t)-        spaced parser = indentPropHolds gtProp *> parser+        spaced parser = indentGt *> parser  -- | Parse module header and imports-parseImports :: FilePath -> String -> Idris (Maybe (Docstring ()), [String], [ImportInfo], Maybe Delta)+parseImports :: FilePath -> String -> Idris (Maybe (Docstring ()), [String], [ImportInfo], Maybe Mark) parseImports fname input     = do i <- getIState-         case parseString (runInnerParser (evalStateT imports i)) (Directed (UTF8.fromString fname) 0 0 0 0) input of-              Failure (ErrInfo err _) -> fail (show err)-              Success (x, annots, i) ->+         case runparser imports i fname input of+              Left err -> formatMessage err >>= ifail . show+              Right (x, annots, i) ->                 do putIState i                    fname' <- runIO $ Dir.makeAbsolute fname                    sendHighlighting $ addPath annots fname'                    return x   where imports :: IdrisParser ((Maybe (Docstring ()), [String],                                  [ImportInfo],-                                 Maybe Delta),+                                 Maybe Mark),                                 [(FC, OutputAnnotation)], IState)         imports = do optional shebang                      whiteSpace                      (mdoc, mname, annots) <- moduleHeader                      ps_exp        <- many import_                      mrk           <- mark-                     isEof         <- lookAheadMatches eof+                     isEof         <- lookAheadMatches P.eof                      let mrk' = if isEof                                    then Nothing                                    else Just mrk@@ -1585,11 +1505,6 @@                      let ps = ps_exp -- imp "Builtins" : imp "Prelude" : ps_exp                      return ((mdoc, mname, ps, mrk'), annots, i) -        imp m = ImportInfo False (toPath m)-                           Nothing [] NoFC NoFC-        ns = Spl.splitOn "."-        toPath = foldl1' (</>) . ns-         addPath :: [(FC, OutputAnnotation)] -> FilePath -> [(FC, OutputAnnotation)]         addPath [] _ = []         addPath ((fc, AnnNamespace ns Nothing) : annots) path =@@ -1597,58 +1512,66 @@         addPath (annot:annots) path = annot : addPath annots path          shebang :: IdrisParser ()-        shebang = string "#!" *> many (satisfy $ not . isEol) *> eol *> pure ()---- | There should be a better way of doing this...-findFC :: Doc -> (FC, String)-findFC x = let s = show (plain x) in findFC' s-  where findFC' s = case span (/= ':') s of-                      -- Horrid kludge to prevent crashes on Windows-                      (prefix, ':':'\\':rest) ->-                        case findFC' rest of-                          (NoFC, msg) -> (NoFC, msg)-                          (FileFC f, msg) -> (FileFC (prefix ++ ":\\" ++ f), msg)-                          (FC f start end, msg) -> (FC (prefix ++ ":\\" ++ f) start end, msg)-                      (failname, ':':rest) -> case span isDigit rest of-                        (line, ':':rest') -> case span isDigit rest' of-                          (col, ':':msg) -> let pos = (read line, read col) in-                                                (FC failname pos pos, msg)+        shebang = string "#!" *> many (P.satisfy $ not . isEol) *> eol *> pure ()  -- | Check if the coloring matches the options and corrects if necessary-fixColour :: Bool -> ANSI.Doc -> ANSI.Doc-fixColour False doc = ANSI.plain doc+fixColour :: Bool -> PP.Doc -> PP.Doc+fixColour False doc = PP.plain doc fixColour True doc  = doc  -- | A program is a list of declarations, possibly with associated -- documentation strings.-parseProg :: SyntaxInfo -> FilePath -> String -> Maybe Delta ->-             Idris [PDecl]+parseProg :: SyntaxInfo -> FilePath -> String -> Maybe Mark -> Idris [PDecl] parseProg syn fname input mrk     = do i <- getIState          case runparser mainProg i fname input of-            Failure (ErrInfo doc _)     -> do -- FIXME: Get error location from trifecta-                                  -- this can't be the solution!-                                  -- Issue #1575 on the issue tracker.-                                  --    https://github.com/idris-lang/Idris-dev/issues/1575-                                  let (fc, msg) = findFC doc-                                  i <- getIState-                                  case idris_outputmode i of-                                    RawOutput h  -> iputStrLn (show $ fixColour (idris_colourRepl i) doc)-                                    IdeMode n h -> iWarn fc (P.text msg)-                                  putIState (i { errSpan = Just fc })-                                  return []-            Success (x, i)  -> do putIState i-                                  reportParserWarnings-                                  return $ collect x+            Left err -> do emitWarning err+                           i <- getIState+                           putIState (i { errSpan = Just (messageExtent err) })+                           return []+            Right (x, i)  -> do putIState i+                                reportParserWarnings+                                return $ collect x   where mainProg :: IdrisParser ([PDecl], IState)         mainProg = case mrk of                         Nothing -> do i <- get; return ([], i)                         Just mrk -> do-                          release mrk+                          restore mrk                           ds <- prog syn                           i' <- get                           return (ds, i') +-- | Collect 'PClauses' with the same function name+collect :: [PDecl] -> [PDecl]+collect (c@(PClauses _ o _ _) : ds)+    = clauses (cname c) [] (c : ds)+  where clauses :: Maybe Name -> [PClause] -> [PDecl] -> [PDecl]+        clauses j@(Just n) acc (PClauses fc _ _ [PClause fc' n' l ws r w] : ds)+           | n == n' = clauses j (PClause fc' n' l ws r (collect w) : acc) ds+        clauses j@(Just n) acc (PClauses fc _ _ [PWith fc' n' l ws r pn w] : ds)+           | n == n' = clauses j (PWith fc' n' l ws r pn (collect w) : acc) ds+        clauses (Just n) acc xs = PClauses (fcOf c) o n (reverse acc) : collect xs+        clauses Nothing acc (x:xs) = collect xs+        clauses Nothing acc [] = []++        cname :: PDecl -> Maybe Name+        cname (PClauses fc _ _ [PClause _ n _ _ _ _]) = Just n+        cname (PClauses fc _ _ [PWith   _ n _ _ _ _ _]) = Just n+        cname (PClauses fc _ _ [PClauseR _ _ _ _]) = Nothing+        cname (PClauses fc _ _ [PWithR _ _ _ _ _]) = Nothing+        fcOf :: PDecl -> FC+        fcOf (PClauses fc _ _ _) = fc+collect (PParams f ns ps : ds) = PParams f ns (collect ps) : collect ds+collect (POpenInterfaces f ns ps : ds) = POpenInterfaces f ns (collect ps) : collect ds+collect (PMutual f ms : ds) = PMutual f (collect ms) : collect ds+collect (PNamespace ns fc ps : ds) = PNamespace ns fc (collect ps) : collect ds+collect (PInterface doc f s cs n nfc ps pdocs fds ds cn cd : ds')+    = PInterface doc f s cs n nfc ps pdocs fds (collect ds) cn cd : collect ds'+collect (PImplementation doc argDocs f s cs pnames acc opts n nfc ps pextra t en ds : ds')+    = PImplementation doc argDocs f s cs pnames acc opts n nfc ps pextra t en (collect ds) : collect ds'+collect (d : ds) = d : collect ds+collect [] = []+ {-| Load idris module and show error if something wrong happens -} loadModule :: FilePath -> IBCPhase -> Idris (Maybe String) loadModule f phase@@ -1664,7 +1587,7 @@    = do i <- getIState         let file = takeWhile (/= ' ') f         ibcsd <- valIBCSubDir i-        ids <- allImportDirs+        ids <- rankedImportDirs file         fp <- findImport ids ibcsd file         if file `elem` imported i           then do logParser 1 $ "Already read " ++ file@@ -1685,6 +1608,7 @@ loadFromIFile :: Bool -> IBCPhase -> IFileType -> Maybe Int -> Idris () loadFromIFile reexp phase i@(IBC fn src) maxline    = do logParser 1 $ "Skipping " ++ getSrcFile i+        logParser 3 $ "loadFromIFile i" ++ show i         idrisCatch (loadIBC reexp phase fn)                 (\err -> ierror $ LoadingFailed fn err)   where@@ -1717,7 +1641,7 @@                   (mdocs, mname, imports_in, pos) <- parseImports f file                   ai <- getAutoImports                   let imports = map (\n -> ImportInfo True n Nothing [] NoFC NoFC) ai ++ imports_in-                  ids <- allImportDirs+                  ids <- rankedImportDirs f                   ibcsd <- valIBCSubDir i                   mapM_ (\(re, f, ns, nfc) ->                                do fp <- findImport ids ibcsd f@@ -1748,8 +1672,8 @@                         ]                       prep = map T.pack . reverse . Spl.splitOn [pathSeparator]                       aliasNames = [ (alias, fc)-                                   | ImportInfo { import_rename = Just (alias, _)-                                                , import_location = fc } <- imports+                                   | ImportInfo { import_rename = Just (alias, fc)+                                                } <- imports                                    ]                       histogram = groupBy ((==) `on` fst) . sortBy (comparing fst) $ aliasNames                   case map head . filter ((/= 1) . length) $ histogram of@@ -1872,6 +1796,7 @@     toMutual :: PDecl -> PDecl     toMutual m@(PMutual _ d) = m     toMutual (PNamespace x fc ds) = PNamespace x fc (map toMutual ds)+    toMutual (POpenInterfaces f ns ds) = POpenInterfaces f ns (map toMutual ds)     toMutual x = let r = PMutual (fileFC "single mutual") [x] in                  case x of                    PClauses{} -> r@@ -1893,8 +1818,6 @@  {-| Adds names to hide list -} addHides :: Ctxt Accessibility -> Idris ()-addHides xs = do i <- getIState-                 let defh = default_access i-                 mapM_ doHide (toAlist xs)+addHides xs = mapM_ doHide (toAlist xs)   where doHide (n, a) = do setAccessibility n a                            addIBC (IBCAccess n a)
src/Idris/Parser/Data.hs view
@@ -1,18 +1,17 @@ {-| Module      : Idris.Parser.Data Description : Parse Data declarations.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}-{-# LANGUAGE ConstraintKinds, GeneralizedNewtypeDeriving, PatternGuards #-}+{-# LANGUAGE ConstraintKinds, FlexibleContexts, GeneralizedNewtypeDeriving,+             MultiParamTypeClasses, PatternGuards #-} module Idris.Parser.Data where  import Idris.AbsSyntax-import Idris.Core.Evaluate import Idris.Core.TT import Idris.Docstrings-import Idris.DSL import Idris.Options import Idris.Parser.Expr import Idris.Parser.Helpers@@ -21,33 +20,20 @@ import Prelude hiding (pi)  import Control.Applicative-import Control.Monad import Control.Monad.State.Strict-import qualified Data.ByteString.UTF8 as UTF8-import Data.Char-import qualified Data.HashSet as HS import Data.List-import qualified Data.List.Split as Spl import Data.Maybe-import Data.Monoid-import qualified Data.Text as T-import Debug.Trace-import qualified Text.Parser.Char as Chr-import Text.Parser.Expression-import Text.Parser.LookAhead-import qualified Text.Parser.Token as Tok-import qualified Text.Parser.Token.Highlight as Hi-import Text.Trifecta hiding (Err, char, charLiteral, natural, span, string,-                      stringLiteral, symbol, whiteSpace)-import Text.Trifecta.Delta+import Text.Megaparsec ((<?>))+import qualified Text.Megaparsec as P  {- | Parses a record type declaration Record ::=     DocComment Accessibility? 'record' FnName TypeSig 'where' OpenBlock Constructor KeepTerminator CloseBlock; -} record :: SyntaxInfo -> IdrisParser PDecl-record syn = do (doc, paramDocs, acc, opts) <- try (do-                      (doc, paramDocs) <- option noDocs docComment+record syn = (appExtent $ do+                (doc, paramDocs, acc, opts) <- P.try (do+                      (doc, paramDocs) <- P.option noDocs docComment                       ist <- get                       let doc' = annotCode (tryFullExpr syn ist) doc                           paramDocs' = [ (n, annotCode (tryFullExpr syn ist) d)@@ -56,40 +42,29 @@                       opts <- dataOpts []                       co <- recordI                       return (doc', paramDocs', acc, opts ++ co))-                fc <- getFC-                (tyn_in, nfc) <- fnName+                (tyn_in, nfc) <- withExtent fnName                 let tyn = expandNS syn tyn_in                 let rsyn = syn { syn_namespace = show (nsroot tyn) :                                                     syn_namespace syn }-                params <- manyTill (recordParameter rsyn) (reservedHL "where")+                params <- P.manyTill (recordParameter rsyn) (keyword "where")                 (fields, cname, cdoc) <- indentedBlockS $ recordBody rsyn tyn                 let fnames = map (expandNS rsyn) (mapMaybe getName fields)                 case cname of                      Just cn' -> accData acc tyn (fst cn' : fnames)                      Nothing -> return ()-                return $ PRecord doc rsyn fc opts tyn nfc params paramDocs fields cname cdoc syn-             <?> "record type declaration"+                return $ \fc -> PRecord doc rsyn fc opts tyn nfc params paramDocs fields cname cdoc syn)+              <?> "record type declaration"   where-    getRecNames :: SyntaxInfo -> PTerm -> [Name]-    getRecNames syn (PPi _ n _ _ sc) = [expandNS syn n, expandNS syn (mkType n)]-                                         ++ getRecNames syn sc-    getRecNames _ _ = []-     getName (Just (n, _), _, _, _) = Just n     getName _ = Nothing -    toFreeze :: Maybe Accessibility -> Maybe Accessibility-    toFreeze (Just Frozen) = Just Private-    toFreeze x = x-     recordBody :: SyntaxInfo -> Name -> IdrisParser ([((Maybe (Name, FC)), Plicity, PTerm, Maybe (Docstring (Either Err PTerm)))], Maybe (Name, FC), Docstring (Either Err PTerm))     recordBody syn tyn = do         ist <- get-        fc  <- getFC -        (constructorName, constructorDoc) <- option (Nothing, emptyDocstring)-                                             (do (doc, _) <- option noDocs docComment-                                                 n <- constructor+        (constructorName, constructorDoc) <- P.option (Nothing, emptyDocstring)+                                             (do (doc, _) <- P.option noDocs docComment+                                                 n <- withExtent constructor                                                  return (Just n, doc))          let constructorDoc' = annotate syn ist constructorDoc@@ -102,7 +77,7 @@         fieldLine syn = do             doc <- optional docComment             c <- optional $ lchar '{'-            let oneName = (do (n, nfc) <- fnName+            let oneName = (do (n, nfc) <- withExtent fnName                               return $ Just (expandNS syn n, nfc))                           <|> (symbol "_" >> return Nothing)             ns <- commaSeparated oneName@@ -116,9 +91,8 @@                         Nothing    -> Nothing             return $ map (\n -> (n, p, t, doc')) ns -        constructor :: IdrisParser (Name, FC)-        constructor = (reservedHL "constructor") *> fnName-+        constructor :: (Parsing m, MonadState IState m) => m Name+        constructor = keyword "constructor" *> fnName          endPlicity :: Maybe Char -> IdrisParser Plicity         endPlicity (Just _) = do lchar '}'@@ -140,43 +114,45 @@   where     namedTy :: SyntaxInfo -> IdrisParser (Name, FC, PTerm)     namedTy syn =-      do (n, nfc) <- fnName+      do (n, nfc) <- withExtent fnName          lchar ':'          ty <- typeExpr (allowImp syn)          return (expandNS syn n, nfc, ty)     onlyName :: SyntaxInfo -> IdrisParser (Name, FC, PTerm)     onlyName syn =-      do (n, nfc) <- fnName-         fc <- getFC-         return (expandNS syn n, nfc, PType fc)+      do (n, nfc) <- withExtent fnName+         return (expandNS syn n, nfc, PType nfc)  {- | Parses data declaration type (normal or codata) DataI ::= 'data' | 'codata'; -} dataI :: IdrisParser DataOpts-dataI = do reservedHL "data"; return []-    <|> do reservedHL "codata"; return [Codata]+dataI = do keyword "data"; return []+    <|> do keyword "codata"; return [Codata]  recordI :: IdrisParser DataOpts-recordI = do reservedHL "record"; return []-          <|> do reservedHL "corecord"; return [Codata]+recordI = do keyword "record"; return []+          <|> do keyword "corecord"; return [Codata]  {- | Parses if a data should not have a default eliminator DefaultEliminator ::= 'noelim'?  -} dataOpts :: DataOpts -> IdrisParser DataOpts dataOpts opts-    = do fc <- reservedFC "%elim"-         warnElim fc+    = do let kw = "%elim"+         fc <- extent $ reserved kw+         warnElim fc kw          dataOpts (DefaultEliminator : DefaultCaseFun : opts)-  <|> do fc <- reservedFC "%case"-         warnElim fc+  <|> do let kw = "%case"+         fc <- extent $ reserved kw+         warnElim fc kw          dataOpts (DefaultCaseFun : opts)   <|> do reserved "%error_reverse"; dataOpts (DataErrRev : opts)   <|> return opts   <?> "data options"-  where warnElim fc =-          parserWarning fc (Just NoElimDeprecationWarnings) (Msg "The 'class' keyword is deprecated. Use 'interface' instead.")+  where warnElim fc kw =+          parserWarning fc (Just NoElimDeprecationWarnings)+                           (Msg ("The '" ++ kw ++ "' directive is deprecated."))  {- | Parses a data type declaration Data ::= DocComment? Accessibility? DataI DefaultEliminator FnName TypeSig ExplicitTypeDataRest?@@ -194,9 +170,9 @@   ; -} data_ :: SyntaxInfo -> IdrisParser PDecl-data_ syn = checkDeclFixity $-            do (doc, argDocs, acc, dataOpts) <- try (do-                    (doc, argDocs) <- option noDocs docComment+data_ syn = (checkDeclFixity $+            do (doc, argDocs, acc, dataOpts) <- P.try (do+                    (doc, argDocs) <- P.option noDocs docComment                     pushIndent                     acc <- accessibility                     elim <- dataOpts []@@ -207,44 +183,43 @@                         argDocs' = [ (n, annotCode (tryFullExpr syn ist) d)                                    | (n, d) <- argDocs ]                     return (doc', argDocs', acc, dataOpts))-               fc <- getFC-               (tyn_in, nfc) <- fnName-               (do try (lchar ':')+               (tyn_in, nfc) <- withExtent fnName+               (do P.try (lchar ':')                    ty <- typeExpr (allowImp syn)                    let tyn = expandNS syn tyn_in-                   d <- option (PData doc argDocs syn fc dataOpts (PLaterdecl tyn nfc ty)) (do-                     reservedHL "where"+                   d <- P.option (PData doc argDocs syn nfc dataOpts (PLaterdecl tyn nfc ty)) (do+                     keyword "where"                      cons <- indentedBlock (constructor syn)                      accData acc tyn (map (\ (_, _, n, _, _, _, _) -> n) cons)-                     return $ PData doc argDocs syn fc dataOpts (PDatadecl tyn nfc ty cons))+                     return $ PData doc argDocs syn nfc dataOpts (PDatadecl tyn nfc ty cons))                    terminator                    return d) <|> (do                     args <- many (do notEndApp-                                     x <- fst <$> name+                                     x <- name                                      return x)-                    let ty = bindArgs (map (const (PType fc)) args) (PType fc)+                    let ty = bindArgs (map (const (PType nfc)) args) (PType nfc)                     let tyn = expandNS syn tyn_in-                    d <- option (PData doc argDocs syn fc dataOpts (PLaterdecl tyn nfc ty)) (do-                      try (lchar '=') <|> do reservedHL "where"-                                             let kw = (if DefaultEliminator `elem` dataOpts then "%elim" else "") ++ (if Codata `elem` dataOpts then "co" else "") ++ "data "-                                             let n  = show tyn_in ++ " "-                                             let s  = kw ++ n-                                             let as = unwords (map show args) ++ " "-                                             let ns = concat (intersperse " -> " $ map ((\x -> "(" ++ x ++ " : Type)") . show) args)-                                             let ss = concat (intersperse " -> " $ map (const "Type") args)-                                             let fix1 = s ++ as ++ " = ..."-                                             let fix2 = s ++ ": " ++ ns ++ " -> Type where\n  ..."-                                             let fix3 = s ++ ": " ++ ss ++ " -> Type where\n  ..."-                                             fail $ fixErrorMsg "unexpected \"where\"" [fix1, fix2, fix3]-                      cons <- sepBy1 (simpleConstructor (syn { withAppAllowed = False })) (reservedOp "|")-                      let conty = mkPApp fc (PRef fc [] tyn) (map (PRef fc []) args)+                    d <- P.option (PData doc argDocs syn nfc dataOpts (PLaterdecl tyn nfc ty)) (do+                      P.try (lchar '=') <|> do keyword "where"+                                               let kw = (if DefaultEliminator `elem` dataOpts then "%elim" else "") ++ (if Codata `elem` dataOpts then "co" else "") ++ "data "+                                               let n  = show tyn_in ++ " "+                                               let s  = kw ++ n+                                               let as = unwords (map show args) ++ " "+                                               let ns = concat (intersperse " -> " $ map ((\x -> "(" ++ x ++ " : Type)") . show) args)+                                               let ss = concat (intersperse " -> " $ map (const "Type") args)+                                               let fix1 = s ++ as ++ " = ..."+                                               let fix2 = s ++ ": " ++ ns ++ " -> Type where\n  ..."+                                               let fix3 = s ++ ": " ++ ss ++ " -> Type where\n  ..."+                                               fail $ fixErrorMsg "unexpected \"where\"" [fix1, fix2, fix3]+                      cons <- P.sepBy1 (simpleConstructor (syn { withAppAllowed = False })) (reservedOp "|")+                      let conty = mkPApp nfc (PRef nfc [] tyn) (map (PRef nfc []) args)                       cons' <- mapM (\ (doc, argDocs, x, xfc, cargs, cfc, fs) ->                                    do let cty = bindArgs cargs conty                                       return (doc, argDocs, x, xfc, cty, cfc, fs)) cons                       accData acc tyn (map (\ (_, _, n, _, _, _, _) -> n) cons')-                      return $ PData doc argDocs syn fc dataOpts (PDatadecl tyn nfc ty cons'))+                      return $ PData doc argDocs syn nfc dataOpts (PDatadecl tyn nfc ty cons'))                     terminator-                    return d)+                    return d))            <?> "data type declaration"   where     mkPApp :: FC -> PTerm -> [PTerm] -> PTerm@@ -263,13 +238,13 @@ -} constructor :: SyntaxInfo -> IdrisParser (Docstring (Either Err PTerm), [(Name, Docstring (Either Err PTerm))], Name, FC, PTerm, FC, [Name]) constructor syn-    = do (doc, argDocs) <- option noDocs docComment-         (cn_in, nfc) <- fnName; fc <- getFC+    = do (doc, argDocs) <- P.option noDocs docComment+         (cn_in, nfc) <- withExtent fnName          let cn = expandNS syn cn_in          lchar ':'-         fs <- option [] (do lchar '%'; reserved "erase"-                             sepBy1 (fst <$> name) (lchar ','))-         ty <- typeExpr (allowImp syn)+         fs <- P.option [] (do lchar '%'; reserved "erase"+                               P.sepBy1 name (lchar ','))+         (ty, fc) <- withExtent $ typeExpr (allowImp syn)          ist <- get          let doc' = annotCode (tryFullExpr syn ist) doc              argDocs' = [ (n, annotCode (tryFullExpr syn ist) d)@@ -283,24 +258,23 @@ -} simpleConstructor :: SyntaxInfo -> IdrisParser (Docstring (Either Err PTerm), [(Name, Docstring (Either Err PTerm))], Name, FC, [PTerm], FC, [Name]) simpleConstructor syn-     = do (doc, _) <- option noDocs (try docComment)+     = (appExtent $ do+          (doc, _) <- P.option noDocs (P.try docComment)           ist <- get           let doc' = annotCode (tryFullExpr syn ist) doc-          (cn_in, nfc) <- fnName+          (cn_in, nfc) <- withExtent fnName           let cn = expandNS syn cn_in-          fc <- getFC           args <- many (do notEndApp                            simpleExpr syn)           checkNameFixity cn-          return (doc', [], cn, nfc, args, fc, [])-       <?> "constructor"-+          return $ \fc -> (doc', [], cn, nfc, args, fc, []))+        <?> "constructor" {- | Parses a dsl block declaration DSL ::= 'dsl' FnName OpenBlock Overload'+ CloseBlock;  -} dsl :: SyntaxInfo -> IdrisParser PDecl-dsl syn = do reservedHL "dsl"-             n <- fst <$> fnName+dsl syn = do keyword "dsl"+             n <- fnName              bs <- indentedBlock (overload syn)              let dsl = mkDSL bs (dsl_info syn)              checkDSL dsl@@ -337,12 +311,10 @@ Overload ::= OverloadIdentifier '=' Expr; -} overload :: SyntaxInfo -> IdrisParser (String, PTerm)-overload syn = do (o, fc) <- identifier <|> do fc <- reservedFC "let"-                                               return ("let", fc)+overload syn = do o <- highlight AnnKeyword $ identifier <|> "let" <$ reserved "let"                   if o `notElem` overloadable                      then fail $ show o ++ " is not an overloading"                      else do-                       highlightP fc AnnKeyword                        lchar '='                        t <- expr syn                        return (o, t)
src/Idris/Parser/Expr.hs view
@@ -1,12 +1,11 @@ {-| Module      : Idris.Parser.Expr Description : Parse Expressions.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}-{-# LANGUAGE ConstraintKinds, GeneralizedNewtypeDeriving, PatternGuards,-             TupleSections #-}+{-# LANGUAGE FlexibleContexts, TupleSections #-} module Idris.Parser.Expr where  import Idris.AbsSyntax@@ -19,26 +18,16 @@ import Prelude hiding (pi)  import Control.Applicative+import Control.Arrow (left) import Control.Monad import Control.Monad.State.Strict-import qualified Data.ByteString.UTF8 as UTF8-import Data.Char import Data.Function (on)-import qualified Data.HashSet as HS import Data.List-import qualified Data.List.Split as Spl import Data.Maybe-import Data.Monoid-import qualified Data.Text as T-import Debug.Trace-import qualified Text.Parser.Char as Chr-import Text.Parser.Expression-import Text.Parser.LookAhead-import qualified Text.Parser.Token as Tok-import qualified Text.Parser.Token.Highlight as Hi-import Text.Trifecta hiding (Err, char, charLiteral, natural, span, string,-                      stringLiteral, symbol, whiteSpace)-import Text.Trifecta.Delta+import Text.Megaparsec ((<?>))+import qualified Text.Megaparsec as P+import qualified Text.Megaparsec.Char as P+import qualified Text.Megaparsec.Expr as P  -- | Allow implicit type declarations allowImp :: SyntaxInfo -> SyntaxInfo@@ -65,15 +54,12 @@  -} fullExpr :: SyntaxInfo -> IdrisParser PTerm fullExpr syn = do x <- expr syn-                  eof+                  P.eof                   i <- get                   return $ debindApp syn (desugar syn i x)  tryFullExpr :: SyntaxInfo -> IState -> String -> Either Err PTerm-tryFullExpr syn st input =-  case runparser (fullExpr syn) st "" input of-    Success tm -> Right tm-    Failure e -> Left (Msg (show e))+tryFullExpr syn st = left (Msg . show . parseErrorDoc) . runparser (fullExpr syn) st ""  {- | Parses an expression @@@ -90,8 +76,7 @@ -} opExpr :: SyntaxInfo -> IdrisParser PTerm opExpr syn = do i <- get-                buildExpressionParser (table (idris_infixes i))-                                      (expr' syn)+                P.makeExprParser (expr' syn) (table (idris_infixes i))  {- | Parses either an internally defined expression or     a user-defined one@@ -101,17 +86,14 @@ @  -} expr' :: SyntaxInfo -> IdrisParser PTerm-expr' syn = try (externalExpr syn)+expr' syn = P.try (externalExpr syn)             <|> internalExpr syn             <?> "expression"  {- | Parses a user-defined expression -} externalExpr :: SyntaxInfo -> IdrisParser PTerm externalExpr syn = do i <- get-                      (FC fn start _) <- getFC-                      expr <- extensions syn (syntaxRulesList $ syntax_rules i)-                      (FC _ _ end) <- getFC-                      let outerFC = FC fn start end+                      (expr, outerFC@(FC fn _ _)) <- withExtent $ extensions syn (syntaxRulesList $ syntax_rules i)                       return (mapPTermFC (fixFC outerFC) (fixFCH fn outerFC) expr)                    <?> "user-defined expression"   where -- Fix non-highlighting FCs by approximating with the span of the syntax application@@ -152,9 +134,9 @@  extension :: SyntaxInfo -> [Maybe (Name, SynMatch)] -> [Syntax] -> IdrisParser PTerm extension syn ns rules =-  choice $ flip map (groupBy (ruleGroup `on` syntaxSymbols) rules) $ \rs ->+  P.choice $ flip map (groupBy (ruleGroup `on` syntaxSymbols) rules) $ \rs ->     case head rs of -- can never be []-      Rule (symb:_) _ _ -> try $ do+      Rule (symb:_) _ _ -> P.try $ do         n <- extensionSymbol symb         extension syn (n : ns) [Rule ss t ctx | (Rule (_:ss) t ctx) <- rs]       -- If we have more than one Rule in this bucket, our grammar is@@ -166,18 +148,14 @@     ruleGroup _ _ = False      extensionSymbol :: SSymbol -> IdrisParser (Maybe (Name, SynMatch))-    extensionSymbol (Keyword n)    = do fc <- reservedFC (show n)-                                        highlightP fc AnnKeyword-                                        return Nothing+    extensionSymbol (Keyword n)    = Nothing <$ keyword (show n)     extensionSymbol (Expr n)       = do tm <- expr syn                                         return $ Just (n, SynTm tm)     extensionSymbol (SimpleExpr n) = do tm <- simpleExpr syn                                         return $ Just (n, SynTm tm)-    extensionSymbol (Binding n)    = do (b, fc) <- name+    extensionSymbol (Binding n)    = do (b, fc) <- withExtent name                                         return $ Just (n, SynBind fc b)-    extensionSymbol (Symbol s)     = do fc <- symbolFC s-                                        highlightP fc AnnKeyword-                                        return Nothing+    extensionSymbol (Symbol s)     = Nothing <$ highlight AnnKeyword (symbol s)      flatten :: PTerm -> PTerm -- flatten application     flatten (PApp fc (PApp _ f as) bs) = flatten (PApp fc f (as ++ bs))@@ -202,9 +180,9 @@       = let (n', nfc') = updateB ns (n, fc)         in PPi (updTacImp ns p) n' nfc'                (update ns ty) (update (dropn n ns) sc)-    update ns (PLet fc n nfc ty val sc)+    update ns (PLet fc rc n nfc ty val sc)       = let (n', nfc') = updateB ns (n, nfc)-        in PLet fc n' nfc' (update ns ty)+        in PLet fc rc n' nfc' (update ns ty)                 (update ns val) (update (dropn n ns) sc)     update ns (PApp fc t args)       = PApp fc (update ns t) (map (fmap (update ns)) args)@@ -229,11 +207,13 @@       where upd :: [(Name, SynMatch)] -> PDo -> PDo             upd ns (DoExp fc t) = DoExp fc (update ns t)             upd ns (DoBind fc n nfc t) = DoBind fc n nfc (update ns t)-            upd ns (DoLet fc n nfc ty t) = DoLet fc n nfc (update ns ty) (update ns t)+            upd ns (DoLet fc rc n nfc ty t) = DoLet fc rc n nfc (update ns ty) (update ns t)             upd ns (DoBindP fc i t ts)                     = DoBindP fc (update ns i) (update ns t)                                  (map (\(l,r) -> (update ns l, update ns r)) ts)-            upd ns (DoLetP fc i t) = DoLetP fc (update ns i) (update ns t)+            upd ns (DoLetP fc i t ts)+                    = DoLetP fc (update ns i) (update ns t)+                                (map (\(l,r) -> (update ns l, update ns r)) ts)             upd ns (DoRewrite fc h) = DoRewrite fc (update ns h)     update ns (PIdiom fc t) = PIdiom fc $ update ns t     update ns (PMetavar fc n) = uncurry (flip PMetavar) $ updateB ns (n, fc)@@ -317,9 +297,7 @@ @ -} impossible :: IdrisParser PTerm-impossible = do fc <- reservedFC "impossible"-                highlightP fc AnnKeyword-                return PImpossible+impossible = PImpossible <$ keyword "impossible"  {- | Parses a case expression @@@ -328,11 +306,10 @@ @ -} caseExpr :: SyntaxInfo -> IdrisParser PTerm-caseExpr syn = do kw1 <- reservedFC "case"; fc <- getFC-                  scr <- expr syn; kw2 <- reservedFC "of";+caseExpr syn = do keyword "case"+                  (scr, fc) <- withExtent $ expr syn+                  keyword "of"                   opts <- indentedBlock1 (caseOption syn)-                  highlightP kw1 AnnKeyword-                  highlightP kw2 AnnKeyword                   return (PCase fc scr opts)                <?> "case expression" @@ -361,9 +338,8 @@ @ -} proofExpr :: SyntaxInfo -> IdrisParser PTerm-proofExpr syn = do kw <- reservedFC "proof"+proofExpr syn = do kw <- extent $ keyword "proof"                    ts <- indentedBlock1 (tactic syn)-                   highlightP kw AnnKeyword                    warnTacticDeprecation kw                    return $ PProof ts                 <?> "proof block"@@ -376,9 +352,8 @@ @ -} tacticsExpr :: SyntaxInfo -> IdrisParser PTerm-tacticsExpr syn = do kw <- reservedFC "tactics"+tacticsExpr syn = do kw <- extent $ keyword "tactics"                      ts <- indentedBlock1 (tactic syn)-                     highlightP kw AnnKeyword                      warnTacticDeprecation kw                      return $ PTactics ts                   <?> "tactics block"@@ -409,41 +384,38 @@ -} simpleExpr :: SyntaxInfo -> IdrisParser PTerm simpleExpr syn =-            try (simpleExternalExpr syn)-        <|> do (x, FC f (l, c) end) <- try (lchar '?' *> name)+            P.try (simpleExternalExpr syn)+        <|> do (x, FC f (l, c) end) <- P.try (lchar '?' *> withExtent name)                return (PMetavar (FC f (l, c-1) end) x)-        <|> do lchar '%'; fc <- getFC; reserved "implementation"; return (PResolveTC fc)-        <|> do lchar '%'; fc <- getFC; reserved "instance"+        <|> do lchar '%'; fc <- extent $ reserved "implementation"; return (PResolveTC fc)+        <|> do lchar '%'; fc <- extent $ reserved "instance"                parserWarning fc Nothing $ Msg "The use of %instance is deprecated, use %implementation instead."                return (PResolveTC fc)-        <|> do reserved "elim_for"; fc <- getFC; t <- fst <$> fnName; return (PRef fc [] (SN $ ElimN t))+        <|> do reserved "elim_for"; (t, fc) <- withExtent $ fnName; return (PRef fc [] (SN $ ElimN t))         <|> proofExpr syn         <|> tacticsExpr syn-        <|> try (do fc <- reservedFC "Type*"; return $ PUniverse fc AllTypes)-        <|> do fc <- reservedFC "AnyType"; return $ PUniverse fc AllTypes-        <|> PType <$> reservedFC "Type"-        <|> do fc <- reservedFC "UniqueType"; return $ PUniverse fc UniqueType-        <|> do fc <- reservedFC "NullType"; return $ PUniverse fc NullType-        <|> do (c, cfc) <- constant-               fc <- getFC-               return (modifyConst syn fc (PConstant cfc c))-        <|> do symbol "'"; fc <- getFC; str <- fst <$> name+        <|> P.try (do fc <- extent (reserved "Type*"); return $ PUniverse fc AllTypes)+        <|> do fc <- extent $ reserved "AnyType"; return $ PUniverse fc AllTypes+        <|> PType <$> extent (reserved "Type")+        <|> do fc <- extent $ reserved "UniqueType"; return $ PUniverse fc UniqueType+        <|> do fc <- extent $ reserved "NullType"; return $ PUniverse fc NullType+        <|> do (c, cfc) <- withExtent constant+               return (modifyConst syn cfc (PConstant cfc c))+        <|> do symbol "'"; (str, fc) <- withExtent name                return (PApp fc (PRef fc [] (sUN "Symbol_"))                           [pexp (PConstant NoFC (Str (show str)))])-        <|> do (x, fc) <- fnName+        <|> do (x, fc) <- withExtent fnName                if inPattern syn-                  then option (PRef fc [fc] x)-                              (do reservedOp "@"-                                  s <- simpleExpr syn-                                  fcIn <- getFC-                                  return (PAs fcIn x s))+                  then P.option (PRef fc [fc] x)+                                (do reservedOp "@"+                                    (s, fcIn) <- withExtent $ simpleExpr syn+                                    return (PAs fcIn x s))                   else return (PRef fc [fc] x)         <|> idiom syn         <|> listExpr syn         <|> alt syn         <|> do reservedOp "!"-               s <- simpleExpr syn-               fc <- getFC+               (s, fc) <- withExtent $ simpleExpr syn                return (PAppBind fc s [])         <|> bracketed (disallowImp syn)         <|> quasiquote syn@@ -458,8 +430,7 @@ @  -} bracketed :: SyntaxInfo -> IdrisParser PTerm-bracketed syn = do (FC fn (sl, sc) _) <- getFC-                   lchar '(' <?> "parenthesized expression"+bracketed syn = do (FC fn (sl, sc) _) <- extent (lchar '(') <?> "parenthesized expression"                    bracketed' (FC fn (sl, sc) (sl, sc+1)) (syn { withAppAllowed = True })  {- |Parses the rest of an expression in braces@@ -476,31 +447,38 @@ -} bracketed' :: FC -> SyntaxInfo -> IdrisParser PTerm bracketed' open syn =-            do (FC f start (l, c)) <- getFC-               lchar ')'-               return $ PTrue (spanFC open (FC f start (l, c+1))) TypeOrTerm-        <|> try (dependentPair TypeOrTerm [] open syn)-        <|> try (do fc <- getFC; o <- operator; e <- expr syn; lchar ')'-                    -- No prefix operators! (bit of a hack here...)-                    if (o == "-" || o == "!")-                      then fail "minus not allowed in section"-                      else return $ PLam fc (sMN 1000 "ARG") NoFC Placeholder-                         (PApp fc (PRef fc [] (sUN o)) [pexp (PRef fc [] (sMN 1000 "ARG")),-                                                        pexp e]))-        <|> try (do l <- simpleExpr syn-                    op <- option Nothing (do o <- operator-                                             lchar ')'-                                             return (Just o))-                    fc0 <- getFC-                    case op of-                         Nothing -> bracketedExpr syn open l-                         Just o -> return $ PLam fc0 (sMN 1000 "ARG") NoFC Placeholder-                             (PApp fc0 (PRef fc0 [] (sUN o)) [pexp l,-                                                              pexp (PRef fc0 [] (sMN 1000 "ARG"))]))+            do fc <- extent (addExtent open *> lchar ')')+               return $ PTrue fc TypeOrTerm+        <|> P.try (dependentPair TypeOrTerm [] open syn)+        <|> P.try (do (opName, fc) <- withExtent operatorName+                      guardNotPrefix opName++                      e <- expr syn+                      lchar ')'+                      return $ PLam fc (sMN 1000 "ARG") NoFC Placeholder+                        (PApp fc (PRef fc [] opName) [pexp (PRef fc [] (sMN 1000 "ARG")),+                                                      pexp e]))+        <|> P.try (simpleExpr syn >>= \l ->+                     P.try (do (opName, fc) <- withExtent operatorName+                               lchar ')'+                               return $ PLam fc (sMN 1000 "ARG") NoFC Placeholder+                                 (PApp fc (PRef fc [] opName) [pexp l,+                                                               pexp (PRef fc [] (sMN 1000 "ARG"))]))+                 <|> bracketedExpr syn open l)         <|> do l <- expr (allowConstr syn)                bracketedExpr (allowConstr syn) open l+  where+    justPrefix                          :: FixDecl -> Maybe Name+    justPrefix (Fix (PrefixN _) opName) = Just (sUN opName)+    justPrefix _                        = Nothing +    guardNotPrefix        :: Name -> IdrisParser ()+    guardNotPrefix opName = do+      guard $ opName /= sUN "-"+      guard $ opName /= sUN "!" +      ops <- idris_infixes <$> get+      guard . not . (opName `elem`) . mapMaybe justPrefix $ ops  {-| Parses the rest of a dependent pair after '(' or '(Expr **' -} dependentPair :: PunInfo -> [(PTerm, Maybe (FC, PTerm), FC)] -> FC -> SyntaxInfo -> IdrisParser PTerm@@ -513,22 +491,22 @@       IsTerm -> exprPart False       TypeOrTerm -> nametypePart <|> namePart <|> exprPart False   where nametypePart = do-          (ln, lnfc, colonFC) <- try $ do-            (ln, lnfc) <- name-            colonFC <- lcharFC ':'+          (ln, lnfc, colonFC) <- P.try $ do+            (ln, lnfc) <- withExtent name+            colonFC <- extent (lchar ':')             return (ln, lnfc, colonFC)           lty <- expr' syn-          starsFC <- reservedOpFC "**"+          starsFC <- extent $ reservedOp "**"           dependentPair IsType ((PRef lnfc [] ln, Just (colonFC, lty), starsFC):prev) openFC syn-        namePart = try $ do-          (ln, lnfc) <- name-          starsFC <- reservedOpFC "**"+        namePart = P.try $ do+          (ln, lnfc) <- withExtent name+          starsFC <- extent $ reservedOp "**"           dependentPair pun ((PRef lnfc [] ln, Nothing, starsFC):prev) openFC syn         exprPart isEnd = do           e <- expr syn           sepFCE <--            let stars = (Left <$> reservedOpFC "**")-                ending = (Right <$> lcharFC ')')+            let stars = (Left <$> extent (reservedOp "**"))+                ending = (Right <$> extent (lchar ')'))             in if isEnd then ending else stars <|> ending           case sepFCE of             Left starsFC -> dependentPair IsTerm ((e, Nothing, starsFC):prev) openFC syn@@ -545,13 +523,13 @@ bracketedExpr :: SyntaxInfo -> FC -> PTerm -> IdrisParser PTerm bracketedExpr syn openParenFC e =              do lchar ')'; return e-        <|>  do exprs <- some (do comma <- lcharFC ','+        <|>  do exprs <- some (do comma <- extent (lchar ',')                                   r <- expr syn                                   return (r, comma))-                closeParenFC <- lcharFC ')'+                closeParenFC <- extent (lchar ')')                 let hilite = [openParenFC, closeParenFC] ++ map snd exprs                 return $ PPair openParenFC hilite TypeOrTerm e (mergePairs exprs)-        <|>  do starsFC <- reservedOpFC "**"+        <|>  do starsFC <- extent $ reservedOp "**"                 dependentPair IsTerm [(e, Nothing, starsFC)] openParenFC syn         <?> "end of bracketed expression"   where mergePairs :: [(PTerm, FC)] -> PTerm@@ -566,7 +544,7 @@ modifyConst :: SyntaxInfo -> FC -> PTerm -> PTerm modifyConst syn fc (PConstant inFC (BI x))     | not (inPattern syn)-        = PConstSugar inFC $ -- wrap in original location for highlighting+        = PConstSugar inFC $ -- wrap in original span for highlighting             PAlternative [] FirstSuccess               (PApp fc (PRef fc [] (sUN "fromInteger")) [pexp (PConstant NoFC (BI (fromInteger x)))]               : consts)@@ -593,7 +571,7 @@ @ -} alt :: SyntaxInfo -> IdrisParser PTerm-alt syn = do symbol "(|"; alts <- sepBy1 (expr' (syn { withAppAllowed = False })) (lchar ','); symbol "|)"+alt syn = do symbol "(|"; alts <- P.sepBy1 (expr' (syn { withAppAllowed = False })) (lchar ','); symbol "|)"              return (PAlternative [] FirstSuccess alts)  {- | Parses a possibly hidden simple expression@@ -618,10 +596,8 @@   ; -} unifyLog :: SyntaxInfo -> IdrisParser PTerm-unifyLog syn = do (FC fn (sl, sc) kwEnd) <- try (lchar '%' *> reservedFC "unifyLog")-                  tm <- simpleExpr syn-                  highlightP (FC fn (sl, sc-1) kwEnd) AnnKeyword-                  return (PUnifyLog tm)+unifyLog syn = do P.try $ highlight AnnKeyword $ lchar '%' *> reserved "unifyLog"+                  PUnifyLog <$> simpleExpr syn                <?> "unification log expression"  {- | Parses a new-style tactics expression@@ -630,10 +606,8 @@   ; -} runElab :: SyntaxInfo -> IdrisParser PTerm-runElab syn = do (FC fn (sl, sc) kwEnd) <- try (lchar '%' *> reservedFC "runElab")-                 fc <- getFC-                 tm <- simpleExpr syn-                 highlightP (FC fn (sl, sc-1) kwEnd) AnnKeyword+runElab syn = do P.try $ highlight AnnKeyword $ lchar '%' *> reserved "runElab"+                 (tm, fc) <- withExtent $ simpleExpr syn                  return $ PRunElab fc tm (syn_namespace syn)               <?> "new-style tactics expression" @@ -643,10 +617,9 @@   ; -} disamb :: SyntaxInfo -> IdrisParser PTerm-disamb syn = do kw <- reservedFC "with"-                ns <- sepBy1 (fst <$> name) (lchar ',')+disamb syn = do keyword "with"+                ns <- P.sepBy1 name (lchar ',')                 tm <- expr' syn-                highlightP kw AnnKeyword                 return (PDisamb (map tons ns) tm)                <?> "namespace disambiguation expression"   where tons (NS n s) = txt (show n) : s@@ -659,7 +632,7 @@ @ -} noImplicits :: SyntaxInfo -> IdrisParser PTerm-noImplicits syn = do try (lchar '%' *> reserved "noImplicits")+noImplicits syn = do P.try (lchar '%' *> reserved "noImplicits")                      tm <- simpleExpr syn                      return (PNoImplicits tm)                  <?> "no implicits expression"@@ -677,26 +650,24 @@ @ -} app :: SyntaxInfo -> IdrisParser PTerm-app syn = do f <- simpleExpr syn-             (do try $ reservedOp "<=="-                 fc <- getFC-                 ff <- fst <$> fnName-                 return (PLet fc (sMN 0 "match") NoFC-                               f-                               (PMatchApp fc ff)-                               (PRef fc [] (sMN 0 "match")))-                   <?> "matching application expression") <|>-               (do fc <- getFC-                   i <- get-                   args <- many (do notEndApp; arg syn)-                   wargs <- if withAppAllowed syn && not (inPattern syn)-                              then many (do notEndApp; reservedOp "|"; expr' syn)-                              else return []-                   case args of-                     [] -> return f-                     _  -> return (withApp fc (flattenFromInt fc f args) wargs))-       <?> "function application"-   where+app syn = (appExtent $ do+    f <- simpleExpr syn+    (do P.try $ reservedOp "<=="+        ff <- fnName+        return (\fc -> (PLet fc RigW (sMN 0 "match") NoFC+                          f+                          (PMatchApp fc ff)+                          (PRef fc [] (sMN 0 "match"))))+          <?> "matching application expression") <|>+      (do args <- many (do notEndApp; arg syn)+          wargs <- if withAppAllowed syn && not (inPattern syn)+                     then many (do notEndApp; reservedOp "|"; expr' syn)+                     else return []+          case args of+            [] -> return $ \fc -> f+            _  -> return $ \fc -> (withApp fc (flattenFromInt fc f args) wargs)))+     <?> "function application"+  where     -- bit of a hack to deal with the situation where we're applying a     -- literal to an argument, which we may want for obscure applications     -- of fromInteger, and this will help disambiguate better.@@ -738,10 +709,9 @@ -} implicitArg :: SyntaxInfo -> IdrisParser PArg implicitArg syn = do lchar '{'-                     (n, nfc) <- name-                     fc <- getFC-                     v <- option (PRef nfc [nfc] n) (do lchar '='-                                                        expr syn)+                     (n, nfc) <- withExtent name+                     v <- P.option (PRef nfc [nfc] n) (do lchar '='+                                                          expr syn)                      lchar '}'                      return (pimp n v True)                   <?> "implicit function argument"@@ -766,55 +736,43 @@  -} quasiquote :: SyntaxInfo -> IdrisParser PTerm-quasiquote syn = do startFC <- symbolFC "`("+quasiquote syn = (highlight AnnQuasiquote $ do+                    highlight AnnKeyword $ symbol "`("                     e <- expr syn { syn_in_quasiquote = (syn_in_quasiquote syn) + 1 ,                                     inPattern = False }                     g <- optional $-                           do fc <- symbolFC ":"-                              ty <- expr syn { inPattern = False } -- don't allow antiquotes-                              return (ty, fc)-                    endFC <- symbolFC ")"-                    mapM_ (uncurry highlightP) [(startFC, AnnKeyword), (endFC, AnnKeyword), (spanFC startFC endFC, AnnQuasiquote)]-                    case g of-                      Just (_, fc) -> highlightP fc AnnKeyword-                      _ -> return ()-                    return $ PQuasiquote e (fst <$> g)-                 <?> "quasiquotation"-+                           do highlight AnnKeyword $ symbol ":"+                              expr syn { inPattern = False } -- don't allow antiquotes+                    highlight AnnKeyword $ symbol ")"+                    return $ PQuasiquote e g)+                  <?> "quasiquotation" {-| Parses an unquoting inside a quasiquotation (for building reflected terms using the elaborator)  > Unquote ::= ',' Expr  -} unquote :: SyntaxInfo -> IdrisParser PTerm-unquote syn = do guard (syn_in_quasiquote syn > 0)-                 startFC <- symbolFC "~"+unquote syn = (highlight AnnAntiquote $ do+                 guard (syn_in_quasiquote syn > 0)+                 highlight AnnKeyword $ symbol "~"                  e <- simpleExpr syn { syn_in_quasiquote = syn_in_quasiquote syn - 1 }-                 endFC <- getFC-                 highlightP startFC AnnKeyword-                 highlightP (spanFC startFC endFC) AnnAntiquote-                 return $ PUnquote e-              <?> "unquotation"-+                 return $ PUnquote e)+               <?> "unquotation" {-| Parses a quotation of a name (for using the elaborator to resolve boring details)  > NameQuote ::= '`{' Name '}'  -} namequote :: SyntaxInfo -> IdrisParser PTerm-namequote syn = do (startFC, res) <--                     try (do fc <- symbolFC "`{{"-                             return (fc, False)) <|>-                       (do fc <- symbolFC "`{"-                           return (fc, True))-                   (n, nfc) <- fnName-                   endFC <- if res then symbolFC "}" else symbolFC "}}"-                   mapM_ (uncurry highlightP)-                         [ (startFC, AnnKeyword)-                         , (endFC, AnnKeyword)-                         , (spanFC startFC endFC, AnnQuasiquote)-                         ]-                   return $ PQuoteName n res nfc+namequote syn = highlight AnnQuasiquote ((P.try $ do+                     highlight AnnKeyword $ symbol "`{{"+                     (n, nfc) <- withExtent fnName+                     highlight AnnKeyword $ symbol "}}"+                     return (PQuoteName n False nfc))+                  <|> (do highlight AnnKeyword $ symbol "`{"+                          (n, nfc) <- withExtent fnName+                          highlight AnnKeyword $ symbol "}"+                          return (PQuoteName n True nfc)))                 <?> "quoted name"  @@ -840,13 +798,13 @@  recordType :: SyntaxInfo -> IdrisParser PTerm recordType syn =-      do kw <- reservedFC "record"-         lchar '{'-         fgs <- fieldGetOrSet-         lchar '}'-         fc <- getFC-         rec <- optional (do notEndApp; simpleExpr syn)-         highlightP kw AnnKeyword+      do ((fgs, rec), fc) <- withExtent $ do+            keyword "record"+            lchar '{'+            fgs <- fieldGetOrSet+            lchar '}'+            rec <- optional (do notEndApp; simpleExpr syn)+            return (fgs, rec)          case fgs of               Left fields ->                 case rec of@@ -874,11 +832,10 @@                     <?> "field setter"           fieldGet :: IdrisParser [Name]-         fieldGet = sepBy1 (fst <$> fnName) (symbol "->")+         fieldGet = P.sepBy1 fnName (symbol "->")           fieldGetOrSet :: IdrisParser (Either [([Name], SetOrUpdate)] [Name])-         fieldGetOrSet = try (do fs <- sepBy1 fieldSet (lchar ',')-                                 return (Left fs))+         fieldGetOrSet = P.try (Left <$> P.sepBy1 fieldSet (lchar ','))                      <|> do f <- fieldGet                             return (Right f) @@ -945,15 +902,13 @@ -} lambda :: SyntaxInfo -> IdrisParser PTerm lambda syn = do lchar '\\' <?> "lambda expression"-                ((do xt <- try $ tyOptDeclList (disallowImp syn)-                     fc <- getFC-                     sc <- lambdaTail+                ((do xt <- P.try $ tyOptDeclList (disallowImp syn)+                     (sc, fc) <- withExtent lambdaTail                      return (bindList (\r -> PLam fc) xt sc))                  <|>-                 (do ps <- sepBy (do fc <- getFC-                                     e <- simpleExpr (disallowImp (syn { inPattern = True }))-                                     return (fc, e))-                                 (lchar ',')+                 (do ps <- P.sepBy (do (e, fc) <- withExtent $ simpleExpr (disallowImp (syn { inPattern = True }))+                                       return (fc, e))+                                   (lchar ',')                      sc <- lambdaTail                      return (pmList (zip [0..] ps) sc)))                   <?> "lambda expression"@@ -974,16 +929,13 @@ @ -} rewriteTerm :: SyntaxInfo -> IdrisParser PTerm-rewriteTerm syn = do kw <- reservedFC "rewrite"-                     fc <- getFC-                     prf <- expr syn+rewriteTerm syn = do keyword "rewrite"+                     (prf, fc) <- withExtent $ expr syn                      giving <- optional (do symbol "==>"; expr' syn)                      using <- optional (do reserved "using"-                                           (n, _) <- name+                                           n <- name                                            return n)-                     kw' <- reservedFC "in";  sc <- expr syn-                     highlightP kw AnnKeyword-                     highlightP kw' AnnKeyword+                     keyword "in";  sc <- expr syn                      return (PRewrite fc using prf sc giving)                   <?> "term rewrite expression" @@ -999,25 +951,23 @@ @  -} let_ :: SyntaxInfo -> IdrisParser PTerm-let_ syn = try (do kw <- reservedFC "let"-                   ls <- indentedBlock (let_binding syn)-                   kw' <- reservedFC "in";  sc <- expr syn-                   highlightP kw AnnKeyword; highlightP kw' AnnKeyword-                   return (buildLets ls sc))+let_ syn = P.try (do keyword "let"+                     ls <- indentedBlock (let_binding syn)+                     keyword "in";  sc <- expr syn+                     return (buildLets ls sc))            <?> "let binding"   where buildLets [] sc = sc         buildLets ((fc, PRef nfc _ n, ty, v, []) : ls) sc-          = PLet fc n nfc ty v (buildLets ls sc)+          = PLet fc RigW n nfc ty v (buildLets ls sc)         buildLets ((fc, pat, ty, v, alts) : ls) sc           = PCase fc v ((pat, buildLets ls sc) : alts) -let_binding syn = do fc <- getFC;-                     pat <- expr' (syn { inPattern = True })-                     ty <- option Placeholder (do lchar ':'; expr' syn)+let_binding syn = do (pat, fc) <- withExtent $ expr' (syn { inPattern = True })+                     ty <- P.option Placeholder (do lchar ':'; expr' syn)                      lchar '='                      v <- expr (syn { withAppAllowed = isVar pat })-                     ts <- option [] (do lchar '|'-                                         sepBy1 (do_alt syn) (lchar '|'))+                     ts <- P.option [] (do lchar '|'+                                           P.sepBy1 (do_alt syn) (lchar '|'))                      return (fc,pat,ty,v,ts)    where isVar (PRef _ _ _) = True          isVar _ = False@@ -1029,14 +979,12 @@  -} if_ :: SyntaxInfo -> IdrisParser PTerm-if_ syn = (do ifFC <- reservedFC "if"-              fc <- getFC-              c <- expr syn-              thenFC <- reservedFC "then"+if_ syn = (do keyword "if"+              (c, fc) <- withExtent $ expr syn+              keyword "then"               t <- expr syn-              elseFC <- reservedFC "else"+              keyword "else"               f <- expr syn-              mapM_ (flip highlightP AnnKeyword) [ifFC, thenFC, elseFC]               return (PIfThenElse fc c t f))           <?> "conditional expression" @@ -1050,13 +998,11 @@ @  -} quoteGoal :: SyntaxInfo -> IdrisParser PTerm-quoteGoal syn = do kw1 <- reservedFC "quoteGoal"; n <- fst <$> name;-                   kw2 <- reservedFC "by"+quoteGoal syn = do keyword "quoteGoal"; n <- name;+                   keyword "by"                    r <- expr syn-                   kw3 <- reservedFC "in"-                   fc <- getFC-                   sc <- expr syn-                   mapM_ (flip highlightP AnnKeyword) [kw1, kw2, kw3]+                   keyword "in"+                   (sc, fc) <- withExtent $ expr syn                    return (PGoal fc r n sc)                 <?> "quote goal expression" @@ -1082,24 +1028,23 @@           return (Exp opts st False RigW)  explicitPi opts st syn-   = do xt <- try (lchar '(' *> typeDeclList syn <* lchar ')')+   = do xt <- P.try (lchar '(' *> typeDeclList syn <* lchar ')')         binder <- bindsymbol opts st syn         sc <- expr (allowConstr syn)         return (bindList (\r -> PPi (binder { pcount = r })) xt sc)  autoImplicit opts st syn-   = do kw <- reservedFC "auto"+   = do keyword "auto"         when (st == Static) $ fail "auto implicits can not be static"         xt <- typeDeclList syn         lchar '}'         symbol "->"         sc <- expr (allowConstr syn)-        highlightP kw AnnKeyword         return (bindList (\r -> PPi           (TacImp [] Dynamic (PTactics [ProofSearch True True 100 Nothing [] []]) r)) xt sc)  defaultImplicit opts st syn = do-   kw <- reservedFC "default"+   keyword "default"    when (st == Static) $ fail "default implicits can not be static"    ist <- get    script' <- simpleExpr syn@@ -1108,7 +1053,6 @@    lchar '}'    symbol "->"    sc <- expr (allowConstr syn)-   highlightP kw AnnKeyword    return (bindList (\r -> PPi (TacImp [] Dynamic script r)) xt sc)  normalImplicit opts st syn = do@@ -1150,9 +1094,9 @@        x <- opExpr syn        (do binder <- bindsymbol opts st syn            sc <- expr syn-           notFollowedBy $ reservedOp "=>"+           P.notFollowedBy $ reservedOp "=>"            return (PPi binder (sUN "__pi_arg") NoFC x sc))-              <|> do notFollowedBy $ reservedOp "=>"+              <|> do P.notFollowedBy $ reservedOp "=>"                      return x  @@ -1161,10 +1105,10 @@      do opts <- piOpts syn         st   <- static         explicitPi opts st syn-         <|> try (do lchar '{'; implicitPi opts st syn)+         <|> P.try (do lchar '{'; implicitPi opts st syn)          <|> if constraintAllowed syn-                then try (unboundPiNoConstraint opts st syn)-                         <|> constraintPi opts st syn+                then P.try (unboundPiNoConstraint opts st syn)+                           <|> constraintPi opts st syn                 else unboundPi opts st syn   <?> "dependent type signature" @@ -1189,22 +1133,22 @@ @ -} constraintList :: SyntaxInfo -> IdrisParser [(RigCount, Name, FC, PTerm)]-constraintList syn = try (constraintList1 syn)+constraintList syn = P.try (constraintList1 syn)                      <|> return []  constraintList1 :: SyntaxInfo -> IdrisParser [(RigCount, Name, FC, PTerm)]-constraintList1 syn = try (do lchar '('-                              tys <- sepBy1 nexpr (lchar ',')-                              lchar ')'-                              reservedOp "=>"-                              return tys)-                  <|> try (do t <- opExpr (disallowImp syn)-                              reservedOp "=>"-                              return [(RigW, defname, NoFC, t)])+constraintList1 syn = P.try (do lchar '('+                                tys <- P.sepBy1 nexpr (lchar ',')+                                lchar ')'+                                reservedOp "=>"+                                return tys)+                  <|> P.try (do t <- opExpr (disallowImp syn)+                                reservedOp "=>"+                                return [(RigW, defname, NoFC, t)])                   <?> "type constraint list"-  where nexpr = try (do (n, fc) <- name; lchar ':'-                        e <- expr (disallowImp syn)-                        return (RigW, n, fc, e))+  where nexpr = P.try (do (n, fc) <- withExtent name; lchar ':'+                          e <- expr (disallowImp syn)+                          return (RigW, n, fc, e))                 <|> do e <- expr (disallowImp syn)                        return (RigW, defname, NoFC, e)         defname = sMN 0 "constraint"@@ -1225,13 +1169,13 @@ @ -} typeDeclList :: SyntaxInfo -> IdrisParser [(RigCount, Name, FC, PTerm)]-typeDeclList syn = try (sepBy1 (do rig <- option RigW rigCount-                                   (x, xfc) <- fnName-                                   lchar ':'-                                   t <- typeExpr (disallowImp syn)-                                   return (rig, x, xfc, t))-                           (lchar ','))-                   <|> do ns <- sepBy1 name (lchar ',')+typeDeclList syn = P.try (P.sepBy1 (do rig <- P.option RigW rigCount+                                       (x, xfc) <- withExtent fnName+                                       lchar ':'+                                       t <- typeExpr (disallowImp syn)+                                       return (rig, x, xfc, t))+                             (lchar ','))+                   <|> do ns <- P.sepBy1 (withExtent name) (lchar ',')                           lchar ':'                           t <- typeExpr (disallowImp syn)                           return (map (\(x, xfc) -> (RigW, x, xfc, t)) ns)@@ -1253,16 +1197,15 @@ @ -} tyOptDeclList :: SyntaxInfo -> IdrisParser [(RigCount, Name, FC, PTerm)]-tyOptDeclList syn = sepBy1 (do (x, fc) <- nameOrPlaceholder-                               t <- option Placeholder (do lchar ':'-                                                           expr syn)-                               return (RigW, x, fc, t))-                           (lchar ',')+tyOptDeclList syn = P.sepBy1 (do (x, fc) <- withExtent nameOrPlaceholder+                                 t <- P.option Placeholder (do lchar ':'+                                                               expr syn)+                                 return (RigW, x, fc, t))+                             (lchar ',')                     <?> "type declaration list"-    where  nameOrPlaceholder :: IdrisParser (Name, FC)+    where  nameOrPlaceholder :: IdrisParser Name            nameOrPlaceholder = fnName-                           <|> do symbol "_"-                                  return (sMN 0 "underscore", NoFC)+                           <|> sMN 0 "underscore" <$ reservedOp "_"                            <?> "name or placeholder"  {- | Parses a list literal expression e.g. [1,2,3] or a comprehension [ (x, y) | x <- xs , y <- ys ]@@ -1287,26 +1230,20 @@ @  -} listExpr :: SyntaxInfo -> IdrisParser PTerm-listExpr syn = do (FC f (l, c) _) <- getFC-                  lchar '['; fc <- getFC;-                  (try . token $ do (char ']' <?> "end of list expression")-                                    (FC _ _ (l', c')) <- getFC-                                    return (mkNil (FC f (l, c) (l', c'))))-                   <|> (do x <- expr (syn { withAppAllowed = False }) <?> "expression"-                           (do try (lchar '|') <?> "list comprehension"-                               qs <- sepBy1 (do_ syn) (lchar ',')+listExpr syn = do (FC f (l, c) _) <- extent (lchar '[')+                  (do (FC _ _ (l', c')) <- extent (lchar ']') <?> "end of list expression"+                      return (mkNil (FC f (l, c) (l', c'))))+                   <|> (do (x, fc) <- withExtent (expr (syn { withAppAllowed = False })) <?> "expression"+                           (do P.try (lchar '|') <?> "list comprehension"+                               qs <- P.sepBy1 (do_ syn) (lchar ',')                                lchar ']'                                return (PDoBlock (map addGuard qs ++                                           [DoExp fc (PApp fc (PRef fc [] (sUN "pure"))                                                        [pexp x])]))) <|>-                            (do xs <- many (do (FC fn (sl, sc) _) <- getFC-                                               lchar ',' <?> "list element"-                                               let commaFC = FC fn (sl, sc) (sl, sc + 1)+                            (do xs <- many (do commaFC <- extent (lchar ',') <?> "list element"                                                elt <- expr syn                                                return (elt, commaFC))-                                (FC fn (sl, sc) _) <- getFC-                                lchar ']' <?> "end of list expression"-                                let rbrackFC = FC fn (sl, sc) (sl, sc+1)+                                rbrackFC <- extent (lchar ']') <?> "end of list expression"                                 return (mkList fc rbrackFC ((x, (FC f (l, c) (l, c+1))) : xs))))                 <?> "list expression"   where@@ -1333,10 +1270,8 @@  -} doBlock :: SyntaxInfo -> IdrisParser PTerm doBlock syn-    = do kw <- reservedFC "do"-         ds <- indentedBlock1 (do_ syn)-         highlightP kw AnnKeyword-         return (PDoBlock ds)+    = do keyword "do"+         PDoBlock <$> indentedBlock1 (do_ syn)       <?> "do block"  {- | Parses an expression inside a do block@@ -1353,53 +1288,51 @@ -} do_ :: SyntaxInfo -> IdrisParser PDo do_ syn-     = try (do kw <- reservedFC "let"-               (i, ifc) <- name-               ty <- option Placeholder (do lchar ':'-                                            expr' syn)-               reservedOp "="-               fc <- getFC-               e <- expr syn-               highlightP kw AnnKeyword-               return (DoLet fc i ifc ty e))-   <|> try (do kw <- reservedFC "let"-               i <- expr' syn-               reservedOp "="-               fc <- getFC-               sc <- expr syn-               highlightP kw AnnKeyword-               return (DoLetP fc i sc))-   <|> try (do kw <- reservedFC "rewrite"-               fc <- getFC-               sc <- expr syn-               highlightP kw AnnKeyword-               return (DoRewrite fc sc))-   <|> try (do (i, ifc) <- name-               symbol "<-"-               fc <- getFC-               e <- expr (syn { withAppAllowed = False });-               option (DoBind fc i ifc e)-                      (do lchar '|'-                          ts <- sepBy1 (do_alt (syn { withAppAllowed = False })) (lchar '|')-                          return (DoBindP fc (PRef ifc [ifc] i) e ts)))-   <|> try (do i <- expr' syn-               symbol "<-"-               fc <- getFC-               e <- expr (syn { withAppAllowed = False });-               option (DoBindP fc i e [])-                      (do lchar '|'-                          ts <- sepBy1 (do_alt (syn { withAppAllowed = False })) (lchar '|')-                          return (DoBindP fc i e ts)))-   <|> do e <- expr syn-          fc <- getFC+     = P.try (do keyword "let"+                 (i, ifc) <- withExtent name+                 ty' <- P.optional (do lchar ':'+                                       expr' syn)+                 reservedOp "="+                 (e, fc) <- withExtent $ expr (syn { withAppAllowed = False })+                 -- If there is an explicit type, this can’t be a pattern-matching let, so do not parse alternatives+                 P.option (DoLet fc RigW i ifc (fromMaybe Placeholder ty') e)+                          (do lchar '|'+                              when (isJust ty') $ fail "a pattern-matching let may not have an explicit type annotation"+                              ts <- P.sepBy1 (do_alt (syn { withAppAllowed = False })) (lchar '|')+                              return (DoLetP fc (PRef ifc [ifc] i) e ts)))+   <|> P.try (do keyword "let"+                 i <- expr' syn+                 reservedOp "="+                 (e, fc) <- withExtent $ expr (syn { withAppAllowed = False })+                 P.option (DoLetP fc i e [])+                          (do lchar '|'+                              ts <- P.sepBy1 (do_alt (syn { withAppAllowed = False })) (lchar '|')+                              return (DoLetP fc i e ts)))+   <|> P.try (do (sc, fc) <- withExtent (keyword "rewrite" *> expr syn)+                 return (DoRewrite fc sc))+   <|> P.try (do (i, ifc) <- withExtent name+                 symbol "<-"+                 (e, fc) <- withExtent $ expr (syn { withAppAllowed = False });+                 P.option (DoBind fc i ifc e)+                          (do lchar '|'+                              ts <- P.sepBy1 (do_alt (syn { withAppAllowed = False })) (lchar '|')+                              return (DoBindP fc (PRef ifc [ifc] i) e ts)))+   <|> P.try (do i <- expr' syn+                 symbol "<-"+                 (e, fc) <- withExtent $ expr (syn { withAppAllowed = False });+                 P.option (DoBindP fc i e [])+                          (do lchar '|'+                              ts <- P.sepBy1 (do_alt (syn { withAppAllowed = False })) (lchar '|')+                              return (DoBindP fc i e ts)))+   <|> do (e, fc) <- withExtent $ expr syn           return (DoExp fc e)    <?> "do block expression"  do_alt syn = do l <- expr' syn-                option (Placeholder, l)-                       (do symbol "=>"-                           r <- expr' syn-                           return (l, r))+                P.option (Placeholder, l)+                         (do symbol "=>"+                             r <- expr' syn+                             return (l, r))  {- | Parses an expression in idiom brackets @@@ -1409,8 +1342,7 @@ idiom :: SyntaxInfo -> IdrisParser PTerm idiom syn     = do symbol "[|"-         fc <- getFC-         e <- expr (syn { withAppAllowed = False })+         (e, fc) <- withExtent $ expr (syn { withAppAllowed = False })          symbol "|]"          return (PIdiom fc e)       <?> "expression in idiom brackets"@@ -1453,31 +1385,28 @@   ]  -- | Parse a constant and its source span-constant :: IdrisParser (Idris.Core.TT.Const, FC)-constant = choice [ do fc <- reservedFC name; return (ty, fc)-                  | (name, ty) <- constants-                  ]-        <|> do (f, fc) <- try float; return (Fl f, fc)-        <|> do (i, fc) <- natural; return (BI i, fc)-        <|> do (s, fc) <- verbatimStringLiteral; return (Str s, fc)-        <|> do (s, fc) <- stringLiteral;  return (Str s, fc)-        <|> do (c, fc) <- try charLiteral; return (Ch c, fc) --Currently ambigous with symbols-        <?> "constant or literal"+constant :: Parsing m => m Idris.Core.TT.Const+constant = P.choice [ ty <$ reserved name | (name, ty) <- constants ]+       <|> P.try (Fl <$> float)+       <|> BI <$> natural+       <|> Str <$> verbatimStringLiteral+       <|> Str <$> stringLiteral+       <|> P.try (Ch <$> charLiteral) --Currently ambigous with symbols+       <?> "constant or literal"  {- | Parses a verbatim multi-line string literal (triple-quoted)  @ VerbatimString_t ::=-  '\"\"\"' ~'\"\"\"' '\"\"\"'+  '\"\"\"' ~'\"\"\"' '\"'* '\"\"\"' ; @  -}-verbatimStringLiteral :: MonadicParsing m => m (String, FC)-verbatimStringLiteral = token $ do (FC f start _) <- getFC-                                   try $ string "\"\"\""-                                   str <- manyTill anyChar $ try (string "\"\"\"")-                                   (FC _ _ end) <- getFC-                                   return (str, FC f start end)+verbatimStringLiteral :: Parsing m => m String+verbatimStringLiteral = token $ do P.try $ string "\"\"\""+                                   str <- P.manyTill P.anyChar $ P.try (string "\"\"\"")+                                   moreQuotes <- P.many $ P.char '"'+                                   return $ str ++ moreQuotes  {- | Parses a static modifier @@ -1488,11 +1417,7 @@ @ -} static :: IdrisParser Static-static =     do reserved "%static"; return Static-         <|> do reserved "[static]"-                fc <- getFC-                parserWarning fc Nothing (Msg "The use of [static] is deprecated, use %static instead.")-                return Static+static =     Static <$ reserved "%static"          <|> return Dynamic          <?> "static modifier" @@ -1548,39 +1473,39 @@ tactics :: [([String], Maybe TacticArg, SyntaxInfo -> IdrisParser PTactic)] tactics =   [ (["intro"], Nothing, const $ -- FIXME syntax for intro (fresh name)-      do ns <- sepBy (spaced (fst <$> name)) (lchar ','); return $ Intro ns)+      do ns <- P.sepBy (spaced name) (lchar ','); return $ Intro ns)   , noArgs ["intros"] Intros   , noArgs ["unfocus"] Unfocus   , (["refine"], Just ExprTArg, const $-       do n <- spaced (fst <$> fnName)+       do n <- spaced fnName           imps <- many imp           return $ Refine n imps)   , (["claim"], Nothing, \syn ->-       do n <- indentPropHolds gtProp *> (fst <$> name)-          goal <- indentPropHolds gtProp *> expr syn+       do n <- indentGt *> name+          goal <- indentGt *> expr syn           return $ Claim n goal)   , (["mrefine"], Just ExprTArg, const $-       do n <- spaced (fst <$> fnName)+       do n <- spaced fnName           return $ MatchRefine n)   , expressionTactic ["rewrite"] Rewrite   , expressionTactic ["case"] CaseTac   , expressionTactic ["induction"] Induction   , expressionTactic ["equiv"] Equiv   , (["let"], Nothing, \syn -> -- FIXME syntax for let-       do n <- (indentPropHolds gtProp *> (fst <$> name))-          (do indentPropHolds gtProp *> lchar ':'-              ty <- indentPropHolds gtProp *> expr' syn-              indentPropHolds gtProp *> lchar '='-              t <- indentPropHolds gtProp *> expr syn+       do n <- (indentGt *> name)+          (do indentGt *> lchar ':'+              ty <- indentGt *> expr' syn+              indentGt *> lchar '='+              t <- indentGt *> expr syn               i <- get               return $ LetTacTy n (desugar syn i ty) (desugar syn i t))-            <|> (do indentPropHolds gtProp *> lchar '='-                    t <- indentPropHolds gtProp *> expr syn+            <|> (do indentGt *> lchar '='+                    t <- indentGt *> expr syn                     i <- get                     return $ LetTac n (desugar syn i t)))    , (["focus"], Just ExprTArg, const $-       do n <- spaced (fst <$> name)+       do n <- spaced name           return $ Focus n)   , expressionTactic ["exact"] Exact   , expressionTactic ["applyTactic"] ApplyTactic@@ -1596,7 +1521,7 @@   , noArgs ["trivial"] Trivial   , noArgs ["unify"] DoUnify   , (["search"], Nothing, const $-      do depth <- option 10 $ fst <$> natural+      do depth <- P.option 10 natural          return (ProofSearch True True (fromInteger depth) Nothing [] []))   , noArgs ["implementation"] TCImplementation   , noArgs ["solve"] Solve@@ -1612,12 +1537,12 @@   , expressionTactic [":t", ":type"] TCheck   , expressionTactic [":search"] TSearch   , (["fail"], Just StringLitTArg, const $-       do msg <- fst <$> stringLiteral+       do msg <- stringLiteral           return $ TFail [Idris.Core.TT.TextPart msg])   , ([":doc"], Just ExprTArg, const $        do whiteSpace-          doc <- (Right . fst <$> constant) <|> (Left . fst <$> fnName)-          eof+          doc <- (Right <$> constant) <|> (Left <$> fnName)+          P.eof           return (TDocStr doc))   ]   where@@ -1626,19 +1551,19 @@         i <- get         return $ tactic (desugar syn i t))   noArgs names tactic = (names, Nothing, const (return tactic))-  spaced parser = indentPropHolds gtProp *> parser+  spaced parser = indentGt *> parser   imp :: IdrisParser Bool   imp = do lchar '?'; return False     <|> do lchar '_'; return True   tactic :: SyntaxInfo -> IdrisParser PTactic-tactic syn = choice [ do choice (map reserved names); parser syn-                    | (names, _, parser) <- tactics ]+tactic syn = P.choice [ do P.choice (map reserved names); parser syn+                      | (names, _, parser) <- tactics ]           <|> do lchar '{'                  t <- tactic syn;                  lchar ';';-                 ts <- sepBy1 (tactic syn) (lchar ';')+                 ts <- P.sepBy1 (tactic syn) (lchar ';')                  lchar '}'                  return $ TSeq t (mergeSeq ts)           <|> ((lchar ':' >> empty) <?> "prover command")@@ -1651,5 +1576,5 @@ -- | Parses a tactic as a whole fullTactic :: SyntaxInfo -> IdrisParser PTactic fullTactic syn = do t <- tactic syn-                    eof+                    P.eof                     return t
src/Idris/Parser/Helpers.hs view
@@ -1,14 +1,73 @@ {-| Module      : Idris.Parser.Helpers Description : Utilities for Idris' parser.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}-{-# LANGUAGE CPP, ConstraintKinds, FlexibleInstances,-             GeneralizedNewtypeDeriving, PatternGuards, StandaloneDeriving,-             TypeSynonymInstances #-}-module Idris.Parser.Helpers where+{-# LANGUAGE ConstraintKinds, FlexibleContexts, MultiParamTypeClasses #-}+module Idris.Parser.Helpers+  ( module Idris.Parser.Stack+    -- * The parser+  , IdrisParser+  , parseErrorDoc+    -- * Space+  , whiteSpace+  , someSpace+  , eol+  , isEol+    -- * Basic parsers+  , char+  , symbol+  , string+  , lookAheadMatches+    -- * Terminals+  , lchar+  , reserved+  , docComment+  , token+  , natural+  , charLiteral+  , stringLiteral+  , float+    -- * Names+  , bindList+  , maybeWithNS+  , iName+  , name+  , identifier+  , packageName+    -- * Access+  , accessibility+  , accData+  , addAcc+    -- * Warnings and errors+  , fixErrorMsg+  , parserWarning+  , clearParserWarnings+  , reportParserWarnings+    -- * Highlighting+  , highlight+  , keyword+    -- * Indentation+  , pushIndent+  , popIndent+  , indentGt+  , notOpenBraces+    -- * Indented blocks+  , openBlock+  , closeBlock+  , terminator+  , notEndBlock+  , indentedBlock+  , indentedBlock1+  , indentedBlockS+  , indented+    -- * Miscellaneous+  , notEndApp+  , commaSeparated+  )+where  import Idris.AbsSyntax import Idris.Core.Evaluate@@ -17,93 +76,48 @@ import Idris.Docstrings import Idris.Options import Idris.Output (iWarn)--import qualified Util.Pretty as Pretty (text)+import Idris.Parser.Stack  import Prelude hiding (pi)  import Control.Applicative import Control.Monad import Control.Monad.State.Strict-import qualified Data.ByteString.UTF8 as UTF8 import Data.Char import qualified Data.HashSet as HS import Data.List-import qualified Data.List.Split as Spl+import qualified Data.List.NonEmpty as NonEmpty import qualified Data.Map as M import Data.Maybe-import Data.Monoid import qualified Data.Text as T-import Debug.Trace-import System.FilePath-import qualified Text.Parser.Char as Chr-import Text.Parser.Expression-import Text.Parser.LookAhead-import qualified Text.Parser.Token as Tok-import qualified Text.Parser.Token.Highlight as Hi-import Text.Trifecta hiding (Err, char, charLiteral, natural, span, string,-                      stringLiteral, symbol, whiteSpace)-import Text.Trifecta.Delta+import Text.Megaparsec ((<?>))+import qualified Text.Megaparsec as P+import qualified Text.Megaparsec.Char as P+import qualified Text.Megaparsec.Char.Lexer as P hiding (space)+import qualified Text.PrettyPrint.ANSI.Leijen as PP --- | Idris parser with state used during parsing-type IdrisParser = StateT IState IdrisInnerParser -newtype IdrisInnerParser a = IdrisInnerParser { runInnerParser :: Parser a }-  deriving (Monad, Functor, MonadPlus, Applicative, Alternative, CharParsing, LookAheadParsing, DeltaParsing, MarkParsing Delta, Monoid, TokenParsing)--deriving instance Parsing IdrisInnerParser--#if MIN_VERSION_base(4,9,0)-instance {-# OVERLAPPING #-} DeltaParsing IdrisParser where-  line = lift line-  {-# INLINE line #-}-  position = lift position-  {-# INLINE position #-}-  slicedWith f (StateT m) = StateT $ \s -> slicedWith (\(a,s') b -> (f a b, s')) $ m s-  {-# INLINE slicedWith #-}-  rend = lift rend-  {-# INLINE rend #-}-  restOfLine = lift restOfLine-  {-# INLINE restOfLine #-}--#endif--instance {-# OVERLAPPING #-} TokenParsing IdrisParser where-  someSpace = many (simpleWhiteSpace <|> singleLineComment <|> multiLineComment) *> pure ()-  token p = do s <- get-               (FC fn (sl, sc) _) <- getFC --TODO: Update after fixing getFC-                                           -- See Issue #1594-               r <- p-               (FC fn _ (el, ec)) <- getFC-               whiteSpace-               put (s { lastTokenSpan = Just (FC fn (sl, sc) (el, ec)) })-               return r--- | Generalized monadic parsing constraint type-type MonadicParsing m = (DeltaParsing m, LookAheadParsing m, TokenParsing m, Monad m)+-- | Idris parser with state used during parsing+type IdrisParser = Parser IState -class HasLastTokenSpan m where-  getLastTokenSpan :: m (Maybe FC)+parseErrorDoc :: ParseError -> PP.Doc+parseErrorDoc = PP.string . prettyError -instance HasLastTokenSpan IdrisParser where-  getLastTokenSpan = lastTokenSpan <$> get+someSpace :: Parsing m => m ()+someSpace = many (simpleWhiteSpace <|> singleLineComment <|> multiLineComment) *> pure () --- | Helper to run Idris inner parser based stateT parsers-runparser :: StateT st IdrisInnerParser res -> st -> String -> String -> Result res-runparser p i inputname =-  parseString (runInnerParser (evalStateT p i))-              (Directed (UTF8.fromString inputname) 0 0 0 0)+token :: Parsing m => m a -> m a+token p = trackExtent p <* whiteSpace -highlightP :: FC -> OutputAnnotation -> IdrisParser ()-highlightP fc annot = do ist <- get-                         put ist { idris_parserHighlights = (fc, annot) : idris_parserHighlights ist}+highlight :: (MonadState IState m, Parsing m) => OutputAnnotation -> m a -> m a+highlight annot p = do+  (result, fc) <- withExtent p+  modify $ \ist -> ist { idris_parserHighlights = (fc, annot) : idris_parserHighlights ist }+  return result -noDocCommentHere :: String -> IdrisParser ()-noDocCommentHere msg =-  optional (do fc <- getFC-               docComment-               ist <- get-               put ist { parserWarnings = (fc, Msg msg) : parserWarnings ist}) *>-  pure ()+-- | Parse a reserved identfier, highlighting it as a keyword+keyword :: (Parsing m, MonadState IState m) => String -> m ()+keyword str = highlight AnnKeyword (reserved str)  clearParserWarnings :: Idris () clearParserWarnings = do ist <- getIState@@ -130,8 +144,8 @@ {- * Space, comments and literals (token/lexing like parsers) -}  -- | Consumes any simple whitespace (any character which satisfies Char.isSpace)-simpleWhiteSpace :: MonadicParsing m => m ()-simpleWhiteSpace = satisfy isSpace *> pure ()+simpleWhiteSpace :: Parsing m => m ()+simpleWhiteSpace = () <$ P.satisfy isSpace  -- | Checks if a charcter is end of line isEol :: Char -> Bool@@ -139,8 +153,8 @@ isEol  _   = False  -- | A parser that succeeds at the end of the line-eol :: MonadicParsing m => m ()-eol = (satisfy isEol *> pure ()) <|> lookAhead eof <?> "end of line"+eol :: Parsing m => m ()+eol = () <$ P.satisfy isEol <|> P.lookAhead P.eof <?> "end of line"  {- | Consumes a single-line comment @@ -148,11 +162,8 @@      SingleLineComment_t ::= '--' ~EOL_t* EOL_t ; @  -}-singleLineComment :: MonadicParsing m => m ()-singleLineComment = (string "--" *>-                     many (satisfy (not . isEol)) *>-                     eol *> pure ())-                    <?> ""+singleLineComment :: Parsing m => m ()+singleLineComment = P.hidden (() <$ string "--" *> many (P.satisfy (not . isEol)) *> eol)  {- | Consumes a multi-line comment @@ -171,16 +182,15 @@   ; @ -}-multiLineComment :: MonadicParsing m => m ()-multiLineComment =     try (string "{-" *> (string "-}") *> pure ())-                   <|> string "{-" *> inCommentChars-                   <?> ""-  where inCommentChars :: MonadicParsing m => m ()+multiLineComment :: Parsing m => m ()+multiLineComment = P.hidden $ P.try (string "{-" *> string "-}" *> pure ())+                              <|> string "{-" *> inCommentChars+  where inCommentChars :: Parsing m => m ()         inCommentChars =     string "-}" *> pure ()-                         <|> try (multiLineComment) *> inCommentChars-                         <|> string "|||" *> many (satisfy (not . isEol)) *> eol *> inCommentChars-                         <|> skipSome (noneOf startEnd) *> inCommentChars-                         <|> oneOf startEnd *> inCommentChars+                         <|> P.try (multiLineComment) *> inCommentChars+                         <|> string "|||" *> many (P.satisfy (not . isEol)) *> eol *> inCommentChars+                         <|> P.skipSome (P.noneOf startEnd) *> inCommentChars+                         <|> P.oneOf startEnd *> inCommentChars                          <?> "end of comment"         startEnd :: String         startEnd = "{}-"@@ -202,173 +212,123 @@                 return (parseDocstring $ T.pack (concat (intersperse "\n" (dc:rest))),                         map (\(n, d) -> (n, parseDocstring (T.pack d))) args) -  where docCommentLine :: MonadicParsing m => m String-        docCommentLine = try (do string "|||"-                                 many (satisfy (==' '))-                                 contents <- option "" (do first <- satisfy (\c -> not (isEol c || c == '@'))-                                                           res <- many (satisfy (not . isEol))-                                                           return $ first:res)-                                 eol ; someSpace-                                 return contents)-- ++ concat rest))-                        <?> ""+  where docCommentLine :: Parsing m => m String+        docCommentLine = P.hidden $ P.try $ do+                           string "|||"+                           many (P.satisfy (==' '))+                           contents <- P.option "" (do first <- P.satisfy (\c -> not (isEol c || c == '@'))+                                                       res <- many (P.satisfy (not . isEol))+                                                       return $ first:res)+                           eol ; someSpace+                           return contents -        argDocCommentLine = do string "|||"-                               many (satisfy isSpace)-                               char '@'-                               many (satisfy isSpace)-                               n <- fst <$> name-                               many (satisfy isSpace)-                               docs <- many (satisfy (not . isEol))-                               eol ; someSpace+        argDocCommentLine :: IdrisParser (Name, String)+        argDocCommentLine = do P.string "|||"+                               P.many (P.satisfy isSpace)+                               P.char '@'+                               P.many (P.satisfy isSpace)+                               n <- name+                               P.many (P.satisfy isSpace)+                               docs <- P.many (P.satisfy (not . isEol))+                               P.eol ; someSpace                                return (n, docs)  -- | Parses some white space-whiteSpace :: MonadicParsing m => m ()-whiteSpace = Tok.whiteSpace+whiteSpace :: Parsing m => m ()+whiteSpace = someSpace <|> pure ()  -- | Parses a string literal-stringLiteral :: (MonadicParsing m, HasLastTokenSpan m) => m (String, FC)-stringLiteral = do str <- Tok.stringLiteral-                   fc <- getLastTokenSpan-                   return (str, fromMaybe NoFC fc)+stringLiteral :: Parsing m => m String+stringLiteral = token . P.try $ P.char '"' *> P.manyTill P.charLiteral (P.char '"')  -- | Parses a char literal-charLiteral :: (MonadicParsing m, HasLastTokenSpan m) => m (Char, FC)-charLiteral = do ch <- Tok.charLiteral-                 fc <- getLastTokenSpan-                 return (ch, fromMaybe NoFC fc)+charLiteral :: Parsing m => m Char+charLiteral = token . P.try $ P.char '\'' *> P.charLiteral <* P.char '\''  -- | Parses a natural number-natural :: (MonadicParsing m, HasLastTokenSpan m) => m (Integer, FC)-natural = do n <- Tok.natural-             fc <- getLastTokenSpan-             return (n, fromMaybe NoFC fc)---- | Parses an integral number-integer :: MonadicParsing m => m Integer-integer = Tok.integer+natural :: Parsing m => m Integer+natural = token (    P.try (P.char '0' *> P.char' 'x' *> P.hexadecimal)+                 <|> P.try (P.char '0' *> P.char' 'o' *> P.octal)+                 <|> P.try P.decimal)  -- | Parses a floating point number-float :: (MonadicParsing m, HasLastTokenSpan m) => m (Double, FC)-float = do f <- Tok.double-           fc <- getLastTokenSpan-           return (f, fromMaybe NoFC fc)+float :: Parsing m => m Double+float = token . P.try $ P.float  {- * Symbols, identifiers, names and operators -} +reservedIdentifiers :: HS.HashSet String+reservedIdentifiers = HS.fromList+  [ "Type"+  , "case", "class", "codata", "constructor", "corecord", "data"+  , "do", "dsl", "else", "export", "if", "implementation", "implicit"+  , "import", "impossible", "in", "infix", "infixl", "infixr", "instance"+  , "interface", "let", "mutual", "namespace", "of", "parameters", "partial"+  , "postulate", "private", "proof", "public", "quoteGoal", "record"+  , "rewrite", "syntax", "then", "total", "using", "where", "with"+  ] --- | Idris Style for parsing identifiers/reserved keywords-idrisStyle :: MonadicParsing m => IdentifierStyle m-idrisStyle = IdentifierStyle {-    _styleName = "Idris"-  , _styleStart = satisfy isAlpha <|> oneOf "_"-  , _styleLetter = satisfy isAlphaNum <|> oneOf "_'."-  , _styleReserved = HS.fromList-      ["let", "in", "data", "codata", "record", "corecord", "Type", "do", "dsl",-      "import", "impossible", "case", "of", "total", "partial", "mutual",-      "infix", "infixl", "infixr", "rewrite", "where", "with", "syntax",-      "proof", "postulate", "using", "namespace", "class", "instance",-      "interface", "implementation", "parameters", "public", "private",-      "export", "abstract", "implicit", "quoteGoal", "constructor", "if",-      "then", "else"]-  , _styleHighlight = Hi.Identifier-  , _styleReservedHighlight = Hi.ReservedIdentifier }+identifierOrReserved :: Parsing m => m String+identifierOrReserved = token $ P.try $ do+  c <- P.satisfy isAlpha <|> P.oneOf "_"+  cs <- P.many (P.satisfy isAlphaNum <|> P.oneOf "_'.")+  return $ c : cs -char :: MonadicParsing m => Char -> m Char-char = Chr.char+char :: Parsing m => Char -> m Char+char = P.char -string :: MonadicParsing m => String -> m String-string = Chr.string+string :: Parsing m => String -> m String+string = P.string  -- | Parses a character as a token-lchar :: MonadicParsing m => Char -> m Char-lchar = token . char---- | Parses a character as a token, returning the source span of the character-lcharFC :: MonadicParsing m => Char -> m FC-lcharFC ch = do (FC file (l, c) _) <- getFC-                _ <- token (char ch)-                return $ FC file (l, c) (l, c+1)---- | Parses string as a token-symbol :: MonadicParsing m => String -> m String-symbol = Tok.symbol+lchar :: Parsing m => Char -> m Char+lchar = token . P.char -symbolFC :: MonadicParsing m => String -> m FC-symbolFC str = do (FC file (l, c) _) <- getFC-                  Tok.symbol str-                  return $ FC file (l, c) (l, c + length str)+symbol :: Parsing m => String -> m ()+symbol = void . token . P.string  -- | Parses a reserved identifier-reserved :: MonadicParsing m => String -> m ()-reserved = Tok.reserve idrisStyle---- | Parses a reserved identifier, computing its span. Assumes that--- reserved identifiers never contain line breaks.-reservedFC :: MonadicParsing m => String -> m FC-reservedFC str = do (FC file (l, c) _) <- getFC-                    reserved str-                    return $ FC file (l, c) (l, c + length str)---- | Parse a reserved identfier, highlighting its span as a keyword-reservedHL :: String -> IdrisParser ()-reservedHL str = reservedFC str >>= flip highlightP AnnKeyword---- Taken from Parsec (c) Daan Leijen 1999-2001, (c) Paolo Martini 2007--- | Parses a reserved operator-reservedOp :: MonadicParsing m => String -> m ()-reservedOp name = token $ try $-  do string name-     notFollowedBy (operatorLetter) <?> ("end of " ++ show name)--reservedOpFC :: MonadicParsing m => String -> m FC-reservedOpFC name = do (FC f (l, c) _) <- getFC-                       reservedOp name-                       return (FC f (l, c) (l, c + length name))+reserved :: Parsing m => String -> m ()+reserved name = token $ P.try $ do+  P.string name+  P.notFollowedBy (P.satisfy isAlphaNum <|> P.oneOf "_'.") <?> "end of " ++ name  -- | Parses an identifier as a token-identifier :: (MonadicParsing m) => m (String, FC)-identifier = try(do (i, fc) <--                      token $ do (FC f (l, c) _) <- getFC-                                 i <- Tok.ident idrisStyle-                                 return (i, FC f (l, c) (l, c + length i))-                    when (i == "_") $ unexpected "wildcard"-                    return (i, fc))+identifier :: Parsing m => m String+identifier = P.try $ do+  ident <- identifierOrReserved+  when (ident `HS.member` reservedIdentifiers) $ P.unexpected . P.Label . NonEmpty.fromList $ "reserved " ++ ident+  when (ident == "_") $ P.unexpected . P.Label . NonEmpty.fromList $ "wildcard"+  return ident  -- | Parses an identifier with possible namespace as a name-iName :: (MonadicParsing m, HasLastTokenSpan m) => [String] -> m (Name, FC)-iName bad = do (n, fc) <- maybeWithNS identifier False bad-               return (n, fc)-            <?> "name"+iName :: Parsing m => [String] -> m Name+iName bad = maybeWithNS identifier bad <?> "name"  -- | Parses an string possibly prefixed by a namespace-maybeWithNS :: (MonadicParsing m, HasLastTokenSpan m) => m (String, FC) -> Bool -> [String] -> m (Name, FC)-maybeWithNS parser ascend bad = do-  fc <- getFC-  i <- option "" (lookAhead (fst <$> identifier))-  when (i `elem` bad) $ unexpected "reserved identifier"-  let transf = if ascend then id else reverse-  (x, xs, fc) <- choice (transf (parserNoNS parser : parsersNS parser i))-  return (mkName (x, xs), fc)-  where parserNoNS :: MonadicParsing m => m (String, FC) -> m (String, String, FC)-        parserNoNS parser = do startFC <- getFC-                               (x, nameFC) <- parser-                               return (x, "", spanFC startFC nameFC)-        parserNS   :: MonadicParsing m => m (String, FC) -> String -> m (String, String, FC)-        parserNS   parser ns = do startFC <- getFC-                                  xs <- string ns-                                  lchar '.';  (x, nameFC) <- parser-                                  return (x, xs, spanFC startFC nameFC)-        parsersNS  :: MonadicParsing m => m (String, FC) -> String -> [m (String, String, FC)]-        parsersNS parser i = [try (parserNS parser ns) | ns <- (initsEndAt (=='.') i)]+maybeWithNS :: Parsing m => m String -> [String] -> m Name+maybeWithNS parser bad = do+  i <- P.option "" (P.lookAhead identifier)+  when (i `elem` bad) $ P.unexpected . P.Label . NonEmpty.fromList $ "reserved identifier"+  mkName <$> P.choice (reverse (parserNoNS parser : parsersNS parser i))+  where parserNoNS :: Parsing m => m String -> m (String, String)+        parserNoNS = fmap (\x -> (x, ""))+        parserNS   :: Parsing m => m String -> String -> m (String, String)+        parserNS   parser ns = do xs <- trackExtent (string ns)+                                  lchar '.'+                                  x <- parser+                                  return (x, xs)+        parsersNS  :: Parsing m => m String -> String -> [m (String, String)]+        parsersNS parser i = [P.try (parserNS parser ns) | ns <- (initsEndAt (=='.') i)]  -- | Parses a name-name :: IdrisParser (Name, FC)-name = (<?> "name") $ do+name :: (Parsing m, MonadState IState m) => m Name+name = do     keywords <- syntax_keywords <$> get     aliases  <- module_aliases  <$> get-    (n, fc) <- iName keywords-    return (unalias aliases n, fc)+    n <- iName keywords+    return (unalias aliases n)+   <?> "name"   where     unalias :: M.Map [T.Text] [T.Text] -> Name -> Name     unalias aliases (NS n ns) | Just ns' <- M.lookup ns aliases = NS n ns'@@ -395,59 +355,14 @@                       (x, "")    -> [x]                       (x, '.':y) -> x : parseNS y -opChars :: String-opChars = ":!#$%&*+./<=>?@\\^|-~"--operatorLetter :: MonadicParsing m => m Char-operatorLetter = oneOf opChars---commentMarkers :: [String]-commentMarkers = [ "--", "|||" ]--invalidOperators :: [String]-invalidOperators = [":", "=>", "->", "<-", "=", "?=", "|", "**", "==>", "\\", "%", "~", "?", "!", "@"]---- | Parses an operator-operator :: MonadicParsing m => m String-operator = do op <- token . some $ operatorLetter-              when (op `elem` (invalidOperators ++ commentMarkers)) $-                   fail $ op ++ " is not a valid operator"-              return op---- | Parses an operator-operatorFC :: MonadicParsing m => m (String, FC)-operatorFC = do (FC f (l, c) _) <- getFC-                op <- operator-                return (op, FC f (l, c) (l, c + length op))+-- | Parse a package name+packageName :: Parsing m => m String+packageName = (:) <$> P.oneOf firstChars <*> many (P.oneOf remChars)+  where firstChars = ['a'..'z'] ++ ['A'..'Z']+        remChars = ['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ ['-','_']  {- * Position helpers -}-{- | Get filename from position (returns "(interactive)" when no source file is given)  -}-fileName :: Delta -> String-fileName (Directed fn _ _ _ _) = UTF8.toString fn-fileName _                     = "(interactive)" -{- | Get line number from position -}-lineNum :: Delta -> Int-lineNum (Lines l _ _ _)      = fromIntegral l + 1-lineNum (Directed _ l _ _ _) = fromIntegral l + 1-lineNum _ = 0--{- | Get column number from position -}-columnNum :: Delta -> Int-columnNum pos = fromIntegral (column pos) + 1---{- | Get file position as FC -}-getFC :: MonadicParsing m => m FC-getFC = do s <- position-           let (dir, file) = splitFileName (fileName s)-           let f = if dir == addTrailingPathSeparator "." then file else fileName s-           return $ FC f (lineNum s, columnNum s) (lineNum s, columnNum s) -- TODO: Change to actual spanning-           -- Issue #1594 on the Issue Tracker.-           -- https://github.com/idris-lang/Idris-dev/issues/1594-- {-* Syntax helpers-} -- | Bind constraints to term bindList :: (RigCount -> Name -> FC -> PTerm -> PTerm -> PTerm) -> [(RigCount, Name, FC, PTerm)] -> PTerm -> PTerm@@ -456,16 +371,16 @@  {- | @commaSeparated p@ parses one or more occurences of `p`,      separated by commas and optional whitespace. -}-commaSeparated :: MonadicParsing m => m a -> m [a]-commaSeparated p = p `sepBy1` (spaces >> char ',' >> spaces)+commaSeparated :: Parsing m => m a -> m [a]+commaSeparated p = p `P.sepBy1` (P.space >> P.char ',' >> P.space)  {- * Layout helpers -}  -- | Push indentation to stack pushIndent :: IdrisParser ()-pushIndent = do pos <- position+pushIndent = do columnNumber <- indent                 ist <- get-                put (ist { indent_stack = (fromIntegral (column pos) + 1) : indent_stack ist })+                put (ist { indent_stack = columnNumber : indent_stack ist })  -- | Pops indentation from stack popIndent :: IdrisParser ()@@ -476,11 +391,11 @@   -- | Gets current indentation-indent :: IdrisParser Int-indent = liftM ((+1) . fromIntegral . column) position+indent :: Parsing m => m Int+indent = P.unPos . P.sourceColumn <$> P.getPosition  -- | Gets last indentation-lastIndent :: IdrisParser Int+lastIndent :: (MonadState IState m) => m Int lastIndent = do ist <- get                 case indent_stack ist of                   (x : xs) -> return x@@ -519,9 +434,8 @@   -- | Checks if the following character matches provided parser-lookAheadMatches :: MonadicParsing m => m a -> m Bool-lookAheadMatches p = do match <- lookAhead (optional p)-                        return $ isJust match+lookAheadMatches :: Parsing m => m a -> m Bool+lookAheadMatches p = isJust <$> P.lookAhead (P.optional p)  -- | Parses a start of block openBlock :: IdrisParser ()@@ -545,7 +459,7 @@ closeBlock :: IdrisParser () closeBlock = do ist <- get                 bs <- case brace_stack ist of-                        []  -> eof >> return []+                        []  -> [] <$ P.eof                         Nothing : xs -> lchar '}' >> return xs <?> "end of block"                         Just lvl : xs -> (do i   <- indent                                              isParen <- lookAheadMatches (char ')')@@ -554,7 +468,7 @@                                                 then fail "not end of block"                                                 else return xs)                                           <|> (do notOpenBraces-                                                  eof+                                                  P.eof                                                   return [])                 put (ist { brace_stack = bs }) @@ -563,19 +477,19 @@ terminator =     do lchar ';'; popIndent              <|> do c <- indent; l <- lastIndent                     if c <= l then popIndent else fail "not a terminator"-             <|> do isParen <- lookAheadMatches (oneOf ")}")+             <|> do isParen <- lookAheadMatches (P.oneOf ")}")                     if isParen then popIndent else fail "not a terminator"-             <|> lookAhead eof+             <|> P.lookAhead P.eof  -- | Parses and keeps a terminator keepTerminator :: IdrisParser ()-keepTerminator =  do lchar ';'; return ()+keepTerminator =  () <$ lchar ';'               <|> do c <- indent; l <- lastIndent                      unless (c <= l) $ fail "not a terminator"-              <|> do isParen <- lookAheadMatches (oneOf ")}|")+              <|> do isParen <- lookAheadMatches (P.oneOf ")}|")                      isIn <- lookAheadMatches (reserved "in")                      unless (isIn || isParen) $ fail "not a terminator"-              <|> lookAhead eof+              <|> P.lookAhead P.eof  -- | Checks if application expression does not end notEndApp :: IdrisParser ()@@ -587,40 +501,15 @@ notEndBlock = do ist <- get                  case brace_stack ist of                       Just lvl : xs -> do i <- indent-                                          isParen <- lookAheadMatches (char ')')+                                          isParen <- lookAheadMatches (P.char ')')                                           when (i < lvl || isParen) (fail "end of block")                       _ -> return () --- | Representation of an operation that can compare the current indentation with the last indentation, and an error message if it fails-data IndentProperty = IndentProperty (Int -> Int -> Bool) String---- | Allows comparison of indent, and fails if property doesn't hold-indentPropHolds :: IndentProperty -> IdrisParser ()-indentPropHolds (IndentProperty op msg) = do+indentGt :: (Parsing m, MonadState IState m) => m ()+indentGt = do   li <- lastIndent   i <- indent-  when (not $ op i li) $ fail ("Wrong indention: " ++ msg)---- | Greater-than indent property-gtProp :: IndentProperty-gtProp = IndentProperty (>) "should be greater than context indentation"---- | Greater-than or equal to indent property-gteProp :: IndentProperty-gteProp = IndentProperty (>=) "should be greater than or equal context indentation"---- | Equal indent property-eqProp :: IndentProperty-eqProp = IndentProperty (==) "should be equal to context indentation"---- | Less-than indent property-ltProp :: IndentProperty-ltProp = IndentProperty (<) "should be less than context indentation"---- | Less-than or equal to indent property-lteProp :: IndentProperty-lteProp = IndentProperty (<=) "should be less than or equal to context indentation"-+  when (i <= li) $ fail "Wrong indention: should be greater than context indentation"  -- | Checks that there are no braces that are not closed notOpenBraces :: IdrisParser ()@@ -631,28 +520,10 @@  {- | Parses an accessibilty modifier (e.g. public, private) -} accessibility' :: IdrisParser Accessibility-accessibility'-              = do reserved "public";-                   gotexp <- optional (reserved "export")-                   case gotexp of-                        Just _ -> return ()-                        Nothing -> do-                           ist <- get-                           fc <- getFC-                           put ist { parserWarnings =-                              (fc, Msg "'public' is deprecated. Use 'public export' instead.")-                                   : parserWarnings ist }-                   return Public-            <|> do reserved "abstract";-                   ist <- get-                   fc <- getFC-                   put ist { parserWarnings =-                      (fc, Msg "The 'abstract' keyword is deprecated. Use 'export' instead.")-                           : parserWarnings ist }-                   return Frozen-            <|> do reserved "export"; return Frozen-            <|> do reserved "private";  return Private-            <?> "accessibility modifier"+accessibility' = Public  <$ reserved "public" <* reserved "export"+             <|> Frozen  <$ reserved "export"+             <|> Private <$ reserved "private"+             <?> "accessibility modifier"  accessibility :: IdrisParser Accessibility accessibility = do acc <- optional accessibility'@@ -679,34 +550,3 @@ {- | Error message with possible fixes list -} fixErrorMsg :: String -> [String] -> String fixErrorMsg msg fixes = msg ++ ", possible fixes:\n" ++ (concat $ intersperse "\n\nor\n\n" fixes)---- | Collect 'PClauses' with the same function name-collect :: [PDecl] -> [PDecl]-collect (c@(PClauses _ o _ _) : ds)-    = clauses (cname c) [] (c : ds)-  where clauses :: Maybe Name -> [PClause] -> [PDecl] -> [PDecl]-        clauses j@(Just n) acc (PClauses fc _ _ [PClause fc' n' l ws r w] : ds)-           | n == n' = clauses j (PClause fc' n' l ws r (collect w) : acc) ds-        clauses j@(Just n) acc (PClauses fc _ _ [PWith fc' n' l ws r pn w] : ds)-           | n == n' = clauses j (PWith fc' n' l ws r pn (collect w) : acc) ds-        clauses (Just n) acc xs = PClauses (fcOf c) o n (reverse acc) : collect xs-        clauses Nothing acc (x:xs) = collect xs-        clauses Nothing acc [] = []--        cname :: PDecl -> Maybe Name-        cname (PClauses fc _ _ [PClause _ n _ _ _ _]) = Just n-        cname (PClauses fc _ _ [PWith   _ n _ _ _ _ _]) = Just n-        cname (PClauses fc _ _ [PClauseR _ _ _ _]) = Nothing-        cname (PClauses fc _ _ [PWithR _ _ _ _ _]) = Nothing-        fcOf :: PDecl -> FC-        fcOf (PClauses fc _ _ _) = fc-collect (PParams f ns ps : ds) = PParams f ns (collect ps) : collect ds-collect (POpenInterfaces f ns ps : ds) = POpenInterfaces f ns (collect ps) : collect ds-collect (PMutual f ms : ds) = PMutual f (collect ms) : collect ds-collect (PNamespace ns fc ps : ds) = PNamespace ns fc (collect ps) : collect ds-collect (PInterface doc f s cs n nfc ps pdocs fds ds cn cd : ds')-    = PInterface doc f s cs n nfc ps pdocs fds (collect ds) cn cd : collect ds'-collect (PImplementation doc argDocs f s cs pnames acc opts n nfc ps pextra t en ds : ds')-    = PImplementation doc argDocs f s cs pnames acc opts n nfc ps pextra t en (collect ds) : collect ds'-collect (d : ds) = d : collect ds-collect [] = []
src/Idris/Parser/Ops.hs view
@@ -1,12 +1,12 @@ {-| Module      : Idris.Parser.Ops Description : Parser for operators and fixity declarations.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -} {-# LANGUAGE ConstraintKinds, FlexibleContexts, GeneralizedNewtypeDeriving,-             PatternGuards #-}+             MultiParamTypeClasses, PatternGuards #-} module Idris.Parser.Ops where  import Idris.AbsSyntax@@ -18,81 +18,100 @@ import Control.Applicative import Control.Monad import Control.Monad.State.Strict-import qualified Data.ByteString.UTF8 as UTF8-import Data.Char-import qualified Data.HashSet as HS+import Data.Char (isAlpha) import Data.List-import qualified Data.List.Split as Spl-import Data.Maybe-import Data.Monoid-import qualified Data.Text as T-import Debug.Trace-import qualified Text.Parser.Char as Chr-import Text.Parser.Expression-import Text.Parser.LookAhead-import qualified Text.Parser.Token as Tok-import qualified Text.Parser.Token.Highlight as Hi-import Text.Trifecta hiding (char, charLiteral, natural, span, string,-                      stringLiteral, symbol, whiteSpace)-import Text.Trifecta.Delta+import Data.List.NonEmpty (fromList)+import Text.Megaparsec ((<?>))+import qualified Text.Megaparsec as P+import qualified Text.Megaparsec.Char as P+import qualified Text.Megaparsec.Expr as P  -- | Creates table for fixity declarations to build expression parser -- using pre-build and user-defined operator/fixity declarations-table :: [FixDecl] -> OperatorTable IdrisParser PTerm+table :: [FixDecl] -> [[P.Operator IdrisParser PTerm]] table fixes    = [[prefix "-" (\fc x -> PApp fc (PRef fc [fc] (sUN "negate")) [pexp x])]] ++       toTable (reverse fixes) ++-     [[backtick],-      [binary "$" (\fc x y -> flatten $ PApp fc x [pexp y]) AssocRight],-      [binary "="  (\fc x y -> PApp fc (PRef fc [fc] eqTy) [pexp x, pexp y]) AssocLeft],-      [nofixityoperator]]+     [[noFixityBacktickOperator],+      [binary "$" P.InfixR $ \fc _ x y -> flatten $ PApp fc x [pexp y]],+      [binary "=" P.InfixL $ \fc _ x y -> PApp fc (PRef fc [fc] eqTy) [pexp x, pexp y]],+      [noFixityOperator]]   where-    flatten :: PTerm -> PTerm -- flatten application+    flatten                            :: PTerm -> PTerm -- flatten application     flatten (PApp fc (PApp _ f as) bs) = flatten (PApp fc f (as ++ bs))-    flatten t = t+    flatten t                          = t +    noFixityBacktickOperator :: P.Operator IdrisParser PTerm+    noFixityBacktickOperator = P.InfixN $ do+                                 (n, fc) <- withExtent backtickOperator+                                 return $ \x y -> PApp fc (PRef fc [fc] n) [pexp x, pexp y] --- | Calculates table for fixity declarations-toTable :: [FixDecl] -> OperatorTable IdrisParser PTerm-toTable fs = map (map toBin)-                 (groupBy (\ (Fix x _) (Fix y _) -> prec x == prec y) fs)-   where toBin (Fix (PrefixN _) op) = prefix op-                                       (\fc x -> PApp fc (PRef fc [] (sUN op)) [pexp x])-         toBin (Fix f op)-            = binary op (\fc x y -> PApp fc (PRef fc [] (sUN op)) [pexp x,pexp y]) (assoc f)-         assoc (Infixl _) = AssocLeft-         assoc (Infixr _) = AssocRight-         assoc (InfixN _) = AssocNone+    -- | Operator without fixity (throws an error)+    noFixityOperator :: P.Operator IdrisParser PTerm+    noFixityOperator = P.InfixN $ do+                         indentGt+                         op <- P.try symbolicOperator+                         P.unexpected . P.Label . fromList $ "Operator without known fixity: " ++ op --- | Binary operator-binary :: String -> (FC -> PTerm -> PTerm -> PTerm) -> Assoc -> Operator IdrisParser PTerm-binary name f = Infix (do indentPropHolds gtProp-                          fc <- reservedOpFC name-                          indentPropHolds gtProp-                          return (f fc))+    -- | Calculates table for fixity declarations+    toTable    :: [FixDecl] -> [[P.Operator IdrisParser PTerm]]+    toTable fs = map (map toBin) (groupBy (\ (Fix x _) (Fix y _) -> prec x == prec y) fs) --- | Prefix operator-prefix :: String -> (FC -> PTerm -> PTerm) -> Operator IdrisParser PTerm-prefix name f = Prefix (do reservedOp name-                           fc <- getFC-                           indentPropHolds gtProp-                           return (f fc))+    toBin (Fix (PrefixN _) op) = prefix op $ \fc x ->+                                   PApp fc (PRef fc [] (sUN op)) [pexp x]+    toBin (Fix f op)           = binary op (assoc f) $ \fc n x y ->+                                   PApp fc (PRef fc [] n) [pexp x,pexp y] --- | Backtick operator-backtick :: Operator IdrisParser PTerm-backtick = Infix (do indentPropHolds gtProp-                     lchar '`'; (n, fc) <- fnName-                     lchar '`'-                     indentPropHolds gtProp-                     return (\x y -> PApp fc (PRef fc [fc] n) [pexp x, pexp y])) AssocNone+    assoc (Infixl _) = P.InfixL+    assoc (Infixr _) = P.InfixR+    assoc (InfixN _) = P.InfixN --- | Operator without fixity (throws an error)-nofixityoperator :: Operator IdrisParser PTerm-nofixityoperator = Infix (do indentPropHolds gtProp-                             op <- try operator-                             unexpected $ "Operator without known fixity: " ++ op) AssocNone+    isBacktick         :: String -> Bool+    isBacktick (c : _) = c == '_' || isAlpha c+    isBacktick _       = False +    binary :: String -> (IdrisParser (PTerm -> PTerm -> PTerm) -> P.Operator IdrisParser PTerm) -> (FC -> Name -> PTerm -> PTerm -> PTerm) -> P.Operator IdrisParser PTerm+    binary name ctor f+      | isBacktick name = ctor $ P.try $ do+                            (n, fc) <- withExtent backtickOperator+                            guard $ show (nsroot n) == name+                            return $ f fc n+      | otherwise       = ctor $ do+                            indentGt+                            fc <- extent $ reservedOp name+                            indentGt+                            return $ f fc (sUN name) +    prefix :: String -> (FC -> PTerm -> PTerm) -> P.Operator IdrisParser PTerm+    prefix name f = P.Prefix $ do+                      fc <- extent $ reservedOp name+                      indentGt+                      return (f fc)++{- | Parses a function used as an operator -- enclosed in backticks++@+  BacktickOperator ::=+    '`' Name '`'+    ;+@+-}+backtickOperator :: (Parsing m, MonadState IState m) => m Name+backtickOperator = P.between (indentGt *> lchar '`') (indentGt *> lchar '`') name++{- | Parses an operator name (either a symbolic name or a backtick-quoted name)++@+  OperatorName ::=+      SymbolicOperator+    | BacktickOperator+    ;+@+-}+operatorName :: (Parsing m, MonadState IState m) => m Name+operatorName =     sUN <$> symbolicOperator+               <|> backtickOperator+ {- | Parses an operator in function position i.e. enclosed by `()', with an  optional namespace @@ -104,15 +123,9 @@ @  -}-operatorFront :: IdrisParser (Name, FC)-operatorFront = try (do (FC f (l, c) _) <- getFC-                        op <- lchar '(' *> reservedOp "="  <* lchar ')'-                        return (eqTy, FC f (l, c) (l, c+3)))-            <|> maybeWithNS (do (FC f (l, c) _) <- getFC-                                op <- lchar '(' *> operator-                                (FC _ _ (l', c')) <- getFC-                                lchar ')'-                                return (op, (FC f (l, c) (l', c' + 1)))) False []+operatorFront :: Parsing m => m Name+operatorFront = do     P.try $ lchar '(' *> (eqTy <$ reservedOp "=") <* lchar ')'+                   <|> maybeWithNS (lchar '(' *> symbolicOperator <* lchar ')') []  {- | Parses a function (either normal name or operator) @@ -120,8 +133,8 @@   FnName ::= Name | OperatorFront; @ -}-fnName :: IdrisParser (Name, FC)-fnName = try operatorFront <|> name <?> "function name"+fnName :: (Parsing m, MonadState IState m) => m Name+fnName = P.try operatorFront <|> name <?> "function name"  {- | Parses a fixity declaration @@@ -131,10 +144,12 @@ @ -} fixity :: IdrisParser PDecl-fixity = do pushIndent-            f <- fixityType; i <- fst <$> natural;-            ops <- sepBy1 operator (lchar ',')-            terminator+fixity = do ((f, i, ops), fc) <- withExtent $ do+                pushIndent+                f <- fixityType; i <- natural+                ops <- P.sepBy1 (show . nsroot <$> operatorName) (lchar ',')+                terminator+                return (f, i, ops)             let prec = fromInteger i             istate <- get             let infixes = idris_infixes istate@@ -145,19 +160,19 @@                then do put (istate { idris_infixes = nub $ sort (fs ++ infixes)                                      , ibc_write     = map IBCFix fs ++ ibc_write istate                                    })-                       fc <- getFC                        return (PFix fc (f prec) ops)                else fail $ concatMap (\(f, (x:xs)) -> "Illegal redeclaration of fixity:\n\t\""                                                 ++ show f ++ "\" overrides \"" ++ show x ++ "\"") ill          <?> "fixity declaration"-             where alreadyDeclared :: [FixDecl] -> FixDecl -> (FixDecl, [FixDecl])-                   alreadyDeclared fs f = (f, filter ((extractName f ==) . extractName) fs)+  where+    alreadyDeclared :: [FixDecl] -> FixDecl -> (FixDecl, [FixDecl])+    alreadyDeclared fs f = (f, filter ((extractName f ==) . extractName) fs) -                   checkValidity :: (FixDecl, [FixDecl]) -> Bool-                   checkValidity (f, fs) = all (== f) fs+    checkValidity :: (FixDecl, [FixDecl]) -> Bool+    checkValidity (f, fs) = all (== f) fs -                   extractName :: FixDecl -> String-                   extractName (Fix _ n) = n+    extractName :: FixDecl -> String+    extractName (Fix _ n) = n  -- | Check that a declaration of an operator also has fixity declared checkDeclFixity :: IdrisParser PDecl -> IdrisParser PDecl@@ -198,3 +213,29 @@          <|> do reserved "infix";  return InfixN          <|> do reserved "prefix"; return PrefixN          <?> "fixity type"++opChars :: String+opChars = ":!#$%&*+./<=>?@\\^|-~"++operatorLetter :: Parsing m => m Char+operatorLetter = P.oneOf opChars++commentMarkers :: [String]+commentMarkers = [ "--", "|||" ]++invalidOperators :: [String]+invalidOperators = [":", "=>", "->", "<-", "=", "?=", "|", "**", "==>", "\\", "%", "~", "?", "!", "@"]++-- | Parses an operator+symbolicOperator :: Parsing m => m String+symbolicOperator = do op <- token . some $ operatorLetter+                      when (op `elem` (invalidOperators ++ commentMarkers)) $+                           fail $ op ++ " is not a valid operator"+                      return op++-- Taken from Parsec (c) Daan Leijen 1999-2001, (c) Paolo Martini 2007+-- | Parses a reserved operator+reservedOp :: Parsing m => String -> m ()+reservedOp name = token $ P.try $+  do string name+     P.notFollowedBy operatorLetter <?> ("end of " ++ show name)
+ src/Idris/Parser/Stack.hs view
@@ -0,0 +1,136 @@+{-|+Module      : Idris.Parser.Stack+Description : Idris parser stack and its primitives.++License     : BSD3+Maintainer  : The Idris Community.+-}+{-# LANGUAGE ConstraintKinds, FlexibleContexts, MultiParamTypeClasses #-}+module Idris.Parser.Stack+  ( -- * Parsing+    Parser(..)+  , Parsing(..)+  , runparser+    -- * Parse errors+  , ParseError+  , prettyError+    -- * Mark and restore+  , Mark+  , mark+  , restore++    -- * Tracking the extent of productions+    --+    -- The parser stack automatically builds up the extent of any parse from+    -- the extents of sub-parsers wrapped with @trackExtent@.+  , getFC+  , addExtent+  , trackExtent+  , extent+  , withExtent+  , appExtent+  )+where++import Idris.Core.TT (FC(..))+import Idris.Output (Message(..))++import Control.Arrow (app)+import Control.Monad.State.Strict (StateT(..), evalStateT)+import Control.Monad.Writer.Strict (MonadWriter(..), WriterT(..), listen,+                                    runWriterT, tell)+import qualified Data.List.NonEmpty as NonEmpty+import Data.Void (Void(..))+import System.FilePath (addTrailingPathSeparator, splitFileName)+import qualified Text.Megaparsec as P+import qualified Util.Pretty as PP++{- * Parsing -}++-- | Our parser stack with state of type @s@+type Parser s = StateT s (WriterT FC (P.Parsec Void String))++-- | A constraint for parsing without state+type Parsing m = (P.MonadParsec Void String m, MonadWriter FC m)++-- | Run the Idris parser stack+runparser :: Parser st res -> st -> String -> String -> Either ParseError res+runparser p i inputname s =+  case P.parse (runWriterT (evalStateT p i)) inputname s of+    Left err -> Left $ ParseError s err+    Right v  -> Right $ fst v++{- * Parse errors -}++data ParseError = ParseError String (P.ParseError (P.Token String) Void)++instance Message ParseError where+  messageExtent (ParseError _ err) = sourcePositionFC pos+    where+      (pos NonEmpty.:| _) = P.errorPos err+  messageText (ParseError _ err) = PP.text . init . P.parseErrorTextPretty $ err+  messageSource (ParseError src _) = Just src++-- | A fully formatted parse error, with caret and bar, etc.+prettyError                    :: ParseError -> String+prettyError (ParseError s err) = P.parseErrorPretty' s err++{- * Mark and restore -}++type Mark = P.State String++-- | Retrieve the parser state so we can restart from this point later.+mark :: Parsing m => m Mark+mark = P.getParserState++restore :: Parsing m => Mark -> m ()+restore = P.setParserState++{- * Tracking the extent of productions -}++sourcePositionFC :: P.SourcePos -> FC+sourcePositionFC (P.SourcePos name line column) =+  FC f (lineNumber, columnNumber) (lineNumber, columnNumber)+  where+    lineNumber = P.unPos line+    columnNumber = P.unPos column+    (dir, file) = splitFileName name+    f = if dir == addTrailingPathSeparator "."+        then file+        else name++-- | Get the current parse position.+--+-- This is useful when the position is needed in a way unrelated to the+-- heirarchy of parsers.  Prefer using @withExtent@ and friends.+getFC :: Parsing m => m FC+getFC = sourcePositionFC <$> P.getPosition++-- | Add an extent (widen) our current parsing context.+addExtent :: MonadWriter FC m => FC -> m ()+addExtent = tell++-- | Run a parser and track its extent.+--+-- Wrap bare Megaparsec parsers with this to make them "visible" in error+-- messages.  Do not wrap whitespace or comment parsers.  If you find an+-- extent is taking trailing whitespace, it's likely there's a double-wrapped+-- parser (usually via @Idris.Parser.Helpers.token@).+trackExtent :: Parsing m => m a -> m a+trackExtent p = do (FC f (sr, sc) _) <- getFC+                   result <- p+                   (FC f _ (er, ec)) <- getFC+                   addExtent (FC f (sr, sc) (er, max 1 (ec - 1)))+                   return result++-- | Run a parser, discard its value, and return its extent.+extent :: MonadWriter FC m => m a -> m FC+extent = fmap snd . withExtent++-- | Run a parser and return its value and extent.+withExtent :: MonadWriter FC m => m a -> m (a, FC)+withExtent = listen++-- | Run a parser and inject the extent after via function application.+appExtent :: MonadWriter FC m => m (FC -> a) -> m a+appExtent = fmap app . withExtent
src/Idris/PartialEval.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.PartialEval Description : Implementation of a partial evaluator.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -19,10 +19,7 @@ import Idris.Core.TT import Idris.Delaborate -import Control.Applicative import Control.Monad.State-import Data.Maybe-import Debug.Trace  -- | Data type representing binding-time annotations for partial evaluation of arguments data PEArgType = ImplicitS Name -- ^ Implicit static argument@@ -97,12 +94,12 @@   where     -- Specialise static argument in type by let-binding provided value instead     -- of expecting it as a function argument-    st ((ExplicitS, v) : xs) (Bind n (Pi _ _ t _) sc)-         = Bind n (Let t v) (st xs sc)-    st ((ImplicitS _, v) : xs) (Bind n (Pi _ _ t _) sc)-         = Bind n (Let t v) (st xs sc)-    st ((ConstraintS, v) : xs) (Bind n (Pi _ _ t _) sc)-         = Bind n (Let t v) (st xs sc)+    st ((ExplicitS, v) : xs) (Bind n (Pi rc _ t _) sc)+         = Bind n (Let rc t v) (st xs sc)+    st ((ImplicitS _, v) : xs) (Bind n (Pi rc _ t _) sc)+         = Bind n (Let rc t v) (st xs sc)+    st ((ConstraintS, v) : xs) (Bind n (Pi rc _ t _) sc)+         = Bind n (Let rc t v) (st xs sc)     -- Erase argument from function type     st ((UnifiedD, _) : xs) (Bind n (Pi _ _ t _) sc)          = st xs sc@@ -261,10 +258,6 @@     mkRHSargs (_ : ns) as = mkRHSargs ns as     mkRHSargs _ _ = [] -    mkSubst :: (Term, Term) -> Maybe (Name, Term)-    mkSubst (P _ n _, t) = Just (n, t)-    mkSubst _ = Nothing- -- | Creates a new declaration for a specialised function application. -- Simple version at the moment: just create a version which is a direct -- application of the function to be specialised.@@ -371,7 +364,7 @@ --                            _ -> []                       else []                _ -> []-    ga env (Bind n (Let t v) sc) = ga env v ++ ga (n : env) sc+    ga env (Bind n (Let rc t v) sc) = ga env v ++ ga (n : env) sc     ga env (Bind n t sc) = ga (n : env) sc     ga env t = [] 
src/Idris/Primitives.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Primitives Description : Provision of primitive data types.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -9,7 +9,6 @@  module Idris.Primitives(primitives, Prim(..)) where -import Idris.AbsSyntax import Idris.Core.Evaluate import Idris.Core.TT import IRTS.Lang@@ -18,9 +17,6 @@ import Data.Char import Data.Function (on) import Data.Int-import qualified Data.Vector.Unboxed as V-import Data.Word-import Debug.Trace  data Prim = Prim { p_name  :: Name,                    p_type  :: Type,@@ -34,10 +30,9 @@ ty []     x = Constant x ty (t:ts) x = Bind (sMN 0 "T") (Pi RigW Nothing (Constant t) (TType (UVar [] (-3)))) (ty ts x) -total, partial, iopartial :: Totality+total, partial :: Totality total = Total [] partial = Partial NotCovering-iopartial = Partial ExternalIO  primitives :: [Prim] primitives =@@ -153,6 +148,8 @@      (1, LFACos) total,    Prim (sUN "prim__floatATan") (ty [(AType ATFloat)] (AType ATFloat)) 1 (p_floatATan)      (1, LFATan) total,+   Prim (sUN "prim__floatATan2") (ty [(AType ATFloat), (AType ATFloat)] (AType ATFloat)) 2 (p_floatATan2)+     (2, LFATan2) total,    Prim (sUN "prim__floatSqrt") (ty [(AType ATFloat)] (AType ATFloat)) 1 (p_floatSqrt)      (1, LFSqrt) total,    Prim (sUN "prim__floatFloor") (ty [(AType ATFloat)] (AType ATFloat)) 1 (p_floatFloor)@@ -210,7 +207,7 @@     [ iBinOp ity "add" (bitBin ity (+)) (LPlus . ATInt) total     , iBinOp ity "sub" (bitBin ity (-)) (LMinus . ATInt) total     , iBinOp ity "mul" (bitBin ity (*)) (LTimes . ATInt) total-    , iBinOp ity "udiv" (bitBin ity div) LUDiv partial+    , iBinOp ity "udiv" (bitBin ity quot) LUDiv partial     , iBinOp ity "sdiv" (bsdiv ity) (LSDiv . ATInt) partial     , iBinOp ity "urem" (bitBin ity rem) LURem partial     , iBinOp ity "srem" (bsrem ity) (LSRem . ATInt) partial@@ -235,36 +232,6 @@                (1, LFloatInt ity) total     ] -bitcastPrim :: ArithTy -> ArithTy -> (ArithTy -> [Const] -> Maybe Const) -> PrimFn -> Prim-bitcastPrim from to impl prim =-    Prim (sUN $ "prim__bitcast" ++ aTyName from ++ "_" ++ aTyName to) (ty [AType from] (AType to)) 1 (impl to)-         (1, prim) total--concatWord8 :: (Word8, Word8) -> Word16-concatWord8 (high, low) = fromIntegral high .|. (fromIntegral low `shiftL` 8)--concatWord16 :: (Word16, Word16) -> Word32-concatWord16 (high, low) = fromIntegral high .|. (fromIntegral low `shiftL` 16)--concatWord32 :: (Word32, Word32) -> Word64-concatWord32 (high, low) = fromIntegral high .|. (fromIntegral low `shiftL` 32)--truncWord16 :: Bool -> Word16 -> Word8-truncWord16 True x = fromIntegral (x `shiftR` 8)-truncWord16 False x = fromIntegral x--truncWord32 :: Bool -> Word32 -> Word16-truncWord32 True x = fromIntegral (x `shiftR` 16)-truncWord32 False x = fromIntegral x--truncWord64 :: Bool -> Word64 -> Word32-truncWord64 True x = fromIntegral (x `shiftR` 32)-truncWord64 False x = fromIntegral x--aTyName :: ArithTy -> String-aTyName (ATInt t) = intTyName t-aTyName ATFloat = "Float"- iCmp  :: IntTy -> String -> Bool -> ([Const] -> Maybe Const) -> (IntTy -> PrimFn) -> Totality -> Prim iCmp ity op self impl irop totality     = Prim (sUN $ "prim__" ++ op ++ intTyName ity)@@ -295,11 +262,6 @@                         Just $ I i bfBin _ _ = Nothing -bcBin :: (Char -> Char -> Bool) -> [Const] -> Maybe Const-bcBin op [Ch x, Ch y] = let i = (if op x y then 1 else 0) in-                        Just $ I i-bcBin _ _ = Nothing- bsBin :: (String -> String -> Bool) -> [Const] -> Maybe Const bsBin op [Str x, Str y]     = let i = (if op x y then 1 else 0) in@@ -325,17 +287,17 @@ bsrem _ _ = Nothing  bsdiv :: IntTy -> [Const] -> Maybe Const-bsdiv ITBig [BI x, BI y] = Just . BI $ x `div` y+bsdiv ITBig [BI x, BI y] = Just . BI $ x `quot` y bsdiv (ITFixed IT8) [B8 x, B8 y]-    = Just $ B8 (fromIntegral (fromIntegral x `div` fromIntegral y :: Int8))+    = Just $ B8 (fromIntegral (fromIntegral x `quot` fromIntegral y :: Int8)) bsdiv (ITFixed IT16) [B16 x, B16 y]-    = Just $ B16 (fromIntegral (fromIntegral x `div` fromIntegral y :: Int16))+    = Just $ B16 (fromIntegral (fromIntegral x `quot` fromIntegral y :: Int16)) bsdiv (ITFixed IT32) [B32 x, B32 y]-    = Just $ B32 (fromIntegral (fromIntegral x `div` fromIntegral y :: Int32))+    = Just $ B32 (fromIntegral (fromIntegral x `quot` fromIntegral y :: Int32)) bsdiv (ITFixed IT64) [B64 x, B64 y]-    = Just $ B64 (fromIntegral (fromIntegral x `div` fromIntegral y :: Int64))-bsdiv ITNative [I x, I y] = Just $ I (x `div` y)-bsdiv ITChar [Ch x, Ch y] = Just $ Ch (chr $ (ord x) `div` (ord y))+    = Just $ B64 (fromIntegral (fromIntegral x `quot` fromIntegral y :: Int64))+bsdiv ITNative [I x, I y] = Just $ I (x `quot` y)+bsdiv ITChar [Ch x, Ch y] = Just $ Ch (chr $ (ord x) `quot` (ord y)) bsdiv _ _ = Nothing  bashr :: IntTy -> [Const] -> Maybe Const@@ -501,6 +463,10 @@ p_floatSqrt = p_fPrim sqrt p_floatFloor = p_fPrim (fromInteger . floor) p_floatCeil = p_fPrim (fromInteger . ceiling)++p_floatATan2 :: [Const] -> Maybe Const+p_floatATan2 [Fl y, Fl x] = Just $ Fl (atan2 y x)+p_floatATan2 _ = Nothing  p_strLen, p_strHead, p_strTail, p_strIndex, p_strCons, p_strRev, p_strSubstr :: [Const] -> Maybe Const p_strLen [Str xs] = Just $ I (length xs)
src/Idris/ProofSearch.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.ProofSearch Description : Searches current context for proofs'-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -16,21 +16,17 @@   ) where  import Idris.AbsSyntax-import Idris.Core.CaseTree import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Evaluate import Idris.Core.TT-import Idris.Core.Typecheck import Idris.Core.Unify import Idris.Delaborate-import Idris.Error  import Control.Applicative ((<$>)) import Control.Monad import Control.Monad.State.Strict import Data.List import qualified Data.Set as S-import Debug.Trace  -- Pass in a term elaborator to avoid a cyclic dependency with ElabTerm @@ -52,7 +48,6 @@         tryAll ((x, _, b):xs)            = do -- if type of x has any holes in it, move on                 hs <- get_holes-                let badhs = hs -- filter (flip notElem holesOK) hs                 g <- goal                 -- anywhere but the top is okay for a hole, if holesOK set                 if -- all (\n -> not (n `elem` badhs)) (freeNames (binderTy b))@@ -88,7 +83,6 @@         tryAll ((x, _, b):xs)            = do -- if type of x has any holes in it, move on                 hs <- get_holes-                let badhs = hs -- filter (flip notElem holesOK) hs                 g <- goal                 env <- get_env                 -- anywhere but the top is okay for a hole, if holesOK set@@ -145,7 +139,7 @@   where     -- if nothing worked, make a new metavariable     tryAllFns [] | fromProver = cantSolveGoal-    tryAllFns [] = do attack; defer [] nroot; solve+    tryAllFns [] = do attack; defer [] [] nroot; solve     tryAllFns (f : fs) = try' (tryFn f) (tryAllFns fs) True      tryFn (f, args) = do let imps = map isImp args@@ -161,7 +155,7 @@                          if fromProver then cantSolveGoal                            else do                              mapM_ (\ h -> do focus h-                                              attack; defer [] nroot; solve)+                                              attack; defer [] [] nroot; solve)                                  (hs' \\ hs) --                                  (filter (\ (x, y) -> not x) (zip (map fst imps) args))                              solve@@ -233,9 +227,6 @@        | (P _ fn _, args@(_:_)) <- unApply fa = fn `notElem` hs     notHole _ _ = True -    inHS hs (P _ n _) = n `elem` hs-    isHS _ _ = False-     toUN t@(P nt (MN i n) ty)        | ('_':xs) <- str n = t        | otherwise = P nt (UN n) ty@@ -251,7 +242,7 @@     -- that's no use)     psRec :: Bool -> Int -> [Name] -> S.Set Type -> ElabD ()     psRec _ 0 locs tys | fromProver = cantSolveGoal-    psRec rec 0 locs tys = do attack; defer [] nroot; solve --fail "Maximum depth reached"+    psRec rec 0 locs tys = do attack; defer [] [] nroot; solve --fail "Maximum depth reached"     psRec False d locs tys = tryCons d locs tys hints     psRec True d locs tys                  = do compute@@ -267,7 +258,7 @@              -- if all else fails, make a new metavariable                          (if fromProver                              then fail "cantSolveGoal"-                             else do attack; defer [] nroot; solve) True) True+                             else do attack; defer [] [] nroot; solve) True) True      -- get recursive function name. Only user given names make sense.     getFn d (Just f) | d < maxDepth-1 && usersname f = [f]@@ -444,12 +435,6 @@     isMeta ns (P _ n _) = n `elem` ns     isMeta _ _ = False -    notHole hs (P _ n _, c)-       | (P _ cn _, _) <- unApply (getRetTy c),-         n `elem` hs && isConName cn (tt_ctxt ist) = False-       | Constant _ <- c = not (n `elem` hs)-    notHole _ _ = True-     numinterface = sNS (sUN "Num") ["Interfaces","Prelude"]      addDefault t num@(P _ nc _) [P Bound a _] | nc == numinterface && defaultOn@@ -487,7 +472,6 @@        | otherwise            = do lams <- introImps                 t <- goal-                let (tc, ttypes) = trace (show t) $ unApply (getRetTy t) --                 if (all boundVar ttypes) then resolveTC (depth - 1) fn impls ist --                   else do                    -- if there's a hole in the goal, don't even try@@ -505,7 +489,7 @@ --                 traceWhen (all boundVar ttypes) ("Progress: " ++ show t ++ " with " ++ show n) $                 mapM_ (\ (_,n) -> do focus n                                      t' <- goal-                                     let (tc', ttype) = unApply (getRetTy t')+                                     let (tc', _) = unApply (getRetTy t')                                      let got = fst (unApply (getRetTy t))                                      let depth' = if tc' `elem` tcs                                                      then depth - 1 else depth
src/Idris/Prover.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Prover Description : Idris' theorem prover.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -11,12 +11,11 @@ -- Hack for GHC 7.10 and earlier compat without CPP or warnings -- This exludes (<$>) as fmap, because wl-pprint uses it for newline import Prelude (Bool(..), Either(..), Eq(..), Maybe(..), Show(..), String,-                concatMap, elem, error, flip, foldl, foldr, fst, id, init,-                length, lines, map, not, null, repeat, reverse, tail, zip, ($),-                (&&), (++), (.), (||))+                concatMap, elem, error, foldl, foldr, fst, id, init, length,+                lines, map, not, null, repeat, reverse, tail, zip, ($), (&&),+                (++), (.), (||))  import Idris.AbsSyntax-import Idris.AbsSyntaxTree import Idris.Completion import Idris.Core.CaseTree import Idris.Core.Elaborate hiding (Tactic(..))@@ -41,11 +40,9 @@  import Control.DeepSeq import Control.Monad.State.Strict-import Debug.Trace import System.Console.Haskeline import System.Console.Haskeline.History import System.IO (Handle, hPutStrLn, stdin, stdout)-import Text.Trifecta.Result (ErrInfo(..), Result(..))  -- | Launch the proof shell prover :: ElabInfo -> Bool -> Bool -> Name -> Idris ()@@ -166,7 +163,7 @@   iputGoal rendered    where-    (h : hs) = holes ps -- apparently the pattern guards don't give us this+    (h : _) = holes ps -- apparently the pattern guards don't give us this      ppo = ppOptionIst ist @@ -183,7 +180,7 @@         | not all && r == txt "rewrite_rule" = prettyPs all g ((n, False):bnd) bs     prettyPs all g bnd ((n@(MN _ _), _, _) : bs)         | not (all || n `elem` freeEnvNames bs || n `elem` goalNames g) = prettyPs all g bnd bs-    prettyPs all g bnd ((n, _, Let t v) : bs) =+    prettyPs all g bnd ((n, _, Let rig t v) : bs) =       line <> bindingOf n False <+> text "=" <+> tPretty bnd v <+> colon <+>         align (tPretty bnd t) <> prettyPs all g ((n, False):bnd) bs     prettyPs all g bnd ((n, _, b) : bs) =@@ -314,15 +311,16 @@         -- if we're abandoning, it has to be outside the scope of the catch        case cmd of-         Success (Left EAbandon) -> do iPrintError ""; ifail "Abandoned"+         Right (Left EAbandon) -> do iPrintError ""; ifail "Abandoned"          _ -> return ()         (d, prev', st, done, prf', env', res) <-          idrisCatch            (case cmd of-              Failure (ErrInfo err _) ->-                return (False, prev, e, False, prf, env, Left . Msg . show . fixColour (idris_colourRepl ist) $ err)-              Success (Left cmd') ->+              Left err -> do+                msg <- fmap (Left . Msg . show) (formatMessage err)+                return (False, prev, e, False, prf, env, msg)+              Right (Left cmd') ->                 case cmd' of                   EQED -> do hs <- lifte e get_holes                              unless (null hs) $ ifail "Incomplete proof"@@ -347,18 +345,18 @@                                    return (d', prev, st', done, prf', env, go)                   EDocStr d -> do (d', st', done, prf', go) <- docStr e prf d                                   return (d', prev, st', done, prf', env, go)-              Success (Right cmd') ->+              Right (Right cmd') ->                 case cmd' of                   DoLetP  {} -> ifail "Pattern-matching let not supported here"                   DoRewrite  {} -> ifail "Pattern-matching do-rewrite not supported here"                   DoBindP {} -> ifail "Pattern-matching <- not supported here"-                  DoLet fc i ifc Placeholder expr ->+                  DoLet fc rig i ifc Placeholder expr ->                     do (tm, ty) <- elabVal (recinfo proverfc) ERHS (inLets ist env expr)                        ctxt <- getContext                        let tm' = normaliseAll ctxt [] tm                            ty' = normaliseAll ctxt [] ty                        return (True, LetStep:prev, e, False, prf ++ [step], (i, ty', tm' ) : env, Right (iPrintResult ""))-                  DoLet fc i ifc ty expr ->+                  DoLet fc rig i ifc ty expr ->                     do (tm, ty) <- elabVal (recinfo proverfc) ERHS                                      (PApp NoFC (PRef NoFC [] (sUN "the"))                                                 [ pexp (inLets ist env ty)@@ -404,7 +402,7 @@     -- the elaborator with a custom environment here to avoid the     -- delab step.     inLets :: IState -> [(Name, Type, Term)] -> PTerm -> PTerm-    inLets ist lets tm = foldr (\(n, ty, v) b -> PLet NoFC n NoFC (delab ist ty) (delab ist v) b) tm (reverse lets)+    inLets ist lets tm = foldr (\(n, ty, v) b -> PLet NoFC RigW n NoFC (delab ist ty) (delab ist v) b) tm (reverse lets)   @@ -432,27 +430,29 @@             Nothing -> do iPrintError ""; ifail "Abandoned"             Just input -> return (parseTactic i input, input)          case cmd of-            Success Abandon -> do iPrintError ""; ifail "Abandoned"+            Right Abandon -> do iPrintError ""; ifail "Abandoned"             _ -> return ()          (d, st, done, prf', res) <- idrisCatch            (case cmd of-              Failure (ErrInfo err _) -> return (False, e, False, prf, Left . Msg . show . fixColour (idris_colourRepl i) $ err)-              Success Undo -> do (_, st) <- elabStep e loadState-                                 return (True, st, False, init prf, Right $ iPrintResult "")-              Success ProofState -> return (True, e, False, prf, Right $ iPrintResult "")-              Success ProofTerm -> do tm <- lifte e get_term-                                      iputStrLn $ "TT: " ++ show tm ++ "\n"-                                      return (False, e, False, prf, Right $ iPrintResult "")-              Success Qed -> do hs <- lifte e get_holes-                                unless (null hs) $ ifail "Incomplete proof"-                                iputStrLn "Proof completed!"-                                return (False, e, True, prf, Right $ iPrintResult "")-              Success (TCheck (PRef _ _ n)) -> checkNameType e prf n-              Success (TCheck t) -> checkType e prf t-              Success (TEval t)  -> evalTerm e prf t-              Success (TDocStr x) -> docStr e prf x-              Success (TSearch t) -> search e prf t-              Success tac ->+              Left err -> do+                msg <- fmap (Left . Msg . show) (formatMessage err)+                return (False, e, False, prf, msg)+              Right Undo -> do (_, st) <- elabStep e loadState+                               return (True, st, False, init prf, Right $ iPrintResult "")+              Right ProofState -> return (True, e, False, prf, Right $ iPrintResult "")+              Right ProofTerm -> do tm <- lifte e get_term+                                    iputStrLn $ "TT: " ++ show tm ++ "\n"+                                    return (False, e, False, prf, Right $ iPrintResult "")+              Right Qed -> do hs <- lifte e get_holes+                              unless (null hs) $ ifail "Incomplete proof"+                              iputStrLn "Proof completed!"+                              return (False, e, True, prf, Right $ iPrintResult "")+              Right (TCheck (PRef _ _ n)) -> checkNameType e prf n+              Right (TCheck t) -> checkType e prf t+              Right (TEval t)  -> evalTerm e prf t+              Right (TDocStr x) -> docStr e prf x+              Right (TSearch t) -> search e prf t+              Right tac ->                 do (_, e) <- elabStep e saveState                    (_, st) <- elabStep e (runTac autoSolve i (Just proverFC) fn tac)                    return (True, st, False, prf ++ [step], Right $ iPrintResult ""))@@ -502,7 +502,6 @@         putIState ist { tt_ctxt = ctxt' }         (tm, ty) <- elabVal (recinfo proverfc) ERHS t         let ppo = ppOptionIst ist-            ty'     = normaliseC ctxt [] ty             infixes = idris_infixes ist             action = case tm of               TType _ ->
src/Idris/Providers.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Providers Description : Idris' 'Type Provider' implementation.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -13,8 +13,6 @@   ) where  import Idris.AbsSyntax-import Idris.AbsSyntaxTree-import Idris.Core.Evaluate import Idris.Core.TT import Idris.Error 
src/Idris/REPL.hs view
@@ -6,6 +6,8 @@ -}  {-# LANGUAGE FlexibleContexts, PatternGuards #-}+-- FIXME: {-# OPTIONS_GHC -fwarn-incomplete-patterns #-}+{-# OPTIONS_GHC -fwarn-unused-imports #-}  module Idris.REPL   ( idemodeStart@@ -49,7 +51,6 @@ import Idris.Core.TT import Idris.Core.Unify import Idris.Core.WHNF-import Idris.Coverage import Idris.DataOpts import Idris.Delaborate import Idris.Docs@@ -78,6 +79,7 @@ import Idris.Termination import Idris.TypeSearch (searchByType) import Idris.WhoCalls+import IRTS.CodegenCommon import IRTS.Compiler import Network import Prelude hiding (id, (.), (<$>))@@ -91,15 +93,12 @@ import System.FSNotify.Devel (allEvents, doAllEvents) import System.IO import System.Process-import Text.Trifecta.Result (ErrInfo(..), Result(..)) import Util.DynamicLinker import Util.Net (listenOnLocalhost, listenOnLocalhostAnyPort) import Util.Pretty hiding ((</>)) import Util.System import Version_idris (gitHash) -import Debug.Trace- -- | Run the REPL repl :: IState -- ^ The initial state      -> [FilePath] -- ^ The loaded modules@@ -177,9 +176,9 @@                  IO (IState, FilePath) processNetCmd orig i h fn cmd     = do res <- case parseCmd i "(net)" cmd of-                  Failure (ErrInfo err _) -> return (Left (Msg " invalid command"))-                  Success (Right c) -> runExceptT $ evalStateT (processNet fn c) i-                  Success (Left err) -> return (Left (Msg err))+                  Left err -> return (Left (Msg " invalid command"))+                  Right (Right c) -> runExceptT $ evalStateT (processNet fn c) i+                  Right (Left err) -> return (Left (Msg err))          case res of               Right x -> return x               Left err -> do hPutStrLn h (show err)@@ -295,8 +294,8 @@   do c <- colourise      i <- getIState      case parseCmd i "(input)" cmd of-       Failure (ErrInfo err _) -> iPrintError $ show (fixColour False err)-       Success (Right (Prove mode n')) ->+       Left err -> iPrintError . show . fixColour False . parseErrorDoc $ err+       Right (Right (Prove mode n')) ->          idrisCatch            (do process fn (Prove mode n')                isetPrompt (mkPrompt mods)@@ -315,10 +314,10 @@                            IdeMode.convSExp "abandon-proof" "Abandoned" n                        _ -> return ()                      iRenderError $ pprintErr ist e)-       Success (Right cmd) -> idrisCatch+       Right (Right cmd) -> idrisCatch                         (idemodeProcess fn cmd)                         (\e -> getIState >>= iRenderError . flip pprintErr e)-       Success (Left err) -> iPrintError err+       Right (Left err) -> iPrintError err runIdeModeCommand h id orig fn mods (IdeMode.REPLCompletions str) =   do (unused, compls) <- replCompletion (reverse str, "")      let good = IdeMode.SexpList [IdeMode.SymbolAtom "ok",@@ -353,8 +352,8 @@                  (Check (PRef (FC "(idemode)" (0,0) (0,0)) [] n)) runIdeModeCommand h id orig fn mods (IdeMode.DocsFor name w) =   case parseConst orig name of-    Success c -> process "(idemode)" (DocStr (Right c) (howMuch w))-    Failure _ ->+    Right c -> process "(idemode)" (DocStr (Right c) (howMuch w))+    Left _ ->      case splitName name of        Left err -> iPrintError err        Right n -> process "(idemode)" (DocStr (Left n) (howMuch w))@@ -403,7 +402,6 @@                          | (n, (_, i, _, _, _)) <- idris_metavars ist                          , not (n `elem` primDefs)                          ]-     let ppo = ppOptionIst ist      -- splitMvs is a list of pairs of names and their split types      let splitMvs = [ (n, (premises, concl, tm))                     | (n, i, ty) <- mvTys ist mvs@@ -421,14 +419,11 @@      runIO . hPutStrLn h $        IdeMode.convSExp "return" (IdeMode.SymbolAtom "ok", mvOutput) id   where mapPair f g xs = zip (map (f . fst) xs) (map (g . snd) xs)-        firstOfThree (x, y, z) = x-        mapThird f xs = map (\(x, y, z) -> (x, y, f z)) xs-         -- | Split a function type into a pair of premises, conclusion.         -- Each maintains both the original and delaborated versions.         splitPi :: IState -> Int -> Type -> ([(Name, Type, PTerm)], Type, PTerm)         splitPi ist i (Bind n (Pi _ _ t _) rest) | i > 0 =-          let (hs, c, pc) = splitPi ist (i - 1) rest in+          let (hs, c, _) = splitPi ist (i - 1) rest in             ((n, t, delabTy' ist [] [] t False False True):hs,              c, delabTy' ist [] [] c False False True)         splitPi ist i tm = ([], tm, delabTy' ist [] [] tm False False True)@@ -606,6 +601,7 @@         unparen str = str  idemodeProcess :: FilePath -> Command -> Idris ()+idemodeProcess fn ShowVersion = process fn ShowVersion idemodeProcess fn Warranty = process fn Warranty idemodeProcess fn Help = process fn Help idemodeProcess fn (RunShellCommand cmd) =@@ -729,13 +725,11 @@          let opts = idris_options i          let quiet = opt_quiet opts          let fn = fromMaybe "" (listToMaybe inputs)-         c <- colourise          case parseCmd i "(input)" cmd of-            Failure (ErrInfo err _) ->   do iputStrLn $ show (fixColour c err)-                                            return (Just inputs)-            Success (Right Reload) ->+            Left err -> Just inputs <$ emitWarning err+            Right (Right Reload) ->                 reload orig inputs-            Success (Right Watch) ->+            Right (Right Watch) ->                 if null inputs then                   do iputStrLn "No loaded files to watch."                      return (Just inputs)@@ -743,7 +737,7 @@                   do iputStrLn efile                      iputStrLn $ "Watching for .idr changes in " ++ show inputs ++ ", press enter to cancel."                      watch orig inputs-            Success (Right (Load f toline)) ->+            Right (Right (Load f toline)) ->                 -- The $!! here prevents a space leak on reloading.                 -- This isn't a solution - but it's a temporary stopgap.                 -- See issue #2386@@ -753,22 +747,20 @@                    clearErr                    mod <- loadInputs [f] toline                    return (Just mod)-            Success (Right (ModImport f)) ->+            Right (Right (ModImport f)) ->                 do clearErr                    fmod <- loadModule f (IBC_REPL True)                    return (Just (inputs ++ maybe [] (:[]) fmod))-            Success (Right Edit) -> do -- takeMVar stvar+            Right (Right Edit) -> do -- takeMVar stvar                                edit efile orig                                return (Just inputs)-            Success (Right Proofs) -> do proofs orig-                                         return (Just inputs)-            Success (Right Quit) -> do when (not quiet) (iputStrLn "Bye bye")-                                       return Nothing-            Success (Right cmd ) -> do idrisCatch (process fn cmd)-                                          (\e -> do msg <- showErr e ; iputStrLn msg)-                                       return (Just inputs)-            Success (Left err) -> do runIO $ putStrLn err+            Right (Right Proofs) -> Just inputs <$ proofs orig+            Right (Right Quit) -> Nothing <$ when (not quiet) (iputStrLn "Bye bye")+            Right (Right cmd ) -> do idrisCatch (process fn cmd)+                                            (\e -> do msg <- showErr e ; iputStrLn msg)                                      return (Just inputs)+            Right (Left err) -> do runIO $ putStrLn err+                                   return (Just inputs)  resolveProof :: Name -> Idris Name resolveProof n'@@ -836,6 +828,7 @@  process :: FilePath -> Command -> Idris () process fn Help = iPrintResult displayHelp+process fn ShowVersion = iPrintResult getIdrisVersion process fn Warranty = iPrintResult warranty process fn (RunShellCommand cmd) = runIO $ system cmd >> return () process fn (ChangeDirectory f)@@ -981,7 +974,7 @@    = do ctxt <- getContext         ist <- getIState         let ppo = ppOptionIst ist-        case lookupNames n ctxt of+        case lookupVisibleNames n ctxt of           ts@(t:_) ->             case lookup t (idris_metavars ist) of                 Just (_, i, _, _, _) -> iRenderResult . fmap (fancifyAnnots ist True) $@@ -989,17 +982,21 @@                 Nothing -> iPrintFunTypes [] n (map (\n -> (n, pprintDelabTy ist n)) ts)           [] -> iPrintError $ "No such variable " ++ show n   where+    lookupVisibleNames :: Name -> Context -> [Name]+    lookupVisibleNames n ctxt = map fst $ lookupCtxtName n (visibleDefinitions ctxt)+     showMetavarInfo ppo ist n i          = case lookupTy n (tt_ctxt ist) of                 (ty:_) -> let ty' = normaliseC (tt_ctxt ist) [] ty in                               putTy ppo ist i [] (delab ist (errReverse ist ty'))     putTy :: PPOption -> IState -> Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation     putTy ppo ist 0 bnd sc = putGoal ppo ist bnd sc-    putTy ppo ist i bnd (PPi _ n _ t sc)+    putTy ppo ist i bnd (PPi p n _ t sc)                = let current = case n of                                    MN _ _ -> text ""                                    UN nm | ('_':'_':_) <- str nm -> text ""-                                   _ -> text "  " <>+                                   _ -> countOf (pcount p)+                                            (LinearTypes `elem` idris_language_extensions ist) <+>                                         bindingOf n False                                             <+> colon                                             <+> align (tPretty bnd ist t)@@ -1012,6 +1009,11 @@                  annotate (AnnName n Nothing Nothing Nothing) (text $ show n) <+> colon <+>                  align (tPretty bnd ist g) +    -- Only display count if linear types extension is enabled+    countOf Rig0 True = text "0"+    countOf Rig1 True = text "1"+    countOf _ _ = text " "+     tPretty bnd ist t = pprintPTerm (ppOptionIst ist) bnd [] (idris_infixes ist) t  @@ -1019,8 +1021,7 @@    = do (tm, ty) <- elabREPL (recinfo (fileFC "toplevel")) ERHS t         ctxt <- getContext         ist <- getIState-        let ppo = ppOptionIst ist-            ty' = if opt_evaltypes (idris_options ist)+        let ty' = if opt_evaltypes (idris_options ist)                      then normaliseC ctxt [] ty                      else ty         case tm of@@ -1125,7 +1126,6 @@         when (not (null imps)) $ iputStrLn (show imps)         let d = lookupDefAcc n False (tt_ctxt i)         when (not (null d)) $ iputStrLn $ "Definition: " ++ (show (head d))-        let cg = lookupCtxtName n (idris_callgraph i)         i <- getIState         let cg' = lookupCtxtName n (idris_callgraph i)         sc <- checkSizeChange n@@ -1284,7 +1284,8 @@                                return (Just m')                        ir <- compile codegen f m                        i <- getIState-                       runIO $ generate codegen (fst (head (idris_imported i))) ir+                       let ir' = ir {interfaces = iface}+                       runIO $ generate codegen (fst (head (idris_imported i))) ir'   where fc = fileFC "main" process fn (LogLvl i) = setLogLevel i process fn (LogCategory cs) = setLogCats cs@@ -1369,7 +1370,7 @@ process fn (Apropos pkgs a) =   do orig <- getIState      when (not (null pkgs)) $-       iputStrLn $ "Searching packages: " ++ showSep ", " pkgs+       iputStrLn $ "Searching packages: " ++ showSep ", " (map show pkgs)      mapM_ loadPkgIndex pkgs      ist <- getIState      let mods = aproposModules ist (T.pack a)@@ -1425,7 +1426,7 @@ process fn (MakeDoc s) =   do     istate        <- getIState          let names      = words s-             parse n    | Success x <- runparser (fmap fst name) istate fn n = Right x+             parse n    | Right x <- runparser name istate fn n = Right x              parse n    = Left n              (bad, nss) = partitionEithers $ map parse names          cd            <- runIO getCurrentDirectory@@ -1455,12 +1456,6 @@                     ts' = showTrans i ts in                     ppTm lhs <+> text " ==> " <+> ppTm rhs : ts' ---               iRenderOutput (pretty lhs)---                    iputStrLn "  ==>  "---                    iPrintTermWithType (pprintDelab i rhs)---                    iputStrLn "---------------"---                    showTrans i ts- process fn (PPrint fmt width (PRef _ _ n))    = do outs <- pprintDef False n         iPrintResult =<< renderExternal fmt width (vsep outs)@@ -1468,11 +1463,19 @@  process fn (PPrint fmt width t)    = do (tm, ty) <- elabVal (recinfo (fileFC "toplevel")) ERHS t-        ctxt <- getContext         ist <- getIState-        let ppo = ppOptionIst ist-            ty' = normaliseC ctxt [] ty         iPrintResult =<< renderExternal fmt width (pprintDelab ist tm)+++process fn Quit = iPrintError "Command ':quit' is currently unsupported"+process fn Reload = iPrintError "Command ':reload' is currently unsupported"+process fn Watch = iPrintError "Command ':watch' is currently unsupported"+process fn (Load _ _) = iPrintError "Command ':load' is currently unsupported"+process fn Edit = iPrintError "Command ':edit' is currently unsupported"+process fn Proofs = iPrintError "Command ':proofs' is currently unsupported"+process fn (Verbosity _)+   = iPrintError "Command ':verbosity' is currently unsupported"+  showTotal :: Totality -> IState -> Doc OutputAnnotation showTotal t@(Partial (Other ns)) i
src/Idris/REPL/Browse.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.REPL.Browse Description : Browse the current namespace.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}
src/Idris/REPL/Commands.hs view
@@ -3,6 +3,7 @@ import Idris.AbsSyntaxTree import Idris.Colours import Idris.Core.TT+import Idris.Imports import Idris.Options  -- | REPL commands@@ -43,7 +44,7 @@              | DynamicLink FilePath              | ListDynamic              | Pattelab PTerm-             | Search [String] PTerm+             | Search [PkgName] PTerm              | CaseSplitAt Bool Int Name              | AddClauseFrom Bool Int Name              | AddProofClauseFrom Bool Int Name@@ -65,11 +66,12 @@              | ListErrorHandlers              | SetConsoleWidth ConsoleWidth              | SetPrinterDepth (Maybe Int)-             | Apropos [String] String+             | Apropos [PkgName] String              | WhoCalls Name              | CallsWho Name              | Browse [String]              | MakeDoc String -- IdrisDoc+             | ShowVersion              | Warranty              | PrintDef Name              | PPrint OutputFmt Int PTerm
src/Idris/REPL/Parser.hs view
@@ -4,6 +4,7 @@ License     : BSD3 Maintainer  : The Idris Community. -}+{-# LANGUAGE FlexibleContexts #-} module Idris.REPL.Parser (     parseCmd   , help@@ -15,31 +16,32 @@ import Idris.Colours import Idris.Core.TT import Idris.Help+import Idris.Imports import Idris.Options-import qualified Idris.Parser as P+import qualified Idris.Parser as IP+import qualified Idris.Parser.Expr as IP+import qualified Idris.Parser.Helpers as IP+import qualified Idris.Parser.Ops as IP+ import Idris.REPL.Commands  import Control.Applicative import Control.Monad.State.Strict-import qualified Data.ByteString.UTF8 as UTF8 import Data.Char (isSpace, toLower) import Data.List import Data.List.Split (splitOn)-import Debug.Trace import System.Console.ANSI (Color(..)) import System.FilePath ((</>))-import Text.Parser.Char (anyChar, oneOf)-import Text.Parser.Combinators-import Text.Trifecta (Result, parseString)-import Text.Trifecta.Delta+import qualified Text.Megaparsec as P+import qualified Text.Megaparsec.Char as P -parseCmd :: IState -> String -> String -> Result (Either String Command)-parseCmd i inputname = P.runparser pCmd i inputname . trim+parseCmd :: IState -> String -> String -> Either IP.ParseError (Either String Command)+parseCmd i inputname = IP.runparser pCmd i inputname . trim     where trim = f . f               where f = reverse . dropWhile isSpace  type CommandTable = [ ( [String], CmdArg, String-                    , String -> P.IdrisParser (Either String Command) ) ]+                    , String -> IP.IdrisParser (Either String Command) ) ]  setOptions :: [(String, Opt)] setOptions = [("errorcontext", ErrContext),@@ -66,7 +68,7 @@   , nameArgCmd ["miss", "missing"] Missing "Show missing clauses"   , (["doc"], NameArg, "Show internal documentation", cmd_doc)   , (["mkdoc"], NamespaceArg, "Generate IdrisDoc for namespace(s) and dependencies"-    , genArg "namespace" (many anyChar) MakeDoc)+    , genArg "namespace" (P.many P.anyChar) MakeDoc)   , (["apropos"], SeqArgs (OptionalArg PkgArgs) NameArg, " Search names, types, and documentation"     , cmd_apropos)   , (["s", "search"], SeqArgs (OptionalArg PkgArgs) ExprArg@@ -109,6 +111,7 @@   , (["consolewidth"], ConsoleWidthArg, "Set the width of the console", cmd_consolewidth)   , (["printerdepth"], OptionalArg NumberArg, "Set the maximum pretty-printer depth (no arg for infinite)", cmd_printdepth)   , noArgCmd ["q", "quit"] Quit "Exit the Idris system"+  , noArgCmd ["version"] ShowVersion "Display the Idris version"   , noArgCmd ["warranty"] Warranty "Displays warranty information"   , (["let"], ManyArgs DeclArg     , "Evaluate a declaration, such as a function definition, instance implementation, or fixity declaration"@@ -166,9 +169,9 @@     , cmd_refine)   , (["debugunify"], SeqArgs ExprArg ExprArg     , "(Debugging) Try to unify two expressions", const $ do-       l <- P.simpleExpr defaultSyntax-       r <- P.simpleExpr defaultSyntax-       eof+       l <- IP.simpleExpr defaultSyntax+       r <- IP.simpleExpr defaultSyntax+       P.eof        return (Right (DebugUnify l r))     )   ]@@ -181,268 +184,266 @@   (names, NamespaceArg, doc, namespaceArg command) exprArgCmd names command doc =   (names, ExprArg, doc, exprArg command)-metavarArgCmd names command doc =-  (names, MetaVarArg, doc, fnNameArg command) optArgCmd names command doc =   (names, OptionArg, doc, optArg command) proofArgCmd names command doc =   (names, NoArg, doc, proofArg command) -pCmd :: P.IdrisParser (Either String Command)-pCmd = choice [ do c <- cmd names; parser c-              | (names, _, _, parser) <- parserCommandsForHelp ++ parserCommands ]+pCmd :: IP.IdrisParser (Either String Command)+pCmd = P.choice [ do c <- cmd names; parser c+                | (names, _, _, parser) <- parserCommandsForHelp ++ parserCommands ]      <|> unrecognized      <|> nop      <|> eval-    where nop = do eof; return (Right NOP)+    where nop = do P.eof; return (Right NOP)           unrecognized = do-              P.lchar ':'-              cmd <- many anyChar+              IP.lchar ':'+              cmd <- P.many P.anyChar               let cmd' = takeWhile (/=' ') cmd               return (Left $ "Unrecognized command: " ++ cmd') -cmd :: [String] -> P.IdrisParser String-cmd xs = try $ do-    P.lchar ':'+cmd :: [String] -> IP.IdrisParser String+cmd xs = P.try $ do+    IP.lchar ':'     docmd sorted_xs      where docmd [] = fail "Could not parse command"-          docmd (x:xs) = try (P.reserved x >> return x) <|> docmd xs+          docmd (x:xs) = P.try (IP.reserved x >> return x) <|> docmd xs            sorted_xs = sortBy (\x y -> compare (length y) (length x)) xs  -noArgs :: Command -> String -> P.IdrisParser (Either String Command)+noArgs :: Command -> String -> IP.IdrisParser (Either String Command) noArgs cmd name = do     let emptyArgs = do-          eof+          P.eof           return (Right cmd)      let failure = return (Left $ ":" ++ name ++ " takes no arguments")      emptyArgs <|> failure -eval :: P.IdrisParser (Either String Command)+eval :: IP.IdrisParser (Either String Command) eval = do-  t <- P.fullExpr defaultSyntax+  t <- IP.fullExpr defaultSyntax   return $ Right (Eval t) -exprArg :: (PTerm -> Command) -> String -> P.IdrisParser (Either String Command)+exprArg :: (PTerm -> Command) -> String -> IP.IdrisParser (Either String Command) exprArg cmd name = do     let noArg = do-          eof+          P.eof           return $ Left ("Usage is :" ++ name ++ " <expression>")      let justOperator = do-          (op, fc) <- P.operatorFC-          eof+          (op, fc) <- IP.withExtent IP.symbolicOperator+          P.eof           return $ Right $ cmd (PRef fc [] (sUN op))      let properArg = do-          t <- P.fullExpr defaultSyntax+          t <- IP.fullExpr defaultSyntax           return $ Right (cmd t)-    try noArg <|> try justOperator <|> properArg+    P.try noArg <|> P.try justOperator <|> properArg -genArg :: String -> P.IdrisParser a -> (a -> Command)-           -> String -> P.IdrisParser (Either String Command)+genArg :: String -> IP.IdrisParser a -> (a -> Command)+           -> String -> IP.IdrisParser (Either String Command) genArg argName argParser cmd name = do-    let emptyArgs = do eof; failure+    let emptyArgs = do P.eof; failure         oneArg = do arg <- argParser-                    eof+                    P.eof                     return (Right (cmd arg))-    try emptyArgs <|> oneArg <|> failure+    P.try emptyArgs <|> oneArg <|> failure     where     failure = return $ Left ("Usage is :" ++ name ++ " <" ++ argName ++ ">") -nameArg, fnNameArg :: (Name -> Command) -> String -> P.IdrisParser (Either String Command)-nameArg = genArg "name" $ fst <$> P.name-fnNameArg = genArg "functionname" $ fst <$> P.fnName+nameArg, fnNameArg :: (Name -> Command) -> String -> IP.IdrisParser (Either String Command)+nameArg = genArg "name" IP.name+fnNameArg = genArg "functionname" IP.fnName -strArg :: (String -> Command) -> String -> P.IdrisParser (Either String Command)-strArg = genArg "string" (many anyChar)+strArg :: (String -> Command) -> String -> IP.IdrisParser (Either String Command)+strArg = genArg "string" (P.many P.anyChar) -moduleArg :: (FilePath -> Command) -> String -> P.IdrisParser (Either String Command)-moduleArg = genArg "module" (fmap (toPath . fst) P.identifier)+moduleArg :: (FilePath -> Command) -> String -> IP.IdrisParser (Either String Command)+moduleArg = genArg "module" (fmap toPath IP.identifier)   where     toPath n = foldl1' (</>) $ splitOn "." n -namespaceArg :: ([String] -> Command) -> String -> P.IdrisParser (Either String Command)-namespaceArg = genArg "namespace" (fmap (toNS . fst) P.identifier)+namespaceArg :: ([String] -> Command) -> String -> IP.IdrisParser (Either String Command)+namespaceArg = genArg "namespace" (fmap toNS IP.identifier)   where     toNS  = splitOn "." -optArg :: (Opt -> Command) -> String -> P.IdrisParser (Either String Command)+optArg :: (Opt -> Command) -> String -> IP.IdrisParser (Either String Command) optArg cmd name = do     let emptyArgs = do-            eof+            P.eof             return $ Left ("Usage is :" ++ name ++ " <option>")      let oneArg = do           o <- pOption-          P.whiteSpace-          eof+          IP.whiteSpace+          P.eof           return (Right (cmd o))      let failure = return $ Left "Unrecognized setting" -    try emptyArgs <|> oneArg <|> failure+    P.try emptyArgs <|> oneArg <|> failure      where-        pOption :: P.IdrisParser Opt-        pOption = foldl (<|>) empty $ map (\(a, b) -> do discard (P.symbol a); return b) setOptions+        pOption :: IP.IdrisParser Opt+        pOption = foldl (<|>) empty $ map (\(a, b) -> do discard (IP.symbol a); return b) setOptions -proofArg :: (Bool -> Int -> Name -> Command) -> String -> P.IdrisParser (Either String Command)+proofArg :: (Bool -> Int -> Name -> Command) -> String -> IP.IdrisParser (Either String Command) proofArg cmd name = do-    upd <- option False $ do-        P.lchar '!'+    upd <- P.option False $ do+        IP.lchar '!'         return True-    l <- fst <$> P.natural-    n <- fst <$> P.name;+    l <- IP.natural+    n <- IP.name     return (Right (cmd upd (fromInteger l) n)) -cmd_doc :: String -> P.IdrisParser (Either String Command)+cmd_doc :: String -> IP.IdrisParser (Either String Command) cmd_doc name = do     let constant = do-          c <- fmap fst P.constant-          eof+          c <- IP.constant+          P.eof           return $ Right (DocStr (Right c) FullDocs)      let pType = do-          P.reserved "Type"-          eof-          return $ Right (DocStr (Left $ P.mkName ("Type", "")) FullDocs)+          IP.reserved "Type"+          P.eof+          return $ Right (DocStr (Left $ sUN "Type") FullDocs)      let fnName = fnNameArg (\n -> DocStr (Left n) FullDocs) name -    try constant <|> pType <|> fnName+    P.try constant <|> pType <|> fnName -cmd_consolewidth :: String -> P.IdrisParser (Either String Command)+cmd_consolewidth :: String -> IP.IdrisParser (Either String Command) cmd_consolewidth name = do     w <- pConsoleWidth     return (Right (SetConsoleWidth w))      where-        pConsoleWidth :: P.IdrisParser ConsoleWidth-        pConsoleWidth = do discard (P.symbol "auto"); return AutomaticWidth-                    <|> do discard (P.symbol "infinite"); return InfinitelyWide-                    <|> do n <- fmap (fromInteger . fst) P.natural+        pConsoleWidth :: IP.IdrisParser ConsoleWidth+        pConsoleWidth = do discard (IP.symbol "auto"); return AutomaticWidth+                    <|> do discard (IP.symbol "infinite"); return InfinitelyWide+                    <|> do n <- fromInteger <$> IP.natural                            return (ColsWide n) -cmd_printdepth :: String -> P.IdrisParser (Either String Command)-cmd_printdepth _ = do d <- optional (fmap (fromInteger . fst) P.natural)+cmd_printdepth :: String -> IP.IdrisParser (Either String Command)+cmd_printdepth _ = do d <- optional (fromInteger <$> IP.natural)                       return (Right $ SetPrinterDepth d) -cmd_execute :: String -> P.IdrisParser (Either String Command)+cmd_execute :: String -> IP.IdrisParser (Either String Command) cmd_execute name = do-    tm <- option maintm (P.fullExpr defaultSyntax)+    tm <- P.option maintm (IP.fullExpr defaultSyntax)     return (Right (Execute tm))   where     maintm = PRef (fileFC "(repl)") [] (sNS (sUN "main") ["Main"]) -cmd_dynamic :: String -> P.IdrisParser (Either String Command)+cmd_dynamic :: String -> IP.IdrisParser (Either String Command) cmd_dynamic name = do-    let optArg = do l <- many anyChar+    let optArg = do l <- P.many P.anyChar                     if (l /= "")                         then return $ Right (DynamicLink l)                         else return $ Right ListDynamic     let failure = return $ Left $ "Usage is :" ++ name ++ " [<library>]"-    try optArg <|> failure+    P.try optArg <|> failure -cmd_pprint :: String -> P.IdrisParser (Either String Command)+cmd_pprint :: String -> IP.IdrisParser (Either String Command) cmd_pprint name = do      fmt <- ppFormat-     P.whiteSpace-     n <- fmap (fromInteger . fst) P.natural-     P.whiteSpace-     t <- P.fullExpr defaultSyntax+     IP.whiteSpace+     n <- fromInteger <$> IP.natural+     IP.whiteSpace+     t <- IP.fullExpr defaultSyntax      return (Right (PPrint fmt n t))      where-        ppFormat :: P.IdrisParser OutputFmt-        ppFormat = (discard (P.symbol "html") >> return HTMLOutput)-               <|> (discard (P.symbol "latex") >> return LaTeXOutput)+        ppFormat :: IP.IdrisParser OutputFmt+        ppFormat = (discard (IP.symbol "html") >> return HTMLOutput)+               <|> (discard (IP.symbol "latex") >> return LaTeXOutput) -cmd_compile :: String -> P.IdrisParser (Either String Command)+cmd_compile :: String -> IP.IdrisParser (Either String Command) cmd_compile name = do     let defaultCodegen = Via IBCFormat "c" -    let codegenOption :: P.IdrisParser Codegen+    let codegenOption :: IP.IdrisParser Codegen         codegenOption = do-            let bytecodeCodegen = discard (P.symbol "bytecode") *> return Bytecode-                viaCodegen = do x <- fst <$> P.identifier+            let bytecodeCodegen = discard (IP.symbol "bytecode") *> return Bytecode+                viaCodegen = do x <- IP.identifier                                 return (Via IBCFormat (map toLower x))             bytecodeCodegen <|> viaCodegen      let hasOneArg = do           i <- get-          f <- fst <$> P.identifier-          eof+          f <- IP.identifier+          P.eof           return $ Right (Compile defaultCodegen f)      let hasTwoArgs = do           i <- get           codegen <- codegenOption-          f <- fst <$> P.identifier-          eof+          f <- IP.identifier+          P.eof           return $ Right (Compile codegen f)      let failure = return $ Left $ "Usage is :" ++ name ++ " [<codegen>] <filename>"-    try hasTwoArgs <|> try hasOneArg <|> failure+    P.try hasTwoArgs <|> P.try hasOneArg <|> failure -cmd_addproof :: String -> P.IdrisParser (Either String Command)+cmd_addproof :: String -> IP.IdrisParser (Either String Command) cmd_addproof name = do-    n <- option Nothing $ do-        x <- fst <$> P.name+    n <- P.option Nothing $ do+        x <- IP.name         return (Just x)-    eof+    P.eof     return (Right (AddProof n)) -cmd_log :: String -> P.IdrisParser (Either String Command)+cmd_log :: String -> IP.IdrisParser (Either String Command) cmd_log name = do-    i <- fmap (fromIntegral . fst) P.natural-    eof+    i <- fromIntegral <$> IP.natural+    P.eof     return (Right (LogLvl i)) -cmd_verb :: String -> P.IdrisParser (Either String Command)+cmd_verb :: String -> IP.IdrisParser (Either String Command) cmd_verb name = do-    i <- fmap (fromIntegral . fst) P.natural-    eof+    i <- fromIntegral <$> IP.natural+    P.eof     return (Right (Verbosity i)) -cmd_cats :: String -> P.IdrisParser (Either String Command)+cmd_cats :: String -> IP.IdrisParser (Either String Command) cmd_cats name = do-    cs <- sepBy pLogCats (P.whiteSpace)-    eof+    cs <- P.sepBy pLogCats (IP.whiteSpace)+    P.eof     return $ Right $ LogCategory (concat cs)   where     badCat = do-      c <- fst <$> P.identifier+      c <- IP.identifier       fail $ "Category: " ++ c ++ " is not recognised." -    pLogCats :: P.IdrisParser [LogCat]-    pLogCats = try (P.symbol (strLogCat IParse)    >> return parserCats)-           <|> try (P.symbol (strLogCat IElab)     >> return elabCats)-           <|> try (P.symbol (strLogCat ICodeGen)  >> return codegenCats)-           <|> try (P.symbol (strLogCat ICoverage) >> return [ICoverage])-           <|> try (P.symbol (strLogCat IIBC)      >> return [IIBC])-           <|> try (P.symbol (strLogCat IErasure)  >> return [IErasure])+    pLogCats :: IP.IdrisParser [LogCat]+    pLogCats = P.try (parserCats  <$ IP.symbol (strLogCat IParse))+           <|> P.try (elabCats    <$ IP.symbol (strLogCat IElab))+           <|> P.try (codegenCats <$ IP.symbol (strLogCat ICodeGen))+           <|> P.try ([ICoverage] <$ IP.symbol (strLogCat ICoverage))+           <|> P.try ([IIBC]      <$ IP.symbol (strLogCat IIBC))+           <|> P.try ([IErasure]  <$ IP.symbol (strLogCat IErasure))            <|> badCat -cmd_let :: String -> P.IdrisParser (Either String Command)+cmd_let :: String -> IP.IdrisParser (Either String Command) cmd_let name = do-    defn <- concat <$> many (P.decl defaultSyntax)+    defn <- concat <$> P.many (IP.decl defaultSyntax)     return (Right (NewDefn defn)) -cmd_unlet :: String -> P.IdrisParser (Either String Command)-cmd_unlet name = (Right . Undefine) `fmap` many (fst <$> P.name)+cmd_unlet :: String -> IP.IdrisParser (Either String Command)+cmd_unlet name = Right . Undefine <$> P.many IP.name -cmd_loadto :: String -> P.IdrisParser (Either String Command)+cmd_loadto :: String -> IP.IdrisParser (Either String Command) cmd_loadto name = do-    toline <- fmap (fromInteger . fst) P.natural-    f <- many anyChar;+    toline <- fromInteger <$> IP.natural+    f <- P.many P.anyChar     return (Right (Load f (Just toline))) -cmd_colour :: String -> P.IdrisParser (Either String Command)+cmd_colour :: String -> IP.IdrisParser (Either String Command) cmd_colour name = fmap Right pSetColourCmd      where@@ -458,30 +459,30 @@                   , ("default", Nothing)                   ] -        pSetColourCmd :: P.IdrisParser Command+        pSetColourCmd :: IP.IdrisParser Command         pSetColourCmd = (do c <- pColourType                             let defaultColour = IdrisColour Nothing True False False False-                            opts <- sepBy pColourMod (P.whiteSpace)+                            opts <- P.sepBy pColourMod (IP.whiteSpace)                             let colour = foldr ($) defaultColour $ reverse opts                             return $ SetColour c colour)-                    <|> try (P.symbol "on" >> return ColourOn)-                    <|> try (P.symbol "off" >> return ColourOff)+                    <|> P.try (IP.symbol "on" >> return ColourOn)+                    <|> P.try (IP.symbol "off" >> return ColourOff) -        pColour :: P.IdrisParser (Maybe Color)+        pColour :: IP.IdrisParser (Maybe Color)         pColour = doColour colours             where doColour [] = fail "Unknown colour"-                  doColour ((s, c):cs) = (try (P.symbol s) >> return c) <|> doColour cs+                  doColour ((s, c):cs) = (P.try (IP.symbol s) >> return c) <|> doColour cs -        pColourMod :: P.IdrisParser (IdrisColour -> IdrisColour)-        pColourMod = try (P.symbol "vivid" >> return doVivid)-                 <|> try (P.symbol "dull" >> return doDull)-                 <|> try (P.symbol "underline" >> return doUnderline)-                 <|> try (P.symbol "nounderline" >> return doNoUnderline)-                 <|> try (P.symbol "bold" >> return doBold)-                 <|> try (P.symbol "nobold" >> return doNoBold)-                 <|> try (P.symbol "italic" >> return doItalic)-                 <|> try (P.symbol "noitalic" >> return doNoItalic)-                 <|> try (pColour >>= return . doSetColour)+        pColourMod :: IP.IdrisParser (IdrisColour -> IdrisColour)+        pColourMod = P.try (doVivid <$ IP.symbol "vivid")+                 <|> P.try (doDull <$ IP.symbol "dull")+                 <|> P.try (doUnderline <$ IP.symbol "underline")+                 <|> P.try (doNoUnderline <$ IP.symbol "nounderline")+                 <|> P.try (doBold <$ IP.symbol "bold")+                 <|> P.try (doNoBold <$ IP.symbol "nobold")+                 <|> P.try (doItalic <$ IP.symbol "italic")+                 <|> P.try (doNoItalic <$ IP.symbol "noitalic")+                 <|> P.try (pColour >>= return . doSetColour)             where doVivid i       = i { vivid = True }                   doDull i        = i { vivid = False }                   doUnderline i   = i { underline = True }@@ -497,42 +498,44 @@         colourTypes = map (\x -> ((map toLower . reverse . drop 6 . reverse . show) x, x)) $                       enumFromTo minBound maxBound -        pColourType :: P.IdrisParser ColourType+        pColourType :: IP.IdrisParser ColourType         pColourType = doColourType colourTypes             where doColourType [] = fail $ "Unknown colour category. Options: " ++                                            (concat . intersperse ", " . map fst) colourTypes-                  doColourType ((s,ct):cts) = (try (P.symbol s) >> return ct) <|> doColourType cts+                  doColourType ((s,ct):cts) = (P.try (IP.symbol s) >> return ct) <|> doColourType cts -idChar = oneOf (['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ ['_'])+idChar = P.oneOf (['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ ['_']) -cmd_apropos :: String -> P.IdrisParser (Either String Command)+cmd_apropos :: String -> IP.IdrisParser (Either String Command) cmd_apropos = packageBasedCmd (some idChar) Apropos -packageBasedCmd :: P.IdrisParser a -> ([String] -> a -> Command)-                -> String -> P.IdrisParser (Either String Command)+packageBasedCmd :: IP.IdrisParser a -> ([PkgName] -> a -> Command)+                -> String -> IP.IdrisParser (Either String Command) packageBasedCmd valParser cmd name =-  try (do P.lchar '('-          pkgs <- sepBy (some idChar) (P.lchar ',')-          P.lchar ')'-          val <- valParser-          return (Right (cmd pkgs val)))+  P.try (do IP.lchar '('+            pkgs <- P.sepBy (pkg <* IP.whiteSpace) (IP.lchar ',')+            IP.lchar ')'+            val <- valParser+            return (Right (cmd pkgs val)))    <|> do val <- valParser           return (Right (cmd [] val))+  where+    pkg = either fail pure . pkgName =<< IP.packageName -cmd_search :: String -> P.IdrisParser (Either String Command)+cmd_search :: String -> IP.IdrisParser (Either String Command) cmd_search = packageBasedCmd-  (P.fullExpr (defaultSyntax { implicitAllowed = True })) Search+  (IP.fullExpr (defaultSyntax { implicitAllowed = True })) Search -cmd_proofsearch :: String -> P.IdrisParser (Either String Command)+cmd_proofsearch :: String -> IP.IdrisParser (Either String Command) cmd_proofsearch name = do-    upd <- option False (do P.lchar '!'; return True)-    l <- fmap (fromInteger . fst) P.natural; n <- fst <$> P.name-    hints <- many (fst <$> P.fnName)+    upd <- P.option False (True <$ IP.lchar '!')+    l <- fromInteger <$> IP.natural; n <- IP.name+    hints <- P.many IP.fnName     return (Right (DoProofSearch upd True l n hints)) -cmd_refine :: String -> P.IdrisParser (Either String Command)+cmd_refine :: String -> IP.IdrisParser (Either String Command) cmd_refine name = do-   upd <- option False (do P.lchar '!'; return True)-   l <- fmap (fromInteger . fst) P.natural; n <- fst <$> P.name-   hint <- fst <$> P.fnName+   upd <- P.option False (do IP.lchar '!'; return True)+   l <- fromInteger <$> IP.natural; n <- IP.name+   hint <- IP.fnName    return (Right (DoProofSearch upd False l n [hint]))
src/Idris/Reflection.hs view
@@ -1,14 +1,26 @@ {-| Module      : Idris.Reflection Description : Code related to Idris's reflection system. This module contains quoters and unquoters along with some supporting datatypes.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}  {-# LANGUAGE CPP, PatternGuards #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns -fwarn-unused-imports #-}-module Idris.Reflection where+module Idris.Reflection (RConstructorDefn(..), RDataDefn(..),RFunArg(..),+                         RFunClause(..), RFunDefn(..), RTyDecl(..),+                         buildDatatypes, buildFunDefns, envTupleType, fromTTMaybe,+                         getArgs, mkList, rawList, rawPair, rawPairTy, reflect,+                         reflectArg, reflectDatatype, reflectEnv, reflectErr,+                         reflectFC, reflectFixity, reflectFunDefn, reflectList,+                         reflectName, reflectNameType, reflectRaw,+                         reflectRawQuotePattern, reflectRawQuote, reflectTTQuote,+                         reflectTTQuotePattern, reflm, reify, reifyBool, reifyEnv,+                         reifyFunDefn, reifyList, reifyRDataDefn, reifyRaw,+                         reifyReportPart, reifyReportParts, reifyTT, reifyTTName,+                         reifyTyDecl, rFunArgToPArg, tacN+                         ) where  import Idris.Core.Elaborate (claim, fill, focus, getNameFrom, initElaborator,                              movelast, runElab, solve)@@ -313,7 +325,7 @@ reifyTTBinderApp reif f [t, k]                       | f == reflm "Pi" = liftM2 (Pi RigW Nothing) (reif t) (reif k) reifyTTBinderApp reif f [x, y]-                      | f == reflm "Let" = liftM2 Let (reif x) (reif y)+                      | f == reflm "Let" = liftM2 (Let RigW) (reif x) (reif y) reifyTTBinderApp reif f [t]                       | f == reflm "Hole" = liftM Hole (reif t) reifyTTBinderApp reif f [t]@@ -533,9 +545,9 @@      focus scH; reflectRawQuotePattern unq sc      focus bH; reflectBinderQuotePattern reflectRawQuotePattern (Var $ reflm "Raw") unq b   where freeNamesR (Var n) = [n]-        freeNamesR (RBind n (Let t v) body) = concat [freeNamesR v,-                                                      freeNamesR body \\ [n],-                                                      freeNamesR t]+        freeNamesR (RBind n (Let rc t v) body) = concat [freeNamesR v,+                                                         freeNamesR body \\ [n],+                                                         freeNamesR t]         freeNamesR (RBind n b body) = freeNamesR (binderTy b) ++                                       (freeNamesR body \\ [n])         freeNamesR (RApp f x) = freeNamesR f ++ freeNamesR x@@ -583,7 +595,7 @@         fill $ reflCall "Pi" [ty, Var t', Var k']         solve         focus t'; q unq t-reflectBinderQuotePattern q ty unq (Let x y)+reflectBinderQuotePattern q ty unq (Let rc x y)    = do x' <- claimTy (sMN 0 "ty") ty; movelast x';         y' <- claimTy (sMN 0 "v")ty; movelast y';         fill $ reflCall "Let" [ty, Var x', Var y']@@ -748,7 +760,7 @@    = reflCall "Lam" [Var ty, q unq t] reflectBinderQuote q ty unq (Pi _ _ t k)    = reflCall "Pi" [Var ty, q unq t, q unq k]-reflectBinderQuote q ty unq (Let x y)+reflectBinderQuote q ty unq (Let rc x y)    = reflCall "Let" [Var ty, q unq x, q unq y] reflectBinderQuote q ty unq (NLet x y)    = reflCall "Let" [Var ty, q unq x, q unq y]
src/Idris/Termination.hs view
@@ -1,12 +1,14 @@ {-| Module      : Idris.Termination Description : The termination checker for Idris-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -} {-# LANGUAGE PatternGuards #-}-module Idris.Termination where+module Idris.Termination (buildSCG, checkAllCovering, checkDeclTotality,+                          checkIfGuarded, checkPositive, checkSizeChange,+                          verifyTotality) where  import Idris.AbsSyntax import Idris.Core.CaseTree@@ -15,10 +17,9 @@ import Idris.Delaborate import Idris.Error import Idris.Options-import Idris.Output (iWarn, iputStrLn)+import Idris.Output (iWarn)  import Control.Monad.State.Strict-import Data.Char import Data.Either import Data.List import Data.Maybe@@ -34,12 +35,11 @@                     do let msg = show top ++ " is " ++ show tot ++ " due to " ++ show n                        putIState i { idris_totcheckfail = (fc, msg) : idris_totcheckfail i }                        addIBC (IBCTotCheckErr fc msg)-             [Partial _] ->-                case lookupCtxt n (idris_callgraph i) of-                     [cg] -> mapM_ (checkAllCovering fc (n : done) top)-                                   (calls cg)-                     _ -> return ()-             x -> return () -- stop if total+             [Partial (Other ns)] ->+                     -- Check that none of the partial functions it relies+                     -- on are partial due to missing cases+                     mapM_ (checkAllCovering fc (n : done) top) ns+             x -> return () -- stop if total, or partial due to recursion checkAllCovering _ _ _ _ = return ()  -- | Check whether all 'Inf' arguments to the name end up guaranteed to be@@ -78,7 +78,7 @@     allGuarded names i _ = True      guardedTerm names i (P _ v _) = v `elem` names || guard v i-    guardedTerm names i (Bind n (Let t v) sc)+    guardedTerm names i (Bind n (Let rig t v) sc)           = guardedTerm names i v && guardedTerm names i sc     guardedTerm names i (Bind n b sc) = False     guardedTerm names i ap@(App _ _ _)@@ -143,9 +143,6 @@ calcTotality :: FC -> Name -> [([Name], Term, Term)] -> Idris Totality calcTotality fc n pats     = do i <- getIState-         let opts = case lookupCtxt n (idris_flags i) of-                            [fs] -> fs-                            _ -> []          case mapMaybe (checkLHS i) (map (\ (_, l, r) -> l) pats) of             (failure : _) -> return failure             _ -> checkSizeChange n@@ -302,7 +299,7 @@ buildSCG' ist topfn pats args = nub $ concatMap scgPat pats where   scgPat (lhs, rhs) = let lhs' = delazy lhs                           rhs' = delazy rhs-                          (f, pargs) = unApply (dePat lhs') in+                          (_, pargs) = unApply (dePat lhs') in                             findCalls [] Toplevel (dePat rhs') (patvars lhs')                                       (zip pargs [0..]) @@ -368,7 +365,7 @@           notPartial _ = True   findCalls cases guarded (App _ f a) pvs pargs         = findCalls cases Unguarded f pvs pargs ++ findCalls cases Unguarded a pvs pargs-  findCalls cases guarded (Bind n (Let t v) e) pvs pargs+  findCalls cases guarded (Bind n (Let rig t v) e) pvs pargs         = findCalls cases Unguarded t pvs pargs ++           findCalls cases Unguarded v pvs pargs ++           -- Substitute in the scope since this might reveal some useful@@ -393,7 +390,7 @@   fccPat cases pvs pargs args g (lhs, rhs)       = let lhs' = delazy lhs             rhs' = delazy rhs-            (f, pargs_case) = unApply (dePat lhs')+            (_, pargs_case) = unApply (dePat lhs')             -- pargs is a pair of a term, and the argument position that             -- term appears in. If any of the arguments to the case block             -- are also on the lhs, we also want those patterns to appear@@ -431,7 +428,7 @@             [ty] -> expand 0 (normalise (tt_ctxt ist) [] ty) args             _ -> args      where expand i (Bind n (Pi _ _ _ _) sc) (x : xs) = x : expand (i + 1) sc xs-           expand i (Bind n (Pi _ _ _ _) sc) [] = Just (i, Same) : expand (i + 1) sc []+           expand i (Bind n (Pi _ _ _ _) sc) [] = Nothing : expand (i + 1) sc []            expand i _ xs = xs    mkChange n args pargs = [(n, expandToArity n (sizes args))]@@ -545,10 +542,6 @@                                collapse paths                      else tryPath 0 [] mp 0   where-    tryPath' d path mp arg-           = let res = tryPath d path mp arg in-                 trace (show mp ++ "\n" ++ show arg ++ " " ++ show res) res-     mkBig (e, d) = (e, 10000)      tryPath :: Int -> [((SCGEntry, Int), Int)] -> MultiPath -> Int -> Totality
src/Idris/Transforms.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Transforms Description : A collection of transformations.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -16,10 +16,7 @@   ) where  import Idris.AbsSyntax-import Idris.Core.CaseTree import Idris.Core.TT--import Debug.Trace  transformPats :: IState -> [Either Term (Term, Term)] ->                 [Either Term (Term, Term)]
src/Idris/TypeSearch.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.TypeSearch Description : A Hoogle for Idris.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -13,8 +13,7 @@   , defaultScoreFunction   ) where -import Idris.AbsSyntax (addImpl, addUsingConstraints, getIState, implicit,-                        logLvl, putIState)+import Idris.AbsSyntax (addUsingConstraints, getIState, implicit, putIState) import Idris.AbsSyntaxTree (IState(idris_docstrings, idris_interfaces, idris_outputmode, tt_ctxt),                             Idris, InterfaceInfo, OutputMode(..), PTerm,                             defaultSyntax, eqTy, implicitAllowed,@@ -27,6 +26,7 @@ import Idris.Docstrings (noDocs, overview) import Idris.Elab.Type (elabType) import Idris.IBC+import Idris.Imports (PkgName) import Idris.Output (iPrintResult, iRenderError, iRenderOutput, iRenderResult,                      iputStrLn, prettyDocumentedIst) @@ -49,16 +49,15 @@ import qualified Data.Text as T (isPrefixOf, pack) import Data.Traversable (traverse) -searchByType :: [String] -> PTerm -> Idris ()+searchByType :: [PkgName] -> PTerm -> Idris () searchByType pkgs pterm = do   i <- getIState -- save original   when (not (null pkgs)) $-     iputStrLn $ "Searching packages: " ++ showSep ", " pkgs+     iputStrLn $ "Searching packages: " ++ showSep ", " (map show pkgs)    mapM_ loadPkgIndex pkgs   pterm' <- addUsingConstraints syn emptyFC pterm   pterm'' <- implicit toplevel syn name pterm'-  let pterm'''  = addImpl [] i pterm''   ty <- elabType toplevel syn (fst noDocs) (snd noDocs) emptyFC [] name NoFC pterm'   let names = searchUsing searchPred i ty   let names' = take numLimit names@@ -155,7 +154,7 @@ usedVars = f True where   f b (P Bound n t) = M.singleton n (t, b) `M.union` f b t   f b (Bind n binder t2) = (M.delete n (f b t2) `M.union`) $ case binder of-    Let t v ->   f b t `M.union` f b v+    Let rig t v -> f b t `M.union` f b v     Guess t v -> f b t `M.union` f b v     bind -> f b (binderTy bind)   f b (App _ t1 t2) = f b t1 `M.union` f (b && isInjective t1) t2@@ -304,7 +303,7 @@  isInterfaceArg :: Ctxt InterfaceInfo -> Type -> Bool isInterfaceArg interfaceInfo ty = not (null (getInterfaceName clss >>= flip lookupCtxt interfaceInfo)) where-  (clss, args) = unApply ty+  (clss, _) = unApply ty   getInterfaceName (P (TCon _ _) interfaceName _) = [interfaceName]   getInterfaceName _ = [] @@ -357,8 +356,6 @@     argNames2 = map fst dag2     usedns = map fst startingHoles     startingHoles = argNames1 ++ argNames2--    startingTypes = [(retTy1, retTy2)]     startQueueOfQueues :: Q.PQueue Score (info, Q.PQueue Score State)
src/Idris/Unlit.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.Unlit Description : Turn literate programs into normal programs.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}
src/Idris/WhoCalls.hs view
@@ -1,7 +1,7 @@ {-| Module      : Idris.WhoCalls Description : Find function callers and callees.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -31,12 +31,12 @@ names _ = []  occursBinder :: Name -> Binder Term -> Bool-occursBinder n (Let ty val) = occurs n ty || occurs n val+occursBinder n (Let rc ty val) = occurs n ty || occurs n val occursBinder n (NLet ty val) = occurs n ty || occurs n val occursBinder n b = occurs n (binderTy b)  namesBinder :: Binder Term -> [Name]-namesBinder (Let ty val) = names ty ++ names val+namesBinder (Let rc ty val) = names ty ++ names val namesBinder (NLet ty val) = names ty ++ names val namesBinder b = names (binderTy b) 
src/Util/DynamicLinker.hs view
@@ -1,7 +1,7 @@ {-| Module      : Util.DynamicLinker Description : Platform-specific dynamic linking support. Add new platforms to this file through conditional compilation.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}@@ -13,22 +13,29 @@                           ) where  #ifdef IDRIS_FFI-import Foreign.LibFFI-import Foreign.Ptr (FunPtr, Ptr(), castPtrToFunPtr, nullFunPtr, nullPtr) import System.Directory-#ifndef mingw32_HOST_OS+#ifdef mingw32_HOST_OS+import qualified Control.Exception as Exception (IOException, catch)+import Foreign.Ptr (FunPtr, castPtrToFunPtr, nullFunPtr, nullPtr)+import System.FilePath.Windows ((</>))+import System.Win32.DLL+import System.Win32.Types+#else import Control.Exception (IOException, throwIO, try)-import Data.Array (Array, bounds, inRange, (!))+import Foreign.Ptr (FunPtr, nullFunPtr, nullPtr)+#ifdef linux_HOST_OS+import Data.Array (bounds, inRange, (!)) import Data.Functor ((<$>)) import Data.Maybe (catMaybes)+#else+import Data.Array (bounds, (!))+#endif import System.FilePath.Posix ((</>)) import System.Posix.DynamicLinker import Text.Regex.TDFA-#else-import qualified Control.Exception as Exception (IOException, catch)-import System.FilePath.Windows ((</>))-import System.Win32.DLL-import System.Win32.Types+#endif++#ifdef mingw32_HOST_OS type DL = HMODULE #endif 
src/Util/Net.hs view
@@ -1,7 +1,7 @@ {-| Module      : Util.Net Description : Utilities for Network IO.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}
src/Util/Pretty.hs view
@@ -1,7 +1,7 @@ {-| Module      : Util.Pretty Description : Utilities for Pretty Printing.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}
src/Util/ScreenSize.hs view
@@ -1,7 +1,7 @@ {-| Module      : Util.ScreenSize Description : Utilities for getting screen width.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}
src/Util/System.hs view
@@ -1,7 +1,7 @@ {-| Module      : Util.System Description : Utilities for interacting with the system.-Copyright   :+ License     : BSD3 Maintainer  : The Idris Community. -}
stack-shell.nix view
@@ -1,9 +1,7 @@+{ ghc }: with (import <nixpkgs> {});  let-  # MUST match resolver in stack.yaml-  resolver = haskell.packages.lts-9_0.ghc;-   native_libs = [     libffi     zlib@@ -15,17 +13,9 @@     CoreServices   ]); -in stdenv.mkDerivation {-+in haskell.lib.buildStackProject {+  inherit ghc;+  buildInputs = native_libs;   name = "idrisBuildEnv";--  buildInputs = [ resolver ] ++ native_libs;--  STACK_IN_NIX_EXTRA_ARGS = builtins.foldl'-    (acc: lib:-      " --extra-lib-dirs=${lib}/lib --extra-include-dirs=${lib}/include" + acc)-    "" native_libs;--  # Needed if one wants to use ghci, due to https://ghc.haskell.org/trac/ghc/ticket/11042-  LD_LIBRARY_PATH = builtins.concatStringsSep ":" (map (lib: lib.out + "/lib") native_libs);+  src = ./.; }
stack.yaml view
@@ -1,17 +1,18 @@ #recheck extra-deps next on resolver or cabal file change-resolver: lts-9.0+resolver: lts-10.0  packages:   - location: . +extra-deps: []+ flags:   idris:     FFI: true     GMP: true -extra-deps:-  - binary-0.8.5.1-  - cheapskate-0.1.1+ghc-options:+  idris: -fwarn-unused-imports -fwarn-unused-binds  nix:   enable: false
test/README.md view
@@ -91,6 +91,7 @@ + *reg*:            Regression tests, covering previous bug fixes + *regression*:     Regression tests, covering previous bug fixes + *sourceLocation*: Interaction with files from Idris++ *st*:             ST, state transition systems + *sugar*:          Syntactic sugar, syntax extensions + *syntax*:         Syntax extensions + *tactics*:        Testing for tactics
test/TestData.hs view
@@ -1,7 +1,6 @@ module TestData where  import Data.IntMap as IMap-import Data.Map.Strict as Map import Data.Set as Set  data Codegen = C | JS deriving (Show, Eq, Ord)@@ -53,31 +52,40 @@   ("base",            "Base",     [ (  1, C_CG )]),   ("basic",           "Basic",-    [ (  1, ANY  ),-      (  2, ANY  ),-      (  3, ANY  ),-      (  4, ANY  ),-      (  5, ANY  ),-      (  6, ANY  ),-      (  7, C_CG ),-      (  8, ANY  ),-      (  9, ANY  ),-      ( 10, ANY  ),-      ( 11, C_CG ),-      ( 12, ANY  ),-      ( 13, ANY  ),-      ( 14, ANY  ),-      ( 15, ANY  ),-      ( 16, ANY  ),-      ( 17, ANY  ),-      ( 18, ANY  ),-      ( 19, ANY  )]),+    [ (  1, ANY     ),+      (  2, ANY     ),+      (  3, ANY     ),+      (  4, ANY     ),+      (  5, ANY     ),+      (  6, ANY     ),+      (  7, C_CG    ),+      (  8, ANY     ),+      (  9, ANY     ),+      ( 10, ANY     ),+      ( 11, C_CG    ),+      ( 12, ANY     ),+      ( 13, ANY     ),+      ( 14, ANY     ),+      ( 15, ANY     ),+      ( 16, ANY     ),+      ( 17, ANY     ),+      ( 18, ANY     ),+      ( 19, ANY     ),+      ( 20, ANY     ),+      ( 21, C_CG    ),+      ( 22, NODE_CG ),+      ( 23, ANY     ),+      ( 24, ANY     ),+      ( 25, ANY     )]),   ("bignum",          "Bignum",     [ (  1, ANY  ),       (  2, ANY  )]),   ("bounded",         "Bounded",     [ (  1, ANY  )]),   ("buffer",          "Buffer",+    [ (  1, C_CG  ),+      (  2, C_CG  )]),+  ("contrib",         "Contrib",     [ (  1, C_CG  )]),   ("corecords",       "Corecords",     [ (  1, ANY  ),@@ -86,7 +94,8 @@     [ (  1, ANY  )]),   ("directives",      "Directives",     [ (  1, ANY  ),-      (  2, ANY  )]),+      (  2, ANY  ),+      (  3, C_CG )]),   ("disambig",        "Disambiguation",     [ (  2, ANY  )]),   ("docs",            "Documentation",@@ -128,6 +137,7 @@     , (  8, C_CG )     , (  9, C_CG )     , ( 10, NODE_CG )+    , ( 11, NODE_CG )     ]),   ("folding",         "Folding",     [ (  1, ANY  )]),@@ -157,7 +167,11 @@       ( 13, ANY  ),       ( 14, C_CG ),       ( 15, ANY  ),-      ( 16, ANY  )]),+      ( 16, ANY  ),+-- FIXME: Re-enable interactive017 once it works with and without node.+-- FIXME: See https://github.com/idris-lang/Idris-dev/pull/4046#issuecomment-326910042+--      ( 17, ANY  ),+      ( 18, ANY  )]),   ("interfaces",      "Interfaces",     [ (  1, ANY  ),       (  2, ANY  ),@@ -165,7 +179,8 @@       (  4, ANY  ), --       (  5, ANY  ),       (  6, ANY  ),-      (  7, ANY  )]),+      (  7, ANY  ),+      (  8, ANY  )]),   ("interpret",      "Interpret",     [ (  1, ANY  ),       (  2, ANY  )]),@@ -262,6 +277,14 @@       (  3 , ANY  )]),   ("sourceLocation",  "Source location",     [ (  1 , ANY  )]),+  ("st",  "ST",+    [ (  1, C_CG),+      (  2, C_CG),+      (  3, C_CG),+      (  4, C_CG),+      (  5, C_CG),+      (  6, C_CG),+      (  7, C_CG)]),   ("sugar",           "Syntactic sugar",     [ (  1, ANY  ),       (  2, ANY  ),
test/TestRun.hs view
@@ -6,13 +6,11 @@ import Control.Monad import Data.Char (isLetter) import qualified Data.IntMap as IMap-import Data.List import Data.Monoid ((<>)) import Data.Proxy import Data.Typeable import Options.Applicative import System.Directory-import System.Environment import System.Exit import System.FilePath ((</>)) import System.Info
test/basic002/expected view
@@ -1,5 +1,13 @@-test006.idr:25:23-28:+test006.idr:25:23-27:+   |+25 | Main.parity_lemma_2 = proof {+   |                       ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.-test006.idr:32:23-28:++test006.idr:32:23-27:+   |+32 | Main.parity_lemma_1 = proof {+   |                       ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.+ [False, True, False, True, False, True]
test/basic006/expected view
@@ -1,4 +1,8 @@-test020a.idr:16:18:When checking right hand side of foo with expected type+test020a.idr:16:10-19:+   |+16 | foo xs = reverse xs+   |          ~~~~~~~~~~+When checking right hand side of foo with expected type         List a  When checking an application of function Prelude.List.reverse:@@ -6,5 +10,6 @@                 Vect n a (Type of xs)         and                 List a (Expected type)+ [3, 2, 1] "Number 42"
test/basic009/expected view
@@ -1,7 +1,16 @@ MAIN-PASS-Faulty.idr:6:9-12:num is bound as an implicit+Faulty.idr:6:9-11:+  |+6 | fault : num = Z+  |         ~~~+num is bound as an implicit 	Did you mean to refer to A.num?-Faulty.idr:7:7:When checking right hand side of fault with expected type++Faulty.idr:7:9-12:+  |+7 | fault = Refl+  |         ~~~~+When checking right hand side of fault with expected type         num = 0  Type mismatch between@@ -14,4 +23,10 @@                 0         and                 num-Multiple.idr:3:1:import alias not unique: "X"++Multiple.idr:3:21:+  |+3 | import Data.Vect as X+  |                     ^+import alias not unique: "X"+
test/basic013/basic013.idr view
@@ -20,6 +20,8 @@           putStrLn (reverse (foo ++ bar))           printLn (length foo)           printLn baz+          printLn (strCons '\x141' "")+          printLn (singleton (chr 0x141))           let x = 4           let newstr = appMany (toNat x)           putStrLn newstr
test/basic013/expected view
@@ -3,6 +3,8 @@ x→xλx→xλ 4 '\955'+"\321"+"\321" λx→xλx→xλx→xλx→xλx→x '\955' 20
test/basic016/expected view
@@ -1,1 +1,1 @@-Cycle detected in imports: CycleA.idr -> CycleB -> CycleC -> CycleA -> CycleB+ Cycle detected in imports: CycleA.idr -> CycleB -> CycleC -> CycleA -> CycleB
test/basic017/expected view
@@ -1,3 +1,8 @@-basic017a.idr:11:8:When checking type of Main.append:+basic017a.idr:11:8:+   |+11 | append : Vect n a -> Vect m a -> Vect (n + m) a+   |        ^+When checking type of Main.append: When checking an application of Main.Vect:         No such variable n+
test/basic018/expected view
@@ -1,10 +1,22 @@-basic018.idr:7:12-17:+basic018.idr:7:12-16:+  |+7 |       Vect thing elem+  |            ~~~~~ thing is bound as an implicit 	Did you mean to refer to Main.thing?-basic018.idr:12:8-13:++basic018.idr:12:8-12:+   |+12 | test : thing = S 41+   |        ~~~~~ thing is bound as an implicit 	Did you mean to refer to Main.thing?-basic018.idr:13:6:When checking right hand side of test with expected type++basic018.idr:13:8-11:+   |+13 | test = Refl+   |        ~~~~+When checking right hand side of test with expected type         thing = S 41  Type mismatch between@@ -17,3 +29,4 @@                 42         and                 thing+
+ test/basic020/basic020.idr view
@@ -0,0 +1,42 @@+%default total++data Ty = Ctor Int++fn : Ty -> Ty+fn m@(Ctor _) = y+  where+    y = m -- from @ pattern++asPatternVisibleInWhere : fn (Ctor 42) = Ctor 42+asPatternVisibleInWhere = Refl++fn2 : Ty -> Ty+fn2 m@(Ctor _) = y (Ctor 99)+  where+    y m = m -- should be the arg `m`, not the @ pattern++lhsVariablesShadowAsPattern : fn2 (Ctor 42) = Ctor 99+lhsVariablesShadowAsPattern = Refl++fn3 : Ty -> Ty+fn3 m@(Ctor _) = y (Ctor 99)+  where+    y m = z+      where+        z = m -- should be y's arg `m`, not @ pattern++nestedWhereShadowsAsPattern : fn3 (Ctor 42) = Ctor 99+nestedWhereShadowsAsPattern = Refl++fn4 : Ty -> Ty+fn4 m@(Ctor _) = y (Ctor 99)+  where+    y _ = z+      where+        z = m -- should be @ pattern++nestedWhereExposesAsPattern : fn4 (Ctor 42) = Ctor 42+nestedWhereExposesAsPattern = Refl++main : IO ()+main = putStrLn "OK"
+ test/basic020/expected view
@@ -0,0 +1,1 @@+OK
+ test/basic020/run view
@@ -0,0 +1,4 @@+#!/usr/bin/env bash+${IDRIS:-idris} $@ basic020.idr -o basic020+./basic020+rm -f basic020 *.ibc
+ test/basic021/basic021.idr view
@@ -0,0 +1,13 @@+import Data.IORef++count : Nat -> IORef Integer -> IO ()+count Z ref+    = do x <- readIORef ref+         printLn x+count (S k) ref+    = do modifyIORef ref (+1)+         count k ref++main : IO ()+main = do r <- newIORef 0+          count 1000000 r
+ test/basic021/basic021_2.idr view
@@ -0,0 +1,13 @@+import Data.IORef++count : HasReference ffi =>  Nat -> IORef Integer -> IO' ffi ()+count Z ref+    = do x <- readIORef' ref+         printLn' x+count (S k) ref+    = do modifyIORef' ref (+1)+         count k ref++main : IO ()+main = do r <- newIORef' 0+          count 1000 r
+ test/basic021/expected view
@@ -0,0 +1,2 @@+1000000+1000
+ test/basic021/run view
@@ -0,0 +1,6 @@+#!/usr/bin/env bash+${IDRIS:-idris} $@ basic021.idr -o basic021+${IDRIS:-idris} $@ basic021_2.idr -o basic021_2+./basic021+./basic021_2+rm -f basic021 basic021_2 *.ibc
+ test/basic022/basic022.idr view
@@ -0,0 +1,13 @@+import Data.IORef++count : HasReference ffi =>  Nat -> IORef Integer -> IO' ffi ()+count Z ref+    = do x <- readIORef' ref+         printLn' x+count (S k) ref+    = do modifyIORef' ref (+1)+         count k ref++main : JS_IO ()+main = do r <- newIORef' 0+          count 1000 r
+ test/basic022/expected view
@@ -0,0 +1,1 @@+1000
+ test/basic022/run view
@@ -0,0 +1,4 @@+#!/usr/bin/env bash+${IDRIS:-idris} $@ basic022.idr -o basic022+./basic022+rm -f basic022 *.ibc
+ test/basic023/expected view
@@ -0,0 +1,10 @@+True+True+True+True+True+True+True+True+True+True
+ test/basic023/run view
@@ -0,0 +1,4 @@+#!/usr/bin/env bash+${IDRIS:-idris} $@ sections.idr -o sections+./sections+rm -f sections *.ibc
+ test/basic023/sections.idr view
@@ -0,0 +1,34 @@+postInc : Nat -> Nat+postInc = (`plus` 1)++infixr 8 `cons`+cons : Int -> List Int -> List Int+cons = (::)++namespace A+  infixr 8 `nmul`+  nmul : Nat -> Nat -> Nat+  nmul = (*)++namespace B+  nmul : Nat -> Nat -> Nat+  nmul _ y = y++prefix 1 :/+(:/) : Nat -> Nat+(:/) = (1 `plus`)++main : IO ()+main = do+  printLn $ (1 `cons`) [2] == [1,2]+  printLn $ (1 ::) [2]     == [1,2]+  printLn $ (`cons` [2]) 1 == [1,2]+  printLn $ (:: [2]) 1     == [1,2]+  let x : Integer = 4+  printLn $ (- x) == -4         -- prefix, not section+  let io : IO Integer = pure 9+  printLn $ (! io) == 9         -- prefix, not section+  printLn $ (:/ 3) == 4         -- custom prefix operator (#2571)+  printLn $ 1 `cons` 2 `cons` [3] == [1,2,3]+  printLn $ 2 `A.nmul` 3 `B.nmul` 5 == 10+  printLn $ 2 `B.nmul` 3 `A.nmul` 5 == 15
+ test/basic024/basic024.idr view
@@ -0,0 +1,51 @@+module basic024++namespace Main+  main : IO ()+  main = do+    printLn $ div (the Integer 5) 2+    printLn $ div (the Int 5) 2+    printLn $ div (the Bits8 5) 2+    printLn $ div (the Bits16 5) 2+    printLn $ div (the Bits32 5) 2+    printLn $ div (the Bits64 5) 2+    printLn $ div (the Nat 5) 2++    printLn $ mod (the Integer 5) 2+    printLn $ mod (the Int 5) 2+    printLn $ mod (the Bits8 5) 2+    printLn $ mod (the Bits16 5) 2+    printLn $ mod (the Bits32 5) 2+    printLn $ mod (the Bits64 5) 2+    printLn $ mod (the Nat 5) 2++    printLn $ div (the Integer 3) 5+    printLn $ div (the Int 3) 5+    printLn $ div (the Bits8 3) 5+    printLn $ div (the Bits16 3) 5+    printLn $ div (the Bits32 3) 5+    printLn $ div (the Bits64 3) 5+    printLn $ div (the Nat 3) 5++    printLn $ mod (the Integer 3) 5+    printLn $ mod (the Int 3) 5+    printLn $ mod (the Bits8 3) 5+    printLn $ mod (the Bits16 3) 5+    printLn $ mod (the Bits32 3) 5+    printLn $ mod (the Bits64 3) 5+    printLn $ mod (the Nat 3) 5++    printLn $ div (the Integer (-5)) 2+    printLn $ div (the Int (-5)) 2++    printLn $ mod (the Integer (-5)) 2+    printLn $ mod (the Int (-5)) 2++    printLn $ div (the Integer (-3)) 5+    printLn $ div (the Int (-3)) 5++    printLn $ mod (the Integer (-3)) 5+    printLn $ mod (the Int (-3)) 5++    printLn $ div (-432642342742368327462378462387) 36473264372+    printLn $ mod (-432642342742368327462378462387) 36473264372
+ test/basic024/expected view
@@ -0,0 +1,76 @@+2 : Integer+2 : Int+2 : Bits8+2 : Bits16+2 : Bits32+2 : Bits64+2 : Nat+1 : Integer+1 : Int+1 : Bits8+1 : Bits16+1 : Bits32+1 : Bits64+1 : Nat+0 : Integer+0 : Int+0 : Bits8+0 : Bits16+0 : Bits32+0 : Bits64+0 : Nat+3 : Integer+3 : Int+3 : Bits8+3 : Bits16+3 : Bits32+3 : Bits64+3 : Nat+-2 : Integer+-2 : Int+-1 : Integer+-1 : Int+0 : Integer+0 : Int+-3 : Integer+-3 : Int+-11861903511836511836 : Integer+-25643355395 : Integer+2+2+02+0002+00000002+0000000000000002+2+1+1+01+0001+00000001+0000000000000001+1+0+0+00+0000+00000000+0000000000000000+0+3+3+03+0003+00000003+0000000000000003+3+-2+-2+-1+-1+0+0+-3+-3+-11861903511836511836+-25643355395
+ test/basic024/input view
@@ -0,0 +1,46 @@+:x div (the Integer 5) 2+:x div (the Int 5) 2+:x div (the Bits8 5) 2+:x div (the Bits16 5) 2+:x div (the Bits32 5) 2+:x div (the Bits64 5) 2+:x div (the Nat 5) 2++:x mod (the Integer 5) 2+:x mod (the Int 5) 2+:x mod (the Bits8 5) 2+:x mod (the Bits16 5) 2+:x mod (the Bits32 5) 2+:x mod (the Bits64 5) 2+:x mod (the Nat 5) 2++:x div (the Integer 3) 5+:x div (the Int 3) 5+:x div (the Bits8 3) 5+:x div (the Bits16 3) 5+:x div (the Bits32 3) 5+:x div (the Bits64 3) 5+:x div (the Nat 3) 5++:x mod (the Integer 3) 5+:x mod (the Int 3) 5+:x mod (the Bits8 3) 5+:x mod (the Bits16 3) 5+:x mod (the Bits32 3) 5+:x mod (the Bits64 3) 5+:x mod (the Nat 3) 5++:x div (the Integer (-5)) 2+:x div (the Int (-5)) 2++:x mod (the Integer (-5)) 2+:x mod (the Int (-5)) 2++:x div (the Integer (-3)) 5+:x div (the Int (-3)) 5++:x mod (the Integer (-3)) 5+:x mod (the Int (-3)) 5++:x div (-432642342742368327462378462387) 36473264372+:x mod (-432642342742368327462378462387) 36473264372
+ test/basic024/run view
@@ -0,0 +1,8 @@+#!/usr/bin/env bash++${IDRIS:-idris} $@ --quiet --port none < input+${IDRIS:-idris} $@ basic024.idr -o basic024++./basic024++rm -f basic024 *.ibc
+ test/basic025/basic025.idr view
@@ -0,0 +1,28 @@+module basic025++-- converting data from strings at runtime so as to prevent the+-- compiler of eliding the calls to atan2 via constant folding+input : List (String, String, String)+input = [+  ("atan2", " 1", " 1"),+  ("atan2", "-1", " 1"),+  ("atan2", " 1", "-1"),+  ("atan2", "-1", "-1"),+  ("atan2", " 0", " 1"),+  ("atan2", " 1", " 0")+]++round : Double -> Double+round x = let y = x * 1e10+              z = if y < 0 then (ceiling y) else (floor y)+          in z / 1e10++-- the input file is read at runtime so as to prevent the compiler of+-- eliding the calls to atan2 via constant folding+namespace Main+  main : IO ()+  main = traverse_ evalInput input+    where+      evalInput : (String, String, String) -> IO ()+      evalInput ("atan2", y, x) = printLn $ round $ atan2 (cast y) (cast x)+      evalInput _ = putStrLn $ "Could not eval line"
+ test/basic025/expected view
@@ -0,0 +1,12 @@+0.7853981633974483 : Double+-0.7853981633974483 : Double+2.356194490192345 : Double+-2.356194490192345 : Double+0.0 : Double+1.5707963267948966 : Double+0.7853981633+-0.7853981633+2.3561944901+-2.3561944901+0+1.5707963267
+ test/basic025/input view
@@ -0,0 +1,7 @@+:x atan2   1    1+:x atan2 (-1)   1+:x atan2   1  (-1)+:x atan2 (-1) (-1)++:x atan2 0 1+:x atan2 1 0
+ test/basic025/run view
@@ -0,0 +1,7 @@+#!/usr/bin/env bash+${IDRIS:-idris} $@ --quiet --port none < input+${IDRIS:-idris} $@ -o basic025 basic025.idr++./basic025 input++rm -f basic025 *.ibc
test/bignum002/bignum002.idr view
@@ -2,4 +2,13 @@  main : IO () main = do-    putStrLn $ show $ divNat 1809022195644390369852458 91238741987+    printLn $ divNat 1809022195644390369852458 91238741987+    printLn $ div (-432642342742368327462378462387) 36473264372++    -- values at the border between C ints and bignums+    printLn $ div 1073741822 73892+    printLn $ div 1073741823 73892+    printLn $ div 1073741824 73892+    printLn $ div (-1073741823) 73892+    printLn $ div (-1073741824) 73892+    printLn $ div (-1073741825) 73892
test/bignum002/expected view
@@ -1,1 +1,8 @@ 19827346982734+-11861903511836511836+14531+14531+14531+-14531+-14531+-14531
+ test/buffer002/buffer002.idr view
@@ -0,0 +1,27 @@+import Data.Buffer++main : IO ()+main = do Just buf <- newBuffer 40+          printLn (size buf)+          setInt buf 5 1234567890+          setInt buf 36 1234567890+          setString buf 20 "Hello world!"+          printLn !(bufferData buf)++          val <- getInt buf 5+          printLn val+          val <- getInt buf 6+          printLn val+          val <- getInt buf 36+          printLn val+          val <- getInt buf 37 -- out of bounds, expect 0+          printLn val++          str <- getString buf 20 10+          putStrLn str+          str <- getString buf 20 12+          putStrLn str+          str <- getString buf 200 12 -- out of bounds, expect ""+          printLn str+          str <- getString buf 35 12 -- out of bounds, expect ""+          printLn str
+ test/buffer002/expected view
@@ -0,0 +1,10 @@+40+[00, 00, 00, 00, 00, D2, 02, 96, 49, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 48, 65, 6C, 6C, 6F, 20, 77, 6F, 72, 6C, 64, 21, 00, 00, 00, 00, D2, 02, 96, 49]+1234567890+4822530+1234567890+0+Hello worl+Hello world!+""+""
+ test/buffer002/run view
@@ -0,0 +1,4 @@+#!/usr/bin/env bash+${IDRIS:-idris} $@ buffer002.idr -o buffer002+./buffer002+rm -f buffer002 test.buf *.ibc
+ test/contrib001/contrib001.idr view
@@ -0,0 +1,14 @@+module Main++import Text.PrettyPrint.WL++%default total++myDoc : Doc+myDoc = fold (|//|) $ map text $ words "this is a long sentence with a lot of words that I can use for testing the performance of the prettier printer implementation. I need a few more words to prove my point, though."++myString : String+myString =  toString 0 15 $ myDoc++main : IO ()+main = putStrLn myString
+ test/contrib001/expected view
@@ -0,0 +1,12 @@+thisisalong+sentencewitha+lotofwordsthatI+canusefor+testingthe+performanceof+theprettier+printer+implementation.+Ineedafewmore+wordstoprovemy+point,though.
+ test/contrib001/run view
@@ -0,0 +1,4 @@+#!/usr/bin/env bash+${IDRIS:-idris} $@ contrib001.idr -o contrib001 -p contrib+./contrib001+rm -f contrib001 *.ibc
test/directives001/expected view
@@ -1,12 +1,42 @@-directives001.idr:14:7:Use of deprecated name directives001.Foo+directives001.idr:14:7:+   |+14 | mkFoo : String -> Foo+   |       ^+Use of deprecated name directives001.Foo To be replaced with `Bar`.-directives001.idr:14:7:Use of deprecated name directives001.Foo++directives001.idr:14:7:+   |+14 | mkFoo : String -> Foo+   |       ^+Use of deprecated name directives001.Foo To be replaced with `Bar`.-directives001.idr:15:7:Use of deprecated name directives001.Foo++directives001.idr:15:9-13:+   |+15 | mkFoo = MkFoo+   |         ~~~~~+Use of deprecated name directives001.Foo To be replaced with `Bar`.-directives001.idr:15:7:Use of deprecated name directives001.Foo++directives001.idr:15:9-13:+   |+15 | mkFoo = MkFoo+   |         ~~~~~+Use of deprecated name directives001.Foo To be replaced with `Bar`.-directives001.idr:26:8:Use of a fragile construct directives001.mkBar++directives001.idr:26:10-28:28:+   |+26 |   main = do+   |          ~~ ...+Use of a fragile construct directives001.mkBar How `Bar`s are to be created is still being discussed, `mkBar` is subject to change.-directives001.idr:26:8:Use of a fragile construct directives001.mkBar++directives001.idr:26:10-28:28:+   |+26 |   main = do+   |          ~~ ...+Use of a fragile construct directives001.mkBar How `Bar`s are to be created is still being discussed, `mkBar` is subject to change.+
test/directives002/expected view
@@ -1,2 +1,6 @@-directives002.idr:12:3:+directives002.idr:12:3-14:28:+   |+12 |   main = do+   |   ~~~~~~~~~ ... directives002.Main.main is possibly not total due to: directives002.loop+
+ test/directives003/directives003.idr view
@@ -0,0 +1,11 @@+module directives003++-- names are randomly generated so as to avoid existing names+%lib C "nuyahcha"+%lib C "mohgiide"+%lib C "apeekair"+%flag C "-Wl,-leeraimam -Wl,-lrahhahwi -Wl,-lgoocheiv"++namespace Main+  main : IO ()+  main = putStrLn "Hello, World!"
+ test/directives003/expected view
@@ -0,0 +1,6 @@+nuyahcha+mohgiide+apeekair+eeraimam+rahhahwi+goocheiv
+ test/directives003/run view
@@ -0,0 +1,13 @@+#!/usr/bin/env bash++# %lib C "nuyahcha"+# %lib C "mohgiide"+# %lib C "apeekair"+# %flag C "-Wl,-leeraimam -Wl,-lrahhahwi -Wl,-lgoocheiv"++${IDRIS:-idris} $@ -o directives003 directives003.idr \+    | tr ' ,"' '\n' \+    | sed 's/-l//' \+    | grep -E 'nuyahcha|mohgiide|apeekair|eeraimam|rahhahwi|goocheiv'++rm -f directives003 *.ibc
test/effects003/expected view
@@ -1,5 +1,9 @@-hangman.idr:204:8-13:+hangman.idr:204:8-12:+    |+204 | wlen = proof search+    |        ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.+ ------------  6 guesses left
test/error001/expected view
@@ -1,4 +1,8 @@-test002.idr:1:6:Universe inconsistency.+test002.idr:1:6:+  |+1 | myid : (a : Type) -> a -> a+  |      ^+Universe inconsistency.         Working on: ./test002.idr.z         Old domain: (6,6)         New domain: (6,5)@@ -6,3 +10,4 @@                 ConstraintFC {uconstraint = ./test002.idr.z <= ./test002.idr.a1, ufc = test002.idr:1:6}                 ConstraintFC {uconstraint = ./test002.idr.y < ./test002.idr.z, ufc = test002.idr:1:6}                 ConstraintFC {uconstraint = ./test002.idr.z <= ./test002.idr.a1, ufc = test002.idr:1:6}+
test/error003/expected view
@@ -1,4 +1,9 @@-ErrorReflection.idr:68:5:When checking right hand side of bad with expected type+ErrorReflection.idr:68:7-20:+   |+68 | bad = Lam (Var Here)+   |       ~~~~~~~~~~~~~~+When checking right hand side of bad with expected type         Tm [] TUnit  DSL type error: (t(504) => t'(503)) doesn't match ()+
test/error004/expected view
@@ -1,12 +1,20 @@-FunErrTest.idr:35:17:+FunErrTest.idr:35:12-18:+   |+35 | badCadr1 = cadr []+   |            ~~~~~~~ When checking right hand side of badCadr1 with expected type         Int  When checking argument cons2 to function FunErrTest.cadr:         Could not prove that [] has at least two elements.-FunErrTest.idr:38:17:++FunErrTest.idr:38:12-19:+   |+38 | badCadr2 = cadr [1]+   |            ~~~~~~~~ When checking right hand side of badCadr2 with expected type         Int  When checking argument cons2 to function FunErrTest.cadr:         Could not prove that [] has at least two elements.+
test/error005/expected view
@@ -1,31 +1,56 @@-error005.idr:13:1:When checking right hand side of two with expected type+error005.idr:11:7:+   |+11 | two = 2+   |       ^+When checking right hand side of two with expected type         Fin 2  When checking argument prf to function Data.Fin.fromInteger:         When using 2 as a literal for a Fin 2                  2 is not strictly less than 2-error005.idr:16:1:When checking right hand side of hahaha with expected type++error005.idr:14:12:+   |+14 | hahaha n = 0+   |            ^+When checking right hand side of hahaha with expected type         Fin n  When checking argument prf to function Data.Fin.fromInteger:         When using 0 as a literal for a Fin n                  0 is not strictly less than n-error005.idr:22:1:When checking right hand side of notOk with expected type++error005.idr:20:11:+   |+20 | notOk n = 2+   |           ^+When checking right hand side of notOk with expected type         Fin (plus 2 n)  When checking argument prf to function Data.Fin.fromInteger:         When using 2 as a literal for a Fin (S (S n))                  2 is not strictly less than S (S n)-error005.idr:23:24:When checking right hand side of b0rken with expected type++error005.idr:23:12-24:+   |+23 | b0rken n = fromInteger n+   |            ~~~~~~~~~~~~~+When checking right hand side of b0rken with expected type         Fin 3  When checking argument prf to function Data.Fin.fromInteger:         When using n as a literal for a Fin 3                  Could not show that n is less than 3 because n is a bound                 variable instead of a constant Integer-error005.idr:28:1:When checking right hand side of x with expected type++error005.idr:26:17:+   |+26 | x = the (Fin 4) 5+   |                 ^+When checking right hand side of x with expected type         Fin 4  When checking argument prf to function Data.Fin.fromInteger:         When using 5 as a literal for a Fin 4                  5 is not strictly less than 4+
test/error006/expected view
@@ -1,2 +1,7 @@-WithPatsNoWith.idr:4:5:When checking left hand side of foo:+WithPatsNoWith.idr:4:1-13:+  |+4 | foo 1 | 2 | 3 = True+  | ~~~~~~~~~~~~~+When checking left hand side of foo: unexpected patterns outside of "with" block+
test/error007/expected view
@@ -1,4 +1,7 @@-error007.idr:26:17:+error007.idr:26:7-29:+   |+26 |       send_page conn str code -- (prim__zextB32_Int code)+   |       ~~~~~~~~~~~~~~~~~~~~~~~ When checking right hand side of answer_to_connection with expected type         IO Int @@ -13,3 +16,4 @@                         Bits32                 and                         Int+
test/error008/expected view
@@ -1,4 +1,14 @@-error008.idr:3:4:When checking type of Main.s2:+error008.idr:3:4:+  |+3 | s2 : x + sum Nil = x * fromInteger 0+  |    ^+When checking type of Main.s2: Can't disambiguate name: Prelude.List.Nil, Data.Vect.Nil-error008a.idr:3:4:When checking type of Main.s1:++error008a.idr:3:4:+  |+3 | s1 : Num a => {x : a} -> x + sum {a} Nil = x -- * fromInteger 0+  |    ^+When checking type of Main.s1: Can't disambiguate name: Prelude.List.Nil, Data.Vect.Nil+
test/ffi002/expected view
@@ -1,1 +1,6 @@-test023.idr:20:21:Type provider error: Always fails+test023.idr:20:26-36:+   |+20 | %provide (t : Type) with badProvider+   |                          ~~~~~~~~~~~+Type provider error: Always fails+
test/ffi007/expected view
@@ -7,3 +7,4 @@ I'm dynamic 3 6 7+3
test/ffi007/ffi007.h view
@@ -1,6 +1,8 @@ #include <stdint.h> typedef int (*callback)(int); +#define THREE 3+ int32_t testvar = 887;  void test_ffi(int (*cb)(int));
test/ffi007/ffi007.idr view
@@ -42,6 +42,10 @@ test8 = foreign FFI_C "test_mulpar" (CFnPtr (Int -> Int -> ()) -> IO ())                                     (MkCFnPtr adder) ++test9 : IO Int+test9 = foreign FFI_C "#THREE" (IO Int)+ main : IO () main = do             test@@ -55,4 +59,5 @@             i <- test7 fptr 3             printLn i             test8+            printLn !test9             pure ()
test/ffi008/ffi008.c view
@@ -1,6 +1,8 @@-#include "ffi008.h" #include <stdio.h>+#include <stdlib.h> +#include "ffi008.h"+ int size1(void) {     return sizeof(struct test1); }@@ -11,4 +13,13 @@  void print_mystruct(void) {     printf("a: %d b: %d\n", mystruct.a, mystruct.b);+}++struct test2* calc_struct(struct test1 *in)+{+    struct test2 *out = malloc(sizeof(struct test2));+    out->a = in->a * in->a;+    out->b = in->b & 0x0000FFFF;++    return out; }
test/ffi008/ffi008.h view
@@ -15,3 +15,5 @@ int size1(void); int size2(void); void print_mystruct();++struct test2* calc_struct(struct test1*);
test/ffi008/ffi008.idr view
@@ -18,6 +18,9 @@ print_mystruct : IO () print_mystruct = foreign FFI_C "print_mystruct" (IO ()) +calc_struct : Ptr -> IO Ptr+calc_struct = foreign FFI_C "calc_struct" (Ptr -> IO Ptr)+ test1 : Composite test1 = STRUCT [I8, I64] @@ -46,3 +49,10 @@         print !(peek I32 f1)     withAlloc PTR $ \p =>         poke PTR p fms+    res <- withAlloc test1 $ \p => do+        let f1 = (test1 # 0) p+        let f2 = (test1 # 1) p+        poke I8 f1 42+        poke I64 f2 1125899906842624+        calc_struct p+    free res
+ test/ffi011/expected view
@@ -0,0 +1,2 @@+Ready to show...+[10, 20, 30, 40]
+ test/ffi011/ffi011 view
@@ -0,0 +1,7 @@+l = require("./lib.js");++x = l.cons(10, l.cons(20, l.nil()));+y = l.cons(30, l.cons(40, l.nil()));+z = l.addLists(x, y);++console.log(l.showList(z));
+ test/ffi011/ffi011.idr view
@@ -0,0 +1,27 @@+module Lib++import Data.List++addLists : List Int -> List Int -> List Int+addLists xs ys = xs ++ ys++nil : List Int+nil = []++cons : Int -> List Int -> List Int+cons x xs = x :: xs++show' : List Int -> JS_IO String+show' xs = do putStrLn' "Ready to show..."+              pure (show xs)++testList : FFI_Export FFI_JS "" []+testList = Data (List Int) "ListInt" $+           Data (List Nat) "ListNat" $+           Fun addLists "addLists" $+           Fun nil "nil" $+           Fun cons "cons" $+           Data Nat "Nat" $+           Fun Strings.length "lengthS" $+           Fun show' "showList" $+           End
+ test/ffi011/run view
@@ -0,0 +1,4 @@+#!/usr/bin/env bash+${IDRIS:-idris} $@ ffi011.idr --interface -o lib.js+node ./ffi011+rm -f *.ibc lib.js
test/interactive010/expected view
@@ -1,20 +1,24 @@ Prelude.List.(++) : List a -> List a -> List a Prelude.Strings.(++) : String -> String -> String-(input):1:11:a is not an implicit argument of Prelude.Interfaces./+(input):1:7-20:a is not an implicit argument of Prelude.Interfaces./ Usage is :doc <functionname> Usage is :wc <functionname> Usage is :printdef <functionname> pat {ty_503} : Type toplevel.u. pat {__interface_504} : Prelude.Interfaces.Fractional {ty_503}. Prelude.Interfaces./ {ty_503} {__interface_504}   : pty {ty_503} : Type toplevel.u. pty {__interface_504} : Prelude.Interfaces.Fractional {ty_503}. {ty_503} -> {ty_503} -> {ty_503}-(input):1:1: error: expected: ":",-    dependent type signature,-    end of input-/<EOF> -^      -(input):1:1: error: expected: ":",-    dependent type signature,-    end of input-++<EOF> -^       +(input):1:1:+  |+1 | /+  | ^+unexpected '/'+expecting ':', dependent type signature, or end of input++(input):1:1:+  |+1 | +++  | ^+unexpected "++"+expecting ':', dependent type signature, or end of input+ Can't find implementation for Fractional ty
test/interactive017/run view
+ test/interactive018/Imported1.idr view
@@ -0,0 +1,10 @@+module Imported1++import Imported2++imported1_private : a -> a+imported1_private = imported2_visible++export+imported1_visible : a -> a+imported1_visible = imported1_private
+ test/interactive018/Imported2.idr view
@@ -0,0 +1,8 @@+module Imported1++imported2_private : a -> a+imported2_private a = a++export+imported2_visible : a -> a+imported2_visible a = a
+ test/interactive018/Public1.idr view
@@ -0,0 +1,10 @@+module Public1++import public Public2++public1_private : a -> a+public1_private a = a++export+public1_visible : a -> a+public1_visible = public1_private
+ test/interactive018/Public2.idr view
@@ -0,0 +1,8 @@+module Public2++public2_private : a -> a+public2_private a = a++export+public2_visible : a -> a+public2_visible = public2_private
+ test/interactive018/Top.idr view
@@ -0,0 +1,11 @@+module Top++import Imported1+import public Public1++top_private : a -> a+top_private = imported1_visible++export+top_visible : a -> a+top_visible = public2_visible
+ test/interactive018/expected view
@@ -0,0 +1,20 @@+1 : Integer+top_private : a -> a+1 : Integer+top_visible : a -> a+No such variable imported1_private+No such variable imported1_private+1 : Integer+imported1_visible : a -> a+No such variable imported2_private+No such variable imported2_private+No such variable imported2_visible+No such variable imported2_visible+No such variable public1_private+No such variable public1_private+1 : Integer+public1_visible : a -> a+No such variable public2_private+No such variable public2_private+1 : Integer+public2_visible : a -> a
+ test/interactive018/input view
@@ -0,0 +1,20 @@+top_private 1+:t top_private+top_visible 1+:t top_visible+imported1_private 1+:t imported1_private+imported1_visible 1+:t imported1_visible+imported2_private 1+:t imported2_private+imported2_visible 1+:t imported2_visible+public1_private 1+:t public1_private+public1_visible 1+:t public1_visible+public2_private 1+:t public2_private+public2_visible 1+:t public2_visible
+ test/interactive018/run view
@@ -0,0 +1,3 @@+#!/usr/bin/env bash+${IDRIS:-idris} $@ --quiet --port none Top.idr < input+rm -f *.ibc
+ test/interfaces008/expected view
@@ -0,0 +1,6 @@+interfaces008.idr:20:18-23:+   |+20 |   implementation Foo2 a where+   |                  ~~~~~~+Default implementations must be for a super interface constraint on the containing interface.+
+ test/interfaces008/interfaces008.idr view
@@ -0,0 +1,20 @@+interface Foo a where++interface Foo2 a where++interface Foo a => Bar a where++interface Foo a => Bar2 a where+  implementation Foo a where++-- Foo is found in parent+interface Bar a => Bar3 a where+  implementation Foo a where++-- not necessary but should compile+interface (Foo a, Bar a) => Bar4 a where+  implementation Foo a where++-- should fail to compile (Foo2 isn't found in parent interfaces)+interface Foo a => Bar5 a where+  implementation Foo2 a where
+ test/interfaces008/run view
@@ -0,0 +1,3 @@+#!/usr/bin/env bash+${IDRIS:-idris} $@ --nocolour --consolewidth 70 interfaces008.idr --noprelude --check+rm -f interfaces008 *.ibc
+ test/interfaces009/expected view
+ test/interfaces009/interfaces009.idr view
@@ -0,0 +1,24 @@+module Test++LTE : (x, y : Double) -> Type++NonNegDouble : Type+NonNegDouble = Subset Double (\ x => 0.0 `LTE` x)++plus : (x, y : NonNegDouble) -> NonNegDouble++mult : (x, y : NonNegDouble) -> NonNegDouble++fromIntegerNN : Integer -> NonNegDouble++implementation [numnnd] Num NonNegDouble where+  (+) = plus+  (*) = mult+  fromInteger = fromIntegerNN++using implementation numnnd+  x : NonNegDouble+  y : NonNegDouble+  z : NonNegDouble+  z = x + y+
+ test/interfaces009/run view
@@ -0,0 +1,3 @@+#!/usr/bin/env bash+${IDRIS:-idris} $@ --nocolour --consolewidth 70 interfaces009.idr --noprelude --check+rm -f interfaces009 *.ibc
test/layout001/expected view
@@ -1,76 +1,82 @@-./layout001a.idr:5:1: error: Wrong-    indention: should be greater-    than context-    indentation, expected: space-y -^ -./layout001b.idr:5:3: error: Wrong-    indention: should be greater-    than context-    indentation, expected: space-= y -  ^ -./layout001c.idr:3:1: error: Wrong-    indention: should be greater-    than context-    indentation, expected: space-2 -^ -./layout001e.idr:6:1: error: Wrong-    indention: should be greater-    than context-    indentation, expected: space-3 -^ -./layout001f.idr:6:2: error: Wrong-    indention: should be greater-    than context-    indentation, expected: space- 3 - ^ -./layout001g.idr:6:3: error: Wrong-    indention: should be greater-    than context-    indentation, expected: space-  3 -  ^ -./layout001h.idr:6:3: error: Wrong-    indention: should be greater-    than context-    indentation, expected: space-  3 -  ^ -./layout001i.idr:6:4: error: Wrong-    indention: should be greater-    than context-    indentation, expected: space-   3 -   ^ -./layout001j.idr:6:5: error: Wrong-    indention: should be greater-    than context-    indentation, expected: space-    3 -    ^ -./layout001l.idr:6:1: error: Wrong-    indention: should be greater-    than context-    indentation, expected: space-y -^ -mplus1.idr:13:31:When checking right hand side of term with expected type+layout001a.idr:5:1:+  |+5 | y+  | ^+Wrong indention: should be greater than context indentation++layout001b.idr:5:3:+  |+5 | = y+  |   ^+Wrong indention: should be greater than context indentation++layout001c.idr:3:1:+  |+3 | 2+  | ^+Wrong indention: should be greater than context indentation++layout001e.idr:6:1:+  |+6 | 3+  | ^+Wrong indention: should be greater than context indentation++layout001f.idr:6:2:+  |+6 |  3+  |  ^+Wrong indention: should be greater than context indentation++layout001g.idr:6:3:+  |+6 |   3+  |   ^+Wrong indention: should be greater than context indentation++layout001h.idr:6:3:+  |+6 |   3+  |   ^+Wrong indention: should be greater than context indentation++layout001i.idr:6:4:+  |+6 |    3+  |    ^+Wrong indention: should be greater than context indentation++layout001j.idr:6:5:+  |+6 |     3+  |     ^+Wrong indention: should be greater than context indentation++layout001l.idr:6:1:+  |+6 | y+  | ^+Wrong indention: should be greater than context indentation++mplus1.idr:13:34-17:49:+   |+13 | term                          =  do f <- factor+   |                                  ~~~~~~~~~~~~~~ ...+When checking right hand side of term with expected type         Maybe Int  When checking an application of function Prelude.Applicative.pure:         No such variable f-./mplus2.idr:17:37: error: not-    end of block, expected: ")",-    "->", ";", "in",-    ambiguous use of a left-associative operator,-    ambiguous use of a non-associative operator,-    ambiguous use of a right-associative operator,-    do block expression,-    end of input-                                    `mplus` pure f -                                    ^              -mplus3.idr:11:1:warning - Unreachable case: term++mplus2.idr:17:37:+   |+17 |                                     `mplus` pure f+   |                                     ^+not end of block++mplus3.idr:11:1-16:+   |+11 | term = ?term_rhs+   | ~~~~~~~~~~~~~~~~+Unreachable case: term+
test/literate001/expected view
@@ -1,4 +1,9 @@-./test003a.lidr:1:0:Program line next to comment+./test003a.lidr:1:0:+  |+1 | Broken+  |^+Program line next to comment+ 'a' 'd' zabcdefg
test/meta002/expected view
@@ -1,13 +1,25 @@-DataDef.idr:74:1-9:+DataDef.idr:74:1-8:+   |+74 | %runElab nope+   | ~~~~~~~~ While running an elaboration script, the following error occurred: Prelude.Either.Either is already defined as a datatype.-Tacs.idr:299:15:++Tacs.idr:299:17-300:78:+    |+299 |     testElab3 = %runElab (elaborateSTLC (App (Lam "x" (App (Var 0) (Var 0)))+    |                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ... When checking right hand side of testElab3 with expected type         DPair Ty (Tm [])  Unifying ty and ARR ty t would lead to infinite value-AgdaStyleReflection.idr:315:5:++AgdaStyleReflection.idr:315:7-20:+    |+315 | baz = tactic trivial+    |       ~~~~~~~~~~~~~~ When checking right hand side of baz with expected type         (Nat, Void)  PROOF SEARCH FAILURE is not defined.+
test/meta003/expected view
@@ -1,6 +1,10 @@-BadDef.idr:14:1-9:+BadDef.idr:14:1-8:+   |+14 | %runElab mkBadDef1+   | ~~~~~~~~ While running an elaboration script, the following error occurred: Type mismatch between         () and         String+
test/meta004/expected view
@@ -1,3 +1,7 @@-meta004.idr:50:1-9:+meta004.idr:50:1-8:+   |+50 | %runElab domore+   | ~~~~~~~~ While running an elaboration script, the following error occurred: Not an impossible case+
test/pkg001/test-pkg.ipkg view
@@ -1,4 +1,4 @@-package "test-pkg"+package test-pkg  pkgs = effects 
test/pkg004/expected view
@@ -1,5 +1,6 @@-Uncaught error: user error (test.ipkg:9:1: error: filename-    must contain no directory-    component, expected: space-<EOF> -^     )+Uncaught error: user error (test.ipkg:9:1:+  |+9 | <empty line>+  | ^+filename must contain no directory component+)
test/pkg004/test.ipkg view
@@ -5,4 +5,4 @@ opts = "--warnpartial --warnreach --nocolour --quiet --consolewidth 80"  main = Main-executable = "filenames/cannot include\a directory separator"+executable = "filenames/cannot include\\a directory separator"
test/primitives003/expected view
@@ -5,6 +5,10 @@ True False True+True+True+True+True False True False
test/primitives003/test038.idr view
@@ -1,4 +1,4 @@-module Main +module Main  import Data.Vect import Data.Fin@@ -17,18 +17,22 @@   putStrLn . show $ test "hello" "world"   putStrLn . show $ test (the Char '\0') (the Char '\0')   putStrLn . show $ test (the Char '\1') (the Char '\2')+  putStrLn . show $ test """""" ""+  putStrLn . show $ test """"hello"""" "\"hello\""+  putStrLn . show $ test """""hello""""" "\"\"hello\"\""+  putStrLn . show $ test """""""""" "\"\"\"\"" -- Non-primitives   -- Vect-  putStrLn . show $ +  putStrLn . show $     test (the (Vect _ Int) [1,2,3]) (the (Vect _ Int) [1,2,3])-  putStrLn . show $ +  putStrLn . show $     test (the (Vect _ Int) [1,2,3]) (the (Vect _ Int) [1,2,4])   -- List-  putStrLn . show $ +  putStrLn . show $     test (the (List Int) [1,2,3]) (the (List Int) [1,2,3])-  putStrLn . show $ +  putStrLn . show $     test (the (List Int) [1,2,3]) (the (List Int) [1,2])-  putStrLn . show $ +  putStrLn . show $     test (the (List Int) [1,2,3]) (the (List Int) [1,2,4])   -- Tuple   putStrLn . show $@@ -45,16 +49,16 @@   putStrLn . show $ test (Just "hello") (Just "world")   putStrLn . show $ test (Just "hello") Nothing   -- Either-  putStrLn . show $ test (the (Either String Bool) (Left "hello")) +  putStrLn . show $ test (the (Either String Bool) (Left "hello"))                          (the (Either String Bool) (Left "hello"))-  putStrLn . show $ test (the (Either String Bool) (Left "hello")) +  putStrLn . show $ test (the (Either String Bool) (Left "hello"))                          (the (Either String Bool) (Left "world"))   putStrLn . show $ test (Left "hello") (Right "world")   putStrLn . show $ test (Left "hello") (Right False)   -- Fin-  putStrLn . show $ test (the (Fin (S (S (S (Z))))) (FS (FS (FZ)))) +  putStrLn . show $ test (the (Fin (S (S (S (Z))))) (FS (FS (FZ))))                          (the (Fin (S (S (S (Z))))) (FS (FS (FZ))))-  putStrLn . show $ test (the (Fin (S (S (S (Z))))) (FS (FS (FZ)))) +  putStrLn . show $ test (the (Fin (S (S (S (Z))))) (FS (FS (FZ))))                          (the (Fin (S (S (S (Z))))) (FS (FZ)))   -- Nat   putStrLn . show $ test (S (S (S Z))) (S (S (S Z)))
test/proof001/expected view
@@ -1,4 +1,12 @@-test029.idr:29:25-30:+test029.idr:29:25-29:+   |+29 | simple.append_lemma_2 = proof {+   |                         ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.-test029.idr:36:25-30:++test029.idr:36:25-29:+   |+36 | simple.append_lemma_1 = proof {+   |                         ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.+
test/proof002/expected view
@@ -1,10 +1,25 @@-Reflect.idr:175:21-26:+Reflect.idr:175:21-25:+    |+175 | Reflect.appRExpr1 = proof {+    |                     ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.-Reflect.idr:184:21-26:++Reflect.idr:184:21-25:+    |+184 | Reflect.appRExpr2 = proof {+    |                     ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.-Reflect.idr:192:15-20:++Reflect.idr:192:15-19:+    |+192 | Reflect.bp1 = proof {+    |               ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.-test030a.idr:12:26-14:1:++test030a.idr:12:26-37:+   |+12 | testReflect1 {a} xs ys = AssocProof a+   |                          ~~~~~~~~~~~~ When checking right hand side of testReflect1 with expected type         ys ++ x :: ys ++ xs = (xs ++ [x]) ++ ys ++ xs @@ -19,3 +34,4 @@                         Just x                 and                         Nothing+
test/proof003/expected view
@@ -1,15 +1,39 @@-Parity.idr:17:18-23:+Parity.idr:17:18-22:+   |+17 | parity_lemma_2 = proof {+   |                  ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.-Parity.idr:24:18-23:++Parity.idr:24:18-22:+   |+24 | parity_lemma_1 = proof {+   |                  ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.-test015.idr:88:15-20:++test015.idr:88:15-19:+   |+88 | Main.ntbOdd = proof {+   |               ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.-test015.idr:97:16-21:++test015.idr:97:16-20:+   |+97 | Main.ntbEven = proof {+   |                ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.-test015.idr:107:20-25:++test015.idr:107:20-24:+    |+107 | Main.adc_lemma_2 = proof {+    |                    ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.-test015.idr:142:20-25:++test015.idr:142:20-24:+    |+142 | Main.adc_lemma_1 = proof {+    |                    ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.+ 00101010 01011001 010000011
test/proof007/expected view
@@ -1,6 +1,10 @@-DefaultArgUnknownName.idr:9:6:+DefaultArgUnknownName.idr:9:8-23:+  |+9 | test = funWithBadDefArg+  |        ~~~~~~~~~~~~~~~~ When checking right hand side of test with expected type         ()  When checking argument arg to function DefaultArgUnknownName.funWithBadDefArg:         No such variable sadgjhsag+
test/proof008/expected view
@@ -1,2 +1,6 @@-ClaimAndUnfocus.idr:8:27-32:+ClaimAndUnfocus.idr:8:27-31:+  |+8 | ClaimAndUnfocus.foo_rhs = proof+  |                           ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.+
test/proof011/expected view
@@ -1,4 +1,8 @@-proof011.idr:19:9:When checking right hand side of vassoc' with expected type+proof011.idr:20:7-21:18:+   |+20 |     = rewrite vassoc xs ys xs using vreplace in +   |       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ...+When checking right hand side of vassoc' with expected type         (x :: xs) ++ ys ++ zs = ((x :: xs) ++ ys) ++ zs  rewriting xs ++ ys ++ xs to (xs ++ ys) ++ xs did not change type x ::@@ -7,7 +11,12 @@                                                                  x ::                                                                  (xs ++ ys) ++                                                                  zs-proof011a.idr:13:9:When checking right hand side of vassoc' with expected type++proof011a.idr:14:7-37:+   |+14 |     = rewrite vassoc xs ys xs in Refl+   |       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+When checking right hand side of vassoc' with expected type         (x :: xs) ++ ys ++ zs = ((x :: xs) ++ ys) ++ zs  rewriting xs ++ ys ++ xs to (xs ++ ys) ++ xs did not change type x ::@@ -16,3 +25,4 @@                                                                  x ::                                                                  (xs ++ ys) ++                                                                  zs+
test/pruviloj001/pruviloj001.idr view
@@ -66,6 +66,19 @@                    l ++ [] = l appendNilRightId = %runElab mush +pair : a -> b -> (a, b)+pair = %runElab (do intros ; construct ; hypothesis ; hypothesis)++data Even : Nat -> Type where+  EvenZ : Even Z+  EvenSS : Even n -> Even (S (S n))++even6 : Even 6+even6 = %runElab (do construct ; construct ; construct ; construct ; skip)++even6' : Even 6+even6' = %runElab (repeatUntilFail (ignore construct))+ -- Local Variables: -- idris-load-packages: ("pruviloj") -- End:
test/quasiquote003/expected view
@@ -1,4 +1,9 @@-NoInfer.idr:11:5:When checking right hand side of zzz with expected type+NoInfer.idr:11:7-11:+   |+11 | zzz = `(FZ)+   |       ~~~~~+When checking right hand side of zzz with expected type         TT  No such variable k+
test/quasiquote004/expected view
@@ -1,11 +1,27 @@-Quasiquote004.idr:39:26-31:+Quasiquote004.idr:39:26-30:+   |+39 | Quasiquote004.getMeNat = proof+   |                          ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.-Quasiquote004.idr:42:28-33:++Quasiquote004.idr:42:28-32:+   |+42 | Quasiquote004.fizzyIsAOK = proof+   |                            ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.-Quasiquote004.idr:50:27-32:++Quasiquote004.idr:50:27-31:+   |+50 | Quasiquote004.getMeNat' = proof+   |                           ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.-Quasiquote004.idr:50:25:++Quasiquote004.idr:50:27-51:18:+   |+50 | Quasiquote004.getMeNat' = proof+   |                           ~~~~~ ... When checking right hand side of Quasiquote004.getMeNat' with expected type         String  Not a Nat goal+
test/quasiquote006/expected view
@@ -1,19 +1,31 @@-quasiquote006.idr:9:3:+quasiquote006.idr:9:5-10:+  |+9 | b = `{Nil}+  |     ~~~~~~ When checking right hand side of b with expected type         TTName  Can't disambiguate name: ForeignEnv.Nil,                           Prelude.List.Nil-quasiquote006.idr:12:3:++quasiquote006.idr:12:5-17:+   |+12 | c = `{alsdkjflkj}+   |     ~~~~~~~~~~~~~ When checking right hand side of c with expected type         TTName  No such variable alsdkjflkj-quasiquote006.idr:15:3:++quasiquote006.idr:15:5-11:+   |+15 | d = `{(::)}+   |     ~~~~~~~ When checking right hand side of d with expected type         TTName  Can't disambiguate name: ForeignEnv.::,                           Prelude.List.::,                           Prelude.Stream.::-quasiquote006.idr:17:3:Main.d already defined++ quasiquote006.idr:17:3:Main.d already defined
test/reg017/expected view
@@ -1,5 +1,13 @@-reg017.idr:5:17-24:+reg017.idr:5:17-23:+  |+5 |       { default tactics { refine Refl; solve; } prfA : a = a } ->+  |                 ~~~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.-reg017.idr:8:17-24:++reg017.idr:8:17-23:+  |+8 |       { default tactics { refine Refl; solve; } prfBC : b = c } ->+  |                 ~~~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.+ 4
test/reg027/expected view
@@ -1,2 +1,7 @@ <<int fn>>-reg027a.idr:9:16:Overlapping implementation: Show (Int -> a) already defined+reg027a.idr:9:16-30:+  |+9 | implementation Show (Int -> b) where+  |                ~~~~~~~~~~~~~~~+Overlapping implementation: Show (Int -> a) already defined+
test/regression002/expected view
@@ -1,13 +1,41 @@-reg003a.idr:4:11:When checking type of Main.ECons:+reg003a.idr:4:13-38:+  |+4 |     ECons : Nat -> OddList -> EvenList+  |             ~~~~~~~~~~~~~~~~~~~~~~~~~~+When checking type of Main.ECons: No such variable OddList-reg003a.idr:7:11:When checking type of Main.OCons:++reg003a.idr:7:13-38:+  |+7 |     OCons : Nat -> EvenList -> OddList+  |             ~~~~~~~~~~~~~~~~~~~~~~~~~~+When checking type of Main.OCons: No such variable EvenList-reg003a.idr:9:6:When checking type of Main.test:++reg003a.idr:9:6:+  |+9 | test : EvenList+  |      ^+When checking type of Main.test: No such variable EvenList-reg006.idr:17:1:++reg006.idr:17:1-23:+   |+17 | lookup k Leaf = Nothing+   | ~~~~~~~~~~~~~~~~~~~~~~~ RBTree.lookup is possibly not total due to recursive path RBTree.lookup --> RBTree.lookup-reg007.lidr:8:3:A.n is already defined-reg007.lidr:12:13-19:When checking right hand side of hurrah with expected type++reg007.lidr:8:3-13:+  |+8 | > A.n     = Z    -- This is where it's at!+  |   ~~~~~~~~~~~+A.n is already defined++reg007.lidr:12:13-18:+   |+12 | > hurrah  = isSame+   |             ~~~~~~+When checking right hand side of hurrah with expected type         0 = 1  Type mismatch between@@ -20,40 +48,111 @@                 1         and                 0-reg010.idr:5:15:++reg010.idr:5:3-26:+  |+5 |   unsafeSubst P x x px | _ = px+  |   ~~~~~~~~~~~~~~~~~~~~~~~~ When checking left hand side of with block in usubst.unsafeSubst: Can't match on with block in usubst.unsafeSubst warg a P x x px-reg018a.idr:16:1:++reg018a.idr:16:1-18:+   |+16 | minusCoNat Z n = Z+   | ~~~~~~~~~~~~~~~~~~ conat.minusCoNat is possibly not total due to recursive path conat.minusCoNat --> conat.minusCoNat-reg018a.idr:21:1:++reg018a.idr:21:1-42:+   |+21 | loopForever = minusCoNat infinity infinity+   | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ conat.loopForever is possibly not total due to: conat.minusCoNat-reg018b.idr:8:1:++reg018b.idr:8:1-28:+  |+8 | showB (I x) = "I" ++ showB x+  | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A.showB is possibly not total due to recursive path A.showB --> A.showB-reg018b.idr:11:1:++reg018b.idr:11:1-6:+   |+11 | Show B where show = showB+   | ~~~~~~ A.B implementation of Prelude.Show.Show is possibly not total due to: A.showB-reg018c.idr:21:1:++reg018c.idr:21:1-22:21:+   |+21 | inf (x :: xs) with (hdtl xs)+   | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ... CodataTest.inf is possibly not total due to: with block in CodataTest.inf-reg018d.idr:8:1:Main.pull is not total as there are missing cases-reg023.idr:7:5:When checking right hand side of bad with expected type++reg018d.idr:8:1-39:+  |+8 | pull {n=Z}   _      (x :: xs) = (x, xs)+  | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Main.pull is not total as there are missing cases++reg023.idr:7:7:+  |+7 | bad = Z+  |       ^+When checking right hand side of bad with expected type         f Nat  Type mismatch between         Nat (Type of 0) and         f Nat (Expected type)-reg028.idr:5:1:tbad.bad is possibly not total due to: with block in tbad.bad-reg028a.idr:17:14-19:++reg028.idr:5:1-9:+  |+5 | bad Z = Z+  | ~~~~~~~~~+tbad.bad is possibly not total due to: with block in tbad.bad++reg028a.idr:17:14-18:+   |+17 | qsortLemma = proof+   |              ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.-reg028a.idr:11:1:++reg028a.idr:11:1-14:+   |+11 | qsort' [] = []+   | ~~~~~~~~~~~~~~ tbad.qsort' is possibly not total due to: with block in tbad.qsort'-reg034.idr:6:5:When checking left hand side of bar:++reg034.idr:6:1-14:+  |+6 | bar xs xs Refl = Refl+  | ~~~~~~~~~~~~~~+When checking left hand side of bar: Can't match on bar xs xs Refl-reg034.idr:9:5:When checking left hand side of foo:++reg034.idr:9:1-14:+  |+9 | foo f x x Refl = Refl+  | ~~~~~~~~~~~~~~+When checking left hand side of foo: Can't match on foo f x x Refl-reg035b.idr:8:6:No such variable __pi_arg-reg044.idr:4:6-11:++reg035b.idr:8:14-38:+  |+8 | fins Z     = ([] ** (finZEmpty {a=_}))+  |              ~~~~~~~~~~~~~~~~~~~~~~~~~+No such variable __pi_arg++reg044.idr:4:6-10:+  |+4 | pf = proof+  |      ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.-reg044.idr:4:4:When checking right hand side of Main.pf with expected type++reg044.idr:4:6-6:13:+  |+4 | pf = proof+  |      ~~~~~ ...+When checking right hand side of Main.pf with expected type         (b : Nat) -> (a : Nat) -> (S a = S b) -> a = b  Type mismatch between@@ -66,73 +165,166 @@                 b         and                 a-reg049.idr:2:9:When checking constructor Main.Bogus:++reg049.idr:2:11-14:+  |+2 |   Bogus : Void+  |           ~~~~+When checking constructor Main.Bogus: Void is not Main.Foo-reg049.idr:5:6:When checking right hand side of uhOh with expected type++reg049.idr:5:8-12:+  |+5 | uhOh = Bogus+  |        ~~~~~+When checking right hand side of uhOh with expected type         Void  No such variable Bogus-./badbangop.idr:7:1: error: ! is-    not a valid-    operator, expected: space-(!) : List a -> Nat -> Maybe a -^                              -./baddoublebang.idr:6:28: error: unexpected-    Operator without known fixity:-    !!, expected: space-doubleBang mmn = do pure !!mmn -                           ^   -reg054.idr:18:5:When checking left hand side of inf:++badbangop.idr:7:1:+  |+7 | (!) : List a -> Nat -> Maybe a+  | ^+! is not a valid operator++baddoublebang.idr:6:28:+  |+6 | doubleBang mmn = do pure !!mmn+  |                            ^+unexpected Operator without known fixity: !!++reg054.idr:18:1-17:+   |+18 | inf (MkInfer _ Z) = True+   | ~~~~~~~~~~~~~~~~~+When checking left hand side of inf: When checking an application of constructor Main.MkInfer:         Attempting concrete match on polymorphic argument: 0-reg054.idr:34:7:When checking left hand side of weird:++reg054.idr:34:1-18:+   |+34 | weird {x = Char} y = '5'+   | ~~~~~~~~~~~~~~~~~~+When checking left hand side of weird: No explicit types on left hand side: Char-reg054.idr:37:8:When checking left hand side of weird':++reg054.idr:37:1-30:+   |+37 | weird' {x = Prelude.Nat.Nat} y = Z+   | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+When checking left hand side of weird': No explicit types on left hand side: Nat-reg054.idr:40:1-8:When checking left hand side of tctrick:++reg054.idr:40:1-7:+   |+40 | tctrick (Just x) = x+   | ~~~~~~~+When checking left hand side of tctrick: When checking an application of Main.tctrick:         Type mismatch between                 Maybe a1 (Type of Just x)         and                 a (Expected type)-reg055.idr:5:3:When checking left hand side of g:++reg055.idr:5:1-7:+  |+5 | g (f Z) = 1    +  | ~~~~~~~+When checking left hand side of g: Can't match on g (f 0)-reg055.idr:8:3:When checking left hand side of h:++reg055.idr:8:1-5:+  |+8 | h x x = x+  | ~~~~~+When checking left hand side of h: Can't match on h x x-reg055a.idr:8:5:When checking left hand side of foo:++reg055a.idr:8:1-18:+  |+8 | foo (CAny Nothing) = 42 +  | ~~~~~~~~~~~~~~~~~~+When checking left hand side of foo: When checking an application of constructor Foo.CAny:         Attempting concrete match on polymorphic argument: Nothing-reg055a.idr:13:7:When checking left hand side of Foo.apply:++reg055a.idr:13:1-23:+   |+13 | apply (\x => \y => x) a = a+   | ~~~~~~~~~~~~~~~~~~~~~~~+When checking left hand side of Foo.apply: Can't match on apply (\x, y => x) a-reg056.idr:7:7:dodgy n m Refl is a valid case-reg056.idr:10:6:nonk Refl is a valid case-reg068.idr:1:6:Main.nat has a name which may be implicitly bound.++reg056.idr:7:16-25:+  |+7 | dodgy n m Refl impossible+  |                ~~~~~~~~~~+dodgy n m Refl is a valid case++reg056.idr:10:11-20:+   |+10 | nonk Refl impossible+   |           ~~~~~~~~~~+nonk Refl is a valid case++reg068.idr:1:6-8:+  |+1 | data nat : Type where --error+  |      ~~~+Main.nat has a name which may be implicitly bound. This is likely to lead to problems!-reg068.idr:2:6:Main.ze has a name which may be implicitly bound.++reg068.idr:2:8-10:+  |+2 |   ze : nat --hello.idr:10:6:When checking constructor Main.ze: !!V 0!! is not Main.nat+  |        ~~~+Main.ze has a name which may be implicitly bound. This is likely to lead to problems!-reg068.idr:2:8-11:++reg068.idr:2:8-10:+  |+2 |   ze : nat --hello.idr:10:6:When checking constructor Main.ze: !!V 0!! is not Main.nat+  |        ~~~ nat is bound as an implicit 	Did you mean to refer to Main.nat?-reg068.idr:2:6:When checking constructor Main.ze:++reg068.idr:2:8-10:+  |+2 |   ze : nat --hello.idr:10:6:When checking constructor Main.ze: !!V 0!! is not Main.nat+  |        ~~~+When checking constructor Main.ze: Type level variable nat is not Main.nat-Mod.idr:11:1:public export Mod.natexp can't refer to export Mod.natfn-reg070.idr:7:1:++Mod.idr:11:1-22:+   |+11 | natexp k = S (natfn k)+   | ~~~~~~~~~~~~~~~~~~~~~~+public export Mod.natexp can't refer to export Mod.natfn++reg070.idr:7:1-7:+  |+7 | Show Te where+  | ~~~~~~~ Test_show.Te implementation of Prelude.Show.Show is possibly not total due to: Prelude.Show.Test_show.Te implementation of Prelude.Show.Show, method show-./reg076.idr:8:1: error: Missing-    fixity declaration for-    Main.:>, expected: "->", "=>",-    ambiguous use of a left-associative operator,-    ambiguous use of a non-associative operator,-    ambiguous use of a right-associative operator-<EOF> -^     -./reg077.idr:3:1: error: Missing-    fixity declaration for-    Main.:>>, expected: ")", ";",-    "in", start of block-<EOF> -^     -DoubleEquality.idr:4:87:When checking right hand side of oops with expected type++reg076.idr:8:1:+  |+8 | <end of file>+  | ^+Missing fixity declaration for Main.:>++reg077.idr:3:1:+  |+3 | <end of file>+  | ^+Missing fixity declaration for Main.:>>++DoubleEquality.idr:4:83-103:+  |+4 | oops = the ((False = True) -> Void) (\Refl impossible) $ cong {f = (>0) . (1/)} $ the (-0.0 = 0.0) Refl+  |                                                                                   ~~~~~~~~~~~~~~~~~~~~~+When checking right hand side of oops with expected type         Void  When checking argument value to function Prelude.Basics.the:@@ -146,5 +338,16 @@                         -0.0                 and                         0.0-Canonicity.idr:9:1:Canonicity.f is not total as there are missing cases-Canonicity.idr:12:1:Canonicity.NaN is possibly not total due to: Canonicity.f++Canonicity.idr:9:1-9:+  |+9 | f Nil = 0+  | ~~~~~~~~~+Canonicity.f is not total as there are missing cases++Canonicity.idr:12:1-20:+   |+12 | NaN = f (Cons 0 Nil)+   | ~~~~~~~~~~~~~~~~~~~~+Canonicity.NaN is possibly not total due to: Canonicity.f+
test/sourceLocation001/expected view
@@ -1,19 +1,35 @@-SourceLoc.idr:12:19-26:+SourceLoc.idr:12:19-25:+   |+12 | getLoc : {default tactics { sourceLocation } x : SourceLocation} -> SourceLocation+   |                   ~~~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.-SourceLoc.idr:21:19-24:++SourceLoc.idr:21:19-23:+   |+21 | fromProofScript = proof sourceLocation+   |                   ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.-SourceLoc.idr:41:20-27:++SourceLoc.idr:41:20-26:+   |+41 |     Die : {default tactics { sourceLocation } loc : SourceLocation} -> Tm ctxt t+   |                    ~~~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.-SourceLoc.idr:99:18-23:++SourceLoc.idr:99:18-22:+   |+99 | SourceLoc.meta = proof+   |                  ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.+ Testing using definition-FileLoc "SourceLoc.idr" (17, 11) (17, 17)+FileLoc "SourceLoc.idr" (17, 11) (17, 16) Testing using inline tactics-FileLoc "SourceLoc.idr" (21, 17) (21, 17)+FileLoc "SourceLoc.idr" (21, 19) (21, 38) Testing using metavariable with later definition-FileLoc "SourceLoc.idr" (99, 16) (99, 16)+FileLoc "SourceLoc.idr" (99, 18) (100, 16) ----------------------- Success!-Error at FileLoc "SourceLoc.idr" (73, 23) (73, 26)+Error at FileLoc "SourceLoc.idr" (73, 23) (73, 25) Success! Success!
+ test/st001/expected view
@@ -0,0 +1,8 @@+# test001:+--test IO:+["HELLO!!\n", "WORLD!!"]+2+--test IOExcept:+["HELLO!!\n", "WORLD!!"]+2+()
+ test/st001/run view
@@ -0,0 +1,6 @@+#!/usr/bin/env bash+${IDRIS:-idris} $@ -p contrib test001.idr -o test001+echo "# test001:"+./test001+rm -f test001 *.ibc+
+ test/st001/test001.idr view
@@ -0,0 +1,66 @@+module Main ++import Control.IOExcept+import Control.ST+import Control.ST.File+import Control.ST.ImplicitCall++increment : (x : Var) -> STrans m () [ x ::: State Int ]+                                     (const [x ::: State Int])+increment x = do num <- read x+                 write x (num + 1)++readFileCount : (ConsoleIO m, File m) => +                   (fileHandle : Var) +                -> (count : Var)+                -> {auto prf   : ValidModeRead mode} +                -> ST m (Either FileError (List String)) +                      [ count      ::: (State Int), +                        fileHandle ::: FileHandleI {m} mode ]+readFileCount fh cnt = +     readAcc fh cnt []  +     where+          readAcc : (ConsoleIO m, File m) => +                       (fileHandle : Var) +                    -> (count : Var)+                    -> List String +                    -> {auto prf   : ValidModeRead mode} +                    -> ST m (Either FileError (List String)) +                          [ count      ::: (State Int), +                            fileHandle ::: FileHandleI {m} mode ]+          readAcc fileHandle cnt acc = with ST do +            e <- (eof fileHandle)+            if (not e) +               then do Right str <- (readLine fileHandle)+                             | Left ferr => pure (Left ferr)+                       (increment cnt) +                       readAcc fileHandle cnt (str :: acc)+               else do let rev = reverse acc+                       pure (Right rev)++testFile : (ConsoleIO m, File m) => ST m () []+testFile = with ST do +              Right fileHandle <- open "testFile" Read +                    | Left ferr => do putStrLn (show ferr)+                                      pure ()+              count <- new 0+              Right fContents <- readFileCount fileHandle count +                    | Left ferr => do putStrLn (show ferr)+                                      delete count+                                      close fileHandle+                                      pure ()+              putStrLn (show fContents) +              putStrLn (show !(read count))+              delete count+              close fileHandle+              pure ()++main : IO ()+main = do putStrLn "--test IO:" +          run testFile+          putStrLn "--test IOExcept:" +          ioe_run (run testFile)+                  (\err => putStrLn err) +                  (\ok  => printLn ok)++-- EOF -------------------------------------------------------------------------
+ test/st001/testFile view
@@ -0,0 +1,2 @@+HELLO!!+WORLD!!
+ test/st002/expected view
@@ -0,0 +1,8 @@+# test002:+--test IO:+['H', 'E', 'L', 'L', 'O', '!', '!', '\n', 'W', 'O', 'R', 'L', 'D', '!', '!', '\NUL']+16+--test IOExcept:+['H', 'E', 'L', 'L', 'O', '!', '!', '\n', 'W', 'O', 'R', 'L', 'D', '!', '!', '\NUL']+16+()
+ test/st002/run view
@@ -0,0 +1,6 @@+#!/usr/bin/env bash+${IDRIS:-idris} $@ -p contrib test002.idr -o test002+echo "# test002:"+./test002+rm -f test002 *.ibc+
+ test/st002/test002.idr view
@@ -0,0 +1,66 @@+module Main ++import Control.IOExcept+import Control.ST+import Control.ST.File+import Control.ST.ImplicitCall++increment : (x : Var) -> STrans m () [ x ::: State Int ]+                                     (const [x ::: State Int])+increment x = do num <- read x+                 write x (num + 1)++readFileCount : (ConsoleIO m, File m) => +                   (fileHandle : Var) +                -> (count : Var)+                -> {auto prf   : ValidModeRead mode} +                -> ST m (Either FileError (List Char)) +                      [ count      ::: (State Int), +                        fileHandle ::: FileHandleI {m} mode ]+readFileCount fh cnt = +     readAcc fh cnt []  +     where+          readAcc : (ConsoleIO m, File m) => +                       (fileHandle : Var) +                    -> (count : Var)+                    -> List Char +                    -> {auto prf   : ValidModeRead mode} +                    -> ST m (Either FileError (List Char)) +                          [ count      ::: (State Int), +                            fileHandle ::: FileHandleI {m} mode ]+          readAcc fileHandle cnt acc = with ST do +            e <- (eof fileHandle)+            if (not e) +               then do Right chr <- (readChar fileHandle)+                             | Left ferr => pure (Left ferr)+                       (increment cnt) +                       readAcc fileHandle cnt (chr :: acc)+               else do let rev = reverse acc+                       pure (Right rev)++testFile : (ConsoleIO m, File m) => ST m () []+testFile = with ST do+              Right fileHandle <- open "testFile" Read +                    | Left ferr => do putStrLn (show ferr)+                                      pure ()+              count <- new 0+              Right fContents <- readFileCount fileHandle count +                    | Left ferr => do putStrLn (show ferr)+                                      delete count+                                      close fileHandle+                                      pure ()+              putStrLn (show fContents) +              putStrLn (show !(read count))+              delete count+              close fileHandle+              pure ()+               +main : IO ()+main = do putStrLn "--test IO:" +          run testFile+          putStrLn "--test IOExcept:" +          ioe_run (run testFile)+                  (\err => putStrLn err) +                  (\ok  => printLn ok)++-- EOF -------------------------------------------------------------------------
+ test/st002/testFile view
@@ -0,0 +1,2 @@+HELLO!!+WORLD!!
+ test/st003/expected view
@@ -0,0 +1,8 @@+# test003:+--test IO:+HELLO!!+WORLD!!+--test IOExcept:+HELLO!!+WORLD!!+()
+ test/st003/run view
@@ -0,0 +1,6 @@+#!/usr/bin/env bash+${IDRIS:-idris} $@ -p contrib test003.idr -o test003+echo "# test003:"+./test003+rm -f test003 *.ibc+
+ test/st003/test003.idr view
@@ -0,0 +1,25 @@+module Main ++import Control.IOExcept+import Control.ST+import Control.ST.File+import Control.ST.ImplicitCall++testFile : (ConsoleIO m, File m) => ST m () []+testFile = with ST do+              Right str <- readFile "testFile" +                  | Left ferr => do putStrLn (show ferr)+                                    pure ()+              putStrLn str +              pure ()+++main : IO ()+main = do putStrLn "--test IO:" +          run testFile+          putStrLn "--test IOExcept:" +          ioe_run (run testFile)+                  (\err => putStrLn err) +                  (\ok  => printLn ok)++-- EOF -------------------------------------------------------------------------
+ test/st003/testFile view
@@ -0,0 +1,2 @@+HELLO!!+WORLD!!
+ test/st004/expected view
@@ -0,0 +1,6 @@+# test004:+--test IO:+File Not Found+--test IOExcept:+File Not Found+()
+ test/st004/run view
@@ -0,0 +1,6 @@+#!/usr/bin/env bash+${IDRIS:-idris} $@ -p contrib test004.idr -o test004+echo "# test004:"+./test004+rm -f test004 *.ibc+
+ test/st004/test004.idr view
@@ -0,0 +1,24 @@+module Main ++import Control.IOExcept+import Control.ST+import Control.ST.File+import Control.ST.ImplicitCall++testFile : (ConsoleIO m, File m) => ST m () []+testFile = with ST do +              Right str <- readFile "noneexistingtestFile" +                  | Left ferr => do putStrLn (show ferr)+                                    pure ()+              putStr str +              pure ()++main : IO ()+main = do putStrLn "--test IO:" +          run testFile+          putStrLn "--test IOExcept:" +          ioe_run (run testFile)+                  (\err => putStrLn err) +                  (\ok  => printLn ok)++-- EOF -------------------------------------------------------------------------
+ test/st005/expected view
@@ -0,0 +1,6 @@+# test005:+--test IO:+--test IOExcept:+()+HELLO!!+WORLD!!
+ test/st005/run view
@@ -0,0 +1,7 @@+#!/usr/bin/env bash+${IDRIS:-idris} $@ -p contrib test005.idr -o test005+echo "# test005:"+./test005+cat writeTestFile+rm -f test005 writeTestFile *.ibc+
+ test/st005/test005.idr view
@@ -0,0 +1,33 @@+module Main ++import Control.IOExcept+import Control.ST+import Control.ST.File+import Control.ST.ImplicitCall++testFile : (ConsoleIO m, File m) => ST m () []+testFile = with ST do+              Right fileHandle <- open "writeTestFile" WriteTruncate+                    | Left ferr =>  do putStrLn (show ferr)+                                       pure ()+              Right _ <- writeLine fileHandle "HELLO!!"+                    | Left ferr =>  do putStrLn (show ferr)+                                       close fileHandle+                                       pure ()+              Right _ <- writeLine fileHandle "WORLD!!"+                    | Left ferr =>  do putStrLn (show ferr)+                                       close fileHandle+                                       pure ()+              close fileHandle+              pure ()+               ++main : IO ()+main = do putStrLn "--test IO:" +          run testFile+          putStrLn "--test IOExcept:" +          ioe_run (run testFile)+                  (\err => putStrLn err) +                  (\ok  => printLn ok)++-- EOF -------------------------------------------------------------------------
+ test/st006/expected view
@@ -0,0 +1,5 @@+# test006:+--test IO:+--test IOExcept:+()+HELLO!!WORLD!!
+ test/st006/run view
@@ -0,0 +1,6 @@+#!/usr/bin/env bash+${IDRIS:-idris} $@ -p contrib test006.idr -o test006+echo "# test006:"+./test006+cat writeStringTestFile+rm -f test006 writeStringTestFile *.ibc
+ test/st006/test006.idr view
@@ -0,0 +1,37 @@+module Main ++import Control.IOExcept+import Control.ST+import Control.ST.File+import Control.ST.ImplicitCall++testFile : (ConsoleIO m, File m) => ST m () []+testFile = with ST do +              Right fileHandle <- open "writeStringTestFile" WriteTruncate+                    | Left ferr =>  do putStrLn (show ferr)+                                       pure ()+              Right _ <- writeString fileHandle "HELLO!!"+                    | Left ferr =>  do putStrLn (show ferr)+                                       close fileHandle+                                       pure ()+              Right _ <- writeString fileHandle "WORLD!!"+                    | Left ferr =>  do putStrLn (show ferr)+                                       close fileHandle+                                       pure ()+              Right _ <- writeString fileHandle "\n"+                    | Left ferr =>  do putStrLn (show ferr)+                                       close fileHandle+                                       pure ()+              close fileHandle+              pure ()+               ++main : IO ()+main = do putStrLn "--test IO:" +          run testFile+          putStrLn "--test IOExcept:" +          ioe_run (run testFile)+                  (\err => putStrLn err) +                  (\ok  => printLn ok)++-- EOF -------------------------------------------------------------------------
+ test/st007/expected view
@@ -0,0 +1,6 @@+# test007:+--test IO:+--test IOExcept:+()+HELLO!!+WORLD!!
+ test/st007/run view
@@ -0,0 +1,6 @@+#!/usr/bin/env bash+${IDRIS:-idris} $@ -p contrib test007.idr -o test007+echo "# test007:"+./test007+cat writeFileTestFile+rm -f test007 writeFileTestFile *.ibc
+ test/st007/test007.idr view
@@ -0,0 +1,24 @@+module Main ++import Control.IOExcept+import Control.ST+import Control.ST.File+import Control.ST.ImplicitCall++testFile : (ConsoleIO m, File m) => ST m () []+testFile = with ST do +              Right _ <- writeFile "writeFileTestFile" "HELLO!!\nWORLD!!\n" +                  | Left ferr => do putStrLn (show ferr)+                                    pure ()+              pure ()+++main : IO ()+main = do putStrLn "--test IO:" +          run testFile+          putStrLn "--test IOExcept:" +          ioe_run (run testFile)+                  (\err => putStrLn err) +                  (\ok  => printLn ok)++-- EOF -------------------------------------------------------------------------
test/sugar004/expected view
@@ -1,3 +1,4 @@ No arguments!+Not an integer! 42 Too many arguments!
test/sugar004/run view
@@ -1,6 +1,7 @@ #!/usr/bin/env bash ${IDRIS:-idris} $@ sugar004.idr -o sugar004 ./sugar004+./sugar004 foo ./sugar004 42 ./sugar004 42 100 rm -f sugar004 *.ibc
test/sugar004/sugar004.idr view
@@ -1,5 +1,6 @@ module Main +import Data.String import System  total@@ -9,7 +10,8 @@ main : IO () main = do [p, a] <- getArgs | [p] => putStrLn "No arguments!"                             | (x :: y :: _) => putStrLn "Too many arguments!"-          printLn (foo (Just (cast a)))+          let Just a' = parseInteger {a = Int} a | Nothing => putStrLn "Not an integer!"+          printLn (foo (Just a'))  {- @@ -28,6 +30,15 @@  do x <- val    case x of+        pat => p+        <alternatives>++do let pat = val | <alternatives>+   p++...becomes...++do case val of         pat => p         <alternatives> 
test/syntax001/expected view
@@ -1,4 +1,8 @@-Syntax.idr:6:7-9:1:When checking right hand side of foo with expected type+Syntax.idr:6:7-18:+  |+6 | foo = fnord "argh"+  |       ~~~~~~~~~~~~+When checking right hand side of foo with expected type         Nat  When checking an application of function Prelude.Interfaces.+:@@ -6,7 +10,12 @@                 String (Type of "argh")         and                 Nat (Expected type)-SyntaxTest.idr:5:7-6:1:When checking right hand side of foo with expected type++SyntaxTest.idr:5:7-18:+  |+5 | foo = fnord "argh"+  |       ~~~~~~~~~~~~+When checking right hand side of foo with expected type         Nat  When checking an application of function Prelude.Interfaces.+:@@ -14,3 +23,4 @@                 String (Type of "argh")         and                 Nat (Expected type)+
test/totality001/expected view
@@ -1,3 +1,18 @@-test010.idr:15:1:Main.foo is possibly not total due to: Main.MkBad-test010a.idr:9:1:main.bar is possibly not total due to: main.MkBad-test010b.idr:9:1:main.bar is possibly not total due to: main.MkBad+test010.idr:15:1-30:+   |+15 | foo (MkBad f i) = f (MkBad' i)+   | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Main.foo is possibly not total due to: Main.MkBad++test010a.idr:9:1-23:+  |+9 | bar = MkBad (\x => 3) 3+  | ~~~~~~~~~~~~~~~~~~~~~~~+main.bar is possibly not total due to: main.MkBad++test010b.idr:9:1-23:+  |+9 | bar = MkBad (\x => 3) 3+  | ~~~~~~~~~~~~~~~~~~~~~~~+main.bar is possibly not total due to: main.MkBad+
test/totality002/expected view
@@ -1,5 +1,18 @@-test017.idr:94:26-31:+test017.idr:94:26-30:+   |+94 | maxCommutativeStepCase = proof {+   |                          ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.-test017a.idr:7:1:++test017a.idr:7:1-24:+  |+7 | vtrans [] _         = []+  | ~~~~~~~~~~~~~~~~~~~~~~~~ scg.vtrans is possibly not total due to recursive path scg.vtrans --> scg.vtrans-test017b.idr:4:1:foo.foo is possibly not total due to recursive path foo.foo++test017b.idr:4:1-9:+  |+4 | foo = foo+  | ~~~~~~~~~+foo.foo is possibly not total due to recursive path foo.foo+
test/totality003/expected view
@@ -1,2 +1,6 @@-totality003a.idr:5:1:+totality003a.idr:5:1-13:+  |+5 | qsort [] = []+  | ~~~~~~~~~~~~~ smaller.qsort is possibly not total due to recursive path smaller.qsort --> smaller.qsort --> smaller.qsort+
test/totality004/expected view
@@ -1,4 +1,13 @@ [1, 2, 2, 4, 3, 6, 4, 8, 5, 10]-totality004a.idr:13:1:+totality004a.idr:13:1-44:+   |+13 | process (Get f) (x :: xs) = process (f x) xs+   | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Main.process is possibly not total due to recursive path Main.process --> Main.process --> Main.process-totality004a.idr:24:1:Main.main is possibly not total due to: Main.process++totality004a.idr:24:1-60:+   |+24 | main = printLn (take 10 (process doubleInt (countStream 1)))+   | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Main.main is possibly not total due to: Main.process+
test/totality006/expected view
@@ -1,4 +1,18 @@-totality006.idr:8:1:Main.prf is not total as there are missing cases-totality006a.idr:11:6:prf' (S _) (S _) Oh is a valid case-totality006b.idr:10:1:+totality006.idr:8:1-29:+  |+8 | prf Z     Z     Oh impossible+  | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Main.prf is not total as there are missing cases++totality006a.idr:11:21-30:+   |+11 | prf' (S _) (S _) Oh impossible+   |                     ~~~~~~~~~~+prf' (S _) (S _) Oh is a valid case++totality006b.idr:10:1-34:+   |+10 | blargh [] (y :: xs) so = absurd so+   | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ totality006b.blargh is not total as there are missing cases+
test/totality007/expected view
@@ -1,5 +1,9 @@ Entering directory `./src'-Totality.idr:4:1:+Totality.idr:4:1-9:+  |+4 | foo Z = Z+  | ~~~~~~~~~ Totality.foo is not total as there are missing cases-Totality.idr:4:1:Could not build: Totality.foo is not total as there are missing cases++Totality.idr:4:1-9:Could not build: Totality.foo is not total as there are missing cases Leaving directory `./src'
test/totality008/expected view
@@ -1,1 +1,6 @@-totality008.idr:7:1:Main.ElimT is possibly not total due to: Main.C2+totality008.idr:7:1-14:+  |+7 | ElimT _ C1 = 3+  | ~~~~~~~~~~~~~~+Main.ElimT is possibly not total due to: Main.C2+
test/totality009/expected view
@@ -1,10 +1,60 @@-TestLambdaPossible.idr:9:25:Warning - TestLambdaPossible.case block in wrongPossible at TestLambdaPossible.idr:9:25 is not total as there are missing cases-TestLambdaPossible.idr:9:1:Warning - TestLambdaPossible.wrongPossible is possibly not total due to: TestLambdaPossible.case block in wrongPossible at TestLambdaPossible.idr:9:25-TestLambdaPossible.idr:12:25:Warning - TestLambdaPossible.case block in wrongPossible' at TestLambdaPossible.idr:12:25 is not total as there are missing cases-TestLambdaPossible.idr:12:1:Warning - TestLambdaPossible.wrongPossible' is possibly not total due to: TestLambdaPossible.case block in wrongPossible' at TestLambdaPossible.idr:12:25-TestLambdaPossible.idr:9:15:Warning - TestLambdaPossible.case block in wrongPossible at TestLambdaPossible.idr:9:25 is not total as there are missing cases-TestLambdaPossible.idr:9:1:Warning - TestLambdaPossible.wrongPossible is possibly not total due to: TestLambdaPossible.case block in wrongPossible at TestLambdaPossible.idr:9:25-TestLambdaPossible.idr:12:16:Warning - TestLambdaPossible.case block in wrongPossible' at TestLambdaPossible.idr:12:25 is not total as there are missing cases-TestLambdaPossible.idr:12:1:Warning - TestLambdaPossible.wrongPossible' is possibly not total due to: TestLambdaPossible.case block in wrongPossible' at TestLambdaPossible.idr:12:25-TestLambdaPossible2.idr:10:1:TestLambdaPossible.wrongPossible is possibly not total due to: TestLambdaPossible.case block in wrongPossible at TestLambdaPossible2.idr:10:25-TestLambdaPossible2.idr:14:1:TestLambdaPossible.wrongPossible' is possibly not total due to: TestLambdaPossible.case block in wrongPossible' at TestLambdaPossible2.idr:14:25+TestLambdaPossible.idr:9:25-34:+  |+9 | wrongPossible = (\Flase impossible)+  |                         ~~~~~~~~~~+Warning - TestLambdaPossible.case block in wrongPossible at TestLambdaPossible.idr:9:25-34 is not total as there are missing cases++TestLambdaPossible.idr:9:1-35:+  |+9 | wrongPossible = (\Flase impossible)+  | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Warning - TestLambdaPossible.wrongPossible is possibly not total due to: TestLambdaPossible.case block in wrongPossible at TestLambdaPossible.idr:9:25-34++TestLambdaPossible.idr:12:25:+   |+12 | wrongPossible' x = case x of+   |                         ^+Warning - TestLambdaPossible.case block in wrongPossible' at TestLambdaPossible.idr:12:25 is not total as there are missing cases++TestLambdaPossible.idr:12:1-13:40:+   |+12 | wrongPossible' x = case x of+   | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ...+Warning - TestLambdaPossible.wrongPossible' is possibly not total due to: TestLambdaPossible.case block in wrongPossible' at TestLambdaPossible.idr:12:25++TestLambdaPossible.idr:9:17-35:+  |+9 | wrongPossible = (\Flase impossible)+  |                 ~~~~~~~~~~~~~~~~~~~+Warning - TestLambdaPossible.case block in wrongPossible at TestLambdaPossible.idr:9:25-34 is not total as there are missing cases++TestLambdaPossible.idr:9:1-35:+  |+9 | wrongPossible = (\Flase impossible)+  | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Warning - TestLambdaPossible.wrongPossible is possibly not total due to: TestLambdaPossible.case block in wrongPossible at TestLambdaPossible.idr:9:25-34++TestLambdaPossible.idr:12:20-13:40:+   |+12 | wrongPossible' x = case x of+   |                    ~~~~~~~~~ ...+Warning - TestLambdaPossible.case block in wrongPossible' at TestLambdaPossible.idr:12:25 is not total as there are missing cases++TestLambdaPossible.idr:12:1-13:40:+   |+12 | wrongPossible' x = case x of+   | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ...+Warning - TestLambdaPossible.wrongPossible' is possibly not total due to: TestLambdaPossible.case block in wrongPossible' at TestLambdaPossible.idr:12:25++TestLambdaPossible2.idr:10:1-35:+   |+10 | wrongPossible = (\Flase impossible)+   | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+TestLambdaPossible.wrongPossible is possibly not total due to: TestLambdaPossible.case block in wrongPossible at TestLambdaPossible2.idr:10:25-34++TestLambdaPossible2.idr:14:1-15:40:+   |+14 | wrongPossible' x = case x of+   | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ...+TestLambdaPossible.wrongPossible' is possibly not total due to: TestLambdaPossible.case block in wrongPossible' at TestLambdaPossible2.idr:14:25+
test/totality010/expected view
@@ -1,2 +1,12 @@-totality010.idr:27:1:Main.evenNotS is not total as there are missing cases-totality010.idr:30:1:Main.bad is possibly not total due to: Main.evenNotS+totality010.idr:27:1-35:+   |+27 | evenNotS MkEven ZeroEven impossible+   | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Main.evenNotS is not total as there are missing cases++totality010.idr:30:1-40:+   |+30 | bad = evenNotS ZeroEven $ MkBad ZeroEven+   | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Main.bad is possibly not total due to: Main.evenNotS+
test/totality011/expected view
@@ -1,2 +1,6 @@-totality011.lidr:22:3:+totality011.lidr:22:3-57:+   |+22 | > weCanOnlyGetOlder {t'' = Z} {t = Z}   _ _ _  =  LTEZero+   |   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Main.weCanOnlyGetOlder is not total as there are missing cases+
test/totality012/expected view
@@ -1,4 +1,12 @@-totality012a.idr:9:1:+totality012a.idr:9:1-10:27:+  |+9 | echo2 x = if (x == "quit") then PutStr "Bye!\n"+  | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ... Main.echo2 is possibly not total due to recursive path Main.echo2 --> Main.echo2-totality012b.idr:11:1:++totality012b.idr:11:1-17:33:+   |+11 | echo = do PutStr "$ "+   | ~~~~~~~~~~~~~~~~~~~~~ ... Main.echo is possibly not total due to recursive path Main.echo+
test/totality013/expected view
@@ -1,3 +1,12 @@-totality013a.idr:5:3:+totality013a.idr:5:3-49:+  |+5 |   foo order x xs y ys _ = mtot order (x :: xs) ys+  |   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Main.foo is possibly not total due to recursive path Main.foo --> Main.mtot --> Main.mtot --> Main.mtot-totality013a.idr:9:3:Main.mtot is possibly not total due to: Main.foo++totality013a.idr:9:3-36:+  |+9 |   mtot order []      right   = right+  |   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Main.mtot is possibly not total due to: Main.foo+
test/totality014/expected view
@@ -1,8 +1,13 @@-totality014.idr:1:6:Universe inconsistency.+totality014.idr:1:6-9:+  |+1 | data Con2 : Type where+  |      ~~~~+Universe inconsistency.         Working on: ./totality014.idr.w         Old domain: (5,5)         New domain: (5,4)         Involved constraints: -                ConstraintFC {uconstraint = ./totality014.idr.w < ./totality014.idr.u, ufc = totality014.idr:1:6}-                ConstraintFC {uconstraint = ./totality014.idr.w < ./totality014.idr.u, ufc = totality014.idr:1:6}-                ConstraintFC {uconstraint = ./totality014.idr.u <= ./totality014.idr.w, ufc = totality014.idr:6:9}+                ConstraintFC {uconstraint = ./totality014.idr.w < ./totality014.idr.u, ufc = totality014.idr:1:6-9}+                ConstraintFC {uconstraint = ./totality014.idr.w < ./totality014.idr.u, ufc = totality014.idr:1:6-9}+                ConstraintFC {uconstraint = ./totality014.idr.u <= ./totality014.idr.w, ufc = totality014.idr:6:29}+
test/totality015/expected view
@@ -1,4 +1,18 @@-totality015a.idr:52:3:+totality015a.idr:52:3-53:+   |+52 |   quiz (num1 :: num2 :: nums) score = quiz nums score+   |   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Main.quiz is possibly not total due to recursive path Main.quiz --> Main.quiz-totality015a.idr:42:3:Main.correct is possibly not total due to: Main.quiz-totality015a.idr:47:3:Main.wrong is possibly not total due to: Main.quiz++totality015a.idr:42:3-44:36:+   |+42 |   correct nums score+   |   ~~~~~~~~~~~~~~~~~~ ...+Main.correct is possibly not total due to: Main.quiz++totality015a.idr:47:3-49:28:+   |+47 |   wrong nums ans score+   |   ~~~~~~~~~~~~~~~~~~~~ ...+Main.wrong is possibly not total due to: Main.quiz+
test/totality016/expected view
@@ -1,9 +1,54 @@-totality016.idr:15:1:Main.f1 is not total as there are missing cases-totality016.idr:19:1:Main.f2 is not total as there are missing cases-totality016.idr:23:1:Main.f3 is not total as there are missing cases-totality016.idr:27:1:Main.g1 is not total as there are missing cases-totality016.idr:31:1:Main.g2 is not total as there are missing cases-totality016.idr:35:1:Main.h1 is not total as there are missing cases-totality016.idr:39:1:Main.h2 is not total as there are missing cases-totality016.idr:43:1:Main.h3 is not total as there are missing cases-totality016.idr:47:1:Main.h4 is not total as there are missing cases+totality016.idr:15:1-21:+   |+15 | f1 (MkTP T1 x) = True+   | ~~~~~~~~~~~~~~~~~~~~~+Main.f1 is not total as there are missing cases++totality016.idr:19:1-24:+   |+19 | f2 (MkTP T1 x, _) = True+   | ~~~~~~~~~~~~~~~~~~~~~~~~+Main.f2 is not total as there are missing cases++totality016.idr:23:1-29:+   |+23 | f3 ((MkTP T1 x, _), _) = True+   | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Main.f3 is not total as there are missing cases++totality016.idr:27:1-14:+   |+27 | g1 T1 x = True+   | ~~~~~~~~~~~~~~+Main.g1 is not total as there are missing cases++totality016.idr:31:1-17:+   |+31 | g2 (T1, x) = True+   | ~~~~~~~~~~~~~~~~~+Main.g2 is not total as there are missing cases++totality016.idr:35:1-16:+   |+35 | h1 True x = True+   | ~~~~~~~~~~~~~~~~+Main.h1 is not total as there are missing cases++totality016.idr:39:1-19:+   |+39 | h2 (True, x) = True+   | ~~~~~~~~~~~~~~~~~~~+Main.h2 is not total as there are missing cases++totality016.idr:43:1-25:+   |+43 | h3 (MkTP2 (T1, x)) = True+   | ~~~~~~~~~~~~~~~~~~~~~~~~~+Main.h3 is not total as there are missing cases++totality016.idr:47:1-30:+   |+47 | h4 (MkTP2 (T1, x), _) _ = True+   | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Main.h4 is not total as there are missing cases+
test/totality017/expected view
@@ -1,6 +1,36 @@-totality017.idr:19:1:Main.g1 is not total as there are missing cases-totality017.idr:25:1:Main.g2 is not total as there are missing cases-totality017.idr:31:1:Main.g3 is not total as there are missing cases-totality017.idr:37:1:Main.g4 is not total as there are missing cases-totality017.idr:42:1:Main.f' is not total as there are missing cases-totality017.idr:47:1:Main.f is not total as there are missing cases+totality017.idr:19:1-15:+   |+19 | g1 T1 T1 = True+   | ~~~~~~~~~~~~~~~+Main.g1 is not total as there are missing cases++totality017.idr:25:1-17:+   |+25 | g2 T1' T1' = True+   | ~~~~~~~~~~~~~~~~~+Main.g2 is not total as there are missing cases++totality017.idr:31:1-13:+   |+31 | g3 T1' = True+   | ~~~~~~~~~~~~~+Main.g3 is not total as there are missing cases++totality017.idr:37:1-36:+   |+37 | g4 (MkTTPP (MkPP 0) (MkPP 0)) = True+   | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Main.g4 is not total as there are missing cases++totality017.idr:42:1-11:+   |+42 | f' 0 = True+   | ~~~~~~~~~~~+Main.f' is not total as there are missing cases++totality017.idr:47:1-17:+   |+47 | f (MkPP 0) = True+   | ~~~~~~~~~~~~~~~~~+Main.f is not total as there are missing cases+
test/totality018/expected view
@@ -1,1 +1,6 @@-totality018.idr:12:1:Main.bar is not total as there are missing cases+totality018.idr:12:1-10:+   |+12 | bar FZ = 0+   | ~~~~~~~~~~+Main.bar is not total as there are missing cases+
test/totality019/expected view
@@ -1,2 +1,12 @@-totality019.idr:8:1:Main.testCov is not total as there are missing cases-totality019.idr:12:1:Main.testCov' is not total as there are missing cases+totality019.idr:8:1-36:+  |+8 | testCov False False = ?testCov_rhs_3+  | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Main.testCov is not total as there are missing cases++totality019.idr:12:1-42:+   |+12 | testCov' (False ** False) = ?testCov_rhs_3+   | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Main.testCov' is not total as there are missing cases+
test/totality020/expected view
@@ -1,2 +1,12 @@-totality020.idr:4:5:bug _ _ Refl is a valid case-totality020.idr:7:5:foo a b Refl is a valid case+totality020.idr:4:14-23:+  |+4 | bug _ _ Refl impossible+  |              ~~~~~~~~~~+bug _ _ Refl is a valid case++totality020.idr:7:14-23:+  |+7 | foo a b Refl impossible+  |              ~~~~~~~~~~+foo a b Refl is a valid case+
test/totality021/expected view
@@ -1,9 +1,30 @@-totality021.idr:8:1:+totality021.idr:8:1-67:+  |+8 | sLevelNotSLevel' (SL (Delay level)) p = sLevelNotSLevel' level Refl+  | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Main.sLevelNotSLevel' is possibly not total due to recursive path Main.sLevelNotSLevel' --> Main.sLevelNotSLevel'-totality021.idr:12:1:++totality021.idr:12:1-66:+   |+12 | sLevelNotSLevel (SL (Delay level)) p = sLevelNotSLevel' level Refl+   | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Main.sLevelNotSLevel is possibly not total due to: Main.sLevelNotSLevel'-totality021.idr:18:1:Main.v is possibly not total due to: Main.sLevelNotSLevel-totality021a.idr:9:1:++totality021.idr:18:1-26:+   |+18 | v = sLevelNotSLevel l Refl+   | ~~~~~~~~~~~~~~~~~~~~~~~~~~+Main.v is possibly not total due to: Main.sLevelNotSLevel++totality021a.idr:9:1-37:+  |+9 | noNonEmptyPointInt {n} Nil impossible+  | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Main.noNonEmptyPointInt is not total as there are missing cases-totality021a.idr:12:1:++totality021a.idr:12:1-31:+   |+12 | myVoid = noNonEmptyPointInt [2]+   | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Main.myVoid is possibly not total due to: Main.noNonEmptyPointInt+
test/totality022/expected view
@@ -1,1 +1,6 @@-totality022.idr:7:3:f _ [] (RSnoc _ _) is a valid case+totality022.idr:7:20-29:+  |+7 | f _ [] (RSnoc _ _) impossible -- = ?wat+  |                    ~~~~~~~~~~+f _ [] (RSnoc _ _) is a valid case+
test/totality023/expected view
@@ -1,2 +1,6 @@-totality023.idr:9:1:+totality023.idr:9:1-10:27:+  |+9 | run (Do x f) = do r <- x+  | ~~~~~~~~~~~~~~~~~~~~~~~~ ... Main.run is possibly not total due to recursive path Main.run --> Main.run+
+ test/totality024/expected view
@@ -0,0 +1,1 @@+totality023.idr:5:3:Main.ana is possibly not total due to: Main.ana, go
+ test/totality024/run view
@@ -0,0 +1,3 @@+#!/usr/bin/env bash+${IDRIS:-idris} $@ totality023.idr --check+rm -f *.ibc
+ test/totality024/totality023.idr view
@@ -0,0 +1,7 @@+%default total++mutual+  ana : (a -> Maybe a) -> a -> Nat+  ana f = go . f+    where go Nothing  = Z+          go (Just x) = S $ ana f x
test/tutorial002/expected view
@@ -1,6 +1,18 @@-tutorial002.idr:41:25-30:+tutorial002.idr:41:25-29:+   |+41 | Main.natToBin_lemma_1 = proof+   |                         ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.-tutorial002.idr:48:18-23:++tutorial002.idr:48:18-22:+   |+48 | parity_lemma_1 = proof+   |                  ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.-tutorial002.idr:54:18-23:++tutorial002.idr:54:18-22:+   |+54 | parity_lemma_2 = proof {+   |                  ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.+
test/tutorial004/expected view
@@ -1,4 +1,12 @@-tutorial004.idr:46:14-19:+tutorial004.idr:46:14-18:+   |+46 | plusredZ_S = proof {+   |              ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.-tutorial004.idr:53:14-19:++tutorial004.idr:53:14-18:+   |+53 | plusredZ_Z = proof {+   |              ~~~~~ This style of tactic proof is deprecated. See %runElab for the replacement.+
test/tutorial006/expected view
@@ -1,4 +1,7 @@-tutorial006a.idr:5:23-25:+tutorial006a.idr:5:23-24:+  |+5 | vapp (x :: xs) ys = x :: vapp xs xs -- BROKEN+  |                       ~~ When checking right hand side of vapp with expected type         Vect (S len + m) a @@ -13,7 +16,11 @@                         plus len len                 and                         plus len m-tutorial006b.idr:10:10:++tutorial006b.idr:10:39-50:+   |+10 |   parity (S (S (j + j)))     | Even = Even {n=S j}+   |                                       ~~~~~~~~~~~~ When checking right hand side of with block in Main.parity with expected type         Parity (S (S (j + j))) @@ -27,3 +34,4 @@                 plus (S j) (S j)         and                 S (S (plus j j))+
test/unique004/expected view
@@ -1,26 +1,75 @@-unique001a.idr:35:11:Type mismatch between+unique001a.idr:35:16-43:50:+   |+35 | showStuff xs = do+   |                ~~ ...+Type mismatch between         Int -> String and         UniqueType (Int -> String)-unique001a.idr:46:12:Type mismatch between++unique001a.idr:46:17-54:28:+   |+46 | showStuff' xs = do+   |                 ~~ ...+Type mismatch between         Int -> String and         UniqueType (Int -> String)-unique001a.idr:57:12:Type mismatch between++unique001a.idr:57:17-62:33:+   |+57 | showThings xs = do+   |                 ~~ ...+Type mismatch between         UniqueType (Int -> String) and         Int -> String-unique001b.idr:18:7:Borrowed name xs must not be used on RHS-unique001c.idr:47:6:Unique name f is used more than once-unique001d.idr:4:7:Borrowed name x must not be used on RHS-unique001e.idr:4:10:++unique001b.idr:18:19-42:+   |+18 | showU (x :: xs) = show x ++ "," ++ free xs+   |                   ~~~~~~~~~~~~~~~~~~~~~~~~+Borrowed name xs must not be used on RHS++unique001c.idr:47:14-62:+   |+47 | ndup {a} x = (\f : Int -> a => MkUPair (f 0) (f 1)) (uconst x)+   |              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Unique name f is used more than once++unique001d.idr:4:18:+  |+4 | steal (Read x) = x+  |                  ^+Borrowed name x must not be used on RHS++unique001e.idr:4:12-40:+  |+4 |      Nil : {a : UniqueType} -> BadList a+  |            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Constructor Main.Nil has a UniqueType, but the data type does not-unique002.idr:17:5:Unique name xs is used more than once-unique002a.idr:17:5:Type mismatch between++unique002.idr:17:10-20:19:+   |+17 | foo xs = do -- let f = \x : Int => showU xs+   |          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ...+Unique name xs is used more than once++unique002a.idr:17:10-20:19:+   |+17 | foo xs = do let f = \x : Int => showU xs+   |          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ...+Type mismatch between         Int -> String and         UniqueType (Int -> String)-unique003.idr:20:5:Type mismatch between++unique003.idr:20:10-24:19:+   |+20 | foo xs = do let f = \x : Int => showU xs -- can't build this in unique context+   |          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ...+Type mismatch between         Int -> String and         UniqueType (Int -> String)+
test/universes001/expected view
@@ -1,9 +1,14 @@-universes001.idr:7:5:Universe inconsistency.+universes001.idr:7:7-21:+  |+7 | foo = Const (Const 0)+  |       ~~~~~~~~~~~~~~~+Universe inconsistency.         Working on: ./universes001.idr.x         Old domain: (5,5)         New domain: (5,4)         Involved constraints: -                ConstraintFC {uconstraint = ./universes001.idr.x <= ./universes001.idr.z, ufc = universes001.idr:7:5}-                ConstraintFC {uconstraint = ./universes001.idr.x < ./universes001.idr.y, ufc = universes001.idr:1:6}-                ConstraintFC {uconstraint = ./universes001.idr.z < ./universes001.idr.x, ufc = universes001.idr:1:6}-                ConstraintFC {uconstraint = ./universes001.idr.x <= ./universes001.idr.z, ufc = universes001.idr:7:5}+                ConstraintFC {uconstraint = ./universes001.idr.x <= ./universes001.idr.z, ufc = universes001.idr:7:7-21}+                ConstraintFC {uconstraint = ./universes001.idr.x < ./universes001.idr.y, ufc = universes001.idr:1:6-8}+                ConstraintFC {uconstraint = ./universes001.idr.z < ./universes001.idr.x, ufc = universes001.idr:1:6-8}+                ConstraintFC {uconstraint = ./universes001.idr.x <= ./universes001.idr.z, ufc = universes001.idr:7:7-21}+
test/universes002/expected view
@@ -1,9 +1,14 @@-universes002.idr:45:9:Universe inconsistency.+universes002.idr:45:11-48:+   |+45 | russell = lemma (MkMPair (MkMPair R lemma) REFL) +   |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Universe inconsistency.         Working on: ./universes002.idr.b1         Old domain: (5,5)         New domain: (5,4)         Involved constraints: -                ConstraintFC {uconstraint = ./universes002.idr.b1 <= ./universes002.idr.e7, ufc = universes002.idr:45:9}-                ConstraintFC {uconstraint = ./universes002.idr.b1 < ./universes002.idr.c1, ufc = universes002.idr:3:6}-                ConstraintFC {uconstraint = ./universes002.idr.b1 <= ./universes002.idr.e7, ufc = universes002.idr:45:9}-                ConstraintFC {uconstraint = ./universes002.idr.d1 <= ./universes002.idr.b1, ufc = universes002.idr:3:6}+                ConstraintFC {uconstraint = ./universes002.idr.b1 <= ./universes002.idr.e7, ufc = universes002.idr:45:11-48}+                ConstraintFC {uconstraint = ./universes002.idr.b1 < ./universes002.idr.c1, ufc = universes002.idr:3:6-10}+                ConstraintFC {uconstraint = ./universes002.idr.b1 <= ./universes002.idr.e7, ufc = universes002.idr:45:11-48}+                ConstraintFC {uconstraint = ./universes002.idr.d1 <= ./universes002.idr.b1, ufc = universes002.idr:3:6-10}+
test/views001/views001.idr view
@@ -26,7 +26,7 @@ testList : Int -> Int -> List Int -> List Int testList 0 seed acc = acc -- Need to explicitly mod since different back ends overflow differently-testList x seed acc = let seed' = seed * 12345 + 768 `mod` 65536 in+testList x seed acc = let seed' = (seed * 12345 + 768) `mod` 65536 in                           testList (x - 1) seed'                                 ((seed' `mod` 100) :: acc) 
test/views001/views001a.idr view
@@ -13,7 +13,7 @@ testList : Int -> Int -> List Int -> List Int testList 0 seed acc = acc -- Need to explicitly mod since different back ends overflow differently-testList x seed acc = let seed' = seed * 12345 + 768 `mod` 65536 in+testList x seed acc = let seed' = (seed * 12345 + 768) `mod` 65536 in                           testList (x - 1) seed'                                 ((seed' `mod` 100) :: acc) 
test/views002/views002.idr view
@@ -11,7 +11,7 @@ testList : Int -> Int -> List Int -> List Int testList 0 seed acc = acc -- Need to explicitly mod since different back ends overflow differently-testList x seed acc = let seed' = seed * 12345 + 768 `mod` 65536 in+testList x seed acc = let seed' = (seed * 12345 + 768) `mod` 65536 in                           testList (x - 1) seed'                                 ((seed' `mod` 100) :: acc)