This project is a parser for jsdoc types. It takes jsdoc type expressions like Array<string> and creates an abstract
syntax tree (AST) out of it. It is heavily inspired by the existing libraries catharsis and jsdoctypeparser, but does
not use PEG.js, instead it is written as a pratt parser.
You can find some more information about pratt parsers here:
import { stringifyRules, transform } from 'jsdoc-type-pratt-parser'const rules = stringifyRules()// `result` is the current node and `transform` is a function to transform child nodes.rules.NAME = (result, transform) => 'something else'const val = transform(rules, { type: 'JsdocTypeName', value: 'name'}) // -> 'something else'
This library also supports compatibility modes for catharsis and jsdoctypeparser. The provided transform functions attempt to
transform the output to the expected output of the target library. This will not always be the same as some types are
parsed differently. These modes are thought to make transition easier, but it is advised to use the native output as
this will be more uniform and will contain more information.
import { parse, jtpTransform } from 'jsdoc-type-pratt-parser'const result = jtpTransform(parse('myType.<string>', 'closure'))
Traverse
You can traverse an AST with the traverse function:
import { traverse } from 'jsdoc-type-pratt-parser'// property is the name of the property on parent that contains nodefunction onEnter(node, parent, property) { console.log(node.type)}// an onEnter and/or an onLeave function can be suppliedtraverse({ type: 'JsdocTypeName', value: 'name'}, onEnter, console.log)
Custom visitor keys (by node type) can be supplied as a fourth argument. They
take precedence over the built-in visitorKeys, which is useful for nodes whose
structure is not known to this package (e.g., the ASTs of computed properties):
traverse(ast, onEnter, onLeave, { // Visit the `expression` property of a custom node type MyCustomNode: ['expression'], // Nodes of unknown type are visited only if keys are given for them Identifier: []})
Custom Parsers and Stringifiers
For TypeScript's computed property and methods, access to JavaScript
(or TypeScript) parsing and stringification is required (beyond the
types supported in jsdoc-type-pratt-parser). You can provide these
by supplying the following optional arguments:
import { parse as espree } from 'espree'import { generate } from '@es-joy/escodegen'const parsed = parse( input, mode, { computedPropertyParser: espree })const stringified = stringify( result, generate)
Tests Status
This parser runs most tests of catharsis and
jsdoctypeparser. It compares the results of the different parsing libraries. If you
want to find out where the output differs, look in the tests for the comments // This seems to be an error of ... or
the differ keyword which indicates that differing results are produced.