List of usage examples for org.eclipse.jdt.core.dom AST newInitializer
public Initializer newInitializer()
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; }// w w w. jav a 2s .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:org.decojer.cavaj.transformers.TrOutline.java
License:Open Source License
private static void decompileMethod(@Nonnull final M m, @Nonnull final CU cu, final boolean strictFp) { if (checkMethodIgnore(m, cu)) { return;/*from ww w . ja va 2 s. com*/ } final String name = m.getName(); final T t = m.getT(); assert t != null : "decompile method cannot be dynamic"; final AST ast = cu.getAst(); final boolean isAnnotationMember = t.getAf(AF.ANNOTATION); // decompile BodyDeclaration, possible subtypes: // MethodDeclaration (method or constructor), // AnnotationTypeMemberDeclaration (all methods in @interface) or // Initializer (static {}) final BodyDeclaration methodDeclaration; if (m.isInitializer()) { methodDeclaration = ast.newInitializer(); } else if (m.isConstructor()) { // MethodDeclaration with type declaration name as name methodDeclaration = ast.newMethodDeclaration(); ((MethodDeclaration) methodDeclaration).setConstructor(true); ((MethodDeclaration) methodDeclaration).setName(newSimpleName( cu.check(DFlag.START_TD_ONLY) || t.isAnonymous() ? t.getPName() : t.getSimpleName(), ast)); } else if (isAnnotationMember) { // AnnotationTypeMemberDeclaration methodDeclaration = ast.newAnnotationTypeMemberDeclaration(); ((AnnotationTypeMemberDeclaration) methodDeclaration).setName(newSimpleName(name, ast)); // check if default value (e.g.: byte byteTest() default 2;) if (m.getAnnotationDefaultValue() != null) { final Expression expression = Annotations .decompileAnnotationDefaultValue(m.getAnnotationDefaultValue(), t); if (expression != null) { ((AnnotationTypeMemberDeclaration) methodDeclaration).setDefault(expression); } } } else { // MethodDeclaration methodDeclaration = ast.newMethodDeclaration(); ((MethodDeclaration) methodDeclaration).setName(newSimpleName(name, ast)); } m.setAstNode(methodDeclaration); // decompile synthetic Javadoc-comment if no annotation set if (m.isSynthetic()) { final Javadoc javadoc = ast.newJavadoc(); final TagElement tagElement = ast.newTagElement(); tagElement.setTagName("is synthetic"); javadoc.tags().add(tagElement); methodDeclaration.setJavadoc(javadoc); } // decompile deprecated Javadoc-tag if no annotation set if (m.getAf(AF.DEPRECATED) && !Annotations.isDeprecatedAnnotation(m.getAs())) { final Javadoc javadoc = ast.newJavadoc(); final TagElement tagElement = ast.newTagElement(); tagElement.setTagName("@deprecated"); javadoc.tags().add(tagElement); methodDeclaration.setJavadoc(javadoc); } final List<IExtendedModifier> modifiers = methodDeclaration.modifiers(); assert modifiers != null; // decompile annotations: // add annotation modifiers before other modifiers, order preserved in // source code generation through Eclipse JDT if (m.getAs() != null) { Annotations.decompileAnnotations(m.getAs(), modifiers, t); } final boolean isInterfaceMember = t.isInterface(); // decompile modifier flags: // interfaces can have default methods since JVM 8 if (isInterfaceMember && m.getCfg() != null && !m.isStatic()) { if (t.isBelow(Version.JVM_8)) { log.warn("Default methods are not known before JVM 8! Adding default keyword anyway, check this."); } modifiers.add(ast.newModifier(ModifierKeyword.DEFAULT_KEYWORD)); } // public is default for interface and annotation type declarations if (m.getAf(AF.PUBLIC) && !isAnnotationMember && !isInterfaceMember) { modifiers.add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD)); } if (m.getAf(AF.PRIVATE)) { modifiers.add(ast.newModifier(ModifierKeyword.PRIVATE_KEYWORD)); } if (m.getAf(AF.PROTECTED)) { modifiers.add(ast.newModifier(ModifierKeyword.PROTECTED_KEYWORD)); } if (m.isStatic()) { modifiers.add(ast.newModifier(ModifierKeyword.STATIC_KEYWORD)); } if (m.getAf(AF.FINAL)) { modifiers.add(ast.newModifier(ModifierKeyword.FINAL_KEYWORD)); } if (m.getAf(AF.SYNCHRONIZED)) { modifiers.add(ast.newModifier(ModifierKeyword.SYNCHRONIZED_KEYWORD)); } if (m.getAf(AF.BRIDGE)) { // TODO } if (m.getAf(AF.NATIVE)) { modifiers.add(ast.newModifier(ModifierKeyword.NATIVE_KEYWORD)); } // abstract is default for interface and annotation type declarations if (m.getAf(AF.ABSTRACT) && !isAnnotationMember && !isInterfaceMember) { modifiers.add(ast.newModifier(ModifierKeyword.ABSTRACT_KEYWORD)); } if (m.getAf(AF.STRICTFP) && !strictFp) { modifiers.add(ast.newModifier(ModifierKeyword.STRICTFP_KEYWORD)); } /* * AF.CONSTRUCTOR, AF.DECLARED_SYNCHRONIZED nothing, Dalvik only? */ if (methodDeclaration instanceof MethodDeclaration) { decompileTypeParams(m.getTypeParams(), ((MethodDeclaration) methodDeclaration).typeParameters(), t); decompileMethodParams(m); if (!m.getAf(AF.ABSTRACT) && !m.getAf(AF.NATIVE)) { // create method block for valid syntax, abstract and native methods have none final Block block = ast.newBlock(); ((MethodDeclaration) methodDeclaration).setBody(block); final CFG cfg = m.getCfg(); if (cfg != null) { // could have no CFG because of empty or incomplete read code attribute cfg.setBlock(block); } } } else if (methodDeclaration instanceof Initializer) { // Initializer (static{}) has block per default assert ((Initializer) methodDeclaration).getBody() != null; final CFG cfg = m.getCfg(); if (cfg != null) { // could have no CFG because of empty or incomplete read code attribute cfg.setBlock(((Initializer) methodDeclaration).getBody()); } } else if (methodDeclaration instanceof AnnotationTypeMemberDeclaration) { assert m.getParamTs().length == 0; ((AnnotationTypeMemberDeclaration) methodDeclaration).setType(newType(m.getReturnT(), t)); } }
From source file:ptolemy.backtrack.eclipse.ast.transform.AssignmentTransformer.java
License:Open Source License
/** Handle a class declaration or anonymous class declaration. Records and * assignment methods are added to the declaration. * * @param node The AST node of class declaration or anonymous class * declaration.//from www . jav a2 s . c o m * @param bodyDeclarations The list of body declarations in the class. * @param state The current state of the type analyzer. */ private void _handleDeclaration(ASTNode node, List bodyDeclarations, TypeAnalyzerState state) { Class currentClass = state.getCurrentClass(); @SuppressWarnings("unused") Class parent = currentClass.getSuperclass(); List newMethods = new LinkedList(); List newFields = new LinkedList(); AST ast = node.getAST(); CompilationUnit root = (CompilationUnit) node.getRoot(); List fieldNames = new LinkedList(); List fieldTypes = new LinkedList(); // Iterate over all the body declarations. Iterator bodyIter = bodyDeclarations.iterator(); while (bodyIter.hasNext()) { Object nextDeclaration = bodyIter.next(); // Handle only field declarations. if (nextDeclaration instanceof FieldDeclaration) { FieldDeclaration fieldDecl = (FieldDeclaration) nextDeclaration; boolean isStatic = Modifier.isStatic(fieldDecl.getModifiers()); // If HANDLE_STATIC_FIELDS is set to false, do not refactor // static fields. if (isStatic && (HANDLE_STATIC_FIELDS != true)) { continue; } // Handle only private fields or the $CHECKPOINT special field. if (Modifier.isPrivate(fieldDecl.getModifiers())) { Type type = Type.getType(fieldDecl); // Iterate over all the fragments in the field declaration. Iterator fragmentIter = fieldDecl.fragments().iterator(); while (fragmentIter.hasNext()) { VariableDeclarationFragment fragment = (VariableDeclarationFragment) fragmentIter.next(); String fieldName = fragment.getName().getIdentifier(); // Get the list of numbers of indices. Hashtable[] tables = new Hashtable[] { _accessedFields, _specialAccessedFields, _backupFields }; for (int i = 0; i < tables.length; i++) { List indicesList = _getAccessedField(tables[i], currentClass.getName(), fieldName); if (indicesList == null) { continue; } // Iterate over all the numbers of indices. Iterator indicesIter = indicesList.iterator(); while (indicesIter.hasNext()) { int indices = ((Integer) indicesIter.next()).intValue(); // Create an extra method for every different // number of indices. if (tables[i] == _backupFields) { newMethods.add(_createBackupMethod(ast, root, state, fieldName, type, indices, isStatic)); } else { newMethods.add(_createAssignMethod(ast, root, state, fieldName, type, indices, tables[i] == _specialAccessedFields, isStatic)); } } } fieldNames.add(fieldName); fieldTypes.add(type); // Create a record field. FieldDeclaration field = _createFieldRecord(ast, root, state, fieldName, type.dimensions(), isStatic); if (field != null) { newFields.add(field); } } } } } boolean isInterface = node instanceof TypeDeclaration && ((TypeDeclaration) node).isInterface(); boolean isAnonymous = node instanceof AnonymousClassDeclaration; if (isAnonymous) { Class[] interfaces = currentClass.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { if (state.getCrossAnalyzedTypes().contains(interfaces[i].getName())) { isAnonymous = false; } } } RehandleDeclarationRecord declarationRecord = null; if (isAnonymous) { Class[] interfaces = currentClass.getInterfaces(); if (interfaces.length == 1) { declarationRecord = new RehandleDeclarationRecord(bodyDeclarations); addToLists(_rehandleDeclaration, interfaces[0].getName(), declarationRecord); } } // Do not handle anonymous class declarations in a static method. boolean ignore = !_isInStatic.isEmpty() && (_isInStatic.peek().equals(Boolean.TRUE)) && isAnonymous; // Add an array of all the records. if (!isInterface && !ignore) { newFields.add(_createRecordArray(ast, root, state, fieldNames)); } // Add a commit method. MethodDeclaration commitMethod = null; if (!ignore) { commitMethod = _createCommitMethod(ast, root, state, fieldNames, fieldTypes, isAnonymous, isInterface); newMethods.add(commitMethod); } if (declarationRecord != null) { if (!ignore) { declarationRecord._addExtendedDeclaration(commitMethod); } MethodDeclaration fixedCommitMethod = _createCommitMethod(ast, root, state, fieldNames, fieldTypes, false, isInterface); declarationRecord._addFixedDeclaration(fixedCommitMethod); } // Add a restore method. MethodDeclaration restoreMethod = null; if (!ignore) { restoreMethod = _createRestoreMethod(ast, root, state, fieldNames, fieldTypes, isAnonymous, isInterface); newMethods.add(restoreMethod); } if (declarationRecord != null) { if (!ignore) { declarationRecord._addExtendedDeclaration(restoreMethod); } MethodDeclaration fixedRestoreMethod = _createRestoreMethod(ast, root, state, fieldNames, fieldTypes, false, isInterface); declarationRecord._addFixedDeclaration(fixedRestoreMethod); } // Get checkpoint method. MethodDeclaration getCheckpoint = null; if (!ignore) { getCheckpoint = _createGetCheckpointMethod(ast, root, state, isAnonymous, isInterface); if (getCheckpoint != null) { newMethods.add(getCheckpoint); } } if (declarationRecord != null) { if (!ignore) { declarationRecord._addExtendedDeclaration(getCheckpoint); } MethodDeclaration fixedGetCheckpoint = _createGetCheckpointMethod(ast, root, state, false, isInterface); declarationRecord._addFixedDeclaration(fixedGetCheckpoint); } // Set checkpoint method. MethodDeclaration setCheckpoint = null; if (!ignore) { setCheckpoint = _createSetCheckpointMethod(ast, root, state, isAnonymous, isInterface); if (setCheckpoint != null) { newMethods.add(setCheckpoint); } } if (declarationRecord != null) { if (!ignore) { declarationRecord._addExtendedDeclaration(setCheckpoint); } MethodDeclaration fixedSetCheckpoint = _createSetCheckpointMethod(ast, root, state, false, isInterface); declarationRecord._addFixedDeclaration(fixedSetCheckpoint); } // Add an interface. if (!ignore) { if (isAnonymous) { TypeDeclaration proxy = _createProxyClass(ast, root, state); bodyDeclarations.add(proxy); if (declarationRecord != null) { declarationRecord._addExtendedDeclaration(proxy); } } else { // Set the class to implement Rollbackable. if (node instanceof TypeDeclaration) { String rollbackType = getClassName(Rollbackable.class, state, root); ((TypeDeclaration) node).superInterfaceTypes() .add(ast.newSimpleType(createName(ast, rollbackType))); } if (!isInterface) { // Create a checkpoint field. FieldDeclaration checkpointField = _createCheckpointField(ast, root, state); if (checkpointField != null) { bodyDeclarations.add(0, checkpointField); } // Create a record for the checkpoint field. FieldDeclaration record = _createCheckpointRecord(ast, root, state); if (record != null) { newFields.add(0, record); } } } } // Add all the methods and then all the fields. if (!ignore) { bodyDeclarations.addAll(newMethods); bodyDeclarations.addAll(newFields); } else { if (declarationRecord != null) { declarationRecord._addFixedDeclarations(newMethods); declarationRecord._addFixedDeclarations(newFields); } } if (isAnonymous && !ignore) { // Create a simple initializer. Initializer initializer = ast.newInitializer(); Block body = ast.newBlock(); initializer.setBody(body); MethodInvocation addInvocation = ast.newMethodInvocation(); addInvocation.setExpression(ast.newSimpleName(CHECKPOINT_NAME)); addInvocation.setName(ast.newSimpleName("addObject")); ClassInstanceCreation proxy = ast.newClassInstanceCreation(); proxy.setType(ast.newSimpleType(ast.newSimpleName(_getProxyName()))); addInvocation.arguments().add(proxy); body.statements().add(ast.newExpressionStatement(addInvocation)); bodyDeclarations.add(initializer); if (declarationRecord != null) { declarationRecord._addExtendedDeclaration(initializer); } } }