Add getVisitorKeys (#13255)
This commit is contained in:
1 parent
a7d1ccb72b
commit
5fa0802315
32 files changed
+2279
-122
No files matched your search
@@ -156,6 +156,7 @@ export const printers = {
|
||||
print,
|
||||
embed,
|
||||
preprocess,
|
||||
getVisitorKeys,
|
||||
insertPragma,
|
||||
canAttachComment,
|
||||
isBlockComment,
|
||||
@@ -308,6 +309,53 @@ The `preprocess` method can process the AST from the parser before passing it in
|
||||
function preprocess(ast: AST, options: Options): AST | Promise<AST>;
|
||||
```
|
||||
|
||||
#### (optional) `getVisitorKeys`
|
||||
|
||||
This property might come in handy if the plugin uses comment attachment or embedded languages. These features traverse the AST iterating through all the own enumerable properties of each node starting from the root. If the AST has [cycles](<https://en.wikipedia.org/wiki/Cycle_(graph_theory)>), such a traverse ends up in an infinite loop. Also, nodes might contain non-node objects (e.g., location data), iterating through which is a waste of resources. To solve these issues, the printer can define a function to return property names that should be traversed.
|
||||
|
||||
Its signature is:
|
||||
|
||||
```ts
|
||||
function getVisitorKeys(node, nonTraversableKeys: Set<string>): string[];
|
||||
```
|
||||
|
||||
The default `getVisitorKeys`:
|
||||
|
||||
```js
|
||||
function getVisitorKeys(node, nonTraversableKeys) {
|
||||
return Object.keys(node).filter((key) => !nonTraversableKeys.has(key));
|
||||
}
|
||||
```
|
||||
|
||||
The second argument `nonTraversableKeys` is a set of common keys and keys that prettier used internal.
|
||||
|
||||
If you have full list of visitor keys
|
||||
|
||||
```js
|
||||
const visitorKeys = {
|
||||
Program: ["body"],
|
||||
Identifier: [],
|
||||
// ...
|
||||
};
|
||||
|
||||
function getVisitorKeys(node /* , nonTraversableKeys*/) {
|
||||
// Return `[]` for unknown node to prevent Prettier fallback to use `Object.keys()`
|
||||
return visitorKeys[node.type] ?? [];
|
||||
}
|
||||
```
|
||||
|
||||
If you only need exclude a small set of keys
|
||||
|
||||
```js
|
||||
const ignoredKeys = new Set(["prev", "next", "range"]);
|
||||
|
||||
function getVisitorKeys(node, nonTraversableKeys) {
|
||||
return Object.keys(node).filter(
|
||||
(key) => !nonTraversableKeys.has(key) && !ignoredKeys.has(key)
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### (optional) `insertPragma`
|
||||
|
||||
A plugin can implement how a pragma comment is inserted in the resulting code when the `--insert-pragma` option is used, in the `insertPragma` function. Its signature is:
|
||||
|
||||
Reference in new issue
Block a user