Movatterモバイル変換
[0]ホーム
{-# LANGUAGE Trustworthy #-}{-# LANGUAGE NoImplicitPrelude #-}{-# LANGUAGE RankNTypes #-}{-# LANGUAGE MagicHash #-}{-# LANGUAGE DeriveFunctor #-}------------------------------------------------------------------------------- |-- Module : Text.ParserCombinators.ReadP-- Copyright : (c) The University of Glasgow 2002-- License : BSD-style (see the file libraries/base/LICENSE)---- Maintainer : libraries@haskell.org-- Stability : provisional-- Portability : non-portable (local universal quantification)---- This is a library of parser combinators, originally written by Koen Claessen.-- It parses all alternatives in parallel, so it never keeps hold of-- the beginning of the input string, a common source of space leaks with-- other parsers. The '(+++)' choice combinator is genuinely commutative;-- it makes no difference which branch is \"shorter\".-----------------------------------------------------------------------------moduleText.ParserCombinators.ReadP(-- * The 'ReadP' typeReadP,-- * Primitive operationsget,look,(+++),(<++),gather,-- * Other operationspfail,eof,satisfy,char,string,munch,munch1,skipSpaces,choice,count,between,option,optional,many,many1,skipMany,skipMany1,sepBy,sepBy1,endBy,endBy1,chainr,chainl,chainl1,chainr1,manyTill,-- * Running a parserReadS,readP_to_S,readS_to_P,-- * Properties-- $properties)whereimportGHC.Unicode(isSpace)importGHC.List(replicate,null)importGHC.Basehiding(many)importControl.Monad.Failinfixr5+++,<++-------------------------------------------------------------------------- ReadS-- | A parser for a type @a@, represented as a function that takes a-- 'String' and returns a list of possible parses as @(a,'String')@ pairs.---- Note that this kind of backtracking parser is very inefficient;-- reading a large structure may be quite slow (cf 'ReadP').typeReadSa=String->[(a,String)]-- ----------------------------------------------------------------------------- The P type-- is representation type -- should be kept abstractdataPa=Get(Char->Pa)|Look(String->Pa)|Fail|Resulta(Pa)|Final[(a,String)]-- invariant: list is non-empty!derivingFunctor-- ^ @since 4.8.0.0-- Monad, MonadPlus-- | @since 4.5.0.0instanceApplicativePwherepurex=ResultxFail(<*>)=ap-- | @since 2.01instanceMonadPlusP-- | @since 2.01instanceMonadPwhere(Getf)>>=k=Get(\c->fc>>=k)(Lookf)>>=k=Look(\s->fs>>=k)Fail>>=_=Fail(Resultxp)>>=k=kx<|>(p>>=k)(Finalr)>>=k=final[ys'|(x,s)<-r,ys'<-run(kx)s]fail_=Fail-- | @since 4.9.0.0instanceMonadFailPwherefail_=Fail-- | @since 4.5.0.0instanceAlternativePwhereempty=Fail-- most common case: two gets are combinedGetf1<|>Getf2=Get(\c->f1c<|>f2c)-- results are delivered as soon as possibleResultxp<|>q=Resultx(p<|>q)p<|>Resultxq=Resultx(p<|>q)-- fail disappearsFail<|>p=pp<|>Fail=p-- two finals are combined-- final + look becomes one look and one final (=optimization)-- final + sthg else becomes one look and one finalFinalr<|>Finalt=Final(r++t)Finalr<|>Lookf=Look(\s->Final(r++run(fs)s))Finalr<|>p=Look(\s->Final(r++runps))Lookf<|>Finalr=Look(\s->Final(run(fs)s++r))p<|>Finalr=Look(\s->Final(runps++r))-- two looks are combined (=optimization)-- look + sthg else floats upwardsLookf<|>Lookg=Look(\s->fs<|>gs)Lookf<|>p=Look(\s->fs<|>p)p<|>Lookf=Look(\s->p<|>fs)-- ----------------------------------------------------------------------------- The ReadP typenewtypeReadPa=R(forallb.(a->Pb)->Pb)-- | @since 2.01instanceFunctorReadPwherefmaph(Rf)=R(\k->f(k.h))-- | @since 4.6.0.0instanceApplicativeReadPwherepurex=R(\k->kx)(<*>)=ap-- liftA2 = liftM2-- | @since 2.01instanceMonadReadPwherefail_=R(\_->Fail)Rm>>=f=R(\k->m(\a->letRm'=fainm'k))-- | @since 4.9.0.0instanceMonadFailReadPwherefail_=R(\_->Fail)-- | @since 4.6.0.0instanceAlternativeReadPwhereempty=pfail(<|>)=(+++)-- | @since 2.01instanceMonadPlusReadP-- ----------------------------------------------------------------------------- Operations over Pfinal::[(a,String)]->Pa-- Maintains invariant for Final constructorfinal[]=Failfinalr=Finalrrun::Pa->ReadSarun(Getf)(c:s)=run(fc)srun(Lookf)s=run(fs)srun(Resultxp)s=(x,s):runpsrun(Finalr)_=rrun__=[]-- ----------------------------------------------------------------------------- Operations over ReadPget::ReadPChar-- ^ Consumes and returns the next character.-- Fails if there is no input left.get=RGetlook::ReadPString-- ^ Look-ahead: returns the part of the input that is left, without-- consuming it.look=RLookpfail::ReadPa-- ^ Always fails.pfail=R(\_->Fail)(+++)::ReadPa->ReadPa->ReadPa-- ^ Symmetric choice.Rf1+++Rf2=R(\k->f1k<|>f2k)(<++)::ReadPa->ReadPa->ReadPa-- ^ Local, exclusive, left-biased choice: If left parser-- locally produces any result at all, then right parser is-- not used.Rf0<++q=dos<-lookprobe(f0return)s0#whereprobe(Getf)(c:s)n=probe(fc)s(n+#1#)probe(Lookf)sn=probe(fs)snprobep@(Result__)_n=discardn>>R(p>>=)probe(Finalr)__=R(Finalr>>=)probe___=qdiscard0#=return()discardn=get>>discard(n-#1#)gather::ReadPa->ReadP(String,a)-- ^ Transforms a parser into one that does the same, but-- in addition returns the exact characters read.-- IMPORTANT NOTE: 'gather' gives a runtime error if its first argument-- is built using any occurrences of readS_to_P.gather(Rm)=R(\k->gathid(m(\a->return(\s->k(s,a)))))wheregath::(String->String)->P(String->Pb)->Pbgathl(Getf)=Get(\c->gath(l.(c:))(fc))gath_Fail=Failgathl(Lookf)=Look(\s->gathl(fs))gathl(Resultkp)=k(l[])<|>gathlpgath_(Final_)=errorWithoutStackTrace"do not use readS_to_P in gather!"-- ----------------------------------------------------------------------------- Derived operationssatisfy::(Char->Bool)->ReadPChar-- ^ Consumes and returns the next character, if it satisfies the-- specified predicate.satisfyp=doc<-get;ifpcthenreturncelsepfailchar::Char->ReadPChar-- ^ Parses and returns the specified character.charc=satisfy(c==)eof::ReadP()-- ^ Succeeds iff we are at the end of inputeof=do{s<-look;ifnullsthenreturn()elsepfail}string::String->ReadPString-- ^ Parses and returns the specified string.stringthis=dos<-look;scanthisswherescan[]_=doreturnthisscan(x:xs)(y:ys)|x==y=do_<-get;scanxsysscan__=dopfailmunch::(Char->Bool)->ReadPString-- ^ Parses the first zero or more characters satisfying the predicate.-- Always succeeds, exactly once having consumed all the characters-- Hence NOT the same as (many (satisfy p))munchp=dos<-lookscanswherescan(c:cs)|pc=do_<-get;s<-scancs;return(c:s)scan_=doreturn""munch1::(Char->Bool)->ReadPString-- ^ Parses the first one or more characters satisfying the predicate.-- Fails if none, else succeeds exactly once having consumed all the characters-- Hence NOT the same as (many1 (satisfy p))munch1p=doc<-getifpcthendos<-munchp;return(c:s)elsepfailchoice::[ReadPa]->ReadPa-- ^ Combines all parsers in the specified list.choice[]=pfailchoice[p]=pchoice(p:ps)=p+++choicepsskipSpaces::ReadP()-- ^ Skips all whitespace.skipSpaces=dos<-lookskipswhereskip(c:s)|isSpacec=do_<-get;skipsskip_=doreturn()count::Int->ReadPa->ReadP[a]-- ^ @count n p@ parses @n@ occurrences of @p@ in sequence. A list of-- results is returned.countnp=sequence(replicatenp)between::ReadPopen->ReadPclose->ReadPa->ReadPa-- ^ @between open close p@ parses @open@, followed by @p@ and finally-- @close@. Only the value of @p@ is returned.betweenopenclosep=do_<-openx<-p_<-closereturnxoption::a->ReadPa->ReadPa-- ^ @option x p@ will either parse @p@ or return @x@ without consuming-- any input.optionxp=p+++returnxoptional::ReadPa->ReadP()-- ^ @optional p@ optionally parses @p@ and always returns @()@.optionalp=(p>>return())+++return()many::ReadPa->ReadP[a]-- ^ Parses zero or more occurrences of the given parser.manyp=return[]+++many1pmany1::ReadPa->ReadP[a]-- ^ Parses one or more occurrences of the given parser.many1p=liftM2(:)p(manyp)skipMany::ReadPa->ReadP()-- ^ Like 'many', but discards the result.skipManyp=manyp>>return()skipMany1::ReadPa->ReadP()-- ^ Like 'many1', but discards the result.skipMany1p=p>>skipManypsepBy::ReadPa->ReadPsep->ReadP[a]-- ^ @sepBy p sep@ parses zero or more occurrences of @p@, separated by @sep@.-- Returns a list of values returned by @p@.sepBypsep=sepBy1psep+++return[]sepBy1::ReadPa->ReadPsep->ReadP[a]-- ^ @sepBy1 p sep@ parses one or more occurrences of @p@, separated by @sep@.-- Returns a list of values returned by @p@.sepBy1psep=liftM2(:)p(many(sep>>p))endBy::ReadPa->ReadPsep->ReadP[a]-- ^ @endBy p sep@ parses zero or more occurrences of @p@, separated and ended-- by @sep@.endBypsep=many(dox<-p;_<-sep;returnx)endBy1::ReadPa->ReadPsep->ReadP[a]-- ^ @endBy p sep@ parses one or more occurrences of @p@, separated and ended-- by @sep@.endBy1psep=many1(dox<-p;_<-sep;returnx)chainr::ReadPa->ReadP(a->a->a)->a->ReadPa-- ^ @chainr p op x@ parses zero or more occurrences of @p@, separated by @op@.-- Returns a value produced by a /right/ associative application of all-- functions returned by @op@. If there are no occurrences of @p@, @x@ is-- returned.chainrpopx=chainr1pop+++returnxchainl::ReadPa->ReadP(a->a->a)->a->ReadPa-- ^ @chainl p op x@ parses zero or more occurrences of @p@, separated by @op@.-- Returns a value produced by a /left/ associative application of all-- functions returned by @op@. If there are no occurrences of @p@, @x@ is-- returned.chainlpopx=chainl1pop+++returnxchainr1::ReadPa->ReadP(a->a->a)->ReadPa-- ^ Like 'chainr', but parses one or more occurrences of @p@.chainr1pop=scanwherescan=p>>=restrestx=dof<-opy<-scanreturn(fxy)+++returnxchainl1::ReadPa->ReadP(a->a->a)->ReadPa-- ^ Like 'chainl', but parses one or more occurrences of @p@.chainl1pop=p>>=restwhererestx=dof<-opy<-prest(fxy)+++returnxmanyTill::ReadPa->ReadPend->ReadP[a]-- ^ @manyTill p end@ parses zero or more occurrences of @p@, until @end@-- succeeds. Returns a list of values returned by @p@.manyTillpend=scanwherescan=(end>>return[])<++(liftM2(:)pscan)-- ----------------------------------------------------------------------------- Converting between ReadP and ReadreadP_to_S::ReadPa->ReadSa-- ^ Converts a parser into a Haskell ReadS-style function.-- This is the main way in which you can \"run\" a 'ReadP' parser:-- the expanded type is-- @ readP_to_S :: ReadP a -> String -> [(a,String)] @readP_to_S(Rf)=run(freturn)readS_to_P::ReadSa->ReadPa-- ^ Converts a Haskell ReadS-style function into a parser.-- Warning: This introduces local backtracking in the resulting-- parser, and therefore a possible inefficiency.readS_to_Pr=R(\k->Look(\s->final[bs''|(a,s')<-rs,bs''<-run(ka)s']))-- ----------------------------------------------------------------------------- QuickCheck properties that hold for the combinators{- $propertiesThe following are QuickCheck specifications of what the combinators do.These can be seen as formal specifications of the behavior of thecombinators.For some values, we only care about the lists contents, not their order,> (=~) :: Ord a => [a] -> [a] -> Bool> xs =~ ys = sort xs == sort ysHere follow the properties:>>> readP_to_S get [][]prop> \c str -> readP_to_S get (c:str) == [(c, str)]prop> \str -> readP_to_S look str == [(str, str)]prop> \str -> readP_to_S pfail str == []prop> \x str -> readP_to_S (return x) s == [(x,s)]> prop_Bind p k s => readP_to_S (p >>= k) s =~> [ ys''> | (x,s') <- readP_to_S p s> , ys'' <- readP_to_S (k (x::Int)) s'> ]> prop_Plus p q s => readP_to_S (p +++ q) s =~> (readP_to_S p s ++ readP_to_S q s)> prop_LeftPlus p q s => readP_to_S (p <++ q) s =~> (readP_to_S p s +<+ readP_to_S q s)> where> [] +<+ ys = ys> xs +<+ _ = xs> prop_Gather s => forAll readPWithoutReadS $ \p ->> readP_to_S (gather p) s =~> [ ((pre,x::Int),s')> | (x,s') <- readP_to_S p s> , let pre = take (length s - length s') s> ]prop> \this str -> readP_to_S (string this) (this ++ str) == [(this,str)]> prop_String_Maybe this s => readP_to_S (string this) s =~> [(this, drop (length this) s) | this `isPrefixOf` s]> prop_Munch p s => readP_to_S (munch p) s =~> [(takeWhile p s, dropWhile p s)]> prop_Munch1 p s => readP_to_S (munch1 p) s =~> [(res,s') | let (res,s') = (takeWhile p s, dropWhile p s), not (null res)]> prop_Choice ps s => readP_to_S (choice ps) s =~> readP_to_S (foldr (+++) pfail ps) s> prop_ReadS r s => readP_to_S (readS_to_P r) s =~ r s-}
[8]ページ先頭