Compile the Java source.  Compile errors are encapsulated in a
ClassNotFound wrapper.
971183
void compileBatch(String []files, boolean isMake)
    throws ClassNotFoundException
  {
    try {
      JavaCompilerUtil compiler = JavaCompilerUtil.create(getClassLoader());
      compiler.setClassDir(_classDir);
      compiler.setSourceDir(_sourceDir);
      if (_encoding != null)
        compiler.setEncoding(_encoding);
      compiler.setArgs(_args);
      compiler.setCompileParent(! isMake);
      compiler.setSourceExtension(_sourceExt);
      if (_compiler != null)
        compiler.setCompiler(_compiler);

      //LineMap lineMap = new LineMap(javaFile.getNativePath());
      // The context path is obvious from the browser url
      //lineMap.add(name.replace('.', '/') + _sourceExt, 1, 1);
          
      compiler.compileBatch(files);
    } catch (Exception e) {
      getClassLoader().addDependency(AlwaysModified.create());

      // Compile errors are wrapped in a special ClassNotFound class
      // so the server can give a nice error message
      throw new CompileClassNotFound(e);
    }
  }
847107
public static Result compile(DiagnosticListener<JavaFileObject> listener, String[] args) {
    return ErrorProneCompiler.builder().listenToDiagnostics(listener).build().run(args);
  }
163893
function compileSourcePreCode() {
    var $version = '##version##';

    var componentRenderers = {};

    function extend(target, source) {
        if (source) {
            Object.keys(source).forEach(function (key) {
                var value = source[key];
                if (typeof value !== 'undefined') {
                    target[key] = value;
                }
            });
        }

        return target;
    }

    function each(array, iterator) {
        if (array && array.length > 0) {
            for (var i = 0, l = array.length; i < l; i++) {
                if (iterator(array[i], i) === false) {
                    break;
                }
            }
        }
    }

    function contains(array, value) {
        var result;
        each(array, function (item) {
            result = item === value;
            return !result;
        });

        return result;
    }

    var HTML_ENTITY = {
        /* jshint ignore:start */
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        /* eslint-disable quotes */
        "'": '&#39;'
        /* eslint-enable quotes */
        /* jshint ignore:end */
    };

    function htmlFilterReplacer(c) {
        return HTML_ENTITY[c];
    }

    function escapeHTML(source) {
        if (source == null) {
            return '';
        }

        if (typeof source === 'string') {
            return source ? source.replace(/[&<>"']/g, htmlFilterReplacer) : '';
        }

        return '' + source;
    }

    function _classFilter(source) {
        if (source instanceof Array) {
            return source.join(' ');
        }

        return source;
    }

    function _styleFilter(source) {
        if (typeof source === 'object') {
            var result = '';
            if (source) {
                Object.keys(source).forEach(function (key) {
                    result += key + ':' + source[key] + ';';
                });
            }

            return result;
        }

        return source;
    }

    function _xclassFilter(source) {
        if (source instanceof Array) {
            source = source.join(' ');
        }

        return source ? ' ' + source : '';
    }

    function _xstyleFilter(source) {
        var result;
        if (typeof source === 'object') {
            result = '';
            if (source) {
                Object.keys(source).forEach(function (key) {
                    result += key + ':' + source[key] + ';';
                });
            }
        }
        else {
            result = source;
        }

        return result ? ';' + result : '';
    }

    function attrFilter(name, value) {
        if (value) {
            return ' ' + name + '="' + value + '"';
        }

        return '';
    }

    function boolAttrFilter(name, value) {
        if (value && value !== 'false' && value !== '0') {
            return ' ' + name;
        }

        return '';
    }

    function callFilter(ctx, name, args) {
        var filter = ctx.proto.filters[name];
        if (typeof filter === 'function') {
            return filter.apply(ctx, args);
        }
    }
}
1036410
public void compile(Session session) {

        if (!database.schemaManager.schemaExists(compileTimeSchema.name)) {
            compileTimeSchema = session.getSchemaHsqlName(null);
        }

        session.setSchema(compileTimeSchema.name);

        ParserDQL p = new ParserDQL(session, new Scanner(statement));

        p.read();

        viewSubQuery    = p.XreadViewSubquery(this);
        queryExpression = viewSubQuery.queryExpression;

        if (getColumnCount() == 0) {
            if (columnNames == null) {
                columnNames =
                    viewSubQuery.queryExpression.getResultColumnNames();
            }

            if (columnNames.length
                    != viewSubQuery.queryExpression.getColumnCount()) {
                throw Error.error(ErrorCode.X_42593, tableName.statementName);
            }

            TableUtil.setColumnsInSchemaTable(
                this, columnNames, queryExpression.getColumnTypes());
        }

        //
        viewSubqueries = p.compileContext.getSubqueries();

        for (int i = 0; i < viewSubqueries.length; i++) {
            if (viewSubqueries[i].parentView == null) {
                viewSubqueries[i].parentView = this;
            }
        }

        //
        viewSubQuery.getTable().view       = this;
        viewSubQuery.getTable().columnList = columnList;
        schemaObjectNames = p.compileContext.getSchemaObjectNames();
        baseTable                          = queryExpression.getBaseTable();

        if (baseTable == null) {
            return;
        }

        switch (check) {

            case SchemaObject.ViewCheckModes.CHECK_NONE :
                break;

            case SchemaObject.ViewCheckModes.CHECK_LOCAL :
                checkExpression = queryExpression.getCheckCondition();
                break;

            case SchemaObject.ViewCheckModes.CHECK_CASCADE :
                break;

            default :
                throw Error.runtimeError(ErrorCode.U_S0500, "View");
        }
    }
1077461
private List<Snippet> compileFailResult(DiagList diags, String userSource, Kind probableKind) {
        ErroneousKey key = state.keyMap.keyForErroneous();
        Snippet snip = new ErroneousSnippet(key, userSource, null,
                probableKind, SubKind.UNKNOWN_SUBKIND);
        snip.setFailed(diags);

        // Install  wrapper for query by SourceCodeAnalysis.wrapper
        String compileSource = Util.trimEnd(new MaskCommentsAndModifiers(userSource, true).cleared());
        OuterWrap outer;
        switch (probableKind) {
            case IMPORT:
                outer = state.outerMap.wrapImport(Wrap.simpleWrap(compileSource), snip);
                break;
            case EXPRESSION:
                outer = state.outerMap.wrapInTrialClass(Wrap.methodReturnWrap(compileSource));
                break;
            case VAR:
            case TYPE_DECL:
            case METHOD:
                outer = state.outerMap.wrapInTrialClass(Wrap.classMemberWrap(compileSource));
                break;
            default:
                outer = state.outerMap.wrapInTrialClass(Wrap.methodWrap(compileSource));
                break;
        }
        snip.setOuterWrap(outer);

        return singletonList(snip);
    }
327498
private void findAllModifiedClasses(String name,
                                      PathImpl sourceDir,
                                      PathImpl classDir,
                                      String sourcePath,
                                      ArrayList<String> sources)
    throws IOException, ClassNotFoundException
  {
    String []list;

    try {
      list = sourceDir.list();
    } catch (IOException e) {
      return;
    }

    for (int i = 0; list != null && i < list.length; i++) {
      if (list[i].startsWith("."))
        continue;

      if (_excludedDirectories.contains(list[i]))
        continue;
      
      PathImpl subSource = sourceDir.lookup(list[i]);

      if (subSource.isDirectory()) {
        findAllModifiedClasses(name + list[i] + "/", subSource,
                               classDir.lookup(list[i]), sourcePath, sources);
      }
      else if (list[i].endsWith(_sourceExt)) {
        int tail = list[i].length() - _sourceExt.length();
        String prefix = list[i].substring(0, tail);
        PathImpl subClass = classDir.lookup(prefix + ".class");

        if (subClass.getLastModified() < subSource.getLastModified()) {
          sources.add(name + list[i]);
        }
      }
    }

    if (! _requireSource)
      return;
    
    try {
      list = classDir.list();
    } catch (IOException e) {
      return;
    }

    for (int i = 0; list != null && i < list.length; i++) {
      if (list[i].startsWith("."))
        continue;

      if (_excludedDirectories.contains(list[i]))
        continue;
      
      PathImpl subClass = classDir.lookup(list[i]);

      if (list[i].endsWith(".class")) {
        String prefix = list[i].substring(0, list[i].length() - 6);
        PathImpl subSource = sourceDir.lookup(prefix + _sourceExt);

        if (! subSource.exists()) {
          String tail = subSource.getTail();
          boolean doRemove = true;

          if (tail.indexOf('$') > 0) {
            String subTail = tail.substring(0, tail.indexOf('$')) + _sourceExt;
            PathImpl subJava = subSource.getParent().lookup(subTail);

            if (subJava.exists())
              doRemove = false;
          }

          if (doRemove) {
            log.finer(L.l("removing obsolete class '{0}'.", subClass.getPath()));

            subClass.remove();
          }
        }
      }
    }
  }
443393
public static void main(String[] args) throws ClassNotFoundException, IOException {
      // When run off the command-line or a build script, this program takes in two arguments: the path containing
      // class files to scan, and the output file to generate.
      long startTime = System.nanoTime();
      String path = args[0];
      String outputFile = args[1];

      System.out.printf(" [ComponentMetadataPersister] Starting component metadata generation.  Scanning classes in %s%n", path);

      ComponentMetadataRepo repo = new ComponentMetadataRepo();

      File f = new File(path);
      process(repo, f.getAbsolutePath(), f);

      // Test that all dependencies now exist in the component metadata map.
      Map<String, String> dependencies = new HashMap<>(128);
      for (ComponentMetadata md : repo.componentMetadataMap.values()) {
         if (md.getDependencies() != null) dependencies.putAll(md.getDependencies());
      }

      if (Boolean.getBoolean("infinispan.isCoreModule")) {
         // Perform this sanity check
         boolean hasErrors = false;
         for (Map.Entry<String, String> e : dependencies.entrySet()) {
            if (!repo.componentMetadataMap.containsKey(e.getKey())) {
               if (!repo.hasFactory(e.getKey())) {
                  System.out.printf(" [ComponentMetadataPersister]     **** WARNING!!!  Missing components or factories for dependency on %s%n", e.getKey());
                  hasErrors = true;
               }
            }
         }

         if (hasErrors && Boolean.getBoolean("infinispan.isCoreModule"))
            throw new RuntimeException("Could not pass sanity check of all annotated components and their respective factories/dependencies.");
      }
      writeMetadata(repo, outputFile);

      System.out.printf(" [ComponentMetadataPersister] %s components and %s factories.%n%n",
            repo.componentMetadataMap.size(), repo.factories.size());
   }
178728
public void compile(String[] files) throws CompilationFailedException {
        CompilationUnit unit = new CompilationUnit(configuration);
        unit.addSources(files);
        unit.compile();
    }
5644
public void addClassCompileTask(final String className,
                                    final BaseDescr descr,
                                    final String text,
                                    final MemoryResourceReader src,
                                    final ErrorHandler handler) {
        final String fileName = className.replace('.',
                                                  '/') + ".java";

        if (src != null) {
            src.add(fileName,
                    text.getBytes(IoUtils.UTF8_CHARSET));
        } else {
            this.src.add(fileName,
                         text.getBytes(IoUtils.UTF8_CHARSET));
        }

        this.errorHandlers.put(fileName,
                               handler);

        addClassName(fileName);
    }
763344
public void compile(int throughPhase) throws CompilationFailedException {
        //
        // To support delta compilations, we always restart
        // the compiler.  The individual passes are responsible
        // for not reprocessing old code.
        gotoPhase(Phases.INITIALIZATION);
        throughPhase = Math.min(throughPhase, Phases.ALL);

        while (throughPhase >= phase && phase <= Phases.ALL) {

            if (phase == Phases.SEMANTIC_ANALYSIS) {
                doPhaseOperation(resolve);
                if (dequeued()) continue;
            }

            processPhaseOperations(phase);
            // Grab processing may have brought in new AST transforms into various phases, process them as well
            processNewPhaseOperations(phase);

            if (progressCallback != null) progressCallback.call(this, phase);
            completePhase();
            applyToSourceUnits(mark);

            if (dequeued()) continue;

            gotoPhase(phase + 1);

            if (phase == Phases.CLASS_GENERATION) {
                sortClasses();
            }
        }

        errorCollector.failIfErrors();
    }
627559
List<String> listCompiledClasses(final File classFolder) {
        List<String> classNames = new ArrayList<String>();
        if (!classFolder.exists()) {
            getLog().info("Class folder does not exist; skipping scan");
            return classNames;
        }
        final String extension = ".class";
        final DirectoryScanner directoryScanner = new DirectoryScanner();
        directoryScanner.setBasedir(classFolder);
        directoryScanner.setIncludes(new String[] { "**" + File.separator + "*" + extension });
        directoryScanner.scan();
        String[] files = directoryScanner.getIncludedFiles();

        String className;
        for (String file : files) {
            className = file.substring(0, file.length() - extension.length()).replace(File.separator, ".");
            classNames.add(className);
        }

        return classNames;
    }
365778
public Class<?> compile(String className, String code, ClassLoader classLoader, OutputStream os, long lastModify) {
        code = code.trim();
        try {
            return Class.forName(className, true, classLoader);
        } catch (ClassNotFoundException e) {
            if (!code.endsWith("}")) {
                throw new IllegalStateException("The java code not endsWith \"}\", code: \n" + code + "\n");
            }
            try {
                return doCompile(className, code, os);
            } catch (RuntimeException t) {
                throw t;
            } catch (Throwable t) {
                throw new IllegalStateException("Failed to compile class, cause: " + t.getMessage() + ", class: "
                        + className + ", code: \n" + code + "\n, stack: " + ClassUtils.toString(t));
            }
        }
    }
1190547
public static boolean compileJavaClass(String sourceCode) {
		try {
			String fileName = getClassName(sourceCode).concat(".java");
			logger.info("Compiling Java Class ({})", fileName);

			File rootDir = JKIOUtil.createTempDirectory();
			String packageDir = getPackageDir(sourceCode);
			File sourceFile ;
			if(packageDir!=null) {
				File file=new File(rootDir,packageDir);
				file.mkdirs();
				sourceFile=new File(file, fileName);
			}else {
				sourceFile=new File(rootDir, fileName);
			}

			JKIOUtil.writeDataToFile(sourceCode, sourceFile);

			// Compile source file.
			JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
			StandardJavaFileManager standardJavaFileManager = compiler.getStandardFileManager(null, null, null);

			standardJavaFileManager.setLocation(StandardLocation.CLASS_PATH, getClassPath());
			standardJavaFileManager.setLocation(StandardLocation.SOURCE_PATH, Arrays.asList(rootDir));

			List<String> options = new ArrayList<String>();

			options.add("-Xlint:unchecked");

			CompilationTask compilationTask = compiler.getTask(null, standardJavaFileManager, null, options, null,
					standardJavaFileManager.getJavaFileObjectsFromFiles(JK.toList(sourceFile)));

			return compilationTask.call();
		} catch (IOException e) {
			JK.throww(e);
			return false;
		}

//		if (compiler.run(System.in, System.out, System.err, sourceFile.getPath()) != 0) {
//			JK.error("Compilation failed, check stack trace");
//		}
	}
431922
public void compile(ModuleConfiguration configuration) {
        LOGGER.debug("Compiling module {}", configuration);
        FileReaderFactory fileReaderFactory = injector.getInstance(FileReaderFactory.class);
        Importer importer = injector.getInstance(Importer.class);
        CompilerRegistry registry = injector.getInstance(CompilerRegistry.class);
        ProtoCompiler compiler = registry.findCompiler(configuration.getGenerator());
        if (compiler == null) {
            throw new GeneratorException("Unknown template: %s | %s", configuration.getGenerator(), registry.availableCompilers());
        }
        FileReader fileReader = fileReaderFactory.create(configuration.getIncludePaths());
        Map<String, Proto> importedFiles = new HashMap<>();
        for (String path : configuration.getProtoFiles()) {
            LOGGER.info("Parse {}", path);
            ProtoContext context = importer.importFile(fileReader, path);
            Proto proto = context.getProto();
            importedFiles.put(path, proto);
        }
        ImmutableModule.Builder builder = ImmutableModule.builder();
        builder.name(configuration.getName());
        builder.output(configuration.getOutput());
        builder.options(configuration.getOptions());
        for (Proto proto : importedFiles.values()) {
            builder.addProtos(proto);
        }
        UsageIndex index = UsageIndex.build(importedFiles.values());
        builder.usageIndex(index);
        ImmutableModule module = builder.build();
        for (Proto proto : importedFiles.values()) {
            proto.setModule(module);
        }
        compiler.compile(module);
    }
1328611
public static GenClassCompiler compile(TypeElement superClass, ProcessingEnvironment env) throws IOException
    {
        GenClassCompiler compiler;
        GrammarDef grammarDef = superClass.getAnnotation(GrammarDef.class);
        if (grammarDef != null)
        {
            compiler = new ParserCompiler(superClass);
        }
        else
        {
            DFAMap mapDef = superClass.getAnnotation(DFAMap.class);
            if (mapDef != null)
            {
                compiler = new MapCompiler(superClass);
            }
            else
            {
                compiler = new GenClassCompiler(superClass);
            }
        }
        compiler.setProcessingEnvironment(env);
        compiler.compile();
        if (env == null)
        {
            System.err.println("warning! classes directory not set");
        }
        else
        {
            compiler.saveClass();
        }
        return compiler;
    }
70335
public void compileAll() {
        if (this.generatedClassList.isEmpty()) {
            this.errorHandlers.clear();
            return;
        }
        final String[] classes = new String[this.generatedClassList.size()];
        this.generatedClassList.toArray(classes);

        File dumpDir = this.configuration.getPackageBuilderConfiguration().getDumpDir();
        if (dumpDir != null) {
            dumpResources(classes,
                          dumpDir);
        }

        final CompilationResult result = this.compiler.compile(classes,
                                                               this.src,
                                                               this.packageStoreWrapper,
                                                               rootClassLoader);


        //this will sort out the errors based on what class/file they happened in
        if (result.getErrors().length > 0) {
            for (int i = 0; i < result.getErrors().length; i++) {
                final CompilationProblem err = result.getErrors()[i];
                final ErrorHandler handler = this.errorHandlers.get(err.getFileName());
                handler.addError(err);
            }

            final Collection errors = this.errorHandlers.values();
            for (Object error : errors) {
                final ErrorHandler handler = (ErrorHandler) error;
                if (handler.isInError()) {
                    this.results.add(handler.getError());
                }
            }
        }

        // We've compiled everthing, so clear it for the next set of additions
        this.generatedClassList.clear();
        this.errorHandlers.clear();
    }
828853
@Override
    public Class<?> compile(String className, String code, ClassLoader classLoader, OutputStream os, long timestamp) {
        Class<?> cls = null;
        try {
            cls = ClassHelper.forName(className, classLoader);
        } catch (ClassNotFoundException e) {
            // ignore this exception
        } catch (LinkageError e) {
            // ignore this exception
        }
        if (cls != null) {
            return cls;
        }

        // to check cache
        byte[] bytes = cached(className, timestamp);
        // if has cached and timestamp is not changed will return a not null byte array
        if (bytes != null) {
            LoadableClassLoader loadableClassLoader = new LoadableClassLoader(classLoader);
            loadableClassLoader.defineNewClass(className, bytes, 0, bytes.length);

            try {
                return loadableClassLoader.loadClass(className);
            } catch (ClassNotFoundException e) {
                // ignore this exception
            }
        }

        cls = compiler.compile(className, code, classLoader, os, timestamp);

        cache(className, compiler.loadBytes(className), timestamp);
        return cls;
    }