Java 类com.intellij.psi.PsiElementFactory 实例源码

项目:GitHub    文件:Processor.java   
protected void generateConvertMethod(PsiElementFactory factory, PsiClass cls, ClassEntity classEntity) {
    if (cls == null || cls.getName() == null) {
        return;
    }
    if (Config.getInstant().isObjectFromData()) {
        createMethod(factory, Config.getInstant().getObjectFromDataStr().replace("$ClassName$", cls.getName()).trim(), cls);
    }
    if (Config.getInstant().isObjectFromData1()) {
        createMethod(factory, Config.getInstant().getObjectFromDataStr1().replace("$ClassName$", cls.getName()).trim(), cls);
    }
    if (Config.getInstant().isArrayFromData()) {
        createMethod(factory, Config.getInstant().getArrayFromDataStr().replace("$ClassName$", cls.getName()).trim(), cls);
    }
    if (Config.getInstant().isArrayFromData1()) {
        createMethod(factory, Config.getInstant().getArrayFromData1Str().replace("$ClassName$", cls.getName()).trim(), cls);
    }
}
项目:GitHub    文件:Processor.java   
protected void createMethod(PsiElementFactory factory, String method, PsiClass cls) {
    Try.run(new Try.TryListener() {
        @Override
        public void run() {
            cls.add(factory.createMethodFromText(method, cls));
        }

        @Override
        public void runAgain() {

        }

        @Override
        public void error() {

        }
    });
}
项目:GitHub    文件:Processor.java   
protected void generateField(PsiElementFactory factory, FieldEntity fieldEntity, PsiClass cls, ClassEntity classEntity) {

        if (fieldEntity.isGenerate()) {
            Try.run(new Try.TryListener() {
                @Override
                public void run() {
                    cls.add(factory.createFieldFromText(generateFieldText(classEntity, fieldEntity, null), cls));

                }

                @Override
                public void runAgain() {
                    fieldEntity.setFieldName(FieldHelper.generateLuckyFieldName(fieldEntity.getFieldName()));
                    cls.add(factory.createFieldFromText(generateFieldText(classEntity, fieldEntity, Constant.FIXME), cls));
                }

                @Override
                public void error() {
                    cls.addBefore(factory.createCommentFromText("// FIXME generate failure  field " + fieldEntity.getFieldName(), cls), cls.getChildren()[0]);
                }
            });

        }

    }
项目:GitHub    文件:FieldsDialog.java   
public FieldsDialog(ConvertBridge.Operator operator, ClassEntity classEntity,
                    PsiElementFactory factory, PsiClass psiClass, PsiClass aClass, PsiFile file, Project project
        , String generateClassStr) {
    this.operator = operator;
    this.factory = factory;
    this.aClass = aClass;
    this.file = file;
    this.project = project;
    this.psiClass = psiClass;
    this.generateClassStr = generateClassStr;
    setContentPane(contentPane);
    setTitle("Virgo Model");
    getRootPane().setDefaultButton(buttonOK);
    this.setAlwaysOnTop(true);
    initListener(classEntity, generateClassStr);
}
项目:CodeGenerate    文件:FieldsDialog.java   
public FieldsDialog(ConvertBridge.Operator operator, ClassEntity classEntity,
                    PsiElementFactory factory, PsiClass psiClass, PsiClass aClass, PsiFile file, Project project
        , String generateClassStr) {
    this.operator = operator;
    this.factory = factory;
    this.aClass = aClass;
    this.file = file;
    this.project = project;
    this.psiClass = psiClass;
    this.generateClassStr = generateClassStr;
    setContentPane(contentPane);
    setTitle("Virgo Model");
    getRootPane().setDefaultButton(buttonOK);
    this.setAlwaysOnTop(true);
    initListener(classEntity, generateClassStr);
}
项目:nullability-annotations-inspection    文件:AddPackageInfoWithNullabilityDefaultsFix.java   
private void addAnnotationToPackageInfo(Project project, PsiJavaFile packageInfoFile) {
    if (!FileModificationService.getInstance().preparePsiElementForWrite(packageInfoFile)) {
        return;
    }

    PsiPackageStatement packageStatement = packageInfoFile.getPackageStatement();
    if (packageStatement == null) {
        return;
    }

    PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
    PsiAnnotation annotation = factory.createAnnotationFromText("@" + annotationForTypeQualifierFqn,
            packageInfoFile.getContext());
    PsiElement addedAnnotation = packageInfoFile.addBefore(annotation, packageStatement);
    JavaCodeStyleManager.getInstance(project).shortenClassReferences(addedAnnotation);

    removeRedundantAnnotationsInPackage(project, packageInfoFile.getContainingDirectory().getFiles(), annotation);
}
项目:nullability-annotations-inspection    文件:NullabilityAnnotationsWithTypeQualifierDefault.java   
static List<String> findAnnotations(PsiModifierListOwner element, boolean nullable) {
    if (overridesSuper(element)) {
        return Collections.emptyList();
    }

    List<String> annotations = new ArrayList<>();
    Project project = element.getProject();
    PsiModifierList modifierList = element.getModifierList();
    List<String> nullabilityAnnotations = nullable
            ? NullableNotNullManager.getInstance(project).getNullables()
            : NullableNotNullManager.getInstance(project).getNotNulls();
    for (String notNullAnnotationFqn : nullabilityAnnotations) {
        PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
        PsiAnnotation annotation = factory.createAnnotationFromText("@" + notNullAnnotationFqn, null);
        PsiAnnotation.TargetType[] targetTypes = getTargetsForLocation(modifierList);
        if (isNullabilityAnnotationForTypeQualifierDefault(annotation, nullable, targetTypes)) {
            annotations.add(annotation.getQualifiedName());
        }
    }
    return annotations;
}
项目:manifold-ij    文件:ManAugmentProvider.java   
private PsiMethod makePsiMethod( AbstractSrcMethod method, PsiClass psiClass )
{
  PsiElementFactory elementFactory = JavaPsiFacade.getInstance( psiClass.getProject() ).getElementFactory();
  StringBuilder sb = new StringBuilder();
  method.render( sb, 0 );
  try
  {
    return elementFactory.createMethodFromText( sb.toString(), psiClass );
  }
  catch( IncorrectOperationException ioe )
  {
    // the text of the method does not conform to method grammar, probably being edited in an IJ editor,
    // ignore these since the editor provides error information
    return null;
  }
}
项目:AndroidStudioPlugin    文件:CreateDialogAction.java   
@Override
public void actionPerformed(AnActionEvent e) {

    // 获取编辑器中的文件
    Project project = e.getData(PlatformDataKeys.PROJECT);
    Editor editor = e.getData(PlatformDataKeys.EDITOR);
    PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);

    // 获取当前类
    PsiClass targetClass = getTargetClass(editor, file);
    // 获取元素操作的工厂类
    PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);

    // 生成代码
    new LayoutCreator(project, targetClass, factory, file).execute();
}
项目:intellij-ce-playground    文件:JavaCoreProjectEnvironment.java   
public JavaCoreProjectEnvironment(Disposable parentDisposable, CoreApplicationEnvironment applicationEnvironment) {
  super(parentDisposable, applicationEnvironment);

  myProject.registerService(PsiElementFactory.class, new PsiElementFactoryImpl(myPsiManager));
  myProject.registerService(JavaPsiImplementationHelper.class, createJavaPsiImplementationHelper());
  myProject.registerService(PsiResolveHelper.class, new PsiResolveHelperImpl(myPsiManager));
  myProject.registerService(LanguageLevelProjectExtension.class, new CoreLanguageLevelProjectExtension());
  myProject.registerService(JavaResolveCache.class, new JavaResolveCache(myMessageBus));
  myProject.registerService(JavaCodeStyleSettingsFacade.class, new CoreJavaCodeStyleSettingsFacade());
  myProject.registerService(JavaCodeStyleManager.class, new CoreJavaCodeStyleManager());

  myPackageIndex = createCorePackageIndex();
  myProject.registerService(PackageIndex.class, myPackageIndex);

  myFileManager = createCoreFileManager();
  myProject.registerService(JavaFileManager.class, myFileManager);

  JavaPsiFacadeImpl javaPsiFacade = new JavaPsiFacadeImpl(myProject, myPsiManager, myFileManager, myMessageBus);
  myProject.registerService(JavaPsiFacade.class, javaPsiFacade);
}
项目:intellij-ce-playground    文件:FieldDescriptorImpl.java   
@Override
public PsiExpression getDescriptorEvaluation(DebuggerContext context) throws EvaluateException {
  PsiElementFactory elementFactory = JavaPsiFacade.getInstance(context.getProject()).getElementFactory();
  String fieldName;
  if(isStatic()) {
    String typeName = myField.declaringType().name().replace('$', '.');
    typeName = DebuggerTreeNodeExpression.normalize(typeName, PositionUtil.getContextElement(context), context.getProject());
    fieldName = typeName + "." + getName();
  }
  else {
    //noinspection HardCodedStringLiteral
    fieldName = isOuterLocalVariableValue()? StringUtil.trimStart(getName(), OUTER_LOCAL_VAR_FIELD_PREFIX) : "this." + getName();
  }
  try {
    return elementFactory.createExpressionFromText(fieldName, null);
  }
  catch (IncorrectOperationException e) {
    throw new EvaluateException(DebuggerBundle.message("error.invalid.field.name", getName()), e);
  }
}
项目:intellij-ce-playground    文件:RemoveLeadingZeroFix.java   
@Override
protected void doFix(Project project, ProblemDescriptor descriptor)
  throws IncorrectOperationException {
  final PsiElement element = descriptor.getPsiElement();
  final String text = element.getText();
  final int max = text.length() - 1;
  if (max < 1) {
    return;
  }
  int index = 0;
  while (index < max && (text.charAt(index) == '0' || text.charAt(index) == '_')) {
    index++;
  }
  final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
  final PsiElementFactory factory = psiFacade.getElementFactory();
  final String textWithoutLeadingZeros = text.substring(index);
  final PsiExpression decimalNumber =
    factory.createExpressionFromText(textWithoutLeadingZeros,
                                     element);
  element.replace(decimalNumber);
}
项目:intellij-ce-playground    文件:GrDocMethodParamsImpl.java   
@Override
public PsiType[] getParameterTypes() {
  ArrayList<PsiType> types = new ArrayList<PsiType>();
  PsiManagerEx manager = getManager();
  GlobalSearchScope scope = GlobalSearchScope.allScope(getProject());
  PsiElementFactory factory = JavaPsiFacade.getInstance(getProject()).getElementFactory();
  for (GrDocMethodParameter parameter : getParameters()) {
    GrDocReferenceElement typeElement = parameter.getTypeElement();
    try {
      PsiType type = factory.createTypeFromText(typeElement.getText(), this);
      type = TypesUtil.boxPrimitiveType(type, manager, scope);
      types.add(type);
    } catch (IncorrectOperationException e) {
      LOG.info(e);
      types.add(null);
    }
  }
  return types.toArray(PsiType.createArray(types.size()));
}
项目:AndroidParcelablePlugin    文件:ParcelableListGenerator.java   
@Override
    public void readMethod(PsiCodeBlock methodBody, PsiElementFactory factory, PsiField field) {
        if (null == methodBody) {
            return;
        }

        String fieldName = field.getName();
        String parameterType = ((PsiClassReferenceType) field.getType()).getParameters()[0].getPresentableText();

//        // phones = new ArrayList<>();
//        // in.readTypedList(phones, Phone.CREATOR);
//        methodBody.add(factory.createStatementFromText(fieldName + " = new ArrayList<" + parameterType + ">();", null));
//        methodBody.add(factory.createStatementFromText("in.readTypedList(" + fieldName + ", " + parameterType + ".CREATOR);", null));

        // phones = in.createTypedArrayList(Phone.CREATOR);
        methodBody.add(factory.createStatementFromText(fieldName + " = in.createTypedArrayList(" + parameterType + ".CREATOR);", null));


    }
项目:google-cloud-intellij    文件:ConstructorInspectionTest.java   
public void testQuickFix_classWithNullaryConstructor() {
  ProblemDescriptorImpl problemDescriptorMock = mock(ProblemDescriptorImpl.class);
  MockitoAnnotations.initMocks(this);

  PsiElementFactory factory =
      JavaPsiFacade.getInstance(myFixture.getProject()).getElementFactory();
  PsiClass psiClass = factory.createClass(getName());
  PsiMethod nullaryConstructor =
      factory.createMethodFromText("public " + psiClass.getName() + "() { }", psiClass);
  psiClass.addAfter(nullaryConstructor, null);

  ConstructorInspection constructorInspection = new ConstructorInspection();
  ConstructorInspection.MyQuickFix myQuickFix = constructorInspection.new MyQuickFix(psiClass);
  myQuickFix.applyFix(myFixture.getProject(), problemDescriptorMock);
  Assert.assertEquals(1, psiClass.getConstructors().length);
  Assert.assertTrue(EndpointUtilities.isPublicNullaryConstructor(psiClass.getConstructors()[0]));
}
项目:google-cloud-intellij    文件:ConstructorInspectionTest.java   
public void testQuickFix_classWithNonNullaryConstructor() {
  ProblemDescriptorImpl problemDescriptorMock = mock(ProblemDescriptorImpl.class);
  MockitoAnnotations.initMocks(this);

  PsiElementFactory factory =
      JavaPsiFacade.getInstance(myFixture.getProject()).getElementFactory();
  PsiClass psiClass = factory.createClass(getName());
  PsiMethod nullaryConstructor =
      factory.createMethodFromText(
          "public " + psiClass.getName() + "(String param) { }", psiClass);
  psiClass.addAfter(nullaryConstructor, null);

  ConstructorInspection constructorInspection = new ConstructorInspection();
  ConstructorInspection.MyQuickFix myQuickFix = constructorInspection.new MyQuickFix(psiClass);
  myQuickFix.applyFix(myFixture.getProject(), problemDescriptorMock);
  Assert.assertEquals(2, psiClass.getConstructors().length);
  Assert.assertTrue(EndpointUtilities.isPublicNullaryConstructor(psiClass.getConstructors()[0]));
}
项目:GsonFormat    文件:Processor.java   
protected void generateConvertMethod(PsiElementFactory factory, PsiClass cls, ClassEntity classEntity) {
    if (cls == null || cls.getName() == null) {
        return;
    }
    if (Config.getInstant().isObjectFromData()) {
        createMethod(factory, Config.getInstant().getObjectFromDataStr().replace("$ClassName$", cls.getName()).trim(), cls);
    }
    if (Config.getInstant().isObjectFromData1()) {
        createMethod(factory, Config.getInstant().getObjectFromDataStr1().replace("$ClassName$", cls.getName()).trim(), cls);
    }
    if (Config.getInstant().isArrayFromData()) {
        createMethod(factory, Config.getInstant().getArrayFromDataStr().replace("$ClassName$", cls.getName()).trim(), cls);
    }
    if (Config.getInstant().isArrayFromData1()) {
        createMethod(factory, Config.getInstant().getArrayFromData1Str().replace("$ClassName$", cls.getName()).trim(), cls);
    }
}
项目:GsonFormat    文件:Processor.java   
protected void createMethod(PsiElementFactory factory, String method, PsiClass cls) {
    Try.run(new Try.TryListener() {
        @Override
        public void run() {
            cls.add(factory.createMethodFromText(method, cls));
        }

        @Override
        public void runAgain() {

        }

        @Override
        public void error() {

        }
    });
}
项目:GsonFormat    文件:Processor.java   
protected void generateField(PsiElementFactory factory, FieldEntity fieldEntity, PsiClass cls, ClassEntity classEntity) {

        if (fieldEntity.isGenerate()) {
            Try.run(new Try.TryListener() {
                @Override
                public void run() {
                    cls.add(factory.createFieldFromText(generateFieldText(classEntity, fieldEntity, null), cls));

                }

                @Override
                public void runAgain() {
                    fieldEntity.setFieldName(FieldHelper.generateLuckyFieldName(fieldEntity.getFieldName()));
                    cls.add(factory.createFieldFromText(generateFieldText(classEntity, fieldEntity, Constant.FIXME), cls));
                }

                @Override
                public void error() {
                    cls.addBefore(factory.createCommentFromText("// FIXME generate failure  field " + fieldEntity.getFieldName(), cls), cls.getChildren()[0]);
                }
            });

        }

    }
项目:GsonFormat    文件:FieldsDialog.java   
public FieldsDialog(ConvertBridge.Operator operator, ClassEntity classEntity,
                    PsiElementFactory factory, PsiClass psiClass, PsiClass aClass, PsiFile file, Project project
        , String generateClassStr) {
    this.operator = operator;
    this.factory = factory;
    this.aClass = aClass;
    this.file = file;
    this.project = project;
    this.psiClass = psiClass;
    this.generateClassStr = generateClassStr;
    setContentPane(contentPane);
    setTitle("Virgo Model");
    getRootPane().setDefaultButton(buttonOK);
    this.setAlwaysOnTop(true);
    initListener(classEntity, generateClassStr);
}
项目:tools-idea    文件:JavaCoreProjectEnvironment.java   
public JavaCoreProjectEnvironment(Disposable parentDisposable, CoreApplicationEnvironment applicationEnvironment) {
  super(parentDisposable, applicationEnvironment);

  myProject.registerService(PsiElementFactory.class, new PsiElementFactoryImpl(myPsiManager));
  myProject.registerService(JavaPsiImplementationHelper.class, createJavaPsiImplementationHelper());
  myProject.registerService(PsiResolveHelper.class, new PsiResolveHelperImpl(myPsiManager));
  myProject.registerService(LanguageLevelProjectExtension.class, new CoreLanguageLevelProjectExtension());
  myProject.registerService(JavaResolveCache.class, new JavaResolveCache(myMessageBus));
  myProject.registerService(JavaCodeStyleSettingsFacade.class, new CoreJavaCodeStyleSettingsFacade());
  myProject.registerService(JavaCodeStyleManager.class, new CoreJavaCodeStyleManager());
  registerProjectExtensionPoint(PsiElementFinder.EP_NAME, PsiElementFinder.class);

  myPackageIndex = createCorePackageIndex();
  myProject.registerService(PackageIndex.class, myPackageIndex);

  myFileManager = createCoreFileManager();
  myProject.registerService(JavaFileManager.class, myFileManager);

  JavaPsiFacadeImpl javaPsiFacade = new JavaPsiFacadeImpl(myProject, myPsiManager, myFileManager, myMessageBus);
  registerProjectComponent(JavaPsiFacade.class, javaPsiFacade);
  myProject.registerService(JavaPsiFacade.class, javaPsiFacade);
}
项目:tools-idea    文件:RemoveLeadingZeroFix.java   
@Override
protected void doFix(Project project, ProblemDescriptor descriptor)
  throws IncorrectOperationException {
  final PsiElement element = descriptor.getPsiElement();
  final String text = element.getText();
  final int max = text.length() - 1;
  if (max < 1) {
    return;
  }
  int index = 0;
  while (index < max && (text.charAt(index) == '0' || text.charAt(index) == '_')) {
    index++;
  }
  final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
  final PsiElementFactory factory = psiFacade.getElementFactory();
  final String textWithoutLeadingZeros = text.substring(index);
  final PsiExpression decimalNumber =
    factory.createExpressionFromText(textWithoutLeadingZeros,
                                     element);
  element.replace(decimalNumber);
}
项目:tools-idea    文件:GrDocMethodParamsImpl.java   
public PsiType[] getParameterTypes() {
  ArrayList<PsiType> types = new ArrayList<PsiType>();
  PsiManagerEx manager = getManager();
  GlobalSearchScope scope = GlobalSearchScope.allScope(getProject());
  PsiElementFactory factory = JavaPsiFacade.getInstance(getProject()).getElementFactory();
  for (GrDocMethodParameter parameter : getParameters()) {
    GrDocReferenceElement typeElement = parameter.getTypeElement();
    try {
      PsiType type = factory.createTypeFromText(typeElement.getText(), this);
      type = TypesUtil.boxPrimitiveType(type, manager, scope);
      types.add(type);
    } catch (IncorrectOperationException e) {
      LOG.info(e);
      types.add(null);
    }
  }
  return types.toArray(new PsiType[types.size()]);
}
项目:ParcelablePlease    文件:CodeGenerator.java   
private void addImport(PsiElementFactory elementFactory, String fullyQualifiedName){
  final PsiFile file = psiClass.getContainingFile();
  if (!(file instanceof PsiJavaFile)) {
    return;
  }
  final PsiJavaFile javaFile = (PsiJavaFile)file;

  final PsiImportList importList = javaFile.getImportList();
  if (importList == null) {
    return;
  }

  // Check if already imported
  for (PsiImportStatementBase is : importList.getAllImportStatements()) {
    String impQualifiedName = is.getImportReference().getQualifiedName();
    if (fullyQualifiedName.equals(impQualifiedName)){
      return; // Already imported so nothing neede
    }

  }

  // Not imported yet so add it
  importList.add(elementFactory.createImportStatementOnDemand(fullyQualifiedName));
}
项目:ParcelablePlease    文件:CodeGenerator.java   
/**
 * Make the class implementing Parcelable
 */
private void makeClassImplementParcelable(PsiElementFactory elementFactory, JavaCodeStyleManager styleManager) {
  final PsiClassType[] implementsListTypes = psiClass.getImplementsListTypes();
  final String implementsType = "android.os.Parcelable";

  for (PsiClassType implementsListType : implementsListTypes) {
    PsiClass resolved = implementsListType.resolve();

    // Already implements Parcelable, no need to add it
    if (resolved != null && implementsType.equals(resolved.getQualifiedName())) {
      return;
    }
  }

  PsiJavaCodeReferenceElement implementsReference =
      elementFactory.createReferenceFromText(implementsType, psiClass);
  PsiReferenceList implementsList = psiClass.getImplementsList();

  if (implementsList != null) {
    styleManager.shortenClassReferences(implementsList.add(implementsReference));
  }
}
项目:lombok-intellij-plugin    文件:AbstractLogProcessor.java   
private LombokLightFieldBuilder createLoggerField(@NotNull PsiClass psiClass, @NotNull PsiAnnotation psiAnnotation) {
  final Project project = psiClass.getProject();
  final PsiManager manager = psiClass.getContainingFile().getManager();

  final PsiElementFactory psiElementFactory = JavaPsiFacade.getElementFactory(project);
  final PsiType psiLoggerType = psiElementFactory.createTypeFromText(loggerType, psiClass);

  LombokLightFieldBuilder loggerField = new LombokLightFieldBuilder(manager, getLoggerName(psiClass), psiLoggerType)
    .withContainingClass(psiClass)
    .withModifier(PsiModifier.FINAL)
    .withModifier(PsiModifier.PRIVATE)
    .withNavigationElement(psiAnnotation);
  if (isLoggerStatic(psiClass)) {
    loggerField.withModifier(PsiModifier.STATIC);
  }

  final String loggerInitializerParameter = createLoggerInitializeParameter(psiClass, psiAnnotation);
  final PsiExpression initializer = psiElementFactory.createExpressionFromText(String.format(loggerInitializer, loggerInitializerParameter), psiClass);
  loggerField.setInitializer(initializer);
  return loggerField;
}
项目:lombok-intellij-plugin    文件:LombokLightMethodBuilder.java   
private PsiMethod rebuildMethodFromString() {
  final StringBuilder methodTextDeclaration = new StringBuilder();
  methodTextDeclaration.append(getAllModifierProperties((LightModifierList) getModifierList()));
  PsiType returnType = getReturnType();
  if (null != returnType) {
    methodTextDeclaration.append(returnType.getCanonicalText()).append(' ');
  }
  methodTextDeclaration.append(getName());
  methodTextDeclaration.append('(');
  if (getParameterList().getParametersCount() > 0) {
    for (PsiParameter parameter : getParameterList().getParameters()) {
      methodTextDeclaration.append(parameter.getType().getCanonicalText()).append(' ').append(parameter.getName()).append(',');
    }
    methodTextDeclaration.deleteCharAt(methodTextDeclaration.length() - 1);
  }
  methodTextDeclaration.append(')');
  methodTextDeclaration.append('{').append("  ").append('}');

  final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(getManager().getProject());

  final PsiMethod methodFromText = elementFactory.createMethodFromText(methodTextDeclaration.toString(), getContainingClass());
  if (null != getBody()) {
    methodFromText.getBody().replace(getBody());
  }
  return methodFromText;
}
项目:lombok-intellij-plugin    文件:PsiClassUtil.java   
/**
 * Creates a PsiType for a PsiClass enriched with generic substitution information if available
 */
@NotNull
private static PsiType getTypeWithGenerics(@NotNull PsiClass psiClass, @NotNull PsiTypeParameter... classTypeParameters) {
  PsiType result;
  final PsiElementFactory factory = JavaPsiFacade.getElementFactory(psiClass.getProject());
  if (classTypeParameters.length > 0) {
    Map<PsiTypeParameter, PsiType> substitutionMap = new HashMap<PsiTypeParameter, PsiType>();
    for (PsiTypeParameter typeParameter : classTypeParameters) {
      substitutionMap.put(typeParameter, factory.createType(typeParameter));
    }
    result = factory.createType(psiClass, factory.createSubstitutor(substitutionMap));
  } else {
    result = factory.createType(psiClass);
  }
  return result;
}
项目:lombok-intellij-plugin    文件:BaseDelombokHandler.java   
private PsiClass rebuildClass(@NotNull Project project, @NotNull PsiClass fromClass) {
  final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);

  PsiClass resultClass = elementFactory.createClass(StringUtil.defaultIfEmpty(fromClass.getName(), "UnknownClassName"));
  copyModifiers(fromClass.getModifierList(), resultClass.getModifierList());
  rebuildTypeParameter(fromClass, resultClass);

  for (PsiField psiField : fromClass.getFields()) {
    resultClass.add(rebuildField(project, psiField));
  }
  for (PsiMethod psiMethod : fromClass.getMethods()) {
    resultClass.add(rebuildMethod(project, psiMethod));
  }

  return (PsiClass) CodeStyleManager.getInstance(project).reformat(resultClass);
}
项目:consulo-javafx    文件:JavaFxGetterSetterPrototypeProvider.java   
@Override
public PsiMethod[] generateGetters(PsiField field) {
  final Project project = field.getProject();
  final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
  final PsiMethod getter = PropertyUtil.generateGetterPrototype(field);

  final PsiType wrappedType = JavaFxPsiUtil.getWrappedPropertyType(field, project, JavaFxCommonClassNames.ourReadOnlyMap);

  final PsiTypeElement returnTypeElement = getter.getReturnTypeElement();
  LOG.assertTrue(returnTypeElement != null);
  returnTypeElement.replace(factory.createTypeElement(wrappedType));

  final PsiCodeBlock getterBody = getter.getBody();
  LOG.assertTrue(getterBody != null);
  getterBody.getStatements()[0].replace(factory.createStatementFromText("return " + field.getName() + ".get();", field));

  final PsiMethod propertyGetter = PropertyUtil.generateGetterPrototype(field);
  propertyGetter.setName(JavaCodeStyleManager.getInstance(project).variableNameToPropertyName(field.getName(), VariableKind.FIELD) + "Property");
  return new PsiMethod[] {getter, propertyGetter};
}
项目:consulo-javafx    文件:JavaFxGetterSetterPrototypeProvider.java   
@Override
public PsiMethod[] generateSetters(PsiField field) {
  final PsiMethod setter = PropertyUtil.generateSetterPrototype(field);
  final Project project = field.getProject();

  final PsiType wrappedType = JavaFxPsiUtil.getWrappedPropertyType(field, project, JavaFxCommonClassNames.ourWritableMap);

  final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
  final PsiTypeElement newTypeElement = elementFactory.createTypeElement(wrappedType);
  final PsiParameter[] parameters = setter.getParameterList().getParameters();
  LOG.assertTrue(parameters.length == 1);
  final PsiParameter parameter = parameters[0];
  final PsiTypeElement typeElement = parameter.getTypeElement();
  LOG.assertTrue(typeElement != null);
  typeElement.replace(newTypeElement);
  final PsiCodeBlock body = setter.getBody();
  LOG.assertTrue(body != null);
  body.getStatements()[0].replace(elementFactory.createStatementFromText("this." + field.getName() + ".set(" + parameter.getName() + ");", field));

  return new PsiMethod[] {setter};
}
项目:intelliJGenPropertyEnumsPlugin    文件:GeneratePropertyEnumsActionHandler.java   
@Override
public void executeWriteAction(final Editor editor, final DataContext dataContext) {


    PsiHelper util = ApplicationManager.getApplication().getComponent(PsiHelper.class);
    JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(editor.getProject());
    PsiElementFactory psiElementFactory = psiFacade.getElementFactory();
    PsiClass clazz = util.getCurrentClass(editor);

    PsiClass psiCls = psiElementFactory.createEnum("Fields");

    for (PsiField field : clazz.getFields()) {
        String fieldName = field.getName();
        String methodNameSuffix = util.capitalize(fieldName);
        String fieldType = field.getType().getCanonicalText();

        psiCls.add(psiElementFactory.createEnumConstantFromText(field.getName(), psiCls));

    }
    clazz.add(psiCls);
}
项目:CopyConstructorPlugin    文件:GenerateCopyConstructorHandler.java   
private PsiMethod generateCopyConstructor(PsiClass psiClass, ClassMember[] copyableFields) {
    String parameterName = "other";

    StringBuilder code = new StringBuilder();
    code.append(String.format("public %s(%s %s) {", psiClass.getName(), psiClass.getName(), parameterName));

    boolean superclassHasCopyConstructor = ConstructorUtil.hasCopyConstructor(psiClass.getSuperClass());
    if (superclassHasCopyConstructor) {
        code.append(String.format("super(%s);", parameterName));
    }

    for (ClassMember fieldMember : copyableFields) {
        PsiField field = ((PsiFieldMember) fieldMember).getElement();
        String name = field.getName();
        code.append(String.format("this.%s = %s.%s;", name, parameterName, name));
    }
    code.append("}");

    PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(psiClass.getProject());
    PsiMethod constructor = elementFactory.createMethodFromText(code.toString(), psiClass);
    return constructor;
}
项目:consulo-apache-velocity    文件:VelocityNamingUtil.java   
@SuppressWarnings("HardCodedStringLiteral")
public static boolean isGetByStringOrByObjectMethod(@NotNull PsiMethod method)
{
    String methodName = method.getName();
    if(!"get".equals(methodName))
    {
        return false;
    }
    PsiParameterList parameterList = method.getParameterList();
    if(parameterList.getParametersCount() != 1)
    {
        return false;
    }
    PsiParameter parameter = parameterList.getParameters()[0];
    final PsiElementFactory factory = JavaPsiFacade.getInstance(method.getProject()).getElementFactory();
    PsiClassType javaLangString = factory.createTypeByFQClassName(JavaClassNames.JAVA_LANG_STRING, method.getResolveScope());
    if(parameter.getType().isAssignableFrom(javaLangString))
    {
        return true;
    }
    PsiClassType javaLangObject = factory.createTypeByFQClassName(JavaClassNames.JAVA_LANG_OBJECT, method.getResolveScope());
    return parameter.getType().isAssignableFrom(javaLangObject);
}
项目:consulo-java    文件:PsiReferenceListImpl.java   
@Override
@NotNull
public PsiClassType[] getReferencedTypes()
{
    PsiClassReferenceListStub stub = getGreenStub();
    if(stub != null)
    {
        return stub.getReferencedTypes();
    }

    PsiJavaCodeReferenceElement[] refs = getReferenceElements();
    PsiElementFactory factory = JavaPsiFacade.getInstance(getProject()).getElementFactory();
    PsiClassType[] types = new PsiClassType[refs.length];
    for(int i = 0; i < types.length; i++)
    {
        types[i] = factory.createType(refs[i]);
    }

    return types;
}
项目:consulo-java    文件:ScopedClassHierarchy.java   
@NotNull
private Map<PsiClass, PsiSubstitutor> calcAllMemberSupers(final LanguageLevel level)
{
    final Map<PsiClass, PsiSubstitutor> map = ContainerUtil.newTroveMap();
    final PsiElementFactory factory = JavaPsiFacade.getElementFactory(myPlaceClass.getProject());
    new PairProcessor<PsiClass, PsiSubstitutor>()
    {
        @Override
        public boolean process(PsiClass eachClass, PsiSubstitutor eachSubstitutor)
        {
            if(!map.containsKey(eachClass))
            {
                map.put(eachClass, eachSubstitutor);
                PsiClassImplUtil.processSuperTypes(eachClass, eachSubstitutor, factory, level, myResolveScope, this);
            }
            return true;
        }
    }.process(myPlaceClass, PsiSubstitutor.EMPTY);
    return map;
}
项目:consulo-java    文件:JavaCoreProjectEnvironment.java   
public JavaCoreProjectEnvironment(Disposable parentDisposable, CoreApplicationEnvironment applicationEnvironment) {
   super(parentDisposable, applicationEnvironment);

   myProject.registerService(PsiElementFactory.class, new PsiElementFactoryImpl(myPsiManager));
   myProject.registerService(JavaPsiImplementationHelper.class, createJavaPsiImplementationHelper());
   myProject.registerService(PsiResolveHelper.class, new PsiResolveHelperImpl(myPsiManager));
   myProject.registerService(JavaResolveCache.class, new JavaResolveCache(myMessageBus));
   myProject.registerService(JavaCodeStyleSettingsFacade.class, new CoreJavaCodeStyleSettingsFacade());
   myProject.registerService(JavaCodeStyleManager.class, new CoreJavaCodeStyleManager());
   registerProjectExtensionPoint(PsiElementFinder.EP_NAME, PsiElementFinder.class);

/*   myPackageIndex = createCorePackageIndex();
   myProject.registerService(PackageIndex.class, myPackageIndex);     */

   myFileManager = createCoreFileManager();
   myProject.registerService(JavaFileManager.class, myFileManager);

   PsiPackageManager manager = new PsiPackageManagerImpl(getProject(), DirectoryIndex.getInstance(getProject()));

   myProject.registerService(PsiPackageManager.class, manager);

   JavaPsiFacadeImpl javaPsiFacade = new JavaPsiFacadeImpl(myProject, manager);
   registerProjectComponent(JavaPsiFacade.class, javaPsiFacade);
   myProject.registerService(JavaPsiFacade.class, javaPsiFacade);
 }
项目:consulo-java    文件:SimplifyToAssignmentFix.java   
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor)
{
    final PsiElement psiElement = descriptor.getPsiElement();
    if(psiElement == null)
    {
        return;
    }

    final PsiAssignmentExpression assignmentExpression = PsiTreeUtil.getParentOfType(psiElement, PsiAssignmentExpression.class);
    if(assignmentExpression == null)
    {
        return;
    }

    final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
    final String lExpressionText = assignmentExpression.getLExpression().getText();
    final PsiExpression rExpression = assignmentExpression.getRExpression();
    final String rExpressionText = rExpression != null ? rExpression.getText() : "";
    assignmentExpression.replace(factory.createExpressionFromText(lExpressionText + " = " + rExpressionText, psiElement));
}
项目:consulo-java    文件:FlipIntersectionSidesFix.java   
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException
{
    if(!FileModificationService.getInstance().prepareFileForWrite(file))
    {
        return;
    }
    myConjuncts.remove(myConjunct);
    myConjuncts.add(0, myConjunct);

    final String intersectionTypeText = StringUtil.join(myConjuncts, new Function<PsiTypeElement, String>()
    {
        @Override
        public String fun(PsiTypeElement element)
        {
            return element.getText();
        }
    }, " & ");
    final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
    final PsiTypeCastExpression fixedCast = (PsiTypeCastExpression) elementFactory.createExpressionFromText("(" +
            intersectionTypeText + ") a", myCastTypeElement);
    final PsiTypeElement fixedCastCastType = fixedCast.getCastType();
    LOG.assertTrue(fixedCastCastType != null);
    final PsiElement flippedTypeElement = myCastTypeElement.replace(fixedCastCastType);
    CodeStyleManager.getInstance(project).reformat(flippedTypeElement);
}
项目:consulo-java    文件:BlockUtils.java   
/**
 * Add new statement after given anchor statement creating code block, if necessary
 *
 * @param anchor       existing statement
 * @param newStatement a new statement which should be added after an existing one
 * @return added physical statement
 */
public static PsiStatement addAfter(PsiStatement anchor, PsiStatement newStatement)
{
    PsiElement oldStatement = anchor;
    PsiElement parent = oldStatement.getParent();
    while(parent instanceof PsiLabeledStatement)
    {
        oldStatement = parent;
        parent = oldStatement.getParent();
    }
    final PsiElement result;
    if(parent instanceof PsiCodeBlock)
    {
        result = parent.addAfter(newStatement, oldStatement);
    }
    else
    {
        PsiElementFactory factory = JavaPsiFacade.getElementFactory(anchor.getProject());
        final PsiBlockStatement newBlockStatement = (PsiBlockStatement) factory.createStatementFromText("{}", oldStatement);
        final PsiElement codeBlock = newBlockStatement.getCodeBlock();
        codeBlock.add(oldStatement);
        codeBlock.add(newStatement);
        result = ((PsiBlockStatement) oldStatement.replace(newBlockStatement)).getCodeBlock().getStatements()[1];
    }
    return (PsiStatement) result;
}