Skip to content

Commit

Permalink
perf: use getVisitorKeys (sveltejs#381)
Browse files Browse the repository at this point in the history
prevents some needless recursion into embed
  • Loading branch information
dummdidumm committed Jul 17, 2023
1 parent 23f3dc4 commit d1cfc0b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
16 changes: 16 additions & 0 deletions src/embed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,22 @@ const {
utils: { removeLines },
} = doc;

const leaveAlone = new Set([
'Script',
'Style',
'Identifier',
'MemberExpression',
'CallExpression',
'ArrowFunctionExpression',
]);
const dontTraverse = new Set(['start', 'end', 'type']);

export function getVisitorKeys(node: any, nonTraversableKeys: Set<string>): string[] {
return Object.keys(node).filter((key) => {
return !nonTraversableKeys.has(key) && !leaveAlone.has(node.type) && !dontTraverse.has(key);
});
}

// Embed works like this in Prettier v3:
// - do depth first traversal of all node properties
// - deepest property is calling embed first
Expand Down
10 changes: 6 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { SupportLanguage, Parser, Printer } from 'prettier';
import * as prettierPluginBabel from 'prettier/plugins/babel';
import { hasPragma, print } from './print';
import { ASTNode } from './print/nodes';
import { embed } from './embed';
import { embed, getVisitorKeys } from './embed';
import { snipScriptAndStyleTagContent } from './lib/snipTagContent';

const babelParser = prettierPluginBabel.parsers.babel;
Expand Down Expand Up @@ -62,16 +62,18 @@ export const parsers: Record<string, Parser> = {
...babelParser,
parse: (text: string, options: any) => {
const ast = babelParser.parse(text, options);

return { ...ast, program: ast.program.body[0].expression };
}
}
},
},
};

export const printers: Record<string, Printer> = {
'svelte-ast': {
print,
embed,
// @ts-expect-error Prettier's type definitions are wrong
getVisitorKeys,
},
};

Expand Down

0 comments on commit d1cfc0b

Please sign in to comment.