Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7494373
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T17:30:12+00:00 2026-05-29T17:30:12+00:00

Assume I’ve this parser: let test p str = match run p str with

  • 0

Assume I’ve this parser:

let test p str =
    match run p str with
    | Success(result, _, _)   -> printfn "Success: %A" result
    | Failure(errorMsg, _, _) -> printfn "Failure: %s" errorMsg

let myStatement =
    choice (seq [
                pchar '2' >>. pchar '+' .>> pchar '3' .>> pchar ';';
                pchar '3' >>. pchar '*' .>> pchar '4' .>> pchar ';';
            ])

let myProgram = many myStatement

test myProgram "2+3;3*4;3*4;" // Success: ['+'; '*'; '*']

Now, "2+3;2*4;3*4;3+3;" will fail with error around 2*4;. But what is best practice if I want both the error for 2*4; and 3+3;? Basically, I want to scan to the nearest ‘;’ but only if there is a fatal error. And if that happens I want to aggregate the errors.

Kind regards, Lasse Espeholt

Update: recoverWith is a nice solution, thanks! But given:

let myProgram = 
    (many1 (myStatement |> recoverWith '�')) <|>% []

test myProgram "monkey"

I would expect to get [] with no errors. Or maybe a bit more “fair”:

let myProgram = 
    (attempt (many1 (myStatement |> recoverWith '�'))) <|>% []
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T17:30:13+00:00Added an answer on May 29, 2026 at 5:30 pm

    FParsec has no built-in support for recovering from fatal parser errors that would allow you to obtain partial parser results and collect errors from multiple positions. However, it’s pretty easy to define a custom combinator function for this purpose.

    For example, to recover from errors in your simple statement parser you could define the following recoverWith combinator:

    open FParsec
    
    type UserState = {
        Errors: (string * ParserError) list
    } with
        static member Create() = {Errors = []}
    
    type Parser<'t> = Parser<'t, UserState>
    
    // recover from error by skipping to the char after the next newline or ';'
    let recoverWith errorResult (p: Parser<_>) : Parser<_> =    
      fun stream ->
        let stateTag = stream.StateTag
        let mutable reply = p stream
        if reply.Status <> Ok then // the parser failed
            let error = ParserError(stream.Position, stream.UserState, reply.Error)
            let errorMsg = error.ToString(stream)
            stream.SkipCharsOrNewlinesWhile(fun c -> c <> ';' && c <> '\n') |> ignore                        
            stream.ReadCharOrNewline() |> ignore
            // To prevent infinite recovery attempts in certain situations,
            // the following check makes sure that either the parser p 
            // or our stream.Skip... commands consumed some input.
            if stream.StateTag <> stateTag then
                let oldErrors = stream.UserState.Errors
                stream.UserState <- {Errors = (errorMsg, error)::oldErrors}     
                reply <- Reply(errorResult)
        reply
    

    You could then use this combinator as follows:

    let myStatement =
        choice [
            pchar '2' >>. pchar '+' .>> pchar '3' .>> pchar ';'
            pchar '3' >>. pchar '*' .>> pchar '4' .>> pchar ';'
        ]
    
    let myProgram = 
        many (myStatement |> recoverWith '�') .>> eof
    
    let test p str =
        let printErrors (errorMsgs: (string * ParserError) list) =        
            for msg, _ in List.rev errorMsgs do
                printfn "%s" msg        
    
        match runParserOnString p (UserState.Create()) "" str with
        | Success(result, {Errors = []}, _) -> printfn "Success: %A" result
        | Success(result, {Errors = errors}, _) ->
            printfn "Result with errors: %A\n" result
            printErrors errors
        | Failure(errorMsg, error, {Errors = errors}) -> 
            printfn "Failure: %s" errorMsg
            printErrors ((errorMsg, error)::errors)
    

    Testing with test myProgram "2+3;2*4;3*4;3+3" would yield the output:

    Result with errors: ['+'; '�'; '*'; '�']
    
    Error in Ln: 1 Col: 6
    2+3;2*4;3*4;3+3
         ^
    Expecting: '+'
    
    Error in Ln: 1 Col: 14
    2+3;2*4;3*4;3+3
                 ^
    Expecting: '*'
    

    Update:

    Hmm, I thought you wanted to recover from a fatal error in order to collect multiple error messages and maybe produce a partial result. Something that would for example be useful for syntax highlighting or allowing your users to fix more than one error at a time.

    Your update seems to suggest that you just want to ignore parts of the input in case of a parser error, which is much simpler:

    let skip1ToNextStatement =
        notEmpty // requires at least one char to be skipped
            (skipManySatisfy (fun c -> c <> ';' && c <> '\n') 
             >>. optional anyChar) // optional since we might be at the EOF
    
    let myProgram =     
        many (attempt myStatement <|> (skip1ToNextStatement >>% '�'))
        |>> List.filter (fun c -> c <> '�')
    

    Update 2:

    The following is a version of recoverWith that doesn’t aggregate errors and only tries to recover from an error if the argument parser consumed input (or changed the parser state in any other way):

    let recoverWith2 errorResult (p: Parser<_>) : Parser<_> =
      fun stream ->
        let stateTag = stream.StateTag
        let mutable reply = p stream
        if reply.Status <> Ok && stream.StateTag <> stateTag then
            stream.SkipCharsOrNewlinesWhile(fun c -> c <> ';' && c <> '\n') |> ignore
            stream.ReadCharOrNewline() |> ignore
            reply <- Reply(errorResult)
        reply
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Assume this is the first route entry: routes.MapRoute( myRoute, employees/{city}/{pageNumber}, new { controller=Employees, action
Assume I have an Activity which contains two FrameLayouts (let's call them FrameA and
Assume there is a file test.txt containing a string 'test' . Now, consider the
Assume I have a code like this: @autoreleasepool { for(int i = 0; i
Assume I have a class like this: public class Foo { public Bar RequiredProperty
Assume I have this barebones structure: project/ main.py providers/ __init.py__ acme1.py acme2.py acme3.py acme4.py
Assume that I have an appstore. developers submit their application in this store. My
Assume this model class : public class Car extends Vehicle implements Visitable { .....
Assume java 1.6 and leopard. Ideally, it would also be nice to get a
(assume php5) consider <?php $foo = 'some words'; //case 1 print these are $foo;

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.