Non-recursive traversal of FunctionElement tree based on TreeWalker to verify that
there are no literal result elements except within a func:result element and that
the func:result element does not contain any following siblings except xsl:fallback.
174443
public void validate(ElemTemplateElement elem, StylesheetHandler handler)
    throws SAXException
  {
    String msg = "";
    while (elem != null)
    { 
      //System.out.println("elem " + elem);
      if (elem instanceof ElemExsltFuncResult 
          && elem.getNextSiblingElem() != null 
          && !(elem.getNextSiblingElem() instanceof ElemFallback))
      {
        msg = "func:result has an illegal following sibling (only xsl:fallback allowed)";
        handler.error(msg, new SAXException(msg));
      }
      
      if((elem instanceof ElemApplyImport
	 || elem instanceof ElemApplyTemplates
	 || elem instanceof ElemAttribute
	 || elem instanceof ElemCallTemplate
	 || elem instanceof ElemComment
	 || elem instanceof ElemCopy
	 || elem instanceof ElemCopyOf
	 || elem instanceof ElemElement
	 || elem instanceof ElemLiteralResult
	 || elem instanceof ElemNumber
	 || elem instanceof ElemPI
	 || elem instanceof ElemText
	 || elem instanceof ElemTextLiteral
	 || elem instanceof ElemValueOf)
	&& !(ancestorIsOk(elem)))
      {
        msg ="misplaced literal result in a func:function container.";
        handler.error(msg, new SAXException(msg));
      }
      ElemTemplateElement nextElem = elem.getFirstChildElem();
      while (nextElem == null)
      {
        nextElem = elem.getNextSiblingElem();
        if (nextElem == null)
          elem = elem.getParentElem();
        if (elem == null || elem instanceof ElemExsltFunction)
          return; // ok
      }  
      elem = nextElem;
    }
  }
718106
function isActuallyCombinator(combinatorNode) {
  // `.foo  /*comment*/, .bar`
  //      ^^
  // If include comments, this spaces is a combinator, but it is not combinators.
  if (!/^\s+$/.test(combinatorNode.value)) {
    return true;
  }

  let next = combinatorNode.next();

  while (skipTest(next)) {
    next = next.next();
  }

  if (isNonTarget(next)) {
    return false;
  }

  let prev = combinatorNode.prev();

  while (skipTest(prev)) {
    prev = prev.prev();
  }

  if (isNonTarget(prev)) {
    return false;
  }

  return true;

  function skipTest(node) {
    if (!node) {
      return false;
    }

    if (node.type === "comment") {
      return true;
    }

    if (node.type === "combinator" && /^\s+$/.test(node.value)) {
      return true;
    }

    return false;
  }

  function isNonTarget(node) {
    if (!node) {
      return true;
    }

    if (node.type === "combinator" && !/^\s+$/.test(node.value)) {
      return true;
    }

    return false;
  }
}
910972
function checkIfWithoutElse(node) {
            const parent = node.parent;

            /*
             * Fixing this would require splitting one statement into two, so no error should
             * be reported if this node is in a position where only one statement is allowed.
             */
            if (!astUtils.STATEMENT_LIST_PARENTS.has(parent.type)) {
                return;
            }

            const consequents = [];
            let alternate;

            for (let currentNode = node; currentNode.type === "IfStatement"; currentNode = currentNode.alternate) {
                if (!currentNode.alternate) {
                    return;
                }
                consequents.push(currentNode.consequent);
                alternate = currentNode.alternate;
            }

            if (consequents.every(alwaysReturns)) {
                displayReport(alternate);
            }
        }
290046
function chainStepsNoError() {
	var steps = slice.call(arguments).map(function(step) {
		return notHandlingError(step);
	});
	return chainSteps.apply(null, steps);
}
1193227
private void visitFallbackFunctionCall(NodeTraversal t, Node call) {
    // Check to make sure the function call looks like:
    // goog.getMsgWithFallback(MSG_1, MSG_2);
    if (call.getChildCount() != 3
        || !call.getSecondChild().isName()
        || !call.getLastChild().isName()) {
      compiler.report(JSError.make(call, BAD_FALLBACK_SYNTAX));
      return;
    }

    Node firstArg = call.getSecondChild();
    String name = firstArg.getOriginalName();
    if (name == null) {
      name = firstArg.getString();
    }
    JsMessage firstMessage = getTrackedMessage(t, name);
    if (firstMessage == null) {
      compiler.report(JSError.make(firstArg, FALLBACK_ARG_ERROR, name));
      return;
    }

    Node secondArg = firstArg.getNext();
    name = secondArg.getOriginalName();
    if (name == null) {
      name = secondArg.getString();
    }
    JsMessage secondMessage = getTrackedMessage(t, name);
    if (secondMessage == null) {
      compiler.report(JSError.make(secondArg, FALLBACK_ARG_ERROR, name));
      return;
    }

    processMessageFallback(call, firstMessage, secondMessage);
  }
960128
function traverseTopDown(fn) {
    var result, i;
    result = fn.call(this);
    if(result)
        return result;
    if (this instanceof tree.ConsNode || this instanceof tree.ListNode) {
        for (i = 0; i < this.length; i++) {
            traverseTopDown.call(this[i], fn);
        }
    }
    return this;
}
1077326
function(dfd, opts, parent, pathSegList) {
			var deferredList,
				i,
				key,
				node,
				remainMap,
				tmpParent,
				segList,
				subDfd,
				self = this;

			function __findChild(parent, key) {
				// console.log("__findChild", key, parent);
				var i,
					l,
					cl = parent.children;

				if (cl) {
					for (i = 0, l = cl.length; i < l; i++) {
						if (opts.matchKey(cl[i], key)) {
							return cl[i];
						}
					}
				}
				return null;
			}

			// console.log("_loadKeyPathImpl, parent=", parent, ", pathSegList=", pathSegList);

			// Pass 1:
			// Handle all path segments for nodes that are already loaded.
			// Collect distinct top-most lazy nodes in a map.
			// Note that we can use node.key to de-dupe entries, even if a custom matcher would
			// look for other node attributes.
			// map[node.key] => {node: node, pathList: [list of remaining rest-paths]}
			remainMap = {};

			for (i = 0; i < pathSegList.length; i++) {
				segList = pathSegList[i];
				// target = targetList[i];

				// Traverse and pop path segments (i.e. keys), until we hit a lazy, unloaded node
				tmpParent = parent;
				while (segList.length) {
					key = segList.shift();
					node = __findChild(tmpParent, key);
					if (!node) {
						this.warn(
							"loadKeyPath: key not found: " +
								key +
								" (parent: " +
								tmpParent +
								")"
						);
						opts.callback(this, key, "error");
						break;
					} else if (segList.length === 0) {
						opts.callback(this, node, "ok");
						break;
					} else if (!node.lazy || node.hasChildren() !== undefined) {
						opts.callback(this, node, "loaded");
						tmpParent = node;
					} else {
						opts.callback(this, node, "loaded");
						key = node.key; //target.segList.join(sep);
						if (remainMap[key]) {
							remainMap[key].pathSegList.push(segList);
						} else {
							remainMap[key] = {
								parent: node,
								pathSegList: [segList],
							};
						}
						break;
					}
				}
			}
			// console.log("_loadKeyPathImpl AFTER pass 1, remainMap=", remainMap);

			// Now load all lazy nodes and continue iteration for remaining paths
			deferredList = [];

			// Avoid jshint warning 'Don't make functions within a loop.':
			function __lazyload(dfd, parent, pathSegList) {
				// console.log("__lazyload", parent, "pathSegList=", pathSegList);
				opts.callback(self, parent, "loading");
				parent
					.load()
					.done(function() {
						self._loadKeyPathImpl
							.call(self, dfd, opts, parent, pathSegList)
							.always(_makeResolveFunc(dfd, self));
					})
					.fail(function(errMsg) {
						self.warn("loadKeyPath: error loading lazy " + parent);
						opts.callback(self, node, "error");
						dfd.rejectWith(self);
					});
			}
			// remainMap contains parent nodes, each with a list of relative sub-paths.
			// We start loading all of them now, and pass the the list to each loader.
			for (var nodeKey in remainMap) {
				var remain = remainMap[nodeKey];
				// console.log("for(): remain=", remain, "remainMap=", remainMap);
				// key = remain.segList.shift();
				// node = __findChild(remain.parent, key);
				// if (node == null) {  // #576
				// 	// Issue #576, refactored for v2.27:
				// 	// The root cause was, that sometimes the wrong parent was used here
				// 	// to find the next segment.
				// 	// Falling back to getNodeByKey() was a hack that no longer works if a custom
				// 	// matcher is used, because we cannot assume that a single segment-key is unique
				// 	// throughout the tree.
				// 	self.error("loadKeyPath: error loading child by key '" + key + "' (parent: " + target.parent + ")", target);
				// 	// 	node = self.getNodeByKey(key);
				// 	continue;
				// }
				subDfd = new $.Deferred();
				deferredList.push(subDfd);
				__lazyload(subDfd, remain.parent, remain.pathSegList);
			}
			// Return a promise that is resolved, when ALL paths were loaded
			return $.when.apply($, deferredList).promise();
		}
497091
function inferenceMatchResult( ast, session ) {

    let inference;
    function sometimesMatch( node ) {

        node.match = 0;

        return node.match;

    }
    function alwaysMatch( node ) {

        inference( node.expression );

        node.match = 1;

        return node.match;

    }

    function inferenceExpression( node ) {

        node.match = inference( node.expression );

        return node.match;

    }
    function inferenceElements( elements, forChoice ) {

        const length = elements.length;
        let always = 0;
        let never = 0;

        for ( let i = 0; i < length; ++i ) {

            const result = inference( elements[ i ] );

            if ( result > 0 ) {

                ++always;

            }
            if ( result < 0 ) {

                ++never;

            }

        }

        if ( always === length ) {

            return 1;

        }
        if ( forChoice ) {

            return never === length ? -1 : 0;

        }

        return never > 0 ? -1 : 0;

    }

    inference = session.buildVisitor( {
        rule( node ) {

            let oldResult;
            let count = 0;

            if ( typeof node.match === "undefined" ) {

                node.match = 0;
                do {

                    oldResult = node.match;
                    node.match = inference( node.expression );
                    // 6 == 3! -- permutations count for all transitions from one match
                    // state to another.
                    // After 6 iterations the cycle with guarantee begins
                    // istanbul ignore next
                    if ( ++count > 6 ) {

                        session.error(
                            "Infinity cycle detected when trying to evaluate node match result",
                            node.location
                        );

                    }

                } while ( oldResult !== node.match );

            }

            return node.match;

        },
        named:        inferenceExpression,
        choice( node ) {

            node.match = inferenceElements( node.alternatives, true );

            return node.match;

        },
        action:       inferenceExpression,
        sequence( node ) {

            node.match = inferenceElements( node.elements, false );

            return node.match;

        },
        labeled:      inferenceExpression,
        text:         inferenceExpression,
        simple_and:   inferenceExpression,
        simple_not( node ) {

            node.match = -inference( node.expression );

            return node.match;

        },
        optional:     alwaysMatch,
        zero_or_more: alwaysMatch,
        one_or_more:  inferenceExpression,
        group:        inferenceExpression,
        semantic_and: sometimesMatch,
        semantic_not: sometimesMatch,
        rule_ref( node ) {

            const rule = ast.findRule( node.name );
            node.match = inference( rule );

            return node.match;

        },
        literal( node ) {

            // Empty literal always match on any input
            node.match = node.value.length === 0 ? 1 : 0;

            return node.match;

        },
        class( node ) {

            // Empty character class never match on any input
            node.match = node.parts.length === 0 ? -1 : 0;

            return node.match;

        },
        // |any| not match on empty input
        any:          sometimesMatch
    } );

    inference( ast );

}
96662
function(element) {
			var result = 0;
			var parent = element.parentNode;
			if (parent) {
				var node = parent.firstElementChild;
				while (node) {
					if (node === element) {
						break;
					} else {
						node = node.nextElementSibling;
						result++;
					}
				}
			}
			return result;
		}
907300
function isInReturnStatement(node) {
            for (let currentNode = node; currentNode; currentNode = currentNode.parent) {
                if (
                    currentNode.type === "ReturnStatement" ||
                    (currentNode.type === "ArrowFunctionExpression" && currentNode.body.type !== "BlockStatement")
                ) {
                    return true;
                }
            }

            return false;
        }
562681
function getNonEmptyNeighbour( that, node, goBack ) {
		node = node[ goBack ? 'getPrevious' : 'getNext' ]( function( node ) {
			return ( isTextNode( node ) && !isEmptyTextNode( node ) ) ||
				( isHtml( node ) && !isFlowBreaker( node ) && !isLine( that, node ) );
		} );

		return node;
	}
329386
@Override
  public boolean shouldTraverse(NodeTraversal nodeTraversal, Node n, Node parent) {
    // We automatically traverse a hoisted function body when that function
    // is first referenced, so that the reference lists are in the right order.
    //
    // TODO(nicksantos): Maybe generalize this to a continuation mechanism
    // like in RemoveUnusedCode.
    if (NodeUtil.isHoistedFunctionDeclaration(n)) {
      Node nameNode = n.getFirstChild();
      Var functionVar = nodeTraversal.getScope().getVar(nameNode.getString());
      checkNotNull(functionVar);
      if (finishedFunctionTraverse.contains(functionVar)) {
        return false;
      }
      startedFunctionTraverse.add(functionVar);
    }

    // If node is a new basic block, put on basic block stack
    if (isBlockBoundary(n, parent)) {
      blockStack.add(new BasicBlock(peek(blockStack), n));
    }

    // Add the second x before the first one in "let [x] = x;". VariableReferenceCheck
    // relies on reference order to give a warning.
    if ((n.isDefaultValue() || n.isDestructuringLhs()) && n.hasTwoChildren()) {
      Scope scope = nodeTraversal.getScope();
      nodeTraversal.traverseInnerNode(n.getSecondChild(), n, scope);
      nodeTraversal.traverseInnerNode(n.getFirstChild(), n, scope);
      return false;
    }
    return true;
  }
1241690
function makeFuncArgTree (pt, args, makeSymbolName, forceBraces, allowNakedSymbol) {
  var noBraces = !forceBraces && args.length === 1 && (args[0].type === 'func' || args[0].type === 'lookup' || args[0].type === 'alt' || (allowNakedSymbol && isPlainSymExpr(args[0])))
  return [noBraces ? '' : leftBraceChar, pt.makeRhsTree (args, makeSymbolName), noBraces ? '' : rightBraceChar]
}
807467
private void visitImplicitReturnExpression(NodeTraversal t, Node exprNode) {
    Node enclosingFunction = t.getEnclosingFunction();
    JSType jsType = getJSType(enclosingFunction);
    if (jsType.isFunctionType()) {
      FunctionType functionType = jsType.toMaybeFunctionType();

      JSType expectedReturnType = functionType.getReturnType();
      // if no return type is specified, undefined must be returned
      // (it's a void function)
      if (expectedReturnType == null) {
        expectedReturnType = getNativeType(VOID_TYPE);
      } else if (enclosingFunction.isAsyncFunction()) {
        // Unwrap the async function's declared return type.
        expectedReturnType = Promises.createAsyncReturnableType(typeRegistry, expectedReturnType);
      }

      // Fetch the returned value's type
      JSType actualReturnType = getJSType(exprNode);

      validator.expectCanAssignTo(
          exprNode, actualReturnType, expectedReturnType, "inconsistent return type");
    }
  }
189080
function walkNodesBreadthFirstHelper(ast, f) {
  let childAst = [];
  (ast || []).forEach(node => {
    f(node);
    childAst = childAst.concat(getChildren(node));
  });
  if (childAst.length > 0) {
    walkNodesBreadthFirstHelper(childAst, f);
  }
}
1157424
function checkLastSegment(node) {
            let loc, name;

            /*
             * Skip if it expected no return value or unreachable.
             * When unreachable, all paths are returned or thrown.
             */
            if (!funcInfo.hasReturnValue ||
                funcInfo.codePath.currentSegments.every(isUnreachable) ||
                astUtils.isES5Constructor(node) ||
                isClassConstructor(node)
            ) {
                return;
            }

            // Adjust a location and a message.
            if (node.type === "Program") {

                // The head of program.
                loc = { line: 1, column: 0 };
                name = "program";
            } else if (node.type === "ArrowFunctionExpression") {

                // `=>` token
                loc = context.getSourceCode().getTokenBefore(node.body, astUtils.isArrowToken).loc.start;
            } else if (
                node.parent.type === "MethodDefinition" ||
                (node.parent.type === "Property" && node.parent.method)
            ) {

                // Method name.
                loc = node.parent.key.loc.start;
            } else {

                // Function name or `function` keyword.
                loc = (node.id || node).loc.start;
            }

            if (!name) {
                name = astUtils.getFunctionNameWithKind(node);
            }

            // Reports.
            context.report({
                node,
                loc,
                messageId: "missingReturn",
                data: { name }
            });
        }
436947
function visitTypedFunction(traverse, node, path, state) {
  var klass = getParentClassDeclaration(path);
  var generics = klass && klass.typeParameters ? toLookup(klass.typeParameters.params.map(getName)) : {};
  if (node.typeParameters) {
    generics = mixin(generics, toLookup(node.typeParameters.params.map(getName)));
  }
  var ctx = new Context(state, generics);
  var rest = node.rest ? ', ' + ctx.getType(node.rest.typeAnnotation.typeAnnotation) : '';
  var types = [];
  var params = [];
  node.params.forEach(function (param) {
    var type = ctx.getType(param.typeAnnotation ? param.typeAnnotation.typeAnnotation : null);
    types.push(param.optional ? ctx.getProperty('optional') + '(' + type + ')' : type);
    params.push(param.name);
  });

  utils.catchup(node.body.range[0] + 1, state);

  if (params.length || rest) {
    utils.append(ctx.getProperty('check') + '(arguments, ' + ctx.getProperty('arguments') + '([' + types.join(', ') + ']' + rest + '));', state);
  }

  if (node.returnType) {
    var returnType = ctx.getType(node.returnType.typeAnnotation);
    utils.append(' var ret = (function (' + params.join(', ') + ') {', state);
    traverse(node.body, path, state);
    utils.catchup(node.body.range[1] - 1, state);
    utils.append('}).apply(this, arguments); return ' + ctx.getProperty('check') + '(ret, ' + returnType + ');', state);
  } else {
    traverse(node.body, path, state);
  }

  return false;
}