use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.
the class InlineToAnonymousConstructorProcessor method generateLocal.
private PsiVariable generateLocal(final String baseName, final PsiType type, final PsiExpression initializer) {
final Project project = myClass.getProject();
final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
String baseNameForIndex = baseName;
int index = 0;
String localName;
while (true) {
localName = codeStyleManager.suggestUniqueVariableName(baseNameForIndex, myNewExpression, true);
if (myClass.findFieldByName(localName, false) == null) {
break;
}
index++;
baseNameForIndex = baseName + index;
}
try {
final PsiDeclarationStatement declaration = myElementFactory.createVariableDeclarationStatement(localName, type, initializer);
PsiVariable variable = (PsiVariable) declaration.getDeclaredElements()[0];
if (!PsiUtil.isLanguageLevel8OrHigher(myNewExpression) || CodeStyleSettingsManager.getSettings(project).GENERATE_FINAL_LOCALS) {
PsiUtil.setModifierProperty(variable, PsiModifier.FINAL, true);
}
final PsiElement parent = myNewStatement.getParent();
if (parent instanceof PsiCodeBlock) {
variable = (PsiVariable) ((PsiDeclarationStatement) parent.addBefore(declaration, myNewStatement)).getDeclaredElements()[0];
} else {
final int offsetInStatement = myNewExpression.getTextRange().getStartOffset() - myNewStatement.getTextRange().getStartOffset();
final PsiBlockStatement blockStatement = (PsiBlockStatement) myElementFactory.createStatementFromText("{}", null);
PsiCodeBlock block = blockStatement.getCodeBlock();
block.add(declaration);
block.add(myNewStatement);
block = ((PsiBlockStatement) myNewStatement.replace(blockStatement)).getCodeBlock();
variable = (PsiVariable) ((PsiDeclarationStatement) block.getStatements()[0]).getDeclaredElements()[0];
myNewStatement = block.getStatements()[1];
myNewExpression = PsiTreeUtil.getParentOfType(myNewStatement.findElementAt(offsetInStatement), PsiNewExpression.class);
}
return variable;
} catch (IncorrectOperationException e) {
LOG.error(e);
return null;
}
}
use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.
the class InputVariables method getParameterName.
private String getParameterName(PsiVariable var) {
String name = var.getName();
if (!(var instanceof PsiParameter)) {
JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(myProject);
VariableKind kind = codeStyleManager.getVariableKind(var);
name = codeStyleManager.variableNameToPropertyName(name, kind);
name = codeStyleManager.propertyNameToVariableName(name, VariableKind.PARAMETER);
}
return name;
}
use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.
the class MakeStaticUtil method collectVariableData.
public static boolean collectVariableData(PsiMember member, InternalUsageInfo[] internalUsages, ArrayList<VariableData> variableDatum) {
HashSet<PsiField> reported = new HashSet<>();
HashSet<PsiField> accessedForWriting = new HashSet<>();
boolean needClassParameter = false;
for (InternalUsageInfo usage : internalUsages) {
final PsiElement referencedElement = usage.getReferencedElement();
if (usage.isWriting()) {
accessedForWriting.add((PsiField) referencedElement);
needClassParameter = true;
} else if (referencedElement instanceof PsiField) {
PsiField field = (PsiField) referencedElement;
reported.add(field);
} else {
needClassParameter = true;
}
}
final ArrayList<PsiField> psiFields = new ArrayList<>(reported);
Collections.sort(psiFields, (psiField, psiField1) -> psiField.getName().compareTo(psiField1.getName()));
for (final PsiField field : psiFields) {
if (accessedForWriting.contains(field))
continue;
VariableData data = new VariableData(field);
JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(member.getProject());
String name = field.getName();
name = codeStyleManager.variableNameToPropertyName(name, VariableKind.FIELD);
name = codeStyleManager.propertyNameToVariableName(name, VariableKind.PARAMETER);
name = RefactoringUtil.suggestUniqueVariableName(name, member, field);
data.name = name;
data.passAsParameter = true;
variableDatum.add(data);
}
return needClassParameter;
}
use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.
the class PsiReferenceExpressionImpl method bindToElement.
@Override
public PsiElement bindToElement(@NotNull final PsiElement element) throws IncorrectOperationException {
CheckUtil.checkWritable(this);
if (isReferenceTo(element))
return this;
final PsiManager manager = getManager();
final PsiJavaParserFacade parserFacade = JavaPsiFacade.getInstance(getProject()).getParserFacade();
if (element instanceof PsiClass) {
final boolean preserveQualification = JavaCodeStyleSettingsFacade.getInstance(getProject()).useFQClassNames() && isFullyQualified(this);
String qName = ((PsiClass) element).getQualifiedName();
if (qName == null) {
qName = ((PsiClass) element).getName();
} else if (JavaPsiFacade.getInstance(manager.getProject()).findClass(qName, getResolveScope()) == null && !preserveQualification) {
return this;
}
PsiExpression ref = parserFacade.createExpressionFromText(qName, this);
getTreeParent().replaceChildInternal(this, (TreeElement) ref.getNode());
final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(manager.getProject());
if (!preserveQualification) {
ref = (PsiExpression) codeStyleManager.shortenClassReferences(ref, JavaCodeStyleManager.INCOMPLETE_CODE);
}
return ref;
} else if (element instanceof PsiPackage) {
final String qName = ((PsiPackage) element).getQualifiedName();
if (qName.isEmpty()) {
throw new IncorrectOperationException();
}
final PsiExpression ref = parserFacade.createExpressionFromText(qName, this);
getTreeParent().replaceChildInternal(this, (TreeElement) ref.getNode());
return ref;
} else if ((element instanceof PsiField || element instanceof PsiMethod) && ((PsiMember) element).hasModifierProperty(PsiModifier.STATIC)) {
if (!isPhysical()) {
// don't qualify reference: the isReferenceTo() check fails anyway, whether we have a static import for this member or not
return this;
}
final PsiMember member = (PsiMember) element;
final PsiClass psiClass = member.getContainingClass();
if (psiClass == null)
throw new IncorrectOperationException();
final String qName = psiClass.getQualifiedName() + "." + member.getName();
final PsiExpression ref = parserFacade.createExpressionFromText(qName, this);
getTreeParent().replaceChildInternal(this, (TreeElement) ref.getNode());
return ref;
} else {
throw new IncorrectOperationException(element.toString());
}
}
use of com.intellij.psi.codeStyle.JavaCodeStyleManager in project intellij-community by JetBrains.
the class Generator method generateDataBindingMethods.
/**
* Should be invoked in command and write action
*/
@SuppressWarnings({ "HardCodedStringLiteral" })
public static void generateDataBindingMethods(final WizardData data) throws MyException {
if (data.myBindToNewBean) {
data.myBeanClass = createBeanClass(data);
} else {
if (!CommonRefactoringUtil.checkReadOnlyStatus(data.myBeanClass.getProject(), data.myBeanClass)) {
return;
}
}
final HashMap<String, String> binding2beanGetter = new HashMap<>();
final HashMap<String, String> binding2beanSetter = new HashMap<>();
final FormProperty2BeanProperty[] bindings = data.myBindings;
for (final FormProperty2BeanProperty form2bean : bindings) {
if (form2bean == null || form2bean.myBeanProperty == null) {
continue;
}
// check that bean contains the property, and if not, try to add the property to the bean
{
final String setterName = PropertyUtil.suggestSetterName(form2bean.myBeanProperty.myName);
final PsiMethod[] methodsByName = data.myBeanClass.findMethodsByName(setterName, true);
if (methodsByName.length < 1) {
// bean does not contain this property
// try to add...
// just generated bean class should contain all necessary properties
LOG.assertTrue(!data.myBindToNewBean);
if (!data.myBeanClass.isWritable()) {
throw new MyException("Cannot add property to non writable class " + data.myBeanClass.getQualifiedName());
}
final StringBuffer membersBuffer = new StringBuffer();
final StringBuffer methodsBuffer = new StringBuffer();
final Project project = data.myBeanClass.getProject();
final CodeStyleManager formatter = CodeStyleManager.getInstance(project);
final JavaCodeStyleManager styler = JavaCodeStyleManager.getInstance(project);
generateProperty(styler, form2bean.myBeanProperty.myName, form2bean.myBeanProperty.myType, membersBuffer, methodsBuffer);
final PsiClass fakeClass;
try {
fakeClass = JavaPsiFacade.getInstance(data.myBeanClass.getProject()).getElementFactory().createClassFromText(membersBuffer.toString() + methodsBuffer.toString(), null);
final PsiField[] fields = fakeClass.getFields();
{
final PsiElement result = data.myBeanClass.add(fields[0]);
styler.shortenClassReferences(result);
formatter.reformat(result);
}
final PsiMethod[] methods = fakeClass.getMethods();
{
final PsiElement result = data.myBeanClass.add(methods[0]);
styler.shortenClassReferences(result);
formatter.reformat(result);
}
{
final PsiElement result = data.myBeanClass.add(methods[1]);
styler.shortenClassReferences(result);
formatter.reformat(result);
}
} catch (IncorrectOperationException e) {
throw new MyException(e.getMessage());
}
}
}
final PsiMethod propertySetter = PropertyUtil.findPropertySetter(data.myBeanClass, form2bean.myBeanProperty.myName, false, true);
final PsiMethod propertyGetter = PropertyUtil.findPropertyGetter(data.myBeanClass, form2bean.myBeanProperty.myName, false, true);
if (propertyGetter == null) {
// todo
continue;
}
if (propertySetter == null) {
// todo
continue;
}
final String binding = form2bean.myFormProperty.getLwComponent().getBinding();
binding2beanGetter.put(binding, propertyGetter.getName());
binding2beanSetter.put(binding, propertySetter.getName());
}
final String dataBeanClassName = data.myBeanClass.getQualifiedName();
final LwRootContainer[] rootContainer = new LwRootContainer[1];
final FormProperty[] formProperties = exposeForm(data.myProject, data.myFormFile, rootContainer);
final StringBuffer getDataBody = new StringBuffer();
final StringBuffer setDataBody = new StringBuffer();
final StringBuffer isModifiedBody = new StringBuffer();
for (final FormProperty formProperty : formProperties) {
final String binding = formProperty.getLwComponent().getBinding();
if (!binding2beanGetter.containsKey(binding)) {
continue;
}
getDataBody.append("data.");
getDataBody.append(binding2beanSetter.get(binding));
getDataBody.append("(");
getDataBody.append(binding);
getDataBody.append(".");
getDataBody.append(formProperty.getComponentPropertyGetterName());
getDataBody.append("());\n");
setDataBody.append(binding);
setDataBody.append(".");
setDataBody.append(formProperty.getComponentPropertySetterName());
setDataBody.append("(data.");
setDataBody.append(binding2beanGetter.get(binding));
setDataBody.append("());\n");
final String propertyClassName = formProperty.getComponentPropertyClassName();
if ("boolean".equals(propertyClassName)) {
isModifiedBody.append("if (");
//
isModifiedBody.append(binding);
isModifiedBody.append(".");
isModifiedBody.append(formProperty.getComponentPropertyGetterName());
isModifiedBody.append("()");
//
isModifiedBody.append("!= ");
//
isModifiedBody.append("data.");
isModifiedBody.append(binding2beanGetter.get(binding));
isModifiedBody.append("()");
//
isModifiedBody.append(") return true;\n");
} else {
isModifiedBody.append("if (");
//
isModifiedBody.append(binding);
isModifiedBody.append(".");
isModifiedBody.append(formProperty.getComponentPropertyGetterName());
isModifiedBody.append("()");
//
isModifiedBody.append("!= null ? ");
//
isModifiedBody.append("!");
//
isModifiedBody.append(binding);
isModifiedBody.append(".");
isModifiedBody.append(formProperty.getComponentPropertyGetterName());
isModifiedBody.append("()");
//
isModifiedBody.append(".equals(");
//
isModifiedBody.append("data.");
isModifiedBody.append(binding2beanGetter.get(binding));
isModifiedBody.append("()");
isModifiedBody.append(") : ");
//
isModifiedBody.append("data.");
isModifiedBody.append(binding2beanGetter.get(binding));
isModifiedBody.append("()");
isModifiedBody.append("!= null");
//
isModifiedBody.append(") return true;\n");
}
}
isModifiedBody.append("return false;\n");
final String textOfMethods = "public void setData(" + dataBeanClassName + " data){\n" + setDataBody.toString() + "}\n" + "\n" + "public void getData(" + dataBeanClassName + " data){\n" + getDataBody.toString() + "}\n" + "\n" + "public boolean isModified(" + dataBeanClassName + " data){\n" + isModifiedBody.toString() + "}\n";
// put them to the bound class
final Module module = ModuleUtil.findModuleForFile(data.myFormFile, data.myProject);
LOG.assertTrue(module != null);
final PsiClass boundClass = FormEditingUtil.findClassToBind(module, rootContainer[0].getClassToBind());
LOG.assertTrue(boundClass != null);
if (!CommonRefactoringUtil.checkReadOnlyStatus(module.getProject(), boundClass)) {
return;
}
// todo: check that this method does not exist yet
final PsiClass fakeClass;
try {
fakeClass = JavaPsiFacade.getInstance(data.myProject).getElementFactory().createClassFromText(textOfMethods, null);
final PsiMethod methodSetData = fakeClass.getMethods()[0];
final PsiMethod methodGetData = fakeClass.getMethods()[1];
final PsiMethod methodIsModified = fakeClass.getMethods()[2];
final PsiMethod existing1 = boundClass.findMethodBySignature(methodSetData, false);
final PsiMethod existing2 = boundClass.findMethodBySignature(methodGetData, false);
final PsiMethod existing3 = boundClass.findMethodBySignature(methodIsModified, false);
// warning already shown
if (existing1 != null) {
existing1.delete();
}
if (existing2 != null) {
existing2.delete();
}
if (existing3 != null) {
existing3.delete();
}
final CodeStyleManager formatter = CodeStyleManager.getInstance(module.getProject());
final JavaCodeStyleManager styler = JavaCodeStyleManager.getInstance(module.getProject());
final PsiElement setData = boundClass.add(methodSetData);
styler.shortenClassReferences(setData);
formatter.reformat(setData);
final PsiElement getData = boundClass.add(methodGetData);
styler.shortenClassReferences(getData);
formatter.reformat(getData);
if (data.myGenerateIsModified) {
final PsiElement isModified = boundClass.add(methodIsModified);
styler.shortenClassReferences(isModified);
formatter.reformat(isModified);
}
final OpenFileDescriptor descriptor = new OpenFileDescriptor(setData.getProject(), setData.getContainingFile().getVirtualFile(), setData.getTextOffset());
FileEditorManager.getInstance(data.myProject).openTextEditor(descriptor, true);
} catch (IncorrectOperationException e) {
throw new MyException(e.getMessage());
}
}
Aggregations