Check a function or method declaration for definite assignment.

@param declaration
@return
499224
@Override
	public ControlFlow visitProperty(Decl.Property declaration, DefinitelyAssignedSet dummy) {
		DefinitelyAssignedSet environment = new DefinitelyAssignedSet();
		// Definitely assigned variables includes all parameters.
		environment = environment.addAll(declaration.getParameters());
		// Iterate through each statement in the body of the function or method,
		// updating the set of definitely assigned variables as appropriate.
		visitExpressions(declaration.getInvariant(),environment);
		//
		return null;
	}
442099
function countDeclarations(declarations) {
            const counts = { uninitialized: 0, initialized: 0 };

            for (let i = 0; i < declarations.length; i++) {
                if (declarations[i].init === null) {
                    counts.uninitialized++;
                } else {
                    counts.initialized++;
                }
            }
            return counts;
        }
937039
function checkParameterInitializer(node) {
            if (ts.getRootDeclaration(node).kind !== 142 /* Parameter */) {
                return;
            }
            var func = ts.getContainingFunction(node);
            visit(node.initializer);
            function visit(n) {
                if (ts.isTypeNode(n) || ts.isDeclarationName(n)) {
                    // do not dive in types
                    // skip declaration names (i.e. in object literal expressions)
                    return;
                }
                if (n.kind === 172 /* PropertyAccessExpression */) {
                    // skip property names in property access expression
                    return visit(n.expression);
                }
                else if (n.kind === 69 /* Identifier */) {
                    // check FunctionLikeDeclaration.locals (stores parameters\function local variable)
                    // if it contains entry with a specified name
                    var symbol = resolveName(n, n.text, 107455 /* Value */ | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined);
                    if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) {
                        return;
                    }
                    if (symbol.valueDeclaration === node) {
                        error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name));
                        return;
                    }
                    // locals map for function contain both parameters and function locals
                    // so we need to do a bit of extra work to check if reference is legal
                    var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
                    if (enclosingContainer === func) {
                        if (symbol.valueDeclaration.kind === 142 /* Parameter */) {
                            // it is ok to reference parameter in initializer if either
                            // - parameter is located strictly on the left of current parameter declaration
                            if (symbol.valueDeclaration.pos < node.pos) {
                                return;
                            }
                            // - parameter is wrapped in function-like entity
                            var current = n;
                            while (current !== node.initializer) {
                                if (ts.isFunctionLike(current.parent)) {
                                    return;
                                }
                                // computed property names/initializers in instance property declaration of class like entities
                                // are executed in constructor and thus deferred
                                if (current.parent.kind === 145 /* PropertyDeclaration */ &&
                                    !(current.parent.flags & 32 /* Static */) &&
                                    ts.isClassLike(current.parent.parent)) {
                                    return;
                                }
                                current = current.parent;
                            }
                        }
                        error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n));
                    }
                }
                else {
                    return ts.forEachChild(n, visit);
                }
            }
        }
963960
function isIdentifierReference(node) {
    const parent = node.parent;

    switch (parent.type) {
        case "LabeledStatement":
        case "BreakStatement":
        case "ContinueStatement":
        case "ArrayPattern":
        case "RestElement":
        case "ImportSpecifier":
        case "ImportDefaultSpecifier":
        case "ImportNamespaceSpecifier":
        case "CatchClause":
            return false;

        case "FunctionDeclaration":
        case "FunctionExpression":
        case "ArrowFunctionExpression":
        case "ClassDeclaration":
        case "ClassExpression":
        case "VariableDeclarator":
            return parent.id !== node;

        case "Property":
        case "MethodDefinition":
            return (
                parent.key !== node ||
                parent.computed ||
                parent.shorthand
            );

        case "AssignmentPattern":
            return parent.key !== node;

        default:
            return true;
    }
}
1096098
private List<Statement> getInitLocation(MethodDeclaration node) {
    List<Statement> stmts = node.getBody().getStatements();
    if (!stmts.isEmpty() && stmts.get(0) instanceof SuperConstructorInvocation) {
      return stmts.subList(0, 1);
    }
    // java.lang.Object supertype is null. All other types should have a super() call.
    assert TypeUtil.isNone(
        ElementUtil.getDeclaringClass(node.getExecutableElement()).getSuperclass())
        : "Constructor didn't have a super() call.";
    return stmts.subList(0, 0);
  }
396023
function shouldSkipAlias(node, declaration) {
        if (node.kind !== ts.SyntaxKind.Identifier) {
            return false;
        }
        if (node.parent === declaration) {
            return true;
        }
        switch (declaration.kind) {
            case ts.SyntaxKind.ImportClause:
            case ts.SyntaxKind.ImportEqualsDeclaration:
                return true;
            case ts.SyntaxKind.ImportSpecifier:
                return declaration.parent.kind === ts.SyntaxKind.NamedImports;
            default:
                return false;
        }
    }
1210874
def is_declaration(self):
        
        if not (self.is_global or self.is_function):
            raise ValueError('expected global or function value, got %s'
                             % (self._kind,))
        return ffi.lib.LLVMPY_IsDeclaration(self)
189620
public void check()
        throws FatalCompileTimeException
    {
        HashSet declsToCheck = new HashSet();

        //
        // First, build up the Set of declarations to check.  We don't want any duplicates.
        //
        for ( int i = 0; i < _atds.length; ++i )
        {
            AnnotationTypeDeclaration atd = _atds[i];
            Declaration[] decls = getAnnotationProcessorEnvironment().getDeclarationsAnnotatedWith( atd );
            for ( int j = 0; j < decls.length; j++ )
            {
                declsToCheck.add( decls[j] );
            }
        }

        // Now, check the declarations.
        check(declsToCheck);
    }
774707
private boolean containsFunctionById(int functionId) {
        if (this instanceof AbstractValueExpression) {
            return false;
        }

        List<AbstractExpression> functionsList = findAllFunctionSubexpressions();
        for (AbstractExpression funcExpr: functionsList) {
            assert(funcExpr instanceof FunctionExpression);
            if (((FunctionExpression)funcExpr).hasFunctionId(functionId)) {
                return true;
            }
        }

        return false;
    }
1118193
private static boolean checkForStateChangeHelper(
      Node n, boolean checkForNewObjects, AbstractCompiler compiler) {
    // Rather than id which ops may have side effects, id the ones
    // that we know to be safe
    switch (n.getToken()) {
      case THROW:
        // Throw is a side-effect by definition.
      case YIELD:
      case AWAIT:
      case FOR_AWAIT_OF:
        // Context switches can conceal side-effects.
      case FOR_OF:
      case FOR_IN:
        // Enhanced for loops are almost always side-effectful; it's not worth checking them
        // further. Particularly, they represent a kind of assignment op.
      case VAR:
      case LET:
      case CONST:
      case EXPORT:
        // Variable declarations are side-effects.
        return true;

      case OBJECTLIT:
      case ARRAYLIT:
      case REGEXP:
        if (checkForNewObjects) {
          return true;
        }
        break;

      case REST:
      case SPREAD:
        if (iteratesImpureIterable(n)) {
          return true;
        }
        break;

      case NAME:
        // TODO(b/129564961): Consider EXPORT declarations.
        if (n.hasChildren()) {
          // This is the left side of a var/let/const
          return true;
        }
        break;

      case FUNCTION:
        // Function expressions don't have side-effects, but function
        // declarations change the namespace. Either way, we don't need to
        // check the children, since they aren't executed at declaration time.
        return checkForNewObjects || isFunctionDeclaration(n);

      case GETTER_DEF:
      case SETTER_DEF:
      case MEMBER_FUNCTION_DEF:
        // simply defining a member function, getter, or setter has no side effects
        return false;

      case CLASS:
        return checkForNewObjects || isClassDeclaration(n)
            // Check the extends clause for side effects.
            || checkForStateChangeHelper(n.getSecondChild(), checkForNewObjects, compiler)
            // Check for class members that are computed properties with side effects.
            || checkForStateChangeHelper(n.getLastChild(), checkForNewObjects, compiler);

      case CLASS_MEMBERS:
        for (Node member = n.getFirstChild(); member != null; member = member.getNext()) {
          if (member.isComputedProp()
              && checkForStateChangeHelper(member.getFirstChild(), checkForNewObjects, compiler)) {
            return true;
          }
        }
        return false;

      case NEW:
        if (checkForNewObjects) {
          return true;
        }

        if (!constructorCallHasSideEffects(n)) {
          // loop below will see if the constructor parameters have
          // side-effects
          break;
        }
        return true;

      case CALL:
        // calls to functions that have no side effects have the no
        // side effect property set.
        if (!functionCallHasSideEffects(n, compiler)) {
          // loop below will see if the function parameters have
          // side-effects
          break;
        }
        return true;

      case TAGGED_TEMPLATELIT:
        // TODO(b/128527671): Inspect the children of the expression for side-effects.
        return functionCallHasSideEffects(n, compiler);

      case CAST:
      case AND:
      case BLOCK:
      case ROOT:
      case EXPR_RESULT:
      case HOOK:
      case IF:
      case PARAM_LIST:
      case NUMBER:
      case OR:
      case THIS:
      case TRUE:
      case FALSE:
      case NULL:
      case STRING:
      case STRING_KEY:
      case SWITCH:
      case TEMPLATELIT_SUB:
      case TRY:
      case EMPTY:
      case TEMPLATELIT:
      case TEMPLATELIT_STRING:
      case COMPUTED_PROP:
        break;

      default:
        if (isSimpleOperator(n)) {
          break;
        }

        if (isAssignmentOp(n)) {
          Node assignTarget = n.getFirstChild();
          if (assignTarget.isName()) {
            return true;
          }

          // Assignments will have side effects if
          // a) The RHS has side effects, or
          // b) The LHS has side effects, or
          // c) A name on the LHS will exist beyond the life of this statement.
          if (checkForStateChangeHelper(n.getFirstChild(), checkForNewObjects, compiler)
              || checkForStateChangeHelper(n.getLastChild(), checkForNewObjects, compiler)) {
            return true;
          }

          if (isGet(assignTarget)) {
            // If the object being assigned to is a local object, don't
            // consider this a side-effect as it can't be referenced
            // elsewhere.  Don't do this recursively as the property might
            // be an alias of another object, unlike a literal below.
            Node current = assignTarget.getFirstChild();
            if (evaluatesToLocalValue(current)) {
              return false;
            }

            // A literal value as defined by "isLiteralValue" is guaranteed
            // not to be an alias, or any components which are aliases of
            // other objects.
            // If the root object is a literal don't consider this a
            // side-effect.
            while (isGet(current)) {
              current = current.getFirstChild();
            }

            return !isLiteralValue(current, true);
          } else {
            // TODO(johnlenz): remove this code and make this an exception. This
            // is here only for legacy reasons, the AST is not valid but
            // preserve existing behavior.
            return !isLiteralValue(assignTarget, true);
          }
        }

        return true;
    }

    for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
      if (checkForStateChangeHelper(c, checkForNewObjects, compiler)) {
        return true;
      }
    }

    return false;
  }
717960
function checkCallExpression(node) {
            // Grammar checking; stop grammar-checking if checkGrammarTypeArguments return true
            checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments);
            var signature = getResolvedSignature(node);
            if (node.expression.kind === 95 /* SuperKeyword */) {
                return voidType;
            }
            if (node.kind === 175 /* NewExpression */) {
                var declaration = signature.declaration;
                if (declaration &&
                    declaration.kind !== 148 /* Constructor */ &&
                    declaration.kind !== 152 /* ConstructSignature */ &&
                    declaration.kind !== 157 /* ConstructorType */ &&
                    !ts.isJSDocConstructSignature(declaration)) {
                    // When resolved signature is a call signature (and not a construct signature) the result type is any, unless
                    // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations
                    // in a JS file
                    // Note:JS inferred classes might come from a variable declaration instead of a function declaration.
                    // In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration.
                    var funcSymbol = node.expression.kind === 69 /* Identifier */ ?
                        getResolvedSymbol(node.expression) :
                        checkExpression(node.expression).symbol;
                    if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 /* Function */ || ts.isDeclarationOfFunctionExpression(funcSymbol))) {
                        return getInferredClassType(funcSymbol);
                    }
                    else if (compilerOptions.noImplicitAny) {
                        error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type);
                    }
                    return anyType;
                }
            }
            // In JavaScript files, calls to any identifier 'require' are treated as external module imports
            if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) {
                return resolveExternalModuleTypeByLiteral(node.arguments[0]);
            }
            return getReturnTypeOfSignature(signature);
        }
431205
private void translatePreconditionMacros(WyilFile.Decl.FunctionOrMethod declaration) {
		Tuple<WyilFile.Expr> invariants = declaration.getRequires();
		//
		for (int i = 0; i != invariants.size(); ++i) {
			// Construct fresh environment for this macro. This is necessary to
			// avoid name clashes with subsequent macros.
			GlobalEnvironment globalEnvironment = new GlobalEnvironment(declaration);
			LocalEnvironment localEnvironment = new LocalEnvironment(globalEnvironment);
			WyalFile.VariableDeclaration[] type = generatePreconditionParameters(declaration, localEnvironment);
			// Translate expression itself
			WyalFile.Stmt.Block clause = translateAsBlock(invariants.get(i), localEnvironment);
			// Capture any free variables. This is necessary to deal with any
			// variable aliases introduced by type test operators.
			clause = captureFreeVariables(declaration, globalEnvironment, clause);
			//
			Name ident = convert(declaration.getQualifiedName(), "_requires_" + i, declaration.getName());
			WyalFile.Declaration md = new WyalFile.Declaration.Named.Macro(ident, type, clause);
			allocate(md, invariants.get(i).getParent(WyilFile.Attribute.Span.class));
		}
	}
651288
function getTypeForBindingElement(declaration) {
            var pattern = declaration.parent;
            var parentType = getTypeForBindingElementParent(pattern.parent);
            // If parent has the unknown (error) type, then so does this binding element
            if (parentType === unknownType) {
                return unknownType;
            }
            // If no type was specified or inferred for parent, or if the specified or inferred type is any,
            // infer from the initializer of the binding element if one is present. Otherwise, go with the
            // undefined or any type of the parent.
            if (!parentType || isTypeAny(parentType)) {
                if (declaration.initializer) {
                    return checkExpressionCached(declaration.initializer);
                }
                return parentType;
            }
            var type;
            if (pattern.kind === 167 /* ObjectBindingPattern */) {
                // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form)
                var name_11 = declaration.propertyName || declaration.name;
                if (isComputedNonLiteralName(name_11)) {
                    // computed properties with non-literal names are treated as 'any'
                    return anyType;
                }
                if (declaration.initializer) {
                    getContextualType(declaration.initializer);
                }
                // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature,
                // or otherwise the type of the string index signature.
                var text = getTextOfPropertyName(name_11);
                type = getTypeOfPropertyOfType(parentType, text) ||
                    isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) ||
                    getIndexTypeOfType(parentType, 0 /* String */);
                if (!type) {
                    error(name_11, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_11));
                    return unknownType;
                }
            }
            else {
                // This elementType will be used if the specific property corresponding to this index is not
                // present (aka the tuple element property). This call also checks that the parentType is in
                // fact an iterable or array (depending on target language).
                var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false);
                if (!declaration.dotDotDotToken) {
                    // Use specific property type when parent is a tuple or numeric index type when parent is an array
                    var propName = "" + ts.indexOf(pattern.elements, declaration);
                    type = isTupleLikeType(parentType)
                        ? getTypeOfPropertyOfType(parentType, propName)
                        : elementType;
                    if (!type) {
                        if (isTupleType(parentType)) {
                            error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length);
                        }
                        else {
                            error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName);
                        }
                        return unknownType;
                    }
                }
                else {
                    // Rest element has an array type with the same element type as the parent type
                    type = createArrayType(elementType);
                }
            }
            // In strict null checking mode, if a default value of a non-undefined type is specified, remove
            // undefined from the final type.
            if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048 /* Undefined */)) {
                type = getTypeWithFacts(type, 131072 /* NEUndefined */);
            }
            return declaration.initializer ?
                getUnionType([type, checkExpressionCached(declaration.initializer)], /*subtypeReduction*/ true) :
                type;
        }
1244359
private ParseTree parseFunctionDeclaration() {
    SourcePosition start = getTreeStartLocation();
    eat(Keywords.FUNCTION.type);
    boolean isGenerator = eatOpt(TokenType.STAR) != null;

    FunctionDeclarationTree.Builder builder =
        FunctionDeclarationTree.builder(FunctionDeclarationTree.Kind.DECLARATION).setName(eatId());
    parseFunctionTail(builder, isGenerator ? FunctionFlavor.GENERATOR : FunctionFlavor.NORMAL);
    return builder.build(getTreeLocation(start));
  }
1172076
public void checkDeclaration(Decl decl) {
		if (decl instanceof Decl.Unit) {
			checkUnit((Decl.Unit) decl);
		} else if (decl instanceof Decl.Import) {
			// Can ignore
		} else if (decl instanceof Decl.StaticVariable) {
			checkStaticVariableDeclaration((Decl.StaticVariable) decl);
		} else if (decl instanceof Decl.Type) {
			checkTypeDeclaration((Decl.Type) decl);
		} else if (decl instanceof Decl.FunctionOrMethod) {
			checkFunctionOrMethodDeclaration((Decl.FunctionOrMethod) decl);
		} else {
			checkPropertyDeclaration((Decl.Property) decl);
		}
	}
1353571
public static boolean isHoistedFunctionDeclaration(Node n) {
    if (isFunctionDeclaration(n)) {
      Node parent = n.getParent();
      return parent.isScript()
          || parent.isModuleBody()
          || parent.getParent().isFunction()
          || parent.isExport();
    }
    return false;
  }
494312
private void movePrototypeDotMethodAssignment(Node destParent, Node functionNode) {
    checkState(functionNode.isFunction(), functionNode);
    Node assignNode = functionNode.getParent();
    checkState(assignNode.isAssign() && functionNode.isSecondChildOf(assignNode), assignNode);
    Node definitionStatement = assignNode.getParent();
    checkState(definitionStatement.isExprResult(), assignNode);

    if (noStubFunctions) {
      // Remove the definition statement from its current location
      Node assignStatementParent = definitionStatement.getParent();
      definitionStatement.detach();
      compiler.reportChangeToEnclosingScope(assignStatementParent);

      // Prepend definition to new chunk
      // Foo.prototype.propName = function() {};
      destParent.addChildToFront(definitionStatement);
      compiler.reportChangeToEnclosingScope(destParent);
    } else {
      int stubId = idGenerator.newId();

      // replace function definition with temporary placeholder so we can clone the whole
      // assignment statement without cloning the function definition itself.
      Node originalDefinitionPlaceholder = astFactory.createEmpty();
      functionNode.replaceWith(originalDefinitionPlaceholder);
      Node newDefinitionStatement = definitionStatement.cloneTree();
      Node newDefinitionPlaceholder =
          newDefinitionStatement // EXPR_RESULT
              .getOnlyChild() // ASSIGN
              .getLastChild(); // EMPTY RHS node

      // convert original assignment statement to
      // owner.prototype.propName = JSCompiler_stubMethod(0);
      Node stubCall = createStubCall(functionNode, stubId);
      originalDefinitionPlaceholder.replaceWith(stubCall);
      compiler.reportChangeToEnclosingScope(definitionStatement);

      // Prepend new definition to new chunk
      // Foo.prototype.propName = JSCompiler_unstubMethod(0, function() {});
      Node unstubCall = createUnstubCall(functionNode, stubId);
      newDefinitionPlaceholder.replaceWith(unstubCall);
      destParent.addChildToFront(newDefinitionStatement);
      compiler.reportChangeToEnclosingScope(destParent);
    }
  }