| 1 |
import shallowEqual from "../utils/shallowEqual"; |
| 2 |
import isType from "./isType"; |
| 3 |
import isPlaceholderType from "./isPlaceholderType"; |
| 4 |
import { FLIPPED_ALIAS_KEYS } from "../definitions"; |
| 5 |
import type * as t from ".."; |
| 6 |
|
| 7 |
export default function is<T extends t.Node["type"]>( |
| 8 |
type: T, |
| 9 |
node: t.Node | null | undefined, |
| 10 |
opts?: undefined, |
| 11 |
): node is Extract<t.Node, { type: T }>; |
| 12 |
|
| 13 |
export default function is< |
| 14 |
T extends t.Node["type"], |
| 15 |
P extends Extract<t.Node, { type: T }>, |
| 16 |
>(type: T, n: t.Node | null | undefined, required: Partial<P>): n is P; |
| 17 |
|
| 18 |
export default function is<P extends t.Node>( |
| 19 |
type: string, |
| 20 |
node: t.Node | null | undefined, |
| 21 |
opts: Partial<P>, |
| 22 |
): node is P; |
| 23 |
|
| 24 |
export default function is( |
| 25 |
type: string, |
| 26 |
node: t.Node | null | undefined, |
| 27 |
opts?: Partial<t.Node>, |
| 28 |
): node is t.Node; |
| 29 |
/** |
| 30 |
* Returns whether `node` is of given `type`. |
| 31 |
* |
| 32 |
* For better performance, use this instead of `is[Type]` when `type` is unknown. |
| 33 |
*/ |
| 34 |
export default function is( |
| 35 |
type: string, |
| 36 |
node: t.Node | null | undefined, |
| 37 |
opts?: Partial<t.Node>, |
| 38 |
): node is t.Node { |
| 39 |
if (!node) return false; |
| 40 |
|
| 41 |
const matches = isType(node.type, type); |
| 42 |
if (!matches) { |
| 43 |
if (!opts && node.type === "Placeholder" && type in FLIPPED_ALIAS_KEYS) { |
| 44 |
// We can only return true if the placeholder doesn't replace a real node, |
| 45 |
// but it replaces a category of nodes (an alias). |
| 46 |
// |
| 47 |
// t.is("Identifier", node) gives some guarantees about node's shape, so we |
| 48 |
// can't say that Placeholder(expectedNode: "Identifier") is an identifier |
| 49 |
// because it doesn't have the same properties. |
| 50 |
// On the other hand, t.is("Expression", node) doesn't say anything about |
| 51 |
// the shape of node because Expression can be many different nodes: we can, |
| 52 |
// and should, safely report expression placeholders as Expressions. |
| 53 |
return isPlaceholderType(node.expectedNode, type); |
| 54 |
} |
| 55 |
return false; |
| 56 |
} |
| 57 |
|
| 58 |
if (typeof opts === "undefined") { |
| 59 |
return true; |
| 60 |
} else { |
| 61 |
return shallowEqual(node, opts); |
| 62 |
} |
| 63 |
} |