List of usage examples for org.eclipse.jdt.core.dom FieldDeclaration getParent
public final ASTNode getParent()
null
if this is the root node. From source file:com.google.devtools.j2cpp.gen.CppImplementationGenerator.java
License:Open Source License
private void printProperties(FieldDeclaration[] fields) { int nPrinted = 0; for (FieldDeclaration field : fields) { if ((field.getModifiers() & Modifier.STATIC) == 0) { @SuppressWarnings("unchecked") List<VariableDeclarationFragment> vars = field.fragments(); // safe by definition for (VariableDeclarationFragment var : vars) { if (var.getName().getIdentifier().startsWith("this$") && superDefinesVariable(var)) { // Don't print, as it shadows an inner field in a super class. continue; }/*from w w w . jav a 2 s . c om*/ String name = NameTable.getName(var.getName()); ITypeBinding type = Types.getTypeBinding(field.getType()); String typeString = NameTable.javaRefToCpp(type); if (!typeString.endsWith("*")) { typeString += " "; } // Don't emit the getter when there is already a method with the // same name. // TODO(user,user): Update when getters are merged with property // accessors (see issues). boolean noGetter = false; ITypeBinding declaringClass = Types.getTypeBinding(field.getParent()); if (declaringClass != null) { IMethodBinding[] methods = declaringClass.getDeclaredMethods(); for (IMethodBinding method : methods) { if (method.getName().equals(name) && method.getParameterTypes().length == 0) { noGetter = true; break; } } } String objCFieldName = NameTable.javaFieldToCpp(name); // Getter if (!noGetter) { printf(String.format("- (%s)%s {\n return %s;\n}\n\n", typeString.trim(), name, objCFieldName)); } // Setter printf(String.format("- (void)set%s:(%s)new%s {\n", NameTable.capitalize(name), typeString.trim(), NameTable.capitalize(name))); if (type.isPrimitive()) { printf(String.format(" %s = new%s;\n}\n\n", objCFieldName, NameTable.capitalize(name))); } else if (Options.useReferenceCounting() && !Types.isWeakReference(Types.getVariableBinding(var))) { String retentionMethod = type.isEqualTo(Types.getNSString()) ? "copy" : "retain"; printf(String.format(" [%s autorelease];\n %s = [new%s %s];\n}\n\n", objCFieldName, objCFieldName, NameTable.capitalize(name), retentionMethod)); } else { printf(String.format(" %s = new%s;\n}\n\n", objCFieldName, NameTable.capitalize(name))); } nPrinted++; } } } if (nPrinted > 0) { newline(); } }
From source file:com.google.devtools.j2cpp.translate.Rewriter.java
License:Open Source License
@Override public boolean visit(FieldDeclaration node) { int mods = node.getModifiers(); if (Modifier.isStatic(mods)) { ASTNode parent = node.getParent(); @SuppressWarnings("unchecked") List<BodyDeclaration> classMembers = parent instanceof AbstractTypeDeclaration ? ((AbstractTypeDeclaration) parent).bodyDeclarations() : ((AnonymousClassDeclaration) parent).bodyDeclarations(); // safe by specification int indexOfNewMember = classMembers.indexOf(node) + 1; @SuppressWarnings("unchecked") List<VariableDeclarationFragment> fragments = node.fragments(); // safe by specification for (VariableDeclarationFragment var : fragments) { IVariableBinding binding = Types.getVariableBinding(var); if (Types.isPrimitiveConstant(binding) && Modifier.isPrivate(binding.getModifiers())) { // Don't define accessors for private constants, since they can be // directly referenced. continue; }/*from w w w . java2 s . com*/ // rename varName to varName_, per Obj-C style guide SimpleName oldName = var.getName(); ITypeBinding type = ((AbstractTypeDeclaration) node.getParent()).resolveBinding(); String varName = NameTable.getStaticVarQualifiedName(type, oldName.getIdentifier()); NameTable.rename(binding, varName); ITypeBinding typeBinding = binding.getType(); var.setExtraDimensions(0); // if array, type was corrected above // add accessor(s) if (needsReader(var, classMembers)) { classMembers.add(indexOfNewMember++, makeStaticReader(var, mods)); } if (!Modifier.isFinal(node.getModifiers()) && needsWriter(var, classMembers)) { classMembers.add(indexOfNewMember++, makeStaticWriter(var, oldName.getIdentifier(), node.getType(), mods)); } // move non-constant initialization to init block Expression initializer = var.getInitializer(); if (initializer != null && initializer.resolveConstantExpressionValue() == null) { var.setInitializer(null); AST ast = var.getAST(); SimpleName newName = ast.newSimpleName(varName); Types.addBinding(newName, binding); Assignment assign = ast.newAssignment(); assign.setLeftHandSide(newName); Expression newInit = NodeCopier.copySubtree(ast, initializer); assign.setRightHandSide(newInit); Types.addBinding(assign, typeBinding); Block initBlock = ast.newBlock(); @SuppressWarnings("unchecked") List<Statement> stmts = initBlock.statements(); // safe by definition stmts.add(ast.newExpressionStatement(assign)); Initializer staticInitializer = ast.newInitializer(); staticInitializer.setBody(initBlock); @SuppressWarnings("unchecked") List<IExtendedModifier> initMods = staticInitializer.modifiers(); // safe by definition initMods.add(ast.newModifier(ModifierKeyword.STATIC_KEYWORD)); classMembers.add(indexOfNewMember++, staticInitializer); } } } return true; }
From source file:com.motorola.studio.android.generateviewbylayout.GenerateCodeBasedOnLayoutVisitor.java
License:Apache License
/** * Check if there is an attribute already declared with the name given. * @param node/*w w w.jav a2 s . c o m*/ * @param considerType false, if must not consider the type in the analysis * @return true if there a variable declared with the node.getNodeId() independent on variable type, * false otherwise */ public boolean checkIfAttributeAlreadyDeclared(LayoutNode node, boolean considerType) { boolean containFieldDeclared = false; if (typeDeclaration.bodyDeclarations() != null) { //check if attribute already declared for (Object bd : typeDeclaration.bodyDeclarations()) { if (bd instanceof FieldDeclaration) { FieldDeclaration fd = (FieldDeclaration) bd; if (fd.getParent() instanceof TypeDeclaration) { TypeDeclaration type = (TypeDeclaration) fd.getParent(); if (typeDeclaration.equals(type)) { //only considers attributes from main class inside the file for (Object fragment : fd.fragments()) { if (fragment instanceof VariableDeclarationFragment) { VariableDeclarationFragment frag = (VariableDeclarationFragment) fragment; if ((frag.getName() != null) && frag.getName().toString().equals(node.getNodeId())) { if (considerType) { if ((fd.getType() != null) && !fd.getType().toString().equals(node.getNodeType())) { containFieldDeclared = true; break; } } else { containFieldDeclared = true; break; } } } } } } } } } return containFieldDeclared; }
From source file:info.okoshi.visitor.AccessorsGenerateVisitor.java
License:Open Source License
/** * {@inheritDoc}// w w w . j a v a2 s. c o m * * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.FieldDeclaration) */ @Override public boolean visit(FieldDeclaration node) { if (!isAccessbileField(node)) { return super.visit(node); } TypeDeclaration parent = (TypeDeclaration) node.getParent(); AST ast = parent.getAST(); VariableDeclarationFragment var = (VariableDeclarationFragment) node.fragments().get(0); String name = var.getName().getIdentifier(); switch (generateAccessorType) { case GETTERS_AND_SETTERS: addAccessorMethodIfNotExists(parent, generateGetter(node, ast, name)); addAccessorMethodIfNotExists(parent, generateSetter(node, ast, name)); break; case GETTERS_ONLY: addAccessorMethodIfNotExists(parent, generateGetter(node, ast, name)); break; default: // means "case SETTERS_ONLY:" addAccessorMethodIfNotExists(parent, generateSetter(node, ast, name)); } return super.visit(node); }
From source file:net.sf.j2s.core.astvisitors.ASTScriptVisitor.java
License:Open Source License
public boolean visitWith(FieldDeclaration node, boolean ignoreInitializer) { if ((node.getModifiers() & Modifier.STATIC) != 0) { return false; }// w w w . j a va2 s . co m ASTNode xparent = node.getParent(); while (xparent != null && !(xparent instanceof AbstractTypeDeclaration) && !(xparent instanceof AnonymousClassDeclaration)) { xparent = xparent.getParent(); } ITypeBinding typeBinding = null; //ITypeBinding anonBinding = null; if (xparent != null) { if (xparent instanceof AbstractTypeDeclaration) { AbstractTypeDeclaration type = (AbstractTypeDeclaration) xparent; typeBinding = type.resolveBinding(); } else if (xparent instanceof AnonymousClassDeclaration) { AnonymousClassDeclaration type = (AnonymousClassDeclaration) xparent; typeBinding = type.resolveBinding();//.getSuperclass(); } } List fragments = node.fragments(); for (Iterator iter = fragments.iterator(); iter.hasNext();) { VariableDeclarationFragment element = (VariableDeclarationFragment) iter.next(); String fieldName = getJ2SName(element.getName()); // String fieldName = element.getName().getIdentifier(); String ext = ""; if (checkKeyworkViolation(fieldName)) { ext += "$"; } if (typeBinding != null && checkSameName(typeBinding, fieldName)) { ext += "$"; } //fieldName = ext + fieldName; //buffer.append(fieldName); buffer.append("this."); if (isInheritedFieldName(typeBinding, fieldName)) { fieldName = getFieldName(typeBinding, fieldName); buffer.append(ext + fieldName); } else { buffer.append(ext + fieldName); } //buffer.append(element.getName()); buffer.append(" = "); if (!ignoreInitializer && element.getInitializer() != null) { element.getInitializer().accept(this); } else { boolean isArray = false; List frags = node.fragments(); if (frags.size() > 0) { VariableDeclarationFragment varFrag = (VariableDeclarationFragment) frags.get(0); IVariableBinding resolveBinding = varFrag.resolveBinding(); if (resolveBinding != null) { isArray = resolveBinding.getType().isArray(); if (isArray) { buffer.append("null"); } } } if (!isArray) { if (node.getType().isPrimitiveType()) { PrimitiveType pType = (PrimitiveType) node.getType(); if (pType.getPrimitiveTypeCode() == PrimitiveType.BOOLEAN) { buffer.append("false"); } else if (pType.getPrimitiveTypeCode() == PrimitiveType.CHAR) { buffer.append("'\\0'"); } else { buffer.append("0"); } } else { buffer.append("null"); } } } buffer.append(";\r\n"); } return false; }
From source file:org.autorefactor.refactoring.rules.RemoveFieldsDefaultValuesRefactoring.java
License:Open Source License
private boolean canRemoveFieldDefaultValue(final FieldDeclaration node) { // Do not remove default values from interface/annotation fields // because they are final by default final ASTNode parent = node.getParent(); if (parent instanceof TypeDeclaration) { return !((TypeDeclaration) parent).isInterface(); }/* ww w. j ava2 s. co m*/ return parent instanceof AnonymousClassDeclaration || parent instanceof EnumDeclaration; }
From source file:org.autorefactor.refactoring.rules.RemoveUselessModifiersRefactoring.java
License:Open Source License
@Override public boolean visit(FieldDeclaration node) { if (isInterface(node.getParent())) { return removePublicStaticFinalModifiers(node); }/*from www.java 2s . c om*/ return ensureModifiersOrder(node); }
From source file:org.eclipse.andmore.android.generateviewbylayout.GenerateCodeBasedOnLayoutVisitor.java
License:Apache License
/** * Check if there is an attribute already declared with the name given. * /* w ww . j ava 2 s. c om*/ * @param node * @param considerType * false, if must not consider the type in the analysis * @return true if there a variable declared with the node.getNodeId() * independent on variable type, false otherwise */ public boolean checkIfAttributeAlreadyDeclared(LayoutNode node, boolean considerType) { boolean containFieldDeclared = false; if (typeDeclaration.bodyDeclarations() != null) { // check if attribute already declared for (Object bd : typeDeclaration.bodyDeclarations()) { if (bd instanceof FieldDeclaration) { FieldDeclaration fd = (FieldDeclaration) bd; if (fd.getParent() instanceof TypeDeclaration) { TypeDeclaration type = (TypeDeclaration) fd.getParent(); if (typeDeclaration.equals(type)) { // only considers attributes from main class inside // the file for (Object fragment : fd.fragments()) { if (fragment instanceof VariableDeclarationFragment) { VariableDeclarationFragment frag = (VariableDeclarationFragment) fragment; if ((frag.getName() != null) && frag.getName().toString().equals(node.getNodeId())) { if (considerType) { if ((fd.getType() != null) && !fd.getType().toString().equals(node.getNodeType())) { containFieldDeclared = true; break; } } else { containFieldDeclared = true; break; } } } } } } } } } return containFieldDeclared; }
From source file:org.eclipse.wb.internal.core.model.variable.EmptyVariableSupport.java
License:Open Source License
/** * Converts this "empty" variable into {@link LocalUniqueVariableSupport}. * <p>//ww w. ja va2s .c o m * Case when initializer {@link Expression} is part of other {@link FieldDeclaration}. */ private void materialize_newField() throws Exception { AstEditor editor = m_javaInfo.getEditor(); FieldDeclaration oldField = getEnclosingField(); // prepare type ITypeBinding typeBinding; String typeName; { typeBinding = AstNodeUtils.getTypeBinding(m_initializer); typeName = editor.getTypeBindingSource(typeBinding); } // initialize position and source int position = oldField.getStartPosition(); String source = ""; // modifier { source += "private "; } // add type Type newType; { newType = editor.getParser().parseQualifiedType(position + source.length(), typeName); source += typeName + " "; } // add variable String variableName; SimpleName newDeclarationVariable; { variableName = editor.getUniqueVariableName(m_initializer.getStartPosition(), NamesManager.getName(m_javaInfo), null); newDeclarationVariable = editor.getParser().parseVariable(position + source.length(), variableName, null, typeBinding, false, Modifier.NONE); source += variableName + " = "; } // move initializer { String initializerSource = editor.getSource(m_initializer); int originalInitializerPosition = m_initializer.getStartPosition(); int originalInitializerLength = m_initializer.getLength(); // replace initializer with variable { SimpleName newUseVariable = editor.getParser().parseVariable(originalInitializerPosition, variableName, null, typeBinding, false, Modifier.NONE); // AstEditor.replaceNode(m_initializer, newUseVariable); m_javaInfo.addRelatedNode(newUseVariable); editor.replaceSubstring(originalInitializerPosition, originalInitializerLength, newUseVariable.getIdentifier()); AstNodeUtils.moveNode(newUseVariable, originalInitializerPosition); editor.inlineParenthesizedExpression(newUseVariable); } // use initializer for declaration AstNodeUtils.moveNode(m_initializer, position + source.length()); source += initializerSource; } // add fragment VariableDeclarationFragment newFragment; { newFragment = m_initializer.getAST().newVariableDeclarationFragment(); newFragment.setName(newDeclarationVariable); newFragment.setInitializer(m_initializer); AstNodeUtils.setSourceRange(newFragment, newDeclarationVariable, m_initializer); } // add statement FieldDeclaration newField; { newField = m_initializer.getAST().newFieldDeclaration(newFragment); newField.setType(newType); AstNodeUtils.setSourceRange(newField, newType, newFragment, 1); source += ";"; } // add EOL and prefix source += editor.getGeneration().getEndOfLine() + editor.getWhitespaceToLeft(position, false); // update source editor.replaceSubstring(position, 0, source); // add new statement to AST { TypeDeclaration typeDeclaration = (TypeDeclaration) oldField.getParent(); List<BodyDeclaration> bodyDeclarations = DomGenerics.bodyDeclarations(typeDeclaration); int index = bodyDeclarations.indexOf(oldField); bodyDeclarations.add(index, newField); editor.resolveImports(newField); } // use local variable support m_javaInfo.setVariableSupport(new FieldInitializerVariableSupport(m_javaInfo, newDeclarationVariable)); }
From source file:org.eclipse.xtend.core.javaconverter.JavaASTFlattener.java
License:Open Source License
@Override public boolean visit(final FieldDeclaration it) { Javadoc _javadoc = it.getJavadoc();// ww w . j a va 2 s .c o m boolean _tripleNotEquals = (_javadoc != null); if (_tripleNotEquals) { it.getJavadoc().accept(this); } final Consumer<VariableDeclarationFragment> _function = (VariableDeclarationFragment frag) -> { this.appendModifiers(it, it.modifiers()); boolean _isPackageVisibility = this._aSTFlattenerUtils .isPackageVisibility(Iterables.<Modifier>filter(it.modifiers(), Modifier.class)); if (_isPackageVisibility) { ASTNode _parent = it.getParent(); if ((_parent instanceof TypeDeclaration)) { ASTNode _parent_1 = it.getParent(); boolean _isInterface = ((TypeDeclaration) _parent_1).isInterface(); boolean _not = (!_isInterface); if (_not) { this.appendToBuffer("package "); } } } it.getType().accept(this); this.appendExtraDimensions(frag.getExtraDimensions()); this.appendSpaceToBuffer(); frag.accept(this); }; it.fragments().forEach(_function); return false; }