-
-
Notifications
You must be signed in to change notification settings - Fork 79
/
Copy pathscope-analyzer.ts
332 lines (305 loc) · 10.9 KB
/
scope-analyzer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
import type * as escopeTypes from "eslint-scope"
import type { ParserOptions } from "../common/parser-options"
import type {
Reference,
VAttribute,
VDirective,
VDocumentFragment,
VElement,
VExpressionContainer,
} from "../ast"
import { traverseNodes } from "../ast"
import { getEslintScope } from "../common/eslint-scope"
const BUILTIN_COMPONENTS = new Set([
"template",
"slot",
"component",
"Component",
"transition",
"Transition",
"transition-group",
"TransitionGroup",
"keep-alive",
"KeepAlive",
"teleport",
"Teleport",
"suspense",
"Suspense",
])
const BUILTIN_DIRECTIVES = new Set([
"bind",
"on",
"text",
"html",
"show",
"if",
"else",
"else-if",
"for",
"model",
"slot",
"pre",
"cloak",
"once",
"memo",
"is",
])
/**
* @see https://github.com/vuejs/core/blob/48de8a42b7fed7a03f7f1ff5d53d6a704252cafe/packages/shared/src/domTagConfig.ts#L5-L28
*/
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element
const HTML_TAGS =
"html,body,base,head,link,meta,style,title,address,article,aside,footer," +
"header,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption," +
"figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code," +
"data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup," +
"time,u,var,wbr,area,audio,map,track,video,embed,object,param,source," +
"canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td," +
"th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup," +
"option,output,progress,select,textarea,details,dialog,menu," +
"summary,template,blockquote,iframe,tfoot"
// https://developer.mozilla.org/en-US/docs/Web/SVG/Element
const SVG_TAGS =
"svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile," +
"defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer," +
"feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap," +
"feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR," +
"feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset," +
"fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter," +
"foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask," +
"mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern," +
"polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol," +
"text,textPath,title,tspan,unknown,use,view"
const NATIVE_TAGS = new Set([...HTML_TAGS.split(","), ...SVG_TAGS.split(",")])
const COMPILER_MACROS_AT_ROOT = new Set([
"defineProps",
"defineEmits",
"defineExpose",
"withDefaults",
// Added in vue 3.3
"defineOptions",
"defineSlots",
])
/**
* `casing.camelCase()` converts the beginning to lowercase,
* but does not convert the case of the beginning character when converting with Vue3.
* @see https://github.com/vuejs/vue-next/blob/48de8a42b7fed7a03f7f1ff5d53d6a704252cafe/packages/shared/src/index.ts#L109
*/
function camelize(str: string) {
return str.replace(/-(\w)/gu, (_, c) => (c ? c.toUpperCase() : ""))
}
function capitalize(str: string) {
return str[0].toUpperCase() + str.slice(1)
}
/**
* Analyze `<script setup>` scope.
* This method does the following process:
*
* 1. Add a virtual reference to the variables used in the template to mark them as used.
* (This is the same way typescript-eslint marks a `React` variable.)
*
* 2. If compiler macros were used, add these variables as global variables.
*/
export function analyzeScriptSetupScope(
scopeManager: escopeTypes.ScopeManager,
templateBody: VElement | undefined,
df: VDocumentFragment,
_parserOptions: ParserOptions,
): void {
analyzeUsedInTemplateVariables(scopeManager, templateBody, df)
analyzeCompilerMacrosVariables(scopeManager)
}
function extractVariables(scopeManager: escopeTypes.ScopeManager) {
const scriptVariables = new Map<string, escopeTypes.Variable>()
const globalScope = scopeManager.globalScope
if (!globalScope) {
return scriptVariables
}
for (const variable of globalScope.variables) {
scriptVariables.set(variable.name, variable)
}
const moduleScope = globalScope.childScopes.find(
(scope) => scope.type === "module",
)
for (const variable of (moduleScope && moduleScope.variables) || []) {
scriptVariables.set(variable.name, variable)
}
return scriptVariables
}
/**
* Analyze the variables used in the template.
* Add a virtual reference to the variables used in the template to mark them as used.
* (This is the same way typescript-eslint marks a `React` variable.)
*/
function analyzeUsedInTemplateVariables(
scopeManager: escopeTypes.ScopeManager,
templateBody: VElement | undefined,
df: VDocumentFragment,
) {
const scriptVariables = extractVariables(scopeManager)
const markedVariables = new Set<string>()
/**
* @see https://github.com/vuejs/vue-next/blob/48de8a42b7fed7a03f7f1ff5d53d6a704252cafe/packages/compiler-core/src/transforms/transformElement.ts#L335
*/
function markSetupReferenceVariableAsUsed(name: string) {
if (scriptVariables.has(name)) {
markVariableAsUsed(name)
return true
}
const camelName = camelize(name)
if (scriptVariables.has(camelName)) {
markVariableAsUsed(camelName)
return true
}
const pascalName = capitalize(camelName)
if (scriptVariables.has(pascalName)) {
markVariableAsUsed(pascalName)
return true
}
return false
}
function markVariableAsUsed(nameOrRef: string | Reference) {
let name: string
let isValueReference: boolean | undefined
let isTypeReference: boolean | undefined
if (typeof nameOrRef === "string") {
name = nameOrRef
} else {
name = nameOrRef.id.name
isValueReference = nameOrRef.isValueReference
isTypeReference = nameOrRef.isTypeReference
}
const variable = scriptVariables.get(name)
if (!variable || variable.identifiers.length === 0) {
return
}
if (markedVariables.has(name)) {
return
}
markedVariables.add(name)
const reference = new (getEslintScope().Reference)()
;(reference as any).vueUsedInTemplate = true // Mark for debugging.
reference.from = variable.scope
reference.identifier = variable.identifiers[0]
reference.isWrite = () => false
reference.isWriteOnly = () => false
reference.isRead = () => true
reference.isReadOnly = () => true
reference.isReadWrite = () => false
// For typescript-eslint
reference.isValueReference = isValueReference
reference.isTypeReference = isTypeReference
variable.references.push(reference)
reference.resolved = variable
if (reference.isTypeReference) {
// @typescript-eslint/no-unused-vars treats type references at the same position as recursive references,
// so without this flag it will be marked as unused.
;(variable as any).eslintUsed = true
}
}
function processVExpressionContainer(node: VExpressionContainer) {
for (const reference of node.references.filter(
(ref) => ref.variable == null,
)) {
markVariableAsUsed(reference)
}
}
function processVElement(node: VElement) {
if (
(node.rawName === node.name && NATIVE_TAGS.has(node.rawName)) ||
BUILTIN_COMPONENTS.has(node.rawName)
) {
return
}
if (!markSetupReferenceVariableAsUsed(node.rawName)) {
// Check namespace
// https://github.com/vuejs/vue-next/blob/48de8a42b7fed7a03f7f1ff5d53d6a704252cafe/packages/compiler-core/src/transforms/transformElement.ts#L306
const dotIndex = node.rawName.indexOf(".")
if (dotIndex > 0) {
markSetupReferenceVariableAsUsed(
node.rawName.slice(0, dotIndex),
)
}
}
}
function processVAttribute(node: VAttribute | VDirective) {
if (node.directive) {
if (BUILTIN_DIRECTIVES.has(node.key.name.name)) {
return
}
markSetupReferenceVariableAsUsed(`v-${node.key.name.rawName}`)
} else if (node.key.name === "ref" && node.value) {
markVariableAsUsed(node.value.value)
}
}
if (templateBody) {
// Analyze `<template>`
traverseNodes(templateBody, {
enterNode(node) {
if (node.type === "VExpressionContainer") {
processVExpressionContainer(node)
} else if (node.type === "VElement") {
processVElement(node)
} else if (node.type === "VAttribute") {
processVAttribute(node)
}
},
leaveNode() {
/* noop */
},
})
}
// Analyze CSS v-bind()
for (const child of df.children) {
if (child.type === "VElement" && child.name === "style") {
for (const node of child.children) {
if (node.type === "VExpressionContainer") {
processVExpressionContainer(node)
}
}
}
}
}
/**
* Analyze compiler macros.
* If compiler macros were used, add these variables as global variables.
*/
function analyzeCompilerMacrosVariables(
scopeManager: escopeTypes.ScopeManager,
) {
const globalScope = scopeManager.globalScope
if (!globalScope) {
return
}
const compilerMacroVariables = new Map<string, escopeTypes.Variable>()
function addCompilerMacroVariable(reference: escopeTypes.Reference) {
const name = reference.identifier.name
let variable = compilerMacroVariables.get(name)
if (!variable) {
variable = new (getEslintScope().Variable)()
variable.name = name
variable.scope = globalScope
globalScope.variables.push(variable)
globalScope.set.set(name, variable)
compilerMacroVariables.set(name, variable)
}
// Links the variable and the reference.
reference.resolved = variable
variable.references.push(reference)
}
const newThrough: escopeTypes.Reference[] = []
for (const reference of globalScope.through) {
if (COMPILER_MACROS_AT_ROOT.has(reference.identifier.name)) {
if (
reference.from.type === "global" ||
reference.from.type === "module"
) {
addCompilerMacroVariable(reference)
// This reference is removed from `Scope#through`.
continue
}
}
newThrough.push(reference)
}
globalScope.through = newThrough
}