All files / compiler-sfc/src/script definePropsDestructure.ts

93.93% Statements 124/132
88.38% Branches 137/155
100% Functions 14/14
94.65% Lines 124/131

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365                                                            40x 1x 39x 1x     38x   38x         51x 51x 4x 4x         38x 56x 54x   54x 1x           53x   24x 24x           24x 29x   27x   2x             2x   2x                               35x       35x 35x 35x 35x 35x 35x 35x   35x 51x 51x 51x       27x 27x 27x 15x         27x 27x 15x   27x       38x 38x 38x                   61x 100x 49x 51x       7x 7x 44x           44x                               56x     56x   62x 62x 81x     53x   28x                   49x 49x   818x         21x     797x         17x     780x 4x             15x       2x     13x     2x         2x             11x                 1590x 6x 6x 4x                   35x 35x 35x 35x   817x     817x         21x     796x 796x     796x 15x 15x 15x 14x 14x   15x       777x 1x 1x     1x 1x       776x         3x 3x 3x 3x   3x 3x   3x       773x 8x 8x 8x     765x 255x       92x 15x           776x 776x 15x 761x 8x 753x           4x          
import type {
  BlockStatement,
  Expression,
  Identifier,
  Node,
  ObjectPattern,
  Program,
  VariableDeclaration,
} from '@babel/types'
import { walk } from 'estree-walker'
import {
  BindingTypes,
  TS_NODE_TYPES,
  extractIdentifiers,
  isFunctionType,
  isInDestructureAssignment,
  isReferencedIdentifier,
  isStaticProperty,
  unwrapTSNode,
  walkFunctionParams,
} from '@vue/compiler-dom'
import { genPropsAccessExp } from '@vue/shared'
import { isCallOf, resolveObjectKey } from './utils'
import type { ScriptCompileContext } from './context'
import { DEFINE_PROPS } from './defineProps'
 
export function processPropsDestructure(
  ctx: ScriptCompileContext,
  declId: ObjectPattern,
): void {
  if (ctx.options.propsDestructure === 'error') {
    ctx.error(`Props destructure is explicitly prohibited via config.`, declId)
  } else if (ctx.options.propsDestructure === false) {
    return
  }
 
  ctx.propsDestructureDecl = declId
 
  const registerBinding = (
    key: string,
    local: string,
    defaultValue?: Expression,
  ) => {
    ctx.propsDestructuredBindings[key] = { local, default: defaultValue }
    if (local !== key) {
      ctx.bindingMetadata[local] = BindingTypes.PROPS_ALIASED
      ;(ctx.bindingMetadata.__propsAliases ||
        (ctx.bindingMetadata.__propsAliases = {}))[local] = key
    }
  }
 
  for (const prop of declId.properties) {
    if (prop.type === 'ObjectProperty') {
      const propKey = resolveObjectKey(prop.key, prop.computed)
 
      if (!propKey) {
        ctx.error(
          `${DEFINE_PROPS}() destructure cannot use computed key.`,
          prop.key,
        )
      }
 
      if (prop.value.type === 'AssignmentPattern') {
        // default value { foo = 123 }
        const { left, right } = prop.value
        Iif (left.type !== 'Identifier') {
          ctx.error(
            `${DEFINE_PROPS}() destructure does not support nested patterns.`,
            left,
          )
        }
        registerBinding(propKey, left.name, right)
      } else if (prop.value.type === 'Identifier') {
        // simple destructure
        registerBinding(propKey, prop.value.name)
      } else {
        ctx.error(
          `${DEFINE_PROPS}() destructure does not support nested patterns.`,
          prop.value,
        )
      }
    } else {
      // rest spread
      ctx.propsDestructureRestId = (prop.argument as Identifier).name
      // register binding
      ctx.bindingMetadata[ctx.propsDestructureRestId] =
        BindingTypes.SETUP_REACTIVE_CONST
    }
  }
}
 
/**
 * true -> prop binding
 * false -> local binding
 */
type Scope = Record<string, boolean>
 
export function transformDestructuredProps(
  ctx: ScriptCompileContext,
  vueImportAliases: Record<string, string>,
): void {
  Iif (ctx.options.propsDestructure === false) {
    return
  }
 
  const rootScope: Scope = Object.create(null)
  const scopeStack: Scope[] = [rootScope]
  const functionScopeStack: Scope[] = [rootScope]
  let currentScope: Scope = rootScope
  const excludedIds = new WeakSet<Identifier>()
  const parentStack: Node[] = []
  const propsLocalToPublicMap: Record<string, string> = Object.create(null)
 
  for (const key in ctx.propsDestructuredBindings) {
    const { local } = ctx.propsDestructuredBindings[key]
    rootScope[local] = true
    propsLocalToPublicMap[local] = key
  }
 
  function pushScope(isFunctionScope = false) {
    const scope = (currentScope = Object.create(currentScope))
    scopeStack.push(scope)
    if (isFunctionScope) {
      functionScopeStack.push(scope)
    }
  }
 
  function popScope(isFunctionScope = false) {
    scopeStack.pop()
    if (isFunctionScope) {
      functionScopeStack.pop()
    }
    currentScope = scopeStack[scopeStack.length - 1] || null
  }
 
  function registerLocalBinding(id: Identifier, scope = currentScope) {
    excludedIds.add(id)
    if (scope) {
      scope[id.name] = false
    } else E{
      ctx.error(
        'registerBinding called without active scope, something is wrong.',
        id,
      )
    }
  }
 
  function walkScope(node: Program | BlockStatement, isRoot = false) {
    for (const stmt of node.body) {
      if (stmt.type === 'VariableDeclaration') {
        walkVariableDeclaration(stmt, isRoot)
      } else if (
        stmt.type === 'FunctionDeclaration' ||
        stmt.type === 'ClassDeclaration'
      ) {
        Iif (stmt.declare || !stmt.id) continue
        registerLocalBinding(stmt.id)
      } else Iif (
        stmt.type === 'ExportNamedDeclaration' &&
        stmt.declaration &&
        stmt.declaration.type === 'VariableDeclaration'
      ) {
        walkVariableDeclaration(stmt.declaration, isRoot)
      } else Iif (
        stmt.type === 'LabeledStatement' &&
        stmt.body.type === 'VariableDeclaration'
      ) {
        walkVariableDeclaration(stmt.body, isRoot)
      }
    }
  }
 
  function walkVariableDeclaration(
    stmt: VariableDeclaration,
    isRoot = false,
    scope = stmt.kind === 'var'
      ? functionScopeStack[functionScopeStack.length - 1]
      : currentScope,
  ) {
    Iif (stmt.declare) {
      return
    }
    for (const decl of stmt.declarations) {
      const isDefineProps =
        isRoot && decl.init && isCallOf(unwrapTSNode(decl.init), 'defineProps')
      for (const id of extractIdentifiers(decl.id)) {
        if (isDefineProps) {
          // for defineProps destructure, only exclude them since they
          // are already passed in as knownProps
          excludedIds.add(id)
        } else {
          registerLocalBinding(id, scope)
        }
      }
    }
  }
 
  function walkFunctionScopeVarDeclarations(
    scopeNode: Program | BlockStatement,
    isRoot = false,
  ) {
    const scope = functionScopeStack[functionScopeStack.length - 1]
    walk(scopeNode, {
      enter(node: Node, parent: Node | null) {
        if (
          parent &&
          parent.type.startsWith('TS') &&
          !TS_NODE_TYPES.includes(parent.type)
        ) {
          return this.skip()
        }
 
        if (
          isFunctionType(node) ||
          node.type === 'ClassDeclaration' ||
          node.type === 'ClassExpression'
        ) {
          return this.skip()
        }
 
        if (node.type === 'VariableDeclaration' && node.kind === 'var') {
          walkVariableDeclaration(node, isRoot && parent === scopeNode, scope)
        }
      },
    })
  }
 
  function rewriteId(id: Identifier, parent: Node, parentStack: Node[]) {
    if (
      (parent.type === 'AssignmentExpression' && id === parent.left) ||
      parent.type === 'UpdateExpression'
    ) {
      ctx.error(`Cannot assign to destructured props as they are readonly.`, id)
    }
 
    if (isStaticProperty(parent) && parent.shorthand) {
      // let binding used in a property shorthand
      // skip for destructure patterns
      Eif (
        !(parent as any).inPattern ||
        isInDestructureAssignment(parent, parentStack)
      ) {
        // { prop } -> { prop: __props.prop }
        ctx.s.appendLeft(
          id.end! + ctx.startOffset!,
          `: ${genPropsAccessExp(propsLocalToPublicMap[id.name])}`,
        )
      }
    } else {
      // x --> __props.x
      ctx.s.overwrite(
        id.start! + ctx.startOffset!,
        id.end! + ctx.startOffset!,
        genPropsAccessExp(propsLocalToPublicMap[id.name]),
      )
    }
  }
 
  function checkUsage(node: Node, method: string, alias = method) {
    if (isCallOf(node, alias)) {
      const arg = unwrapTSNode(node.arguments[0])
      if (arg.type === 'Identifier' && currentScope[arg.name]) {
        ctx.error(
          `"${arg.name}" is a destructured prop and should not be passed directly to ${method}(). ` +
            `Pass a getter () => ${arg.name} instead.`,
          arg,
        )
      }
    }
  }
 
  // check root scope first
  const ast = ctx.scriptSetupAst!
  walkFunctionScopeVarDeclarations(ast, true)
  walkScope(ast, true)
  walk(ast, {
    enter(node: Node, parent: Node | null) {
      parent && parentStack.push(parent)
 
      // skip type nodes
      if (
        parent &&
        parent.type.startsWith('TS') &&
        !TS_NODE_TYPES.includes(parent.type)
      ) {
        return this.skip()
      }
 
      checkUsage(node, 'watch', vueImportAliases.watch)
      checkUsage(node, 'toRef', vueImportAliases.toRef)
 
      // function scopes
      if (isFunctionType(node)) {
        pushScope(true)
        walkFunctionParams(node, registerLocalBinding)
        if (node.body.type === 'BlockStatement') {
          walkFunctionScopeVarDeclarations(node.body)
          walkScope(node.body)
        }
        return
      }
 
      // catch param
      if (node.type === 'CatchClause') {
        pushScope()
        Iif (node.param && node.param.type === 'Identifier') {
          registerLocalBinding(node.param)
        }
        walkScope(node.body)
        return
      }
 
      // for loops: loop variable should be scoped to the loop
      if (
        node.type === 'ForOfStatement' ||
        node.type === 'ForInStatement' ||
        node.type === 'ForStatement'
      ) {
        pushScope()
        const varDecl = node.type === 'ForStatement' ? node.init : node.left
        Eif (varDecl && varDecl.type === 'VariableDeclaration') {
          walkVariableDeclaration(varDecl)
        }
        Eif (node.body.type === 'BlockStatement') {
          walkScope(node.body)
        }
        return
      }
 
      // non-function block scopes
      if (node.type === 'BlockStatement' && !isFunctionType(parent!)) {
        pushScope()
        walkScope(node)
        return
      }
 
      if (node.type === 'Identifier') {
        if (
          isReferencedIdentifier(node, parent!, parentStack) &&
          !excludedIds.has(node)
        ) {
          if (currentScope[node.name]) {
            rewriteId(node, parent!, parentStack)
          }
        }
      }
    },
    leave(node: Node, parent: Node | null) {
      parent && parentStack.pop()
      if (isFunctionType(node)) {
        popScope(true)
      } else if (node.type === 'BlockStatement' && !isFunctionType(parent!)) {
        popScope()
      } else if (
        node.type === 'CatchClause' ||
        node.type === 'ForOfStatement' ||
        node.type === 'ForInStatement' ||
        node.type === 'ForStatement'
      ) {
        popScope()
      }
    },
  })
}