當前位置: 首頁>>代碼示例>>Java>>正文


Java JavacProcessingEnvironment.instance方法代碼示例

本文整理匯總了Java中com.sun.tools.javac.processing.JavacProcessingEnvironment.instance方法的典型用法代碼示例。如果您正苦於以下問題:Java JavacProcessingEnvironment.instance方法的具體用法?Java JavacProcessingEnvironment.instance怎麽用?Java JavacProcessingEnvironment.instance使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在com.sun.tools.javac.processing.JavacProcessingEnvironment的用法示例。


在下文中一共展示了JavacProcessingEnvironment.instance方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: dataflow

import com.sun.tools.javac.processing.JavacProcessingEnvironment; //導入方法依賴的package包/類
/**
 * Run the {@code transfer} dataflow analysis over the method, lambda or initializer which is the
 * leaf of the {@code path}.
 *
 * <p>For caching, we make the following assumptions: - if two paths to methods are {@code equal},
 * their control flow graph is the same. - if two transfer functions are {@code equal}, and are
 * run over the same control flow graph, the analysis result is the same. - for all contexts, the
 * analysis result is the same.
 */
private <A extends AbstractValue<A>, S extends Store<S>, T extends TransferFunction<A, S>>
    Result<A, S, T> dataflow(TreePath path, Context context, T transfer) {
  final ProcessingEnvironment env = JavacProcessingEnvironment.instance(context);
  final ControlFlowGraph cfg = cfgCache.getUnchecked(CfgParams.create(path, env));
  final AnalysisParams aparams = AnalysisParams.create(transfer, cfg, env);
  @SuppressWarnings("unchecked")
  final Analysis<A, S, T> analysis = (Analysis<A, S, T>) analysisCache.getUnchecked(aparams);

  return new Result<A, S, T>() {
    @Override
    public Analysis<A, S, T> getAnalysis() {
      return analysis;
    }

    @Override
    public ControlFlowGraph getControlFlowGraph() {
      return cfg;
    }
  };
}
 
開發者ID:uber,項目名稱:NullAway,代碼行數:30,代碼來源:DataFlow.java

示例2: loadPlugins

import com.sun.tools.javac.processing.JavacProcessingEnvironment; //導入方法依賴的package包/類
public static ScannerSupplier loadPlugins(ScannerSupplier scannerSupplier, Context context) {
  JavaFileManager fileManager = context.get(JavaFileManager.class);
  // Unlike in annotation processor discovery, we never search CLASS_PATH if
  // ANNOTATION_PROCESSOR_PATH is unavailable.
  if (!fileManager.hasLocation(StandardLocation.ANNOTATION_PROCESSOR_PATH)) {
    return scannerSupplier;
  }
  // Use the same classloader that Error Prone was loaded from to avoid classloader skew
  // when using Error Prone plugins together with the Error Prone javac plugin.
  JavacProcessingEnvironment processingEnvironment = JavacProcessingEnvironment.instance(context);
  ClassLoader loader = processingEnvironment.getProcessorClassLoader();
  Iterable<BugChecker> extraBugCheckers = ServiceLoader.load(BugChecker.class, loader);
  if (Iterables.isEmpty(extraBugCheckers)) {
    return scannerSupplier;
  }
  return scannerSupplier.plus(
      ScannerSupplier.fromBugCheckerClasses(
          Iterables.transform(extraBugCheckers, BugChecker::getClass)));
}
 
開發者ID:google,項目名稱:error-prone,代碼行數:20,代碼來源:ErrorPronePlugins.java

示例3: main

import com.sun.tools.javac.processing.JavacProcessingEnvironment; //導入方法依賴的package包/類
public static void main(String[] args) {
    if (args.length != 1) {
        System.out.println("Usage:");
        System.out.println("    java IndexGenerator [class or package name]");
        return;
    }

    Context context = new Context();
    ProcessingEnvironment env = JavacProcessingEnvironment.instance(context);

    StubGenerator generator = new StubGenerator();

    if (env.getElementUtils().getPackageElement(args[0]) != null)
        generator.skeletonFromPackage(env.getElementUtils().getPackageElement(args[0]));
    else if (env.getElementUtils().getTypeElement(args[0]) != null)
        generator.skeletonFromType(env.getElementUtils().getTypeElement(args[0]));
    else
        System.err.println("Couldn't find a package or a class named " + args[0]);
}
 
開發者ID:reprogrammer,項目名稱:checker-framework,代碼行數:20,代碼來源:StubGenerator.java

示例4: getFieldInitializerNullness

import com.sun.tools.javac.processing.JavacProcessingEnvironment; //導入方法依賴的package包/類
/**
 * Returns {@link Nullness} of the initializer of the {@link VariableTree} at the leaf of the
 * given {@code fieldDeclPath}. Returns {@link Nullness#NULL} should there be no initializer.
 */
// TODO(kmb): Fold this functionality into Dataflow.expressionDataflow
public Nullness getFieldInitializerNullness(TreePath fieldDeclPath, Context context) {
  Tree decl = fieldDeclPath.getLeaf();
  checkArgument(
      decl instanceof VariableTree && ((JCVariableDecl) decl).sym.getKind() == ElementKind.FIELD,
      "Leaf of fieldDeclPath must be a field declaration: %s",
      decl);

  ExpressionTree initializer = ((VariableTree) decl).getInitializer();
  if (initializer == null) {
    // An uninitialized field is null or 0 to start :)
    return ((JCVariableDecl) decl).type.isPrimitive() ? Nullness.NONNULL : Nullness.NULL;
  }
  TreePath initializerPath = TreePath.getPath(fieldDeclPath, initializer);
  ClassTree classTree = (ClassTree) fieldDeclPath.getParentPath().getLeaf();
  JavacProcessingEnvironment javacEnv = JavacProcessingEnvironment.instance(context);
  UnderlyingAST ast = new UnderlyingAST.CFGStatement(decl, classTree);
  ControlFlowGraph cfg =
      CFGBuilder.build(
          initializerPath,
          javacEnv,
          ast,
          /* assumeAssertionsEnabled */ false,
          /* assumeAssertionsDisabled */ false);
  try {
    nullnessPropagation
        .setContext(context)
        .setCompilationUnit(fieldDeclPath.getCompilationUnit());

    Analysis<Nullness, LocalStore<Nullness>, TrustingNullnessPropagation> analysis =
        new Analysis<>(javacEnv, nullnessPropagation);
    analysis.performAnalysis(cfg);
    return analysis.getValue(initializer);
  } finally {
    nullnessPropagation.setContext(null).setCompilationUnit(null);
  }
}
 
開發者ID:google,項目名稱:error-prone,代碼行數:42,代碼來源:TrustingNullnessAnalysis.java

示例5: methodDataflow

import com.sun.tools.javac.processing.JavacProcessingEnvironment; //導入方法依賴的package包/類
/**
 * Run the {@code transfer} dataflow analysis over the method or lambda which is the leaf of the
 * {@code methodPath}.
 *
 * <p>For caching, we make the following assumptions: - if two paths to methods are {@code equal},
 * their control flow graph is the same. - if two transfer functions are {@code equal}, and are
 * run over the same control flow graph, the analysis result is the same. - for all contexts, the
 * analysis result is the same.
 */
private static <A extends AbstractValue<A>, S extends Store<S>, T extends TransferFunction<A, S>>
    Result<A, S, T> methodDataflow(TreePath methodPath, Context context, T transfer) {
  final ProcessingEnvironment env = JavacProcessingEnvironment.instance(context);

  final ControlFlowGraph cfg;
  try {
    cfg = cfgCache.getUnchecked(CfgParams.create(methodPath, env));
  } catch (UncheckedExecutionException e) {
    throw e.getCause() instanceof CompletionFailure ? (CompletionFailure) e.getCause() : e;
  }
  final AnalysisParams aparams = AnalysisParams.create(transfer, cfg, env);
  @SuppressWarnings("unchecked")
  final Analysis<A, S, T> analysis = (Analysis<A, S, T>) analysisCache.getUnchecked(aparams);

  return new Result<A, S, T>() {
    @Override
    public Analysis<A, S, T> getAnalysis() {
      return analysis;
    }

    @Override
    public ControlFlowGraph getControlFlowGraph() {
      return cfg;
    }
  };
}
 
開發者ID:google,項目名稱:error-prone,代碼行數:36,代碼來源:DataFlow.java

示例6: anyAnnotation

import com.sun.tools.javac.processing.JavacProcessingEnvironment; //導入方法依賴的package包/類
private static Matcher<Tree> anyAnnotation(
    List<? extends TypeMirror> mirrors, VisitorState state) {
  JavacProcessingEnvironment javacEnv = JavacProcessingEnvironment.instance(state.context);
  ArrayList<Matcher<Tree>> matchers = new ArrayList<>(mirrors.size());
  for (TypeMirror mirror : mirrors) {
    TypeElement typeElem = (TypeElement) javacEnv.getTypeUtils().asElement(mirror);
    String name = mirror.toString();
    if (typeElem != null) {
      // Get the binary name if possible ($ to separate nested members). See b/36160747
      name = javacEnv.getElementUtils().getBinaryName(typeElem).toString();
    }
    matchers.add(Matchers.hasAnnotation(name));
  }
  return Matchers.anyOf(matchers);
}
 
開發者ID:google,項目名稱:error-prone,代碼行數:16,代碼來源:RestrictedApiChecker.java

示例7: findDeclaration

import com.sun.tools.javac.processing.JavacProcessingEnvironment; //導入方法依賴的package包/類
@Nullable
private VariableTree findDeclaration(VisitorState state, Symbol field) {
  JavacProcessingEnvironment javacEnv = JavacProcessingEnvironment.instance(state.context);
  TreePath fieldDeclPath = Trees.instance(javacEnv).getPath(field);
  // Skip fields declared in other compilation units since we can't make a fix for them here.
  if (fieldDeclPath != null
      && fieldDeclPath.getCompilationUnit() == state.getPath().getCompilationUnit()
      && (fieldDeclPath.getLeaf() instanceof VariableTree)) {
    return (VariableTree) fieldDeclPath.getLeaf();
  }
  return null;
}
 
開發者ID:google,項目名稱:error-prone,代碼行數:13,代碼來源:FieldMissingNullable.java

示例8: findDeclaration

import com.sun.tools.javac.processing.JavacProcessingEnvironment; //導入方法依賴的package包/類
@Nullable
private VariableTree findDeclaration(VisitorState state, Symbol parameter) {
  JavacProcessingEnvironment javacEnv = JavacProcessingEnvironment.instance(state.context);
  TreePath declPath = Trees.instance(javacEnv).getPath(parameter);
  if (declPath != null
      && declPath.getCompilationUnit() == state.getPath().getCompilationUnit()
      && (declPath.getLeaf() instanceof VariableTree)) {
    return (VariableTree) declPath.getLeaf();
  }
  return null;
}
 
開發者ID:google,項目名稱:error-prone,代碼行數:12,代碼來源:ParameterNotNullable.java

示例9: main

import com.sun.tools.javac.processing.JavacProcessingEnvironment; //導入方法依賴的package包/類
public static void main(String[] args) {
    if (!(args.length == 1 && !args[0].startsWith(CHECKER_ARG))
        && !(args.length == 2 && args[0].startsWith(CHECKER_ARG))) {
        printUsage();
        return;
    }

    // process arguments
    String checkerName = "";
    if (args[0].startsWith(CHECKER_ARG))
        checkerName = args[0].substring(CHECKER_ARG.length());

    // Setup compiler environment
    Context context = new Context();
    JavacProcessingEnvironment env = JavacProcessingEnvironment.instance(context);
    SignaturePrinter printer = new SignaturePrinter();
    printer.init(env, checkerName);

    String className = args[args.length - 1];
    TypeElement elem = env.getElementUtils().getTypeElement(className);
    if (elem == null) {
        System.err.println("Couldn't find class: " + className);
        return;
    }

    printer.typeProcess(elem, null);
}
 
開發者ID:reprogrammer,項目名稱:checker-framework,代碼行數:28,代碼來源:SignaturePrinter.java

示例10: run

import com.sun.tools.javac.processing.JavacProcessingEnvironment; //導入方法依賴的package包/類
public void run(String[] args) {
    ProcessingEnvironment env = JavacProcessingEnvironment.instance(new Context());
    Elements elements = env.getElementUtils();

    AnnotatedTypeFactory atypeFactory = new GeneralAnnotatedTypeFactory(this);

    for (String className : args) {
        TypeElement typeElt = elements.getTypeElement(className);
        printClassType(typeElt, atypeFactory);
    }
}
 
開發者ID:reprogrammer,項目名稱:checker-framework,代碼行數:12,代碼來源:TypeOutputtingChecker.java

示例11: handle

import com.sun.tools.javac.processing.JavacProcessingEnvironment; //導入方法依賴的package包/類
@Override
public void handle(AnnotationValues<Vertex> annotation, JCAnnotation ast, JavacNode annotationNode) {
    JavacNode typeNode = annotationNode.up();
    JCAnnotation annotationAst = (JCAnnotation) annotationNode.get();

    JavacProcessingEnvironment processingEnvironment = JavacProcessingEnvironment.instance(annotationNode.getContext());

    this.typesUtil = processingEnvironment.getTypeUtils();
    this.elementUtils = processingEnvironment.getElementUtils();

    // Annotation parameter values
    ClassType idClass = (ClassType) getAnnotationParameterValue(annotationAst, ANNOTATION_PARAMETER_NAME_ID_CLASS, null);

    // Annotated id field
    JavacNode idFieldNode = findIdField(typeNode);

    // Modify the AST
    implementInterfaces(typeNode, idClass);
    createPropertyChangesField(typeNode);
    createAlreadyFetchedField(typeNode);
    modifyPropertySetters(typeNode);
    modifyRelationshipGetters(typeNode);
    modifyRelationshipSetters(typeNode);
    createGetPropertyChangesMethod(typeNode);
    createToKeyValuesMethod(typeNode, idFieldNode);
    JavacNode gizmoIdFieldNode = createIdField(typeNode, idClass);
    createElementField(typeNode);
    createGetElementMethod(typeNode);
    createConstructor(typeNode, gizmoIdFieldNode, idFieldNode);
    createGetIdMethod(typeNode, idClass);

    System.out.println(typeNode);
}
 
開發者ID:ezand,項目名稱:gizmo,代碼行數:34,代碼來源:VertexHandler.java

示例12: getPluginSettings

import com.sun.tools.javac.processing.JavacProcessingEnvironment; //導入方法依賴的package包/類
@NotNull
private TrautePluginSettings getPluginSettings(@NotNull Context context) {
    Log log = Log.instance(context);
    TrautePluginLogger logger = null;
    if (log != null) {
        logger = getPluginLogger(null, log);
    }

    TrautePluginSettingsBuilder builder = settingsBuilder();

    JavacProcessingEnvironment environment = JavacProcessingEnvironment.instance(context);
    if (environment == null) {
        if (logger != null) {
            logger.report(String.format(
                    "Can't read plugin settings from the javac command line arguments - expected to find a %s "
                    + "instance in the javac context but it doesn't there. %s",
                    JavacProcessingEnvironment.class.getName(), getProblemMessageSuffix()
            ));
        }
        // Use default settings
        return builder.build();
    }

    Map<String, String> options = environment.getOptions();
    if (options == null) {
        if (logger != null) {
            logger.info("No plugin settings are detected at the javac command line. Using default values");
        }
        // Use default settings
        return builder.build();
    }

    for (Map.Entry<String, String> entry : options.entrySet()) {
        if (entry.getKey().contains("traute") && !pluginOptionKeys.contains(entry.getKey())) {
            String error = String.format(
                    "Found an unknown setting '%s' with value '%s'. Probably a typo? Known settings: %s",
                    entry.getKey(), entry.getValue(), pluginOptionKeys
            );
            if (log == null) {
                throw new RuntimeException(error);
            } else {
                log.printRawLines(Log.WriterKind.ERROR, error);
            }
        }
    }

    String logFilePath = options.get(TrauteConstants.OPTION_LOG_FILE);
    if (logFilePath != null) {
        File file = new File(logFilePath);
        logger = new FileLogger(file);
        builder.withLogFile(file);
    }

    applyVerboseMode(logger, builder, options);
    applyNotNullAnnotations(logger, builder, options);
    applyNullableAnnotations(logger, builder, options);
    applyInstrumentations(logger, builder, options);
    applyExceptionsToThrow(logger, builder, options);
    applyExceptionTextPatterns(logger, builder, options);
    applyNotNullByDefaultAnnotations(logger, builder, options);

    return builder.build();
}
 
開發者ID:denis-zhdanov,項目名稱:traute,代碼行數:64,代碼來源:TrauteJavacPlugin.java

示例13: fieldInitializerNullnessIfAvailable

import com.sun.tools.javac.processing.JavacProcessingEnvironment; //導入方法依賴的package包/類
@Nullable
private Nullness fieldInitializerNullnessIfAvailable(ClassAndField accessed) {
  if (!traversed.add(accessed.symbol)) {
    // Circular dependency between initializers results in null.  Note static fields can also be
    // null if they're observed before initialized, but we're ignoring that case for simplicity.
    // TODO(kmb): Try to recognize problems with initialization order
    return NULL;
  }

  try {
    JavacProcessingEnvironment javacEnv = JavacProcessingEnvironment.instance(context);
    TreePath fieldDeclPath = Trees.instance(javacEnv).getPath(accessed.symbol);
    // Skip initializers in other compilation units as analysis of such nodes can fail due to
    // missing types.
    if (fieldDeclPath == null
        || fieldDeclPath.getCompilationUnit() != compilationUnit
        || !(fieldDeclPath.getLeaf() instanceof VariableTree)) {
      return null;
    }

    ExpressionTree initializer = ((VariableTree) fieldDeclPath.getLeaf()).getInitializer();
    if (initializer == null) {
      return null;
    }

    ClassTree classTree = (ClassTree) fieldDeclPath.getParentPath().getLeaf();

    // Run flow analysis on field initializer.  This is inefficient compared to just walking
    // the initializer expression tree but it avoids duplicating the logic from this transfer
    // function into a method that operates on Javac Nodes.
    TreePath initializerPath = TreePath.getPath(fieldDeclPath, initializer);
    UnderlyingAST ast = new UnderlyingAST.CFGStatement(initializerPath.getLeaf(), classTree);
    ControlFlowGraph cfg =
        CFGBuilder.build(
            initializerPath,
            javacEnv,
            ast,
            /* assumeAssertionsEnabled */ false, /* assumeAssertionsDisabled */
            false);
    Analysis<Nullness, LocalStore<Nullness>, NullnessPropagationTransfer> analysis =
        new Analysis<>(javacEnv, this);
    analysis.performAnalysis(cfg);
    return analysis.getValue(initializerPath.getLeaf());
  } finally {
    traversed.remove(accessed.symbol);
  }
}
 
開發者ID:google,項目名稱:error-prone,代碼行數:48,代碼來源:NullnessPropagationTransfer.java

示例14: AnnotationBuilderTest

import com.sun.tools.javac.processing.JavacProcessingEnvironment; //導入方法依賴的package包/類
public AnnotationBuilderTest() {
    env = JavacProcessingEnvironment.instance(new Context());
    ErrorReporter.setHandler(new TestChecker());
}
 
開發者ID:reprogrammer,項目名稱:checker-framework,代碼行數:5,代碼來源:AnnotationBuilderTest.java

示例15: TreeParserTest

import com.sun.tools.javac.processing.JavacProcessingEnvironment; //導入方法依賴的package包/類
public TreeParserTest() {
    env = JavacProcessingEnvironment.instance(new Context());
    parser = new TreeParser(env);
}
 
開發者ID:reprogrammer,項目名稱:checker-framework,代碼行數:5,代碼來源:TreeParserTest.java


注:本文中的com.sun.tools.javac.processing.JavacProcessingEnvironment.instance方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。