List of usage examples for org.eclipse.jdt.internal.compiler.util Util getFileCharContent
public static char[] getFileCharContent(File file, String encoding) throws IOException
From source file:com.android.build.gradle.tasks.annotations.ExtractAnnotationsDriver.java
License:Apache License
@NonNull private static Pair<Collection<CompilationUnitDeclaration>, INameEnvironment> parseSources( @NonNull List<File> sourcePaths, @NonNull List<String> classpath, @NonNull String encoding, long languageLevel) throws IOException { List<ICompilationUnit> sourceUnits = Lists.newArrayListWithExpectedSize(100); for (File source : gatherJavaSources(sourcePaths)) { char[] contents = Util.getFileCharContent(source, encoding); ICompilationUnit unit = new CompilationUnit(contents, source.getPath(), encoding); sourceUnits.add(unit);/*from w w w . java2 s . co m*/ } Map<ICompilationUnit, CompilationUnitDeclaration> outputMap = Maps .newHashMapWithExpectedSize(sourceUnits.size()); CompilerOptions options = EcjParser.createCompilerOptions(); options.docCommentSupport = true; // So I can find @hide // Note: We can *not* set options.ignoreMethodBodies=true because it disables // type attribution! options.sourceLevel = languageLevel; options.complianceLevel = options.sourceLevel; // We don't generate code, but just in case the parser consults this flag // and makes sure that it's not greater than the source level: options.targetJDK = options.sourceLevel; options.originalComplianceLevel = options.sourceLevel; options.originalSourceLevel = options.sourceLevel; options.inlineJsrBytecode = true; // >= 1.5 INameEnvironment environment = EcjParser.parse(options, sourceUnits, classpath, outputMap, null); Collection<CompilationUnitDeclaration> parsedUnits = outputMap.values(); return Pair.of(parsedUnits, environment); }
From source file:com.android.build.gradle.tasks.ExtractAnnotations.java
License:Apache License
@NonNull private EcjParser.EcjResult parseSources() { final List<EcjSourceFile> sourceUnits = Lists.newArrayListWithExpectedSize(100); getSource().visit(new EmptyFileVisitor() { @Override/* w w w.j a v a2 s . c o m*/ public void visitFile(FileVisitDetails fileVisitDetails) { File file = fileVisitDetails.getFile(); String path = file.getPath(); if (path.endsWith(DOT_JAVA) && file.isFile()) { char[] contents; try { contents = Util.getFileCharContent(file, encoding); } catch (IOException e) { getLogger().warn("Could not read file", e); return; } EcjSourceFile unit = new EcjSourceFile(contents, file, encoding); sourceUnits.add(unit); } } }); List<String> jars = Lists.newArrayList(); if (bootClasspath != null) { jars.addAll(bootClasspath); } if (getClasspath() != null) { for (File jar : getClasspath()) { jars.add(jar.getPath()); } } CompilerOptions options = EcjParser.createCompilerOptions(); options.docCommentSupport = Extractor.REMOVE_HIDDEN_TYPEDEFS; // So I can find @hide // Note: We can *not* set options.ignoreMethodBodies=true because it disables // type attribution! options.sourceLevel = getLanguageLevel(getSourceCompatibility()); options.complianceLevel = options.sourceLevel; // We don't generate code, but just in case the parser consults this flag // and makes sure that it's not greater than the source level: options.targetJDK = options.sourceLevel; options.originalComplianceLevel = options.sourceLevel; options.originalSourceLevel = options.sourceLevel; options.inlineJsrBytecode = true; // >= 1.5 return EcjParser.parse(options, sourceUnits, jars, null); }
From source file:com.codenvy.ide.ext.java.server.internal.core.BasicCompilationUnit.java
License:Open Source License
public char[] getContents() { if (this.contents != null) return this.contents; // answer the cached source // otherwise retrieve it try {/*from w ww . j a va 2 s. c om*/ return Util.getFileCharContent(new File(new String(this.fileName)), this.encoding); } catch (IOException e) { // could not read file: returns an empty array } return CharOperation.NO_CHAR; }
From source file:org.eclipse.jdt.core.dom.CompilationUnitResolver.java
License:Open Source License
public static void parse(String[] sourceUnits, String[] encodings, FileASTRequestor astRequestor, int apiLevel, Map options, int flags, IProgressMonitor monitor) { try {/*ww w .j a v a 2 s . co m*/ CompilerOptions compilerOptions = new CompilerOptions(options); compilerOptions.ignoreMethodBodies = (flags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0; Parser parser = new CommentRecorderParser( new ProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions, new DefaultProblemFactory()), false); int unitLength = sourceUnits.length; if (monitor != null) monitor.beginTask("", unitLength); //$NON-NLS-1$ for (int i = 0; i < unitLength; i++) { char[] contents = null; String encoding = encodings != null ? encodings[i] : null; try { contents = Util.getFileCharContent(new File(sourceUnits[i]), encoding); } catch (IOException e) { // go to the next unit continue; } if (contents == null) { // go to the next unit continue; } org.eclipse.jdt.internal.compiler.batch.CompilationUnit compilationUnit = new org.eclipse.jdt.internal.compiler.batch.CompilationUnit( contents, sourceUnits[i], encoding); org.eclipse.jdt.internal.compiler.env.ICompilationUnit sourceUnit = compilationUnit; CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit); CompilationUnitDeclaration compilationUnitDeclaration = parser.dietParse(sourceUnit, compilationResult); if (compilationUnitDeclaration.ignoreMethodBodies) { compilationUnitDeclaration.ignoreFurtherInvestigation = true; // if initial diet parse did not work, no need to dig into method bodies. continue; } //fill the methods bodies in order for the code to be generated //real parse of the method.... org.eclipse.jdt.internal.compiler.ast.TypeDeclaration[] types = compilationUnitDeclaration.types; if (types != null) { for (int j = 0, typeLength = types.length; j < typeLength; j++) { types[j].parseMethods(parser, compilationUnitDeclaration); } } // convert AST CompilationUnit node = convert(compilationUnitDeclaration, parser.scanner.getSource(), apiLevel, options, false/*don't resolve binding*/, null/*no owner needed*/, null/*no binding table needed*/, flags /* flags */, monitor, true); node.setTypeRoot(null); // accept AST astRequestor.acceptAST(sourceUnits[i], node); if (monitor != null) monitor.worked(1); } } finally { if (monitor != null) monitor.done(); } }
From source file:org.eclipse.jdt.core.dom.CompilationUnitResolver.java
License:Open Source License
private void resolve(String[] sourceCompilationUnits, String[] encodings, String[] bindingKeys, FileASTRequestor astRequestor, int apiLevel, Map compilerOptions, int flags) { // temporarily connect ourselves to the ASTResolver - must disconnect when done astRequestor.compilationUnitResolver = this; this.bindingTables = new DefaultBindingResolver.BindingTables(); CompilationUnitDeclaration unit = null; try {/*ww w. j a v a 2 s.c om*/ int length = sourceCompilationUnits.length; org.eclipse.jdt.internal.compiler.env.ICompilationUnit[] sourceUnits = new org.eclipse.jdt.internal.compiler.env.ICompilationUnit[length]; int count = 0; for (int i = 0; i < length; i++) { char[] contents = null; String encoding = encodings != null ? encodings[i] : null; String sourceUnitPath = sourceCompilationUnits[i]; try { contents = Util.getFileCharContent(new File(sourceUnitPath), encoding); } catch (IOException e) { // go to the next unit continue; } if (contents == null) { // go to the next unit continue; } sourceUnits[count++] = new org.eclipse.jdt.internal.compiler.batch.CompilationUnit(contents, sourceUnitPath, encoding); } beginToCompile(sourceUnits, bindingKeys); // process all units (some more could be injected in the loop by the lookup environment) for (int i = 0; i < this.totalUnits; i++) { if (resolvedRequestedSourcesAndKeys(i)) { // no need to keep resolving if no more ASTs and no more binding keys are needed // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=114935 // cleanup remaining units for (; i < this.totalUnits; i++) { this.unitsToProcess[i].cleanUp(); this.unitsToProcess[i] = null; } break; } unit = this.unitsToProcess[i]; try { super.process(unit, i); // this.process(...) is optimized to not process already known units // requested AST char[] fileName = unit.compilationResult.getFileName(); org.eclipse.jdt.internal.compiler.env.ICompilationUnit source = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) this.requestedSources .get(fileName); if (source != null) { // convert AST CompilationResult compilationResult = unit.compilationResult; org.eclipse.jdt.internal.compiler.env.ICompilationUnit sourceUnit = compilationResult.compilationUnit; char[] contents = sourceUnit.getContents(); AST ast = AST.newAST(apiLevel); ast.setFlag(flags | AST.RESOLVED_BINDINGS); ast.setDefaultNodeFlag(ASTNode.ORIGINAL); ASTConverter converter = new ASTConverter(compilerOptions, true/*need to resolve bindings*/, this.monitor); BindingResolver resolver = new DefaultBindingResolver(unit.scope, null, this.bindingTables, (flags & ICompilationUnit.ENABLE_BINDINGS_RECOVERY) != 0, this.fromJavaProject); ast.setBindingResolver(resolver); converter.setAST(ast); CompilationUnit compilationUnit = converter.convert(unit, contents); compilationUnit.setTypeRoot(null); compilationUnit.setLineEndTable(compilationResult.getLineSeparatorPositions()); ast.setDefaultNodeFlag(0); ast.setOriginalModificationCount(ast.modificationCount()); // pass it to requestor astRequestor.acceptAST(new String(source.getFileName()), compilationUnit); worked(1); // remove at the end so that we don't resolve twice if a source and a key for the same file name have been requested this.requestedSources.put(fileName, null); // mark it as removed } // requested binding Object key = this.requestedKeys.get(fileName); if (key != null) { if (key instanceof BindingKeyResolver) { reportBinding(key, astRequestor, unit); worked(1); } else if (key instanceof ArrayList) { Iterator iterator = ((ArrayList) key).iterator(); while (iterator.hasNext()) { reportBinding(iterator.next(), astRequestor, unit); worked(1); } } // remove at the end so that we don't resolve twice if a source and a key for the same file name have been requested this.requestedKeys.put(fileName, null); // mark it as removed } } finally { // cleanup compilation unit result unit.cleanUp(); } this.unitsToProcess[i] = null; // release reference to processed unit declaration this.requestor.acceptResult(unit.compilationResult.tagAsAccepted()); } // remaining binding keys DefaultBindingResolver resolver = new DefaultBindingResolver(this.lookupEnvironment, null, this.bindingTables, (flags & ICompilationUnit.ENABLE_BINDINGS_RECOVERY) != 0, true); Object[] keys = this.requestedKeys.valueTable; for (int j = 0, keysLength = keys.length; j < keysLength; j++) { BindingKeyResolver keyResolver = (BindingKeyResolver) keys[j]; if (keyResolver == null) continue; Binding compilerBinding = keyResolver.getCompilerBinding(); IBinding binding = compilerBinding == null ? null : resolver.getBinding(compilerBinding); // pass it to requestor astRequestor.acceptBinding(((BindingKeyResolver) this.requestedKeys.valueTable[j]).getKey(), binding); worked(1); } } catch (OperationCanceledException e) { throw e; } catch (AbortCompilation e) { this.handleInternalException(e, unit); } catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow } catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow } finally { // disconnect ourselves from ast requestor astRequestor.compilationUnitResolver = null; } }
From source file:org.eclipse.jdt.internal.compiler.parser.Parser.java
License:Open Source License
public final static void buildFilesFromLPG(String dataFilename, String dataFilename2) { //RUN THIS METHOD TO GENERATE PARSER*.RSC FILES //build from the lpg javadcl.java files that represents the parser tables //lhs check_table asb asr symbol_index //[org.eclipse.jdt.internal.compiler.parser.Parser.buildFilesFromLPG("d:/leapfrog/grammar/javadcl.java")] char[] contents = CharOperation.NO_CHAR; try {// ww w . j a v a 2s . co m contents = Util.getFileCharContent(new File(dataFilename), null); } catch (IOException ex) { System.out.println(Messages.parser_incorrectPath); return; } java.util.StringTokenizer st = new java.util.StringTokenizer(new String(contents), " \t\n\r[]={,;"); //$NON-NLS-1$ String[] tokens = new String[st.countTokens()]; int j = 0; while (st.hasMoreTokens()) { tokens[j++] = st.nextToken(); } final String prefix = FILEPREFIX; int i = 0; char[] newLhs = buildFileOfIntFor(prefix + (++i) + ".rsc", "lhs", tokens); //$NON-NLS-1$ //$NON-NLS-2$ buildFileOfShortFor(prefix + (++i) + ".rsc", "check_table", tokens); //$NON-NLS-2$ //$NON-NLS-1$ buildFileOfIntFor(prefix + (++i) + ".rsc", "asb", tokens); //$NON-NLS-2$ //$NON-NLS-1$ buildFileOfIntFor(prefix + (++i) + ".rsc", "asr", tokens); //$NON-NLS-2$ //$NON-NLS-1$ buildFileOfIntFor(prefix + (++i) + ".rsc", "nasb", tokens); //$NON-NLS-2$ //$NON-NLS-1$ buildFileOfIntFor(prefix + (++i) + ".rsc", "nasr", tokens); //$NON-NLS-2$ //$NON-NLS-1$ char[] newTerminalIndex = buildFileOfIntFor(prefix + (++i) + ".rsc", "terminal_index", tokens); //$NON-NLS-2$ //$NON-NLS-1$ char[] newNonTerminalIndex = buildFileOfIntFor(prefix + (++i) + ".rsc", "non_terminal_index", tokens); //$NON-NLS-1$ //$NON-NLS-2$ buildFileOfIntFor(prefix + (++i) + ".rsc", "term_action", tokens); //$NON-NLS-2$ //$NON-NLS-1$ buildFileOfIntFor(prefix + (++i) + ".rsc", "scope_prefix", tokens); //$NON-NLS-2$ //$NON-NLS-1$ buildFileOfIntFor(prefix + (++i) + ".rsc", "scope_suffix", tokens); //$NON-NLS-2$ //$NON-NLS-1$ buildFileOfIntFor(prefix + (++i) + ".rsc", "scope_lhs", tokens); //$NON-NLS-2$ //$NON-NLS-1$ buildFileOfIntFor(prefix + (++i) + ".rsc", "scope_state_set", tokens); //$NON-NLS-2$ //$NON-NLS-1$ buildFileOfIntFor(prefix + (++i) + ".rsc", "scope_rhs", tokens); //$NON-NLS-2$ //$NON-NLS-1$ buildFileOfIntFor(prefix + (++i) + ".rsc", "scope_state", tokens); //$NON-NLS-2$ //$NON-NLS-1$ buildFileOfIntFor(prefix + (++i) + ".rsc", "in_symb", tokens); //$NON-NLS-2$ //$NON-NLS-1$ byte[] newRhs = buildFileOfByteFor(prefix + (++i) + ".rsc", "rhs", tokens); //$NON-NLS-2$ //$NON-NLS-1$ buildFileOfByteFor(prefix + (++i) + ".rsc", "term_check", tokens); //$NON-NLS-2$ //$NON-NLS-1$ buildFileOfByteFor(prefix + (++i) + ".rsc", "scope_la", tokens); //$NON-NLS-2$ //$NON-NLS-1$ String[] newName = buildFileForName(prefix + (++i) + ".rsc", new String(contents)); //$NON-NLS-1$ contents = CharOperation.NO_CHAR; try { contents = Util.getFileCharContent(new File(dataFilename2), null); } catch (IOException ex) { System.out.println(Messages.parser_incorrectPath); return; } st = new java.util.StringTokenizer(new String(contents), "\t\n\r#"); //$NON-NLS-1$ tokens = new String[st.countTokens()]; j = 0; while (st.hasMoreTokens()) { tokens[j++] = st.nextToken(); } buildFileForCompliance(prefix + (++i) + ".rsc", newRhs.length, tokens);//$NON-NLS-1$ buildFileForReadableName(READABLE_NAMES_FILE + ".properties", newLhs, newNonTerminalIndex, newName, tokens);//$NON-NLS-1$ buildFilesForRecoveryTemplates(prefix + (++i) + ".rsc", //$NON-NLS-1$ prefix + (++i) + ".rsc", //$NON-NLS-1$ newTerminalIndex, newNonTerminalIndex, newName, newLhs, tokens); buildFilesForStatementsRecoveryFilter(prefix + (++i) + ".rsc", //$NON-NLS-1$ newNonTerminalIndex, newLhs, tokens); System.out.println(Messages.parser_moveFiles); }
From source file:org.eclipse.tycho.compiler.jdt.JDTCompiler.java
License:Open Source License
/** * check the compiler arguments. Extract from files specified using @, lines marked with * ADAPTER_PREFIX These lines specify information that needs to be interpreted by us. * //from www .j a v a2 s. c om * @param args * compiler arguments to process */ private void checkCompilerArgs(Map<String, String> args) { for (String arg : args.keySet()) { if (arg.charAt(0) == '@') { try { char[] content = Util.getFileCharContent(new File(arg.substring(1)), null); int offset = 0; int prefixLength = ADAPTER_PREFIX.length; while ((offset = CharOperation.indexOf(ADAPTER_PREFIX, content, true, offset)) > -1) { int start = offset + prefixLength; int end = CharOperation.indexOf('\n', content, start); if (end == -1) end = content.length; while (CharOperation.isWhitespace(content[end])) { end--; } // end is inclusive, but in the API end is exclusive if (CharOperation.equals(ADAPTER_ENCODING, content, start, start + ADAPTER_ENCODING.length)) { CharOperation.replace(content, SEPARATOR_CHARS, File.separatorChar, start, end + 1); // file or folder level custom encoding start += ADAPTER_ENCODING.length; int encodeStart = CharOperation.lastIndexOf('[', content, start, end); if (start < encodeStart && encodeStart < end) { boolean isFile = CharOperation.equals(SuffixConstants.SUFFIX_java, content, encodeStart - 5, encodeStart, false); String str = String.valueOf(content, start, encodeStart - start); String enc = String.valueOf(content, encodeStart, end - encodeStart + 1); if (isFile) { if (fileEncodings == null) fileEncodings = new HashMap<String, String>(); // use File to translate the string into a // path with the correct File.seperator fileEncodings.put(str, enc); } else { if (dirEncodings == null) dirEncodings = new HashMap<String, String>(); dirEncodings.put(str, enc); } } } else if (CharOperation.equals(ADAPTER_ACCESS, content, start, start + ADAPTER_ACCESS.length)) { // access rules for the classpath start += ADAPTER_ACCESS.length; int accessStart = CharOperation.indexOf('[', content, start, end); // CharOperation.replace(content, SEPARATOR_CHARS, // File.separatorChar, start, accessStart); if (start < accessStart && accessStart < end) { String path = String.valueOf(content, start, accessStart - start); String access = String.valueOf(content, accessStart, end - accessStart + 1); if (accessRules == null) accessRules = new ArrayList<String>(); accessRules.add(path); accessRules.add(access); } } offset = end; } } catch (IOException e) { // ignore } } } }
From source file:org.kepler.build.Format.java
License:Open Source License
private void formatFileHelper(File file) throws IOException, BadLocationException { IDocument doc = new Document(); String contents = new String(Util.getFileCharContent(file, null)); doc.set(contents);//from w ww .j a v a2 s. com TextEdit edit = cf.format(CodeFormatter.K_COMPILATION_UNIT, contents, 0, contents.length(), 0, null); System.out.print("Formatting: " + file.getAbsolutePath() + ". "); if (edit != null) { System.out.println(); edit.apply(doc); } else { System.out.println("FAILED."); } BufferedWriter out = new BufferedWriter(new FileWriter(file)); out.write(doc.get()); out.flush(); }