Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.21 KB | None | 0 0
  1. module Lexer =
  2.  
  3.     open FParsec.Primitives
  4.     open FParsec.CharParsers
  5.  
  6.     let escapeCharacters<'a> : Parser<string, 'a> =
  7.         ["+"; "-"; "&&"; "||"; "!"; "("; ")"; "{"; "}"; "["; "]"; "^"; "\""; "~"; "*"; "?"; ":"; "\\"]  |> Seq.map pstring |> Seq.reduce (<|>)
  8.  
  9.    let wordOperator<'a> : Parser<Token, 'a> =
  10.        pipe3 spaces1 (pstring "TO" <|> pstring "OR" <|> pstring "AND" <|> pstring "NOT") spaces1  (fun _ s _ -> Operator s)
  11.  
  12.    let operator<'a> : Parser<Token, 'a> =
  13.        (escapeCharacters |>> Operator) <|> attempt wordOperator <|> (spaces1 |>> fun c -> Operator "OR")
  14.                
  15.    let term<'a> : Parser<Token, 'a> =
  16.        many1Chars (notFollowedBy operator >>. anyChar) |>> Term
  17.  
  18.    let phrase<'a> : Parser<Token, 'a> =
  19.        between (pchar '\"') (pchar '\"') (manyStrings ((notFollowedBy operator >>. anyString 1) <|> (skipString "\\" >>. escapeCharacters))) |>> Phrase
  20.  
  21.    let exec<'a> : Parser<list<Token>, 'a> =
  22.        manyTill (term <|> phrase <|> operator) eof
  23.  
  24.    let tokenize input =
  25.        let r = runParserOnString exec "" "" input
  26.        match r with
  27.        | Success (a, b, c) ->
  28.            a
  29.        | Failure (a, b, c) ->
  30.            failwith a
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement