{"id":19918002,"url":"https://github.com/sethfowler/pegjs-template","last_synced_at":"2025-07-06T23:06:52.820Z","repository":{"id":57321840,"uuid":"273986107","full_name":"sethfowler/pegjs-template","owner":"sethfowler","description":"Build PEG.js grammars using template strings.","archived":false,"fork":false,"pushed_at":"2020-07-14T00:03:53.000Z","size":15,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-05-24T00:50:05.559Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","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/sethfowler.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":"2020-06-21T21:26:08.000Z","updated_at":"2022-10-24T11:40:21.000Z","dependencies_parsed_at":"2022-08-25T21:01:31.292Z","dependency_job_id":null,"html_url":"https://github.com/sethfowler/pegjs-template","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/sethfowler/pegjs-template","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sethfowler%2Fpegjs-template","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sethfowler%2Fpegjs-template/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sethfowler%2Fpegjs-template/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sethfowler%2Fpegjs-template/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sethfowler","download_url":"https://codeload.github.com/sethfowler/pegjs-template/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sethfowler%2Fpegjs-template/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":261631280,"owners_count":23187233,"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","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":[],"created_at":"2024-11-12T21:52:07.296Z","updated_at":"2025-07-06T23:06:52.802Z","avatar_url":"https://github.com/sethfowler.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# pegjs-template\nBuild [PEG.js](https://pegjs.org) grammars using template strings.\n\nPEG.js grammars are normally just strings; semantic actions are specified using\nJavaScript embedded in the string. This library allows you to write semantic\nactions using real JavaScript functions. This has several advantages:\n- Syntax highlighting works.\n- Code completion and other code intelligence features work.\n- Semantic actions can be written in TypeScript, allowing them to be type\n  checked.\n- Semantic actions can easily reference variables or APIs defined outside the\n  grammar, without any awkward workarounds like passing them in via the context.\n\nIn addition, `pegjs-template` allows you to write partial grammars. These are\nsmall grammars that can be merged together to make a complete grammar. This\nallows you to make your grammars modular and factor out shared code so that it\ncan be reused in multiple grammars.\n\n`pegjs-template` is a better way to write PEG.js grammars!\n\n# Basic usage\n\nUse the `pegGrammar` function exported by this library as a template tag\nfunction and interpolate your semantic actions in as functions. If you're using\nthe library from TypeScript, you'll need to provide a type parameter for\n`pegGrammar`; this is the type of the AST that your parser returns.\n\nSemantic action functions must have this type:\n\n```ts\ntype Action = (context: ActionContext, ...labels: any[]) =\u003e any;\n```\n\nThe first argument to your semantic action will be an `ActionContext` object\ncontaining the standard PEG.js helpers:\n\n```ts\nexport type PEGActionContext = {\n  /** @returns the text matched by the current rule. */\n  text(): string;\n\n  /** @returns the source range matched by the current rule. */\n  location(): SourceLocation;\n\n  /** Throw an exception indicating that 'expected' was expected but not found. */\n  expected(expected: string, location?: SourceLocation): never;\n\n  /** Throw an exception with the error message 'message'. */\n  error(message: string, location?: SourceLocation): never;\n\n  /** Options passed to the parser. */\n  options: Record\u003cstring, any\u003e;\n};\n```\n\nThe remaining arguments are the semantic values for the labeled expressions in\nthe current rule. Note that, while the context argument can be named anything,\nthe label argument names must match the label names in the grammar exactly!\n\nOne limitation to be aware of: this library parses the argument list of your\nsemantic action functions using a simple regular expression. Don't try to get\nfancy with destructuring or rest parameters in the argument list; they won't\nwork the way you expect.\n\nAn example's worth a thousand words, so here's the arithmetic grammar example\nfrom the PEG.js docs, rewritten to use this library:\n\n```ts\nimport { pegGrammar } from 'pegjs-template';\n\nconst parser = pegGrammar\u003cnumber\u003e`\n// Simple Arithmetics Grammar\n// ==========================\n//\n// Accepts expressions like \"2 * (3 + 4)\" and computes their value.\n\nExpression\n  = head:Term tail:(_ (\"+\" / \"-\") _ Term)* ${(_, head, tail) =\u003e {\n      return tail.reduce(function(result, element) {\n        if (element[1] === \"+\") { return result + element[3]; }\n        if (element[1] === \"-\") { return result - element[3]; }\n      }, head);\n    }}\n\nTerm\n  = head:Factor tail:(_ (\"*\" / \"/\") _ Factor)* ${(_, head, tail) =\u003e {\n      return tail.reduce(function(result, element) {\n        if (element[1] === \"*\") { return result * element[3]; }\n        if (element[1] === \"/\") { return result / element[3]; }\n      }, head);\n    }}\n\nFactor\n  = \"(\" _ expr:Expression _ \")\" ${(_, expr) =\u003e expr}\n  / Integer\n\nInteger \"integer\"\n  = _ [0-9]+ ${(ctx) =\u003e parseInt(ctx.text(), 10)}\n\n_ \"whitespace\"\n  = [ \\t\\n\\r]*\n`;\n\nparser.parse('2 * (3 + 4)');  // Returns '14'.\n```\n\n# Partial grammars\n\nYou can create a partial grammar using the `pegPartialGrammar` function exported\nby this library. It's also a template tag function that works just like\n`pegGrammar`, except that instead of returning a parser it returns a\n`PartialGrammar` object.\n\nYou can interpolate `PartialGrammar` objects into other grammars using either\n`pegGrammar` or `pegPartialGrammar`. The result is just like you interpolated\nthe source code into the grammar as text, except that any semantic action\nfunctions you defined in JavaScript come along for the ride. This makes it easy\nto combine smaller grammars into larger grammars while retaining all the\nbenefits of defining your semantic actions in JavaScript.\n\n# Generate options\n\n`pegGrammar` automatically calls PEG.js's `generate()` function for you to\ngenerate a parser from your grammar. This means that you can't provide options\nto `generate()` in the usual way. Normally the defaults are fine, but if you do\nneed to provide options - for example, to enable tracing - you can use\n`pegGenerateOptions()`. This function accepts the same options argument that\n`generate()` does. It returns a `GenerateOptions` object that you can\ninterpolate into your grammar using `pegGrammar` or `pegPartialGrammar`. This\ndoesn't change the grammar source code itself, but the options will be\nrecognized and passed to `generate()` as you'd expect.\n\nThere is one limitation: you can only interpolate one `GenerateOptions` object\ninto your grammar. `pegGrammar` will throw an exception if you try to include\nmore than one.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsethfowler%2Fpegjs-template","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsethfowler%2Fpegjs-template","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsethfowler%2Fpegjs-template/lists"}