Skip to content

Commit

Permalink
cleaner
Browse files Browse the repository at this point in the history
  • Loading branch information
markw65 committed Sep 9, 2023
1 parent 1f6eb83 commit 7876d0a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 21 deletions.
9 changes: 9 additions & 0 deletions lib/peg.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,15 @@ declare namespace ast {
location: LocationRange;
}

type AllNodes =
| Expression
| Grammar
| Initializer
| Named
| Rule
| TopLevelInitializer
;

/** The main Peggy AST class returned by the parser. */
interface Grammar extends Node<"grammar"> {
/** Initializer that run once when importing generated parser module. */
Expand Down
35 changes: 14 additions & 21 deletions test/types/peg.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,14 +176,7 @@ describe("peg.d.ts", () => {
it("creates an AST", () => {
const grammar = peggy.parser.parse(src);
expectType<peggy.ast.Grammar>(grammar);
type AstTypes = (
peggy.ast.Expression |
peggy.ast.Grammar |
peggy.ast.Initializer |
peggy.ast.Named |
peggy.ast.Rule |
peggy.ast.TopLevelInitializer
)["type"];
type AstTypes = peggy.ast.AllNodes["type"];
const visited: { [typ in AstTypes]?: number } = {};
function add(typ: AstTypes): void {
const v = visited[typ] || 0;
Expand Down Expand Up @@ -424,16 +417,10 @@ describe("peg.d.ts", () => {
},
});

// Extract the visitor object
type VisitorArg
= typeof visit extends peggy.compiler.visitor.Visitor<infer U>
? U : never;

// Extract the functions that don't return `any`
type DefinedKeys = keyof {
[K in keyof VisitorArg as VisitorArg[K] extends (...args: any) => any
? unknown extends ReturnType<VisitorArg[K]> ? never : K : never]: true
};
// Extract the keys from the visitor object
type DefinedKeys
= typeof visit extends peggy.compiler.visitor.Visitor<infer U>
? keyof U : never;

visit(grammar);

Expand Down Expand Up @@ -461,11 +448,17 @@ describe("peg.d.ts", () => {
"text",
"top_level_initializer",
"zero_or_more",
] satisfies AstTypes[];
] satisfies AstTypes[] satisfies DefinedKeys[];

expect(Object.keys(visited).sort()).toStrictEqual(astKeys);
expectType<AstTypes[]>(astKeys);
expectType<DefinedKeys[]>(astKeys);
function foo(a: typeof astKeys[number]): typeof a {
return a;
}
function bar(a: AstTypes, b: DefinedKeys): void {
foo(a);
foo(b);
}
bar("grammar", "grammar");
});

it("compiles", () => {
Expand Down

0 comments on commit 7876d0a

Please sign in to comment.