Debian Codegraph @

packages/babel-types/src/modifications/flow/removeTypeDuplicates.ts

raw
1 import {
2 isAnyTypeAnnotation,
3 isGenericTypeAnnotation,
4 isUnionTypeAnnotation,
5 isFlowBaseAnnotation,
6 isIdentifier,
7 } from "../../validators/generated";
8 import type * as t from "../..";
9
10 function getQualifiedName(node: t.GenericTypeAnnotation["id"]): string {
11 return isIdentifier(node)
12 ? node.name
13 : `${node.id.name}.${getQualifiedName(node.qualification)}`;
14 }
15
16 /**
17 * Dedupe type annotations.
18 */
19 export default function removeTypeDuplicates(
20 // todo(babel-8): change type to Array<...>
21 nodes: ReadonlyArray<t.FlowType | false | null | undefined>,
22 ): t.FlowType[] {
23 const generics = new Map<string, t.GenericTypeAnnotation>();
24 const bases = new Map<t.FlowBaseAnnotation["type"], t.FlowBaseAnnotation>();
25
26 // store union type groups to circular references
27 const typeGroups = new Set<t.FlowType[]>();
28
29 const types: t.FlowType[] = [];
30
31 for (let i = 0; i < nodes.length; i++) {
32 const node = nodes[i];
33 if (!node) continue;
34
35 // detect duplicates
36 if (types.indexOf(node) >= 0) {
37 continue;
38 }
39
40 // this type matches anything
41 if (isAnyTypeAnnotation(node)) {
42 return [node];
43 }
44
45 if (isFlowBaseAnnotation(node)) {
46 bases.set(node.type, node);
47 continue;
48 }
49
50 if (isUnionTypeAnnotation(node)) {
51 if (!typeGroups.has(node.types)) {
52 // todo(babel-8): use .push when nodes is mutable
53 nodes = nodes.concat(node.types);
54 typeGroups.add(node.types);
55 }
56 continue;
57 }
58
59 // find a matching generic type and merge and deduplicate the type parameters
60 if (isGenericTypeAnnotation(node)) {
61 const name = getQualifiedName(node.id);
62
63 if (generics.has(name)) {
64 let existing: t.Flow = generics.get(name);
65 if (existing.typeParameters) {
66 if (node.typeParameters) {
67 existing.typeParameters.params = removeTypeDuplicates(
68 existing.typeParameters.params.concat(node.typeParameters.params),
69 );
70 }
71 } else {
72 existing = node.typeParameters;
73 }
74 } else {
75 generics.set(name, node);
76 }
77
78 continue;
79 }
80
81 types.push(node);
82 }
83
84 // add back in bases
85 for (const [, baseType] of bases) {
86 types.push(baseType);
87 }
88
89 // add back in generics
90 for (const [, genericName] of generics) {
91 types.push(genericName);
92 }
93
94 return types;
95 }