/*
We can't use ASTHelpers here. It's in core, which depends on jdk8, so we can't make jdk8 depend
back on core.
425071
@Nullable
  private static Symbol tryGetSymbol(Tree tree) {
    if (tree instanceof JCIdent) {
      return ((JCIdent) tree).sym;
    }
    if (tree instanceof JCFieldAccess) {
      return ((JCFieldAccess) tree).sym;
    }
    if (tree instanceof JCVariableDecl) {
      return ((JCVariableDecl) tree).sym;
    }
    return null;
  }
343701
public static BatchASTFuture analyze(final BatchASTListener listener, final WildcardImportResolver importResolver,
                final Set<String> libraryPaths,
                final Set<String> sourcePaths, Set<Path> sourceFiles)
    {

        final String[] encodings = null;
        final String[] bindingKeys = new String[0];
        final ExecutorService executor = WindupExecutors.newFixedThreadPool(WindupExecutors.getDefaultThreadCount());
        final FileASTRequestor requestor = new FileASTRequestor()
        {
            @Override
            public void acceptAST(String sourcePath, CompilationUnit ast)
            {
                try
                {
                    /*
                     * This super() call doesn't do anything, but we call it just to be nice, in case that ever changes.
                     */
                    super.acceptAST(sourcePath, ast);
                    ReferenceResolvingVisitor visitor = new ReferenceResolvingVisitor(importResolver, ast, sourcePath);
                    ast.accept(visitor);
                    listener.processed(Paths.get(sourcePath), visitor.getJavaClassReferences());
                }
                catch (WindupStopException ex)
                {
                    throw ex;
                }
                catch (Throwable t)
                {
                    listener.failed(Paths.get(sourcePath), t);
                }
            }
        };

        List<List<String>> batches = createBatches(sourceFiles);

        for (final List<String> batch : batches)
        {
            executor.submit(new Callable<Void>()
            {
                @Override
                public Void call() throws Exception
                {
                    ASTParser parser = ASTParser.newParser(AST.JLS8);
                    parser.setBindingsRecovery(false);
                    parser.setResolveBindings(true);
                    Map<String, String> options = JavaCore.getOptions();
                    JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
                    // these options seem to slightly reduce the number of times that JDT aborts on compilation errors
                    options.put(JavaCore.CORE_INCOMPLETE_CLASSPATH, "warning");
                    options.put(JavaCore.COMPILER_PB_ENUM_IDENTIFIER, "warning");
                    options.put(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, "warning");
                    options.put(JavaCore.CORE_CIRCULAR_CLASSPATH, "warning");
                    options.put(JavaCore.COMPILER_PB_ASSERT_IDENTIFIER, "warning");
                    options.put(JavaCore.COMPILER_PB_NULL_SPECIFICATION_VIOLATION, "warning");
                    options.put(JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH, "ignore");
                    options.put(JavaCore.COMPILER_PB_NULL_ANNOTATION_INFERENCE_CONFLICT, "warning");
                    options.put(JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, "warning");
                    options.put(JavaCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE, "warning");

                    parser.setCompilerOptions(options);
                    parser.setEnvironment(libraryPaths.toArray(new String[libraryPaths.size()]),
                                sourcePaths.toArray(new String[sourcePaths.size()]),
                                null,
                                true);

                    parser.createASTs(batch.toArray(new String[batch.size()]), encodings, bindingKeys, requestor, null);
                    return null;
                }
            });
        }

        executor.shutdown();

        return new BatchASTFuture()
        {
            @Override
            public boolean isDone()
            {
                return executor.isTerminated();
            }
        };
    }
800430
Class evalReturnType( CallStack callstack, Interpreter interpreter )
        throws EvalError
    {
        insureNodesParsed();
        if ( returnTypeNode != null )
            return returnTypeNode.evalReturnType( callstack, interpreter );
        else
            return null;
    }
964249
@Override
    String sourceContentFor(String aSource, Boolean nullOnMissing) {
        for (int i = 0; i < this._sections.size(); i++) {
            ParsedSection section = this._sections.get(i);
            String content = section.consumer.sourceContentFor(aSource, true);
            if (content != null) {
                return content;
            }
        }
        if (nullOnMissing != null && nullOnMissing) {
            return null;
        } else {
            throw new RuntimeException("\"" + aSource + "\" is not in the SourceMap.");
        }
    }
954372
public final void synpred135_Java_fragment() throws RecognitionException {
		// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:656:9: ( classDeclaration ( ';' )? )
		// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:656:9: classDeclaration ( ';' )?
		{
		pushFollow(FOLLOW_classDeclaration_in_synpred135_Java2582);
		classDeclaration();
		state._fsp--;
		if (state.failed) return;
		// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:656:26: ( ';' )?
		int alt208=2;
		int LA208_0 = input.LA(1);
		if ( (LA208_0==52) ) {
			alt208=1;
		}
		switch (alt208) {
			case 1 :
				// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:656:26: ';'
				{
				match(input,52,FOLLOW_52_in_synpred135_Java2584); if (state.failed) return;
				}
				break;

		}

		}

	}
725324
@Override
    protected AstNode parseCustomStatement( DdlTokenStream tokens,
                                            AstNode parentNode ) throws ParsingException {
        assert tokens != null;
        assert parentNode != null;

        AstNode result = super.parseCustomStatement(tokens, parentNode);
        if (result == null) {
            if (tokens.matches(STMT_LOCK_TABLE)) {
                result = parseLockTable(tokens, parentNode);
            } else if (tokens.matches(STMT_RENAME_TABLE)) {
                result = parseRenameTable(tokens, parentNode);
            } else if (tokens.matches(STMT_RENAME_INDEX)) {
                result = parseRenameIndex(tokens, parentNode);
            } else if (tokens.matches(STMT_DECLARE_GLOBAL_TEMP_TABLE)) {
                result = parseDeclareGlobalTempTable(tokens, parentNode);
            }
        }
        return result;
    }
915131
private void compile(ICompilationUnit[] sourceUnits, boolean lastRound) {
        this.stats.startTime = System.currentTimeMillis();
        try {
            // build and record parsed units
            reportProgress(Messages.compilation_beginningToCompile);

            if (this.options.complianceLevel >= ClassFileConstants.JDK9) {
                // in Java 9 the compiler must never ask the oracle for a module that is contained in the input units:
                sortModuleDeclarationsFirst(sourceUnits);
            }
            if (this.annotationProcessorManager == null) {
                beginToCompile(sourceUnits);
            } else {
                ICompilationUnit[] originalUnits = sourceUnits.clone(); // remember source units in case a source type collision occurs
                try {
                    beginToCompile(sourceUnits);
                    if (!lastRound) {
                        processAnnotations();
                    }
                    if (!this.options.generateClassFiles) {
                        // -proc:only was set on the command line
                        return;
                    }
                } catch (SourceTypeCollisionException e) {
                    backupAptProblems();
                    reset();
                    // a generated type was referenced before it was created
                    // the compiler either created a MissingType or found a BinaryType for it
                    // so add the processor's generated files & start over,
                    // but remember to only pass the generated files to the annotation processor
                    int originalLength = originalUnits.length;
                    int newProcessedLength = e.newAnnotationProcessorUnits.length;
                    ICompilationUnit[] combinedUnits = new ICompilationUnit[originalLength + newProcessedLength];
                    System.arraycopy(originalUnits, 0, combinedUnits, 0, originalLength);
                    System.arraycopy(e.newAnnotationProcessorUnits, 0, combinedUnits, originalLength, newProcessedLength);
                    this.annotationProcessorStartIndex  = originalLength;
                    compile(combinedUnits, e.isLastRound);
                    return;
                }
            }
            // Restore the problems before the results are processed and cleaned up.
            restoreAptProblems();
            processCompiledUnits(0, lastRound);
        } catch (AbortCompilation e) {
            this.handleInternalException(e, null);
        }
        if (this.options.verbose) {
            if (this.totalUnits > 1) {
                this.out.println(
                        Messages.bind(Messages.compilation_units, String.valueOf(this.totalUnits)));
            } else {
                this.out.println(
                        Messages.bind(Messages.compilation_unit, String.valueOf(this.totalUnits)));
            }
        }
    }
996074
final public AuxiliaryTree TreeRoot(boolean requiresFoot) throws ParseException {
 /*@bgen(jjtree) TreeRoot */
  SimpleNode jjtn000 = new SimpleNode(JJTTREEROOT);
  boolean jjtc000 = true;
  jjtree.openNodeScope(jjtn000);Tree t;
    try {
      t = TreeNode();
      jjtree.closeNodeScope(jjtn000, true);
      jjtc000 = false;
      {if (true) return new AuxiliaryTree(t,requiresFoot);}
    } catch (Throwable jjte000) {
    if (jjtc000) {
      jjtree.clearNodeScope(jjtn000);
      jjtc000 = false;
    } else {
      jjtree.popNode();
    }
    if (jjte000 instanceof RuntimeException) {
      {if (true) throw (RuntimeException)jjte000;}
    }
    if (jjte000 instanceof ParseException) {
      {if (true) throw (ParseException)jjte000;}
    }
    {if (true) throw (Error)jjte000;}
    } finally {
    if (jjtc000) {
      jjtree.closeNodeScope(jjtn000, true);
    }
    }
    throw new Error("Missing return statement in function");
  }
306185
static Object callSecurely(final CodeSource codeSource, Callable callable,
            Context cx, Scriptable scope, Scriptable thisObj, Object[] args)
    {
        final Thread thread = Thread.currentThread();
        // Run in doPrivileged as we might be checked for "getClassLoader"
        // runtime permission
        final ClassLoader classLoader = (ClassLoader)AccessController.doPrivileged(
            new PrivilegedAction<Object>() {
                @Override
                public Object run() {
                    return thread.getContextClassLoader();
                }
            });
        Map<ClassLoader,SoftReference<SecureCaller>> classLoaderMap;
        synchronized(callers)
        {
            classLoaderMap = callers.get(codeSource);
            if(classLoaderMap == null)
            {
                classLoaderMap = new WeakHashMap<ClassLoader,SoftReference<SecureCaller>>();
                callers.put(codeSource, classLoaderMap);
            }
        }
        SecureCaller caller;
        synchronized(classLoaderMap)
        {
            SoftReference<SecureCaller> ref = classLoaderMap.get(classLoader);
            if (ref != null) {
                caller = ref.get();
            } else {
                caller = null;
            }
            if (caller == null) {
                try
                {
                    // Run in doPrivileged as we'll be checked for
                    // "createClassLoader" runtime permission
                    caller = (SecureCaller)AccessController.doPrivileged(
                            new PrivilegedExceptionAction<Object>()
                    {
                        @Override
                        public Object run() throws Exception
                        {
                            ClassLoader effectiveClassLoader;
                            Class<?> thisClass = getClass();
                            if(classLoader.loadClass(thisClass.getName()) != thisClass) {
                                effectiveClassLoader = thisClass.getClassLoader();
                            } else {
                                effectiveClassLoader = classLoader;
                            }
                            SecureClassLoaderImpl secCl =
                                new SecureClassLoaderImpl(effectiveClassLoader);
                            Class<?> c = secCl.defineAndLinkClass(
                                    SecureCaller.class.getName() + "Impl",
                                    secureCallerImplBytecode, codeSource);
                            return c.newInstance();
                        }
                    });
                    classLoaderMap.put(classLoader, new SoftReference<SecureCaller>(caller));
                }
                catch(PrivilegedActionException ex)
                {
                    throw new UndeclaredThrowableException(ex.getCause());
                }
            }
        }
        return caller.call(callable, cx, scope, thisObj, args);
    }
287058
@Nullable
  @OverrideOnDemand
  protected IHCElement <?> createSingleErrorNode (@Nonnull final IError aError, @Nonnull final Locale aContentLocale)
  {
    return BootstrapFormHelper.createDefaultErrorNode (aError, aContentLocale);
  }
237500
final public void Boolean() throws ParseException {
    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
    case TRUE:
      AstTrue jjtn001 = new AstTrue(JJTTRUE);
      boolean jjtc001 = true;
      jjtree.openNodeScope(jjtn001);
      try {
        jj_consume_token(TRUE);
      } finally {
      if (jjtc001) {
        jjtree.closeNodeScope(jjtn001, true);
      }
      }
      break;
    case FALSE:
        AstFalse jjtn002 = new AstFalse(JJTFALSE);
        boolean jjtc002 = true;
        jjtree.openNodeScope(jjtn002);
      try {
        jj_consume_token(FALSE);
      } finally {
        if (jjtc002) {
          jjtree.closeNodeScope(jjtn002, true);
        }
      }
      break;
    default:
      jj_la1[51] = jj_gen;
      jj_consume_token(-1);
      throw new ParseException();
    }
  }
1298217
@Override
    public JavaClassBuilderAt at(TypeReferenceLocation... locations)
    {
        if (locations != null)
            this.locations = Arrays.asList(locations);
        return this;
    }
984973
Node createAsyncGeneratorWrapperReference(JSType originalFunctionType, Scope scope) {
    Node ctor = createQName(scope, "$jscomp.AsyncGeneratorWrapper");

    if (isAddingTypes() && !ctor.getJSType().isUnknownType()) {
      // if ctor has the unknown type, we must have not injected the required runtime
      // libraries - hopefully because this is in a test using NonInjectingCompiler.

      // e.g get `number` from `AsyncIterable<number>`
      JSType yieldedType =
          originalFunctionType
              .toMaybeFunctionType()
              .getReturnType()
              .getInstantiatedTypeArgument(getNativeType(JSTypeNative.ASYNC_ITERABLE_TYPE));

      // e.g. replace
      //  AsyncGeneratorWrapper<T>
      // with
      //  AsyncGeneratorWrapper<number>
      ctor.setJSType(replaceTemplate(ctor.getJSType(), yieldedType));
    }

    return ctor;
  }
251896
@Override
    @SuppressWarnings("ReferenceEquality")
    protected boolean evaluateDependencies(final Dependency dependency, final Dependency nextDependency, final Set<Dependency> dependenciesToRemove) {
        Dependency main;
        //CSOFF: InnerAssignment
        if ((main = getMainGemspecDependency(dependency, nextDependency)) != null) {
            if (main == dependency) {
                mergeDependencies(dependency, nextDependency, dependenciesToRemove);
            } else {
                mergeDependencies(nextDependency, dependency, dependenciesToRemove);
                return true; //since we merged into the next dependency - skip forward to the next in mainIterator
            }
        } else if ((main = getMainSwiftDependency(dependency, nextDependency)) != null) {
            if (main == dependency) {
                mergeDependencies(dependency, nextDependency, dependenciesToRemove);
            } else {
                mergeDependencies(nextDependency, dependency, dependenciesToRemove);
                return true; //since we merged into the next dependency - skip forward to the next in mainIterator
            }
        } else if ((main = getMainAndroidDependency(dependency, nextDependency)) != null) {
            if (main == dependency) {
                mergeDependencies(dependency, nextDependency, dependenciesToRemove);
            } else {
                mergeDependencies(nextDependency, dependency, dependenciesToRemove);
                return true; //since we merged into the next dependency - skip forward to the next in mainIterator
            }
        } else if ((main = getMainDotnetDependency(dependency, nextDependency)) != null) {
            if (main == dependency) {
                mergeDependencies(dependency, nextDependency, dependenciesToRemove);
            } else {
                mergeDependencies(nextDependency, dependency, dependenciesToRemove);
                return true; //since we merged into the next dependency - skip forward to the next in mainIterator
            }
        }
        //CSON: InnerAssignment
        return false;
    }
677446
@Provides
  SoyFileSet.Builder provideBuilder(SoyFileSet.CoreDependencies coreDeps) {
    return new SoyFileSet.Builder(coreDeps);
  }
426922
@Override
    public DependencyInstance nextInstance() throws IOException {

        ArrayList<String[]> lstLines = getFileContentAsArray();

        if (lstLines.isEmpty()) {
            return null;
        }

        int length = lstLines.size();
        String[] forms = new String[length + 1];
        String[] lemmas = new String[length + 1];
        String[] cpos = new String[length + 1];
        String[] pos = new String[length + 1];
        String[][] feats = new String[length + 1][];
        String[] deprels = new String[length + 1];
        int[] heads = new int[length + 1];

        forms[0] = "<root>";
        lemmas[0] = "<root-LEMMA>";
        pos[0] = "<root-POS>";
        cpos[0] = pos[0];
        deprels[0] = "<no-type>";
        heads[0] = -1;

        boolean hasLemma = false;

        for (int i = 1; i < length + 1; ++i) {
            String[] parts = lstLines.get(i-1);
            forms[i] = parts[1];
            if (!parts[2].equals("_")) {
                lemmas[i] = parts[2];
                hasLemma = true;
            }

            pos[i] = parts[3];
            cpos[i] = pos[i];

            if (!parts[5].equals("_")) {
                feats[i] = parts[5].split("\\|");
            }

            if (parts[6].equals("_")) {
                System.out.println("Error in sentence:\n");
                System.out.println(parts[0] + " " + parts[1] + " " +  parts[2] + " " + parts[3]);
            }

            heads[i] = Integer.parseInt(parts[6]);
            deprels[i] = parts[7];

        }
        if (!hasLemma) lemmas = null;

        return new DependencyInstance(forms, lemmas, cpos, pos, feats, heads, deprels, null, null);
    }
414271
@Override
    public void visitClassContext(ClassContext classContext) {
        JavaClass jclass = classContext.getJavaClass();

        // We can ignore classes that were compiled for anything
        // less than JDK 1.5. This should avoid lots of unnecessary work
        // when analyzing code for older VM targets.
        if (BCELUtil.preTiger(jclass)) {
            return;
        }

        boolean sawUtilConcurrentLocks = false;
        for (Constant c : jclass.getConstantPool().getConstantPool()) {
            if (c instanceof ConstantMethodref) {
                ConstantMethodref m = (ConstantMethodref) c;
                ConstantClass cl = (ConstantClass) jclass.getConstantPool().getConstant(m.getClassIndex());
                ConstantUtf8 name = (ConstantUtf8) jclass.getConstantPool().getConstant(cl.getNameIndex());
                String nameAsString = name.getBytes();
                if (nameAsString.startsWith("java/util/concurrent/locks")) {
                    sawUtilConcurrentLocks = true;
                }

            }
        }
        if (sawUtilConcurrentLocks) {
            super.visitClassContext(classContext);
        }
    }