{"id":33966003,"url":"https://github.com/nielssp/parco","last_synced_at":"2026-06-05T10:31:16.446Z","repository":{"id":57026869,"uuid":"46222284","full_name":"nielssp/parco","owner":"nielssp","description":"PHP parser combinators","archived":false,"fork":false,"pushed_at":"2016-02-14T09:32:56.000Z","size":68,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-08-01T12:17:59.769Z","etag":null,"topics":["grammar","lexer","parser","parser-combinators","php","regular-expression"],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nielssp.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-11-15T15:03:24.000Z","updated_at":"2017-03-04T14:52:41.000Z","dependencies_parsed_at":"2022-08-23T16:20:35.267Z","dependency_job_id":null,"html_url":"https://github.com/nielssp/parco","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"purl":"pkg:github/nielssp/parco","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nielssp%2Fparco","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nielssp%2Fparco/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nielssp%2Fparco/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nielssp%2Fparco/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nielssp","download_url":"https://codeload.github.com/nielssp/parco/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nielssp%2Fparco/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":27694446,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-12-12T02:00:06.775Z","response_time":129,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["grammar","lexer","parser","parser-combinators","php","regular-expression"],"created_at":"2025-12-12T23:01:15.973Z","updated_at":"2025-12-12T23:01:37.573Z","avatar_url":"https://github.com/nielssp.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Parco – PHP parser combinators\n\n[![Build Status](https://travis-ci.org/nielssp/parco.svg?branch=master)](https://travis-ci.org/nielssp/parco) [![Coverage Status](https://coveralls.io/repos/nielssp/parco/badge.svg?branch=master\u0026service=github)](https://coveralls.io/github/nielssp/parco?branch=master) [![Latest Stable Version](https://poser.pugx.org/nielssp/parco/v/stable)](https://packagist.org/packages/nielssp/parco)\n\nParco is an experimental parser combinator library for PHP inspired by [Scala Parser Combinators](https://github.com/scala/scala-parser-combinators). See also [Wikipedia](https://en.wikipedia.org/wiki/Parser_combinator) for general information on parser combinators.\n\nThe API documentation is available on [parco.nielssp.dk/api](http://parco.nielssp.dk/api).\n\n## Install\nRequirements:\n\n* PHP 5.4 or newer\n\nInstall using composer:\n```\ncomposer require nielssp/parco\n```\n## Usage\n\nSee the `examples` directory for some examples:\n\n* `calculator.php` is a simple calculator made using `RegexParsers` based on [this example in the Scala Parser Combinators documentation](http://www.scala-lang.org/files/archive/api/2.11.2/scala-parser-combinators/#scala.util.parsing.combinator.RegexParsers).\n* `json.php` is a JSON parser using `RegexParsers`.\n* `lexer.php` is a lexer/scanner for a small expression language based on the \u0026lambda;-calculus.\n* `tokens.php` is a parser using `PositionalParsers` to convert the token sequence produced by `lexer.php` into an abstract syntax tree.\n\n### Writing a parser\n\nTo write a parser using Parco simply use one of the combinator traits in a class. There are currently three traits:\n\n* [Parsers](http://parco.nielssp.dk/api/class-Parco.Combinator.Parsers.html) for generic parser combinators (the user must provide an input sequence implementation),\n* [RegexParsers](http://parco.nielssp.dk/api/class-Parco.Combinator.RegexParsers.html) (extends `Parsers`) for parsing strings, and\n* [PositionalParsers](http://parco.nielssp.dk/api/class-Parco.Combinator.PositionalParsers.html) (extends `Parsers`) for parsing arrays of objects that implement the `Positional` interface (e.g. a list of tokens from a lexer).\n\n```php\nclass Myparser\n{\n    use \\Parco\\Combinator\\RegexParsers;\n}\n```\n\nTo implement a parser you may define multiple subparsers and combine them using combinators.\n\nEach subparser is implemented as a parameterless method returning a `Parser` object. It usually makes sense to have a method for each production rule in your language grammar, so for a grammar such as:\n```nohighlight\n expr   ::= term {\"+\" term | \"-\" term}\n term   ::= factor {\"*\" factor | \"/\" factor}\n factor ::= \"(\" expr \")\"\n          | number\n number ::= digit {digit} [\".\" digit {digit}]\n```\nour parser class may have the following structure:\n```php\nclass Myparser\n{\n    use \\Parco\\Combinator\\RegexParsers;\n\n    public function expr()\n    {\n    \treturn // a parser for expressions\n    }\n\n    public function term()\n    {\n    \treturn // a parser for terms\n    }\n\n    public function factor()\n    {\n    \treturn // a parser for factors\n    }\n\n    public function number()\n    {\n    \treturn // a parser for numbers\n    }\n}\n```\nYou may also want to add a method for invoking the parser:\n```php\nclass MyParser\n{\n    use \\Parco\\Combinator\\RegexParsers;\n\n    // ...\n\n    public function __invoke($string)\n    {\n    \treturn $this-\u003eparseAll($this-\u003eexpr, $string)-\u003eget();\n    }\n}\n```\nThe `parseAll` method is provided by the `RegexParsers` trait. It converts the input string to a sequence of characters and makes sure that there is no leftover input after the given parser has been applied. Now we can use the parser by constructing and then invoking it:\n```php\n$myParser = new MyParser();\necho $myParser('1 + 5 - 7 / 2');\n```\nIf the parser fails, a `ParseException` is thrown. The \"Error handling\" section below explains how to handle parse errors.\n\n### Terminals\n\nThe follwing parsers can be used to parse one or more input sequence elements:\n\n```php\n$this-\u003eelem('a') // exact element\n$this-\u003eacceptIf(function ($elem) { return $elem instanceof NumberToken; }) // predicate\n$this-\u003echar('a') // character (RegexParsers)\n$this-\u003estring('goto') // string (RegexParsers)\n```\nAdditionally `RegexParsers` provides a method for parsing input sequence elements using regular expressions, e.g.:\n```php\n$this-\u003eregex('/[a-z][a-z0-9]*/i')\n```\nThe above parsers serve as the basic building blocks for constructing more advanced parsers. The following section shows how to combine them.\n\n### From grammar to code\n\nSome basic combinators provided by `Parsers`:\n\n* Sequencing: `a b c` (`a` followed by `b` followed by `c`):\n```php\n$this-\u003eseq($this-\u003ea, $this-\u003eb, $this-\u003ec)\n```\nIf you want to parse `a` followed by `b`, but only want to keep the result of `a`, the method `seqL` can be used:\n```php\n$this-\u003ea-\u003eseqL($this-\u003eb)\n```\nSimilarily, `seqR` can be used to keep the result of `b` instead.\n* Alternation: `a | b | c` (`a`, `b`, or `c`):\n```php\n$this-\u003ealt($this-\u003ea, $this-\u003eb, $this-\u003ec)\n```\n* Repetition: `{a}` (zero or more repetitions of `a`):\n```php\n$this-\u003erep($this-\u003ea)\n```\n* Option: `[a]` (zero or one `a`):\n```php\n$this-\u003eopt($this-\u003ea)\n```\n\nMore combinators are described on the [API documentation page](http://parco.nielssp.dk/api/class-Parco.Combinator.Parsers.html).\n\n### Manipulating parser results\n\nThe abstract `Parser` class provides some methods for manipulating the result of a parser. The most important one is the `map`-method, which converts the result of a parser using a function, e.g.:\n```php\n$this-\u003eregex('/\\d+/')-\u003emap(function ($digits) {\n    return intval($digits);\n});\n```\nThe above parser uses a regular expression to parse one or more digits, then converts the result to and integer.\n\nTwo other useful methods are:\n* `withResult` replace the result of a parser:\n```php\n$this-\u003estring('true')-\u003ewithResult(true);\n```\n* `withFailure` set a custom failure message:\n```php\n$this-\u003eregex('/\\d+/')-\u003ewithFailure('expected an integer');\n```\n\n### Recursion\n\nThe `Parsers` trait provides a magic getter that converts parameterless parsers into lazy parsers. This can be used to implement recursive grammars such as the follwing:\n\n```nohighlight\nexpr ::= term \"-\" term\nterm ::= \"(\" expr \")\"\n       | number\n```\n\nTo use this feature simply refererence your parser functions without parentheses (e.g. `$this-\u003eexpr` instead of `$this-\u003eexpr()`):\n\n```php\npublic function expr()\n{\n    return $this-\u003eseq($this-\u003eterm, $this-\u003echar(\"-\"), $this-\u003eterm);\n}\npublic function term()\n{\n    return $this-\u003ealt(\n    \t$this-\u003eseq($this-\u003echar(\"(\"), $this-\u003eexpr, $this-\u003echar(\")\")),\n        $this-\u003enumber\n    );\n}\n```\n\n### Left recursion\n\nSome left-recursive grammars (e.g. left-associative operators) such as\n```nohighlight\nexpr ::= expr \"-\" term\n       | term\n```\ncan be implemented using the `chainl`-combinator:\n```php\npublic function expr()\n{\n    return $this-\u003echainl(\n        $this-\u003eterm,\n        $this-\u003echar('-')-\u003ewithResult(function ($left, $right) {\n            return $left - $right;\n        })\n    );\n}\n```\nThe second parameter to `chainl` is a parser that parses the separator (i.e. the `'-'` terminal) and returns a function that combines parse result from left to right.\n\nThus the result of parsing `8 - 4 - 1 - 3` with the above parser is `((8 - 4) - 1) - 3 = 0`.\n\nA similar combinator, `chainr`, can be used for right-associative operators.\n\n### Error handling\n\nThe result of a parser includes information about the line number and column number. This can be used to produce helpful error messages.\n\nAn example of a parser error handler:\n```php\n$result = $myParser($input);\nif (! $result-\u003esuccessful) {\n    $lines = explode(\"\\n\", $input);\n    $line = $result-\u003egetInputLine($lines);\n    $column = $result-\u003egetInputColumn($lines);\n    echo 'Syntax Error: ' . $result-\u003emessage\n        . ' on line ' . $line\n        . ' column ' . $column . PHP_EOL;\n    if ($line \u003e 0) {\n        echo $lines[$line - 1] . PHP_EOL;\n        echo str_repeat('-', $column - 1) . '^';\n    }\n}\n```\nWhich produces output such as:\n```\nSyntax Error: expected \"-\u003e\" on line 1 column 17\nlet x = 5 in \\y - x + y\n----------------^\n```\nParco also has an exception class, `ParseException`, that can be used to wrap parse errors. It is thrown automatically when calling `get()` on an unsuccessful parser result.\n\n## License\nCopyright (C) 2015 Niels Sonnich Poulsen (http://nielssp.dk)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 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 THE SOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnielssp%2Fparco","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnielssp%2Fparco","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnielssp%2Fparco/lists"}