2
votes

I'm trying to parse a variable declaration with FParsec. I read part of the tutorial, as well as Phillip Trelford's example of parsing C#. Here is what could be scanned:

let [identifier] = [value];
let [identifier] [: type] = [value];
let [identifier] = [new [type(constructor)]];

For example:

let foo = 9;
let foo: Integer = 9;
let foo = new Integer(9);

But foo can also take arguments, for example:

let foo(a, b) = a + b;
let foo(a: Integer, b: Integer = 0) -> Integer = a + b;

Basically, a let instruction is identical to that of F#, except that the arguments are in parentheses, and that there is no block, just an expression.

In the tutorial, it implemented a C# variable such as:

let pdefine = pipe2 (pidentifier .>> ws1) (pidentifier)
                (fun ty name -> Define(ty,name))

let pdefinition = pdefine |>> fun d -> Definition(d)

But I have no idea how to implement my version, which seems more complex.... If someone could give me a lead, or a link that would explain more clearly how to do it, it would help me a lot.

1

1 Answers

3
votes

You could use this as an example:

open FParsec
open System

let str = pstring
let ws = spaces

type VarType = 
    | Implicit
    | Explicit of string

type Value = 
    | IntValue of int
    | TypeConstructor of string * Value

type LetDeclr = LetDeclr of string * VarType * Value

let isValidChar c =
    ['A'..'Z'] @ ['a'..'z']
    |> Seq.exists (fun ch -> ch = c)

let identifierParser = manySatisfy isValidChar

let value, valueRef = createParserForwardedToRef()

do valueRef := choice [
    str "new" >>. ws >>. identifierParser >>= fun typeName ->
        ws >>. between (str "(") (str ")") value |>> fun typeValue ->
             TypeConstructor(typeName, typeValue)
    pint32 |>> IntValue
]

let parser = 
    str "let" >>. ws >>. identifierParser
    >>= fun identifier ->
    attempt (ws >>. str ":" >>. ws >>. identifierParser |>> Explicit) <|> (ws >>% Implicit )
    >>= fun varType ->
    ws >>. str "=" >>. ws >>. value
    |>> fun varValue -> LetDeclr(identifier, varType, varValue)
    .>> ws .>> str ";"

let parse = FParsec.CharParsers.run parser

parse "let foo = 9;"
parse "let foo: Integer = 9;"
parse "let foo = new Integer(new String(344));"