Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

An OCaml modular and generalised parser combinator library.

License

NotificationsYou must be signed in to change notification settings

d-plaindoux/transept

Repository files navigation

Transept

An OCaml modular and generalised parser combinator library.

Installation

Install the library and its dependencies viaOPAM:

opam install transept

or in yourproject-name.opam dependencies:

...depends: [  "transept" { >= "0.1.0" }  ...]  ...

Examples

Parsing arithmetic expressions

ADTs definition

This example is the traditional arithmetic expression language. This can be represented by the following abstract datatypes.In this first example we only care about significant items likefloat, parenthesis and finally operations.

typeoperation=  |Add  |Minus  |Mult  |Divtypeexpr=  |Numberoffloat  |BinOpofoperation*expr*expr

Parsers with a direct style

Direct style means we parse a stream of characters. In this case all characters are significant even spaces.

Required modules

Transept provides modules in order to help parsers construction. In the next fragmentUtils contains basic functionslikeconstant. TheParser module is a is parser dedicated to char stream analysis andLiteralsis dedicated to string,float etc. parsing.

moduleUtils=Transept.UtilsmoduleCharParser=Transept.Extension.Parser.For_char_listmoduleLiterals=Transept.Extension.Literals.Make (CharParser)

Operation parser

Therefore we can propose a first parser dedicated to operations.

let operator=letopenUtilsinletopenCharParserin        (atom'+'<$> constantAdd)<|> (atom'-'<$> constantMinus)<|> (atom'*'<$> constantMult)<|> (atom'/'<$> constantDiv)

Expression parser

Then the simple expression and the expression can be defined by the following parsers.

let expr=(* sexpr ::= float | '(' expr ')'*)letrecsexpr()=letopenLiteralsinletopenCharParserinfloat<$> (funf ->Number f)<|> (atom'('&> do_lazy expr<& atom')')(* expr ::= sexpr (operator expr)?*)andexpr()=letopenCharParserin      do_lazy sexpr<&> opt (operator<&> do_lazy expr)<$>function|e1,None -> e1|e1,Some (op,e2) ->BinOp (op, e1, e2)in expr

Finally, a sentence can be easily parsed.

letparses=letopenUtilsinletopenCharParserin    parse (expr())@@Stream.build@@ chars_of_string s

With this solution we don't skip whitespaces. It means1+(2+3) is parsed when1 + (2 + 3) is not!

The indirect style

SinceTransept is a generalized version, it's possible to parse something other than characters. For this purpose ageneric lexer is proposed thanks to theGenlex module.

Required modules

Transept provides modules in order to help parsers construction. In the next fragmentUtils contains basic functionslikeconstant. TheCharParser module is a parser dedicated to char stream analysis andStreamis dedicated toparsing using another parser.

moduleUtils=Transept.Utils.FunmoduleParser=Transept.Extension.Parser.For_char_listmoduleStream=Transept.Stream.Via_parser (Parser)moduleGenlex=Transept.Genlex.Lexer.Make (Parser)

Main parser

moduleParser=Transept.Core.Parser.Make_via_stream    (Stream)    (structtypet=Transept.Genlex.Lexeme.tend)moduleToken=Transept.Genlex.Lexeme.Make (Parser)

Operation parser

Therefore, we can propose a first parser dedicated to operations.

let operator=letopenUtilsinletopenParserinletopenTokenin        (kwd"+"<$> constantAdd)<|> (kwd"-"<$> constantMinus)<|> (kwd"*"<$> constantMult)<|> (kwd"/"<$> constantDiv)

Expression parser

Then the simple expression and the expression can be defined by the following parsers.

let expr=(* sexpr ::= float | '(' expr ')'*)letrecsexpr()=letopenParserinletopenLexemeinfloat<$> (funf ->Number f)<|> (kwd"("&> do_lazy expr<& kwd")")(* expr ::= sexpr (operator expr)?*)andexpr()=letopenParserin      do_lazy sexpr<&> opt (operator<&> do_lazy expr)<$>function|e1,None -> e1|e1,Some (op,e2) ->BinOp (op, e1, e2)in expr()

Finally, a sentence can be parsed using parsers. First oneCharParser parses char stream and is used by theGenlex in order to create a streamof lexemes. The second oneParser is used to parse the previous lexeme stream.

letparses=letopenUtilsinletopenParserinlet parser=CharParser.Stream.build@@Utils.chars_of_string sinlet stream=Stream.buildGenlex.tokenizer parserin    parse (expr<& eos) stream

With this solution whitespaces are skipped by the generic lexer. It means1 + ( 2+ 3) is parsed correctly now.

Indirect style applied to JSON parsing

AJSON Parser has been designed with this approch based on a low level parser producing tokens and a high level parser producing JSON terms from tokens.

LICENSE

MIT License

Copyright (c) 2020 Didier Plaindoux

Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.

About

An OCaml modular and generalised parser combinator library.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages


[8]ページ先頭

©2009-2025 Movatter.jp