Rewrites all provides and requires in the given namespace.

<p>Call this instead of {@link #collectProvidedNames(Node, Node)} if you want rewriting.
503955
void rewriteProvidesAndRequires(Node externs, Node root) {
    checkState(!hasRewritingOccurred, "Cannot call rewriteProvidesAndRequires twice per instance");
    hasRewritingOccurred = true;

    collectProvidedNames(externs, root);

    for (ProvidedName pn : providedNames.values()) {
      pn.replace();
    }
    deleteNamespaceInitializationsFromPreviousProvides();

    if (requiresLevel.isOn()) {
      for (UnrecognizedRequire r : unrecognizedRequires) {
        checkForLateOrMissingProvide(r);
      }
    }

    for (Node closureRequire : requiresToBeRemoved) {
      compiler.reportChangeToEnclosingScope(closureRequire);
      closureRequire.detach();
    }
    for (Node forwardDeclare : forwardDeclaresToRemove) {
      NodeUtil.deleteNode(forwardDeclare, compiler);
    }
  }
490900
public static void rewriteContent(@NotNull Element parent, @NotNull RewriteContentHandler rewriteContentHandler) {

    // iterate through content list and build new content list
    List<Content> originalContent = parent.getContent();
    List<Content> newContent = new ArrayList<Content>();
    for (Content contentElement : originalContent) {

      // handle element
      if (contentElement instanceof Element) {
        Element element = (Element)contentElement;

        // check if rewrite is needed for element
        List<Content> rewriteContent = rewriteContentHandler.rewriteElement(element);
        if (rewriteContent != null) {
          // element was removed
          if (rewriteContent.isEmpty()) {
            // do not add to newContent
          }

          // element is the same - rewrite child elements
          else if (rewriteContent.size() == 1 && rewriteContent.get(0) == element) { //NOPMD
            rewriteContent(element, rewriteContentHandler);
            newContent.add(element);
          }

          // element was replaced with other content - rewrite and add instead
          else {
            for (Content newContentItem : rewriteContent) {
              if (newContentItem instanceof Element) {
                Element newElement = (Element)newContentItem;
                rewriteContent(newElement, rewriteContentHandler);
              }
              newContent.add(newContentItem.clone());
            }
          }
        }

        // nothing to rewrite - do nothing, but rewrite child element
        else {
          rewriteContent(element, rewriteContentHandler);
          newContent.add(element);
        }

      }

      // handle text node
      else if (contentElement instanceof Text) {
        Text text = (Text)contentElement;

        // check if rewrite is needed for text node
        List<Content> rewriteContent = rewriteContentHandler.rewriteText(text);
        if (rewriteContent != null) {
          // element was removed
          if (rewriteContent.isEmpty()) {
            // do not add to newContent
          }

          // element is the same - ignore
          else if (rewriteContent.size() == 1 && rewriteContent.get(0) == text) { //NOPMD
            // add original element
            newContent.add(text);
          }

          // element was replaced with other content - add instead
          else {
            for (Content newContentItem : rewriteContent) {
              newContent.add(newContentItem.clone());
            }
          }
        }

        // nothing to rewrite - do nothing, but add original text element
        else {
          newContent.add(text);
        }

      }

      // unknown element - just add to new content
      else {
        newContent.add(contentElement);
      }

    }

    // replace original content with new content
    parent.removeContent();
    parent.addContent(newContent);

  }
700806
private void rewriteInternal(
      final BatchHelper batchHelper,
      final KeySetView<IOException, Boolean> innerExceptions,
      final String srcBucketName, final String srcObjectName,
      final String dstBucketName, final String dstObjectName)
      throws IOException {
    Storage.Objects.Rewrite rewriteObject =
        configureRequest(
            gcs.objects().rewrite(srcBucketName, srcObjectName, dstBucketName, dstObjectName, null),
            srcBucketName);
    if (storageOptions.getMaxBytesRewrittenPerCall() > 0) {
      rewriteObject.setMaxBytesRewrittenPerCall(storageOptions.getMaxBytesRewrittenPerCall());
    }

    // TODO(b/79750454) do not batch rewrite requests because they time out in batches.
    batchHelper.queue(
        rewriteObject,
        new JsonBatchCallback<RewriteResponse>() {
          @Override
          public void onSuccess(RewriteResponse rewriteResponse, HttpHeaders responseHeaders) {
            String srcString = StorageResourceId.createReadableString(srcBucketName, srcObjectName);
            String dstString = StorageResourceId.createReadableString(dstBucketName, dstObjectName);

            if (rewriteResponse.getDone()) {
              logger.atFine().log("Successfully copied %s to %s", srcString, dstString);
            } else {
              // If an object is very large, we need to continue making successive calls to
              // rewrite until the operation completes.
              logger.atFine().log(
                  "Copy (%s to %s) did not complete. Resuming...", srcString, dstString);
              try {
                Storage.Objects.Rewrite rewriteObjectWithToken =
                    configureRequest(
                        gcs.objects()
                            .rewrite(
                                srcBucketName, srcObjectName, dstBucketName, dstObjectName, null),
                        srcBucketName);
                if (storageOptions.getMaxBytesRewrittenPerCall() > 0) {
                  rewriteObjectWithToken.setMaxBytesRewrittenPerCall(
                      storageOptions.getMaxBytesRewrittenPerCall());
                }
                rewriteObjectWithToken.setRewriteToken(rewriteResponse.getRewriteToken());
                batchHelper.queue(rewriteObjectWithToken, this);
              } catch (IOException e) {
                innerExceptions.add(e);
              }
            }
          }

          @Override
          public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
            onCopyFailure(innerExceptions, e, srcBucketName, srcObjectName);
          }
        });
  }
519045
public final void rewriteXml(
        Writer out,
        String xmlFile,
        String aloneTags[]
    ) {
        rewriteXml(
            out,
            xmlFile,
            aloneTags,
            false
        );
    }
1009334
private boolean isEligibleDefinitionSite(String name, Node definitionSite) {
    switch (definitionSite.getToken()) {
      case GETPROP:
      case MEMBER_FUNCTION_DEF:
      case STRING_KEY:
        break;

      default:
        // No other node types are supported.
        throw new IllegalArgumentException(definitionSite.toString());
    }

    // Exporting a method prevents rewrite.
    CodingConvention codingConvention = compiler.getCodingConvention();
    if (codingConvention.isExported(name)) {
      return false;
    }

    if (!isPrototypeMethodDefinition(definitionSite)) {
      return false;
    }

    return true;
  }
670651
Map<String, DefineInfo> collectDefines(Node externs, Node root) {
    GlobalNamespace namespace = null;
    if (namespaceSupplier != null) {
      namespace = namespaceSupplier.get();
    }
    if (namespace == null) {
      namespace = new GlobalNamespace(compiler, externs, root);
    }

    // namespace =
    //     namespaceSupplier != nul
    //         ? namespaceSupplier.get()
    //         : new GlobalNamespace(compiler, externs, root);

    // Find all the global names with a @define annotation
    List<Name> listOfDefines = new ArrayList<>();
    for (Name name : namespace.getNameIndex().values()) {
      Ref decl = name.getDeclaration();
      if (name.getJSDocInfo() != null && name.getJSDocInfo().isDefine()) {
        // Process defines should not depend on check types being enabled,
        // so we look for the JSDoc instead of the inferred type.
        if (isValidDefineType(name.getJSDocInfo().getType())) {
          listOfDefines.add(name);
        } else {
          JSError error = JSError.make(decl.getNode(), INVALID_DEFINE_TYPE_ERROR);
          compiler.report(error);
        }
      } else {
        for (Ref ref : name.getRefs()) {
          if (ref == decl) {
            // Declarations were handled above.
            continue;
          }

          Node n = ref.getNode();
          Node parent = ref.getNode().getParent();
          JSDocInfo info = n.getJSDocInfo();
          if (info == null && parent.isVar() && parent.hasOneChild()) {
            info = parent.getJSDocInfo();
          }

          if (info != null && info.isDefine()) {
            listOfDefines.add(name);
            break;
          }
        }
      }
    }

    CollectDefines pass = new CollectDefines(namespace, listOfDefines);
    NodeTraversal.traverseRoots(compiler, pass, externs, root);
    return pass.allDefines;
  }
1326358
@SuppressWarnings({ "unchecked", "unused" })
  private static void rewriteMergeList(String key, String subKey,
      NamedList<Object> snl, NamedList<Object> tnl) {
    for (int i = 0; i < tnl.size(); i++) {
      Object item = snl.get(tnl.getName(i));
      if (item != null && tnl.getVal(i) instanceof NamedList) {
        NamedList<Object> tnnl = (NamedList<Object>) tnl.getVal(i);
        Object o = tnnl.get(key);
        NamedList<Object> tnnnl;
        if (o != null && o instanceof NamedList) {
          tnnnl = (NamedList<Object>) o;
        } else {
          tnnnl = new SimpleOrderedMap<>();
          tnnl.add(key, tnnnl);
        }
        tnnnl.add(subKey, item);
      }
    }
  }
501924
@Override
	public void rebind(Name name, Object obj) throws NamingException
    {
        if (name.isEmpty())
            throw new InvalidNameException("Cannot bind empty name");

        // Extract components that belong to this namespace
        String nm = name.toString();

        // Add object to internal hash table
        bindings.put(nm, obj);
    }
296425
private void rewriteReturns(Node fnNode) {
    checkState(fnNode.isFunction());
    final Node body = fnNode.getLastChild();
    NodeUtil.visitPostOrder(
      body,
      new NodeUtil.Visitor() {
        @Override
        public void visit(Node n) {
          if (n.isReturn() && n.hasOneChild()) {
            Node result = n.getFirstChild();
            boolean keepValue = !isRemovableValue(result);
            result.detach();
            if (keepValue) {
              n.getParent().addChildBefore(IR.exprResult(result).srcref(result), n);
            } else {
              NodeUtil.markFunctionsDeleted(result, compiler);
            }
            compiler.reportChangeToEnclosingScope(body);
          }
        }
      },
      new NodeUtil.MatchShallowStatement());
  }
660960
public void xmlns(Map<String, String> definition) {
        Assert.notNull(namespaceHandlerResolver, "You cannot define a Spring namespace without a [namespaceHandlerResolver] set");
        if (definition.isEmpty()) {
            return;
        }

        for (Map.Entry<String, String> entry : definition.entrySet()) {
            String namespace = entry.getKey();
            String uri = entry.getValue() == null ? null : entry.getValue();

            Assert.notNull(uri, "Namespace definition cannot supply a null URI");

            final NamespaceHandler namespaceHandler = namespaceHandlerResolver.resolve(uri);
            if (namespaceHandler == null) {
                throw new BeanDefinitionParsingException(
                      new Problem("No namespace handler found for URI: " + uri,
                            new Location(readerContext.getResource())));
            }
            namespaceHandlers.put(namespace, namespaceHandler);
            namespaces.put(namespace, uri);
        }
    }
779816
private void handleCandidateProvideDefinition(NodeTraversal t, Node n, Node parent) {
    if (t.inGlobalHoistScope()) {
      String name = null;
      if (n.isName() && NodeUtil.isNameDeclaration(parent)) {
        name = n.getString();
      } else if (n.isAssign() && parent.isExprResult()) {
        name = n.getFirstChild().getQualifiedName();
      }

      if (name != null) {
        if (parent.getBooleanProp(Node.IS_NAMESPACE)) {
          // TODO(b/128361464): stop including goog.module exports in this case.
          processProvideFromPreviousPass(t, name, parent);
        } else {
          ProvidedName pn = providedNames.get(name);
          if (pn != null) {
            pn.addDefinition(parent, t.getModule());
          }
        }
      }
    }
  }
1223375
private void rewriteCall(Node getprop, String newMethodName) {
    checkArgument(getprop.isGetProp(), getprop);
    Node call = getprop.getParent();
    checkArgument(call.isCall(), call);
    Node receiver = getprop.getFirstChild();

    // This rewriting does not exactly preserve order of operations; the newly inserted static
    // method name will be resolved before `receiver` is evaluated. This is known to be safe due
    // to the eligibility checks earlier in the pass.
    //
    // We choose not to do a full-fidelity rewriting (e.g. using `ExpressionDecomposer`) because
    // doing so means extracting `receiver` into a new variable at each call-site. This  has a
    // significant code-size impact (circa 2018-11-19).

    getprop.removeChild(receiver);
    call.replaceChild(getprop, receiver);
    call.addChildToFront(IR.name(newMethodName).srcref(getprop));

    if (receiver.isSuper()) {
      // Case: `super.foo(a, b)` => `foo(this, a, b)`
      receiver.setToken(Token.THIS);
    }

    call.putBooleanProp(Node.FREE_CALL, true);
    compiler.reportChangeToEnclosingScope(call);
  }
809420
public List<NodeRecord> loadNodes (String namespace, boolean includeShutdown)
    {
        // we specifically avoid caching this query because we want the servers to always see the
        // most up to date set of nodes
        Query<NodeRecord> query = from(NodeRecord.class).noCache();
        List<SQLExpression<?>> conditions = Lists.newArrayList();
        if (!StringUtil.isBlank(namespace)) {
            conditions.add(NodeRecord.NODE_NAME.like(namespace + "%"));
        }
        if (!includeShutdown) {
            conditions.add(Ops.not(NodeRecord.SHUTDOWN));
        }
        return (conditions.isEmpty() ? query : query.where(conditions)).select();
    }
262495
public void setNamespace(String prefix, String uri) {
		Namespace namespace = new Namespace(prefix, uri);
		this.namespace.add(namespace);
	}
964260
Map<String, ProvidedName> collectProvidedNames(Node externs, Node root) {
    if (this.providedNames.isEmpty()) {
      // goog is special-cased because it is provided in Closure's base library.
      providedNames.put(GOOG, new ProvidedName(GOOG, null, null, false /* implicit */, false));
      NodeTraversal.traverseRoots(compiler, new CollectDefinitions(), externs, root);
    }
    return this.providedNames;
  }
143352
public boolean compete(NamespaceSpecification other) {
    // if no wildcard for other then we check coverage
    if ("".equals(other.wildcard)) {
      return covers(other.ns);
    }
    // split the namespaces at wildcards     
    String[] otherParts = split(other.ns, other.wildcard);
    
    // if the given namepsace specification does not use its wildcard
    // then we just look if the current namespace specification covers it
    if (otherParts.length == 1) {
      return covers(other.ns);
    }
    // if no wildcard for the current namespace specification
    if ("".equals(wildcard)) {
      return other.covers(ns);
    }
    // also for the current namespace specification
    String[] parts = split(ns, wildcard); 
    // now check if the current namespace specification is just an URI
    if (parts.length == 1) {
      return other.covers(ns);
    }
    // now each namespace specification contains wildcards
    // suppose we have 
    // ns   = a1*a2*...*an 
    // and 
    // other.ns = b1*b2*...*bm
    // then we only need to check matchPrefix(a1, b1) and matchPrefix(an, bn) where
    // matchPrefix(a, b) means a starts with b or b starts with a.
    return matchPrefix(parts[0], otherParts[0])
           && matchPrefix(parts[parts.length - 1], otherParts[otherParts.length - 1]);
  }
1304588
private Map<String,Namespace> buildByPrefixMap()
    {
        int len = mNamespaces.size();
        if (len == 0) {
            return Collections.emptyMap();
        }

        LinkedHashMap<String,Namespace> m = new LinkedHashMap<String,Namespace>(1 + len + (len>>1));
        for (int i = 0; i < len; ++i) {
            Namespace ns = mNamespaces.get(i);
            String prefix = ns.getPrefix();
            if (prefix == null) { // shouldn't happen but...
                prefix = "";
            }
            m.put(prefix, ns);
        }
        return m;
    }