Use Typescript to infer types of grammar rules #98
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR is the big one! It merges https://github.com/siefkenj/peggy-to-ts/ into
ts-pegjs
.This PR depends on #97
Much code in the
src/lib
directory was added. This code adds aTypeExtractor
object which takes a grammar AST and creates a Typescript type for each rule usingts-morph
to call Typescript for type inference.Key features:
returnTypes
, they will override whatever is computed.any
.onlyGenerateGrammarTypes
option was added to have only the grammar types output. This can be used if someone wants to split their parser into a types file and a parser file.Circularly defined types
If a grammar is defined like
the generator will try to create the following types:
which is a circular type definition. While the grammar knows it won't get stuck in an infinite parsing loop, the type has no idea. Ideally, someone would re-write the grammar to be
Rather than make users rewrite their grammar, the algorithm in
prune-circular-references.ts
"snips" the circular reference by insertingvoid
for one of the types. That is,turns to
This means the type of
B
is incorrect, but the type ofA
is correct. Assuming the rule closer to the top of the file is the start rule, everything should be fine.This actually comes up in practice in the
st
andjavascript
.pegjs
files.Currently no warning is emitted, but this could be easily changed.
Dependencies
This PR adds a dependency on
ts-morph
andprettier
. Theprettier
dependency can be removed without changing the meaning of the generated types, but it makes them look a lot nicer (and removes many excess parenthesis that are added when creating types)