text
stringlengths 30
1.67M
|
|---|
<s> package org . codehaus . groovy . eclipse . codeassist . processors ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jdt . core . compiler . CharOperation ; import org . eclipse . jdt . internal . codeassist . CompletionEngine ; import org . eclipse . jdt . internal . codeassist . InternalCompletionProposal ; import org . eclipse . jdt . internal . core . NameLookup ; public class GroovyCompletionProposal extends InternalCompletionProposal { private char [ ] [ ] namedParameterNames = CharOperation . NO_CHAR_CHAR ; private char [ ] [ ] namedParameterTypeNames = CharOperation . NO_CHAR_CHAR ; private char [ ] [ ] optionalParameterNames = CharOperation . NO_CHAR_CHAR ; private char [ ] [ ] optionalParameterTypeNames = CharOperation . NO_CHAR_CHAR ; private char [ ] [ ] regularParameterNames = CharOperation . NO_CHAR_CHAR ; private char [ ] [ ] regularParameterTypeNames = CharOperation . NO_CHAR_CHAR ; private boolean useExtraParameters = false ; public GroovyCompletionProposal ( int kind , int completionLocation ) { super ( kind , completionLocation ) ; } public char [ ] [ ] getNamedParameterNames ( ) { return namedParameterNames ; } public char [ ] [ ] getNamedParameterTypeNames ( ) { return namedParameterTypeNames ; } public char [ ] [ ] getOptionalParameterNames ( ) { return optionalParameterNames ; } public char [ ] [ ] getOptionalParameterTypeNames ( ) { return optionalParameterTypeNames ; } public char [ ] [ ] getRegularParameterNames ( ) { if ( useExtraParameters ) { return regularParameterNames ; } else { return findParameterNames ( null ) ; } } public char [ ] [ ] getRegularParameterTypeNames ( ) { if ( useExtraParameters ) { return regularParameterTypeNames ; } else { return parameterTypeNames ; } } @ Override public void setAccessibility ( int kind ) { super . setAccessibility ( kind ) ; } public void setCompletionEngine ( CompletionEngine completionEngine ) { this . completionEngine = completionEngine ; } @ Override public void setDeclarationTypeName ( char [ ] declarationTypeName ) { super . setDeclarationTypeName ( declarationTypeName ) ; } public void setNamedParameterNames ( char [ ] [ ] namedParameterNames ) { this . namedParameterNames = namedParameterNames ; } public void setNamedParameterTypeNames ( char [ ] [ ] namedParameterTypeNames ) { this . namedParameterTypeNames = namedParameterTypeNames ; } public void setNameLookup ( NameLookup lookup ) { super . nameLookup = lookup ; } public void setOptionalParameterNames ( char [ ] [ ] optionalParameterNames ) { this . optionalParameterNames = optionalParameterNames ; } public void setOptionalParameterTypeNames ( char [ ] [ ] optionalParameterTypeNames ) { this . optionalParameterTypeNames = optionalParameterTypeNames ; } @ Override public void setPackageName ( char [ ] packageName ) { super . setPackageName ( packageName ) ; } @ Override public void setParameterTypeNames ( char [ ] [ ] parameterTypeNames ) { super . setParameterTypeNames ( parameterTypeNames ) ; } public void setRegularParameterNames ( char [ ] [ ] regularParameterNames ) { useExtraParameters = true ; this . regularParameterNames = regularParameterNames ; } public void setRegularParameterTypeNames ( char [ ] [ ] regularParameterTypeNames ) { useExtraParameters = true ; this . regularParameterTypeNames = regularParameterTypeNames ; } @ Override public void setTypeName ( char [ ] typeName ) { super . setTypeName ( typeName ) ; } @ Override protected void setDeclarationPackageName ( char [ ] declarationPackageName ) { super . setDeclarationPackageName ( declarationPackageName ) ; } @ Override protected void setIsContructor ( boolean isConstructor ) { super . setIsContructor ( isConstructor ) ; } @ Override public char [ ] [ ] findParameterNames ( IProgressMonitor monitor ) { return super . findParameterNames ( monitor ) ; } public boolean hasParameters ( ) { return super . getParameterTypeNames ( ) != null && super . getParameterTypeNames ( ) . length > <NUM_LIT:0> ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . codeassist . processors ; import java . util . LinkedList ; import java . util . List ; import org . codehaus . groovy . ast . FieldNode ; import org . codehaus . groovy . eclipse . codeassist . CharArraySourceBuffer ; import org . codehaus . groovy . eclipse . codeassist . ProposalUtils ; import org . codehaus . groovy . eclipse . codeassist . relevance . Relevance ; import org . codehaus . groovy . eclipse . codeassist . requestor . ContentAssistContext ; import org . codehaus . groovy . eclipse . core . GroovyCore ; import org . codehaus . groovy . eclipse . core . util . ExpressionFinder ; import org . codehaus . groovy . eclipse . core . util . ExpressionFinder . NameAndLocation ; import org . codehaus . jdt . groovy . model . GroovyCompilationUnit ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jdt . core . CompletionProposal ; import org . eclipse . jdt . core . Flags ; import org . eclipse . jdt . core . IType ; import org . eclipse . jdt . core . NamingConventions ; import org . eclipse . jdt . internal . core . InternalNamingConventions ; import org . eclipse . jdt . internal . core . SearchableEnvironment ; import org . eclipse . jdt . internal . ui . text . java . JavaCompletionProposal ; import org . eclipse . jdt . ui . text . java . JavaContentAssistInvocationContext ; import org . eclipse . jface . preference . JFacePreferences ; import org . eclipse . jface . text . contentassist . ICompletionProposal ; import org . eclipse . jface . viewers . StyledString ; import org . eclipse . swt . graphics . Image ; public class NewFieldCompletionProcessor extends AbstractGroovyCompletionProcessor { public static class NewGroovyFieldCompletionProposal extends JavaCompletionProposal { NewGroovyFieldCompletionProposal ( String fieldName , int replacementOffset , int replacementLength , int relevance , boolean isStatic , boolean useKeywordBeforeReplacement , String typeName ) { super ( createReplacementString ( fieldName , typeName , isStatic ) , replacementOffset , replacementLength , createImage ( isStatic ) , createDisplayString ( fieldName , typeName , isStatic , useKeywordBeforeReplacement ) , relevance ) ; } static String createReplacementString ( String fieldName , String typeName , boolean isStatic ) { if ( isStatic ) { if ( typeName != null ) { return "<STR_LIT>" + typeName + fieldName + "<STR_LIT>" ; } else { return "<STR_LIT>" + fieldName + "<STR_LIT>" ; } } else if ( typeName != null ) { return typeName + fieldName ; } else { return "<STR_LIT>" + fieldName ; } } static Image createImage ( boolean isStatic ) { CompletionProposal dummy = CompletionProposal . create ( CompletionProposal . FIELD_REF , - <NUM_LIT:1> ) ; if ( isStatic ) { dummy . setFlags ( Flags . AccStatic ) ; } return ProposalUtils . getImage ( dummy ) ; } static StyledString createDisplayString ( String fieldName , String typeName , boolean isStatic , boolean useKeywordBeforeReplacement ) { StyledString ss = new StyledString ( ) ; if ( useKeywordBeforeReplacement ) { if ( isStatic ) { ss . append ( "<STR_LIT>" , StyledString . createColorRegistryStyler ( JFacePreferences . HYPERLINK_COLOR , null ) ) ; if ( typeName != null ) { ss . append ( typeName ) ; } } else { if ( typeName == null ) { ss . append ( "<STR_LIT>" , StyledString . createColorRegistryStyler ( JFacePreferences . HYPERLINK_COLOR , null ) ) ; } else { ss . append ( typeName ) ; } } } if ( isStatic ) { ss . append ( fieldName ) ; ss . append ( "<STR_LIT>" , StyledString . QUALIFIER_STYLER ) ; } else { ss . append ( fieldName ) ; ss . append ( "<STR_LIT>" , StyledString . QUALIFIER_STYLER ) ; } return ss ; } } public NewFieldCompletionProcessor ( ContentAssistContext context , JavaContentAssistInvocationContext javaContext , SearchableEnvironment nameEnvironment ) { super ( context , javaContext , nameEnvironment ) ; } public List < ICompletionProposal > generateProposals ( IProgressMonitor monitor ) { ContentAssistContext context = getContext ( ) ; List < String > unimplementedFieldNames = getAllSuggestedFieldNames ( context ) ; List < ICompletionProposal > proposals = new LinkedList < ICompletionProposal > ( ) ; IType enclosingType = context . getEnclosingType ( ) ; if ( enclosingType != null ) { for ( String fieldName : unimplementedFieldNames ) { proposals . add ( createProposal ( fieldName , context , enclosingType ) ) ; } NameAndLocation nameAndLocation = findCompletionTypeName ( context . unit , context . completionLocation ) ; if ( nameAndLocation != null ) { String typeName = nameAndLocation . toTypeName ( ) ; if ( typeName . equals ( "<STR_LIT>" ) ) { typeName = "<STR_LIT:value>" ; } String [ ] suggestedNames = NamingConventions . suggestVariableNames ( NamingConventions . VK_INSTANCE_FIELD , InternalNamingConventions . BK_SIMPLE_TYPE_NAME , typeName , context . unit . getJavaProject ( ) , nameAndLocation . dims ( ) , null , true ) ; if ( suggestedNames != null ) { for ( String suggestedName : suggestedNames ) { if ( suggestedName . startsWith ( context . completionExpression ) ) { proposals . add ( createProposal ( suggestedName , nameAndLocation . name , context , enclosingType , false , true , nameAndLocation . location , context . completionLocation - nameAndLocation . location ) ) ; } } } } } return proposals ; } private NameAndLocation findCompletionTypeName ( GroovyCompilationUnit unit , int completionLocation ) { return new ExpressionFinder ( ) . findPreviousTypeNameToken ( new CharArraySourceBuffer ( unit . getContents ( ) ) , completionLocation ) ; } private List < String > getAllSuggestedFieldNames ( ContentAssistContext context ) { List < String > allNewFieldNames = new LinkedList < String > ( ) ; try { List < IProposalProvider > providers = ProposalProviderRegistry . getRegistry ( ) . getProvidersFor ( context . unit ) ; for ( IProposalProvider provider : providers ) { List < String > newFieldNames = provider . getNewFieldProposals ( context ) ; if ( newFieldNames != null ) { allNewFieldNames . addAll ( newFieldNames ) ; } } } catch ( CoreException e ) { GroovyCore . logException ( "<STR_LIT>" + context . unit . getElementName ( ) , e ) ; } return allNewFieldNames ; } private ICompletionProposal createProposal ( String fieldName , ContentAssistContext context , IType enclosingType ) { boolean isStatic ; if ( fieldName . startsWith ( IProposalProvider . NONSTATIC_FIELD ) ) { fieldName = fieldName . substring ( IProposalProvider . NONSTATIC_FIELD . length ( ) ) ; isStatic = false ; } else { isStatic = true ; } boolean useKeywordBeforeReplacement = context . completionExpression . length ( ) > <NUM_LIT:0> && ( ( context . completionNode instanceof FieldNode ) || "<STR_LIT>" . startsWith ( context . completionExpression ) || "<STR_LIT>" . startsWith ( context . completionExpression ) ) ; int replaceStart = context . completionNode instanceof FieldNode ? context . completionNode . getStart ( ) : context . completionLocation - context . completionExpression . length ( ) ; int replaceLength = context . completionNode instanceof FieldNode ? context . completionLocation - replaceStart : context . completionExpression . length ( ) ; return createProposal ( fieldName , null , context , enclosingType , isStatic , useKeywordBeforeReplacement , replaceStart , replaceLength ) ; } private ICompletionProposal createProposal ( String fieldName , String typeName , ContentAssistContext context , IType enclosingType , boolean isStatic , boolean useKeywordBeforeReplacement , int replaceStart , int replaceLength ) { int relevance = Relevance . VERY_HIGH . getRelavance ( ) ; return new NewGroovyFieldCompletionProposal ( fieldName , replaceStart , replaceLength , relevance , isStatic , useKeywordBeforeReplacement , typeName ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . codeassist . processors ; import java . util . Collections ; import java . util . LinkedList ; import java . util . List ; import org . codehaus . groovy . eclipse . codeassist . requestor . ContentAssistContext ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jdt . core . JavaConventions ; import org . eclipse . jdt . core . compiler . CharOperation ; import org . eclipse . jdt . core . search . IJavaSearchConstants ; import org . eclipse . jdt . internal . core . SearchableEnvironment ; import org . eclipse . jdt . ui . text . java . JavaContentAssistInvocationContext ; import org . eclipse . jface . text . contentassist . ICompletionProposal ; public class PackageCompletionProcessor extends AbstractGroovyCompletionProcessor { public PackageCompletionProcessor ( ContentAssistContext context , JavaContentAssistInvocationContext javaContext , SearchableEnvironment nameEnvironment ) { super ( context , javaContext , nameEnvironment ) ; } public List < ICompletionProposal > generateProposals ( IProgressMonitor monitor ) { ContentAssistContext context = getContext ( ) ; char [ ] packageCompletionText = getPackageCompletionText ( context . fullCompletionExpression ) ; if ( mightBePackage ( packageCompletionText ) ) { int expressionStart = context . completionLocation - context . fullCompletionExpression . trim ( ) . length ( ) ; GroovyProposalTypeSearchRequestor requestor = new GroovyProposalTypeSearchRequestor ( context , getJavaContext ( ) , expressionStart , context . completionEnd - expressionStart , getNameEnvironment ( ) . nameLookup , monitor ) ; getNameEnvironment ( ) . findPackages ( packageCompletionText , requestor ) ; List < ICompletionProposal > typeProposals = requestor . processAcceptedPackages ( ) ; boolean alsoLookForTypes = shouldLookForTypes ( packageCompletionText ) ; if ( alsoLookForTypes ) { getNameEnvironment ( ) . findTypes ( packageCompletionText , true , true , getSearchFor ( ) , requestor , monitor ) ; typeProposals . addAll ( requestor . processAcceptedTypes ( ) ) ; } return typeProposals ; } else { return Collections . emptyList ( ) ; } } private boolean shouldLookForTypes ( char [ ] packageCompletionText ) { return CharOperation . indexOf ( '<CHAR_LIT:.>' , packageCompletionText ) > - <NUM_LIT:1> ; } private boolean mightBePackage ( char [ ] packageCompletionText ) { if ( packageCompletionText == null || packageCompletionText . length == <NUM_LIT:0> ) { return false ; } String text = String . valueOf ( packageCompletionText ) ; String [ ] splits = text . split ( "<STR_LIT:\\.>" ) ; for ( String split : splits ) { if ( split . length ( ) > <NUM_LIT:0> ) { IStatus status = JavaConventions . validateIdentifier ( split , "<STR_LIT>" , "<STR_LIT>" ) ; if ( status . getSeverity ( ) >= IStatus . ERROR ) { return false ; } } } return true ; } private char [ ] getPackageCompletionText ( String fullCompletionExpression ) { List < Character > chars = new LinkedList < Character > ( ) ; if ( fullCompletionExpression == null ) { return new char [ <NUM_LIT:0> ] ; } char [ ] fullArray = fullCompletionExpression . toCharArray ( ) ; for ( int i = <NUM_LIT:0> ; i < fullArray . length ; i ++ ) { if ( Character . isWhitespace ( fullArray [ i ] ) ) { continue ; } else if ( Character . isJavaIdentifierPart ( fullArray [ i ] ) || fullArray [ i ] == '<CHAR_LIT:.>' ) { chars . add ( fullArray [ i ] ) ; } else { return null ; } } char [ ] res = new char [ chars . size ( ) ] ; int i = <NUM_LIT:0> ; for ( Character c : chars ) { res [ i ] = c . charValue ( ) ; i ++ ; } return res ; } private int getSearchFor ( ) { switch ( getContext ( ) . location ) { case EXTENDS : return IJavaSearchConstants . CLASS ; case IMPLEMENTS : return IJavaSearchConstants . INTERFACE ; case EXCEPTIONS : return IJavaSearchConstants . CLASS ; default : return IJavaSearchConstants . TYPE ; } } } </s>
|
<s> package org . codehaus . groovy . eclipse . codeassist . processors ; import java . util . Collections ; import java . util . HashSet ; import java . util . LinkedList ; import java . util . List ; import java . util . Set ; import org . codehaus . groovy . ast . ASTNode ; import org . codehaus . groovy . ast . ModuleNode ; import org . codehaus . groovy . ast . expr . ConstructorCallExpression ; import org . codehaus . groovy . ast . expr . Expression ; import org . codehaus . groovy . ast . expr . MapEntryExpression ; import org . codehaus . groovy . ast . expr . MapExpression ; import org . codehaus . groovy . ast . expr . TupleExpression ; import org . codehaus . groovy . eclipse . codeassist . requestor . ContentAssistContext ; import org . codehaus . groovy . eclipse . codeassist . requestor . ContentAssistLocation ; import org . codehaus . groovy . eclipse . codeassist . requestor . MethodInfoContentAssistContext ; import org . codehaus . jdt . groovy . internal . compiler . ast . JDTResolver ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jdt . core . compiler . CharOperation ; import org . eclipse . jdt . groovy . search . ITypeResolver ; import org . eclipse . jdt . internal . core . SearchableEnvironment ; import org . eclipse . jdt . ui . text . java . JavaContentAssistInvocationContext ; import org . eclipse . jface . text . contentassist . ICompletionProposal ; public class ConstructorCompletionProcessor extends AbstractGroovyCompletionProcessor implements ITypeResolver { private JDTResolver resolver ; public ConstructorCompletionProcessor ( ContentAssistContext context , JavaContentAssistInvocationContext javaContext , SearchableEnvironment nameEnvironment ) { super ( context , javaContext , nameEnvironment ) ; } public List < ICompletionProposal > generateProposals ( IProgressMonitor monitor ) { ContentAssistContext context = getContext ( ) ; char [ ] constructorCompletionText = getCompletionText ( context . fullCompletionExpression ) ; if ( constructorCompletionText == null ) { return Collections . emptyList ( ) ; } int completionExprStart ; if ( context . location == ContentAssistLocation . METHOD_CONTEXT ) { completionExprStart = ( ( MethodInfoContentAssistContext ) context ) . methodNameEnd - ( ( MethodInfoContentAssistContext ) context ) . methodName . length ( ) ; } else { completionExprStart = context . completionLocation - constructorCompletionText . length ; } if ( completionExprStart < <NUM_LIT:0> ) { return Collections . emptyList ( ) ; } GroovyProposalTypeSearchRequestor requestor = new GroovyProposalTypeSearchRequestor ( context , getJavaContext ( ) , completionExprStart , context . completionEnd - completionExprStart , getNameEnvironment ( ) . nameLookup , monitor ) ; getNameEnvironment ( ) . findConstructorDeclarations ( constructorCompletionText , true , requestor , monitor ) ; List < ICompletionProposal > constructorProposals = requestor . processAcceptedConstructors ( findUsedParameters ( context ) , resolver ) ; return constructorProposals ; } private Set < String > findUsedParameters ( ContentAssistContext context ) { if ( context . location != ContentAssistLocation . METHOD_CONTEXT ) { return Collections . emptySet ( ) ; } Set < String > usedParams = new HashSet < String > ( ) ; ASTNode completionNode = context . completionNode ; if ( completionNode instanceof ConstructorCallExpression ) { ConstructorCallExpression call = ( ConstructorCallExpression ) completionNode ; Expression arguments = call . getArguments ( ) ; if ( arguments instanceof TupleExpression ) { for ( Expression maybeArg : ( ( TupleExpression ) arguments ) . getExpressions ( ) ) { if ( maybeArg instanceof MapExpression ) { arguments = maybeArg ; break ; } } } if ( arguments instanceof MapExpression ) { MapExpression enclosingCallArgs = ( MapExpression ) arguments ; for ( MapEntryExpression entry : enclosingCallArgs . getMapEntryExpressions ( ) ) { usedParams . add ( entry . getKeyExpression ( ) . getText ( ) ) ; } } } return usedParams ; } private char [ ] getCompletionText ( String fullCompletionExpression ) { List < Character > chars = new LinkedList < Character > ( ) ; if ( fullCompletionExpression == null ) { return new char [ <NUM_LIT:0> ] ; } char [ ] fullArray = fullCompletionExpression . toCharArray ( ) ; int newIndex = CharOperation . indexOf ( "<STR_LIT>" . toCharArray ( ) , fullArray , true ) + <NUM_LIT:4> ; if ( newIndex == - <NUM_LIT:1> ) { return null ; } for ( int i = newIndex ; i < fullArray . length ; i ++ ) { if ( Character . isWhitespace ( fullArray [ i ] ) ) { continue ; } else if ( Character . isJavaIdentifierPart ( fullArray [ i ] ) || fullArray [ i ] == '<CHAR_LIT:.>' ) { chars . add ( fullArray [ i ] ) ; } else { return null ; } } char [ ] res = new char [ chars . size ( ) ] ; int i = <NUM_LIT:0> ; for ( Character c : chars ) { res [ i ] = c . charValue ( ) ; i ++ ; } return res ; } public void setResolverInformation ( ModuleNode module , JDTResolver resolver ) { this . resolver = resolver ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . codeassist ; import java . util . HashSet ; import java . util . Set ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . ui . plugin . AbstractUIPlugin ; import org . osgi . framework . BundleContext ; public class GroovyContentAssistActivator extends AbstractUIPlugin { public static final String PLUGIN_ID = "<STR_LIT>" ; public static final String FILTERED_DGMS = PLUGIN_ID + "<STR_LIT>" ; private static GroovyContentAssistActivator plugin ; public GroovyContentAssistActivator ( ) { plugin = this ; } @ Override public void start ( BundleContext context ) throws Exception { super . start ( context ) ; } @ Override public void stop ( BundleContext context ) throws Exception { plugin = null ; super . stop ( context ) ; } public static GroovyContentAssistActivator getDefault ( ) { return plugin ; } public static void logError ( Throwable e ) { getDefault ( ) . getLog ( ) . log ( new Status ( IStatus . ERROR , PLUGIN_ID , IStatus . OK , e . getLocalizedMessage ( ) , e ) ) ; } public static void logError ( String message , Throwable e ) { getDefault ( ) . getLog ( ) . log ( new Status ( IStatus . ERROR , PLUGIN_ID , IStatus . OK , message , e ) ) ; } public Set < String > getFilteredDGMs ( ) { String filtered = getPreferenceStore ( ) . getString ( FILTERED_DGMS ) ; String [ ] filteredArr = filtered . split ( "<STR_LIT:U+002C>" ) ; Set < String > filteredSet = new HashSet < String > ( filteredArr . length ) ; for ( String s : filteredArr ) { s = s . trim ( ) ; if ( s . length ( ) > <NUM_LIT:0> ) { filteredSet . add ( s ) ; } } return filteredSet ; } public void setFilteredDGMs ( Set < String > filteredSet ) { StringBuilder sb = new StringBuilder ( ) ; for ( String s : filteredSet ) { if ( s == null ) continue ; s = s . trim ( ) ; if ( s . length ( ) > <NUM_LIT:0> ) { sb . append ( s + "<STR_LIT:U+002C>" ) ; } } getPreferenceStore ( ) . setValue ( FILTERED_DGMS , sb . toString ( ) ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . codeassist . creators ; import java . util . Set ; import org . codehaus . groovy . ast . ClassHelper ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . FieldNode ; import org . codehaus . groovy . ast . MethodNode ; import org . codehaus . groovy . eclipse . codeassist . ProposalUtils ; import org . eclipse . jdt . groovy . search . AccessorSupport ; import org . eclipse . jdt . groovy . search . VariableScope ; public abstract class AbstractProposalCreator implements IProposalCreator { protected ClassNode lhsType ; protected VariableScope currentScope ; protected boolean checkName ( String name ) { return name . charAt ( <NUM_LIT:0> ) != '<CHAR_LIT>' && ! name . contains ( "<STR_LIT:$>" ) ; } protected void getAllSupers ( ClassNode type , Set < ClassNode > set , Set < ClassNode > except ) { if ( type == null ) { return ; } if ( ! except . contains ( type ) ) { set . add ( type ) ; } getAllSupers ( type . getSuperClass ( ) , set , except ) ; for ( ClassNode inter : ( Iterable < ClassNode > ) type . getAllInterfaces ( ) ) { if ( ! inter . getName ( ) . equals ( type . getName ( ) ) ) { getAllSupers ( inter , set , except ) ; } } } protected boolean isInterestingType ( ClassNode type ) { return lhsType != null && ClassHelper . getUnwrapper ( type ) . equals ( lhsType ) ; } protected void getAllSupersAsStrings ( ClassNode type , Set < String > set ) { if ( type == null ) { return ; } set . add ( type . getName ( ) ) ; getAllSupersAsStrings ( type . getSuperClass ( ) , set ) ; for ( ClassNode inter : ( Iterable < ClassNode > ) type . getAllInterfaces ( ) ) { if ( ! inter . getName ( ) . equals ( type . getName ( ) ) ) { getAllSupersAsStrings ( inter , set ) ; } } } public void setLhsType ( ClassNode lhsType ) { this . lhsType = lhsType ; } public void setCurrentScope ( VariableScope currentScope ) { this . currentScope = currentScope ; } protected boolean hasNoField ( ClassNode declaringClass , String methodName ) { return declaringClass . getField ( ProposalUtils . createMockFieldName ( methodName ) ) == null && declaringClass . getField ( ProposalUtils . createCapitalMockFieldName ( methodName ) ) == null ; } protected FieldNode createMockField ( MethodNode method ) { FieldNode field = new FieldNode ( ProposalUtils . createMockFieldName ( method . getName ( ) ) , method . getModifiers ( ) , method . getReturnType ( ) , method . getDeclaringClass ( ) , null ) ; field . setDeclaringClass ( method . getDeclaringClass ( ) ) ; field . setSourcePosition ( method ) ; return field ; } protected AccessorSupport findLooselyMatchedAccessorKind ( String prefix , String methodName , boolean isCategory ) { AccessorSupport accessor = AccessorSupport . create ( methodName , isCategory ) ; if ( accessor . isAccessor ( ) ) { String newName = ProposalUtils . createMockFieldName ( methodName ) ; return ProposalUtils . looselyMatches ( prefix , newName ) ? accessor : AccessorSupport . NONE ; } else { return AccessorSupport . NONE ; } } public boolean redoForLoopClosure ( ) { return true ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . codeassist . creators ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashSet ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import java . util . Map . Entry ; import java . util . Set ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . ImportNode ; import org . codehaus . groovy . ast . ImportNodeCompatibilityWrapper ; import org . codehaus . groovy . ast . MethodNode ; import org . codehaus . groovy . ast . ModuleNode ; import org . codehaus . groovy . eclipse . codeassist . ProposalUtils ; import org . codehaus . groovy . eclipse . codeassist . proposals . GroovyFieldProposal ; import org . codehaus . groovy . eclipse . codeassist . proposals . GroovyMethodProposal ; import org . codehaus . groovy . eclipse . codeassist . proposals . IGroovyProposal ; import org . codehaus . groovy . eclipse . codeassist . proposals . ProposalFormattingOptions ; import org . eclipse . jdt . groovy . search . AccessorSupport ; import org . eclipse . jdt . groovy . search . VariableScope ; public class MethodProposalCreator extends AbstractProposalCreator implements IProposalCreator { ProposalFormattingOptions options = ProposalFormattingOptions . newFromOptions ( ) ; private Set < ClassNode > alreadySeen = Collections . emptySet ( ) ; public List < IGroovyProposal > findAllProposals ( ClassNode type , Set < ClassNode > categories , String prefix , boolean isStatic , boolean isPrimary ) { boolean firstTime = alreadySeen . isEmpty ( ) ; List < MethodNode > allMethods = getAllMethods ( type ) ; List < IGroovyProposal > groovyProposals = new LinkedList < IGroovyProposal > ( ) ; Set < String > alreadySeenFields = new HashSet < String > ( ) ; if ( isStatic ) { alreadySeenFields . add ( "<STR_LIT:class>" ) ; } for ( MethodNode method : allMethods ) { String methodName = method . getName ( ) ; if ( ( ! isStatic || method . isStatic ( ) || method . getDeclaringClass ( ) == VariableScope . OBJECT_CLASS_NODE ) && checkName ( methodName ) ) { boolean isInterestingType = isInterestingType ( method . getReturnType ( ) ) ; if ( ProposalUtils . looselyMatches ( prefix , methodName ) ) { GroovyMethodProposal methodProposal = new GroovyMethodProposal ( method , "<STR_LIT>" , options ) ; float relevanceMultiplier = isInterestingType ? <NUM_LIT> : <NUM_LIT> ; relevanceMultiplier *= method . isStatic ( ) ? <NUM_LIT> : <NUM_LIT> ; relevanceMultiplier *= ! alreadySeen . isEmpty ( ) ? <NUM_LIT> : <NUM_LIT> ; methodProposal . setRelevanceMultiplier ( relevanceMultiplier ) ; groovyProposals . add ( methodProposal ) ; } AccessorSupport accessor = findLooselyMatchedAccessorKind ( prefix , methodName , false ) ; if ( accessor . isAccessorKind ( method , false ) ) { String mockFieldName = ProposalUtils . createMockFieldName ( methodName ) ; if ( ! alreadySeenFields . contains ( mockFieldName ) ) { alreadySeenFields . add ( mockFieldName ) ; if ( hasNoField ( method . getDeclaringClass ( ) , methodName ) ) { GroovyFieldProposal fieldProposal = new GroovyFieldProposal ( createMockField ( method ) ) ; fieldProposal . setRelevanceMultiplier ( isInterestingType ? <NUM_LIT:11> : <NUM_LIT:1> ) ; groovyProposals . add ( fieldProposal ) ; } } } } } ClassNode enclosingTypeDeclaration = currentScope . getEnclosingTypeDeclaration ( ) ; if ( enclosingTypeDeclaration != null && firstTime && isPrimary && type . getModule ( ) != null ) { groovyProposals . addAll ( getStaticImportProposals ( prefix , type . getModule ( ) ) ) ; } return groovyProposals ; } protected List < MethodNode > getAllMethods ( ClassNode thisType ) { Set < ClassNode > types = new HashSet < ClassNode > ( ) ; List < MethodNode > allMethods = thisType . getAllDeclaredMethods ( ) ; if ( ! alreadySeen . isEmpty ( ) ) { for ( Iterator < MethodNode > methodIter = allMethods . iterator ( ) ; methodIter . hasNext ( ) ; ) { if ( alreadySeen . contains ( methodIter . next ( ) . getDeclaringClass ( ) ) ) { methodIter . remove ( ) ; } } } getAllSupers ( thisType , types , alreadySeen ) ; if ( alreadySeen . isEmpty ( ) ) { alreadySeen = types ; } else { alreadySeen . addAll ( types ) ; } return allMethods ; } private List < IGroovyProposal > getStaticImportProposals ( String prefix , ModuleNode module ) { List < IGroovyProposal > staticProposals = new ArrayList < IGroovyProposal > ( ) ; Map < String , ImportNode > staticImports = ImportNodeCompatibilityWrapper . getStaticImports ( module ) ; for ( Entry < String , ImportNode > entry : staticImports . entrySet ( ) ) { String fieldName = entry . getValue ( ) . getFieldName ( ) ; if ( fieldName != null && ProposalUtils . looselyMatches ( prefix , fieldName ) ) { List < MethodNode > methods = entry . getValue ( ) . getType ( ) . getDeclaredMethods ( fieldName ) ; if ( methods != null ) { for ( MethodNode method : methods ) { staticProposals . add ( new GroovyMethodProposal ( method , "<STR_LIT>" , options ) ) ; } } } } Map < String , ImportNode > staticStarImports = ImportNodeCompatibilityWrapper . getStaticStarImports ( module ) ; for ( Entry < String , ImportNode > entry : staticStarImports . entrySet ( ) ) { ClassNode type = entry . getValue ( ) . getType ( ) ; if ( type != null ) { for ( MethodNode method : ( Iterable < MethodNode > ) type . getMethods ( ) ) { if ( method . isStatic ( ) && ProposalUtils . looselyMatches ( prefix , method . getName ( ) ) ) { staticProposals . add ( new GroovyMethodProposal ( method , "<STR_LIT>" , options ) ) ; } } } } return staticProposals ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . codeassist . creators ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . HashMap ; import java . util . LinkedHashSet ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import java . util . Map . Entry ; import java . util . Set ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . FieldNode ; import org . codehaus . groovy . ast . ImportNode ; import org . codehaus . groovy . ast . ImportNodeCompatibilityWrapper ; import org . codehaus . groovy . ast . MethodNode ; import org . codehaus . groovy . ast . ModuleNode ; import org . codehaus . groovy . ast . Parameter ; import org . codehaus . groovy . ast . expr . ClosureExpression ; import org . codehaus . groovy . ast . expr . Expression ; import org . codehaus . groovy . ast . stmt . BlockStatement ; import org . codehaus . groovy . eclipse . codeassist . ProposalUtils ; import org . codehaus . groovy . eclipse . codeassist . proposals . GroovyFieldProposal ; import org . codehaus . groovy . eclipse . codeassist . proposals . GroovyMethodProposal ; import org . codehaus . groovy . eclipse . codeassist . proposals . IGroovyProposal ; import org . eclipse . jdt . groovy . search . VariableScope ; import org . objectweb . asm . Opcodes ; public class FieldProposalCreator extends AbstractProposalCreator implements IProposalCreator { private static final Parameter [ ] NO_PARAMETERS = new Parameter [ <NUM_LIT:0> ] ; private static final ClassNode [ ] NO_CLASSES = new ClassNode [ <NUM_LIT:0> ] ; private static final GroovyFieldProposal CLASS_PROPOSAL = createClassProposal ( ) ; private Set < ClassNode > alreadySeen = Collections . emptySet ( ) ; private static GroovyFieldProposal createClassProposal ( ) { FieldNode field = new FieldNode ( "<STR_LIT:class>" , Opcodes . ACC_PUBLIC & Opcodes . ACC_STATIC & Opcodes . ACC_FINAL , VariableScope . CLASS_CLASS_NODE , VariableScope . OBJECT_CLASS_NODE , null ) ; field . setDeclaringClass ( VariableScope . OBJECT_CLASS_NODE ) ; return new GroovyFieldProposal ( field ) ; } public List < IGroovyProposal > findAllProposals ( ClassNode type , Set < ClassNode > categories , String prefix , boolean isStatic , boolean isPrimary ) { boolean isFirstTime = alreadySeen . isEmpty ( ) ; Collection < FieldNode > allFields = getAllFields ( type ) ; List < IGroovyProposal > groovyProposals = new LinkedList < IGroovyProposal > ( ) ; for ( FieldNode field : allFields ) { if ( ( ! isStatic || field . isStatic ( ) ) && ProposalUtils . looselyMatches ( prefix , field . getName ( ) ) ) { GroovyFieldProposal fieldProposal = new GroovyFieldProposal ( field ) ; float relevanceMultiplier = isInterestingType ( field . getType ( ) ) ? <NUM_LIT> : <NUM_LIT> ; relevanceMultiplier *= field . isStatic ( ) ? <NUM_LIT> : <NUM_LIT> ; relevanceMultiplier *= ! isFirstTime ? <NUM_LIT> : <NUM_LIT> ; fieldProposal . setRelevanceMultiplier ( relevanceMultiplier ) ; groovyProposals . add ( fieldProposal ) ; if ( field . getInitialExpression ( ) instanceof ClosureExpression ) { groovyProposals . add ( new GroovyMethodProposal ( convertToMethodProposal ( field ) ) ) ; } } } if ( isStatic && "<STR_LIT:class>" . startsWith ( prefix ) ) { groovyProposals . add ( CLASS_PROPOSAL ) ; } ClassNode enclosingTypeDeclaration = currentScope . getEnclosingTypeDeclaration ( ) ; if ( enclosingTypeDeclaration != null && isFirstTime && isPrimary && type . getModule ( ) != null ) { groovyProposals . addAll ( getStaticImportProposals ( prefix , type . getModule ( ) ) ) ; } return groovyProposals ; } private MethodNode convertToMethodProposal ( FieldNode field ) { MethodNode method = new MethodNode ( field . getName ( ) , field . getModifiers ( ) , field . getType ( ) , extractParameters ( field . getInitialExpression ( ) ) , NO_CLASSES , new BlockStatement ( ) ) ; method . setDeclaringClass ( field . getDeclaringClass ( ) ) ; return method ; } private Parameter [ ] extractParameters ( Expression expr ) { if ( expr instanceof ClosureExpression ) { return ( ( ClosureExpression ) expr ) . getParameters ( ) ; } return NO_PARAMETERS ; } private List < IGroovyProposal > getStaticImportProposals ( String prefix , ModuleNode module ) { List < IGroovyProposal > staticProposals = new ArrayList < IGroovyProposal > ( ) ; Map < String , ImportNode > staticImports = ImportNodeCompatibilityWrapper . getStaticImports ( module ) ; for ( Entry < String , ImportNode > entry : staticImports . entrySet ( ) ) { String fieldName = entry . getValue ( ) . getFieldName ( ) ; if ( fieldName != null && ProposalUtils . looselyMatches ( prefix , fieldName ) ) { FieldNode field = entry . getValue ( ) . getType ( ) . getField ( fieldName ) ; if ( field != null ) { staticProposals . add ( new GroovyFieldProposal ( field ) ) ; } } } Map < String , ImportNode > staticStarImports = ImportNodeCompatibilityWrapper . getStaticStarImports ( module ) ; for ( Entry < String , ImportNode > entry : staticStarImports . entrySet ( ) ) { ClassNode type = entry . getValue ( ) . getType ( ) ; if ( type != null ) { for ( FieldNode field : ( Iterable < FieldNode > ) type . getFields ( ) ) { if ( field . isStatic ( ) && ProposalUtils . looselyMatches ( prefix , field . getName ( ) ) ) { staticProposals . add ( new GroovyFieldProposal ( field ) ) ; } } } } return staticProposals ; } private Collection < FieldNode > getAllFields ( ClassNode thisType ) { Set < ClassNode > types = new LinkedHashSet < ClassNode > ( ) ; getAllSupers ( thisType , types , alreadySeen ) ; Map < String , FieldNode > nameFieldMap = new HashMap < String , FieldNode > ( ) ; for ( ClassNode type : types ) { for ( FieldNode field : type . getFields ( ) ) { if ( checkName ( field . getName ( ) ) ) { FieldNode existing = nameFieldMap . get ( field . getName ( ) ) ; if ( existing == null || leftIsMoreAccessible ( field , existing ) ) { nameFieldMap . put ( field . getName ( ) , field ) ; } } } } if ( alreadySeen . isEmpty ( ) ) { alreadySeen = types ; } else { alreadySeen . addAll ( types ) ; } return nameFieldMap . values ( ) ; } private boolean leftIsMoreAccessible ( FieldNode field , FieldNode existing ) { int leftAcc ; switch ( field . getModifiers ( ) & ( Opcodes . ACC_PUBLIC | Opcodes . ACC_PRIVATE | Opcodes . ACC_PROTECTED ) ) { case Opcodes . ACC_PUBLIC : leftAcc = <NUM_LIT:0> ; break ; case Opcodes . ACC_PROTECTED : leftAcc = <NUM_LIT:1> ; break ; case Opcodes . ACC_PRIVATE : leftAcc = <NUM_LIT:3> ; break ; default : leftAcc = <NUM_LIT:2> ; break ; } int rightAcc ; switch ( existing . getModifiers ( ) & ( Opcodes . ACC_PUBLIC | Opcodes . ACC_PRIVATE | Opcodes . ACC_PROTECTED ) ) { case Opcodes . ACC_PUBLIC : rightAcc = <NUM_LIT:0> ; break ; case Opcodes . ACC_PROTECTED : rightAcc = <NUM_LIT:1> ; break ; case Opcodes . ACC_PRIVATE : rightAcc = <NUM_LIT:3> ; break ; default : rightAcc = <NUM_LIT:2> ; break ; } return leftAcc < rightAcc ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . codeassist . creators ; import java . util . List ; import java . util . Set ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . eclipse . codeassist . proposals . IGroovyProposal ; public interface IProposalCreator { List < IGroovyProposal > findAllProposals ( ClassNode type , Set < ClassNode > categories , String prefix , boolean isStatic , boolean isPrimary ) ; boolean redoForLoopClosure ( ) ; } </s>
|
<s> package org . codehaus . groovy . eclipse . codeassist . creators ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . HashSet ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . MethodNode ; import org . codehaus . groovy . ast . Parameter ; import org . codehaus . groovy . eclipse . codeassist . ProposalUtils ; import org . codehaus . groovy . eclipse . codeassist . preferences . DGMProposalFilter ; import org . codehaus . groovy . eclipse . codeassist . proposals . GroovyCategoryMethodProposal ; import org . codehaus . groovy . eclipse . codeassist . proposals . GroovyFieldProposal ; import org . codehaus . groovy . eclipse . codeassist . proposals . IGroovyProposal ; import org . eclipse . jdt . groovy . search . VariableScope ; public class CategoryProposalCreator extends AbstractProposalCreator { public List < IGroovyProposal > findAllProposals ( ClassNode type , Set < ClassNode > categories , String prefix , boolean isStatic , boolean isPrimary ) { ClassNode candidate = VariableScope . maybeConvertFromPrimitive ( type ) ; Set < String > set = new HashSet < String > ( ) ; getAllSupersAsStrings ( candidate , set ) ; set . add ( "<STR_LIT>" ) ; List < IGroovyProposal > groovyProposals = findAllProposals ( set , categories , prefix , candidate ) ; return groovyProposals ; } private List < IGroovyProposal > findAllProposals ( Set < String > set , Set < ClassNode > categories , String prefix , ClassNode declaringClass ) { DGMProposalFilter filter = new DGMProposalFilter ( ) ; List < IGroovyProposal > groovyProposals = new LinkedList < IGroovyProposal > ( ) ; Set < String > existingFieldProposals = new HashSet < String > ( ) ; Map < String , List < MethodNode > > existingMethodProposals = new HashMap < String , List < MethodNode > > ( ) ; for ( ClassNode category : categories ) { List < MethodNode > allMethods = category . getAllDeclaredMethods ( ) ; boolean isDGMCategory = isDGMCategory ( category ) ; for ( MethodNode method : allMethods ) { if ( isDGMCategory && filter . isFiltered ( method ) ) { continue ; } String methodName = method . getName ( ) ; if ( method . isStatic ( ) && method . isPublic ( ) ) { Parameter [ ] params = method . getParameters ( ) ; if ( ProposalUtils . looselyMatches ( prefix , methodName ) ) { if ( params != null && params . length > <NUM_LIT:0> && set . contains ( params [ <NUM_LIT:0> ] . getType ( ) . getName ( ) ) && ! dupMethod ( method , existingMethodProposals ) ) { GroovyCategoryMethodProposal methodProposal = new GroovyCategoryMethodProposal ( method ) ; methodProposal . setRelevanceMultiplier ( isInterestingType ( method . getReturnType ( ) ) ? <NUM_LIT> : <NUM_LIT:1> ) ; groovyProposals . add ( methodProposal ) ; List < MethodNode > methodList = existingMethodProposals . get ( methodName ) ; if ( methodList == null ) { methodList = new ArrayList < MethodNode > ( <NUM_LIT:2> ) ; existingMethodProposals . put ( methodName , methodList ) ; } methodList . add ( method ) ; } } else if ( params . length == <NUM_LIT:1> && findLooselyMatchedAccessorKind ( prefix , methodName , true ) . isAccessorKind ( method , true ) && ! existingFieldProposals . contains ( methodName ) && hasNoField ( declaringClass , methodName ) ) { GroovyFieldProposal fieldProposal = new GroovyFieldProposal ( createMockField ( method ) ) ; fieldProposal . setRelevanceMultiplier ( <NUM_LIT:1> ) ; groovyProposals . add ( fieldProposal ) ; existingFieldProposals . add ( methodName ) ; } } } } return groovyProposals ; } private boolean dupMethod ( MethodNode newMethod , Map < String , List < MethodNode > > existingMethodProposals ) { List < MethodNode > otherMethods = existingMethodProposals . get ( newMethod . getName ( ) ) ; if ( otherMethods != null ) { Parameter [ ] newParameters = newMethod . getParameters ( ) ; for ( MethodNode otherMethod : otherMethods ) { Parameter [ ] otherParameters = otherMethod . getParameters ( ) ; if ( otherParameters . length == newParameters . length ) { for ( int i = <NUM_LIT:1> ; i < otherParameters . length ; i ++ ) { if ( ! otherParameters [ i ] . getType ( ) . getName ( ) . equals ( newParameters [ i ] . getType ( ) . getName ( ) ) ) { continue ; } } return true ; } } } return false ; } private boolean isDGMCategory ( ClassNode category ) { String className = category . getName ( ) ; for ( ClassNode dgClass : VariableScope . ALL_DEFAULT_CATEGORIES ) { if ( dgClass . getName ( ) . equals ( className ) ) { return true ; } } return false ; } @ Override public boolean redoForLoopClosure ( ) { return true ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . codeassist ; import org . codehaus . groovy . eclipse . core . ISourceBuffer ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; public class DocumentSourceBuffer implements ISourceBuffer { private IDocument document ; public DocumentSourceBuffer ( IDocument document ) { this . document = document ; } public char charAt ( int offset ) { try { return document . getChar ( offset ) ; } catch ( BadLocationException e ) { throw new IndexOutOfBoundsException ( e . getMessage ( ) ) ; } } public int length ( ) { return document . getLength ( ) ; } public CharSequence subSequence ( int start , int end ) { try { return document . get ( start , end - start ) ; } catch ( BadLocationException e ) { throw new IndexOutOfBoundsException ( e . getMessage ( ) ) ; } } public int [ ] toLineColumn ( int offset ) { int line ; try { line = document . getLineOfOffset ( offset ) ; int lineOffset = document . getLineOffset ( line ) ; return new int [ ] { line + <NUM_LIT:1> , offset - lineOffset + <NUM_LIT:1> } ; } catch ( BadLocationException e ) { throw new IndexOutOfBoundsException ( e . getMessage ( ) ) ; } } public int toOffset ( int line , int column ) { int offset ; try { offset = document . getLineOffset ( line - <NUM_LIT:1> ) ; return offset + column - <NUM_LIT:1> ; } catch ( BadLocationException e ) { try { return document . getLineOffset ( document . getNumberOfLines ( ) - <NUM_LIT:1> ) ; } catch ( BadLocationException e1 ) { throw new IndexOutOfBoundsException ( e . getMessage ( ) ) ; } } } } </s>
|
<s> package org . codehaus . groovy . eclipse . codeassist ; import org . codehaus . groovy . eclipse . core . ISourceBuffer ; import org . eclipse . jdt . core . compiler . CharOperation ; public class CharArraySourceBuffer implements ISourceBuffer { private final char [ ] chars ; public CharArraySourceBuffer ( char [ ] chars ) { this . chars = chars ; } public char charAt ( int offset ) { return chars [ offset ] ; } public int length ( ) { return chars . length ; } public CharSequence subSequence ( int start , int end ) { return String . valueOf ( CharOperation . subarray ( chars , start , end ) ) ; } public int [ ] toLineColumn ( int offset ) { return null ; } public int toOffset ( int line , int column ) { return <NUM_LIT:0> ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . codeassist . relevance ; import java . util . Arrays ; import org . codehaus . groovy . eclipse . codeassist . ProposalUtils ; import org . codehaus . groovy . eclipse . core . GroovyCore ; import org . eclipse . jdt . core . Flags ; import org . eclipse . jdt . core . IAccessRule ; import org . eclipse . jdt . core . IPackageFragment ; import org . eclipse . jdt . core . IType ; import org . eclipse . jdt . core . JavaModelException ; import org . eclipse . jdt . core . compiler . CharOperation ; import org . eclipse . jdt . core . compiler . IProblem ; import org . eclipse . jdt . internal . compiler . env . AccessRestriction ; import org . eclipse . jdt . internal . core . SourceType ; public class RelevanceRules implements IRelevanceRule { public static int DEFAULT_STARTING_RELEVANCE_VALUE = <NUM_LIT:1> ; public static enum RelevanceRuleType { SOURCE_TYPE , ACCESSIBILITY , MODIFIERS , LIBRARY_TYPE , SIMILAR_PACKAGE } private RelevanceRuleType [ ] ruleTypes ; public static RelevanceRules ALL_RULES = new RelevanceRules ( RelevanceRuleType . LIBRARY_TYPE , RelevanceRuleType . SOURCE_TYPE , RelevanceRuleType . MODIFIERS , RelevanceRuleType . SIMILAR_PACKAGE ) ; public static IRelevanceRule getRule ( RelevanceRuleType type ) { if ( type == null ) { return null ; } IRelevanceRule rule = null ; switch ( type ) { case SOURCE_TYPE : rule = new SourceRule ( ) ; break ; case MODIFIERS : rule = new ModifierRule ( ) ; break ; case LIBRARY_TYPE : rule = new LibraryTypeRule ( ) ; break ; case SIMILAR_PACKAGE : rule = new SimilarPackagesRule ( ) ; break ; } return rule ; } public RelevanceRules ( RelevanceRuleType ... ruleTypes ) { this . ruleTypes = ruleTypes ; } public int getRelevance ( char [ ] fullyQualifiedName , IType [ ] contextTypes , int accessibility , int modifiers ) { if ( fullyQualifiedName == null ) { return <NUM_LIT:0> ; } RelevanceRuleType [ ] rTypes = ruleTypes == null || ruleTypes . length == <NUM_LIT:0> ? RelevanceRuleType . values ( ) : ruleTypes ; int relevance = getStartingRelevanceValue ( ) ; for ( RelevanceRuleType ruleType : rTypes ) { IRelevanceRule rule = getRule ( ruleType ) ; if ( rule != null ) { relevance += rule . getRelevance ( fullyQualifiedName , contextTypes , accessibility , modifiers ) ; } } return Relevance . LOWEST . getRelevance ( relevance ) ; } public int getRelevance ( IType type , IType [ ] contextTypes ) { if ( type == null ) { return <NUM_LIT:0> ; } RelevanceRuleType [ ] rTypes = ruleTypes == null || ruleTypes . length == <NUM_LIT:0> ? RelevanceRuleType . values ( ) : ruleTypes ; int relevance = getStartingRelevanceValue ( ) ; for ( RelevanceRuleType ruleType : rTypes ) { IRelevanceRule rule = getRule ( ruleType ) ; if ( rule != null ) { relevance += rule . getRelevance ( type , contextTypes ) ; } } return Relevance . LOWEST . getRelevance ( relevance ) ; } protected int getStartingRelevanceValue ( ) { return DEFAULT_STARTING_RELEVANCE_VALUE ; } public static class SourceRule extends AbstractRule { public int getRelevance ( IType relevanceType , IType [ ] contextTypes ) { return relevanceType instanceof SourceType ? TypeRelevanceCategory . MEDIUM_TYPE . applyCategory ( <NUM_LIT:1> ) : TypeRelevanceCategory . LOW_TYPE . applyCategory ( <NUM_LIT:1> ) ; } public int getRelevance ( char [ ] fullyQualifiedName , IType [ ] contextTypes , int accessibility , int modifiers ) { return <NUM_LIT:0> ; } } public static class AccessibilityRule extends AbstractRule { public int getRelevance ( IType relevanceType , IType [ ] contextTypes ) { if ( relevanceType == null ) { return <NUM_LIT:0> ; } AccessRestriction accessRestriction = ProposalUtils . getTypeAccessibility ( relevanceType ) ; int accessibility = IAccessRule . K_ACCESSIBLE ; if ( accessRestriction != null ) { switch ( accessRestriction . getProblemId ( ) ) { case IProblem . ForbiddenReference : accessibility = IAccessRule . K_NON_ACCESSIBLE ; break ; case IProblem . DiscouragedReference : accessibility = IAccessRule . K_DISCOURAGED ; break ; } } return getRelevance ( null , null , accessibility , <NUM_LIT:0> ) ; } public int getRelevance ( char [ ] fullyQualifiedName , IType [ ] contextTypes , int accessibility , int modifiers ) { return accessibility == IAccessRule . K_ACCESSIBLE ? TypeRelevanceCategory . MEDIUM_TYPE . applyCategory ( <NUM_LIT:1> ) : <NUM_LIT:0> ; } } public static class ModifierRule extends AbstractRule { protected TypeRelevanceCategory getTypeCategory ( IType relevanceType , IType [ ] contextTypes ) { TypeRelevanceCategory category = null ; if ( areTypesInSameCompilationUnit ( relevanceType , contextTypes ) ) { category = TypeRelevanceCategory . HIGH_TYPE ; } else if ( areTypesInSamePackage ( relevanceType , contextTypes ) ) { category = TypeRelevanceCategory . MEDIUM_HIGH_TYPE ; } else { category = null ; } return category ; } public int getRelevance ( IType relevanceType , IType [ ] contextTypes ) { int relevance = <NUM_LIT:0> ; TypeRelevanceCategory category = null ; try { int modifiers = relevanceType . getFlags ( ) ; category = getTypeCategory ( relevanceType , contextTypes ) ; if ( category != null ) { relevance += ( modifiers & Flags . AccDefault ) != <NUM_LIT:0> ? <NUM_LIT:0> : <NUM_LIT:1> ; relevance += ( modifiers & Flags . AccPrivate ) != <NUM_LIT:0> ? <NUM_LIT:0> : <NUM_LIT:1> ; return category . applyCategory ( relevance ) ; } } catch ( JavaModelException e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; } return <NUM_LIT:0> ; } public int getRelevance ( char [ ] fullyQualifiedName , IType [ ] contextTypes , int accessibility , int modifiers ) { return <NUM_LIT:0> ; } } public static class LibraryTypeRule extends AbstractRule { enum LibraryType { JAVA ( "<STR_LIT>" ) , JAVAX ( "<STR_LIT>" ) , GROOVY ( "<STR_LIT>" ) , GROOVYX ( "<STR_LIT>" ) ; private LibraryType ( String value ) { this . value = value . toCharArray ( ) ; } private char [ ] value ; public char [ ] getValue ( ) { return value ; } } protected LibraryType getLibraryType ( char [ ] qualifiedName ) { char [ ] [ ] segments = CharOperation . splitOn ( '<CHAR_LIT:.>' , qualifiedName ) ; if ( segments != null && segments . length > <NUM_LIT:0> ) { char [ ] firstPackSegment = segments [ <NUM_LIT:0> ] ; for ( LibraryType type : LibraryType . values ( ) ) { if ( Arrays . equals ( type . getValue ( ) , firstPackSegment ) ) { return type ; } } } return null ; } public int getRelevance ( IType relevanceType , IType [ ] contextTypes ) { if ( relevanceType == null ) { return <NUM_LIT:0> ; } return getRelevance ( relevanceType . getFullyQualifiedName ( ) . toCharArray ( ) , contextTypes , <NUM_LIT:0> , <NUM_LIT:0> ) ; } public int getRelevance ( char [ ] fullyQualifiedName , IType [ ] contextTypes , int accessibility , int modifiers ) { int relevance = <NUM_LIT:0> ; LibraryType packType = getLibraryType ( fullyQualifiedName ) ; if ( packType != null ) { switch ( packType ) { case JAVA : relevance += <NUM_LIT:4> ; break ; case GROOVY : relevance += <NUM_LIT:3> ; break ; case GROOVYX : relevance += <NUM_LIT:2> ; break ; case JAVAX : relevance += <NUM_LIT:1> ; break ; } } return TypeRelevanceCategory . LOW_TYPE . applyCategory ( relevance ) ; } } public static class SimilarPackagesRule extends AbstractRule { protected String convertToDot ( String name ) { return name != null ? name . replace ( '<CHAR_LIT>' , '<CHAR_LIT:.>' ) : name ; } public int getRelevance ( IType relevanceType , IType [ ] contextTypes ) { return getRelevance ( relevanceType . getFullyQualifiedName ( '<CHAR_LIT:.>' ) . toCharArray ( ) , contextTypes , <NUM_LIT:0> , <NUM_LIT:0> ) ; } public int getRelevance ( char [ ] fullyQualifiedName , IType [ ] contextTypes , int accessibility , int modifiers ) { int relevance = <NUM_LIT:0> ; IPackageFragment contextFragment = getContextPackageFragment ( contextTypes ) ; if ( contextFragment != null && fullyQualifiedName != null ) { String relQualified = String . valueOf ( fullyQualifiedName ) ; String contextQualified = convertToDot ( contextFragment . getElementName ( ) ) ; String [ ] relSegments = relQualified . split ( "<STR_LIT:\\.>" ) ; String [ ] contextSegments = contextQualified . split ( "<STR_LIT:\\.>" ) ; for ( int i = <NUM_LIT:0> ; i < relSegments . length && i < contextSegments . length ; i ++ ) { if ( relSegments [ i ] . equals ( contextSegments [ i ] ) ) { relevance ++ ; } else { break ; } } } return TypeRelevanceCategory . HIGH_TYPE . applyCategory ( relevance ) ; } } } </s>
|
<s> package org . codehaus . groovy . eclipse . codeassist . relevance ; import org . eclipse . jdt . core . ICompilationUnit ; import org . eclipse . jdt . core . IJavaProject ; import org . eclipse . jdt . core . IPackageFragment ; import org . eclipse . jdt . core . IType ; public abstract class AbstractRule implements IRelevanceRule { public enum TypeRelevanceCategory { LOWEST_TYPE ( <NUM_LIT:1> ) , LOW_TYPE ( <NUM_LIT:4> ) , MEDIUM_TYPE ( <NUM_LIT:8> ) , MEDIUM_HIGH_TYPE ( <NUM_LIT:12> ) , HIGH_TYPE ( <NUM_LIT:16> ) ; private double multiplier ; private TypeRelevanceCategory ( double multiplier ) { this . multiplier = multiplier ; } public double getMultiplier ( ) { return multiplier ; } public int applyCategory ( int value ) { return ( int ) getMultiplier ( ) * value ; } } public boolean areTypesInSameProject ( IType relevanceType , IType [ ] contextTypes ) { if ( relevanceType == null || contextTypes == null || contextTypes . length == <NUM_LIT:0> ) { return false ; } IJavaProject relevanceProject = relevanceType . getJavaProject ( ) ; if ( relevanceProject == null ) { return false ; } for ( IType cType : contextTypes ) { if ( ! relevanceProject . equals ( cType . getJavaProject ( ) ) ) { return false ; } } return true ; } public boolean areTypesInSamePackage ( IType relevanceType , IType [ ] contextTypes ) { if ( relevanceType == null || contextTypes == null || contextTypes . length == <NUM_LIT:0> ) { return false ; } IPackageFragment relevancePackage = relevanceType . getPackageFragment ( ) ; if ( relevancePackage == null ) { return false ; } for ( IType cType : contextTypes ) { if ( ! relevancePackage . equals ( cType . getPackageFragment ( ) ) ) { return false ; } } return true ; } public boolean areTypesInSameCompilationUnit ( IType relevanceType , IType [ ] contextTypes ) { if ( relevanceType == null || contextTypes == null || contextTypes . length == <NUM_LIT:0> ) { return false ; } ICompilationUnit relevanceCompilationUnit = relevanceType . getCompilationUnit ( ) ; if ( relevanceCompilationUnit != null ) { for ( IType contextType : contextTypes ) { ICompilationUnit contextCu = contextType . getCompilationUnit ( ) ; if ( ! relevanceCompilationUnit . equals ( contextCu ) ) { return false ; } } return true ; } return false ; } public IPackageFragment getContextPackageFragment ( IType [ ] contextTypes ) { if ( contextTypes == null ) { return null ; } IPackageFragment frag = null ; for ( IType type : contextTypes ) { IPackageFragment fragToCheck = type . getPackageFragment ( ) ; if ( frag != null && ! frag . equals ( fragToCheck ) ) { return null ; } frag = fragToCheck ; } return frag ; } public IType getFirstContextType ( IType [ ] contextTypes ) { return contextTypes != null && contextTypes . length > <NUM_LIT:0> ? contextTypes [ <NUM_LIT:0> ] : null ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . codeassist . relevance ; import java . util . HashSet ; import java . util . Set ; import org . codehaus . groovy . ast . AnnotatedNode ; import org . codehaus . groovy . ast . FieldNode ; import org . codehaus . groovy . ast . MethodNode ; import org . codehaus . groovy . eclipse . codeassist . proposals . AbstractGroovyProposal ; import org . codehaus . groovy . eclipse . codeassist . proposals . GroovyCategoryMethodProposal ; import org . codehaus . groovy . eclipse . codeassist . proposals . GroovyFieldProposal ; import org . codehaus . groovy . eclipse . codeassist . proposals . GroovyMethodProposal ; import org . codehaus . groovy . eclipse . codeassist . proposals . GroovyPropertyProposal ; import org . eclipse . jdt . groovy . search . VariableScope ; public enum Relevance { LOWEST ( <NUM_LIT:1> ) , VERY_LOW ( <NUM_LIT:10> ) , LOW ( <NUM_LIT:100> ) , MEDIUM ( <NUM_LIT:1000> ) , MEDIUM_HIGH ( <NUM_LIT> ) , HIGH ( <NUM_LIT> ) , VERY_HIGH ( <NUM_LIT> ) ; private Relevance ( int value ) { this . value = value ; } private int value ; public int getRelevance ( float multiplier ) { return Math . max ( <NUM_LIT:1> , ( int ) ( ( float ) value * multiplier ) ) ; } public int getRelavance ( ) { return value ; } public static int calculateRelevance ( AbstractGroovyProposal groovyProposal , float multiplier ) { return findRelevanceClass ( groovyProposal ) . getRelevance ( multiplier ) ; } public static Relevance findRelevanceClass ( AbstractGroovyProposal groovyProposal ) { if ( groovyProposal instanceof GroovyFieldProposal || groovyProposal instanceof GroovyPropertyProposal ) { AnnotatedNode node = groovyProposal . getAssociatedNode ( ) ; if ( node instanceof FieldNode && IGNORED_FIELD_NAMES . contains ( ( ( FieldNode ) node ) . getName ( ) ) ) { return VERY_LOW ; } else { return MEDIUM_HIGH ; } } else if ( groovyProposal instanceof GroovyCategoryMethodProposal ) { AnnotatedNode node = groovyProposal . getAssociatedNode ( ) ; if ( ! ( node instanceof MethodNode ) ) { return MEDIUM_HIGH ; } MethodNode method = ( MethodNode ) node ; if ( VariableScope . ALL_DEFAULT_CATEGORIES . contains ( method . getDeclaringClass ( ) ) ) { return VERY_LOW ; } else { return MEDIUM_HIGH ; } } else if ( groovyProposal instanceof GroovyMethodProposal ) { AnnotatedNode node = groovyProposal . getAssociatedNode ( ) ; if ( ! ( node instanceof MethodNode ) ) { return MEDIUM ; } MethodNode method = ( MethodNode ) node ; if ( node instanceof MethodNode && IGNORED_METHOD_NAMES . contains ( method . getName ( ) ) || VariableScope . OBJECT_CLASS_NODE . equals ( method . getDeclaringClass ( ) ) ) { return VERY_LOW ; } else { return MEDIUM ; } } else { return MEDIUM ; } } private static final Set < String > IGNORED_FIELD_NAMES = new HashSet < String > ( ) ; static { IGNORED_FIELD_NAMES . add ( "<STR_LIT>" ) ; IGNORED_FIELD_NAMES . add ( "<STR_LIT>" ) ; IGNORED_FIELD_NAMES . add ( "<STR_LIT:class>" ) ; } private static final Set < String > IGNORED_METHOD_NAMES = new HashSet < String > ( ) ; static { IGNORED_METHOD_NAMES . add ( "<STR_LIT>" ) ; IGNORED_METHOD_NAMES . add ( "<STR_LIT>" ) ; IGNORED_METHOD_NAMES . add ( "<STR_LIT>" ) ; IGNORED_METHOD_NAMES . add ( "<STR_LIT>" ) ; IGNORED_METHOD_NAMES . add ( "<STR_LIT>" ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . codeassist . relevance ; import org . eclipse . jdt . core . IType ; public interface IRelevanceRule { public int getRelevance ( IType relevanceType , IType [ ] contextTypes ) ; public int getRelevance ( char [ ] fullyQualifiedName , IType [ ] contextTypes , int accessibility , int modifiers ) ; } </s>
|
<s> package org . codehaus . groovy . eclipse . codeassist . preferences ; import java . util . Arrays ; import org . codehaus . groovy . eclipse . codeassist . GroovyContentAssistActivator ; import org . codehaus . groovy . eclipse . preferences . FieldEditorOverlayPage ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jdt . core . JavaConventions ; import org . eclipse . jdt . internal . corext . util . JavaConventionsUtil ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . jface . dialogs . IInputValidator ; import org . eclipse . jface . dialogs . InputDialog ; import org . eclipse . jface . preference . ListEditor ; import org . eclipse . jface . window . Window ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . IWorkbenchPreferencePage ; public class ContentAssistPreferencesPage extends FieldEditorOverlayPage implements IWorkbenchPreferencePage { private class DGMValidator implements IInputValidator { public String isValid ( String newText ) { if ( newText . trim ( ) . length ( ) == <NUM_LIT:0> ) { return "<STR_LIT>" ; } String [ ] complianceLevels = JavaConventionsUtil . getSourceComplianceLevels ( null ) ; IStatus s = JavaConventions . validateMethodName ( newText , complianceLevels [ <NUM_LIT:0> ] , complianceLevels [ <NUM_LIT:1> ] ) ; if ( s . getSeverity ( ) > IStatus . OK ) { return s . getMessage ( ) ; } return null ; } } private class MultiDGMValidator extends DGMValidator { @ Override public String isValid ( String newText ) { String [ ] splits = newText . split ( "<STR_LIT>" ) ; StringBuilder sb = new StringBuilder ( ) ; for ( String split : splits ) { String res = super . isValid ( split ) ; if ( res != null ) { sb . append ( res ) ; } } return sb . length ( ) > <NUM_LIT:0> ? sb . toString ( ) : null ; } } private class CompletionFilterListEditor extends ListEditor { private Button addMultipleButton ; public CompletionFilterListEditor ( String name , String labelText , Composite parent ) { super ( name , labelText , parent ) ; setPreferenceName ( GroovyContentAssistActivator . FILTERED_DGMS ) ; } @ Override protected String createList ( String [ ] items ) { StringBuilder sb = new StringBuilder ( ) ; for ( String item : items ) { sb . append ( item + "<STR_LIT:U+002C>" ) ; } return sb . toString ( ) ; } @ Override protected String getNewInputObject ( ) { InputDialog dialog = new InputDialog ( getFieldEditorParent ( ) . getShell ( ) , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , new DGMValidator ( ) ) ; int res = dialog . open ( ) ; if ( res == Window . OK ) { return dialog . getValue ( ) ; } return null ; } @ Override public Composite getButtonBoxControl ( Composite parent ) { Composite buttonBox = super . getButtonBoxControl ( parent ) ; if ( addMultipleButton == null ) { addMultipleButton = createAddMultipleButton ( buttonBox , "<STR_LIT>" ) ; } getUpButton ( ) . setVisible ( false ) ; getDownButton ( ) . setVisible ( false ) ; return buttonBox ; } private Button createAddMultipleButton ( Composite parent , String name ) { Button button = new Button ( parent , SWT . PUSH ) ; button . setText ( name ) ; button . setFont ( parent . getFont ( ) ) ; GridData data = new GridData ( GridData . FILL_HORIZONTAL ) ; int widthHint = convertHorizontalDLUsToPixels ( button , IDialogConstants . BUTTON_WIDTH ) ; data . widthHint = Math . max ( widthHint , button . computeSize ( SWT . DEFAULT , SWT . DEFAULT , true ) . x ) ; button . setLayoutData ( data ) ; button . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { addMultiple ( ) ; } } ) ; return button ; } protected void addMultiple ( ) { String [ ] items = getList ( ) . getItems ( ) ; StringBuilder sb = new StringBuilder ( ) ; for ( String item : items ) { sb . append ( item + "<STR_LIT:n>" ) ; } InputDialog input = new InputDialog ( getShell ( ) , "<STR_LIT>" , "<STR_LIT>" , sb . toString ( ) , new MultiDGMValidator ( ) ) { @ Override protected int getInputTextStyle ( ) { return SWT . MULTI | SWT . BORDER ; } @ Override protected Control createDialogArea ( Composite parent ) { Control child = super . createDialogArea ( parent ) ; getText ( ) . setLayoutData ( new GridData ( GridData . GRAB_HORIZONTAL | GridData . HORIZONTAL_ALIGN_FILL | GridData . GRAB_VERTICAL | GridData . VERTICAL_ALIGN_FILL ) ) ; return child ; } } ; int res = input . open ( ) ; if ( res == Window . OK ) { String text = input . getValue ( ) ; items = text . split ( "<STR_LIT>" ) ; Arrays . sort ( items ) ; getList ( ) . setItems ( items ) ; getList ( ) . deselectAll ( ) ; selectionChanged ( ) ; } } @ Override protected String [ ] parseString ( String stringList ) { String [ ] split = stringList . split ( "<STR_LIT:U+002C>" ) ; Arrays . sort ( split ) ; return split ; } } public ContentAssistPreferencesPage ( ) { super ( FLAT ) ; setPreferenceStore ( GroovyContentAssistActivator . getDefault ( ) . getPreferenceStore ( ) ) ; } @ Override protected String getPageId ( ) { return "<STR_LIT>" ; } @ Override protected void createFieldEditors ( ) { addField ( new CompletionFilterListEditor ( "<STR_LIT>" , "<STR_LIT>" , getFieldEditorParent ( ) ) ) ; } public void init ( IWorkbench workbench ) { } } </s>
|
<s> package org . codehaus . groovy . eclipse . codeassist . preferences ; import java . util . Set ; import org . codehaus . groovy . ast . MethodNode ; import org . codehaus . groovy . eclipse . codeassist . GroovyContentAssistActivator ; public class DGMProposalFilter { private Set < String > filteredDGMs ; public DGMProposalFilter ( ) { refreshFilter ( ) ; } public boolean isFiltered ( MethodNode proposal ) { return filteredDGMs . contains ( proposal . getName ( ) ) ; } public void refreshFilter ( ) { filteredDGMs = GroovyContentAssistActivator . getDefault ( ) . getFilteredDGMs ( ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . codeassist . requestor ; import static org . codehaus . groovy . eclipse . codeassist . requestor . ContentAssistLocation . CLASS_BODY ; import static org . codehaus . groovy . eclipse . codeassist . requestor . ContentAssistLocation . EXCEPTIONS ; import static org . codehaus . groovy . eclipse . codeassist . requestor . ContentAssistLocation . EXPRESSION ; import static org . codehaus . groovy . eclipse . codeassist . requestor . ContentAssistLocation . EXTENDS ; import static org . codehaus . groovy . eclipse . codeassist . requestor . ContentAssistLocation . IMPLEMENTS ; import static org . codehaus . groovy . eclipse . codeassist . requestor . ContentAssistLocation . IMPORT ; import static org . codehaus . groovy . eclipse . codeassist . requestor . ContentAssistLocation . PARAMETER ; import static org . codehaus . groovy . eclipse . codeassist . requestor . ContentAssistLocation . SCRIPT ; import static org . codehaus . groovy . eclipse . codeassist . requestor . ContentAssistLocation . STATEMENT ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Stack ; import org . codehaus . groovy . ast . ASTNode ; import org . codehaus . groovy . ast . AnnotatedNode ; import org . codehaus . groovy . ast . AnnotationNode ; import org . codehaus . groovy . ast . ClassCodeVisitorSupport ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . ConstructorNode ; import org . codehaus . groovy . ast . FieldNode ; import org . codehaus . groovy . ast . ImportNode ; import org . codehaus . groovy . ast . ImportNodeCompatibilityWrapper ; import org . codehaus . groovy . ast . InnerClassNode ; import org . codehaus . groovy . ast . MethodNode ; import org . codehaus . groovy . ast . ModuleNode ; import org . codehaus . groovy . ast . PackageNode ; import org . codehaus . groovy . ast . Parameter ; import org . codehaus . groovy . ast . expr . ArgumentListExpression ; import org . codehaus . groovy . ast . expr . ArrayExpression ; import org . codehaus . groovy . ast . expr . BinaryExpression ; import org . codehaus . groovy . ast . expr . CastExpression ; import org . codehaus . groovy . ast . expr . ClassExpression ; import org . codehaus . groovy . ast . expr . ClosureExpression ; import org . codehaus . groovy . ast . expr . ConstantExpression ; import org . codehaus . groovy . ast . expr . ConstructorCallExpression ; import org . codehaus . groovy . ast . expr . DeclarationExpression ; import org . codehaus . groovy . ast . expr . Expression ; import org . codehaus . groovy . ast . expr . FieldExpression ; import org . codehaus . groovy . ast . expr . ListExpression ; import org . codehaus . groovy . ast . expr . MapExpression ; import org . codehaus . groovy . ast . expr . MethodCallExpression ; import org . codehaus . groovy . ast . expr . PropertyExpression ; import org . codehaus . groovy . ast . expr . StaticMethodCallExpression ; import org . codehaus . groovy . ast . expr . TupleExpression ; import org . codehaus . groovy . ast . expr . VariableExpression ; import org . codehaus . groovy . ast . stmt . BlockStatement ; import org . codehaus . groovy . ast . stmt . CatchStatement ; import org . codehaus . groovy . ast . stmt . ExpressionStatement ; import org . codehaus . groovy . ast . stmt . ForStatement ; import org . codehaus . groovy . ast . stmt . Statement ; import org . codehaus . groovy . control . SourceUnit ; import org . codehaus . groovy . eclipse . core . util . VisitCompleteException ; import org . codehaus . groovy . runtime . GeneratedClosure ; import org . codehaus . jdt . groovy . model . GroovyCompilationUnit ; public class CompletionNodeFinder extends ClassCodeVisitorSupport { private Stack < ASTNode > blockStack ; private AnnotatedNode currentDeclaration ; private int completionOffset ; private int completionEnd ; private int supportingNodeEnd ; private String completionExpression ; private String fullCompletionExpression ; private GroovyCompilationUnit unit ; private ContentAssistContext context ; private Expression lhsNode ; private Stack < TupleExpression > argsStack ; public CompletionNodeFinder ( int completionOffset , int completionEnd , int supportingNodeEnd , String completionExpression , String fullCompletionExpression ) { this . completionOffset = completionOffset ; this . completionEnd = completionEnd ; this . supportingNodeEnd = supportingNodeEnd ; this . completionExpression = completionExpression ; this . fullCompletionExpression = fullCompletionExpression ; this . blockStack = new Stack < ASTNode > ( ) ; this . argsStack = new Stack < TupleExpression > ( ) ; } public ContentAssistContext findContentAssistContext ( GroovyCompilationUnit unit ) { try { this . unit = unit ; internalVisitModuleNode ( unit . getModuleNode ( ) ) ; } catch ( VisitCompleteException e ) { } return context ; } private void internalVisitModuleNode ( ModuleNode module ) { visitImports ( module ) ; ClassNode script = null ; for ( ClassNode clazz : ( Iterable < ClassNode > ) module . getClasses ( ) ) { if ( clazz . isScript ( ) ) { script = clazz ; } else { visitClass ( clazz ) ; } } if ( script != null ) { visitClass ( script ) ; } } @ Override public void visitImports ( ModuleNode node ) { PackageNode packageNode = node . getPackage ( ) ; if ( packageNode != null && doTest ( packageNode ) ) { currentDeclaration = packageNode ; createContext ( null , packageNode , ContentAssistLocation . PACKAGE ) ; } ImportNodeCompatibilityWrapper wrapper = new ImportNodeCompatibilityWrapper ( node ) ; for ( ImportNode importNode : wrapper . getAllImportNodes ( ) ) { visitAnnotations ( importNode ) ; if ( importNode . getType ( ) != null && doTest ( importNode . getType ( ) ) ) { currentDeclaration = importNode ; createContext ( null , importNode , IMPORT ) ; } } } @ Override public void visitClass ( ClassNode node ) { if ( ! doTest ( node ) && ! node . isScript ( ) ) { return ; } currentDeclaration = node ; blockStack . push ( node ) ; visitAnnotations ( node ) ; blockStack . pop ( ) ; ClassNode supr = node . getUnresolvedSuperClass ( ) ; if ( supr != null && supr . getEnd ( ) > <NUM_LIT:0> && doTest ( supr ) ) { createContext ( null , node , EXTENDS ) ; } Iterator < InnerClassNode > innerClasses = node . getInnerClasses ( ) ; if ( innerClasses != null ) { while ( innerClasses . hasNext ( ) ) { InnerClassNode inner = innerClasses . next ( ) ; if ( ! inner . isSynthetic ( ) || inner instanceof GeneratedClosure ) { this . visitClass ( inner ) ; } } } if ( node . getInterfaces ( ) != null ) { for ( ClassNode interf : node . getInterfaces ( ) ) { if ( doTest ( interf ) ) { createContext ( null , node , IMPLEMENTS ) ; } } } for ( FieldNode fn : node . getFields ( ) ) { visitField ( fn ) ; } for ( ConstructorNode cn : node . getDeclaredConstructors ( ) ) { visitConstructor ( cn ) ; } for ( MethodNode mn : node . getMethods ( ) ) { visitMethod ( mn ) ; } MethodNode clinit = node . getMethod ( "<STR_LIT>" , new Parameter [ <NUM_LIT:0> ] ) ; if ( clinit != null && clinit . getCode ( ) instanceof BlockStatement ) { blockStack . push ( clinit . getCode ( ) ) ; for ( Statement element : ( Iterable < Statement > ) ( ( BlockStatement ) clinit . getCode ( ) ) . getStatements ( ) ) { element . visit ( this ) ; } blockStack . pop ( ) ; } ConstructorNode init = findDefaultConstructor ( node ) ; if ( init != null ) { blockStack . push ( init . getCode ( ) ) ; for ( Statement element : ( Iterable < Statement > ) ( ( BlockStatement ) init . getCode ( ) ) . getStatements ( ) ) { element . visit ( this ) ; } blockStack . pop ( ) ; } currentDeclaration = node ; for ( Statement element : ( Iterable < Statement > ) node . getObjectInitializerStatements ( ) ) { element . visit ( this ) ; } if ( node . isScript ( ) ) { MethodNode run = node . getMethod ( "<STR_LIT>" , new Parameter [ <NUM_LIT:0> ] ) ; if ( run != null && run . getDeclaringClass ( ) . equals ( node ) ) { internalVisitConstructorOrMethod ( run ) ; } } createContext ( null , node , node . isScript ( ) ? SCRIPT : CLASS_BODY ) ; } @ Override protected void visitConstructorOrMethod ( MethodNode node , boolean isConstructor ) { if ( ! isRunMethod ( node ) ) { internalVisitConstructorOrMethod ( node ) ; } } @ Override public void visitAnnotations ( AnnotatedNode node ) { List < AnnotationNode > annotations = node . getAnnotations ( ) ; if ( annotations . isEmpty ( ) ) { return ; } for ( AnnotationNode an : annotations ) { if ( an . isBuiltIn ( ) ) { continue ; } for ( Map . Entry < String , Expression > member : an . getMembers ( ) . entrySet ( ) ) { member . getValue ( ) . visit ( this ) ; } if ( doTest ( an . getClassNode ( ) ) ) { createContext ( node , currentDeclaration , ContentAssistLocation . ANNOTATION ) ; } } } private boolean isRunMethod ( MethodNode node ) { return node . getDeclaringClass ( ) != null && node . getDeclaringClass ( ) . isScript ( ) && node . getName ( ) . equals ( "<STR_LIT>" ) && ( node . getParameters ( ) == null || node . getParameters ( ) . length == <NUM_LIT:0> ) && ( node . getReturnType ( ) != null && node . getReturnType ( ) . getName ( ) . equals ( "<STR_LIT>" ) ) ; } private void internalVisitConstructorOrMethod ( MethodNode node ) { if ( ! isRunMethod ( node ) ) { if ( ! doTest ( node ) ) { return ; } currentDeclaration = node ; } internalVisitParameters ( node . getParameters ( ) , node ) ; if ( node . getExceptions ( ) != null ) { for ( ClassNode excep : node . getExceptions ( ) ) { if ( doTest ( excep ) ) { createContext ( null , node , EXCEPTIONS ) ; } } } blockStack . push ( node ) ; visitAnnotations ( node ) ; blockStack . pop ( ) ; Statement code = node . getCode ( ) ; visitClassCodeContainer ( code ) ; if ( completionOffset < code . getStart ( ) && ! isRunMethod ( node ) ) { createContext ( null , node , PARAMETER ) ; } createContext ( code , code , expressionScriptOrStatement ( node ) ) ; } private ContentAssistLocation expressionScriptOrStatement ( MethodNode node ) { return isRunMethod ( node ) ? expressionOrScript ( ) : expressionOrStatement ( ) ; } private ContentAssistLocation expressionOrScript ( ) { return supportingNodeEnd == - <NUM_LIT:1> ? SCRIPT : EXPRESSION ; } private ContentAssistLocation expressionOrStatement ( ) { return supportingNodeEnd == - <NUM_LIT:1> ? STATEMENT : EXPRESSION ; } @ Override public void visitBlockStatement ( BlockStatement node ) { blockStack . push ( node ) ; super . visitBlockStatement ( node ) ; if ( doTest ( node ) ) { createContext ( blockStack . peek ( ) , node , expressionOrStatement ( ) ) ; } blockStack . pop ( ) ; } @ Override protected void visitStatement ( Statement statement ) { if ( doTest ( statement ) || ( statement . getStart ( ) <= <NUM_LIT:0> && statement . getEnd ( ) <= <NUM_LIT:0> ) ) { super . visitStatement ( statement ) ; } } @ Override public void visitExpressionStatement ( ExpressionStatement statement ) { super . visitExpressionStatement ( statement ) ; if ( doTest ( statement ) ) { Expression expression = statement . getExpression ( ) ; int exprEnd = expression . getEnd ( ) ; int stateEnd = statement . getEnd ( ) ; if ( ( completionOffset <= stateEnd && completionOffset > exprEnd ) || ( supportingNodeEnd <= stateEnd && supportingNodeEnd > exprEnd ) ) { if ( expression instanceof VariableExpression || expression instanceof ConstantExpression || expression instanceof PropertyExpression ) { if ( expression instanceof PropertyExpression ) { expression = getRightMost ( expression ) ; } if ( expression != null ) { createContextForCallContext ( expression , expression , expression . getText ( ) ) ; } } } } } private Expression getRightMost ( Expression expression ) { if ( expression instanceof VariableExpression || expression instanceof ConstantExpression ) { return expression ; } else if ( expression instanceof PropertyExpression ) { return getRightMost ( ( ( PropertyExpression ) expression ) . getProperty ( ) ) ; } else if ( expression instanceof BinaryExpression ) { return getRightMost ( ( ( BinaryExpression ) expression ) . getRightExpression ( ) ) ; } return null ; } @ Override public void visitField ( FieldNode node ) { if ( ! doTest ( node ) ) { return ; } currentDeclaration = node ; ClassNode type = node . getType ( ) ; if ( type != null && doTest ( type ) ) { createContext ( null , node . getDeclaringClass ( ) , CLASS_BODY ) ; } blockStack . push ( node ) ; super . visitField ( node ) ; blockStack . pop ( ) ; if ( node . isStatic ( ) && node . getEnd ( ) > node . getNameEnd ( ) + <NUM_LIT:1> ) { return ; } currentDeclaration = node . getDeclaringClass ( ) ; createContext ( node , node . getDeclaringClass ( ) , CLASS_BODY ) ; } @ Override public void visitVariableExpression ( VariableExpression expression ) { if ( doTest ( expression ) ) { createContext ( expression , blockStack . peek ( ) , expressionOrStatement ( ) ) ; } super . visitVariableExpression ( expression ) ; } @ Override public void visitFieldExpression ( FieldExpression expression ) { if ( doTest ( expression ) ) { createContext ( expression , blockStack . peek ( ) , expressionOrStatement ( ) ) ; } super . visitFieldExpression ( expression ) ; } @ Override public void visitClassExpression ( ClassExpression expression ) { if ( doTest ( expression ) ) { createContext ( expression , blockStack . peek ( ) , expressionOrStatement ( ) ) ; } super . visitClassExpression ( expression ) ; } @ Override public void visitConstantExpression ( ConstantExpression expression ) { if ( doTest ( expression ) ) { createContext ( expression , blockStack . peek ( ) , expressionOrStatement ( ) ) ; } super . visitConstantExpression ( expression ) ; } @ Override public void visitCastExpression ( CastExpression node ) { if ( doTest ( node . getType ( ) ) ) { createContext ( node . getType ( ) , blockStack . peek ( ) , expressionOrStatement ( ) ) ; } super . visitCastExpression ( node ) ; } @ Override public void visitDeclarationExpression ( DeclarationExpression expression ) { ClassNode type = expression . getLeftExpression ( ) . getType ( ) ; if ( doTest ( type ) ) { createContext ( type , blockStack . peek ( ) , expressionOrStatement ( ) ) ; } super . visitDeclarationExpression ( expression ) ; } @ Override public void visitCatchStatement ( CatchStatement statement ) { internalVisitParameter ( statement . getVariable ( ) , statement ) ; super . visitCatchStatement ( statement ) ; } @ Override public void visitForLoop ( ForStatement forLoop ) { internalVisitParameter ( forLoop . getVariable ( ) , forLoop ) ; super . visitForLoop ( forLoop ) ; } @ Override public void visitArrayExpression ( ArrayExpression expression ) { if ( doTest ( expression ) ) { createContext ( expression , blockStack . peek ( ) , expressionOrStatement ( ) ) ; } super . visitArrayExpression ( expression ) ; } @ Override public void visitStaticMethodCallExpression ( StaticMethodCallExpression call ) { if ( ! doTest ( call ) ) { return ; } if ( call . getOwnerType ( ) . getNameEnd ( ) == <NUM_LIT:0> && doTest ( call . getOwnerType ( ) ) ) { createContext ( call . getOwnerType ( ) , blockStack . peek ( ) , expressionOrStatement ( ) ) ; } internalVisitCallArguments ( call . getArguments ( ) ) ; if ( doTest ( call ) ) { createContext ( call , blockStack . peek ( ) , expressionOrStatement ( ) ) ; } } @ Override public void visitClosureExpression ( ClosureExpression expression ) { blockStack . push ( expression ) ; internalVisitParameters ( expression . getParameters ( ) , expression . getCode ( ) ) ; super . visitClosureExpression ( expression ) ; blockStack . pop ( ) ; if ( doTest ( expression ) ) { createContext ( expression , expression . getCode ( ) , expressionOrStatement ( ) ) ; } } @ Override public void visitBinaryExpression ( BinaryExpression expression ) { if ( expression . getOperation ( ) . getText ( ) . equals ( "<STR_LIT:=>" ) ) { lhsNode = expression . getLeftExpression ( ) ; } super . visitBinaryExpression ( expression ) ; lhsNode = null ; if ( expression . getOperation ( ) . getText ( ) . equals ( "<STR_LIT:[>" ) && doTest ( expression ) ) { createContext ( expression , blockStack . peek ( ) , expressionOrStatement ( ) ) ; } } @ Override public void visitPropertyExpression ( PropertyExpression expression ) { if ( ! doTest ( expression ) ) { return ; } Expression objectExpression = expression . getObjectExpression ( ) ; Expression propertyExpression = expression . getProperty ( ) ; if ( supportingNodeEnd >= <NUM_LIT:0> && supportingNodeEnd < propertyExpression . getStart ( ) ) { createContext ( objectExpression , blockStack . peek ( ) , EXPRESSION ) ; } checkForCommandExpression ( objectExpression , propertyExpression ) ; super . visitPropertyExpression ( expression ) ; } void checkForCommandExpression ( Expression leftExpression , Expression rightExpression ) { Expression leftMost = leftMost ( rightExpression ) ; if ( methodCallWithOneArgument ( leftExpression ) && leftMost instanceof ConstantExpression && doTest ( leftMost ) ) { createContext ( leftExpression , blockStack . peek ( ) , EXPRESSION ) ; } } boolean methodCallWithOneArgument ( Expression objectExpression ) { if ( objectExpression instanceof MethodCallExpression ) { Expression arguments = ( ( MethodCallExpression ) objectExpression ) . getArguments ( ) ; return arguments instanceof TupleExpression && ( ( TupleExpression ) arguments ) . getExpressions ( ) != null && ( ( TupleExpression ) arguments ) . getExpressions ( ) . size ( ) > <NUM_LIT:0> ; } else { return false ; } } private Expression leftMost ( Expression expr ) { if ( expr instanceof ConstantExpression ) { return expr ; } else if ( expr instanceof PropertyExpression ) { return leftMost ( ( ( PropertyExpression ) expr ) . getObjectExpression ( ) ) ; } else if ( expr instanceof MethodCallExpression ) { return leftMost ( ( ( MethodCallExpression ) expr ) . getObjectExpression ( ) ) ; } else if ( expr instanceof BinaryExpression ) { return leftMost ( ( ( BinaryExpression ) expr ) . getLeftExpression ( ) ) ; } else { return null ; } } @ Override public void visitMethodCallExpression ( MethodCallExpression call ) { if ( ! doTest ( call ) ) { return ; } Expression objectExpression = call . getObjectExpression ( ) ; Expression methodExpression = call . getMethod ( ) ; Expression arguments = call . getArguments ( ) ; checkForCommandExpression ( objectExpression , methodExpression ) ; checkForAfterClosingParen ( methodExpression , arguments ) ; objectExpression . visit ( this ) ; if ( supportingNodeEnd >= <NUM_LIT:0> && supportingNodeEnd < methodExpression . getStart ( ) ) { createContext ( objectExpression , blockStack . peek ( ) , EXPRESSION ) ; } methodExpression . visit ( this ) ; internalVisitCallArguments ( arguments ) ; createContextForCallContext ( call , methodExpression , methodExpression . getText ( ) ) ; } @ Override public void visitConstructorCallExpression ( ConstructorCallExpression call ) { if ( ! doTest ( call ) ) { return ; } Expression arguments = call . getArguments ( ) ; ClassNode constructorType = call . getType ( ) ; checkForAfterClosingParen ( call , arguments ) ; if ( doTest ( constructorType ) ) { createContext ( constructorType , blockStack . peek ( ) , ContentAssistLocation . CONSTRUCTOR ) ; } internalVisitCallArguments ( arguments ) ; String constructorName = constructorType . getNameWithoutPackage ( ) ; if ( constructorName . length ( ) < constructorType . getLength ( ) ) { constructorName = constructorType . getName ( ) ; } fullCompletionExpression = "<STR_LIT>" + constructorName ; createContextForCallContext ( call , constructorType , constructorName ) ; } private void checkForAfterClosingParen ( AnnotatedNode contextTarget , Expression arguments ) { int lastArgEnd = findLastArgumentEnd ( arguments ) ; int start = arguments . getStart ( ) ; if ( start == <NUM_LIT:0> && arguments instanceof TupleExpression && ( ( TupleExpression ) arguments ) . getExpressions ( ) . size ( ) > <NUM_LIT:0> ) { start = ( ( TupleExpression ) arguments ) . getExpression ( <NUM_LIT:0> ) . getStart ( ) ; } if ( start == <NUM_LIT:0> && lastArgEnd == <NUM_LIT:0> ) { return ; } boolean shouldLookAtArguments = ! ( lastArgEnd == start && completionOffset == start ) ; if ( shouldLookAtArguments ) { if ( after ( lastArgEnd ) ) { createContext ( contextTarget , blockStack . peek ( ) , expressionOrStatement ( ) ) ; } } else { } } @ Override public void visitArgumentlistExpression ( ArgumentListExpression ale ) { super . visitArgumentlistExpression ( ale ) ; } @ Override public void visitListExpression ( ListExpression expression ) { super . visitListExpression ( expression ) ; if ( doTest ( expression ) ) { createContext ( expression , currentDeclaration , EXPRESSION ) ; } } @ Override public void visitMapExpression ( MapExpression expression ) { super . visitMapExpression ( expression ) ; if ( doTest ( expression ) ) { if ( ! isArgument ( expression ) ) { createContext ( expression , currentDeclaration , EXPRESSION ) ; } else { } } } private boolean isArgument ( Expression expression ) { if ( argsStack . isEmpty ( ) ) { return false ; } TupleExpression args = argsStack . peek ( ) ; if ( args . getExpressions ( ) != null ) { for ( Expression arg : args . getExpressions ( ) ) { if ( arg == expression ) { return true ; } } } return false ; } private int findLastArgumentEnd ( Expression args ) { int listEnd = args . getEnd ( ) ; int lastExpressionEnd = - <NUM_LIT:1> ; if ( args instanceof TupleExpression ) { TupleExpression list = ( TupleExpression ) args ; int numExprs = list . getExpressions ( ) . size ( ) ; if ( numExprs > <NUM_LIT:0> ) { if ( listEnd == <NUM_LIT:0> ) { listEnd = list . getExpression ( numExprs - <NUM_LIT:1> ) . getEnd ( ) ; } Expression lastExpression = list . getExpression ( numExprs - <NUM_LIT:1> ) ; lastExpressionEnd = lastExpression . getEnd ( ) ; } } return Math . max ( listEnd , lastExpressionEnd ) ; } private boolean after ( int callEnd ) { return ( supportingNodeEnd == - <NUM_LIT:1> && callEnd < completionOffset ) || callEnd <= supportingNodeEnd ; } private void internalVisitCallArguments ( Expression arguments ) { boolean doContext = false ; if ( arguments instanceof TupleExpression ) { TupleExpression tuple = ( TupleExpression ) arguments ; for ( Expression expr : tuple . getExpressions ( ) ) { if ( expr . getStart ( ) == completionOffset ) { doContext = true ; break ; } } argsStack . push ( tuple ) ; } else if ( arguments != null ) { if ( arguments . getStart ( ) == completionOffset ) { doContext = true ; } } if ( ! doContext ) { arguments . visit ( this ) ; } if ( arguments instanceof TupleExpression ) { argsStack . pop ( ) ; } } private void internalVisitParameters ( Parameter [ ] ps , ASTNode declaringNode ) { if ( ps != null ) { for ( Parameter p : ps ) { internalVisitParameter ( p , declaringNode ) ; } } } private void internalVisitParameter ( Parameter p , ASTNode declaringNode ) { if ( doTest ( p . getType ( ) ) ) { createContext ( null , declaringNode , PARAMETER ) ; } ClassNode componentType = p . getType ( ) . getComponentType ( ) ; if ( componentType != null && doTest ( componentType ) ) { createContext ( null , declaringNode , PARAMETER ) ; } Expression initialExpression = p . getInitialExpression ( ) ; if ( initialExpression != null && doTest ( initialExpression ) ) { initialExpression . visit ( this ) ; } if ( p . getNameStart ( ) < completionOffset && p . getNameEnd ( ) >= completionOffset ) { createContext ( null , declaringNode , PARAMETER ) ; } if ( doTest ( p ) ) { createContext ( p , declaringNode , expressionOrStatement ( ) ) ; } } private ConstructorNode findDefaultConstructor ( ClassNode node ) { List < ConstructorNode > constructors = node . getDeclaredConstructors ( ) ; for ( ConstructorNode constructor : constructors ) { if ( constructor . getParameters ( ) == null || constructor . getParameters ( ) . length == <NUM_LIT:0> ) { if ( constructor . getEnd ( ) <= <NUM_LIT:0> ) { return constructor ; } } } return null ; } private void createContextForCallContext ( Expression origExpression , AnnotatedNode methodExpr , String methodName ) { context = new MethodInfoContentAssistContext ( completionOffset , completionExpression , fullCompletionExpression , origExpression , blockStack . peek ( ) , lhsNode , unit , currentDeclaration , completionEnd , methodExpr , methodName , methodExpr . getEnd ( ) ) ; throw new VisitCompleteException ( ) ; } private void createContext ( ASTNode completionNode , ASTNode declaringNode , ContentAssistLocation location ) { context = new ContentAssistContext ( completionOffset , completionExpression , fullCompletionExpression , completionNode , declaringNode , lhsNode , location , unit , currentDeclaration , completionEnd ) ; throw new VisitCompleteException ( ) ; } protected boolean doTest ( ASTNode node ) { return node . getEnd ( ) > <NUM_LIT:0> && ( ( supportingNodeEnd > node . getStart ( ) && supportingNodeEnd <= node . getEnd ( ) ) || ( completionOffset > node . getStart ( ) && completionOffset <= node . getEnd ( ) ) ) ; } public ContentAssistContext getContext ( ) { return context ; } @ Override protected SourceUnit getSourceUnit ( ) { return null ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . codeassist . requestor ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . codehaus . groovy . eclipse . GroovyLogManager ; import org . codehaus . groovy . eclipse . TraceCategory ; import org . codehaus . groovy . eclipse . codeassist . DocumentSourceBuffer ; import org . codehaus . groovy . eclipse . codeassist . factories . ConstructorCompletionProcessorFactory ; import org . codehaus . groovy . eclipse . codeassist . factories . ExpressionCompletionProcessorFactory ; import org . codehaus . groovy . eclipse . codeassist . factories . IGroovyCompletionProcessorFactory ; import org . codehaus . groovy . eclipse . codeassist . factories . LocalVariableCompletionProcessorFactory ; import org . codehaus . groovy . eclipse . codeassist . factories . ModifiersCompletionProcessorFactory ; import org . codehaus . groovy . eclipse . codeassist . factories . NewFieldCompletionProcessorFactory ; import org . codehaus . groovy . eclipse . codeassist . factories . NewMethodCompletionProcessorFactory ; import org . codehaus . groovy . eclipse . codeassist . factories . NewVariableCompletionProcessorFactory ; import org . codehaus . groovy . eclipse . codeassist . factories . PackageCompletionProcessorFactory ; import org . codehaus . groovy . eclipse . codeassist . factories . TypeCompletionProcessorFactory ; import org . codehaus . groovy . eclipse . codeassist . processors . IGroovyCompletionProcessor ; import org . codehaus . groovy . eclipse . codeassist . processors . IProposalFilter ; import org . codehaus . groovy . eclipse . codeassist . processors . IProposalFilterExtension ; import org . codehaus . groovy . eclipse . codeassist . processors . ProposalProviderRegistry ; import org . codehaus . groovy . eclipse . core . GroovyCore ; import org . codehaus . groovy . eclipse . core . ISourceBuffer ; import org . codehaus . groovy . eclipse . core . util . ExpressionFinder ; import org . codehaus . groovy . eclipse . core . util . ParseException ; import org . codehaus . jdt . groovy . model . GroovyCompilationUnit ; import org . codehaus . jdt . groovy . model . ModuleNodeMapper . ModuleNodeInfo ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jdt . core . ICompilationUnit ; import org . eclipse . jdt . core . JavaModelException ; import org . eclipse . jdt . groovy . search . ITypeResolver ; import org . eclipse . jdt . internal . core . JavaProject ; import org . eclipse . jdt . internal . core . SearchableEnvironment ; import org . eclipse . jdt . ui . text . java . ContentAssistInvocationContext ; import org . eclipse . jdt . ui . text . java . IJavaCompletionProposalComputer ; import org . eclipse . jdt . ui . text . java . JavaContentAssistInvocationContext ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . contentassist . ICompletionProposal ; import org . eclipse . jface . text . contentassist . IContextInformation ; public class GroovyCompletionProposalComputer implements IJavaCompletionProposalComputer { private static Map < ContentAssistLocation , List < IGroovyCompletionProcessorFactory > > locationFactoryMap ; static { locationFactoryMap = new HashMap < ContentAssistLocation , List < IGroovyCompletionProcessorFactory > > ( ) ; List < IGroovyCompletionProcessorFactory > factories = new ArrayList < IGroovyCompletionProcessorFactory > ( <NUM_LIT:1> ) ; factories = new ArrayList < IGroovyCompletionProcessorFactory > ( <NUM_LIT:5> ) ; factories . add ( new ModifiersCompletionProcessorFactory ( ) ) ; factories . add ( new NewMethodCompletionProcessorFactory ( ) ) ; factories . add ( new NewFieldCompletionProcessorFactory ( ) ) ; factories . add ( new TypeCompletionProcessorFactory ( ) ) ; factories . add ( new PackageCompletionProcessorFactory ( ) ) ; factories . add ( new NewVariableCompletionProcessorFactory ( ) ) ; locationFactoryMap . put ( ContentAssistLocation . CLASS_BODY , factories ) ; factories = new ArrayList < IGroovyCompletionProcessorFactory > ( <NUM_LIT:3> ) ; factories . add ( new TypeCompletionProcessorFactory ( ) ) ; factories . add ( new PackageCompletionProcessorFactory ( ) ) ; factories . add ( new ConstructorCompletionProcessorFactory ( ) ) ; locationFactoryMap . put ( ContentAssistLocation . EXCEPTIONS , factories ) ; locationFactoryMap . put ( ContentAssistLocation . EXTENDS , factories ) ; locationFactoryMap . put ( ContentAssistLocation . IMPLEMENTS , factories ) ; locationFactoryMap . put ( ContentAssistLocation . ANNOTATION , factories ) ; locationFactoryMap . put ( ContentAssistLocation . IMPORT , factories ) ; locationFactoryMap . put ( ContentAssistLocation . CONSTRUCTOR , factories ) ; locationFactoryMap . put ( ContentAssistLocation . PARAMETER , factories ) ; factories = new ArrayList < IGroovyCompletionProcessorFactory > ( <NUM_LIT:3> ) ; factories . add ( new PackageCompletionProcessorFactory ( ) ) ; locationFactoryMap . put ( ContentAssistLocation . PACKAGE , factories ) ; factories = new ArrayList < IGroovyCompletionProcessorFactory > ( <NUM_LIT:2> ) ; factories . add ( new ExpressionCompletionProcessorFactory ( ) ) ; factories . add ( new PackageCompletionProcessorFactory ( ) ) ; locationFactoryMap . put ( ContentAssistLocation . EXPRESSION , factories ) ; factories = new ArrayList < IGroovyCompletionProcessorFactory > ( <NUM_LIT:5> ) ; factories . add ( new TypeCompletionProcessorFactory ( ) ) ; factories . add ( new ExpressionCompletionProcessorFactory ( ) ) ; factories . add ( new LocalVariableCompletionProcessorFactory ( ) ) ; factories . add ( new PackageCompletionProcessorFactory ( ) ) ; factories . add ( new NewVariableCompletionProcessorFactory ( ) ) ; locationFactoryMap . put ( ContentAssistLocation . STATEMENT , factories ) ; factories = new ArrayList < IGroovyCompletionProcessorFactory > ( <NUM_LIT:8> ) ; factories . add ( new ModifiersCompletionProcessorFactory ( ) ) ; factories . add ( new NewMethodCompletionProcessorFactory ( ) ) ; factories . add ( new NewFieldCompletionProcessorFactory ( ) ) ; factories . add ( new TypeCompletionProcessorFactory ( ) ) ; factories . add ( new ExpressionCompletionProcessorFactory ( ) ) ; factories . add ( new LocalVariableCompletionProcessorFactory ( ) ) ; factories . add ( new PackageCompletionProcessorFactory ( ) ) ; factories . add ( new NewVariableCompletionProcessorFactory ( ) ) ; locationFactoryMap . put ( ContentAssistLocation . SCRIPT , factories ) ; factories = new ArrayList < IGroovyCompletionProcessorFactory > ( <NUM_LIT:2> ) ; factories . add ( new ExpressionCompletionProcessorFactory ( ) ) ; factories . add ( new ConstructorCompletionProcessorFactory ( ) ) ; locationFactoryMap . put ( ContentAssistLocation . METHOD_CONTEXT , factories ) ; } public GroovyCompletionProposalComputer ( ) { } public List < ICompletionProposal > computeCompletionProposals ( ContentAssistInvocationContext context , IProgressMonitor monitor ) { if ( ! ( context instanceof JavaContentAssistInvocationContext ) ) { return Collections . EMPTY_LIST ; } JavaContentAssistInvocationContext javaContext = ( JavaContentAssistInvocationContext ) context ; ICompilationUnit unit = javaContext . getCompilationUnit ( ) ; if ( ! ( unit instanceof GroovyCompilationUnit ) ) { return Collections . EMPTY_LIST ; } String event = null ; if ( GroovyLogManager . manager . hasLoggers ( ) ) { GroovyLogManager . manager . log ( TraceCategory . CONTENT_ASSIST , "<STR_LIT>" + unit . getElementName ( ) ) ; event = "<STR_LIT>" + unit . getElementName ( ) ; GroovyLogManager . manager . logStart ( event ) ; } GroovyCompilationUnit gunit = ( GroovyCompilationUnit ) unit ; ModuleNodeInfo moduleInfo = gunit . getModuleInfo ( true ) ; if ( moduleInfo == null ) { if ( GroovyLogManager . manager . hasLoggers ( ) ) { GroovyLogManager . manager . log ( TraceCategory . CONTENT_ASSIST , "<STR_LIT>" + gunit . getElementName ( ) ) ; } return Collections . EMPTY_LIST ; } IDocument document = context . getDocument ( ) ; ContentAssistContext assistContext = createContentAssistContext ( gunit , context . getInvocationOffset ( ) , document ) ; List < ICompletionProposal > proposals = new ArrayList < ICompletionProposal > ( ) ; if ( assistContext != null ) { List < IGroovyCompletionProcessorFactory > factories = locationFactoryMap . get ( assistContext . location ) ; if ( factories != null ) { SearchableEnvironment nameEnvironment = createSearchableEnvironment ( javaContext ) ; try { for ( IGroovyCompletionProcessorFactory factory : factories ) { IGroovyCompletionProcessor processor = factory . createProcessor ( assistContext , javaContext , nameEnvironment ) ; if ( processor != null ) { if ( processor instanceof ITypeResolver ) { ( ( ITypeResolver ) processor ) . setResolverInformation ( moduleInfo . module , moduleInfo . resolver ) ; } proposals . addAll ( processor . generateProposals ( monitor ) ) ; } } } finally { if ( nameEnvironment != null ) { nameEnvironment . cleanup ( ) ; } } } try { List < IProposalFilter > filters = ProposalProviderRegistry . getRegistry ( ) . getFiltersFor ( assistContext . unit ) ; for ( IProposalFilter filter : filters ) { try { if ( filter instanceof IProposalFilterExtension ) { List < ICompletionProposal > newProposals = ( ( IProposalFilterExtension ) filter ) . filterExtendedProposals ( proposals , assistContext , javaContext ) ; proposals = newProposals == null ? proposals : newProposals ; } } catch ( Exception e ) { GroovyCore . logException ( "<STR_LIT>" + filter . getClass ( ) . getCanonicalName ( ) , e ) ; } } } catch ( CoreException e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; } } if ( event != null ) { GroovyLogManager . manager . logEnd ( event , TraceCategory . CONTENT_ASSIST ) ; } return proposals ; } public ContentAssistContext createContentAssistContext ( GroovyCompilationUnit gunit , int invocationOffset , IDocument document ) { String fullCompletionText = findCompletionText ( document , invocationOffset ) ; String [ ] completionExpressions = findCompletionExpression ( fullCompletionText ) ; if ( completionExpressions == null ) { completionExpressions = new String [ ] { "<STR_LIT>" , "<STR_LIT>" } ; } String completionExpression = completionExpressions [ <NUM_LIT:1> ] == null ? completionExpressions [ <NUM_LIT:0> ] : completionExpressions [ <NUM_LIT:1> ] ; int supportingNodeEnd = findSupportingNodeEnd ( invocationOffset , fullCompletionText ) ; int completionEnd = findCompletionEnd ( document , invocationOffset ) ; CompletionNodeFinder finder = new CompletionNodeFinder ( invocationOffset , completionEnd , supportingNodeEnd , completionExpression , fullCompletionText ) ; ContentAssistContext assistContext = finder . findContentAssistContext ( gunit ) ; return assistContext ; } private int findSupportingNodeEnd ( int invocationOffset , String fullCompletionText ) { String [ ] completionExpressions = new ExpressionFinder ( ) . splitForCompletionNoTrim ( fullCompletionText ) ; return completionExpressions [ <NUM_LIT:1> ] == null ? - <NUM_LIT:1> : invocationOffset - fullCompletionText . length ( ) + completionExpressions [ <NUM_LIT:0> ] . length ( ) ; } private SearchableEnvironment createSearchableEnvironment ( JavaContentAssistInvocationContext javaContext ) { try { return ( ( JavaProject ) javaContext . getProject ( ) ) . newSearchableNameEnvironment ( javaContext . getCompilationUnit ( ) . getOwner ( ) ) ; } catch ( JavaModelException e ) { GroovyCore . logException ( "<STR_LIT>" + javaContext . getCompilationUnit ( ) , e ) ; return null ; } } private String [ ] findCompletionExpression ( String completionText ) { return new ExpressionFinder ( ) . splitForCompletion ( completionText ) ; } protected String findCompletionText ( IDocument doc , int offset ) { try { if ( offset > <NUM_LIT:0> ) { ISourceBuffer buffer = new DocumentSourceBuffer ( doc ) ; return new ExpressionFinder ( ) . findForCompletions ( buffer , offset - <NUM_LIT:1> ) ; } } catch ( ParseException e ) { GroovyCore . trace ( "<STR_LIT>" + e . getMessage ( ) ) ; } return "<STR_LIT>" ; } private int findCompletionEnd ( IDocument doc , int offset ) { ISourceBuffer buffer = new DocumentSourceBuffer ( doc ) ; return new ExpressionFinder ( ) . findTokenEnd ( buffer , offset ) ; } public List < IContextInformation > computeContextInformation ( ContentAssistInvocationContext context , IProgressMonitor monitor ) { List < ICompletionProposal > proposals = computeCompletionProposals ( context , monitor ) ; ArrayList < IContextInformation > contexts = new ArrayList < IContextInformation > ( proposals . size ( ) ) ; for ( ICompletionProposal proposal : proposals ) { if ( proposal . getContextInformation ( ) != null ) { contexts . add ( proposal . getContextInformation ( ) ) ; } } return contexts ; } public String getErrorMessage ( ) { return "<STR_LIT>" ; } public void sessionEnded ( ) { } public void sessionStarted ( ) { } } </s>
|
<s> package org . codehaus . groovy . eclipse . codeassist . requestor ; import org . codehaus . groovy . ast . ASTNode ; import org . codehaus . groovy . ast . AnnotatedNode ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . expr . Expression ; import org . codehaus . groovy . eclipse . core . GroovyCore ; import org . codehaus . jdt . groovy . model . GroovyCompilationUnit ; import org . eclipse . jdt . core . IJavaElement ; import org . eclipse . jdt . core . IType ; import org . eclipse . jdt . core . JavaModelException ; import org . eclipse . jdt . groovy . search . TypeInferencingVisitorWithRequestor ; import org . eclipse . jdt . groovy . search . VariableScope ; public class ContentAssistContext { public final int completionLocation ; public final int completionEnd ; public final String completionExpression ; public final String fullCompletionExpression ; public final ASTNode completionNode ; public final ASTNode containingCodeBlock ; public final Expression lhsNode ; public final ContentAssistLocation location ; public final GroovyCompilationUnit unit ; public final AnnotatedNode containingDeclaration ; public VariableScope currentScope ; public ContentAssistContext ( int completionLocation , String completionExpression , String fullCompletionExpression , ASTNode completionNode , ASTNode containingCodeBlock , Expression lhsNode , ContentAssistLocation location , GroovyCompilationUnit unit , AnnotatedNode containingDeclaration , int completionEnd ) { this . completionLocation = completionLocation ; this . completionExpression = completionExpression ; this . fullCompletionExpression = fullCompletionExpression ; this . completionNode = completionNode ; this . containingCodeBlock = containingCodeBlock ; this . lhsNode = lhsNode ; this . location = location ; this . unit = unit ; this . containingDeclaration = containingDeclaration ; this . completionEnd = completionEnd ; } public IType getEnclosingType ( ) { try { IJavaElement element = unit . getElementAt ( completionLocation ) ; if ( element != null ) { return ( IType ) element . getAncestor ( IJavaElement . TYPE ) ; } } catch ( JavaModelException e ) { GroovyCore . logException ( "<STR_LIT>" + unit , e ) ; } return null ; } public ClassNode getEnclosingGroovyType ( ) { if ( containingDeclaration instanceof ClassNode ) { return ( ClassNode ) containingDeclaration ; } else { return containingDeclaration . getDeclaringClass ( ) ; } } public ASTNode getPerceivedCompletionNode ( ) { return completionNode ; } public String getPerceivedCompletionExpression ( ) { return completionExpression ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . codeassist . requestor ; public enum ContentAssistLocation { ANNOTATION , IMPORT , PACKAGE , PARAMETER , IMPLEMENTS , EXTENDS , EXCEPTIONS , EXPRESSION , CONSTRUCTOR , STATEMENT , CLASS_BODY , SCRIPT , METHOD_CONTEXT } </s>
|
<s> package org . codehaus . groovy . eclipse . codeassist . requestor ; import org . codehaus . groovy . ast . ASTNode ; import org . codehaus . groovy . ast . AnnotatedNode ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . expr . ConstructorCallExpression ; import org . codehaus . groovy . ast . expr . Expression ; import org . codehaus . jdt . groovy . model . GroovyCompilationUnit ; public class MethodInfoContentAssistContext extends ContentAssistContext { public final int methodNameEnd ; public final AnnotatedNode methodExpression ; public final String methodName ; public MethodInfoContentAssistContext ( int completionLocation , String completionExpression , String fullCompletionExpression , ASTNode completionNode , ASTNode containingCodeBlock , Expression lhsNode , GroovyCompilationUnit unit , AnnotatedNode containingDeclaration , int completionEnd , AnnotatedNode methodExpression , String methodName , int methodNameEnd ) { super ( completionLocation , completionExpression , fullCompletionExpression , completionNode , containingCodeBlock , lhsNode , ContentAssistLocation . METHOD_CONTEXT , unit , containingDeclaration , completionEnd ) ; this . methodNameEnd = methodNameEnd ; this . methodExpression = methodExpression ; this . methodName = methodName ; } @ Override public ASTNode getPerceivedCompletionNode ( ) { return methodExpression ; } @ Override public String getPerceivedCompletionExpression ( ) { return methodName ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring ; import org . eclipse . jdt . core . formatter . DefaultCodeFormatterConstants ; public class PreferenceConstants { public static final int SAME_LINE = <NUM_LIT:0> ; public static final int NEXT_LINE = <NUM_LIT:1> ; public static final String SAME = "<STR_LIT>" ; public static final String NEXT = "<STR_LIT>" ; public static final int DEFAULT_MAX_LINE_LEN = <NUM_LIT> ; public static final int DEFAULT_BRACES_START = SAME_LINE ; public static final int DEFAULT_BRACES_END = NEXT_LINE ; public static final boolean DEFAULT_USE_TABS = true ; public static final int DEFAULT_TAB_SIZE = <NUM_LIT:4> ; public static final int DEFAULT_INDENT_SIZE = <NUM_LIT:4> ; public static final int DEFAULT_INDENT_MULTILINE = <NUM_LIT:2> ; public static final boolean DEFAULT_SMART_PASTE = true ; public static final boolean DEFAULT_INDENT_EMPTY_LINES = false ; public static final boolean DEFAULT_REMOVE_UNNECESSARY_SEMICOLONS = false ; public static final int DEFAULT_LONG_LIST_LENGTH = <NUM_LIT:30> ; public static final String P_PATH = "<STR_LIT>" ; public static final String GROOVY_FORMATTER_INDENTATION = DefaultCodeFormatterConstants . FORMATTER_TAB_CHAR ; public static final String GROOVY_FORMATTER_INDENTATION_SIZE = DefaultCodeFormatterConstants . FORMATTER_INDENTATION_SIZE ; public static final String GROOVY_FORMATTER_TAB_SIZE = DefaultCodeFormatterConstants . FORMATTER_TAB_SIZE ; public static final String GROOVY_FORMATTER_MULTILINE_INDENTATION = "<STR_LIT>" ; public static final String GROOVY_FORMATTER_BRACES_START = "<STR_LIT>" ; public static final String GROOVY_FORMATTER_BRACES_END = "<STR_LIT>" ; public static final String GROOVY_FORMATTER_MAX_LINELENGTH = "<STR_LIT>" ; public static final String GROOVY_FORMATTER_LONG_LIST_LENGTH = "<STR_LIT>" ; public static final String GROOVY_FORMATTER_REMOVE_UNNECESSARY_SEMICOLONS = "<STR_LIT>" ; public static final String GROOVY_SAVE_ACTION_REMOVE_UNNECESSARY_SEMICOLONS = "<STR_LIT>" ; } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring ; import org . codehaus . groovy . eclipse . refactoring . core . rename . RefactoringSearchScopeExpander ; import org . codehaus . jdt . groovy . integration . internal . GroovyLanguageSupport ; import org . eclipse . jface . resource . ImageDescriptor ; import org . eclipse . ui . plugin . AbstractUIPlugin ; import org . osgi . framework . BundleContext ; public class Activator extends AbstractUIPlugin { public static final String PLUGIN_ID = "<STR_LIT>" ; private static Activator plugin ; public Activator ( ) { } @ Override public void start ( BundleContext context ) throws Exception { super . start ( context ) ; plugin = this ; GroovyLanguageSupport . searchScopeExpander = new RefactoringSearchScopeExpander ( ) ; } @ Override public void stop ( BundleContext context ) throws Exception { plugin = null ; super . stop ( context ) ; } public static Activator getDefault ( ) { return plugin ; } public static ImageDescriptor getImageDescriptor ( String path ) { return imageDescriptorFromPlugin ( PLUGIN_ID , path ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . ui . extract ; import java . text . MessageFormat ; import java . util . HashMap ; import java . util . HashSet ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import java . util . Observable ; import java . util . Observer ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . Parameter ; import org . codehaus . groovy . eclipse . refactoring . core . extract . ExtractGroovyMethodRefactoring ; import org . codehaus . groovy . eclipse . refactoring . core . utils . GroovyConventionsBuilder ; import org . codehaus . groovy . eclipse . refactoring . core . utils . StatusHelper ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . jdt . core . Signature ; import org . eclipse . ltk . core . refactoring . RefactoringStatus ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . TableEditor ; import org . eclipse . swt . events . KeyAdapter ; import org . eclipse . swt . events . KeyEvent ; import org . eclipse . swt . events . ModifyEvent ; import org . eclipse . swt . events . ModifyListener ; import org . eclipse . swt . events . MouseAdapter ; import org . eclipse . swt . events . MouseEvent ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Table ; import org . eclipse . swt . widgets . TableColumn ; import org . eclipse . swt . widgets . TableItem ; import org . eclipse . swt . widgets . Text ; import org . objectweb . asm . Opcodes ; public class ExtractMethodPageContent extends Composite implements Observer { private final ExtractGroovyMethodRefactoring extractMethodRefactoring ; private final ExtractMethodPage extractMethodPage ; private Text txtNewMethodName ; private Text txtPreviewCall ; private Table tblParameters ; private static final String MODIFIER_DEF = "<STR_LIT>" ; private static final String MODIFIER_PROTECTED = "<STR_LIT>" ; private static final String MODIFIER_PRIVATE = "<STR_LIT>" ; private static final String MODIFIER_NONE = "<STR_LIT:none>" ; private final String [ ] possibleModifiers = { MODIFIER_DEF , MODIFIER_PROTECTED , MODIFIER_PRIVATE , MODIFIER_NONE } ; private static final int DEFAULT_MODIFIER = <NUM_LIT:2> ; private Composite accessModifierComposite ; private Composite newMethodNameComposite ; private Composite parameterComposite ; private Composite previewComposite ; private Button btnDown ; private Button btnUp ; private TableEditor editor ; private final Map < String , String > renameVariablesMap = new HashMap < String , String > ( ) ; private boolean firstPreviewEver = true ; public ExtractMethodPageContent ( Composite parent , ExtractGroovyMethodRefactoring refactoring , ExtractMethodPage extractMethodPage ) { super ( parent , SWT . NONE ) ; this . extractMethodRefactoring = refactoring ; this . extractMethodPage = extractMethodPage ; if ( refactoring != null ) { refactoring . addObserver ( this ) ; } setLayout ( new GridLayout ( ) ) ; GridData compositeLData = new GridData ( ) ; compositeLData . horizontalAlignment = GridData . FILL ; compositeLData . grabExcessHorizontalSpace = true ; setLayoutData ( compositeLData ) ; createNewMethodNameComposite ( this ) ; createAccessModifierComposite ( this ) ; createParameterComposite ( this ) ; createPreviewComposite ( this ) ; initializeValues ( - <NUM_LIT:1> ) ; layout ( ) ; } private void initializeValues ( int selectionIndex ) { if ( extractMethodRefactoring != null ) { setModifier ( ) ; if ( extractMethodRefactoring . getCallAndMethHeadParameters ( ) . length > <NUM_LIT:0> ) { tblParameters . removeAll ( ) ; for ( Parameter param : extractMethodRefactoring . getCallAndMethHeadParameters ( ) ) { TableItem tblItem = new TableItem ( tblParameters , SWT . NONE ) ; tblItem . setText ( <NUM_LIT:0> , createSimpleTypeName ( param . getType ( ) ) ) ; setVariableNameInTable ( param , tblItem ) ; } tblParameters . setSelection ( selectionIndex ) ; updateButtonsEnabled ( tblParameters ) ; } updateView ( ) ; } } private String createSimpleTypeName ( ClassNode node ) { String name = node . getName ( ) ; if ( name . startsWith ( "<STR_LIT:[>" ) ) { int arrayCount = Signature . getArrayCount ( name ) ; String noArrayName = Signature . getElementType ( name ) ; String simpleName = Signature . getSignatureSimpleName ( noArrayName ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( simpleName ) ; for ( int i = <NUM_LIT:0> ; i < arrayCount ; i ++ ) { sb . append ( "<STR_LIT:[]>" ) ; } return sb . toString ( ) ; } else { return node . getNameWithoutPackage ( ) ; } } private void setVariableNameInTable ( Parameter param , TableItem tblItem ) { String variableName = param . getName ( ) ; if ( renameVariablesMap . containsKey ( variableName ) ) tblItem . setText ( <NUM_LIT:1> , renameVariablesMap . get ( variableName ) ) ; else tblItem . setText ( <NUM_LIT:1> , variableName ) ; } private void updateView ( ) { String methodHead = extractMethodRefactoring . getMethodHead ( ) ; if ( firstPreviewEver ) { createDummyMethodHead ( methodHead ) ; } else { txtPreviewCall . setText ( methodHead ) ; } RefactoringStatus status = validateGroovyIdentifiers ( ) ; checkForDuplicateVariableNames ( status ) ; extractMethodPage . setPageComplete ( status ) ; } private void checkForDuplicateVariableNames ( RefactoringStatus status ) { HashSet < String > uniquenessTestSet = new HashSet < String > ( ) ; for ( Parameter p : extractMethodRefactoring . getCallAndMethHeadParameters ( ) ) { if ( ! uniquenessTestSet . add ( p . getName ( ) ) ) { String errorMsg = MessageFormat . format ( GroovyRefactoringMessages . ExtractMethodWizard_DuplicateVariableName , p . getName ( ) ) ; status . addFatalError ( errorMsg ) ; } } } private void createDummyMethodHead ( String methodHead ) { String dummyMethodName = GroovyRefactoringMessages . ExtractMethodWizard_DefaultMethodName ; int paraStartPos = methodHead . indexOf ( '<CHAR_LIT:(>' ) ; String partOne = methodHead . substring ( <NUM_LIT:0> , paraStartPos ) ; String partTwo = methodHead . substring ( paraStartPos , methodHead . length ( ) ) ; txtPreviewCall . setText ( partOne + dummyMethodName + partTwo ) ; } private RefactoringStatus validateGroovyIdentifiers ( ) { List < String > variablesToCheck = new LinkedList < String > ( ) ; variablesToCheck . add ( txtNewMethodName . getText ( ) ) ; for ( Parameter p : extractMethodRefactoring . getCallAndMethHeadParameters ( ) ) { variablesToCheck . add ( p . getName ( ) ) ; } IStatus statusOfUsedGroovyIdentifiers = new GroovyConventionsBuilder ( variablesToCheck , GroovyConventionsBuilder . METHOD ) . validateGroovyIdentifier ( ) . validateLowerCase ( IStatus . WARNING ) . done ( ) ; return StatusHelper . convertStatus ( statusOfUsedGroovyIdentifiers ) ; } private void setModifier ( ) { extractMethodRefactoring . setModifier ( DEFAULT_MODIFIER ) ; } private void setModifier ( MouseEvent e ) { if ( e . getSource ( ) instanceof Button ) { Button selectedButton = ( Button ) e . getSource ( ) ; if ( selectedButton . getText ( ) . equals ( MODIFIER_PRIVATE ) ) extractMethodRefactoring . setModifier ( Opcodes . ACC_PRIVATE ) ; else if ( selectedButton . getText ( ) . equals ( MODIFIER_DEF ) ) extractMethodRefactoring . setModifier ( Opcodes . ACC_PUBLIC ) ; else if ( selectedButton . getText ( ) . equals ( MODIFIER_PROTECTED ) ) extractMethodRefactoring . setModifier ( Opcodes . ACC_PROTECTED ) ; else if ( selectedButton . getText ( ) . equals ( MODIFIER_NONE ) ) extractMethodRefactoring . setModifier ( <NUM_LIT:0> ) ; } } public void update ( Observable o , Object arg ) { updateView ( ) ; } private void createAccessModifierComposite ( Composite parent ) { accessModifierComposite = new Composite ( parent , SWT . NONE ) ; GridLayout gridLayout = new GridLayout ( ) ; gridLayout . numColumns = <NUM_LIT:6> ; gridLayout . marginHeight = <NUM_LIT:0> ; GridData compositeLData = new GridData ( ) ; compositeLData . horizontalAlignment = GridData . FILL ; compositeLData . grabExcessHorizontalSpace = true ; accessModifierComposite . setLayoutData ( compositeLData ) ; accessModifierComposite . setLayout ( gridLayout ) ; Label lbAccessModifier = new Label ( accessModifierComposite , SWT . NONE ) ; lbAccessModifier . setText ( GroovyRefactoringMessages . ExtractMethodWizard_LB_AcessModifier ) ; GridData data = new GridData ( ) ; data . horizontalSpan = <NUM_LIT:2> ; lbAccessModifier . setLayoutData ( data ) ; MouseAdapter btnClick = new MouseAdapter ( ) { @ Override public void mouseUp ( MouseEvent e ) { super . mouseUp ( e ) ; setModifier ( e ) ; } } ; createRadioButtons ( btnClick ) ; } private void createRadioButtons ( MouseAdapter btnClick ) { for ( String buttonName : possibleModifiers ) { Button btnModifier = new Button ( accessModifierComposite , SWT . RADIO ) ; btnModifier . setText ( buttonName ) ; btnModifier . addMouseListener ( btnClick ) ; enableAndSelectButtons ( buttonName , btnModifier ) ; } } private void enableAndSelectButtons ( String buttonName , Button btnModifier ) { if ( buttonName . equals ( possibleModifiers [ DEFAULT_MODIFIER ] ) ) { btnModifier . setSelection ( true ) ; } if ( buttonName . equals ( MODIFIER_NONE ) ) { btnModifier . setEnabled ( extractMethodRefactoring . isStatic ( ) ) ; } } private void createNewMethodNameComposite ( Composite parent ) { newMethodNameComposite = new Composite ( parent , SWT . NONE ) ; GridLayout gridLayout = new GridLayout ( ) ; gridLayout . numColumns = <NUM_LIT:2> ; gridLayout . marginHeight = <NUM_LIT:10> ; GridData compositeLData = new GridData ( ) ; compositeLData . horizontalAlignment = GridData . FILL ; compositeLData . grabExcessHorizontalSpace = true ; newMethodNameComposite . setLayoutData ( compositeLData ) ; newMethodNameComposite . setLayout ( gridLayout ) ; Label lbMethodName = new Label ( newMethodNameComposite , SWT . NONE ) ; lbMethodName . setText ( GroovyRefactoringMessages . ExtractMethodWizard_LB_NewMethodName ) ; txtNewMethodName = new Text ( newMethodNameComposite , SWT . BORDER ) ; txtNewMethodName . addKeyListener ( new KeyAdapter ( ) { @ Override public void keyReleased ( KeyEvent e ) { firstPreviewEver = false ; extractMethodRefactoring . setNewMethodname ( txtNewMethodName . getText ( ) ) ; } } ) ; GridData data = new GridData ( ) ; data . horizontalAlignment = GridData . FILL ; data . grabExcessHorizontalSpace = true ; txtNewMethodName . setLayoutData ( data ) ; } private void createParameterComposite ( Composite parent ) { if ( extractMethodRefactoring . getCallAndMethHeadParameters ( ) . length > <NUM_LIT:0> ) { GridLayout gridLayout ; initParameterComposite ( parent ) ; Label lbParameters = new Label ( parameterComposite , SWT . NONE ) ; lbParameters . setText ( GroovyRefactoringMessages . ExtractMethodWizard_LB_Parameters ) ; Composite parameterTableAndButtons = createTableAndButtonComposite ( ) ; Composite tableframe = createTableComposite ( parameterTableAndButtons ) ; createParameterTable ( tableframe ) ; Composite buttonframe = new Composite ( parameterTableAndButtons , SWT . NONE ) ; gridLayout = new GridLayout ( ) ; gridLayout . numColumns = <NUM_LIT:1> ; buttonframe . setLayout ( gridLayout ) ; GridData buttonData = new GridData ( ) ; buttonData . widthHint = <NUM_LIT> ; createUpButton ( buttonframe , buttonData ) ; createDownButton ( buttonframe , buttonData ) ; createTableSelectionListener ( ) ; } } private void createTableSelectionListener ( ) { createTableEditor ( ) ; tblParameters . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { final int EDITABLECOLUMN = <NUM_LIT:1> ; TableItem currentTableItem = ( ( TableItem ) e . item ) ; if ( currentTableItem == null ) return ; updateButtonsEnabled ( tblParameters ) ; disposeTableEditor ( ) ; Text newEditor = new Text ( tblParameters , SWT . NONE ) ; newEditor . setText ( currentTableItem . getText ( EDITABLECOLUMN ) ) ; addListenerToEditor ( EDITABLECOLUMN , newEditor ) ; newEditor . selectAll ( ) ; newEditor . setFocus ( ) ; editor . setEditor ( newEditor , currentTableItem , EDITABLECOLUMN ) ; } private void addListenerToEditor ( final int EDITABLECOLUMN , Text newEditor ) { newEditor . addModifyListener ( new ModifyListener ( ) { public void modifyText ( ModifyEvent e ) { saveRenamedVariable ( EDITABLECOLUMN ) ; } private void saveRenamedVariable ( final int EDITABLECOLUMN ) { Text text = ( Text ) editor . getEditor ( ) ; int selectionIndex = tblParameters . getSelectionIndex ( ) ; String before = extractMethodRefactoring . getOriginalParameterName ( selectionIndex ) ; editor . getItem ( ) . setText ( EDITABLECOLUMN , text . getText ( ) ) ; String after = editor . getItem ( ) . getText ( EDITABLECOLUMN ) ; renameVariablesMap . put ( before , after ) ; extractMethodRefactoring . setParameterRename ( renameVariablesMap ) ; } } ) ; } } ) ; } private void createTableEditor ( ) { editor = new TableEditor ( tblParameters ) ; editor . horizontalAlignment = SWT . LEFT ; editor . grabHorizontal = true ; editor . minimumWidth = <NUM_LIT> ; } private Button createPushButton ( Composite buttonframe , GridData buttonData , String text , boolean enabled , boolean visible ) { Button pushButton = new Button ( buttonframe , SWT . PUSH ) ; pushButton . setText ( text ) ; pushButton . setLayoutData ( buttonData ) ; pushButton . setEnabled ( enabled ) ; pushButton . setVisible ( visible ) ; return pushButton ; } private void createDownButton ( Composite buttonframe , GridData buttonData ) { btnDown = createPushButton ( buttonframe , buttonData , GroovyRefactoringMessages . ExtractMethodWizard_LB_BTN_Down , false , true ) ; btnDown . addMouseListener ( new ExtractMethodMouseAdapter ( this , ExtractMethodMouseAdapter . DOWNEVENT ) ) ; } private void createUpButton ( Composite buttonframe , GridData buttonData ) { btnUp = createPushButton ( buttonframe , buttonData , GroovyRefactoringMessages . ExtractMethodWizard_LB_BTN_UP , false , true ) ; btnUp . addMouseListener ( new ExtractMethodMouseAdapter ( this , ExtractMethodMouseAdapter . UPEVENT ) ) ; } private void createParameterTable ( Composite tableframe ) { int tableParams = SWT . BORDER | SWT . V_SCROLL | SWT . FULL_SELECTION ; tblParameters = new Table ( tableframe , tableParams ) ; tblParameters . setLinesVisible ( true ) ; tblParameters . setHeaderVisible ( true ) ; createTableColumn ( GroovyRefactoringMessages . ExtractMethodWizard_LB_Col_Type ) ; createTableColumn ( GroovyRefactoringMessages . ExtractMethodWizard_LB_Col_Name ) ; } private Composite createTableComposite ( Composite parameterTableAndButtons ) { GridLayout gridLayout ; Composite tableframe = new Composite ( parameterTableAndButtons , SWT . NONE ) ; gridLayout = new GridLayout ( ) ; gridLayout . numColumns = <NUM_LIT:1> ; gridLayout . horizontalSpacing = <NUM_LIT:0> ; tableframe . setLayout ( gridLayout ) ; return tableframe ; } private Composite createTableAndButtonComposite ( ) { GridLayout gridLayout ; Composite parameterTableAndButtons = new Composite ( parameterComposite , SWT . NONE ) ; gridLayout = new GridLayout ( ) ; gridLayout . numColumns = <NUM_LIT:2> ; parameterTableAndButtons . setLayout ( gridLayout ) ; return parameterTableAndButtons ; } private void initParameterComposite ( Composite parent ) { parameterComposite = new Composite ( parent , SWT . NONE ) ; GridLayout gridLayout = new GridLayout ( ) ; gridLayout . numColumns = <NUM_LIT:1> ; gridLayout . marginHeight = <NUM_LIT:0> ; gridLayout . marginTop = <NUM_LIT:10> ; gridLayout . verticalSpacing = <NUM_LIT:0> ; GridData compositeLData = new GridData ( ) ; compositeLData . horizontalAlignment = GridData . FILL ; compositeLData . grabExcessHorizontalSpace = true ; parameterComposite . setLayoutData ( compositeLData ) ; parameterComposite . setLayout ( gridLayout ) ; } private void createTableColumn ( String title ) { TableColumn column = new TableColumn ( tblParameters , SWT . NONE ) ; column . setText ( title ) ; column . setWidth ( <NUM_LIT> ) ; column . setMoveable ( false ) ; column . setResizable ( false ) ; } private void createPreviewComposite ( Composite parent ) { previewComposite = new Composite ( parent , SWT . NONE ) ; GridLayout gridLayout = new GridLayout ( ) ; gridLayout . marginHeight = <NUM_LIT:0> ; GridData compositeLData = new GridData ( ) ; compositeLData . horizontalAlignment = GridData . FILL ; compositeLData . grabExcessHorizontalSpace = true ; previewComposite . setLayoutData ( compositeLData ) ; previewComposite . setLayout ( gridLayout ) ; Label lbPreview = new Label ( previewComposite , SWT . NONE ) ; lbPreview . setText ( GroovyRefactoringMessages . ExtractMethodWizard_LB_MethodSignaturePreview ) ; txtPreviewCall = new Text ( previewComposite , SWT . MULTI | SWT . READ_ONLY ) ; txtPreviewCall . setText ( GroovyRefactoringMessages . ExtractMethodWizard_MethodCall ) ; GridData data = new GridData ( ) ; data . heightHint = <NUM_LIT> ; data . horizontalAlignment = GridData . FILL ; data . verticalAlignment = GridData . FILL ; data . grabExcessHorizontalSpace = true ; data . grabExcessVerticalSpace = true ; txtPreviewCall . setLayoutData ( data ) ; } protected void handleUpDownEvent ( boolean upEvent ) { String variName = "<STR_LIT>" ; if ( tblParameters . getSelectionCount ( ) > <NUM_LIT:0> ) { variName = tblParameters . getSelection ( ) [ <NUM_LIT:0> ] . getText ( <NUM_LIT:1> ) ; } int indexOfSelectedParam = extractMethodRefactoring . setMoveParameter ( variName , upEvent , <NUM_LIT:1> ) ; initializeValues ( indexOfSelectedParam ) ; disposeTableEditor ( ) ; } private void disposeTableEditor ( ) { Control oldEditor = editor . getEditor ( ) ; if ( oldEditor != null ) oldEditor . dispose ( ) ; } private void updateButtonsEnabled ( Table tbl ) { int lastElementIndex = extractMethodRefactoring . getCallAndMethHeadParameters ( ) . length - <NUM_LIT:1> ; int selectionIndex = tbl . getSelectionIndex ( ) ; if ( tbl . getItemCount ( ) == <NUM_LIT:1> ) { btnDown . setEnabled ( false ) ; btnUp . setEnabled ( false ) ; } else if ( selectionIndex == <NUM_LIT:0> ) { btnDown . setEnabled ( true ) ; btnUp . setEnabled ( false ) ; } else if ( selectionIndex == lastElementIndex ) { btnDown . setEnabled ( false ) ; btnUp . setEnabled ( true ) ; } else { btnDown . setEnabled ( true ) ; btnUp . setEnabled ( true ) ; } } } class ExtractMethodMouseAdapter extends MouseAdapter { public static final int EDITEVENT = <NUM_LIT:1> ; public static final int DOWNEVENT = <NUM_LIT:2> ; public static final int UPEVENT = <NUM_LIT:3> ; private final ExtractMethodPageContent wizard ; private final int eventType ; public ExtractMethodMouseAdapter ( ExtractMethodPageContent wizard , int eventtype ) { this . wizard = wizard ; this . eventType = eventtype ; } @ Override public void mouseUp ( MouseEvent e ) { super . mouseUp ( e ) ; switch ( eventType ) { case DOWNEVENT : wizard . handleUpDownEvent ( false ) ; break ; case UPEVENT : wizard . handleUpDownEvent ( true ) ; break ; } } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . ui . extract ; import org . codehaus . groovy . eclipse . refactoring . core . extract . ExtractGroovyMethodRefactoring ; import org . eclipse . ltk . ui . refactoring . RefactoringWizard ; public class ExtractMethodRefactoringWizard extends RefactoringWizard { public ExtractMethodRefactoringWizard ( ExtractGroovyMethodRefactoring refactoring ) { super ( refactoring , DIALOG_BASED_USER_INTERFACE ) ; } @ Override protected void addUserInputPages ( ) { ExtractGroovyMethodRefactoring groovyRefactoring = ( ExtractGroovyMethodRefactoring ) getRefactoring ( ) ; super . addPage ( new ExtractMethodPage ( groovyRefactoring . getName ( ) , ( ExtractGroovyMethodRefactoring ) getRefactoring ( ) ) ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . ui . extract ; import org . eclipse . osgi . util . NLS ; public class GroovyRefactoringMessages extends NLS { private static final String BUNDLE_NAME = "<STR_LIT>" ; public static String GroovyRefactoringAction_No_Module_Node ; public static String GroovyRefactoringAction_Syntax_Errors ; public static String InlineMethodInfo_Multiple_Methodbodies ; public static String InlineMethodInfo_Multiple_Returns_found ; public static String InlineMethodInfo_No_Method_Call_Found ; public static String InlineMethodInfo_No_Methodbody_Found ; public static String InlineMethodInfo_No_Methodcall_found ; public static String InlineMethodWizard_All_Invocations ; public static String InlineMethodWizard_Delete_Method ; public static String InlineMethodWizard_Inline ; public static String InlineMethodWizard_Only_Selected_Invocation ; public static String RenameLocalInfo_VariableAlreadyExists ; public static String RenameLocalInfo_NoLocalVariableInSelection ; public static String RenameClassInfo_RenameNotPossible ; public static String RenameClassInfo_RenameAliasNotPossible ; public static String RenameClassInfo_ClassNameAlreadyExists ; public static String ExtractMethodInfo_NoExtractionOfConstructorCallinConstructor ; public static String ExtractMethodInfo_NoStatementSelected ; public static String ExtractMethodInfo_ToMuchReturnValues ; public static String ExtractMethodWizard_LB_AcessModifier ; public static String ExtractMethodWizard_LB_BTN_Down ; public static String ExtractMethodWizard_LB_BTN_Edit ; public static String ExtractMethodWizard_LB_BTN_UP ; public static String ExtractMethodWizard_LB_Col_Name ; public static String ExtractMethodWizard_LB_Col_Type ; public static String ExtractMethodWizard_LB_MethodSignaturePreview ; public static String ExtractMethodWizard_LB_NewMethodName ; public static String ExtractMethodWizard_LB_Parameters ; public static String ExtractMethodWizard_MethodCall ; public static String ExtractMethodWizard_MethodNameAlreadyExists ; public static String ExtractMethodWizard_DefaultMethodName ; public static String ExtractMethodWizard_DuplicateVariableName ; public static String GroovyConventions_NameLowChar ; public static String GroovyConventions_NameUpperChar ; public static String GroovyConventions_IllegalName ; public static String GroovyConventions_ProvideName ; public static String RenameMethodFileSelectionPage_LB_CodePreview ; public static String RenameMethodFileSelectionPage_LB_DefinitveCandidates ; public static String RenameMethodFileSelectionPage_LB_AmbiguousCandidates ; public static String RenameMethod_VariableAlreadyExists ; public static String RenameMethod_DefaultParamsUsed ; public static String RenameClassRefactoring ; public static String RenameFieldRefactoring ; public static String RenameMethodRefactoring ; public static String RenameLocalRefactoring ; public static String ExtractMethodRefactoring ; public static String InlineMethodRefactoring ; public static String FormattingAction_Syntax_Errors ; public static String FormattingAction_RootNode_Errors ; public static String CandidateSelection_Title ; public static String CandidateSelection_Message ; public static String CandidateSelection_SelectionOK ; public static String CandidateSelection_SelectionNotOK ; public static String JavaClassUpdateRefactoring ; public static String JavaFieldUpdateRefactoring ; public static String JavaMethodUpdateRefactoring ; public static String JavaSyntheticFieldUpdateRefactoring ; public static String ParticipantDispatcherError ; static { NLS . initializeMessages ( BUNDLE_NAME , GroovyRefactoringMessages . class ) ; } private GroovyRefactoringMessages ( ) { } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . ui . extract ; import org . codehaus . groovy . eclipse . refactoring . core . extract . ExtractGroovyMethodRefactoring ; import org . eclipse . ltk . ui . refactoring . UserInputWizardPage ; import org . eclipse . swt . SWT ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; public class ExtractMethodPage extends UserInputWizardPage { private ExtractGroovyMethodRefactoring extractMethodRefactoring ; public ExtractMethodPage ( String name , ExtractGroovyMethodRefactoring refactoring ) { super ( name ) ; this . extractMethodRefactoring = refactoring ; setTitle ( name ) ; setMessage ( "<STR_LIT>" ) ; } public void createControl ( Composite parent ) { Composite control = new Composite ( parent , SWT . NONE ) ; GridLayout baseLayout = new GridLayout ( ) ; baseLayout . numColumns = <NUM_LIT:1> ; new ExtractMethodPageContent ( control , extractMethodRefactoring , this ) ; control . setLayout ( baseLayout ) ; setControl ( control ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . ui . extract ; import org . codehaus . groovy . eclipse . refactoring . core . extract . ExtractGroovyLocalRefactoring ; import org . eclipse . core . runtime . Assert ; import org . eclipse . jdt . internal . ui . IJavaHelpContextIds ; import org . eclipse . jdt . internal . ui . refactoring . RefactoringMessages ; import org . eclipse . jdt . internal . ui . refactoring . TextInputWizardPage ; import org . eclipse . jdt . internal . ui . refactoring . contentassist . ControlContentAssistHelper ; import org . eclipse . jdt . internal . ui . refactoring . contentassist . VariableNamesProcessor ; import org . eclipse . jdt . internal . ui . util . RowLayouter ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogSettings ; import org . eclipse . ltk . core . refactoring . RefactoringStatus ; import org . eclipse . ltk . ui . refactoring . RefactoringWizard ; import org . eclipse . swt . SWT ; import org . eclipse . swt . events . SelectionAdapter ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Text ; import org . eclipse . ui . PlatformUI ; public class ExtractLocalWizard extends RefactoringWizard { static final String DIALOG_SETTING_SECTION = "<STR_LIT>" ; private static class ExtractLocalPage extends TextInputWizardPage { private static final String REPLACE_ALL = "<STR_LIT>" ; private final boolean fInitialValid ; private static final String DESCRIPTION = RefactoringMessages . ExtractTempInputPage_enter_name ; private String [ ] fTempNameProposals ; private IDialogSettings fSettings ; public ExtractLocalPage ( String [ ] tempNameProposals ) { super ( DESCRIPTION , true , tempNameProposals . length == <NUM_LIT:0> ? "<STR_LIT>" : tempNameProposals [ <NUM_LIT:0> ] ) ; Assert . isNotNull ( tempNameProposals ) ; fTempNameProposals = tempNameProposals ; fInitialValid = tempNameProposals . length > <NUM_LIT:0> ; } public void createControl ( Composite parent ) { loadSettings ( ) ; Composite result = new Composite ( parent , SWT . NONE ) ; setControl ( result ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = <NUM_LIT:2> ; layout . verticalSpacing = <NUM_LIT:8> ; result . setLayout ( layout ) ; RowLayouter layouter = new RowLayouter ( <NUM_LIT:2> ) ; Label label = new Label ( result , SWT . NONE ) ; label . setText ( RefactoringMessages . ExtractTempInputPage_variable_name ) ; Text text = createTextInputField ( result ) ; text . selectAll ( ) ; text . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; ControlContentAssistHelper . createTextContentAssistant ( text , new VariableNamesProcessor ( fTempNameProposals ) ) ; layouter . perform ( label , text , <NUM_LIT:1> ) ; addReplaceAllCheckbox ( result , layouter ) ; validateTextField ( text . getText ( ) ) ; Dialog . applyDialogFont ( result ) ; PlatformUI . getWorkbench ( ) . getHelpSystem ( ) . setHelp ( getControl ( ) , IJavaHelpContextIds . EXTRACT_TEMP_WIZARD_PAGE ) ; } private void loadSettings ( ) { fSettings = getDialogSettings ( ) . getSection ( ExtractLocalWizard . DIALOG_SETTING_SECTION ) ; if ( fSettings == null ) { fSettings = getDialogSettings ( ) . addNewSection ( ExtractLocalWizard . DIALOG_SETTING_SECTION ) ; fSettings . put ( REPLACE_ALL , true ) ; } getExtractLocalRefactoring ( ) . setReplaceAllOccurrences ( fSettings . getBoolean ( REPLACE_ALL ) ) ; } private void addReplaceAllCheckbox ( Composite result , RowLayouter layouter ) { String title = RefactoringMessages . ExtractTempInputPage_replace_all ; boolean defaultValue = getExtractLocalRefactoring ( ) . isReplaceAllOccurrences ( ) ; final Button checkBox = createCheckbox ( result , title , defaultValue , layouter ) ; getExtractLocalRefactoring ( ) . setReplaceAllOccurrences ( checkBox . getSelection ( ) ) ; checkBox . addSelectionListener ( new SelectionAdapter ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { fSettings . put ( REPLACE_ALL , checkBox . getSelection ( ) ) ; getExtractLocalRefactoring ( ) . setReplaceAllOccurrences ( checkBox . getSelection ( ) ) ; } } ) ; } @ Override protected void textModified ( String text ) { getExtractLocalRefactoring ( ) . setLocalName ( text ) ; super . textModified ( text ) ; } @ Override protected RefactoringStatus validateTextField ( String text ) { return getExtractLocalRefactoring ( ) . checkLocalNameOnChange ( text ) ; } private ExtractGroovyLocalRefactoring getExtractLocalRefactoring ( ) { return ( ExtractGroovyLocalRefactoring ) getRefactoring ( ) ; } private static Button createCheckbox ( Composite parent , String title , boolean value , RowLayouter layouter ) { Button checkBox = new Button ( parent , SWT . CHECK ) ; checkBox . setText ( title ) ; checkBox . setSelection ( value ) ; layouter . perform ( checkBox ) ; return checkBox ; } @ Override protected boolean isInitialInputValid ( ) { return fInitialValid ; } } public ExtractLocalWizard ( ExtractGroovyLocalRefactoring ref ) { super ( ref , DIALOG_BASED_USER_INTERFACE | PREVIEW_EXPAND_FIRST_NODE ) ; setDefaultPageTitle ( RefactoringMessages . ExtractTempWizard_defaultPageTitle ) ; } @ Override protected void addUserInputPages ( ) { addPage ( new ExtractLocalPage ( getExtractTempRefactoring ( ) . guessLocalNames ( ) ) ) ; } private ExtractGroovyLocalRefactoring getExtractTempRefactoring ( ) { return ( ExtractGroovyLocalRefactoring ) getRefactoring ( ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . rename ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Map . Entry ; import java . util . Set ; import org . codehaus . groovy . eclipse . core . GroovyCore ; import org . codehaus . groovy . eclipse . core . search . ISearchRequestor ; import org . codehaus . groovy . eclipse . core . search . SyntheticAccessorSearchRequestor ; import org . codehaus . jdt . groovy . model . GroovyNature ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . resources . IResource ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . SubMonitor ; import org . eclipse . jdt . core . IClassFile ; import org . eclipse . jdt . core . ICompilationUnit ; import org . eclipse . jdt . core . IField ; import org . eclipse . jdt . core . IJavaElement ; import org . eclipse . jdt . core . IMember ; import org . eclipse . jdt . core . IMethod ; import org . eclipse . jdt . core . IPackageFragment ; import org . eclipse . jdt . core . IPackageFragmentRoot ; import org . eclipse . jdt . core . JavaCore ; import org . eclipse . jdt . core . JavaModelException ; import org . eclipse . jdt . core . SourceRange ; import org . eclipse . jdt . core . refactoring . CompilationUnitChange ; import org . eclipse . jdt . core . search . SearchMatch ; import org . eclipse . jdt . groovy . core . util . ContentTypeUtils ; import org . eclipse . jdt . internal . corext . refactoring . Checks ; import org . eclipse . jdt . internal . corext . refactoring . RefactoringCoreMessages ; import org . eclipse . jdt . internal . corext . refactoring . SearchResultGroup ; import org . eclipse . jdt . internal . corext . refactoring . base . JavaStatusContext ; import org . eclipse . jdt . internal . corext . refactoring . base . ReferencesInBinaryContext ; import org . eclipse . jdt . internal . corext . refactoring . rename . RenameFieldProcessor ; import org . eclipse . jdt . internal . corext . refactoring . rename . RenameMethodProcessor ; import org . eclipse . ltk . core . refactoring . Change ; import org . eclipse . ltk . core . refactoring . CompositeChange ; import org . eclipse . ltk . core . refactoring . RefactoringStatus ; import org . eclipse . ltk . core . refactoring . RefactoringStatusEntry ; import org . eclipse . ltk . core . refactoring . TextChange ; import org . eclipse . ltk . core . refactoring . TextEditChangeGroup ; import org . eclipse . ltk . core . refactoring . participants . CheckConditionsContext ; import org . eclipse . ltk . core . refactoring . participants . RefactoringProcessor ; import org . eclipse . ltk . core . refactoring . participants . RenameParticipant ; import org . eclipse . text . edits . MultiTextEdit ; import org . eclipse . text . edits . ReplaceEdit ; import org . eclipse . text . edits . TextEdit ; import org . eclipse . text . edits . TextEditGroup ; public class SyntheticAccessorsRenameParticipant extends RenameParticipant { private IMember renameTarget ; private List < SearchMatch > matches ; @ Override public RefactoringStatus checkConditions ( IProgressMonitor pm , CheckConditionsContext context ) throws OperationCanceledException { RefactoringStatus status = new RefactoringStatus ( ) ; try { if ( shouldUpdateReferences ( ) ) { matches = findExtraReferences ( SubMonitor . convert ( pm , "<STR_LIT>" , <NUM_LIT:10> ) ) ; } else { matches = Collections . emptyList ( ) ; } checkForBinaryRefs ( matches , status ) ; SearchResultGroup [ ] grouped = convert ( matches ) ; Checks . excludeCompilationUnits ( grouped , status ) ; status . merge ( Checks . checkCompileErrorsInAffectedFiles ( grouped ) ) ; checkForPotentialRefs ( matches , status ) ; } catch ( CoreException e ) { GroovyCore . logException ( e . getLocalizedMessage ( ) , e ) ; return RefactoringStatus . createFatalErrorStatus ( e . getLocalizedMessage ( ) ) ; } return status ; } private boolean shouldUpdateReferences ( ) { RefactoringProcessor processor = getProcessor ( ) ; if ( processor instanceof RenameFieldProcessor ) { return ( ( RenameFieldProcessor ) processor ) . getUpdateReferences ( ) ; } else if ( processor instanceof RenameMethodProcessor ) { return ( ( RenameMethodProcessor ) processor ) . getUpdateReferences ( ) ; } return true ; } private void checkForPotentialRefs ( List < SearchMatch > toCheck , RefactoringStatus status ) { for ( SearchMatch match : toCheck ) { if ( match . getAccuracy ( ) == SearchMatch . A_INACCURATE ) { final RefactoringStatusEntry entry = new RefactoringStatusEntry ( RefactoringStatus . WARNING , RefactoringCoreMessages . RefactoringSearchEngine_potential_matches , JavaStatusContext . create ( JavaCore . createCompilationUnitFrom ( ( IFile ) match . getResource ( ) ) , new SourceRange ( match . getOffset ( ) , match . getLength ( ) ) ) ) ; status . addEntry ( entry ) ; } } } private void checkForBinaryRefs ( List < SearchMatch > toCheck , RefactoringStatus status ) throws JavaModelException { ReferencesInBinaryContext binaryRefs = new ReferencesInBinaryContext ( "<STR_LIT>" + renameTarget . getElementName ( ) + "<STR_LIT>" ) ; for ( Iterator < SearchMatch > iter = toCheck . iterator ( ) ; iter . hasNext ( ) ; ) { SearchMatch match = iter . next ( ) ; if ( isBinaryElement ( match . getElement ( ) ) ) { if ( match . getAccuracy ( ) == SearchMatch . A_ACCURATE ) { binaryRefs . add ( match ) ; } iter . remove ( ) ; } } binaryRefs . addErrorIfNecessary ( status ) ; } private boolean isBinaryElement ( Object element ) throws JavaModelException { if ( element instanceof IMember ) { return ( ( IMember ) element ) . isBinary ( ) ; } else if ( element instanceof ICompilationUnit ) { return true ; } else if ( element instanceof IClassFile ) { return false ; } else if ( element instanceof IPackageFragment ) { return isBinaryElement ( ( ( IPackageFragment ) element ) . getParent ( ) ) ; } else if ( element instanceof IPackageFragmentRoot ) { return ( ( IPackageFragmentRoot ) element ) . getKind ( ) == IPackageFragmentRoot . K_BINARY ; } return false ; } private SearchResultGroup [ ] convert ( List < SearchMatch > toGroup ) { Map < IResource , List < SearchMatch > > groups = new HashMap < IResource , List < SearchMatch > > ( toGroup . size ( ) ) ; for ( SearchMatch searchMatch : toGroup ) { if ( searchMatch . getResource ( ) == null ) { continue ; } List < SearchMatch > group = groups . get ( searchMatch . getResource ( ) ) ; if ( group == null ) { group = new ArrayList < SearchMatch > ( ) ; groups . put ( searchMatch . getResource ( ) , group ) ; } group . add ( searchMatch ) ; } SearchResultGroup [ ] results = new SearchResultGroup [ groups . size ( ) ] ; int i = <NUM_LIT:0> ; for ( Entry < IResource , List < SearchMatch > > group : groups . entrySet ( ) ) { results [ i ++ ] = new SearchResultGroup ( group . getKey ( ) , group . getValue ( ) . toArray ( new SearchMatch [ <NUM_LIT:0> ] ) ) ; } return results ; } @ Override public Change createChange ( IProgressMonitor pm ) throws CoreException , OperationCanceledException { CompositeChange change = new CompositeChange ( getName ( ) ) ; createMatchedChanges ( matches , change , getNameMap ( ) ) ; if ( change . getChildren ( ) . length > <NUM_LIT:0> ) { return change ; } return null ; } @ Override public String getName ( ) { return "<STR_LIT>" ; } @ Override protected boolean initialize ( Object element ) { if ( element instanceof IMethod || element instanceof IField ) { renameTarget = ( IMember ) element ; if ( ! renameTarget . isReadOnly ( ) && ContentTypeUtils . isGroovyLikeFileName ( renameTarget . getCompilationUnit ( ) . getElementName ( ) ) && GroovyNature . hasGroovyNature ( renameTarget . getJavaProject ( ) . getProject ( ) ) ) { return true ; } } return false ; } private String accessorName ( String prefix , String name ) { return prefix + Character . toUpperCase ( name . charAt ( <NUM_LIT:0> ) ) + name . substring ( <NUM_LIT:1> ) ; } private void addChange ( CompositeChange finalChange , IMember enclosingElement , int offset , int length , String newName ) { CompilationUnitChange existingChange = findOrCreateChange ( enclosingElement , finalChange ) ; TextEditChangeGroup [ ] groups = existingChange . getTextEditChangeGroups ( ) ; TextEdit occurrenceEdit = new ReplaceEdit ( offset , length , newName ) ; boolean isOverlapping = false ; for ( TextEditChangeGroup group : groups ) { if ( group . getTextEdits ( ) [ <NUM_LIT:0> ] . covers ( occurrenceEdit ) ) { isOverlapping = true ; break ; } } if ( isOverlapping ) { return ; } existingChange . addEdit ( occurrenceEdit ) ; existingChange . addChangeGroup ( new TextEditChangeGroup ( existingChange , new TextEditGroup ( "<STR_LIT>" , occurrenceEdit ) ) ) ; } private String basename ( String fullName ) { int baseStart ; if ( fullName . startsWith ( "<STR_LIT>" ) && fullName . length ( ) > <NUM_LIT:2> && Character . isUpperCase ( fullName . charAt ( <NUM_LIT:2> ) ) ) { baseStart = <NUM_LIT:2> ; } else if ( ( fullName . startsWith ( "<STR_LIT:get>" ) || fullName . startsWith ( "<STR_LIT>" ) ) && fullName . length ( ) > <NUM_LIT:3> && Character . isUpperCase ( fullName . charAt ( <NUM_LIT:3> ) ) ) { baseStart = <NUM_LIT:3> ; } else { baseStart = - <NUM_LIT:1> ; } if ( baseStart > <NUM_LIT:0> ) { return Character . toLowerCase ( fullName . charAt ( baseStart ) ) + fullName . substring ( baseStart + <NUM_LIT:1> ) ; } else { return fullName ; } } private void createMatchedChanges ( List < SearchMatch > references , CompositeChange finalChange , Map < String , String > nameMap ) throws JavaModelException { for ( SearchMatch searchMatch : references ) { Object elt = searchMatch . getElement ( ) ; if ( elt instanceof IMember ) { String oldName = findMatchName ( searchMatch , nameMap . keySet ( ) ) ; if ( oldName != null ) { String newName = nameMap . get ( oldName ) ; addChange ( finalChange , ( IMember ) elt , searchMatch . getOffset ( ) , oldName . length ( ) , newName ) ; } } } } private List < SearchMatch > findExtraReferences ( IProgressMonitor pm ) throws CoreException { SyntheticAccessorSearchRequestor synthRequestor = new SyntheticAccessorSearchRequestor ( ) ; final List < SearchMatch > matches = new ArrayList < SearchMatch > ( ) ; synthRequestor . findSyntheticMatches ( renameTarget , new ISearchRequestor ( ) { public void acceptMatch ( SearchMatch match ) { matches . add ( match ) ; } } , SubMonitor . convert ( pm , "<STR_LIT>" , <NUM_LIT:10> ) ) ; return matches ; } private String findMatchName ( SearchMatch searchMatch , Set < String > keySet ) throws JavaModelException { IJavaElement element = JavaCore . create ( searchMatch . getResource ( ) ) ; if ( element . getElementType ( ) == IJavaElement . COMPILATION_UNIT ) { ICompilationUnit unit = ( ICompilationUnit ) element ; String matchedText = unit . getBuffer ( ) . getText ( searchMatch . getOffset ( ) , searchMatch . getLength ( ) ) ; for ( String oldName : keySet ) { if ( matchedText . startsWith ( oldName ) ) { return oldName ; } } } return null ; } private CompilationUnitChange findOrCreateChange ( IMember accessor , CompositeChange finalChange ) { TextChange textChange = getTextChange ( accessor . getCompilationUnit ( ) ) ; CompilationUnitChange existingChange = null ; if ( textChange instanceof CompilationUnitChange ) { existingChange = ( CompilationUnitChange ) textChange ; } else { Change [ ] children = finalChange . getChildren ( ) ; for ( Change change : children ) { if ( change instanceof CompilationUnitChange ) { if ( ( ( CompilationUnitChange ) change ) . getCompilationUnit ( ) . equals ( accessor . getCompilationUnit ( ) ) ) { existingChange = ( CompilationUnitChange ) change ; break ; } } } } if ( existingChange == null ) { existingChange = new CompilationUnitChange ( "<STR_LIT>" + accessor . getCompilationUnit ( ) . getElementName ( ) , accessor . getCompilationUnit ( ) ) ; existingChange . setEdit ( new MultiTextEdit ( ) ) ; finalChange . add ( existingChange ) ; } return existingChange ; } private Map < String , String > getNameMap ( ) { Map < String , String > nameMap = new HashMap < String , String > ( ) ; String newBaseName = basename ( getArguments ( ) . getNewName ( ) ) ; String oldBaseName = basename ( renameTarget . getElementName ( ) ) ; nameMap . put ( oldBaseName , newBaseName ) ; nameMap . put ( accessorName ( "<STR_LIT>" , oldBaseName ) , accessorName ( "<STR_LIT>" , newBaseName ) ) ; nameMap . put ( accessorName ( "<STR_LIT:get>" , oldBaseName ) , accessorName ( "<STR_LIT:get>" , newBaseName ) ) ; nameMap . put ( accessorName ( "<STR_LIT>" , oldBaseName ) , accessorName ( "<STR_LIT>" , newBaseName ) ) ; return nameMap ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . rename ; import org . codehaus . groovy . eclipse . core . GroovyCore ; import org . codehaus . jdt . groovy . model . GroovyCompilationUnit ; import org . eclipse . jdt . core . IJavaElement ; import org . eclipse . jdt . core . ISourceReference ; import org . eclipse . jdt . core . JavaModelException ; import org . eclipse . jface . text . ITextSelection ; public class CandidateCollector { protected ITextSelection selection ; protected GroovyCompilationUnit unit ; protected ISourceReference refactoringTarget ; private boolean isValid = true ; public CandidateCollector ( GroovyCompilationUnit unit , ITextSelection selection ) { this . unit = unit ; this . selection = selection ; } public ISourceReference getRefactoringTarget ( ) { if ( isValid && refactoringTarget == null ) { try { IJavaElement [ ] element = unit . codeSelect ( selection . getOffset ( ) , selection . getLength ( ) ) ; if ( element != null && element . length > <NUM_LIT:0> && element [ <NUM_LIT:0> ] instanceof ISourceReference ) { refactoringTarget = ( ISourceReference ) element [ <NUM_LIT:0> ] ; } else { isValid = false ; } } catch ( JavaModelException e ) { GroovyCore . logException ( "<STR_LIT>" + selection . getOffset ( ) + "<STR_LIT>" + unit . getElementName ( ) , e ) ; } } return refactoringTarget ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . rename . renameLocal ; import org . codehaus . groovy . ast . ASTNode ; import org . codehaus . groovy . ast . Variable ; import org . codehaus . groovy . ast . expr . ConstantExpression ; import org . codehaus . groovy . ast . expr . VariableExpression ; import org . eclipse . jdt . core . IJavaElement ; import org . eclipse . jdt . core . ISourceRange ; import org . eclipse . jdt . core . ISourceReference ; import org . eclipse . jdt . core . JavaModelException ; import org . eclipse . jdt . groovy . search . ITypeRequestor ; import org . eclipse . jdt . groovy . search . TypeLookupResult ; import org . eclipse . jdt . internal . core . util . Util ; public class LocalVariableNameCheckerRequestor implements ITypeRequestor { private final Variable variable ; private final int start ; private final int end ; private final String newName ; private boolean shadowing = false ; private boolean variableFound = false ; private IJavaElement foundEnclosingElement = null ; public LocalVariableNameCheckerRequestor ( Variable variable , String newName ) { this . variable = variable ; this . newName = newName ; if ( variable instanceof ASTNode ) { ASTNode v = ( ASTNode ) variable ; start = v . getStart ( ) ; end = v . getEnd ( ) ; } else { start = end = - <NUM_LIT:1> ; } } public VisitStatus acceptASTNode ( ASTNode node , TypeLookupResult result , IJavaElement enclosingElement ) { if ( ! interestingElement ( enclosingElement ) ) { return VisitStatus . CANCEL_MEMBER ; } if ( ! variableFound ) { if ( node == variable ) { variableFound = true ; foundEnclosingElement = enclosingElement ; } return VisitStatus . CONTINUE ; } if ( enclosingElement != foundEnclosingElement ) { return VisitStatus . STOP_VISIT ; } if ( node instanceof Variable ) { Variable other = ( Variable ) node ; if ( other . getName ( ) . equals ( newName ) ) { if ( ! ( other instanceof VariableExpression ) || ( ( VariableExpression ) other ) . getAccessedVariable ( ) != variable ) { shadowing = true ; return VisitStatus . STOP_VISIT ; } } } if ( node instanceof ConstantExpression ) { ConstantExpression con = ( ConstantExpression ) node ; if ( con . getText ( ) . equals ( variable . getName ( ) ) && result . declaration != variable ) { shadowing = true ; return VisitStatus . STOP_VISIT ; } } return VisitStatus . CONTINUE ; } public boolean isShadowing ( ) { return shadowing ; } private boolean interestingElement ( IJavaElement enclosingElement ) { if ( enclosingElement . getElementName ( ) . equals ( "<STR_LIT>" ) ) { return true ; } if ( start >= <NUM_LIT:0> && end >= <NUM_LIT:0> && enclosingElement instanceof ISourceReference ) { try { ISourceRange range = ( ( ISourceReference ) enclosingElement ) . getSourceRange ( ) ; return range . getOffset ( ) <= start && range . getOffset ( ) + range . getLength ( ) >= end ; } catch ( JavaModelException e ) { Util . log ( e ) ; } } return false ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . rename . renameLocal ; import java . util . List ; import org . codehaus . groovy . ast . ASTNode ; import org . codehaus . groovy . ast . Variable ; import org . codehaus . groovy . eclipse . codebrowsing . requestor . ASTNodeFinder ; import org . codehaus . groovy . eclipse . codebrowsing . requestor . Region ; import org . codehaus . groovy . eclipse . refactoring . Activator ; import org . codehaus . jdt . groovy . model . GroovyCompilationUnit ; import org . codehaus . jdt . groovy . model . GroovyNature ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jdt . core . ICompilationUnit ; import org . eclipse . jdt . core . IField ; import org . eclipse . jdt . core . IJavaElement ; import org . eclipse . jdt . core . ILocalVariable ; import org . eclipse . jdt . core . IMethod ; import org . eclipse . jdt . core . ISourceRange ; import org . eclipse . jdt . core . IType ; import org . eclipse . jdt . core . JavaConventions ; import org . eclipse . jdt . core . JavaCore ; import org . eclipse . jdt . core . JavaModelException ; import org . eclipse . jdt . core . refactoring . CompilationUnitChange ; import org . eclipse . jdt . groovy . core . util . ReflectionUtils ; import org . eclipse . jdt . groovy . search . LocalVariableReferenceRequestor ; import org . eclipse . jdt . groovy . search . TypeInferencingVisitorFactory ; import org . eclipse . jdt . groovy . search . TypeInferencingVisitorWithRequestor ; import org . eclipse . jdt . internal . compiler . impl . CompilerOptions ; import org . eclipse . jdt . internal . corext . refactoring . RefactoringCoreMessages ; import org . eclipse . jdt . internal . corext . refactoring . base . JavaStatusContext ; import org . eclipse . jdt . internal . corext . refactoring . rename . JavaRenameProcessor ; import org . eclipse . jdt . internal . corext . refactoring . rename . RenameModifications ; import org . eclipse . jdt . internal . corext . refactoring . util . ResourceUtil ; import org . eclipse . jdt . ui . refactoring . RefactoringSaveHelper ; import org . eclipse . jface . text . IRegion ; import org . eclipse . ltk . core . refactoring . Change ; import org . eclipse . ltk . core . refactoring . RefactoringStatus ; import org . eclipse . ltk . core . refactoring . participants . CheckConditionsContext ; import org . eclipse . ltk . core . refactoring . participants . RenameArguments ; import org . eclipse . text . edits . MultiTextEdit ; import org . eclipse . text . edits . ReplaceEdit ; import org . eclipse . text . edits . TextEdit ; import org . eclipse . text . edits . TextEditGroup ; public class GroovyRenameLocalVariableProcessor extends JavaRenameProcessor { GroovyCompilationUnit unit ; Variable variable ; CompilationUnitChange change ; ILocalVariable localVariable ; GroovyRenameLocalVariableProcessor ( ILocalVariable localVariable , String newName , RefactoringStatus status ) { initialize ( localVariable , newName , status ) ; } private void initialize ( ILocalVariable localVariable , String newName , RefactoringStatus status ) { this . localVariable = localVariable ; ICompilationUnit unit = ( ICompilationUnit ) localVariable . getAncestor ( IJavaElement . COMPILATION_UNIT ) ; if ( unit instanceof GroovyCompilationUnit ) { this . unit = ( GroovyCompilationUnit ) unit ; } else { status . merge ( RefactoringStatus . createErrorStatus ( "<STR_LIT>" + unit . getElementName ( ) ) ) ; } if ( newName != null && newName . length ( ) > <NUM_LIT:0> ) { if ( newName . equals ( localVariable . getElementName ( ) ) ) { status . merge ( RefactoringStatus . createErrorStatus ( "<STR_LIT>" ) ) ; } setNewElementName ( newName ) ; } else { status . merge ( RefactoringStatus . createErrorStatus ( "<STR_LIT>" ) ) ; } } @ Override protected RenameModifications computeRenameModifications ( ) throws CoreException { RenameModifications mods = new RenameModifications ( ) ; mods . rename ( localVariable , new RenameArguments ( getNewElementName ( ) , true ) ) ; return mods ; } @ Override protected RefactoringStatus doCheckFinalConditions ( IProgressMonitor pm , CheckConditionsContext context ) throws CoreException , OperationCanceledException { boolean wasWorkingCopy = true ; try { if ( ! unit . isWorkingCopy ( ) ) { unit . becomeWorkingCopy ( new SubProgressMonitor ( pm , <NUM_LIT:10> ) ) ; wasWorkingCopy = false ; } List < IRegion > references = findReferences ( ) ; change = createEdits ( references ) ; RefactoringStatus result = checkShadowing ( ) ; return result ; } catch ( Exception e ) { return RefactoringStatus . create ( new Status ( IStatus . ERROR , Activator . PLUGIN_ID , "<STR_LIT>" , e ) ) ; } finally { if ( ! wasWorkingCopy ) { unit . discardWorkingCopy ( ) ; } } } private RefactoringStatus checkShadowing ( ) { IType type = ( IType ) localVariable . getAncestor ( IJavaElement . TYPE ) ; if ( type != null ) { IField maybeShadows = type . getField ( getNewElementName ( ) ) ; if ( maybeShadows . exists ( ) ) { return RefactoringStatus . createWarningStatus ( "<STR_LIT>" + getNewElementName ( ) + "<STR_LIT>" + type . getElementName ( ) ) ; } } LocalVariableNameCheckerRequestor requestor = new LocalVariableNameCheckerRequestor ( variable , getNewElementName ( ) ) ; TypeInferencingVisitorWithRequestor visitor = new TypeInferencingVisitorFactory ( ) . createVisitor ( unit ) ; visitor . visitCompilationUnit ( requestor ) ; if ( requestor . isShadowing ( ) ) { IJavaElement parent = localVariable . getParent ( ) ; if ( parent instanceof IMethod ) { return RefactoringStatus . createWarningStatus ( "<STR_LIT>" + getNewElementName ( ) + "<STR_LIT>" + localVariable . getParent ( ) . getElementName ( ) , JavaStatusContext . create ( ( IMethod ) parent ) ) ; } else { return RefactoringStatus . createWarningStatus ( "<STR_LIT>" + getNewElementName ( ) + "<STR_LIT>" + localVariable . getParent ( ) . getElementName ( ) ) ; } } return new RefactoringStatus ( ) ; } @ Override protected String [ ] getAffectedProjectNatures ( ) throws CoreException { return new String [ ] { JavaCore . NATURE_ID , GroovyNature . GROOVY_NATURE } ; } @ Override protected IFile [ ] getChangedFiles ( ) throws CoreException { return new IFile [ ] { ResourceUtil . getFile ( unit ) } ; } @ Override public int getSaveMode ( ) { return RefactoringSaveHelper . SAVE_NOTHING ; } public RefactoringStatus checkNewElementName ( String newName ) throws CoreException { if ( localVariable . getElementName ( ) . equals ( newName ) ) { return RefactoringStatus . createErrorStatus ( "<STR_LIT>" ) ; } else { return RefactoringStatus . create ( JavaConventions . validateFieldName ( newName , CompilerOptions . VERSION_1_6 , CompilerOptions . VERSION_1_6 ) ) ; } } public String getCurrentElementName ( ) { return localVariable . getElementName ( ) ; } public Object getNewElement ( ) throws CoreException { return ReflectionUtils . createLocalVariable ( localVariable . getParent ( ) , getNewElementName ( ) , localVariable . getNameRange ( ) . getOffset ( ) , localVariable . getTypeSignature ( ) ) ; } @ Override public RefactoringStatus checkInitialConditions ( IProgressMonitor pm ) throws CoreException , OperationCanceledException { Variable variable = findVariable ( ) ; if ( variable == null ) { return RefactoringStatus . createErrorStatus ( "<STR_LIT>" + localVariable . getElementName ( ) ) ; } return new RefactoringStatus ( ) ; } @ Override public Change createChange ( IProgressMonitor pm ) throws CoreException , OperationCanceledException { return change ; } @ Override public Object [ ] getElements ( ) { return new Object [ ] { localVariable } ; } @ Override public String getIdentifier ( ) { return RenameLocalGroovyVariableContribution . ID ; } @ Override public String getProcessorName ( ) { return "<STR_LIT>" ; } @ Override public boolean isApplicable ( ) throws CoreException { if ( unit == null ) { return false ; } return true ; } private List < IRegion > findReferences ( ) { if ( variable == null ) { try { variable = findVariable ( ) ; } catch ( JavaModelException e ) { throw new RuntimeException ( e ) ; } } LocalVariableReferenceRequestor requestor = new LocalVariableReferenceRequestor ( variable , localVariable . getParent ( ) ) ; TypeInferencingVisitorWithRequestor visitor = new TypeInferencingVisitorFactory ( ) . createVisitor ( unit ) ; visitor . visitCompilationUnit ( requestor ) ; return requestor . getReferences ( ) ; } private Variable findVariable ( ) throws JavaModelException { ISourceRange sourceRange = localVariable . getSourceRange ( ) ; ASTNodeFinder findLocalVar = new ASTNodeFinder ( new Region ( sourceRange . getOffset ( ) , sourceRange . getLength ( ) ) ) ; ASTNode node = findLocalVar . doVisit ( unit . getModuleNode ( ) ) ; return node instanceof Variable ? ( Variable ) node : null ; } private CompilationUnitChange createEdits ( List < IRegion > references ) { TextEdit [ ] allEdits = new TextEdit [ references . size ( ) ] ; int index = <NUM_LIT:0> ; for ( IRegion region : references ) { allEdits [ index ] = new ReplaceEdit ( region . getOffset ( ) , region . getLength ( ) , getNewElementName ( ) ) ; index ++ ; } CompilationUnitChange change = new CompilationUnitChange ( RefactoringCoreMessages . RenameTempRefactoring_rename , unit ) ; MultiTextEdit rootEdit = new MultiTextEdit ( ) ; change . setEdit ( rootEdit ) ; change . setKeepPreviewEdits ( true ) ; for ( int i = <NUM_LIT:0> ; i < allEdits . length ; i ++ ) { rootEdit . addChild ( allEdits [ i ] ) ; change . addTextEditGroup ( new TextEditGroup ( RefactoringCoreMessages . RenameTempRefactoring_changeName , allEdits [ i ] ) ) ; } return change ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . rename . renameLocal ; import java . util . Map ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jdt . core . IJavaElement ; import org . eclipse . jdt . core . ILocalVariable ; import org . eclipse . jdt . core . refactoring . descriptors . JavaRefactoringDescriptor ; import org . eclipse . jdt . core . refactoring . descriptors . RenameJavaElementDescriptor ; import org . eclipse . jdt . groovy . core . util . ReflectionUtils ; import org . eclipse . jdt . internal . corext . refactoring . scripting . JavaUIRefactoringContribution ; import org . eclipse . ltk . core . refactoring . Refactoring ; import org . eclipse . ltk . core . refactoring . RefactoringDescriptor ; import org . eclipse . ltk . core . refactoring . RefactoringStatus ; import org . eclipse . ltk . core . refactoring . participants . RenameRefactoring ; public class RenameLocalGroovyVariableContribution extends JavaUIRefactoringContribution { public static final String ID = "<STR_LIT>" ; @ Override public Refactoring createRefactoring ( JavaRefactoringDescriptor descriptor , RefactoringStatus status ) throws CoreException { if ( descriptor instanceof RenameJavaElementDescriptor ) { IJavaElement elt = ( IJavaElement ) ReflectionUtils . getPrivateField ( RenameJavaElementDescriptor . class , "<STR_LIT>" , descriptor ) ; String newName = ( String ) ReflectionUtils . getPrivateField ( RenameJavaElementDescriptor . class , "<STR_LIT>" , descriptor ) ; if ( elt instanceof ILocalVariable && newName != null ) { ILocalVariable var = ( ILocalVariable ) elt ; return new RenameRefactoring ( new GroovyRenameLocalVariableProcessor ( var , newName , status ) ) ; } } return null ; } @ SuppressWarnings ( "<STR_LIT:unchecked>" ) @ Override public RefactoringDescriptor createDescriptor ( String id , String project , String description , String comment , Map arguments , int flags ) throws IllegalArgumentException { return new RenameJavaElementDescriptor ( id , project , description , comment , arguments , flags ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . rename ; import org . codehaus . groovy . eclipse . core . GroovyCore ; import org . codehaus . jdt . groovy . integration . internal . ISearchScopeExpander ; import org . eclipse . jdt . core . ICompilationUnit ; import org . eclipse . jdt . core . JavaModelException ; import org . eclipse . jdt . core . search . IJavaSearchScope ; import org . eclipse . jdt . core . search . SearchPattern ; import org . eclipse . jdt . core . search . SearchRequestor ; import org . eclipse . jdt . internal . corext . refactoring . CollectingSearchRequestor ; import org . eclipse . jdt . internal . corext . refactoring . RefactoringScopeFactory ; public class RefactoringSearchScopeExpander implements ISearchScopeExpander { public IJavaSearchScope expandSearchScope ( IJavaSearchScope scope , SearchPattern pattern , SearchRequestor requestor ) { if ( pattern . focus . getOpenable ( ) instanceof ICompilationUnit && requestor instanceof CollectingSearchRequestor ) { try { return RefactoringScopeFactory . create ( pattern . focus , false , true ) ; } catch ( JavaModelException e ) { GroovyCore . logException ( "<STR_LIT>" + pattern . focus . getElementName ( ) , e ) ; } } return scope ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . rename ; import org . codehaus . jdt . groovy . model . GroovyCompilationUnit ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . jdt . core . IJavaElement ; import org . eclipse . jdt . core . ILocalVariable ; import org . eclipse . jdt . core . IMember ; import org . eclipse . jdt . core . IType ; import org . eclipse . ltk . core . refactoring . Change ; import org . eclipse . ltk . core . refactoring . RefactoringStatus ; import org . eclipse . ltk . core . refactoring . participants . CheckConditionsContext ; import org . eclipse . ltk . core . refactoring . participants . RenameParticipant ; public class ForcePreviewParticipant extends RenameParticipant { private static boolean muted = false ; private static final String FIRST_MSG = "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" ; private static final String SECOND_MSG = "<STR_LIT>" + "<STR_LIT>" ; private IType type ; public ForcePreviewParticipant ( ) { } @ Override public RefactoringStatus checkConditions ( IProgressMonitor pm , CheckConditionsContext context ) throws OperationCanceledException { RefactoringStatus status = RefactoringStatus . createWarningStatus ( FIRST_MSG ) ; if ( shouldWarnAboutFileRename ( ) ) { status . addWarning ( SECOND_MSG ) ; } return status ; } @ Override public Change createChange ( IProgressMonitor pm ) throws CoreException , OperationCanceledException { return null ; } @ Override public String getName ( ) { return "<STR_LIT>" ; } @ Override protected boolean initialize ( Object element ) { if ( muted ) { return false ; } if ( element instanceof IMember || element instanceof ILocalVariable ) { IJavaElement member = ( IJavaElement ) element ; boolean groovyElement = member . getAncestor ( IJavaElement . COMPILATION_UNIT ) instanceof GroovyCompilationUnit ; if ( groovyElement && element instanceof IType ) { type = ( IType ) element ; } return groovyElement ; } return false ; } boolean shouldWarnAboutFileRename ( ) { if ( type != null ) { return type . equals ( type . getCompilationUnit ( ) . findPrimaryType ( ) ) ; } return false ; } public static void mute ( ) { muted = true ; } public static void unmute ( ) { muted = false ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . rename ; import java . util . HashMap ; import java . util . Map ; import org . codehaus . groovy . eclipse . refactoring . core . rename . renameLocal . GroovyRenameLocalVariableProcessor ; import org . codehaus . groovy . eclipse . refactoring . core . rename . renameLocal . RenameLocalGroovyVariableContribution ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jdt . core . IField ; import org . eclipse . jdt . core . IJavaElement ; import org . eclipse . jdt . core . ILocalVariable ; import org . eclipse . jdt . core . IMethod ; import org . eclipse . jdt . core . IType ; import org . eclipse . jdt . core . refactoring . IJavaRefactorings ; import org . eclipse . jdt . core . refactoring . descriptors . RenameJavaElementDescriptor ; import org . eclipse . jdt . groovy . core . util . ReflectionUtils ; import org . eclipse . jdt . internal . ui . refactoring . UserInterfaceManager ; import org . eclipse . jdt . internal . ui . refactoring . reorg . RenameLocalVariableWizard ; import org . eclipse . jdt . internal . ui . refactoring . reorg . RenameUserInterfaceManager ; import org . eclipse . jdt . internal . ui . refactoring . reorg . RenameUserInterfaceStarter ; import org . eclipse . jdt . ui . refactoring . RenameSupport ; import org . eclipse . ltk . core . refactoring . RefactoringDescriptor ; public class JavaRefactoringDispatcher { static { UserInterfaceManager uiManager = RenameUserInterfaceManager . getDefault ( ) ; ReflectionUtils . executePrivateMethod ( UserInterfaceManager . class , "<STR_LIT>" , new Class [ ] { Class . class , Class . class , Class . class } , uiManager , new Object [ ] { GroovyRenameLocalVariableProcessor . class , RenameUserInterfaceStarter . class , RenameLocalVariableWizard . class } ) ; } private IJavaElement element ; public JavaRefactoringDispatcher ( IJavaElement element ) { this . element = element ; } public RenameSupport dispatchJavaRenameRefactoring ( ) throws CoreException { if ( element instanceof IType ) { return createTypeRefactoring ( ( IType ) element ) ; } else if ( element instanceof IField ) { return createFieldRefactoring ( ( IField ) element ) ; } else if ( element instanceof IMethod ) { return createMethodRefactoring ( ( IMethod ) element ) ; } else if ( element instanceof ILocalVariable ) { return createLocalVariableRefactoring ( ) ; } return null ; } private RenameSupport createLocalVariableRefactoring ( ) throws CoreException { RenameJavaElementDescriptor descriptor = createDescriptorForLocalVariable ( ) ; return RenameSupport . create ( descriptor ) ; } public RenameJavaElementDescriptor createDescriptorForLocalVariable ( ) { Map < String , String > args = new HashMap < String , String > ( ) ; args . put ( "<STR_LIT:name>" , getNewName ( ) ) ; args . put ( "<STR_LIT>" , element . getHandleIdentifier ( ) ) ; RenameJavaElementDescriptor descriptor = new RenameJavaElementDescriptor ( IJavaRefactorings . RENAME_LOCAL_VARIABLE , element . getJavaProject ( ) . getElementName ( ) , "<STR_LIT>" + element . getElementName ( ) , null , args , RenameSupport . UPDATE_REFERENCES ) ; ReflectionUtils . setPrivateField ( RefactoringDescriptor . class , "<STR_LIT>" , descriptor , RenameLocalGroovyVariableContribution . ID ) ; return descriptor ; } private RenameSupport createTypeRefactoring ( IType type ) throws CoreException { return RenameSupport . create ( type , getNewName ( ) , RenameSupport . UPDATE_REFERENCES ) ; } private RenameSupport createFieldRefactoring ( IField field ) throws CoreException { return RenameSupport . create ( field , getNewName ( ) , RenameSupport . UPDATE_REFERENCES | RenameSupport . UPDATE_GETTER_METHOD | RenameSupport . UPDATE_SETTER_METHOD ) ; } private RenameSupport createMethodRefactoring ( IMethod method ) throws CoreException { return RenameSupport . create ( method , getNewName ( ) , RenameSupport . UPDATE_REFERENCES ) ; } private String newName ; public String getNewName ( ) { if ( newName != null ) { return newName ; } else { return element . getElementName ( ) ; } } public void setNewName ( String name ) { newName = name ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . rewriter ; import java . io . IOException ; import java . io . StringWriter ; import java . io . Writer ; import java . util . Arrays ; import java . util . Collection ; import java . util . Iterator ; import java . util . List ; import java . util . Map . Entry ; import java . util . Stack ; import org . codehaus . groovy . antlr . LineColumn ; import org . codehaus . groovy . ast . ASTNode ; import org . codehaus . groovy . ast . AnnotatedNode ; import org . codehaus . groovy . ast . AnnotationNode ; import org . codehaus . groovy . ast . ClassHelper ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . CodeVisitorSupport ; import org . codehaus . groovy . ast . CompileUnit ; import org . codehaus . groovy . ast . ConstructorNode ; import org . codehaus . groovy . ast . FieldNode ; import org . codehaus . groovy . ast . GenericsType ; import org . codehaus . groovy . ast . GroovyClassVisitor ; import org . codehaus . groovy . ast . ImportNode ; import org . codehaus . groovy . ast . MethodNode ; import org . codehaus . groovy . ast . ModuleNode ; import org . codehaus . groovy . ast . Parameter ; import org . codehaus . groovy . ast . PropertyNode ; import org . codehaus . groovy . ast . Variable ; import org . codehaus . groovy . ast . expr . ArgumentListExpression ; import org . codehaus . groovy . ast . expr . ArrayExpression ; import org . codehaus . groovy . ast . expr . AttributeExpression ; import org . codehaus . groovy . ast . expr . BinaryExpression ; import org . codehaus . groovy . ast . expr . BitwiseNegationExpression ; import org . codehaus . groovy . ast . expr . BooleanExpression ; import org . codehaus . groovy . ast . expr . CastExpression ; import org . codehaus . groovy . ast . expr . ClassExpression ; import org . codehaus . groovy . ast . expr . ClosureExpression ; import org . codehaus . groovy . ast . expr . ClosureListExpression ; import org . codehaus . groovy . ast . expr . ConstantExpression ; import org . codehaus . groovy . ast . expr . ConstructorCallExpression ; import org . codehaus . groovy . ast . expr . DeclarationExpression ; import org . codehaus . groovy . ast . expr . ElvisOperatorExpression ; import org . codehaus . groovy . ast . expr . Expression ; import org . codehaus . groovy . ast . expr . FieldExpression ; import org . codehaus . groovy . ast . expr . GStringExpression ; import org . codehaus . groovy . ast . expr . ListExpression ; import org . codehaus . groovy . ast . expr . MapEntryExpression ; import org . codehaus . groovy . ast . expr . MapExpression ; import org . codehaus . groovy . ast . expr . MethodCallExpression ; import org . codehaus . groovy . ast . expr . MethodPointerExpression ; import org . codehaus . groovy . ast . expr . NamedArgumentListExpression ; import org . codehaus . groovy . ast . expr . NotExpression ; import org . codehaus . groovy . ast . expr . PostfixExpression ; import org . codehaus . groovy . ast . expr . PrefixExpression ; import org . codehaus . groovy . ast . expr . PropertyExpression ; import org . codehaus . groovy . ast . expr . RangeExpression ; import org . codehaus . groovy . ast . expr . SpreadExpression ; import org . codehaus . groovy . ast . expr . SpreadMapExpression ; import org . codehaus . groovy . ast . expr . StaticMethodCallExpression ; import org . codehaus . groovy . ast . expr . TernaryExpression ; import org . codehaus . groovy . ast . expr . TupleExpression ; import org . codehaus . groovy . ast . expr . UnaryMinusExpression ; import org . codehaus . groovy . ast . expr . UnaryPlusExpression ; import org . codehaus . groovy . ast . expr . VariableExpression ; import org . codehaus . groovy . ast . stmt . AssertStatement ; import org . codehaus . groovy . ast . stmt . BlockStatement ; import org . codehaus . groovy . ast . stmt . BreakStatement ; import org . codehaus . groovy . ast . stmt . CaseStatement ; import org . codehaus . groovy . ast . stmt . CatchStatement ; import org . codehaus . groovy . ast . stmt . ContinueStatement ; import org . codehaus . groovy . ast . stmt . DoWhileStatement ; import org . codehaus . groovy . ast . stmt . EmptyStatement ; import org . codehaus . groovy . ast . stmt . ExpressionStatement ; import org . codehaus . groovy . ast . stmt . ForStatement ; import org . codehaus . groovy . ast . stmt . IfStatement ; import org . codehaus . groovy . ast . stmt . ReturnStatement ; import org . codehaus . groovy . ast . stmt . Statement ; import org . codehaus . groovy . ast . stmt . SwitchStatement ; import org . codehaus . groovy . ast . stmt . SynchronizedStatement ; import org . codehaus . groovy . ast . stmt . ThrowStatement ; import org . codehaus . groovy . ast . stmt . TryCatchStatement ; import org . codehaus . groovy . ast . stmt . WhileStatement ; import org . codehaus . groovy . eclipse . core . GroovyCore ; import org . codehaus . groovy . eclipse . refactoring . core . utils . FilePartReader ; import org . codehaus . groovy . eclipse . refactoring . core . utils . ImportResolver ; import org . codehaus . groovy . syntax . Token ; import org . codehaus . groovy . syntax . Types ; import org . eclipse . jdt . core . Signature ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . objectweb . asm . Opcodes ; public class ASTWriter extends CodeVisitorSupport implements GroovyClassVisitor , Opcodes { protected StringBuilder groovyCode ; private String lineDelimiter ; protected Stack < ASTNode > nodeStack = new Stack < ASTNode > ( ) ; private final ModuleNode root ; private int lineOfPreviousNode = <NUM_LIT:1> ; private int lineOfCurrentNode = <NUM_LIT:1> ; private int columnOffset = <NUM_LIT:0> ; private int caseCount = <NUM_LIT:0> ; private boolean inElseBlock = false ; private final IDocument currentDocument ; private int lineOffset = <NUM_LIT:0> ; private boolean explizitModifier = false ; private String modifier = "<STR_LIT>" ; private int linesSinceFirstAnnotation = <NUM_LIT:0> ; private DeclarationExpression previousDeclaration = null ; public ASTWriter ( ModuleNode root , int lineOffset , IDocument currentDocument ) { this ( root , currentDocument ) ; setLineOffset ( lineOffset ) ; } public ASTWriter ( ModuleNode root , IDocument currentDocument ) { groovyCode = new StringBuilder ( ) ; try { if ( currentDocument != null ) { lineDelimiter = currentDocument . getLineDelimiter ( <NUM_LIT:0> ) ; } } catch ( BadLocationException e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; } if ( lineDelimiter == null ) { lineDelimiter = System . getProperty ( "<STR_LIT>" ) ; } this . root = root ; this . currentDocument = currentDocument ; } public ASTWriter ( Expression e ) { this ( createModuleNode ( e ) , null ) ; } private static ModuleNode createModuleNode ( Expression e ) { ModuleNode module = new ModuleNode ( ( CompileUnit ) null ) ; module . addStatement ( new ExpressionStatement ( e ) ) ; module . setDescription ( "<STR_LIT>" ) ; return module ; } public void setStartOffset ( int startOffset ) { this . columnOffset = startOffset ; printColumnOffset ( ) ; } public void setLineOffset ( int offset ) { this . lineOffset = offset ; } public void setModifierToUse ( String mod ) { this . modifier = mod ; explizitModifier = true ; } public void insertLineFeed ( ) { groovyCode . append ( lineDelimiter ) ; } public String getGroovyCode ( ) { return groovyCode . toString ( ) ; } public void visitRoot ( ) { preVisitStatement ( root ) ; if ( root . getPackageName ( ) != null ) { groovyCode . append ( "<STR_LIT>" ) ; String packageName = root . getPackageName ( ) ; groovyCode . append ( packageName . substring ( <NUM_LIT:0> , packageName . length ( ) - <NUM_LIT:1> ) ) ; } printImports ( root . getStarImports ( ) ) ; printImports ( root . getImports ( ) ) ; printImports ( root . getStaticImports ( ) . values ( ) ) ; printImports ( root . getStaticStarImports ( ) . values ( ) ) ; if ( ! root . getStatementBlock ( ) . isEmpty ( ) ) { visitBlockStatement ( root . getStatementBlock ( ) ) ; } List < ClassNode > classes = root . getClasses ( ) ; for ( ClassNode classNode : classes ) { if ( ! classNode . isScript ( ) ) { visitClass ( classNode ) ; } else { List < MethodNode > methods = root . getMethods ( ) ; for ( MethodNode method : methods ) { visitMethod ( method ) ; } } } postVisitStatement ( root ) ; } private void printImports ( Collection < ImportNode > imports ) { for ( Iterator < ImportNode > impIter = imports . iterator ( ) ; impIter . hasNext ( ) ; ) { ImportNode imp = impIter . next ( ) ; groovyCode . append ( imp . getText ( ) ) ; if ( impIter . hasNext ( ) ) { insertLineFeed ( ) ; lineOfPreviousNode ++ ; } } } public void visitClass ( ClassNode node ) { visitAnnotations ( node ) ; preVisitStatement ( node ) ; linesSinceFirstAnnotation = <NUM_LIT:0> ; if ( node . getSuperClass ( ) . getName ( ) . equals ( "<STR_LIT>" ) ) { writeEnum ( node ) ; return ; } if ( node . isInterface ( ) ) { groovyCode . append ( "<STR_LIT>" ) ; } else { groovyCode . append ( ASTWriterHelper . getAccModifier ( node . getModifiers ( ) , ASTWriterHelper . MOD_CLASS ) ) ; groovyCode . append ( "<STR_LIT>" ) ; } printType ( node ) ; if ( ! node . getSuperClass ( ) . getNameWithoutPackage ( ) . equals ( "<STR_LIT>" ) ) { groovyCode . append ( "<STR_LIT>" ) ; groovyCode . append ( node . getSuperClass ( ) . getNameWithoutPackage ( ) ) ; } if ( node . getInterfaces ( ) . length > <NUM_LIT:0> ) { groovyCode . append ( "<STR_LIT>" ) ; ClassNode [ ] theInterfaces = node . getInterfaces ( ) ; for ( int i = <NUM_LIT:0> ; i < theInterfaces . length ; i ++ ) { groovyCode . append ( theInterfaces [ i ] . getNameWithoutPackage ( ) ) ; if ( i < theInterfaces . length - <NUM_LIT:1> ) { groovyCode . append ( "<STR_LIT:U+002CU+0020>" ) ; } } } preVisitStatementOpenBlock ( node ) ; node . visitContents ( this ) ; postVisitStatementCloseBlock ( node ) ; postVisitStatement ( node ) ; } private void writeEnum ( ClassNode node ) { groovyCode . append ( "<STR_LIT>" ) ; groovyCode . append ( node . getName ( ) + "<STR_LIT:U+0020>" ) ; groovyCode . append ( '<CHAR_LIT>' ) ; for ( int i = <NUM_LIT:0> ; i < node . getFields ( ) . size ( ) ; i ++ ) { FieldNode fn = ( FieldNode ) node . getFields ( ) . get ( i ) ; if ( i == <NUM_LIT:0> ) groovyCode . append ( fn . getName ( ) ) ; else { if ( ! fn . getName ( ) . startsWith ( "<STR_LIT:$>" ) ) { groovyCode . append ( "<STR_LIT:U+002CU+0020>" + fn . getName ( ) ) ; } } } groovyCode . append ( '<CHAR_LIT:}>' ) ; postVisitStatement ( node ) ; } public void visitAnnotations ( AnnotatedNode node ) { boolean first = true ; List < AnnotationNode > annotionMap = node . getAnnotations ( ) ; if ( annotionMap . isEmpty ( ) ) return ; Iterator < AnnotationNode > it = annotionMap . iterator ( ) ; while ( it . hasNext ( ) ) { AnnotationNode an = ( AnnotationNode ) it . next ( ) ; int extra = <NUM_LIT:1> ; linesSinceFirstAnnotation += ( an . getLastLineNumber ( ) + extra ) - an . getLineNumber ( ) ; preVisitStatement ( an ) ; groovyCode . append ( "<STR_LIT:@>" ) ; groovyCode . append ( an . getClassNode ( ) . getNameWithoutPackage ( ) ) ; if ( an . isBuiltIn ( ) ) continue ; for ( Entry < String , Expression > member : an . getMembers ( ) . entrySet ( ) ) { Expression memberValue = member . getValue ( ) ; preVisitExpression ( memberValue ) ; if ( first ) { first = false ; groovyCode . append ( "<STR_LIT>" ) ; } else { groovyCode . append ( "<STR_LIT>" ) ; } memberValue . visit ( this ) ; if ( ! first ) { groovyCode . append ( "<STR_LIT:)>" ) ; } postVisitExpression ( memberValue ) ; } postVisitStatement ( an ) ; } } protected void visitClassCodeContainer ( Statement code ) { if ( code != null ) { code . visit ( this ) ; } } protected void visitConstructorOrMethod ( MethodNode node , boolean isConstructor ) { visitAnnotations ( node ) ; preVisitStatement ( node ) ; linesSinceFirstAnnotation = <NUM_LIT:0> ; printMethodHead ( node ) ; Statement code = node . getCode ( ) ; if ( code != null ) { code . setSourcePosition ( node ) ; visitClassCodeContainer ( code ) ; } postVisitStatement ( node ) ; } public void printMethodHead ( MethodNode node ) { if ( node . isVoidMethod ( ) ) { if ( explizitModifier ) { groovyCode . append ( modifier ) ; groovyCode . append ( "<STR_LIT:U+0020>" ) ; } groovyCode . append ( "<STR_LIT>" ) ; } else { if ( explizitModifier ) { groovyCode . append ( modifier ) ; groovyCode . append ( "<STR_LIT:U+0020>" ) ; } else { groovyCode . append ( ASTWriterHelper . getAccModifier ( node . getModifiers ( ) , ASTWriterHelper . MOD_METHOD ) ) ; } if ( ! node . isDynamicReturnType ( ) ) { printType ( node . getReturnType ( ) ) ; groovyCode . append ( "<STR_LIT:U+0020>" ) ; } } groovyCode . append ( node . getName ( ) ) ; groovyCode . append ( "<STR_LIT:(>" ) ; Parameter [ ] parameters = node . getParameters ( ) ; printParameters ( parameters ) ; groovyCode . append ( "<STR_LIT:)>" ) ; if ( node . getExceptions ( ) != null ) { if ( node . getExceptions ( ) . length > <NUM_LIT:0> ) { groovyCode . append ( "<STR_LIT>" ) ; for ( int i = <NUM_LIT:0> ; i < node . getExceptions ( ) . length ; i ++ ) { if ( i == <NUM_LIT:0> ) groovyCode . append ( node . getExceptions ( ) [ i ] . getNameWithoutPackage ( ) ) ; else groovyCode . append ( "<STR_LIT:U+002CU+0020>" + node . getExceptions ( ) [ i ] . getNameWithoutPackage ( ) ) ; } } } } private void printParameters ( Parameter [ ] parameters ) { for ( int i = <NUM_LIT:0> ; i < parameters . length ; i ++ ) { Parameter parameter = parameters [ i ] ; visitAnnotations ( parameter ) ; if ( ! parameter . getAnnotations ( ) . isEmpty ( ) ) { groovyCode . append ( "<STR_LIT:U+0020>" ) ; } linesSinceFirstAnnotation = <NUM_LIT:0> ; if ( ! parameter . isDynamicTyped ( ) ) { printType ( parameter . getOriginType ( ) ) ; groovyCode . append ( "<STR_LIT:U+0020>" ) ; } groovyCode . append ( parameter . getName ( ) ) ; if ( parameter . hasInitialExpression ( ) ) { groovyCode . append ( "<STR_LIT:=>" ) ; parameter . getInitialExpression ( ) . visit ( this ) ; } if ( i < parameters . length - <NUM_LIT:1> ) { groovyCode . append ( "<STR_LIT:U+002CU+0020>" ) ; } } } public void visitConstructor ( ConstructorNode node ) { visitConstructorOrMethod ( node , true ) ; } public void visitMethod ( MethodNode node ) { visitConstructorOrMethod ( node , false ) ; } public void visitField ( FieldNode node ) { if ( ! node . getName ( ) . startsWith ( "<STR_LIT:$>" ) ) { visitAnnotations ( node ) ; preVisitStatement ( node ) ; if ( ASTWriterHelper . isProperty ( node ) ) { if ( ! node . isDynamicTyped ( ) ) { if ( node . isStatic ( ) ) { groovyCode . append ( "<STR_LIT>" ) ; } printType ( node . getOriginType ( ) ) ; } else { groovyCode . append ( "<STR_LIT>" ) ; if ( node . isStatic ( ) ) { groovyCode . append ( "<STR_LIT>" ) ; } } groovyCode . append ( "<STR_LIT:U+0020>" ) ; } else { groovyCode . append ( ASTWriterHelper . getAccModifier ( node . getModifiers ( ) , ASTWriterHelper . MOD_FIELD ) ) ; if ( ! node . isDynamicTyped ( ) ) { printType ( node . getOriginType ( ) ) ; groovyCode . append ( "<STR_LIT:U+0020>" ) ; } } groovyCode . append ( node . getName ( ) ) ; Expression init = node . getInitialExpression ( ) ; if ( init != null ) { if ( init . getLineNumber ( ) != - <NUM_LIT:1> ) { groovyCode . append ( "<STR_LIT:U+0020=U+0020>" ) ; init . visit ( this ) ; } } postVisitStatement ( node ) ; } } public void visitProperty ( PropertyNode node ) { } @ Override public void visitAssertStatement ( AssertStatement statement ) { preVisitStatement ( statement ) ; groovyCode . append ( "<STR_LIT>" ) ; super . visitAssertStatement ( statement ) ; postVisitStatement ( statement ) ; } @ Override public void visitBlockStatement ( BlockStatement block ) { if ( getTop ( ) instanceof CaseStatement || getTop ( ) instanceof SwitchStatement || getTop ( ) instanceof BlockStatement || getTop ( ) instanceof ModuleNode ) { preVisitStatement ( block ) ; super . visitBlockStatement ( block ) ; postVisitStatement ( block ) ; } else { preVisitStatementOpenBlock ( block ) ; if ( getParent ( ) instanceof ClosureExpression ) { ClosureExpression closure = ( ClosureExpression ) getParent ( ) ; Parameter [ ] parameters = closure . getParameters ( ) ; if ( parameters . length > <NUM_LIT:0> ) { printParameters ( parameters ) ; groovyCode . append ( "<STR_LIT>" ) ; } } super . visitBlockStatement ( block ) ; postVisitStatementCloseBlock ( block ) ; } } @ Override public void visitBreakStatement ( BreakStatement statement ) { preVisitStatement ( statement ) ; groovyCode . append ( "<STR_LIT>" ) ; if ( statement . getLabel ( ) != null ) { groovyCode . append ( "<STR_LIT:U+0020>" + statement . getLabel ( ) ) ; } super . visitBreakStatement ( statement ) ; postVisitStatement ( statement ) ; } @ Override public void visitCaseStatement ( CaseStatement statement ) { preVisitStatement ( statement ) ; groovyCode . append ( "<STR_LIT>" ) ; super . visitCaseStatement ( statement ) ; postVisitStatement ( statement ) ; } @ Override public void visitCatchStatement ( CatchStatement statement ) { preVisitStatement ( statement ) ; groovyCode . append ( "<STR_LIT>" ) ; ClassNode typOfException = statement . getExceptionType ( ) ; Parameter eVariable = statement . getVariable ( ) ; if ( ! eVariable . isDynamicTyped ( ) ) { printType ( typOfException ) ; groovyCode . append ( "<STR_LIT:U+0020>" ) ; } groovyCode . append ( eVariable . getName ( ) ) ; groovyCode . append ( "<STR_LIT:)>" ) ; super . visitCatchStatement ( statement ) ; postVisitStatement ( statement ) ; } @ Override public void visitContinueStatement ( ContinueStatement statement ) { preVisitStatement ( statement ) ; groovyCode . append ( "<STR_LIT>" ) ; super . visitContinueStatement ( statement ) ; postVisitStatement ( statement ) ; } @ Override public void visitDoWhileLoop ( DoWhileStatement loop ) { preVisitStatementOpenBlock ( loop ) ; super . visitDoWhileLoop ( loop ) ; postVisitStatementCloseBlock ( loop ) ; } @ Override public void visitExpressionStatement ( ExpressionStatement statement ) { preVisitStatement ( statement ) ; if ( statement . getStatementLabel ( ) != null ) { groovyCode . append ( statement . getStatementLabel ( ) + "<STR_LIT::U+0020>" ) ; } if ( statement . getExpression ( ) instanceof MethodCallExpression ) { MethodCallExpression methCallExpr = ( MethodCallExpression ) statement . getExpression ( ) ; if ( ! methCallExpr . isImplicitThis ( ) ) { methCallExpr . getObjectExpression ( ) . visit ( this ) ; ArgumentListExpression ale = ( ( ArgumentListExpression ) methCallExpr . getArguments ( ) ) ; printArgumentsOfaMethodCall ( methCallExpr , ale ) ; } else { super . visitExpressionStatement ( statement ) ; } } else { super . visitExpressionStatement ( statement ) ; } postVisitStatement ( statement ) ; } private void printArgumentsOfaMethodCall ( MethodCallExpression methCallExpr , ArgumentListExpression ale ) { if ( ale != null ) { groovyCode . append ( '<CHAR_LIT:.>' ) ; groovyCode . append ( methCallExpr . getMethod ( ) . getText ( ) ) ; if ( ale . getExpressions ( ) . size ( ) >= <NUM_LIT:1> ) { List < Expression > listOfAllExpressions = ale . getExpressions ( ) ; ArgumentListExpression listOfMethodArguments = new ArgumentListExpression ( ) ; ClosureExpression closure = null ; for ( Expression expr : listOfAllExpressions ) { if ( expr instanceof ClosureExpression ) { closure = ( ClosureExpression ) expr ; } else { listOfMethodArguments . addExpression ( expr ) ; } } if ( listOfMethodArguments . getExpressions ( ) . size ( ) >= <NUM_LIT:1> ) { printArgumentsOfaMethod ( listOfMethodArguments ) ; } if ( closure != null ) { closure . visit ( this ) ; } } else { groovyCode . append ( "<STR_LIT>" ) ; } } } private void printArgumentsOfaMethod ( ArgumentListExpression methCallExpr ) { groovyCode . append ( '<CHAR_LIT:(>' ) ; methCallExpr . visit ( this ) ; groovyCode . append ( '<CHAR_LIT:)>' ) ; } @ Override public void visitForLoop ( ForStatement forLoop ) { preVisitStatement ( forLoop ) ; groovyCode . append ( "<STR_LIT>" ) ; if ( ! forLoop . getVariable ( ) . getName ( ) . equals ( "<STR_LIT>" ) ) { groovyCode . append ( "<STR_LIT:(>" ) ; groovyCode . append ( forLoop . getVariable ( ) . getName ( ) ) ; groovyCode . append ( "<STR_LIT>" ) ; forLoop . getCollectionExpression ( ) . visit ( this ) ; groovyCode . append ( "<STR_LIT:)>" ) ; forLoop . getLoopBlock ( ) . visit ( this ) ; } else { forLoop . getCollectionExpression ( ) . visit ( this ) ; if ( forLoop . getLoopBlock ( ) instanceof BlockStatement ) { forLoop . getLoopBlock ( ) . visit ( this ) ; } else { columnOffset ++ ; forLoop . getLoopBlock ( ) . visit ( this ) ; columnOffset -- ; } } postVisitStatement ( forLoop ) ; } @ Override public void visitIfElse ( IfStatement ifElse ) { preVisitStatement ( ifElse ) ; groovyCode . append ( "<STR_LIT>" ) ; ifElse . getBooleanExpression ( ) . visit ( this ) ; groovyCode . append ( "<STR_LIT:)>" ) ; if ( ! ( ifElse . getIfBlock ( ) instanceof BlockStatement ) ) { columnOffset ++ ; ifElse . getIfBlock ( ) . visit ( this ) ; columnOffset -- ; } else { ifElse . getIfBlock ( ) . visit ( this ) ; } if ( ! ( ifElse . getElseBlock ( ) instanceof EmptyStatement ) ) { if ( ! ( ifElse . getElseBlock ( ) instanceof BlockStatement ) && ! ( ifElse . getElseBlock ( ) instanceof IfStatement ) ) { positioningCursor ( ) ; insertLineFeed ( ) ; groovyCode . append ( "<STR_LIT>" ) ; lineOfPreviousNode ++ ; columnOffset ++ ; ifElse . getElseBlock ( ) . visit ( this ) ; columnOffset -- ; } else { inElseBlock = true ; ifElse . getElseBlock ( ) . visit ( this ) ; } } postVisitStatement ( ifElse ) ; } @ Override public void visitReturnStatement ( ReturnStatement statement ) { if ( ! shouldIgnoreReturn ( ) ) { preVisitStatement ( statement ) ; groovyCode . append ( "<STR_LIT>" ) ; super . visitReturnStatement ( statement ) ; postVisitStatement ( statement ) ; } } private boolean shouldIgnoreReturn ( ) { if ( root . getClasses ( ) . size ( ) == <NUM_LIT:1> ) { ClassNode clazz = ( ClassNode ) root . getClasses ( ) . get ( <NUM_LIT:0> ) ; if ( clazz . isScript ( ) ) { MethodNode runMethod = clazz . getMethod ( "<STR_LIT>" , new Parameter [ <NUM_LIT:0> ] ) ; if ( runMethod != null ) { Statement s = runMethod . getCode ( ) ; if ( s instanceof BlockStatement ) { BlockStatement body = ( BlockStatement ) s ; if ( body . getStatements ( ) . size ( ) == <NUM_LIT:1> && body . getStatements ( ) . get ( <NUM_LIT:0> ) instanceof ReturnStatement ) { ReturnStatement ret = ( ReturnStatement ) body . getStatements ( ) . get ( <NUM_LIT:0> ) ; return ret . getExpression ( ) instanceof ConstantExpression && ( ( ConstantExpression ) ret . getExpression ( ) ) . getText ( ) . equals ( "<STR_LIT:null>" ) ; } } } } } return false ; } @ Override public void visitSwitch ( SwitchStatement statement ) { preVisitStatement ( statement ) ; groovyCode . append ( "<STR_LIT>" ) ; statement . getExpression ( ) . visit ( this ) ; groovyCode . append ( "<STR_LIT:)>" ) ; List < CaseStatement > list = statement . getCaseStatements ( ) ; if ( list != null ) { for ( CaseStatement caseStatement : list ) { caseStatement . visit ( this ) ; } } statement . getDefaultStatement ( ) . visit ( this ) ; postVisitStatementCloseBlock ( statement ) ; } @ Override public void visitSynchronizedStatement ( SynchronizedStatement statement ) { preVisitStatement ( statement ) ; groovyCode . append ( "<STR_LIT>" ) ; statement . getExpression ( ) . visit ( this ) ; groovyCode . append ( "<STR_LIT:)>" ) ; statement . getCode ( ) . visit ( this ) ; postVisitStatement ( statement ) ; } @ Override public void visitThrowStatement ( ThrowStatement statement ) { preVisitStatement ( statement ) ; groovyCode . append ( "<STR_LIT>" ) ; super . visitThrowStatement ( statement ) ; postVisitStatement ( statement ) ; } @ Override public void visitTryCatchFinally ( TryCatchStatement statement ) { preVisitStatement ( statement ) ; groovyCode . append ( "<STR_LIT>" ) ; statement . getTryStatement ( ) . visit ( this ) ; List < CatchStatement > list = statement . getCatchStatements ( ) ; if ( list != null ) { for ( CatchStatement catchStatement : list ) { catchStatement . visit ( this ) ; } } if ( ! statement . getFinallyStatement ( ) . isEmpty ( ) ) { groovyCode . append ( "<STR_LIT>" ) ; statement . getFinallyStatement ( ) . visit ( this ) ; } postVisitStatement ( statement ) ; } @ Override public void visitWhileLoop ( WhileStatement loop ) { preVisitStatement ( loop ) ; groovyCode . append ( "<STR_LIT>" ) ; loop . getBooleanExpression ( ) . visit ( this ) ; groovyCode . append ( "<STR_LIT:)>" ) ; if ( loop . getLoopBlock ( ) instanceof BlockStatement ) { loop . getLoopBlock ( ) . visit ( this ) ; } else { columnOffset ++ ; loop . getLoopBlock ( ) . visit ( this ) ; columnOffset -- ; } postVisitStatement ( loop ) ; } @ Override public void visitMethodCallExpression ( MethodCallExpression call ) { preVisitExpression ( call ) ; if ( ! call . getText ( ) . contains ( "<STR_LIT>" ) ) { call . getObjectExpression ( ) . visit ( this ) ; groovyCode . append ( "<STR_LIT:.>" ) ; } call . getMethod ( ) . visit ( this ) ; groovyCode . append ( "<STR_LIT:(>" ) ; call . getArguments ( ) . visit ( this ) ; groovyCode . append ( "<STR_LIT:)>" ) ; postVisitExpression ( call ) ; } @ Override public void visitStaticMethodCallExpression ( StaticMethodCallExpression call ) { preVisitExpression ( call ) ; groovyCode . append ( call . getMethod ( ) ) ; groovyCode . append ( "<STR_LIT:(>" ) ; call . getArguments ( ) . visit ( this ) ; groovyCode . append ( "<STR_LIT:)>" ) ; postVisitExpression ( call ) ; } @ Override public void visitConstructorCallExpression ( ConstructorCallExpression call ) { preVisitExpression ( call ) ; groovyCode . append ( "<STR_LIT>" ) ; printType ( call . getType ( ) ) ; groovyCode . append ( "<STR_LIT:(>" ) ; call . getArguments ( ) . visit ( this ) ; groovyCode . append ( "<STR_LIT:)>" ) ; postVisitExpression ( call ) ; } @ Override public void visitBinaryExpression ( BinaryExpression expression ) { boolean writeParanthesis = false ; preVisitExpression ( expression ) ; Token operation = expression . getOperation ( ) ; if ( operation . getType ( ) == Types . LEFT_SQUARE_BRACKET ) { expression . getLeftExpression ( ) . visit ( this ) ; groovyCode . append ( "<STR_LIT:[>" ) ; expression . getRightExpression ( ) . visit ( this ) ; groovyCode . append ( "<STR_LIT:]>" ) ; } else { LineColumn coords = new LineColumn ( expression . getLineNumber ( ) , expression . getColumnNumber ( ) ) ; if ( ! ( getParent ( ) instanceof DeclarationExpression ) && FilePartReader . readForwardFromCoordinate ( currentDocument , coords ) . startsWith ( "<STR_LIT:(>" ) ) { groovyCode . append ( "<STR_LIT:(>" ) ; writeParanthesis = true ; } expression . getLeftExpression ( ) . visit ( this ) ; if ( expression . getRightExpression ( ) . getText ( ) != "<STR_LIT:null>" ) { groovyCode . append ( "<STR_LIT:U+0020>" ) ; groovyCode . append ( operation . getText ( ) ) ; groovyCode . append ( "<STR_LIT:U+0020>" ) ; expression . getRightExpression ( ) . visit ( this ) ; } if ( writeParanthesis ) { groovyCode . append ( "<STR_LIT:)>" ) ; } } postVisitExpression ( expression ) ; } @ Override public void visitTernaryExpression ( TernaryExpression expression ) { expression . getBooleanExpression ( ) . visit ( this ) ; groovyCode . append ( "<STR_LIT>" ) ; expression . getTrueExpression ( ) . visit ( this ) ; groovyCode . append ( "<STR_LIT:U+0020:U+0020>" ) ; expression . getFalseExpression ( ) . visit ( this ) ; } @ Override public void visitPostfixExpression ( PostfixExpression expression ) { preVisitExpression ( expression ) ; super . visitPostfixExpression ( expression ) ; groovyCode . append ( expression . getOperation ( ) . getText ( ) ) ; postVisitExpression ( expression ) ; } @ Override public void visitPrefixExpression ( PrefixExpression expression ) { preVisitExpression ( expression ) ; groovyCode . append ( expression . getOperation ( ) . getText ( ) ) ; super . visitPrefixExpression ( expression ) ; postVisitExpression ( expression ) ; } @ Override public void visitBooleanExpression ( BooleanExpression expression ) { preVisitExpression ( expression ) ; super . visitBooleanExpression ( expression ) ; postVisitExpression ( expression ) ; } @ Override public void visitNotExpression ( NotExpression expression ) { preVisitExpression ( expression ) ; printExpression ( "<STR_LIT:!>" , expression , "<STR_LIT>" ) ; postVisitExpression ( expression ) ; } @ Override public void visitClosureExpression ( ClosureExpression expression ) { preVisitExpression ( expression ) ; expression . getCode ( ) . setSourcePosition ( expression ) ; expression . getCode ( ) . visit ( this ) ; postVisitExpression ( expression ) ; } @ Override public void visitTupleExpression ( TupleExpression expression ) { visitListOfExpressions ( expression . getExpressions ( ) ) ; } @ Override public void visitListExpression ( ListExpression expression ) { preVisitExpression ( expression ) ; groovyCode . append ( "<STR_LIT:[>" ) ; visitListOfExpressions ( expression . getExpressions ( ) , "<STR_LIT:U+002C>" ) ; groovyCode . append ( "<STR_LIT:]>" ) ; postVisitExpression ( expression ) ; } @ Override public void visitArrayExpression ( ArrayExpression expression ) { preVisitExpression ( expression ) ; visitListOfExpressions ( expression . getExpressions ( ) ) ; groovyCode . append ( "<STR_LIT>" ) ; String typeName = expression . getType ( ) . getNameWithoutPackage ( ) ; if ( typeName . startsWith ( "<STR_LIT:[>" ) ) { typeName = Signature . getElementType ( typeName ) ; typeName = Signature . getSignatureSimpleName ( typeName ) ; } groovyCode . append ( typeName ) ; visitListOfExpressions ( expression . getSizeExpression ( ) , "<STR_LIT>" ) ; postVisitExpression ( expression ) ; } @ Override public void visitMapExpression ( MapExpression expression ) { boolean isMapList = ! ( expression instanceof NamedArgumentListExpression ) ; preVisitExpression ( expression ) ; List < MapEntryExpression > mapEntries = expression . getMapEntryExpressions ( ) ; if ( isMapList ) { groovyCode . append ( "<STR_LIT:[>" ) ; } if ( ! mapEntries . isEmpty ( ) ) { visitListOfExpressions ( mapEntries , "<STR_LIT:U+002C>" ) ; } else { groovyCode . append ( "<STR_LIT::>" ) ; } if ( isMapList ) groovyCode . append ( "<STR_LIT:]>" ) ; postVisitExpression ( expression ) ; } @ Override public void visitMapEntryExpression ( MapEntryExpression expression ) { preVisitExpression ( expression ) ; expression . getKeyExpression ( ) . visit ( this ) ; groovyCode . append ( "<STR_LIT::>" ) ; expression . getValueExpression ( ) . visit ( this ) ; postVisitExpression ( expression ) ; } @ Override public void visitRangeExpression ( RangeExpression expression ) { preVisitExpression ( expression ) ; expression . getFrom ( ) . visit ( this ) ; groovyCode . append ( "<STR_LIT>" ) ; if ( ! expression . isInclusive ( ) ) { groovyCode . append ( "<STR_LIT:<>" ) ; } expression . getTo ( ) . visit ( this ) ; postVisitExpression ( expression ) ; } @ Override public void visitSpreadExpression ( SpreadExpression expression ) { preVisitExpression ( expression ) ; groovyCode . append ( "<STR_LIT:*>" ) ; super . visitSpreadExpression ( expression ) ; postVisitExpression ( expression ) ; } @ Override public void visitSpreadMapExpression ( SpreadMapExpression expression ) { preVisitExpression ( expression ) ; groovyCode . append ( "<STR_LIT:*>" ) ; postVisitExpression ( expression ) ; } @ Override public void visitMethodPointerExpression ( MethodPointerExpression expression ) { preVisitStatement ( expression ) ; expression . getExpression ( ) . visit ( this ) ; groovyCode . append ( "<STR_LIT>" ) ; expression . getMethodName ( ) . visit ( this ) ; postVisitStatement ( expression ) ; } @ Override public void visitBitwiseNegationExpression ( BitwiseNegationExpression expression ) { preVisitExpression ( expression ) ; groovyCode . append ( "<STR_LIT>" ) ; expression . getExpression ( ) . visit ( this ) ; postVisitExpression ( expression ) ; } @ Override public void visitCastExpression ( CastExpression expression ) { preVisitExpression ( expression ) ; groovyCode . append ( "<STR_LIT:(>" ) ; printType ( expression . getType ( ) ) ; groovyCode . append ( "<STR_LIT:)>" ) ; super . visitCastExpression ( expression ) ; postVisitExpression ( expression ) ; } @ Override public void visitConstantExpression ( ConstantExpression expression ) { preVisitExpression ( expression ) ; String pre = "<STR_LIT>" ; String post = "<STR_LIT>" ; ASTNode parent = getParent ( ) ; if ( parent instanceof AssertStatement && expression . getText ( ) != "<STR_LIT:null>" ) { pre = "<STR_LIT>" ; } if ( parent instanceof DeclarationExpression || parent instanceof FieldNode ) { if ( expression . getType ( ) . equals ( ClassHelper . Float_TYPE ) ) { post += "<STR_LIT:f>" ; } else if ( expression . getType ( ) . equals ( ClassHelper . Double_TYPE ) ) { post += "<STR_LIT:d>" ; } else if ( expression . getType ( ) . equals ( ClassHelper . BigInteger_TYPE ) ) { post += "<STR_LIT>" ; } else if ( expression . getType ( ) . equals ( ClassHelper . Long_TYPE ) ) { post += "<STR_LIT>" ; } } if ( constExprIsAString ( expression ) ) { LineColumn coords = new LineColumn ( expression . getLineNumber ( ) , expression . getColumnNumber ( ) ) ; String stringMarker = ASTWriterHelper . getStringMarker ( currentDocument , coords ) ; pre += stringMarker ; printExpression ( pre , expression , stringMarker ) ; if ( stringMarker . length ( ) == <NUM_LIT:3> ) { lineOfPreviousNode += expression . getLastLineNumber ( ) - expression . getLineNumber ( ) ; } } else { printExpression ( pre , expression , post ) ; } postVisitExpression ( expression ) ; } private boolean constExprIsAString ( ConstantExpression expression ) { return expression . getType ( ) . getName ( ) == "<STR_LIT>" && ! ( getParent ( ) instanceof MethodCallExpression ) && ! ( getParent ( ) instanceof GStringExpression ) && ! ( getParent ( ) instanceof MethodPointerExpression ) ; } @ Override public void visitClassExpression ( ClassExpression expression ) { preVisitExpression ( expression ) ; printType ( expression . getType ( ) ) ; postVisitExpression ( expression ) ; } @ Override public void visitVariableExpression ( VariableExpression expression ) { getParent ( ) ; preVisitExpression ( expression ) ; LineColumn coords = new LineColumn ( expression . getLineNumber ( ) , expression . getColumnNumber ( ) ) ; if ( FilePartReader . readForwardFromCoordinate ( currentDocument , coords ) . startsWith ( "<STR_LIT:(>" ) ) { printExpression ( "<STR_LIT:(>" , expression , "<STR_LIT:)>" ) ; } else { printExpression ( expression ) ; } postVisitExpression ( expression ) ; } @ Override public void visitDeclarationExpression ( DeclarationExpression expression ) { preVisitExpression ( expression ) ; VariableExpression variable = ( VariableExpression ) expression . getLeftExpression ( ) ; Variable accessedVariable = variable . getAccessedVariable ( ) == null ? variable : variable . getAccessedVariable ( ) ; if ( previousDeclaration != null ) { if ( previousDeclaration . getVariableExpression ( ) . getLineNumber ( ) != expression . getVariableExpression ( ) . getLineNumber ( ) ) { if ( ! accessedVariable . isDynamicTyped ( ) ) { printType ( variable . getOriginType ( ) ) ; } else { groovyCode . append ( "<STR_LIT>" ) ; } } else { groovyCode . append ( "<STR_LIT:U+002C>" ) ; } } else { if ( ! accessedVariable . isDynamicTyped ( ) ) { printType ( variable . getOriginType ( ) ) ; } else { groovyCode . append ( "<STR_LIT>" ) ; } } groovyCode . append ( "<STR_LIT:U+0020>" ) ; visitBinaryExpression ( expression ) ; previousDeclaration = expression ; postVisitExpression ( expression ) ; } private void printType ( ClassNode type ) { if ( type . isArray ( ) ) { printArray ( type ) ; } else { groovyCode . append ( ImportResolver . getResolvedClassName ( root , type , true ) ) ; if ( type . isUsingGenerics ( ) ) { GenericsType [ ] genericTypes = type . getGenericsTypes ( ) ; if ( genericTypes != null ) { groovyCode . append ( "<STR_LIT:<>" ) ; for ( GenericsType generic : Arrays . asList ( genericTypes ) ) { printGenericsType ( generic ) ; } groovyCode . append ( "<STR_LIT:>>" ) ; } } } } public void printGenericsType ( GenericsType genericType ) { ClassNode [ ] upperBounds = genericType . getUpperBounds ( ) ; ClassNode lowerBound = genericType . getLowerBound ( ) ; groovyCode . append ( genericType . getName ( ) ) ; if ( upperBounds != null ) { groovyCode . append ( "<STR_LIT>" ) ; for ( int i = <NUM_LIT:0> ; i < upperBounds . length ; i ++ ) { printType ( upperBounds [ i ] ) ; if ( i + <NUM_LIT:1> < upperBounds . length ) groovyCode . append ( "<STR_LIT>" ) ; } } else if ( lowerBound != null ) { groovyCode . append ( "<STR_LIT>" ) ; printType ( lowerBound ) ; } } private void printArray ( ClassNode compType ) { ClassNode componentType = compType ; int dimension = <NUM_LIT:0> ; while ( componentType . isArray ( ) ) { dimension ++ ; componentType = componentType . getComponentType ( ) ; } printType ( componentType ) ; for ( int i = <NUM_LIT:0> ; i < dimension ; i ++ ) { groovyCode . append ( "<STR_LIT:[]>" ) ; } } @ Override public void visitPropertyExpression ( PropertyExpression expression ) { preVisitExpression ( expression ) ; String alias = ImportResolver . asAlias ( root , expression . getObjectExpression ( ) . getType ( ) ) ; String fieldName = ImportResolver . asFieldName ( root , expression . getObjectExpression ( ) . getType ( ) , expression . getPropertyAsString ( ) ) ; if ( alias != "<STR_LIT>" ) { groovyCode . append ( alias ) ; } else if ( fieldName != "<STR_LIT>" ) { groovyCode . append ( fieldName ) ; } else { expression . getObjectExpression ( ) . visit ( this ) ; groovyCode . append ( "<STR_LIT:.>" ) ; expression . getProperty ( ) . visit ( this ) ; } postVisitExpression ( expression ) ; } @ Override public void visitAttributeExpression ( AttributeExpression expression ) { preVisitExpression ( expression ) ; expression . getObjectExpression ( ) . visit ( this ) ; groovyCode . append ( "<STR_LIT>" ) ; expression . getProperty ( ) . visit ( this ) ; postVisitExpression ( expression ) ; } @ Override public void visitFieldExpression ( FieldExpression expression ) { preVisitExpression ( expression ) ; ClassNode classNode = expression . getField ( ) . getOwner ( ) ; groovyCode . append ( ImportResolver . getResolvedClassName ( root , classNode , true ) ) ; groovyCode . append ( "<STR_LIT:.>" ) ; groovyCode . append ( expression . getFieldName ( ) ) ; postVisitExpression ( expression ) ; } @ Override public void visitGStringExpression ( GStringExpression expression ) { preVisitExpression ( expression ) ; List < Expression > values = expression . getValues ( ) ; Iterator < Expression > it = values . iterator ( ) ; LineColumn coords = new LineColumn ( expression . getLineNumber ( ) , expression . getColumnNumber ( ) ) ; String stringMarker = ASTWriterHelper . getStringMarker ( currentDocument , coords ) ; groovyCode . append ( stringMarker ) ; for ( ConstantExpression stringExpression : expression . getStrings ( ) ) { stringExpression . visit ( this ) ; if ( it . hasNext ( ) ) { visitValueInGString ( it ) ; } } while ( it . hasNext ( ) ) { visitValueInGString ( it ) ; } groovyCode . append ( stringMarker ) ; if ( stringMarker . length ( ) == <NUM_LIT:3> ) { lineOfPreviousNode += expression . getLastLineNumber ( ) - expression . getLineNumber ( ) ; } postVisitExpression ( expression ) ; } private void visitValueInGString ( Iterator < Expression > it ) { Expression valueExpression = it . next ( ) ; LineColumn coords = new LineColumn ( valueExpression . getLineNumber ( ) , valueExpression . getColumnNumber ( ) ) ; char firstChar = FilePartReader . readForwardFromCoordinate ( currentDocument , coords ) . charAt ( <NUM_LIT:0> ) ; groovyCode . append ( "<STR_LIT:$>" ) ; if ( firstChar == '<CHAR_LIT>' ) { groovyCode . append ( "<STR_LIT:{>" ) ; ( valueExpression ) . visit ( this ) ; groovyCode . append ( "<STR_LIT:}>" ) ; } else { ( valueExpression ) . visit ( this ) ; } } protected void visitListOfExpressions ( List < ? extends Expression > list , String separator ) { if ( list == null ) return ; for ( Iterator < ? extends Expression > iterator = list . iterator ( ) ; iterator . hasNext ( ) ; ) { Expression expression = iterator . next ( ) ; preVisitExpression ( expression ) ; if ( getParent ( ) instanceof ArrayExpression ) { groovyCode . append ( "<STR_LIT:[>" ) ; } expression . visit ( this ) ; if ( getParent ( ) instanceof ArrayExpression ) { groovyCode . append ( "<STR_LIT:]>" ) ; } else if ( iterator . hasNext ( ) ) { groovyCode . append ( separator + "<STR_LIT:U+0020>" ) ; } postVisitExpression ( expression ) ; } } @ Override public void visitArgumentlistExpression ( ArgumentListExpression ale ) { visitListOfExpressions ( ale . getExpressions ( ) , "<STR_LIT:U+002C>" ) ; } @ Override public void visitShortTernaryExpression ( ElvisOperatorExpression expression ) { preVisitExpression ( expression ) ; expression . getBooleanExpression ( ) . visit ( this ) ; groovyCode . append ( "<STR_LIT>" ) ; expression . getFalseExpression ( ) . visit ( this ) ; postVisitExpression ( expression ) ; } @ Override public void visitUnaryPlusExpression ( UnaryPlusExpression expression ) { preVisitExpression ( expression ) ; groovyCode . append ( '<CHAR_LIT>' ) ; super . visitUnaryPlusExpression ( expression ) ; postVisitExpression ( expression ) ; } @ Override public void visitUnaryMinusExpression ( UnaryMinusExpression expression ) { preVisitExpression ( expression ) ; groovyCode . append ( '<CHAR_LIT:->' ) ; super . visitUnaryMinusExpression ( expression ) ; postVisitExpression ( expression ) ; } @ Override public void visitClosureListExpression ( ClosureListExpression cle ) { preVisitExpression ( cle ) ; groovyCode . append ( "<STR_LIT:(>" ) ; visitListOfExpressions ( cle . getExpressions ( ) , "<STR_LIT:;>" ) ; groovyCode . append ( "<STR_LIT:)>" ) ; postVisitExpression ( cle ) ; } protected void preVisitStatement ( ASTNode statement ) { ASTNode parent = getTop ( ) ; if ( statement instanceof CaseStatement ) { caseCount ++ ; } if ( parent instanceof SwitchStatement && ( caseCount == <NUM_LIT:1> ) ) { nodeStack . pop ( ) ; preVisitStatementOpenBlock ( parent ) ; } nodeStack . push ( statement ) ; if ( statement . getLineNumber ( ) != - <NUM_LIT:1> ) { lineOfCurrentNode = statement . getLineNumber ( ) - lineOffset ; } if ( ! ( statement instanceof AnnotationNode ) ) { lineOfCurrentNode += linesSinceFirstAnnotation ; } positioningCursor ( ) ; if ( parent instanceof SwitchStatement && ! ( statement instanceof CaseStatement ) ) { groovyCode . append ( "<STR_LIT>" ) ; } else { if ( inElseBlock ) { groovyCode . append ( "<STR_LIT>" ) ; inElseBlock = false ; } } } protected void preVisitStatementOpenBlock ( ASTNode statement ) { nodeStack . push ( statement ) ; lineOfCurrentNode = statement . getLineNumber ( ) - lineOffset ; positioningCursor ( ) ; columnOffset ++ ; if ( inElseBlock ) { groovyCode . append ( "<STR_LIT>" ) ; inElseBlock = false ; } groovyCode . append ( "<STR_LIT>" ) ; } protected void postVisitStatement ( ASTNode statement ) { nodeStack . pop ( ) ; lineOfCurrentNode = statement . getLastLineNumber ( ) - lineOffset ; if ( statement instanceof SwitchStatement ) { caseCount = <NUM_LIT:0> ; } } protected void postVisitStatementCloseBlock ( ASTNode statement ) { nodeStack . pop ( ) ; lineOfCurrentNode = statement . getLastLineNumber ( ) - lineOffset ; columnOffset -- ; positioningCursor ( ) ; groovyCode . append ( "<STR_LIT:}>" ) ; } protected void preVisitExpression ( ASTNode expression ) { nodeStack . push ( expression ) ; lineOfCurrentNode = expression . getLineNumber ( ) - lineOffset ; positioningCursor ( ) ; } protected void postVisitExpression ( ASTNode expression ) { nodeStack . pop ( ) ; } protected void printExpression ( ASTNode expression ) { String pre = "<STR_LIT>" ; String post = "<STR_LIT>" ; if ( expression . getText ( ) != "<STR_LIT:null>" ) { printExpression ( pre , expression , post ) ; } } protected void printExpression ( String pre , ASTNode expression , String post ) { String printExpression = expression . getText ( ) ; if ( expression . getText ( ) == "<STR_LIT:null>" ) { printExpression = "<STR_LIT>" ; } if ( pre . length ( ) > <NUM_LIT:0> ) { if ( pre . charAt ( <NUM_LIT:0> ) != '<CHAR_LIT:/>' && expression . getLineNumber ( ) == expression . getLastLineNumber ( ) ) { printExpression = escapeJava ( printExpression ) ; } else { printExpression = printExpression . replaceAll ( "<STR_LIT>" , System . getProperty ( "<STR_LIT>" ) ) ; } } groovyCode . append ( pre ) ; groovyCode . append ( printExpression ) ; groovyCode . append ( post ) ; if ( getParent ( ) instanceof CaseStatement ) { groovyCode . append ( "<STR_LIT:U+0020:U+0020>" ) ; } } private void positioningCursor ( ) { boolean onNewLine = false ; if ( ( lineOfPreviousNode == lineOfCurrentNode ) && ( getTop ( ) instanceof BreakStatement ) ) { groovyCode . append ( "<STR_LIT>" ) ; } else { while ( lineOfPreviousNode < lineOfCurrentNode ) { groovyCode . append ( lineDelimiter ) ; lineOfPreviousNode ++ ; onNewLine = true ; } } if ( onNewLine ) { printColumnOffset ( ) ; } } private void printColumnOffset ( ) { for ( int i = <NUM_LIT:0> ; i < columnOffset ; i ++ ) { groovyCode . append ( "<STR_LIT:U+0020U+0020U+0020U+0020>" ) ; } } private ASTNode getTop ( ) { if ( nodeStack . isEmpty ( ) ) { return null ; } return nodeStack . peek ( ) ; } private ASTNode getParent ( ) { if ( nodeStack . size ( ) > <NUM_LIT:1> ) { ASTNode topNode = nodeStack . pop ( ) ; ASTNode parrentNode = nodeStack . peek ( ) ; nodeStack . push ( topNode ) ; return parrentNode ; } return null ; } private static String escapeJava ( String str ) { return escapeJavaStyleString ( str , false ) ; } private static String escapeJavaStyleString ( String str , boolean escapeSingleQuotes ) { if ( str == null ) { return null ; } try { StringWriter writer = new StringWriter ( str . length ( ) * <NUM_LIT:2> ) ; escapeJavaStyleString ( writer , str , escapeSingleQuotes ) ; return writer . toString ( ) ; } catch ( IOException ioe ) { ioe . printStackTrace ( ) ; return null ; } } private static void escapeJavaStyleString ( Writer out , String str , boolean escapeSingleQuote ) throws IOException { if ( out == null ) { throw new IllegalArgumentException ( "<STR_LIT>" ) ; } if ( str == null ) { return ; } int sz ; sz = str . length ( ) ; for ( int i = <NUM_LIT:0> ; i < sz ; i ++ ) { char ch = str . charAt ( i ) ; if ( ch > <NUM_LIT> ) { out . write ( "<STR_LIT>" + hex ( ch ) ) ; } else if ( ch > <NUM_LIT> ) { out . write ( "<STR_LIT>" + hex ( ch ) ) ; } else if ( ch > <NUM_LIT> ) { out . write ( "<STR_LIT>" + hex ( ch ) ) ; } else if ( ch < <NUM_LIT:32> ) { switch ( ch ) { case '<STR_LIT>' : out . write ( '<STR_LIT:\\>' ) ; out . write ( '<CHAR_LIT:b>' ) ; break ; case '<STR_LIT:\n>' : out . write ( '<STR_LIT:\\>' ) ; out . write ( '<CHAR_LIT>' ) ; break ; case '<STR_LIT:\t>' : out . write ( '<STR_LIT:\\>' ) ; out . write ( '<CHAR_LIT>' ) ; break ; case '<STR_LIT>' : out . write ( '<STR_LIT:\\>' ) ; out . write ( '<CHAR_LIT>' ) ; break ; case '<STR_LIT>' : out . write ( '<STR_LIT:\\>' ) ; out . write ( '<CHAR_LIT>' ) ; break ; default : if ( ch > <NUM_LIT> ) { out . write ( "<STR_LIT>" + hex ( ch ) ) ; } else { out . write ( "<STR_LIT>" + hex ( ch ) ) ; } break ; } } else { switch ( ch ) { case '<STR_LIT>' : if ( escapeSingleQuote ) { out . write ( '<STR_LIT:\\>' ) ; } out . write ( '<STR_LIT>' ) ; break ; case '<CHAR_LIT:">' : out . write ( '<STR_LIT:\\>' ) ; out . write ( '<CHAR_LIT:">' ) ; break ; case '<STR_LIT:\\>' : out . write ( '<STR_LIT:\\>' ) ; out . write ( '<STR_LIT:\\>' ) ; break ; default : out . write ( ch ) ; break ; } } } } private static String hex ( char ch ) { return Integer . toHexString ( ch ) . toUpperCase ( ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . rewriter ; import java . util . List ; import org . codehaus . groovy . antlr . LineColumn ; import org . codehaus . groovy . ast . FieldNode ; import org . codehaus . groovy . ast . PropertyNode ; import org . codehaus . groovy . eclipse . refactoring . core . utils . FilePartReader ; import org . eclipse . jface . text . IDocument ; import org . objectweb . asm . Opcodes ; public class ASTWriterHelper implements Opcodes { public static final int MOD_FIELD = <NUM_LIT:1> ; public static final int MOD_CLASS = <NUM_LIT:2> ; public static final int MOD_METHOD = <NUM_LIT:3> ; public static String getAccModifier ( int modifiers , int appearance ) { StringBuilder accMod = new StringBuilder ( ) ; if ( ( modifiers & ACC_PRIVATE ) != <NUM_LIT:0> ) { accMod . append ( "<STR_LIT>" ) ; } else if ( ( modifiers & ACC_PUBLIC ) != <NUM_LIT:0> ) { if ( appearance == MOD_METHOD ) accMod . append ( "<STR_LIT>" ) ; else if ( appearance == MOD_FIELD ) accMod . append ( "<STR_LIT>" ) ; } else if ( ( modifiers & ACC_PROTECTED ) != <NUM_LIT:0> ) { accMod . append ( "<STR_LIT>" ) ; } if ( ( modifiers & ACC_STATIC ) != <NUM_LIT:0> ) { accMod . append ( "<STR_LIT>" ) ; } if ( ( modifiers & ACC_TRANSIENT ) != <NUM_LIT:0> ) { accMod . append ( "<STR_LIT>" ) ; } if ( ( modifiers & ACC_FINAL ) != <NUM_LIT:0> ) { accMod . append ( "<STR_LIT>" ) ; } if ( ( modifiers & ACC_SYNCHRONIZED ) != <NUM_LIT:0> ) { accMod . append ( "<STR_LIT>" ) ; } if ( ( modifiers & ACC_VOLATILE ) != <NUM_LIT:0> ) { accMod . append ( "<STR_LIT>" ) ; } if ( ( modifiers & ACC_NATIVE ) != <NUM_LIT:0> ) { accMod . append ( "<STR_LIT>" ) ; } if ( ( modifiers & ACC_STRICT ) != <NUM_LIT:0> ) { accMod . append ( "<STR_LIT>" ) ; } return accMod . toString ( ) ; } public static boolean isProperty ( FieldNode node ) { List < PropertyNode > properties = node . getOwner ( ) . getProperties ( ) ; for ( PropertyNode property : properties ) { if ( property . getField ( ) . equals ( node ) ) { return true ; } } return false ; } public static String getStringMarker ( IDocument currentDocument , LineColumn coords ) { if ( currentDocument == null ) { return "<STR_LIT:\">" ; } String expressionInFile = FilePartReader . readForwardFromCoordinate ( currentDocument , coords ) ; char charBefore = expressionInFile . charAt ( <NUM_LIT:0> ) ; String firstThreeChars = "<STR_LIT>" ; boolean firstThreeCharsAreSame = false ; if ( expressionInFile . length ( ) >= <NUM_LIT:3> ) { firstThreeChars = expressionInFile . substring ( <NUM_LIT:0> , <NUM_LIT:3> ) ; firstThreeCharsAreSame = ( ( firstThreeChars . charAt ( <NUM_LIT:0> ) == firstThreeChars . charAt ( <NUM_LIT:1> ) ) && ( firstThreeChars . charAt ( <NUM_LIT:1> ) == firstThreeChars . charAt ( <NUM_LIT:2> ) ) ) ; } if ( charBefore == '<STR_LIT>' || charBefore == '<STR_LIT:\">' || charBefore == '<CHAR_LIT:/>' ) { if ( firstThreeCharsAreSame ) { return firstThreeChars ; } return String . valueOf ( charBefore ) ; } return "<STR_LIT:\">" ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . extract ; import java . util . Map ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jdt . core . refactoring . descriptors . JavaRefactoringDescriptor ; import org . eclipse . jdt . internal . core . refactoring . descriptors . RefactoringSignatureDescriptorFactory ; import org . eclipse . jdt . internal . corext . refactoring . JavaRefactoringArguments ; import org . eclipse . jdt . internal . corext . refactoring . scripting . JavaUIRefactoringContribution ; import org . eclipse . ltk . core . refactoring . Refactoring ; import org . eclipse . ltk . core . refactoring . RefactoringDescriptor ; import org . eclipse . ltk . core . refactoring . RefactoringStatus ; public class ExtractGroovyMethodRefactoringContribution extends JavaUIRefactoringContribution { @ Override public RefactoringDescriptor createDescriptor ( ) { return RefactoringSignatureDescriptorFactory . createExtractMethodDescriptor ( ) ; } @ Override public RefactoringDescriptor createDescriptor ( String id , String project , String description , String comment , Map arguments , int flags ) { return RefactoringSignatureDescriptorFactory . createExtractMethodDescriptor ( project , description , comment , arguments , flags ) ; } @ Override public Refactoring createRefactoring ( JavaRefactoringDescriptor descriptor , RefactoringStatus status ) throws CoreException { JavaRefactoringArguments arguments = new JavaRefactoringArguments ( descriptor . getProject ( ) , retrieveArgumentMap ( descriptor ) ) ; return new ExtractGroovyMethodRefactoring ( arguments , status ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . extract ; import java . util . Map ; import org . codehaus . groovy . ast . ClassCodeVisitorSupport ; import org . codehaus . groovy . ast . DynamicVariable ; import org . codehaus . groovy . ast . MethodNode ; import org . codehaus . groovy . ast . Variable ; import org . codehaus . groovy . ast . expr . VariableExpression ; import org . codehaus . groovy . control . SourceUnit ; import org . eclipse . text . edits . MultiTextEdit ; import org . eclipse . text . edits . ReplaceEdit ; public class VariableRenamer extends ClassCodeVisitorSupport { private MultiTextEdit edits ; private Map < String , String > variablesToRename ; public VariableRenamer ( ) { edits = new MultiTextEdit ( ) ; } public MultiTextEdit rename ( MethodNode method , Map < String , String > variablesToRename ) { this . variablesToRename = variablesToRename ; method . getCode ( ) . visit ( this ) ; return edits ; } @ Override public void visitVariableExpression ( VariableExpression expression ) { Variable accessedVar = expression . getAccessedVariable ( ) ; if ( accessedVar instanceof DynamicVariable ) { String newName = variablesToRename . get ( accessedVar . getName ( ) ) ; if ( newName != null ) { edits . addChild ( new ReplaceEdit ( expression . getStart ( ) , expression . getLength ( ) , newName ) ) ; } } } @ Override protected SourceUnit getSourceUnit ( ) { return null ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . extract ; import java . util . Collections ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . FieldNode ; import org . codehaus . groovy . ast . MethodNode ; import org . codehaus . groovy . ast . expr . CastExpression ; import org . codehaus . groovy . ast . expr . ClassExpression ; import org . codehaus . groovy . ast . expr . ConstantExpression ; import org . codehaus . groovy . ast . expr . Expression ; import org . codehaus . groovy . ast . expr . MethodCallExpression ; import org . codehaus . groovy . ast . expr . StaticMethodCallExpression ; import org . codehaus . groovy . ast . expr . VariableExpression ; import org . codehaus . groovy . eclipse . codebrowsing . fragments . ASTFragmentKind ; import org . codehaus . groovy . eclipse . codebrowsing . fragments . BinaryExpressionFragment ; import org . codehaus . groovy . eclipse . codebrowsing . fragments . IASTFragment ; import org . codehaus . groovy . eclipse . codebrowsing . fragments . MethodCallFragment ; import org . codehaus . groovy . eclipse . codebrowsing . fragments . PropertyExpressionFragment ; import org . codehaus . groovy . eclipse . codebrowsing . selection . FindAllOccurrencesVisitor ; import org . codehaus . groovy . eclipse . core . GroovyCore ; import org . codehaus . groovy . eclipse . refactoring . Activator ; import org . codehaus . groovy . eclipse . refactoring . core . utils . ASTTools ; import org . codehaus . groovy . eclipse . refactoring . formatter . DefaultGroovyFormatter ; import org . codehaus . groovy . eclipse . refactoring . formatter . FormatterPreferences ; import org . codehaus . jdt . groovy . model . GroovyCompilationUnit ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jdt . core . IJavaElement ; import org . eclipse . jdt . core . IJavaProject ; import org . eclipse . jdt . core . IMember ; import org . eclipse . jdt . core . JavaModelException ; import org . eclipse . jdt . core . NamingConventions ; import org . eclipse . jdt . core . compiler . CharOperation ; import org . eclipse . jdt . core . refactoring . CompilationUnitChange ; import org . eclipse . jdt . core . refactoring . descriptors . ExtractConstantDescriptor ; import org . eclipse . jdt . core . refactoring . descriptors . JavaRefactoringDescriptor ; import org . eclipse . jdt . groovy . core . util . ReflectionUtils ; import org . eclipse . jdt . internal . core . refactoring . descriptors . RefactoringSignatureDescriptorFactory ; import org . eclipse . jdt . internal . corext . refactoring . Checks ; import org . eclipse . jdt . internal . corext . refactoring . JDTRefactoringDescriptorComment ; import org . eclipse . jdt . internal . corext . refactoring . JavaRefactoringArguments ; import org . eclipse . jdt . internal . corext . refactoring . JavaRefactoringDescriptorUtil ; import org . eclipse . jdt . internal . corext . refactoring . RefactoringCoreMessages ; import org . eclipse . jdt . internal . corext . refactoring . base . JavaStatusContext ; import org . eclipse . jdt . internal . corext . refactoring . code . ExtractConstantRefactoring ; import org . eclipse . jdt . internal . corext . util . CodeFormatterUtil ; import org . eclipse . jdt . internal . corext . util . JdtFlags ; import org . eclipse . jdt . internal . ui . viewsupport . BasicElementLabels ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . TextUtilities ; import org . eclipse . ltk . core . refactoring . Change ; import org . eclipse . ltk . core . refactoring . RefactoringChangeDescriptor ; import org . eclipse . ltk . core . refactoring . RefactoringDescriptor ; import org . eclipse . ltk . core . refactoring . RefactoringStatus ; import org . eclipse . ltk . core . refactoring . RefactoringStatusContext ; import org . eclipse . ltk . core . refactoring . TextEditChangeGroup ; import org . eclipse . ltk . internal . core . refactoring . Messages ; import org . eclipse . text . edits . InsertEdit ; import org . eclipse . text . edits . MalformedTreeException ; import org . eclipse . text . edits . MultiTextEdit ; import org . eclipse . text . edits . ReplaceEdit ; import org . eclipse . text . edits . TextEdit ; import org . eclipse . text . edits . TextEditGroup ; public class ExtractGroovyConstantRefactoring extends ExtractConstantRefactoring { private static final String MODIFIER = "<STR_LIT>" ; private IASTFragment selectedFragment ; private GroovyCompilationUnit unit ; private int start = - <NUM_LIT:1> , length = - <NUM_LIT:1> ; private String constantName ; private boolean insertFirst ; private FieldNode toInsertAfter ; private String constantText ; public ExtractGroovyConstantRefactoring ( JavaRefactoringArguments arguments , RefactoringStatus status ) { super ( arguments , status ) ; } public ExtractGroovyConstantRefactoring ( GroovyCompilationUnit unit , int offset , int length ) { super ( unit , offset , length ) ; this . unit = unit ; this . start = offset ; this . length = expandSelection ( start , length ) ; setSelectionLength ( this . length ) ; } @ Override public RefactoringStatus checkInitialConditions ( IProgressMonitor pm ) throws CoreException { try { pm . beginTask ( "<STR_LIT>" , <NUM_LIT:7> ) ; RefactoringStatus result = Checks . validateEdit ( getCu ( ) , getValidationContext ( ) ) ; if ( result . hasFatalError ( ) ) { return result ; } pm . worked ( <NUM_LIT:4> ) ; result . merge ( checkSelection ( new SubProgressMonitor ( pm , <NUM_LIT:3> ) ) ) ; if ( result . hasFatalError ( ) ) { return result ; } ClassNode targetType = getContainingClassNode ( ) ; if ( targetType == null ) { result . merge ( RefactoringStatus . createFatalErrorStatus ( "<STR_LIT>" ) ) ; } if ( targetType . isScript ( ) ) { result . merge ( RefactoringStatus . createFatalErrorStatus ( "<STR_LIT>" ) ) ; } if ( targetType . isAnnotationDefinition ( ) || targetType . isInterface ( ) ) { setTargetIsInterface ( true ) ; setVisibility ( JdtFlags . VISIBILITY_STRING_PUBLIC ) ; } return result ; } finally { pm . done ( ) ; } } private int expandSelection ( int s , int l ) { int end = s + l ; char [ ] contents = unit . getContents ( ) ; while ( end < contents . length && ( contents [ end ] == '<CHAR_LIT:U+0020>' || contents [ end ] == '<STR_LIT:\t>' ) ) { end ++ ; } return end - s ; } private CompilationUnitChange getChange ( ) { return ( CompilationUnitChange ) ReflectionUtils . getPrivateField ( ExtractConstantRefactoring . class , "<STR_LIT>" , this ) ; } private void setChange ( CompilationUnitChange change ) { ReflectionUtils . setPrivateField ( ExtractConstantRefactoring . class , "<STR_LIT>" , this , change ) ; } @ Override public RefactoringStatus checkFinalConditions ( IProgressMonitor pm ) throws CoreException { try { RefactoringStatus result = new RefactoringStatus ( ) ; CompilationUnitChange change = new CompilationUnitChange ( "<STR_LIT>" , getCu ( ) ) ; change . setEdit ( new MultiTextEdit ( ) ) ; TextEditGroup group = createConstantDeclaration ( ) ; change . addChangeGroup ( new TextEditChangeGroup ( change , group ) ) ; for ( TextEdit edit : group . getTextEdits ( ) ) { change . addEdit ( edit ) ; } group = replaceExpressionsWithConstant ( ) ; change . addChangeGroup ( new TextEditChangeGroup ( change , group ) ) ; for ( TextEdit edit : group . getTextEdits ( ) ) { change . addEdit ( edit ) ; } setChange ( change ) ; return result ; } catch ( MalformedTreeException e ) { throw new CoreException ( new Status ( IStatus . ERROR , Activator . PLUGIN_ID , e . getMessage ( ) , e ) ) ; } catch ( BadLocationException e ) { throw new CoreException ( new Status ( IStatus . ERROR , Activator . PLUGIN_ID , e . getMessage ( ) , e ) ) ; } finally { pm . done ( ) ; } } private TextEditGroup replaceExpressionsWithConstant ( ) throws JavaModelException { IASTFragment origExpr = getSelectedFragment ( ) ; List < IASTFragment > occurrences ; if ( getReplaceAllOccurrences ( ) ) { FindAllOccurrencesVisitor v = new FindAllOccurrencesVisitor ( getCu ( ) . getModuleNode ( ) ) ; occurrences = v . findOccurrences ( origExpr ) ; } else { occurrences = Collections . singletonList ( origExpr ) ; } TextEditGroup msg = new TextEditGroup ( RefactoringCoreMessages . ExtractConstantRefactoring_replace ) ; for ( IASTFragment fragment : occurrences ) { String replaceText ; if ( getQualifyReferencesWithDeclaringClassName ( ) ) { replaceText = getContainingClassNode ( ) . getNameWithoutPackage ( ) + "<STR_LIT:.>" + getConstantName ( ) ; } else { replaceText = getConstantName ( ) ; } msg . addTextEdit ( new ReplaceEdit ( fragment . getStart ( ) , fragment . getLength ( ) , replaceText ) ) ; } return msg ; } private TextEditGroup createConstantDeclaration ( ) throws MalformedTreeException , BadLocationException { String constantText = getConstantText ( ) ; TextEditGroup msg = new TextEditGroup ( RefactoringCoreMessages . ExtractConstantRefactoring_declare_constant ) ; int insertLocation = findInsertLocation ( ) ; msg . addTextEdit ( new InsertEdit ( insertLocation , constantText ) ) ; return msg ; } private int findInsertLocation ( ) { if ( insertFirst ( ) ) { ClassNode node = getContainingClassNode ( ) ; if ( node . isScript ( ) ) { int statementStart = node . getModule ( ) . getStatementBlock ( ) . getStart ( ) ; int methodStart ; if ( node . getModule ( ) . getMethods ( ) . size ( ) > <NUM_LIT:0> ) { methodStart = ( ( MethodNode ) node . getModule ( ) . getMethods ( ) . get ( <NUM_LIT:0> ) ) . getStart ( ) ; } else { methodStart = Integer . MAX_VALUE ; } return Math . min ( methodStart , statementStart ) ; } else { return CharOperation . indexOf ( '<CHAR_LIT>' , getCu ( ) . getContents ( ) , node . getNameEnd ( ) ) + <NUM_LIT:1> ; } } else { return toInsertAfter . getEnd ( ) ; } } private String getConstantText ( ) throws MalformedTreeException , BadLocationException { if ( constantText == null ) { constantText = createConstantText ( ) ; } return constantText ; } private String createConstantText ( ) throws MalformedTreeException , BadLocationException { StringBuilder sb = new StringBuilder ( ) ; IJavaProject javaProject = getCu ( ) . getJavaProject ( ) ; sb . append ( CodeFormatterUtil . createIndentString ( getIndentLevel ( ) , javaProject ) ) ; sb . append ( MODIFIER ) . append ( "<STR_LIT:U+0020>" ) . append ( getConstantTypeName ( ) ) . append ( constantName ) . append ( "<STR_LIT:U+0020=U+0020>" ) . append ( createExpressionText ( ) ) ; IDocument doc = new Document ( sb . toString ( ) ) ; DefaultGroovyFormatter formatter = new DefaultGroovyFormatter ( doc , new FormatterPreferences ( unit ) , getIndentLevel ( ) ) ; TextEdit edit = formatter . format ( ) ; edit . apply ( doc ) ; return getDefaultNewlineCharacterTwice ( ) + doc . get ( ) ; } private String getDefaultNewlineCharacterTwice ( ) { String newline = TextUtilities . determineLineDelimiter ( String . valueOf ( unit . getContents ( ) ) , "<STR_LIT:n>" ) ; return newline + newline ; } private int getIndentLevel ( ) { ClassNode node = getContainingClassNode ( ) ; ClassNode containing = node ; int indentLevel = <NUM_LIT:0> ; while ( containing != null ) { indentLevel ++ ; if ( containing . getEnclosingMethod ( ) != null ) { indentLevel ++ ; containing = containing . getEnclosingMethod ( ) . getDeclaringClass ( ) ; } else { containing = containing . getOuterClass ( ) ; } } return indentLevel ; } private String createExpressionText ( ) { IASTFragment fragment = getSelectedFragment ( ) ; return String . valueOf ( unit . getContents ( ) ) . substring ( fragment . getStart ( ) , fragment . getEnd ( ) ) ; } private boolean insertFirst ( ) { if ( ! isDeclarationLocationComputed ( ) ) computeConstantDeclarationLocation ( ) ; return insertFirst ; } private boolean isDeclarationLocationComputed ( ) { return insertFirst || toInsertAfter != null ; } @ Override public Change createChange ( IProgressMonitor monitor ) throws CoreException { ExtractConstantDescriptor descriptor = createRefactoringDescriptor ( ) ; getChange ( ) . setDescriptor ( new RefactoringChangeDescriptor ( descriptor ) ) ; return getChange ( ) ; } private ExtractConstantDescriptor createRefactoringDescriptor ( ) { final Map < String , String > arguments = new HashMap < String , String > ( ) ; String project = null ; IJavaProject javaProject = getCu ( ) . getJavaProject ( ) ; if ( javaProject != null ) project = javaProject . getElementName ( ) ; int flags = JavaRefactoringDescriptor . JAR_REFACTORING | JavaRefactoringDescriptor . JAR_SOURCE_ATTACHMENT ; flags |= RefactoringDescriptor . STRUCTURAL_CHANGE ; String expression = createExpressionText ( ) ; final String description = Messages . format ( RefactoringCoreMessages . ExtractConstantRefactoring_descriptor_description_short , BasicElementLabels . getJavaElementName ( constantName ) ) ; final String header = Messages . format ( RefactoringCoreMessages . ExtractConstantRefactoring_descriptor_description , new String [ ] { BasicElementLabels . getJavaElementName ( constantName ) , BasicElementLabels . getJavaCodeString ( expression ) } ) ; final JDTRefactoringDescriptorComment comment = new JDTRefactoringDescriptorComment ( project , this , header ) ; comment . addSetting ( Messages . format ( RefactoringCoreMessages . ExtractConstantRefactoring_constant_name_pattern , BasicElementLabels . getJavaElementName ( constantName ) ) ) ; comment . addSetting ( Messages . format ( RefactoringCoreMessages . ExtractConstantRefactoring_constant_expression_pattern , BasicElementLabels . getJavaCodeString ( expression ) ) ) ; String visibility = "<STR_LIT>" ; if ( "<STR_LIT>" . equals ( visibility ) ) visibility = RefactoringCoreMessages . ExtractConstantRefactoring_default_visibility ; comment . addSetting ( Messages . format ( RefactoringCoreMessages . ExtractConstantRefactoring_visibility_pattern , visibility ) ) ; if ( getReplaceAllOccurrences ( ) ) { comment . addSetting ( RefactoringCoreMessages . ExtractConstantRefactoring_replace_occurrences ) ; } if ( getQualifyReferencesWithDeclaringClassName ( ) ) { comment . addSetting ( RefactoringCoreMessages . ExtractConstantRefactoring_qualify_references ) ; } arguments . put ( JavaRefactoringDescriptorUtil . ATTRIBUTE_INPUT , JavaRefactoringDescriptorUtil . elementToHandle ( project , getCu ( ) ) ) ; arguments . put ( JavaRefactoringDescriptorUtil . ATTRIBUTE_NAME , constantName ) ; arguments . put ( JavaRefactoringDescriptorUtil . ATTRIBUTE_SELECTION , new Integer ( start ) . toString ( ) + "<STR_LIT:U+0020>" + new Integer ( length ) . toString ( ) ) ; arguments . put ( "<STR_LIT>" , Boolean . valueOf ( getReplaceAllOccurrences ( ) ) . toString ( ) ) ; arguments . put ( "<STR_LIT>" , Boolean . valueOf ( getQualifyReferencesWithDeclaringClassName ( ) ) . toString ( ) ) ; arguments . put ( "<STR_LIT>" , new Integer ( JdtFlags . getVisibilityCode ( "<STR_LIT>" ) ) . toString ( ) ) ; ExtractConstantDescriptor descriptor = RefactoringSignatureDescriptorFactory . createExtractConstantDescriptor ( project , description , comment . asString ( ) , arguments , flags ) ; return descriptor ; } private boolean getReplaceAllOccurrences ( ) { return ( ( Boolean ) ReflectionUtils . getPrivateField ( ExtractConstantRefactoring . class , "<STR_LIT>" , this ) ) . booleanValue ( ) ; } private boolean getQualifyReferencesWithDeclaringClassName ( ) { return ( ( Boolean ) ReflectionUtils . getPrivateField ( ExtractConstantRefactoring . class , "<STR_LIT>" , this ) ) . booleanValue ( ) ; } private void computeConstantDeclarationLocation ( ) { if ( isDeclarationLocationComputed ( ) ) { return ; } FieldNode lastStaticDependency = null ; Iterator < FieldNode > decls = getContainingClassNode ( ) . getFields ( ) . iterator ( ) ; while ( decls . hasNext ( ) ) { FieldNode decl = ( FieldNode ) decls . next ( ) ; if ( decl . isStatic ( ) && decl . getEnd ( ) > <NUM_LIT:0> ) { lastStaticDependency = decl ; } } if ( lastStaticDependency == null ) { insertFirst = true ; } else { toInsertAfter = lastStaticDependency ; } } private ClassNode getContainingClassNode ( ) { return ASTTools . getContainingClassNode ( getCu ( ) . getModuleNode ( ) , getSelectionStart ( ) ) ; } private void setTargetIsInterface ( boolean b ) { ReflectionUtils . setPrivateField ( ExtractConstantRefactoring . class , "<STR_LIT>" , this , true ) ; } private RefactoringStatus checkSelection ( IProgressMonitor pm ) throws JavaModelException { try { pm . beginTask ( "<STR_LIT>" , <NUM_LIT:2> ) ; IASTFragment selectedFragment = getSelectedFragment ( ) ; if ( selectedFragment == null ) { String message = RefactoringCoreMessages . ExtractConstantRefactoring_select_expression ; return RefactoringStatus . createFatalErrorStatus ( message , createContext ( ) ) ; } pm . worked ( <NUM_LIT:1> ) ; RefactoringStatus result = new RefactoringStatus ( ) ; result . merge ( checkFragment ( ) ) ; if ( result . hasFatalError ( ) ) return result ; pm . worked ( <NUM_LIT:1> ) ; return result ; } finally { pm . done ( ) ; } } private RefactoringStatus checkFragment ( ) throws JavaModelException { RefactoringStatus result = new RefactoringStatus ( ) ; IASTFragment selectedFragment = getSelectedFragment ( ) ; result . merge ( checkExpressionFragmentIsRValue ( selectedFragment ) ) ; if ( result . hasFatalError ( ) ) return result ; checkAllStaticFinal ( ) ; if ( ( selectedFragment instanceof ConstantExpression ) && ( ( ConstantExpression ) selectedFragment ) . isNullExpression ( ) ) { result . merge ( RefactoringStatus . createFatalErrorStatus ( RefactoringCoreMessages . ExtractConstantRefactoring_null_literals ) ) ; } return result ; } private void checkAllStaticFinal ( ) throws JavaModelException { StaticFragmentChecker checker = new StaticFragmentChecker ( ) ; boolean maybeStatic = checker . mayNotBeStatic ( getSelectedFragment ( ) ) ; ReflectionUtils . setPrivateField ( ExtractConstantRefactoring . class , "<STR_LIT>" , this , maybeStatic ) ; ReflectionUtils . setPrivateField ( ExtractConstantRefactoring . class , "<STR_LIT>" , this , true ) ; } private RefactoringStatus checkExpressionFragmentIsRValue ( IASTFragment fragment ) throws JavaModelException { if ( fragment . kind ( ) == ASTFragmentKind . SIMPLE_EXPRESSION ) { Expression expr = fragment . getAssociatedExpression ( ) ; if ( expr instanceof VariableExpression ) { VariableExpression var = ( VariableExpression ) expr ; if ( var . getAccessedVariable ( ) == var ) { return RefactoringStatus . createFatalErrorStatus ( "<STR_LIT>" ) ; } } } return new RefactoringStatus ( ) ; } private RefactoringStatusContext createContext ( ) { IJavaElement elt ; try { elt = getCu ( ) . getElementAt ( getSelectionStart ( ) ) ; if ( elt instanceof IMember ) { return JavaStatusContext . create ( ( IMember ) elt ) ; } } catch ( JavaModelException e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; } return null ; } private IASTFragment getSelectedFragment ( ) { if ( selectedFragment == null ) { selectedFragment = ASTTools . getSelectionFragment ( getCu ( ) . getModuleNode ( ) , getSelectionStart ( ) , getSelectionLength ( ) ) ; } return selectedFragment ; } private String getConstantTypeName ( ) { Expression e = getSelectedFragment ( ) . getAssociatedExpression ( ) ; if ( e != null ) { String name = e . getType ( ) . getNameWithoutPackage ( ) ; if ( ! name . equals ( "<STR_LIT>" ) ) { return name + "<STR_LIT:U+0020>" ; } } return "<STR_LIT>" ; } @ Override public String getConstantSignaturePreview ( ) throws JavaModelException { String space = "<STR_LIT:U+0020>" ; return getVisibility ( ) + space + MODIFIER + space + getConstantTypeName ( ) + space + constantName ; } @ Override public RefactoringStatus checkConstantNameOnChange ( ) throws JavaModelException { return Checks . checkConstantName ( getConstantName ( ) , getCu ( ) ) ; } @ Override public String [ ] guessConstantNames ( ) { String text = getBaseNameFromExpression ( getCu ( ) . getJavaProject ( ) , getSelectedFragment ( ) , NamingConventions . VK_STATIC_FINAL_FIELD ) ; try { Integer . parseInt ( text ) ; text = "<STR_LIT:_>" + text ; } catch ( NumberFormatException e ) { } return NamingConventions . suggestVariableNames ( NamingConventions . VK_STATIC_FINAL_FIELD , NamingConventions . BK_NAME , text , getCu ( ) . getJavaProject ( ) , getContainingClassNode ( ) . isArray ( ) ? <NUM_LIT:1> : <NUM_LIT:0> , null , true ) ; } private static final String [ ] KNOWN_METHOD_NAME_PREFIXES = { "<STR_LIT:get>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" } ; private static String getBaseNameFromExpression ( IJavaProject project , IASTFragment assignedFragment , int variableKind ) { String name = null ; Expression assignedExpression = assignedFragment . getAssociatedExpression ( ) ; if ( assignedExpression instanceof CastExpression ) { assignedExpression = ( ( CastExpression ) assignedFragment ) . getExpression ( ) ; } String candidate = null ; if ( assignedExpression instanceof ConstantExpression ) { candidate = ( ( ConstantExpression ) assignedExpression ) . getText ( ) ; } else if ( assignedExpression instanceof VariableExpression ) { candidate = ( ( VariableExpression ) assignedExpression ) . getName ( ) ; } else if ( assignedExpression instanceof ClassExpression ) { candidate = ( ( ClassExpression ) assignedExpression ) . getType ( ) . getNameWithoutPackage ( ) ; } else if ( assignedExpression instanceof MethodCallExpression ) { candidate = ( ( MethodCallExpression ) assignedExpression ) . getMethodAsString ( ) ; } else if ( assignedExpression instanceof StaticMethodCallExpression ) { candidate = ( ( StaticMethodCallExpression ) assignedExpression ) . getMethod ( ) ; } if ( candidate != null ) { StringBuffer res = new StringBuffer ( ) ; boolean needsUnderscore = false ; for ( int i = <NUM_LIT:0> ; i < candidate . length ( ) ; i ++ ) { char ch = candidate . charAt ( i ) ; if ( Character . isJavaIdentifierPart ( ch ) ) { if ( res . length ( ) == <NUM_LIT:0> && ! Character . isJavaIdentifierStart ( ch ) || needsUnderscore ) { res . append ( '<CHAR_LIT:_>' ) ; } res . append ( ch ) ; needsUnderscore = false ; } else { needsUnderscore = res . length ( ) > <NUM_LIT:0> ; } } if ( res . length ( ) > <NUM_LIT:0> ) { name = res . toString ( ) ; } } IASTFragment next ; switch ( assignedFragment . kind ( ) ) { case PROPERTY : case SAFE_PROPERTY : case SPREAD_SAFE_PROPERTY : case METHOD_POINTER : next = ( ( PropertyExpressionFragment ) assignedFragment ) . getNext ( ) ; break ; case METHOD_CALL : next = ( ( MethodCallFragment ) assignedFragment ) . getNext ( ) ; break ; case BINARY : next = ( ( BinaryExpressionFragment ) assignedFragment ) . getNext ( ) ; break ; default : next = null ; } if ( next != null ) { name = name + "<STR_LIT:_>" + getBaseNameFromExpression ( project , next , variableKind ) ; } if ( name != null ) { for ( int i = <NUM_LIT:0> ; i < KNOWN_METHOD_NAME_PREFIXES . length ; i ++ ) { String curr = KNOWN_METHOD_NAME_PREFIXES [ i ] ; if ( name . startsWith ( curr ) ) { if ( name . equals ( curr ) ) { return null ; } else if ( Character . isUpperCase ( name . charAt ( curr . length ( ) ) ) ) { return name . substring ( curr . length ( ) ) ; } } } } else { name = "<STR_LIT>" ; } return name ; } @ Override public void setConstantName ( String newName ) { super . setConstantName ( newName ) ; Assert . isNotNull ( newName ) ; constantName = newName ; } @ Override public String getConstantName ( ) { return constantName ; } private GroovyCompilationUnit getCu ( ) { if ( unit == null ) { unit = ( GroovyCompilationUnit ) ReflectionUtils . getPrivateField ( ExtractConstantRefactoring . class , "<STR_LIT>" , this ) ; } return unit ; } private int getSelectionStart ( ) { if ( start == - <NUM_LIT:1> ) { start = ( Integer ) ReflectionUtils . getPrivateField ( ExtractConstantRefactoring . class , "<STR_LIT>" , this ) ; } return start ; } private int getSelectionLength ( ) { if ( length == - <NUM_LIT:1> ) { length = ( Integer ) ReflectionUtils . getPrivateField ( ExtractConstantRefactoring . class , "<STR_LIT>" , this ) ; } return length ; } private void setSelectionLength ( int newLength ) { ReflectionUtils . setPrivateField ( ExtractConstantRefactoring . class , "<STR_LIT>" , this , newLength ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . extract ; import java . util . Map ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jdt . core . refactoring . descriptors . JavaRefactoringDescriptor ; import org . eclipse . jdt . internal . core . refactoring . descriptors . RefactoringSignatureDescriptorFactory ; import org . eclipse . jdt . internal . corext . refactoring . JavaRefactoringArguments ; import org . eclipse . jdt . internal . corext . refactoring . scripting . JavaUIRefactoringContribution ; import org . eclipse . ltk . core . refactoring . Refactoring ; import org . eclipse . ltk . core . refactoring . RefactoringDescriptor ; import org . eclipse . ltk . core . refactoring . RefactoringStatus ; public class ExtractGroovyLocalRefactoringContribution extends JavaUIRefactoringContribution { @ Override public RefactoringDescriptor createDescriptor ( ) { return RefactoringSignatureDescriptorFactory . createExtractLocalDescriptor ( ) ; } @ Override public RefactoringDescriptor createDescriptor ( String id , String project , String description , String comment , Map arguments , int flags ) { return RefactoringSignatureDescriptorFactory . createExtractLocalDescriptor ( project , description , comment , arguments , flags ) ; } @ Override public Refactoring createRefactoring ( JavaRefactoringDescriptor descriptor , RefactoringStatus status ) throws CoreException { JavaRefactoringArguments arguments = new JavaRefactoringArguments ( descriptor . getProject ( ) , retrieveArgumentMap ( descriptor ) ) ; return new ExtractGroovyLocalRefactoring ( arguments , status ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . extract ; import org . codehaus . groovy . ast . CodeVisitorSupport ; import org . codehaus . groovy . ast . MethodNode ; import org . codehaus . groovy . ast . expr . ConstructorCallExpression ; import org . codehaus . groovy . ast . stmt . BlockStatement ; public class ExtractConstructorTest extends CodeVisitorSupport { private boolean constructorCall = false ; public boolean containsConstructorCall ( MethodNode method ) { constructorCall = false ; visitBlockStatement ( ( BlockStatement ) method . getCode ( ) ) ; return constructorCall ; } @ Override public void visitConstructorCallExpression ( ConstructorCallExpression call ) { constructorCall = true ; super . visitConstructorCallExpression ( call ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . extract ; import java . util . LinkedHashSet ; import java . util . Set ; import org . codehaus . groovy . ast . ASTNode ; import org . codehaus . groovy . ast . FieldNode ; import org . codehaus . groovy . ast . Parameter ; import org . codehaus . groovy . ast . Variable ; import org . codehaus . groovy . ast . expr . BinaryExpression ; import org . codehaus . groovy . ast . expr . ClosureExpression ; import org . codehaus . groovy . ast . expr . DeclarationExpression ; import org . codehaus . groovy . ast . expr . PostfixExpression ; import org . codehaus . groovy . ast . expr . PrefixExpression ; import org . codehaus . groovy . ast . expr . VariableExpression ; import org . codehaus . groovy . ast . stmt . DoWhileStatement ; import org . codehaus . groovy . ast . stmt . ForStatement ; import org . codehaus . groovy . ast . stmt . IfStatement ; import org . codehaus . groovy . ast . stmt . WhileStatement ; import org . codehaus . groovy . eclipse . refactoring . core . utils . ASTVisitorDecorator ; import org . codehaus . groovy . syntax . Token ; import org . codehaus . groovy . syntax . Types ; public class ASTVariableScanner { private Set < Variable > declaredVariables = new LinkedHashSet < Variable > ( ) ; private Set < Variable > declaredInblockVariables = new LinkedHashSet < Variable > ( ) ; private Set < Variable > usedVariables = new LinkedHashSet < Variable > ( ) ; private Set < Variable > returnVariables = new LinkedHashSet < Variable > ( ) ; private Set < Variable > innerLoopAssignedVariables = new LinkedHashSet < Variable > ( ) ; private boolean selectionIsInLoopOrClosure = false ; public ASTVariableScanner ( boolean blockIsInLoop ) { selectionIsInLoopOrClosure = blockIsInLoop ; } public Set < Variable > getDeclaratedVariables ( ) { return declaredVariables ; } public Set < Variable > getUsedVariables ( ) { return usedVariables ; } public Set < Variable > getAssignedVariables ( ) { return returnVariables ; } public Set < Variable > getInnerLoopAssignedVariables ( ) { return innerLoopAssignedVariables ; } public void visitNode ( ASTNode node ) { if ( selectionIsInLoopOrClosure ) { node . visit ( new RepeatableBlockVisit ( this ) ) ; } else { node . visit ( new DefaultVisit ( this ) ) ; } } private class DefaultVisit extends ASTVisitorDecorator < ASTVariableScanner > { public DefaultVisit ( ASTVariableScanner container ) { super ( container ) ; } @ Override public void visitVariableExpression ( VariableExpression expression ) { super . visitVariableExpression ( expression ) ; Variable var = expression . getAccessedVariable ( ) ; if ( expression . getEnd ( ) < <NUM_LIT:1> ) { return ; } else if ( var != null && ! ( var instanceof FieldNode ) ) { if ( ! declaredVariables . contains ( var ) ) { usedVariables . add ( var ) ; } } } @ Override public void visitDeclarationExpression ( DeclarationExpression expression ) { Variable var = expression . getVariableExpression ( ) . getAccessedVariable ( ) ; if ( var != null ) { declaredVariables . add ( var ) ; } super . visitDeclarationExpression ( expression ) ; } @ Override public void visitForLoop ( ForStatement forLoop ) { if ( forLoop . getVariable ( ) != null ) { declaredInblockVariables . add ( forLoop . getVariable ( ) ) ; } forLoop . getCollectionExpression ( ) . visit ( new RepeatableBlockVisit ( container ) ) ; forLoop . getLoopBlock ( ) . visit ( new RepeatableBlockVisit ( container ) ) ; } @ Override public void visitWhileLoop ( WhileStatement loop ) { loop . getLoopBlock ( ) . visit ( new RepeatableBlockVisit ( container ) ) ; } @ Override public void visitDoWhileLoop ( DoWhileStatement loop ) { loop . getLoopBlock ( ) . visit ( new RepeatableBlockVisit ( container ) ) ; } @ Override public void visitIfElse ( IfStatement ifElse ) { ifElse . getIfBlock ( ) . visit ( new InnerBlockVisit ( container ) ) ; ifElse . getElseBlock ( ) . visit ( new InnerBlockVisit ( container ) ) ; } @ Override public void visitClosureExpression ( ClosureExpression expression ) { if ( expression . getParameters ( ) . length > <NUM_LIT:0> ) { for ( Parameter p : expression . getParameters ( ) ) { declaredInblockVariables . add ( p ) ; } } expression . getCode ( ) . visit ( new ClosureVisit ( container ) ) ; } @ Override public void visitBinaryExpression ( BinaryExpression expression ) { if ( expression . getLeftExpression ( ) instanceof VariableExpression ) { expression . getLeftExpression ( ) . visit ( new DefaultAssignementVisit ( container , expression . getOperation ( ) ) ) ; } else { expression . getLeftExpression ( ) . visit ( this ) ; } expression . getRightExpression ( ) . visit ( this ) ; } @ Override public void visitPostfixExpression ( PostfixExpression expression ) { expression . getExpression ( ) . visit ( new DefaultAssignementVisit ( container , expression . getOperation ( ) ) ) ; } @ Override public void visitPrefixExpression ( PrefixExpression expression ) { expression . getExpression ( ) . visit ( new DefaultAssignementVisit ( container , expression . getOperation ( ) ) ) ; } protected boolean isUsed ( Variable var ) { return declaredVariables . contains ( var ) || declaredInblockVariables . contains ( var ) ; } } private class DefaultAssignementVisit extends DefaultVisit { protected Token operator ; public DefaultAssignementVisit ( ASTVariableScanner container , Token token ) { super ( container ) ; this . operator = token ; } @ Override public void visitVariableExpression ( VariableExpression expression ) { super . visitVariableExpression ( expression ) ; if ( expression . getEnd ( ) < <NUM_LIT:1> ) { return ; } Variable var = expression . getAccessedVariable ( ) ; if ( operator . getType ( ) != Types . LEFT_SQUARE_BRACKET ) { returnVariables . add ( var ) ; } } } private class InnerBlockVisit extends DefaultVisit { public InnerBlockVisit ( ASTVariableScanner container ) { super ( container ) ; } @ Override public void visitVariableExpression ( VariableExpression expression ) { if ( expression . getEnd ( ) < <NUM_LIT:1> ) { return ; } Variable var = expression . getAccessedVariable ( ) ; if ( var != null && ! ( var instanceof FieldNode ) ) { if ( ! declaredInblockVariables . contains ( var ) && ! declaredVariables . contains ( var ) ) { usedVariables . add ( var ) ; } } } } private class RepeatableBlockVisit extends InnerBlockVisit { public RepeatableBlockVisit ( ASTVariableScanner container ) { super ( container ) ; } protected void checkAssertedVariables ( VariableExpression expression , int operatorTokenType ) { if ( operatorTokenType == Types . LEFT_SQUARE_BRACKET ) return ; Variable var = expression . getAccessedVariable ( ) ; if ( var != null && isUsed ( var ) ) { returnVariables . add ( var ) ; } if ( usedVariables . contains ( var ) ) { innerLoopAssignedVariables . add ( var ) ; } } @ Override public void visitBinaryExpression ( BinaryExpression expression ) { expression . getLeftExpression ( ) . visit ( new AssignmentInRepeatableBlockVisit ( container , expression . getOperation ( ) ) ) ; expression . getRightExpression ( ) . visit ( new RepeatableBlockVisit ( container ) ) ; } @ Override public void visitPostfixExpression ( PostfixExpression expression ) { expression . getExpression ( ) . visit ( new AssignmentInRepeatableBlockVisit ( container , expression . getOperation ( ) ) ) ; } @ Override public void visitPrefixExpression ( PrefixExpression expression ) { expression . getExpression ( ) . visit ( new AssignmentInRepeatableBlockVisit ( container , expression . getOperation ( ) ) ) ; } @ Override public void visitIfElse ( IfStatement ifElse ) { ifElse . getIfBlock ( ) . visit ( this ) ; ifElse . getElseBlock ( ) . visit ( this ) ; } } private class AssignmentInRepeatableBlockVisit extends RepeatableBlockVisit { protected Token operator ; public AssignmentInRepeatableBlockVisit ( ASTVariableScanner container , Token operator ) { super ( container ) ; this . operator = operator ; } @ Override public void visitVariableExpression ( VariableExpression expression ) { super . visitVariableExpression ( expression ) ; checkAssertedVariables ( expression , operator . getType ( ) ) ; } } private class ClosureVisit extends RepeatableBlockVisit { public ClosureVisit ( ASTVariableScanner container ) { super ( container ) ; } @ Override public void visitVariableExpression ( VariableExpression expression ) { Variable var = expression . getAccessedVariable ( ) ; if ( var instanceof Parameter && ( ( Parameter ) var ) . getEnd ( ) <= <NUM_LIT:0> && var . getName ( ) . equals ( "<STR_LIT>" ) ) { declaredInblockVariables . add ( var ) ; } super . visitVariableExpression ( expression ) ; } @ Override public void visitBinaryExpression ( BinaryExpression expression ) { expression . getLeftExpression ( ) . visit ( new AssignementInClosureVisit ( container , expression . getOperation ( ) ) ) ; expression . getRightExpression ( ) . visit ( this ) ; } @ Override public void visitPostfixExpression ( PostfixExpression expression ) { expression . getExpression ( ) . visit ( new AssignementInClosureVisit ( container , expression . getOperation ( ) ) ) ; } @ Override public void visitPrefixExpression ( PrefixExpression expression ) { expression . getExpression ( ) . visit ( new AssignementInClosureVisit ( container , expression . getOperation ( ) ) ) ; } } private class AssignementInClosureVisit extends ClosureVisit { protected Token operator ; public AssignementInClosureVisit ( ASTVariableScanner container , Token token ) { super ( container ) ; this . operator = token ; } @ Override public void visitVariableExpression ( VariableExpression expression ) { super . visitVariableExpression ( expression ) ; checkAssertedVariables ( expression , operator . getType ( ) ) ; } } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . extract ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import org . codehaus . groovy . ast . ASTNode ; import org . codehaus . groovy . ast . ClassCodeVisitorSupport ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . DynamicVariable ; import org . codehaus . groovy . ast . FieldNode ; import org . codehaus . groovy . ast . InnerClassNode ; import org . codehaus . groovy . ast . MethodNode ; import org . codehaus . groovy . ast . ModuleNode ; import org . codehaus . groovy . ast . Variable ; import org . codehaus . groovy . ast . VariableScope ; import org . codehaus . groovy . ast . expr . ClosureExpression ; import org . codehaus . groovy . ast . expr . DeclarationExpression ; import org . codehaus . groovy . ast . expr . Expression ; import org . codehaus . groovy . ast . expr . VariableExpression ; import org . codehaus . groovy . ast . stmt . BlockStatement ; import org . codehaus . groovy . control . SourceUnit ; import org . codehaus . groovy . eclipse . codebrowsing . fragments . IASTFragment ; import org . codehaus . groovy . eclipse . codebrowsing . requestor . Region ; import org . codehaus . groovy . eclipse . codebrowsing . selection . FindSurroundingNode ; import org . codehaus . groovy . eclipse . codebrowsing . selection . FindSurroundingNode . VisitKind ; import org . codehaus . groovy . eclipse . core . util . VisitCompleteException ; import org . codehaus . groovy . eclipse . refactoring . core . utils . ASTTools ; import org . codehaus . groovy . eclipse . refactoring . formatter . DefaultGroovyFormatter ; import org . codehaus . groovy . eclipse . refactoring . formatter . FormatterPreferences ; import org . codehaus . jdt . groovy . model . GroovyCompilationUnit ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . jdt . core . compiler . CharOperation ; import org . eclipse . jdt . core . refactoring . CompilationUnitChange ; import org . eclipse . jdt . groovy . core . util . ReflectionUtils ; import org . eclipse . jdt . internal . corext . refactoring . Checks ; import org . eclipse . jdt . internal . corext . refactoring . RefactoringCoreMessages ; import org . eclipse . jdt . internal . corext . refactoring . code . PromoteTempToFieldRefactoring ; import org . eclipse . jdt . internal . corext . util . CodeFormatterUtil ; import org . eclipse . jdt . internal . corext . util . JdtFlags ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . TextUtilities ; import org . eclipse . ltk . core . refactoring . Change ; import org . eclipse . ltk . core . refactoring . RefactoringStatus ; import org . eclipse . ltk . core . refactoring . TextEditChangeGroup ; import org . eclipse . text . edits . InsertEdit ; import org . eclipse . text . edits . MalformedTreeException ; import org . eclipse . text . edits . MultiTextEdit ; import org . eclipse . text . edits . ReplaceEdit ; import org . eclipse . text . edits . TextEdit ; import org . eclipse . text . edits . TextEditGroup ; public class ConvertGroovyLocalToFieldRefactoring extends PromoteTempToFieldRefactoring { private GroovyCompilationUnit unit ; private String fieldName ; private int fieldVisibility = - <NUM_LIT:1> ; private int selectionStart ; private int selectionLength ; private IASTFragment selectionFragment ; private VariableExpression variableExpressionInDeclaration ; private DeclarationExpression declarationExpression ; private ClassNode containingClassNode ; private ModuleNode moduleNode ; private MethodNode methodNode ; private CompilationUnitChange change ; public ConvertGroovyLocalToFieldRefactoring ( GroovyCompilationUnit unit , int selectionStart , int selectionLength ) { super ( unit , selectionStart , selectionLength ) ; this . unit = unit ; this . selectionStart = selectionStart ; this . selectionLength = selectionLength ; } @ Override public int getVisibility ( ) { if ( fieldVisibility == - <NUM_LIT:1> ) { fieldVisibility = ( Integer ) ReflectionUtils . getPrivateField ( PromoteTempToFieldRefactoring . class , "<STR_LIT>" , this ) ; } return fieldVisibility ; } @ Override public boolean getDeclareFinal ( ) { return false ; } @ Override public boolean getDeclareStatic ( ) { return false ; } public String getFieldName ( ) { if ( fieldName == null ) { fieldName = ( String ) ReflectionUtils . getPrivateField ( PromoteTempToFieldRefactoring . class , "<STR_LIT>" , this ) ; } if ( ( fieldName == null || fieldName . length ( ) == <NUM_LIT:0> ) && variableExpressionInDeclaration != null ) { fieldName = variableExpressionInDeclaration . getName ( ) ; } return fieldName ; } @ Override public int getInitializeIn ( ) { return INITIALIZE_IN_METHOD ; } @ Override public void setVisibility ( int accessModifier ) { super . setVisibility ( accessModifier ) ; fieldVisibility = accessModifier ; } @ Override public void setDeclareFinal ( boolean declareFinal ) { } @ Override public void setDeclareStatic ( boolean declareStatic ) { } @ Override public void setFieldName ( String fieldName ) { super . setFieldName ( fieldName ) ; this . fieldName = fieldName ; } @ Override public void setInitializeIn ( int initializeIn ) { } @ Override public boolean canEnableSettingStatic ( ) { return false ; } @ Override public boolean canEnableSettingFinal ( ) { return false ; } @ Override public boolean canEnableSettingDeclareInConstructors ( ) { return false ; } @ Override public boolean canEnableSettingDeclareInMethod ( ) { return true ; } @ Override public boolean canEnableSettingDeclareInFieldDeclaration ( ) { return false ; } @ Override public RefactoringStatus checkInitialConditions ( IProgressMonitor pm ) throws CoreException { try { pm . beginTask ( "<STR_LIT>" , <NUM_LIT:5> ) ; RefactoringStatus result = Checks . validateEdit ( unit , getValidationContext ( ) ) ; if ( result . hasFatalError ( ) ) { return result ; } pm . worked ( <NUM_LIT:1> ) ; IASTFragment selectionFragment = getSelectionFragment ( ) ; if ( selectionFragment == null ) { result . merge ( RefactoringStatus . createFatalErrorStatus ( RefactoringCoreMessages . PromoteTempToFieldRefactoring_select_declaration ) ) ; return result ; } Expression selectedExpression = selectionFragment . getAssociatedExpression ( ) ; if ( ! ( selectedExpression instanceof VariableExpression ) ) { result . merge ( RefactoringStatus . createFatalErrorStatus ( RefactoringCoreMessages . PromoteTempToFieldRefactoring_select_declaration ) ) ; return result ; } pm . worked ( <NUM_LIT:1> ) ; VariableExpression selectedVariableExpression = ( VariableExpression ) selectedExpression ; Variable declaredVariable = selectedVariableExpression . getAccessedVariable ( ) ; if ( declaredVariable instanceof DynamicVariable ) { result . merge ( RefactoringStatus . createFatalErrorStatus ( "<STR_LIT>" ) ) ; return result ; } if ( ! ( declaredVariable instanceof VariableExpression ) ) { result . merge ( RefactoringStatus . createFatalErrorStatus ( RefactoringCoreMessages . PromoteTempToFieldRefactoring_select_declaration ) ) ; return result ; } pm . worked ( <NUM_LIT:1> ) ; VariableExpression variableExpressionInDeclaration = ( VariableExpression ) declaredVariable ; DeclarationExpression declarationExpression = getDeclarationExpression ( variableExpressionInDeclaration ) ; if ( declarationExpression == null ) { result . merge ( RefactoringStatus . createFatalErrorStatus ( "<STR_LIT>" ) ) ; return result ; } if ( declarationExpression . isMultipleAssignmentDeclaration ( ) ) { result . merge ( RefactoringStatus . createFatalErrorStatus ( "<STR_LIT>" ) ) ; return result ; } pm . worked ( <NUM_LIT:1> ) ; this . variableExpressionInDeclaration = variableExpressionInDeclaration ; ClassNode containingClassNode = getContainingClassNode ( ) ; if ( containingClassNode == null ) { result . merge ( RefactoringStatus . createFatalErrorStatus ( "<STR_LIT>" ) ) ; return result ; } if ( containingClassNode . isScript ( ) ) { result . merge ( RefactoringStatus . createFatalErrorStatus ( "<STR_LIT>" ) ) ; return result ; } if ( containingClassNode . isInterface ( ) || containingClassNode . isAnnotationDefinition ( ) ) { result . merge ( RefactoringStatus . createFatalErrorStatus ( "<STR_LIT>" ) ) ; return result ; } pm . worked ( <NUM_LIT:1> ) ; return result ; } finally { pm . done ( ) ; } } @ Override public String [ ] guessFieldNames ( ) { return new String [ ] { variableExpressionInDeclaration . getName ( ) } ; } @ Override public RefactoringStatus checkFinalConditions ( IProgressMonitor pm ) throws CoreException { try { pm . beginTask ( "<STR_LIT>" , <NUM_LIT:4> ) ; FieldNode conflictingField = getContainingClassNode ( ) . getDeclaredField ( getFieldName ( ) ) ; if ( conflictingField != null ) { return RefactoringStatus . createFatalErrorStatus ( RefactoringCoreMessages . PromoteTempToFieldRefactoring_Name_conflict_with_field ) ; } pm . worked ( <NUM_LIT:1> ) ; CompilationUnitChange change = new CompilationUnitChange ( "<STR_LIT>" , unit ) ; change . setEdit ( new MultiTextEdit ( ) ) ; TextEditGroup group = createFieldTextEditGroup ( ) ; change . addChangeGroup ( new TextEditChangeGroup ( change , group ) ) ; for ( TextEdit edit : group . getTextEdits ( ) ) { change . addEdit ( edit ) ; } pm . worked ( <NUM_LIT:1> ) ; group = declarationToReferenceTextEditGroup ( ) ; change . addChangeGroup ( new TextEditChangeGroup ( change , group ) ) ; for ( TextEdit edit : group . getTextEdits ( ) ) { change . addEdit ( edit ) ; } pm . worked ( <NUM_LIT:1> ) ; RefactoringStatus status = new RefactoringStatus ( ) ; group = renameVariableReferencesTextEditGroup ( status ) ; change . addChangeGroup ( new TextEditChangeGroup ( change , group ) ) ; for ( TextEdit edit : group . getTextEdits ( ) ) { change . addEdit ( edit ) ; } pm . worked ( <NUM_LIT:1> ) ; this . change = change ; return status ; } finally { pm . done ( ) ; } } private TextEditGroup createFieldTextEditGroup ( ) { ClassNode classNode = getContainingClassNode ( ) ; char [ ] contents = unit . getContents ( ) ; MethodNode method = getContainingMethodNode ( ) ; int methodLineOffset = method . getStart ( ) - method . getColumnNumber ( ) + <NUM_LIT:1> ; int methodOffset = method . getStart ( ) ; String methodIndentation = String . valueOf ( CharOperation . subarray ( contents , methodLineOffset , methodOffset ) ) ; int indentLevel = ASTTools . getCurrentIntentation ( methodIndentation ) ; String fieldText = null ; try { fieldText = createFieldText ( indentLevel ) ; } catch ( Exception e ) { } TextEditGroup group = new TextEditGroup ( "<STR_LIT>" ) ; if ( fieldText != null ) { int insertOffset = CharOperation . indexOf ( '<CHAR_LIT>' , contents , classNode . getStart ( ) ) + <NUM_LIT:1> ; String newline = TextUtilities . determineLineDelimiter ( String . valueOf ( contents ) , "<STR_LIT:n>" ) ; group . addTextEdit ( new InsertEdit ( insertOffset , newline + fieldText ) ) ; } return group ; } private String createFieldText ( int indentLevel ) throws MalformedTreeException , BadLocationException { StringBuilder sb = new StringBuilder ( ) ; String indentation = CodeFormatterUtil . createIndentString ( indentLevel , unit . getJavaProject ( ) ) ; sb . append ( indentation ) ; String visibility = JdtFlags . getVisibilityString ( getVisibility ( ) ) ; sb . append ( visibility ) ; if ( ! visibility . equals ( "<STR_LIT>" ) ) { sb . append ( "<STR_LIT:U+0020>" ) ; } char [ ] contents = unit . getContents ( ) ; String typeOrDef = new String ( CharOperation . subarray ( contents , declarationExpression . getStart ( ) , variableExpressionInDeclaration . getStart ( ) ) ) ; sb . append ( typeOrDef ) . append ( getFieldName ( ) ) ; IDocument doc = new Document ( sb . toString ( ) ) ; DefaultGroovyFormatter formatter = new DefaultGroovyFormatter ( doc , new FormatterPreferences ( unit ) , indentLevel ) ; TextEdit edit = formatter . format ( ) ; edit . apply ( doc ) ; return doc . get ( ) ; } private TextEditGroup declarationToReferenceTextEditGroup ( ) { TextEditGroup group = new TextEditGroup ( "<STR_LIT>" ) ; int typeOrDefLength = variableExpressionInDeclaration . getStart ( ) - declarationExpression . getStart ( ) ; group . addTextEdit ( new ReplaceEdit ( declarationExpression . getStart ( ) , typeOrDefLength , "<STR_LIT>" ) ) ; return group ; } private TextEditGroup renameVariableReferencesTextEditGroup ( RefactoringStatus status ) { final Set < VariableExpression > references = new HashSet < VariableExpression > ( ) ; ClassCodeVisitorSupport referencesVisitor = new ClassCodeVisitorSupport ( ) { @ Override public void visitVariableExpression ( VariableExpression variableExpression ) { if ( variableExpression . getAccessedVariable ( ) == variableExpressionInDeclaration && variableExpression . getLineNumber ( ) >= <NUM_LIT:0> ) { references . add ( variableExpression ) ; } } @ Override protected SourceUnit getSourceUnit ( ) { return null ; } } ; referencesVisitor . visitClass ( getContainingClassNode ( ) ) ; Iterator < InnerClassNode > innerClasses = getContainingClassNode ( ) . getInnerClasses ( ) ; while ( innerClasses != null && innerClasses . hasNext ( ) ) { ClassNode innerClass = innerClasses . next ( ) ; referencesVisitor . visitClass ( innerClass ) ; } TextEditGroup group = new TextEditGroup ( "<STR_LIT>" ) ; for ( VariableExpression reference : references ) { if ( getUsedVariableAndFieldNames ( reference ) . contains ( getFieldName ( ) ) ) { status . merge ( RefactoringStatus . createWarningStatus ( "<STR_LIT>" ) ) ; } group . addTextEdit ( new ReplaceEdit ( reference . getStart ( ) , reference . getLength ( ) , getFieldName ( ) ) ) ; } return group ; } @ Override public Change createChange ( IProgressMonitor pm ) throws CoreException { return change ; } private IASTFragment getSelectionFragment ( ) { if ( selectionFragment == null ) { selectionFragment = ASTTools . getSelectionFragment ( getModuleNode ( ) , selectionStart , selectionLength ) ; } return selectionFragment ; } private ClassNode getContainingClassNode ( ) { if ( containingClassNode == null ) { ModuleNode moduleNode = getModuleNode ( ) ; if ( moduleNode == null ) { return null ; } if ( declarationExpression == null ) { return null ; } containingClassNode = ASTTools . getContainingClassNode ( moduleNode , declarationExpression . getStart ( ) ) ; } return containingClassNode ; } private ModuleNode getModuleNode ( ) { if ( moduleNode == null ) { moduleNode = unit . getModuleNode ( ) ; } return moduleNode ; } private DeclarationExpression getDeclarationExpression ( final VariableExpression variableExpressionInDeclaration ) { if ( declarationExpression != null ) { return declarationExpression ; } ClassCodeVisitorSupport visitor = new ClassCodeVisitorSupport ( ) { @ Override public void visitDeclarationExpression ( DeclarationExpression declarationExpression ) { ConvertGroovyLocalToFieldRefactoring . this . declarationExpression = declarationExpression ; super . visitDeclarationExpression ( declarationExpression ) ; } @ Override public void visitVariableExpression ( VariableExpression variableExpression ) { if ( variableExpression == variableExpressionInDeclaration ) { throw new VisitCompleteException ( ) ; } super . visitVariableExpression ( variableExpression ) ; } @ Override protected SourceUnit getSourceUnit ( ) { return null ; } } ; for ( ClassNode classNode : getModuleNode ( ) . getClasses ( ) ) { try { visitor . visitClass ( classNode ) ; } catch ( VisitCompleteException expected ) { break ; } declarationExpression = null ; } return declarationExpression ; } private MethodNode getContainingMethodNode ( ) { if ( methodNode != null ) { return methodNode ; } ClassCodeVisitorSupport visitor = new ClassCodeVisitorSupport ( ) { @ Override public void visitConstructorOrMethod ( MethodNode methodNode , boolean isConstructor ) { ConvertGroovyLocalToFieldRefactoring . this . methodNode = methodNode ; super . visitConstructorOrMethod ( methodNode , isConstructor ) ; } @ Override public void visitVariableExpression ( VariableExpression variableExpression ) { if ( variableExpression == variableExpressionInDeclaration ) { throw new VisitCompleteException ( ) ; } super . visitVariableExpression ( variableExpression ) ; } @ Override protected SourceUnit getSourceUnit ( ) { return null ; } } ; for ( ClassNode classNode : getModuleNode ( ) . getClasses ( ) ) { try { visitor . visitClass ( classNode ) ; } catch ( VisitCompleteException expected ) { break ; } methodNode = null ; } return methodNode ; } private Set < String > getUsedVariableAndFieldNames ( VariableExpression variableExpression ) { FindSurroundingNode find = new FindSurroundingNode ( new Region ( variableExpression ) , VisitKind . PARENT_STACK ) ; find . doVisitSurroundingNode ( moduleNode ) ; List < IASTFragment > parentStack = new ArrayList < IASTFragment > ( find . getParentStack ( ) ) ; Collections . reverse ( parentStack ) ; Set < String > result = new HashSet < String > ( ) ; for ( IASTFragment fragment : parentStack ) { ASTNode astNode = fragment . getAssociatedNode ( ) ; VariableScope scope = null ; if ( astNode instanceof BlockStatement ) { scope = ( ( BlockStatement ) astNode ) . getVariableScope ( ) ; } else if ( astNode instanceof MethodNode ) { scope = ( ( MethodNode ) astNode ) . getVariableScope ( ) ; } else if ( astNode instanceof ClosureExpression ) { scope = ( ( ClosureExpression ) astNode ) . getVariableScope ( ) ; } else if ( astNode instanceof ClassNode ) { for ( FieldNode field : ( ( ClassNode ) astNode ) . getFields ( ) ) { if ( field . getLineNumber ( ) > <NUM_LIT:0> ) { result . add ( field . getName ( ) ) ; } } } if ( scope != null ) { Iterator < Variable > declaredVariables = scope . getDeclaredVariablesIterator ( ) ; while ( declaredVariables . hasNext ( ) ) { Variable variable = declaredVariables . next ( ) ; if ( variable instanceof VariableExpression ) { VariableExpression varExpression = ( VariableExpression ) variable ; if ( varExpression . getAccessedVariable ( ) != variableExpression . getAccessedVariable ( ) ) { result . add ( variable . getName ( ) ) ; } } else { result . add ( variable . getName ( ) ) ; } } } } return result ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . extract ; import java . util . ArrayList ; import java . util . List ; import org . codehaus . groovy . ast . ASTNode ; import org . codehaus . groovy . ast . AnnotatedNode ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . CodeVisitorSupport ; import org . codehaus . groovy . ast . ConstructorNode ; import org . codehaus . groovy . ast . FieldNode ; import org . codehaus . groovy . ast . MethodNode ; import org . codehaus . groovy . ast . ModuleNode ; import org . codehaus . groovy . ast . expr . ClosureExpression ; import org . codehaus . groovy . ast . stmt . BlockStatement ; import org . codehaus . groovy . ast . stmt . DoWhileStatement ; import org . codehaus . groovy . ast . stmt . ForStatement ; import org . codehaus . groovy . ast . stmt . ReturnStatement ; import org . codehaus . groovy . ast . stmt . Statement ; import org . codehaus . groovy . ast . stmt . WhileStatement ; import org . codehaus . groovy . eclipse . codebrowsing . requestor . Region ; import org . codehaus . groovy . eclipse . refactoring . core . utils . ASTTools ; public class StatementFinder extends CodeVisitorSupport { private List < Statement > inSelection , postSelection ; private AnnotatedNode actualSelectedDeclaration ; private AnnotatedNode currentDeclaration ; private final Region selection ; private final ModuleNode rootNode ; boolean preCode = true ; boolean isInLoopOrClosure = false ; boolean internalInLoopOrClosure = false ; public StatementFinder ( Region selection , ModuleNode rootNode ) { this . selection = selection ; this . rootNode = rootNode ; scanDocument ( ) ; } public boolean isStatic ( ) { return actualSelectedDeclaration instanceof MethodNode ? ( ( MethodNode ) actualSelectedDeclaration ) . isStatic ( ) : ( ( FieldNode ) actualSelectedDeclaration ) . isStatic ( ) ; } public boolean isInConstructor ( ) { return ( actualSelectedDeclaration instanceof MethodNode && ( ( MethodNode ) actualSelectedDeclaration ) . getName ( ) . equals ( "<STR_LIT>" ) ) ; } public boolean isInLoopOrClosure ( ) { return isInLoopOrClosure ; } public List < Statement > getInSelection ( ) { return inSelection ; } public List < Statement > getPostSelection ( ) { return postSelection ; } public AnnotatedNode getSelectedDeclaration ( ) { return actualSelectedDeclaration ; } public List < String > getMethodNames ( ) { List < String > methods = new ArrayList < String > ( ) ; if ( actualSelectedDeclaration != null ) { ClassNode declaringClass = actualSelectedDeclaration . getDeclaringClass ( ) ; for ( MethodNode method : ( List < MethodNode > ) declaringClass . getMethods ( ) ) { methods . add ( method . getName ( ) ) ; } } return methods ; } public String getClassName ( ) { ClassNode declaringClass = actualSelectedDeclaration . getDeclaringClass ( ) ; if ( declaringClass != null ) return declaringClass . getNameWithoutPackage ( ) ; return "<STR_LIT>" ; } public ClassNode getClassNode ( ) { return actualSelectedDeclaration . getDeclaringClass ( ) ; } public void scanDocument ( ) { inSelection = new ArrayList < Statement > ( ) ; postSelection = new ArrayList < Statement > ( ) ; if ( rootNode != null ) { for ( ClassNode cl : ( List < ClassNode > ) rootNode . getClasses ( ) ) { for ( ConstructorNode method : ( List < ConstructorNode > ) cl . getDeclaredConstructors ( ) ) { scanMethod ( cl , method ) ; } for ( MethodNode method : ( List < MethodNode > ) cl . getMethods ( ) ) { scanMethod ( cl , method ) ; } for ( FieldNode field : ( List < FieldNode > ) cl . getFields ( ) ) { scanField ( cl , field ) ; } } } } private void scanField ( ClassNode cl , FieldNode field ) { if ( testSelection ( selection , field , SelectionTestKind . SELECTION_IS_COVERED_BY ) ) { if ( field . getInitialExpression ( ) instanceof ClosureExpression ) { Statement closureBlock = ( ( ClosureExpression ) field . getInitialExpression ( ) ) . getCode ( ) ; if ( closureBlock instanceof BlockStatement ) { currentDeclaration = field ; visitBlockStatement ( ( BlockStatement ) closureBlock ) ; } } } } private void scanMethod ( ClassNode cl , MethodNode method ) { if ( testSelection ( selection , method , SelectionTestKind . SELECTION_IS_COVERED_BY ) ) { if ( method . getCode ( ) instanceof BlockStatement ) { currentDeclaration = method ; visitBlockStatement ( ( ( BlockStatement ) method . getCode ( ) ) ) ; } } } @ Override public void visitBlockStatement ( BlockStatement block ) { for ( Statement statement : ( List < Statement > ) block . getStatements ( ) ) { if ( testSelection ( selection , statement , SelectionTestKind . SELECTION_COVERS ) ) { inSelection . add ( statement ) ; if ( internalInLoopOrClosure ) { isInLoopOrClosure = true ; } preCode = false ; actualSelectedDeclaration = currentDeclaration ; } else { if ( preCode ) { if ( testSelection ( selection , statement , SelectionTestKind . SELECTION_IS_COVERED_BY ) ) { statement . visit ( this ) ; } } else { postSelection . add ( <NUM_LIT:0> , statement ) ; } } } } @ Override public void visitForLoop ( ForStatement forLoop ) { boolean oldInLoop = internalInLoopOrClosure ; internalInLoopOrClosure = true ; super . visitForLoop ( forLoop ) ; internalInLoopOrClosure = oldInLoop ; } @ Override public void visitWhileLoop ( WhileStatement loop ) { boolean oldInLoop = internalInLoopOrClosure ; internalInLoopOrClosure = true ; super . visitWhileLoop ( loop ) ; internalInLoopOrClosure = oldInLoop ; } @ Override public void visitDoWhileLoop ( DoWhileStatement loop ) { boolean oldInLoop = internalInLoopOrClosure ; internalInLoopOrClosure = true ; super . visitDoWhileLoop ( loop ) ; internalInLoopOrClosure = oldInLoop ; } @ Override public void visitClosureExpression ( ClosureExpression expression ) { boolean oldInLoop = internalInLoopOrClosure ; internalInLoopOrClosure = true ; super . visitClosureExpression ( expression ) ; internalInLoopOrClosure = oldInLoop ; } private enum SelectionTestKind { SELECTION_COVERS , SELECTION_IS_COVERED_BY } private boolean testSelection ( Region sel , ASTNode astNode , SelectionTestKind inSelection ) { if ( sel . isEmpty ( ) ) { return false ; } ASTNode node = astNode ; if ( ! ASTTools . hasValidPosition ( node ) && node instanceof ReturnStatement ) { node = ( ( ReturnStatement ) node ) . getExpression ( ) ; } if ( inSelection == SelectionTestKind . SELECTION_COVERS ) { return sel . regionCoversNode ( node ) ; } else { return sel . regionIsCoveredByNode ( node ) ; } } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . extract ; import java . util . Map ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . jdt . core . refactoring . descriptors . JavaRefactoringDescriptor ; import org . eclipse . jdt . internal . core . refactoring . descriptors . RefactoringSignatureDescriptorFactory ; import org . eclipse . jdt . internal . corext . refactoring . JavaRefactoringArguments ; import org . eclipse . jdt . internal . corext . refactoring . scripting . JavaUIRefactoringContribution ; import org . eclipse . ltk . core . refactoring . Refactoring ; import org . eclipse . ltk . core . refactoring . RefactoringDescriptor ; import org . eclipse . ltk . core . refactoring . RefactoringStatus ; public class ExtractGroovyConstantRefactoringContribution extends JavaUIRefactoringContribution { public RefactoringDescriptor createDescriptor ( ) { return RefactoringSignatureDescriptorFactory . createExtractConstantDescriptor ( ) ; } public RefactoringDescriptor createDescriptor ( String id , String project , String description , String comment , Map arguments , int flags ) { return RefactoringSignatureDescriptorFactory . createExtractConstantDescriptor ( project , description , comment , arguments , flags ) ; } @ Override public Refactoring createRefactoring ( JavaRefactoringDescriptor descriptor , RefactoringStatus status ) throws CoreException { JavaRefactoringArguments arguments = new JavaRefactoringArguments ( descriptor . getProject ( ) , retrieveArgumentMap ( descriptor ) ) ; return new ExtractGroovyConstantRefactoring ( arguments , status ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . extract ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . codehaus . groovy . ast . ASTNode ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . Variable ; import org . codehaus . groovy . ast . expr . VariableExpression ; import org . codehaus . groovy . eclipse . codebrowsing . requestor . Region ; import org . eclipse . jdt . core . IJavaElement ; import org . eclipse . jdt . core . ISourceRange ; import org . eclipse . jdt . core . ISourceReference ; import org . eclipse . jdt . core . JavaModelException ; import org . eclipse . jdt . groovy . search . ITypeRequestor ; import org . eclipse . jdt . groovy . search . TypeLookupResult ; import org . eclipse . jdt . groovy . search . VariableScope ; import org . eclipse . jdt . internal . core . util . Util ; public class InferParameterAndReturnTypesRequestor implements ITypeRequestor { private Map < Variable , ClassNode > inferredTypes ; private final Region selectedText ; public InferParameterAndReturnTypesRequestor ( List < Variable > actualParameters , Set < Variable > returnParameters , Region selectedText ) { inferredTypes = new HashMap < Variable , ClassNode > ( ) ; for ( Variable variable : actualParameters ) { inferredTypes . put ( variable , null ) ; } for ( Variable variable : returnParameters ) { inferredTypes . put ( variable , null ) ; } this . selectedText = selectedText ; } public VisitStatus acceptASTNode ( ASTNode node , TypeLookupResult result , IJavaElement enclosingElement ) { if ( ! interestingElement ( enclosingElement ) ) { return VisitStatus . CANCEL_MEMBER ; } if ( node instanceof Variable ) { if ( inferredTypes . containsKey ( node ) ) { inferredTypes . put ( ( Variable ) node , extractType ( result ) ) ; } else if ( node instanceof VariableExpression ) { Variable accessedVar = ( ( VariableExpression ) node ) . getAccessedVariable ( ) ; if ( inferredTypes . containsKey ( accessedVar ) ) { inferredTypes . put ( ( Variable ) accessedVar , extractType ( result ) ) ; } } } return VisitStatus . CONTINUE ; } private ClassNode extractType ( TypeLookupResult result ) { ClassNode type = result . type . getPlainNodeReference ( ) ; if ( type . getName ( ) . equals ( VariableScope . VOID_WRAPPER_CLASS_NODE . getName ( ) ) ) { type = VariableScope . OBJECT_CLASS_NODE ; } return type ; } public Map < Variable , ClassNode > getInferredTypes ( ) { return inferredTypes ; } private boolean interestingElement ( IJavaElement enclosingElement ) { if ( enclosingElement . getElementName ( ) . equals ( "<STR_LIT>" ) ) { return true ; } if ( enclosingElement instanceof ISourceReference ) { try { ISourceRange range = ( ( ISourceReference ) enclosingElement ) . getSourceRange ( ) ; return range . getOffset ( ) <= selectedText . getOffset ( ) && range . getOffset ( ) + range . getLength ( ) >= selectedText . getEnd ( ) ; } catch ( JavaModelException e ) { Util . log ( e ) ; } } return false ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . extract ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . codehaus . groovy . ast . ASTNode ; import org . codehaus . groovy . ast . ASTNodeCompatibilityWrapper ; import org . codehaus . groovy . ast . AnnotatedNode ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . FieldNode ; import org . codehaus . groovy . ast . MethodNode ; import org . codehaus . groovy . ast . ModuleNode ; import org . codehaus . groovy . ast . Variable ; import org . codehaus . groovy . ast . VariableScope ; import org . codehaus . groovy . ast . expr . BinaryExpression ; import org . codehaus . groovy . ast . expr . CastExpression ; import org . codehaus . groovy . ast . expr . ClosureExpression ; import org . codehaus . groovy . ast . expr . ConstantExpression ; import org . codehaus . groovy . ast . expr . Expression ; import org . codehaus . groovy . ast . expr . MethodCallExpression ; import org . codehaus . groovy . ast . expr . StaticMethodCallExpression ; import org . codehaus . groovy . ast . expr . VariableExpression ; import org . codehaus . groovy . ast . stmt . BlockStatement ; import org . codehaus . groovy . ast . stmt . Statement ; import org . codehaus . groovy . eclipse . codebrowsing . fragments . ASTFragmentKind ; import org . codehaus . groovy . eclipse . codebrowsing . fragments . BinaryExpressionFragment ; import org . codehaus . groovy . eclipse . codebrowsing . fragments . FragmentVisitor ; import org . codehaus . groovy . eclipse . codebrowsing . fragments . IASTFragment ; import org . codehaus . groovy . eclipse . codebrowsing . fragments . MethodCallFragment ; import org . codehaus . groovy . eclipse . codebrowsing . fragments . PropertyExpressionFragment ; import org . codehaus . groovy . eclipse . codebrowsing . fragments . SimpleExpressionASTFragment ; import org . codehaus . groovy . eclipse . codebrowsing . requestor . Region ; import org . codehaus . groovy . eclipse . codebrowsing . selection . FindAllOccurrencesVisitor ; import org . codehaus . groovy . eclipse . codebrowsing . selection . FindSurroundingNode ; import org . codehaus . groovy . eclipse . codebrowsing . selection . FindSurroundingNode . VisitKind ; import org . codehaus . groovy . eclipse . core . GroovyCore ; import org . codehaus . groovy . eclipse . refactoring . formatter . DefaultGroovyFormatter ; import org . codehaus . groovy . eclipse . refactoring . formatter . FormatterPreferences ; import org . codehaus . groovy . syntax . Types ; import org . codehaus . jdt . groovy . model . GroovyCompilationUnit ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . Status ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jdt . core . ICompilationUnit ; import org . eclipse . jdt . core . IJavaElement ; import org . eclipse . jdt . core . IJavaProject ; import org . eclipse . jdt . core . IMember ; import org . eclipse . jdt . core . JavaModelException ; import org . eclipse . jdt . core . NamingConventions ; import org . eclipse . jdt . core . SourceRange ; import org . eclipse . jdt . core . compiler . CharOperation ; import org . eclipse . jdt . core . refactoring . CompilationUnitChange ; import org . eclipse . jdt . core . refactoring . descriptors . ExtractLocalDescriptor ; import org . eclipse . jdt . internal . core . refactoring . descriptors . RefactoringSignatureDescriptorFactory ; import org . eclipse . jdt . internal . corext . refactoring . Checks ; import org . eclipse . jdt . internal . corext . refactoring . JDTRefactoringDescriptorComment ; import org . eclipse . jdt . internal . corext . refactoring . JavaRefactoringArguments ; import org . eclipse . jdt . internal . corext . refactoring . JavaRefactoringDescriptorUtil ; import org . eclipse . jdt . internal . corext . refactoring . RefactoringCoreMessages ; import org . eclipse . jdt . internal . corext . refactoring . base . JavaStatusContext ; import org . eclipse . jdt . internal . corext . refactoring . util . ResourceUtil ; import org . eclipse . jdt . internal . corext . util . JavaConventionsUtil ; import org . eclipse . jdt . internal . corext . util . Messages ; import org . eclipse . jdt . internal . ui . viewsupport . BasicElementLabels ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . IDocument ; import org . eclipse . ltk . core . refactoring . Change ; import org . eclipse . ltk . core . refactoring . Refactoring ; import org . eclipse . ltk . core . refactoring . RefactoringChangeDescriptor ; import org . eclipse . ltk . core . refactoring . RefactoringDescriptor ; import org . eclipse . ltk . core . refactoring . RefactoringStatus ; import org . eclipse . ltk . core . refactoring . RefactoringStatusContext ; import org . eclipse . ltk . core . refactoring . TextEditChangeGroup ; import org . eclipse . text . edits . InsertEdit ; import org . eclipse . text . edits . MalformedTreeException ; import org . eclipse . text . edits . MultiTextEdit ; import org . eclipse . text . edits . ReplaceEdit ; import org . eclipse . text . edits . TextEditGroup ; public class ExtractGroovyLocalRefactoring extends Refactoring { private static final String [ ] KNOWN_METHOD_NAME_PREFIXES = { "<STR_LIT:get>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" } ; private static final String ATTRIBUTE_REPLACE = "<STR_LIT>" ; private IASTFragment selectedExpression ; private GroovyCompilationUnit unit ; private ModuleNode module ; private int start = - <NUM_LIT:1> , length = - <NUM_LIT:1> ; private String localName ; private boolean replaceAllOccurrences ; private CompilationUnitChange change ; private Map < IASTFragment , List < IASTFragment > > allParentStack ; private List < IASTFragment > matchingFragments ; public ExtractGroovyLocalRefactoring ( JavaRefactoringArguments arguments , RefactoringStatus status ) { } public ExtractGroovyLocalRefactoring ( GroovyCompilationUnit unit , int offset , int length ) { this . unit = unit ; this . start = offset ; this . length = length ; } @ Override public RefactoringStatus checkInitialConditions ( IProgressMonitor pm ) throws CoreException { try { pm . beginTask ( "<STR_LIT>" , <NUM_LIT:6> ) ; IASTFragment expr = getSelectedFragment ( ) ; int trimmedLength = expr . getTrimmedLength ( unit ) ; int exprLength = expr . getLength ( ) ; if ( expr == null || expr . getStart ( ) != start || length > exprLength || length < trimmedLength ) { return RefactoringStatus . createFatalErrorStatus ( "<STR_LIT>" , JavaStatusContext . create ( unit , new SourceRange ( start , length ) ) ) ; } RefactoringStatus result = Checks . validateModifiesFiles ( ResourceUtil . getFiles ( new ICompilationUnit [ ] { unit } ) , getValidationContext ( ) ) ; if ( result . hasFatalError ( ) ) { return result ; } module = unit . getModuleNode ( ) ; if ( module == null ) { result . addFatalError ( "<STR_LIT>" ) ; return result ; } result . merge ( checkSelection ( new SubProgressMonitor ( pm , <NUM_LIT:3> ) ) ) ; if ( ! result . hasFatalError ( ) && isLiteralNodeSelected ( ) ) { replaceAllOccurrences = false ; } return result ; } finally { pm . done ( ) ; } } @ Override public RefactoringStatus checkFinalConditions ( IProgressMonitor pm ) throws CoreException { try { pm . beginTask ( RefactoringCoreMessages . ExtractTempRefactoring_checking_preconditions , <NUM_LIT:4> ) ; RefactoringStatus result = new RefactoringStatus ( ) ; change = doCreateChange ( result , new SubProgressMonitor ( pm , <NUM_LIT:2> ) ) ; if ( getExcludedVariableNames ( ) . contains ( localName ) ) { result . addWarning ( Messages . format ( RefactoringCoreMessages . ExtractTempRefactoring_another_variable , BasicElementLabels . getJavaElementName ( localName ) ) ) ; } result . merge ( checkMatchingFragments ( ) ) ; change . setKeepPreviewEdits ( true ) ; return result ; } finally { pm . done ( ) ; } } private Set < String > getExcludedVariableNames ( ) { List < IASTFragment > parentStack = getParentStack ( getSelectedFragment ( ) ) ; Set < String > usedNames = new HashSet < String > ( ) ; for ( IASTFragment astNode : parentStack ) { VariableScope scope ; if ( astNode instanceof BlockStatement ) { scope = ( ( BlockStatement ) astNode ) . getVariableScope ( ) ; } else if ( astNode instanceof MethodNode ) { scope = ( ( MethodNode ) astNode ) . getVariableScope ( ) ; } else if ( astNode instanceof ClosureExpression ) { scope = ( ( ClosureExpression ) astNode ) . getVariableScope ( ) ; } else { scope = null ; } if ( scope != null ) { Iterator < Variable > declared = scope . getDeclaredVariablesIterator ( ) ; while ( declared . hasNext ( ) ) { usedNames . add ( declared . next ( ) . getName ( ) ) ; } } } String selectedText = getTextAt ( getSelectedFragment ( ) . getStart ( ) , getSelectedFragment ( ) . getEnd ( ) ) ; if ( JavaConventionsUtil . validateIdentifier ( selectedText , null ) == Status . OK_STATUS ) { usedNames . add ( selectedText ) ; } return usedNames ; } private RefactoringStatus checkMatchingFragments ( ) { RefactoringStatus result = new RefactoringStatus ( ) ; List < IASTFragment > matchingExprs = getMatchingExpressions ( ) ; for ( IASTFragment matchingExpr : matchingExprs ) { if ( isDeclaration ( matchingExpr ) ) { String msg = "<STR_LIT>" ; result . addError ( msg , JavaStatusContext . create ( unit , new SourceRange ( matchingExpr . getStart ( ) , matchingExpr . getLength ( ) ) ) ) ; } if ( isLeftValue ( matchingExpr ) ) { String msg = RefactoringCoreMessages . ExtractTempRefactoring_assigned_to ; result . addWarning ( msg , JavaStatusContext . create ( unit , new SourceRange ( matchingExpr . getStart ( ) , matchingExpr . getLength ( ) ) ) ) ; } } return result ; } private boolean isDeclaration ( IASTFragment matchingExpr ) { Expression associatedExpression = matchingExpr . getAssociatedExpression ( ) ; if ( associatedExpression instanceof VariableExpression ) { if ( ( ( VariableExpression ) associatedExpression ) . getAccessedVariable ( ) == associatedExpression ) { return true ; } } return false ; } private boolean isLeftValue ( IASTFragment frag ) { return frag . kind ( ) == ASTFragmentKind . BINARY && ( ( BinaryExpressionFragment ) frag ) . getToken ( ) . getType ( ) == Types . ASSIGN ; } private List < IASTFragment > getMatchingExpressions ( ) { if ( matchingFragments != null ) { return matchingFragments ; } IASTFragment origFragment = getSelectedFragment ( ) ; List < IASTFragment > parentStack = getParentStack ( origFragment ) ; AnnotatedNode limitTo = null ; for ( IASTFragment fragment : parentStack ) { ASTNode astNode = fragment . getAssociatedNode ( ) ; if ( astNode instanceof FieldNode ) { limitTo = ( FieldNode ) astNode ; break ; } if ( astNode instanceof MethodNode ) { limitTo = ( MethodNode ) astNode ; break ; } if ( astNode instanceof ClassNode ) { limitTo = ( ClassNode ) astNode ; break ; } if ( astNode instanceof ModuleNode ) { limitTo = ASTNodeCompatibilityWrapper . getScriptClassDummy ( ( ModuleNode ) astNode ) ; } } if ( replaceAllOccurrences ) { FindAllOccurrencesVisitor v = new FindAllOccurrencesVisitor ( unit . getModuleNode ( ) , limitTo ) ; matchingFragments = v . findOccurrences ( origFragment ) ; } else { matchingFragments = Collections . singletonList ( origFragment ) ; } return matchingFragments ; } private CompilationUnitChange doCreateChange ( RefactoringStatus status , IProgressMonitor pm ) throws CoreException { CompilationUnitChange newChange = new CompilationUnitChange ( "<STR_LIT>" , unit ) ; try { pm . beginTask ( RefactoringCoreMessages . ExtractTempRefactoring_checking_preconditions , <NUM_LIT:1> ) ; newChange . setEdit ( new MultiTextEdit ( ) ) ; createTempDeclaration ( newChange , status ) ; if ( ! status . hasFatalError ( ) ) { addReplaceExpressionWithTemp ( newChange ) ; } } finally { pm . done ( ) ; } return newChange ; } private void addReplaceExpressionWithTemp ( CompilationUnitChange newChange ) { List < IASTFragment > matchingExpressions ; if ( replaceAllOccurrences ) { matchingExpressions = getMatchingExpressions ( ) ; } else { matchingExpressions = Collections . singletonList ( getSelectedFragment ( ) ) ; } for ( IASTFragment matchingExpr : matchingExpressions ) { TextEditGroup group = new TextEditGroup ( RefactoringCoreMessages . ExtractTempRefactoring_replace_occurrences ) ; ReplaceEdit edit = new ReplaceEdit ( matchingExpr . getStart ( ) , matchingExpr . getLength ( ) , localName ) ; group . addTextEdit ( edit ) ; newChange . addChangeGroup ( new TextEditChangeGroup ( newChange , group ) ) ; newChange . addEdit ( edit ) ; } } private void createTempDeclaration ( CompilationUnitChange newChange , RefactoringStatus status ) { List < IASTFragment > matchingExpressions = replaceAllOccurrences ? getMatchingExpressions ( ) : Collections . singletonList ( getSelectedFragment ( ) ) ; int insertLoc = insertAt ( matchingExpressions , status ) ; if ( insertLoc == - <NUM_LIT:1> && ! status . hasFatalError ( ) ) { status . addFatalError ( "<STR_LIT>" , createContext ( ) ) ; } if ( status . hasFatalError ( ) ) { return ; } int lineStart = findLineStart ( insertLoc ) ; String prefix = getTextAt ( lineStart , insertLoc ) ; TextEditGroup group = new TextEditGroup ( RefactoringCoreMessages . ExtractTempRefactoring_declare_local_variable ) ; InsertEdit edit = new InsertEdit ( lineStart , createExpressionText ( prefix , status ) ) ; group . addTextEdit ( edit ) ; newChange . addChangeGroup ( new TextEditChangeGroup ( newChange , group ) ) ; newChange . addEdit ( edit ) ; } private String getTextAt ( int start , int end ) { return String . valueOf ( CharOperation . subarray ( unit . getContents ( ) , start , end ) ) ; } private int insertAt ( List < IASTFragment > matchingExpressions , RefactoringStatus status ) { List < IASTFragment > [ ] parentsStack = new List [ matchingExpressions . size ( ) ] ; int i = <NUM_LIT:0> ; IASTFragment firstExpression = null ; for ( IASTFragment matchingExpr : matchingExpressions ) { if ( firstExpression == null || matchingExpr . getStart ( ) < firstExpression . getStart ( ) ) { firstExpression = matchingExpr ; } parentsStack [ i ++ ] = getParentStack ( matchingExpr ) ; } IASTFragment [ ] commonPrefix = getLongestStackPrefix ( parentsStack ) ; if ( commonPrefix . length == <NUM_LIT:0> ) { status . addFatalError ( "<STR_LIT>" , createContext ( ) ) ; return - <NUM_LIT:1> ; } Statement firstCommonStatement = null ; for ( IASTFragment fragment : commonPrefix ) { if ( fragment . getAssociatedNode ( ) instanceof Statement ) { firstCommonStatement = ( Statement ) fragment . getAssociatedNode ( ) ; break ; } } int insertLoc ; if ( firstCommonStatement instanceof BlockStatement ) { insertLoc = - <NUM_LIT:1> ; List < IASTFragment > firstParentStack = getParentStack ( firstExpression ) ; for ( int j = <NUM_LIT:1> ; j < firstParentStack . size ( ) ; j ++ ) { if ( firstParentStack . get ( j ) . getAssociatedNode ( ) == firstCommonStatement ) { insertLoc = firstParentStack . get ( j - <NUM_LIT:1> ) . getStart ( ) ; break ; } } } else if ( firstCommonStatement != null ) { insertLoc = firstCommonStatement . getStart ( ) ; } else { insertLoc = - <NUM_LIT:1> ; } return insertLoc ; } private int findLineStart ( int insertLoc ) { char [ ] contents = unit . getContents ( ) ; while ( insertLoc >= <NUM_LIT:0> && contents [ insertLoc ] != '<STR_LIT:\n>' && contents [ insertLoc ] != '<STR_LIT>' ) { insertLoc -- ; } return insertLoc ; } private IASTFragment [ ] getLongestStackPrefix ( List < IASTFragment > [ ] parentsStack ) { int length = - <NUM_LIT:1> ; if ( parentsStack . length == <NUM_LIT:0> ) { return new IASTFragment [ <NUM_LIT:0> ] ; } int minArrayLength = parentsStack [ <NUM_LIT:0> ] . size ( ) ; for ( int i = <NUM_LIT:1> ; i < parentsStack . length ; i ++ ) { minArrayLength = Math . min ( minArrayLength , parentsStack [ i ] . size ( ) ) ; } for ( int i = <NUM_LIT:0> ; i < minArrayLength ; i ++ ) { if ( ! allStacksEqual ( parentsStack , i ) ) { break ; } length ++ ; } if ( length <= - <NUM_LIT:1> ) { return new IASTFragment [ <NUM_LIT:0> ] ; } return getStackPrefix ( parentsStack [ <NUM_LIT:0> ] , length ) ; } private IASTFragment [ ] getStackPrefix ( List < IASTFragment > stack , int length ) { IASTFragment [ ] array = new IASTFragment [ length + <NUM_LIT:1> ] ; int i = <NUM_LIT:0> ; while ( i <= length ) { array [ length - i ] = stack . get ( stack . size ( ) - <NUM_LIT:1> - i ) ; i ++ ; } return array ; } private boolean allStacksEqual ( List < IASTFragment > [ ] parentsStack , int i ) { IASTFragment candidate = parentsStack [ <NUM_LIT:0> ] . get ( parentsStack [ <NUM_LIT:0> ] . size ( ) - <NUM_LIT:1> - i ) ; for ( List < IASTFragment > stack : parentsStack ) { if ( stack . get ( stack . size ( ) - <NUM_LIT:1> - i ) . getAssociatedNode ( ) != candidate . getAssociatedNode ( ) ) { return false ; } } return true ; } private List < IASTFragment > getParentStack ( IASTFragment expr ) { if ( allParentStack == null ) { allParentStack = new HashMap < IASTFragment , List < IASTFragment > > ( ) ; } else if ( allParentStack . containsKey ( expr ) ) { return allParentStack . get ( expr ) ; } FindSurroundingNode find = new FindSurroundingNode ( new Region ( expr ) , VisitKind . PARENT_STACK ) ; find . doVisitSurroundingNode ( module ) ; List < IASTFragment > parentStack = new ArrayList < IASTFragment > ( find . getParentStack ( ) ) ; Collections . reverse ( parentStack ) ; allParentStack . put ( expr , parentStack ) ; return parentStack ; } private boolean isLiteralNodeSelected ( ) throws JavaModelException { ASTNode expr = getSelectedFragment ( ) . getAssociatedExpression ( ) ; if ( expr == null ) { return false ; } if ( expr instanceof ConstantExpression ) { ConstantExpression constExpr = ( ConstantExpression ) expr ; return constExpr . isEmptyStringExpression ( ) || constExpr . isFalseExpression ( ) || constExpr . isNullExpression ( ) || constExpr . isTrueExpression ( ) || constExpr . getValue ( ) instanceof Number || unit . getContents ( ) [ constExpr . getStart ( ) ] == '<CHAR_LIT:">' ; } else { return false ; } } private String createExpressionText ( String prefix , RefactoringStatus status ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "<STR_LIT>" ) . append ( localName ) . append ( "<STR_LIT:U+0020=U+0020>" ) . append ( getTextAt ( getSelectedFragment ( ) . getStart ( ) , getSelectedFragment ( ) . getEnd ( ) ) ) ; IDocument doc = new Document ( sb . toString ( ) ) ; DefaultGroovyFormatter formatter = new DefaultGroovyFormatter ( doc , new FormatterPreferences ( unit ) , <NUM_LIT:0> ) ; try { formatter . format ( ) . apply ( doc ) ; } catch ( MalformedTreeException e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; status . addFatalError ( e . getMessage ( ) , createContext ( ) ) ; } catch ( BadLocationException e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; status . addFatalError ( e . getMessage ( ) , createContext ( ) ) ; } return prefix + doc . get ( ) ; } private RefactoringStatus checkSelection ( IProgressMonitor pm ) throws JavaModelException { try { pm . beginTask ( "<STR_LIT>" , <NUM_LIT:2> ) ; IASTFragment selectedExpression = getSelectedFragment ( ) ; if ( selectedExpression == null ) { String message = RefactoringCoreMessages . ExtractTempRefactoring_select_expression ; return RefactoringStatus . createFatalErrorStatus ( message , createContext ( ) ) ; } pm . worked ( <NUM_LIT:1> ) ; RefactoringStatus result = new RefactoringStatus ( ) ; result . merge ( checkExpression ( ) ) ; if ( result . hasFatalError ( ) ) return result ; pm . worked ( <NUM_LIT:1> ) ; return result ; } finally { pm . done ( ) ; } } private RefactoringStatus checkExpression ( ) throws JavaModelException { RefactoringStatus result = new RefactoringStatus ( ) ; IASTFragment selectedExpression = getSelectedFragment ( ) ; result . merge ( checkExpressionFragmentIsRValue ( selectedExpression ) ) ; if ( result . hasFatalError ( ) ) return result ; if ( ( selectedExpression instanceof ConstantExpression ) && ( ( ConstantExpression ) selectedExpression ) . isNullExpression ( ) ) { result . merge ( RefactoringStatus . createFatalErrorStatus ( RefactoringCoreMessages . ExtractTempRefactoring_null_literals ) ) ; } return result ; } private RefactoringStatus checkExpressionFragmentIsRValue ( IASTFragment fragment ) throws JavaModelException { if ( isDeclaration ( fragment ) ) { return RefactoringStatus . createFatalErrorStatus ( "<STR_LIT>" ) ; } if ( isLeftValue ( fragment ) ) { return RefactoringStatus . createFatalErrorStatus ( "<STR_LIT>" ) ; } return new RefactoringStatus ( ) ; } private RefactoringStatusContext createContext ( ) { IJavaElement elt ; try { elt = unit . getElementAt ( start ) ; if ( elt instanceof IMember ) { return JavaStatusContext . create ( ( IMember ) elt ) ; } } catch ( JavaModelException e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; } return null ; } private IASTFragment getSelectedFragment ( ) { if ( selectedExpression != null ) { return selectedExpression ; } FindSurroundingNode finder = new FindSurroundingNode ( new Region ( start , length ) , VisitKind . SURROUNDING_NODE ) ; IASTFragment fragment = finder . doVisitSurroundingNode ( unit . getModuleNode ( ) ) ; if ( ASTFragmentKind . isExpressionKind ( fragment ) ) { selectedExpression = fragment ; } return selectedExpression ; } public String getSignaturePreview ( ) throws JavaModelException { String space = "<STR_LIT:U+0020>" ; return "<STR_LIT>" + space + localName ; } public void setReplaceAllOccurrences ( boolean replaceAllOccurrences ) { this . replaceAllOccurrences = replaceAllOccurrences ; } public boolean isReplaceAllOccurrences ( ) { return replaceAllOccurrences ; } public RefactoringStatus checkLocalNameOnChange ( String newName ) { Assert . isTrue ( newName . equals ( getLocalName ( ) ) ) ; String selectedText = getTextAt ( getSelectedFragment ( ) . getStart ( ) , getSelectedFragment ( ) . getEnd ( ) ) ; if ( newName . equals ( selectedText ) ) { return RefactoringStatus . createFatalErrorStatus ( "<STR_LIT>" ) ; } return Checks . checkTempName ( newName , unit ) ; } public String [ ] guessLocalNames ( ) { String text = getBaseNameFromExpression ( getSelectedFragment ( ) ) ; return NamingConventions . suggestVariableNames ( NamingConventions . VK_LOCAL , NamingConventions . BK_NAME , text , unit . getJavaProject ( ) , <NUM_LIT:0> , null , true ) ; } class GuessBaseNameVisitor extends FragmentVisitor { StringBuilder sb = new StringBuilder ( ) ; String getGuessedName ( ) { String name = sb . toString ( ) ; if ( name . length ( ) == <NUM_LIT:0> ) { name = "<STR_LIT>" ; } else { for ( int i = <NUM_LIT:0> ; i < KNOWN_METHOD_NAME_PREFIXES . length ; i ++ ) { String curr = KNOWN_METHOD_NAME_PREFIXES [ i ] ; if ( name . startsWith ( curr ) ) { if ( name . equals ( curr ) ) { return "<STR_LIT>" ; } else if ( Character . isUpperCase ( name . charAt ( curr . length ( ) ) ) ) { return name . substring ( curr . length ( ) ) ; } } } try { Integer . parseInt ( name ) ; name = "<STR_LIT:_>" + name ; } catch ( NumberFormatException e ) { } } if ( name . length ( ) > <NUM_LIT:0> ) { name = "<STR_LIT>" + Character . toLowerCase ( name . charAt ( <NUM_LIT:0> ) ) + name . substring ( <NUM_LIT:1> ) ; } return name ; } @ Override public boolean visit ( BinaryExpressionFragment fragment ) { String nextPart = nameFromExpression ( fragment . getAssociatedExpression ( ) ) ; if ( nextPart != null ) { sb . append ( nextPart ) ; } return true ; } @ Override public boolean visit ( MethodCallFragment fragment ) { String nextPart = nameFromExpression ( fragment . getAssociatedExpression ( ) ) ; if ( nextPart != null ) { sb . append ( nextPart ) ; } return true ; } @ Override public boolean visit ( PropertyExpressionFragment fragment ) { String nextPart = nameFromExpression ( fragment . getAssociatedExpression ( ) ) ; if ( nextPart != null ) { sb . append ( nextPart ) ; } return true ; } @ Override public boolean visit ( SimpleExpressionASTFragment fragment ) { String nextPart = nameFromExpression ( fragment . getAssociatedExpression ( ) ) ; if ( nextPart != null ) { sb . append ( nextPart ) ; } return true ; } private String nameFromExpression ( Expression expr ) { String name = null ; if ( expr instanceof org . codehaus . groovy . ast . expr . CastExpression ) { expr = ( ( CastExpression ) expr ) . getExpression ( ) ; } if ( expr instanceof ConstantExpression ) { name = ( ( ConstantExpression ) expr ) . getText ( ) ; } else if ( expr instanceof MethodCallExpression ) { name = ( ( MethodCallExpression ) expr ) . getMethodAsString ( ) ; } else if ( expr instanceof StaticMethodCallExpression ) { name = ( ( StaticMethodCallExpression ) expr ) . getMethod ( ) ; } else if ( expr instanceof BinaryExpression ) { name = nameFromExpression ( ( ( BinaryExpression ) expr ) . getLeftExpression ( ) ) + nameFromExpression ( ( ( BinaryExpression ) expr ) . getRightExpression ( ) ) ; } else if ( expr instanceof Variable ) { name = ( ( Variable ) expr ) . getName ( ) ; } if ( name != null && name . length ( ) > <NUM_LIT:0> ) { name = "<STR_LIT>" + Character . toUpperCase ( name . charAt ( <NUM_LIT:0> ) ) + name . substring ( <NUM_LIT:1> ) ; } return name ; } } private String getBaseNameFromExpression ( IASTFragment assignedFragment ) { if ( assignedFragment == null ) { return "<STR_LIT>" ; } GuessBaseNameVisitor visitor = new GuessBaseNameVisitor ( ) ; assignedFragment . accept ( visitor ) ; return visitor . getGuessedName ( ) ; } public void setLocalName ( String newName ) { Assert . isNotNull ( newName ) ; localName = newName ; } public String getLocalName ( ) { return localName ; } @ Override public String getName ( ) { return "<STR_LIT>" ; } @ Override public Change createChange ( IProgressMonitor pm ) throws CoreException , OperationCanceledException { try { pm . beginTask ( RefactoringCoreMessages . ExtractTempRefactoring_checking_preconditions , <NUM_LIT:1> ) ; ExtractLocalDescriptor descriptor = createRefactoringDescriptor ( ) ; change . setDescriptor ( new RefactoringChangeDescriptor ( descriptor ) ) ; return change ; } finally { pm . done ( ) ; } } private ExtractLocalDescriptor createRefactoringDescriptor ( ) { final Map < String , String > arguments = new HashMap < String , String > ( ) ; String project = null ; IJavaProject javaProject = unit . getJavaProject ( ) ; if ( javaProject != null ) project = javaProject . getElementName ( ) ; final String description = Messages . format ( RefactoringCoreMessages . ExtractTempRefactoring_descriptor_description_short , BasicElementLabels . getJavaElementName ( localName ) ) ; final String expression = getTextAt ( getSelectedFragment ( ) . getStart ( ) , getSelectedFragment ( ) . getEnd ( ) ) ; final String header = Messages . format ( RefactoringCoreMessages . ExtractTempRefactoring_descriptor_description , new String [ ] { BasicElementLabels . getJavaElementName ( localName ) , BasicElementLabels . getJavaCodeString ( expression ) } ) ; final JDTRefactoringDescriptorComment comment = new JDTRefactoringDescriptorComment ( project , this , header ) ; comment . addSetting ( Messages . format ( RefactoringCoreMessages . ExtractTempRefactoring_name_pattern , BasicElementLabels . getJavaElementName ( localName ) ) ) ; comment . addSetting ( Messages . format ( RefactoringCoreMessages . ExtractTempRefactoring_expression_pattern , BasicElementLabels . getJavaCodeString ( expression ) ) ) ; if ( replaceAllOccurrences ) comment . addSetting ( RefactoringCoreMessages . ExtractTempRefactoring_replace_occurrences ) ; final ExtractLocalDescriptor descriptor = RefactoringSignatureDescriptorFactory . createExtractLocalDescriptor ( project , description , comment . asString ( ) , arguments , RefactoringDescriptor . NONE ) ; arguments . put ( JavaRefactoringDescriptorUtil . ATTRIBUTE_INPUT , JavaRefactoringDescriptorUtil . elementToHandle ( project , unit ) ) ; arguments . put ( JavaRefactoringDescriptorUtil . ATTRIBUTE_NAME , localName ) ; arguments . put ( JavaRefactoringDescriptorUtil . ATTRIBUTE_SELECTION , new Integer ( start ) . toString ( ) + "<STR_LIT:U+0020>" + new Integer ( length ) . toString ( ) ) ; arguments . put ( ATTRIBUTE_REPLACE , Boolean . valueOf ( replaceAllOccurrences ) . toString ( ) ) ; return descriptor ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . extract ; import org . codehaus . groovy . ast . CodeVisitorSupport ; import org . codehaus . groovy . ast . FieldNode ; import org . codehaus . groovy . ast . Parameter ; import org . codehaus . groovy . ast . PropertyNode ; import org . codehaus . groovy . ast . Variable ; import org . codehaus . groovy . ast . expr . ClassExpression ; import org . codehaus . groovy . ast . expr . Expression ; import org . codehaus . groovy . ast . expr . FieldExpression ; import org . codehaus . groovy . ast . expr . MethodCallExpression ; import org . codehaus . groovy . ast . expr . VariableExpression ; import org . codehaus . groovy . eclipse . core . util . VisitCompleteException ; public class StaticExpressionChecker extends CodeVisitorSupport { boolean maybeStatic = true ; public boolean doVisit ( Expression e ) { try { e . visit ( this ) ; } catch ( VisitCompleteException vce ) { } return maybeStatic ; } @ Override public void visitFieldExpression ( FieldExpression expression ) { if ( ! expression . getField ( ) . isStatic ( ) ) { maybeStatic = false ; throw new VisitCompleteException ( ) ; } super . visitFieldExpression ( expression ) ; } @ Override public void visitMethodCallExpression ( MethodCallExpression call ) { if ( ! ( call . getObjectExpression ( ) instanceof ClassExpression ) ) { maybeStatic = false ; throw new VisitCompleteException ( ) ; } super . visitMethodCallExpression ( call ) ; } @ Override public void visitVariableExpression ( VariableExpression expression ) { Variable accessedVar = expression . getAccessedVariable ( ) ; boolean notStatic = false ; if ( accessedVar instanceof Parameter || accessedVar instanceof VariableExpression ) { notStatic = true ; } else if ( accessedVar instanceof FieldNode ) { notStatic = ! ( ( FieldNode ) accessedVar ) . isStatic ( ) ; } else if ( accessedVar instanceof PropertyNode ) { notStatic = ! ( ( PropertyNode ) accessedVar ) . isStatic ( ) ; } if ( notStatic ) { maybeStatic = false ; throw new VisitCompleteException ( ) ; } super . visitVariableExpression ( expression ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . extract ; import org . codehaus . groovy . ast . expr . ClassExpression ; import org . codehaus . groovy . ast . expr . Expression ; import org . codehaus . groovy . eclipse . codebrowsing . fragments . ASTFragmentKind ; import org . codehaus . groovy . eclipse . codebrowsing . fragments . FragmentVisitor ; import org . codehaus . groovy . eclipse . codebrowsing . fragments . IASTFragment ; import org . codehaus . groovy . eclipse . codebrowsing . fragments . MethodCallFragment ; public class StaticFragmentChecker extends FragmentVisitor { private boolean maybeStatic = true ; private boolean previousWasClassExpression = false ; private StaticExpressionChecker expressionChecker ; public boolean mayNotBeStatic ( IASTFragment fragment ) { expressionChecker = new StaticExpressionChecker ( ) ; fragment . accept ( this ) ; return maybeStatic ; } @ Override public boolean previsit ( IASTFragment fragment ) { if ( fragment . kind ( ) == ASTFragmentKind . METHOD_CALL && ! previousWasClassExpression ) { maybeStatic = false ; return false ; } Expression node = fragment . getAssociatedExpression ( ) ; if ( node != null ) { maybeStatic = expressionChecker . doVisit ( node ) ; } previousWasClassExpression = node instanceof ClassExpression ; return maybeStatic ; } @ Override public boolean visit ( MethodCallFragment fragment ) { Expression node = fragment . getArguments ( ) ; if ( node != null ) { maybeStatic = expressionChecker . doVisit ( node ) ; } return maybeStatic ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . extract ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import java . util . Observable ; import java . util . Observer ; import java . util . Set ; import java . util . StringTokenizer ; import org . codehaus . groovy . ast . ClassHelper ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . MethodNode ; import org . codehaus . groovy . ast . ModuleNode ; import org . codehaus . groovy . ast . Parameter ; import org . codehaus . groovy . ast . Variable ; import org . codehaus . groovy . ast . expr . ArgumentListExpression ; import org . codehaus . groovy . ast . expr . BinaryExpression ; import org . codehaus . groovy . ast . expr . DeclarationExpression ; import org . codehaus . groovy . ast . expr . Expression ; import org . codehaus . groovy . ast . expr . MethodCallExpression ; import org . codehaus . groovy . ast . expr . VariableExpression ; import org . codehaus . groovy . ast . stmt . BlockStatement ; import org . codehaus . groovy . ast . stmt . ReturnStatement ; import org . codehaus . groovy . classgen . VariableScopeVisitor ; import org . codehaus . groovy . eclipse . codebrowsing . requestor . Region ; import org . codehaus . groovy . eclipse . core . GroovyCore ; import org . codehaus . groovy . eclipse . core . compiler . GroovySnippetParser ; import org . codehaus . groovy . eclipse . refactoring . Activator ; import org . codehaus . groovy . eclipse . refactoring . core . rewriter . ASTWriter ; import org . codehaus . groovy . eclipse . refactoring . core . utils . ASTTools ; import org . codehaus . groovy . eclipse . refactoring . formatter . DefaultGroovyFormatter ; import org . codehaus . groovy . eclipse . refactoring . formatter . FormatterPreferencesOnStore ; import org . codehaus . groovy . eclipse . refactoring . formatter . GroovyIndentationService ; import org . codehaus . groovy . eclipse . refactoring . ui . extract . GroovyRefactoringMessages ; import org . codehaus . groovy . syntax . Token ; import org . codehaus . groovy . syntax . Types ; import org . codehaus . jdt . groovy . model . GroovyCompilationUnit ; import org . eclipse . core . resources . IFile ; import org . eclipse . core . runtime . Assert ; import org . eclipse . core . runtime . CoreException ; import org . eclipse . core . runtime . IProgressMonitor ; import org . eclipse . core . runtime . OperationCanceledException ; import org . eclipse . core . runtime . SubProgressMonitor ; import org . eclipse . jdt . core . Flags ; import org . eclipse . jdt . core . IJavaElement ; import org . eclipse . jdt . core . refactoring . CompilationUnitChange ; import org . eclipse . jdt . core . refactoring . IJavaRefactorings ; import org . eclipse . jdt . groovy . search . TypeInferencingVisitorFactory ; import org . eclipse . jdt . groovy . search . TypeInferencingVisitorWithRequestor ; import org . eclipse . jdt . groovy . search . VariableScope ; import org . eclipse . jdt . internal . corext . refactoring . JavaRefactoringArguments ; import org . eclipse . jdt . internal . corext . refactoring . JavaRefactoringDescriptorUtil ; import org . eclipse . jdt . internal . corext . refactoring . RefactoringCoreMessages ; import org . eclipse . jdt . internal . corext . util . Messages ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . TextUtilities ; import org . eclipse . ltk . core . refactoring . Change ; import org . eclipse . ltk . core . refactoring . FileStatusContext ; import org . eclipse . ltk . core . refactoring . Refactoring ; import org . eclipse . ltk . core . refactoring . RefactoringStatus ; import org . eclipse . ltk . core . refactoring . TextEditChangeGroup ; import org . eclipse . text . edits . InsertEdit ; import org . eclipse . text . edits . MultiTextEdit ; import org . eclipse . text . edits . ReplaceEdit ; import org . eclipse . text . edits . TextEditGroup ; import org . objectweb . asm . Opcodes ; public class ExtractGroovyMethodRefactoring extends Refactoring { private class GroovyRefactoringObservable extends Observable { @ Override protected synchronized void setChanged ( ) { super . setChanged ( ) ; } @ Override public void notifyObservers ( Object arg ) { super . notifyObservers ( arg ) ; clearChanged ( ) ; } } private GroovyRefactoringObservable observable = new GroovyRefactoringObservable ( ) ; private String newMethodName = "<STR_LIT>" ; private MethodNode newMethod ; private BlockStatement block ; private int newMethodModifier = Flags . AccDefault ; private Region replaceScope ; private Region selectedText ; private StatementFinder methodCodeFinder ; private boolean returnMustBeDeclared = false ; private List < Variable > actualParameters ; private List < ClassNode > inferredTypeOfActualParameters ; private List < Variable > originalParametersBeforeRename ; private Set < Variable > returnParameters ; private List < ClassNode > inferredReturnTypes ; private Map < String , String > variablesToRename ; protected IPreferenceStore refactoringPreferences ; private GroovyCompilationUnit unit ; private CompilationUnitChange change ; public ExtractGroovyMethodRefactoring ( GroovyCompilationUnit unit , int offset , int length , RefactoringStatus status ) { this . refactoringPreferences = Activator . getDefault ( ) . getPreferenceStore ( ) ; this . selectedText = new Region ( offset , length ) ; this . unit = unit ; initializeExtractedStatements ( status ) ; } public ExtractGroovyMethodRefactoring ( JavaRefactoringArguments arguments , RefactoringStatus status ) { status . merge ( initialize ( arguments ) ) ; initializeExtractedStatements ( status ) ; } private void initializeExtractedStatements ( RefactoringStatus status ) { StatementFinder f ; try { f = new StatementFinder ( selectedText , this . unit . getModuleNode ( ) ) ; } catch ( Exception e ) { status . addFatalError ( e . getMessage ( ) , createErrorContext ( ) ) ; f = null ; } methodCodeFinder = f ; createBlockStatement ( ) ; updateMethod ( ) ; saveOriginalParameters ( ) ; } @ Override public RefactoringStatus checkInitialConditions ( IProgressMonitor pm ) throws CoreException , OperationCanceledException { RefactoringStatus status = new RefactoringStatus ( ) ; pm . beginTask ( "<STR_LIT>" , <NUM_LIT:100> ) ; updateMethod ( ) ; if ( pm . isCanceled ( ) ) { throw new OperationCanceledException ( ) ; } status . merge ( checkNrOfReturnValues ( pm ) ) ; if ( pm . isCanceled ( ) ) { throw new OperationCanceledException ( ) ; } status . merge ( checkStatementSelection ( pm ) ) ; if ( pm . isCanceled ( ) ) { throw new OperationCanceledException ( ) ; } status . merge ( checkExtractFromConstructor ( pm ) ) ; if ( pm . isCanceled ( ) ) { throw new OperationCanceledException ( ) ; } pm . done ( ) ; return status ; } @ Override public RefactoringStatus checkFinalConditions ( IProgressMonitor pm ) throws CoreException , OperationCanceledException { RefactoringStatus stat = new RefactoringStatus ( ) ; stat . merge ( checkDuplicateMethod ( pm ) ) ; change = new CompilationUnitChange ( GroovyRefactoringMessages . ExtractMethodRefactoring , unit ) ; change . setEdit ( new MultiTextEdit ( ) ) ; if ( newMethod != null ) { TextEditGroup group = new TextEditGroup ( "<STR_LIT>" , createMethodCallEdit ( ) ) ; change . addChangeGroup ( new TextEditChangeGroup ( change , group ) ) ; change . addEdit ( group . getTextEdits ( ) [ <NUM_LIT:0> ] ) ; group = new TextEditGroup ( "<STR_LIT>" , createMethodDeclarationEdit ( stat ) ) ; change . addChangeGroup ( new TextEditChangeGroup ( change , group ) ) ; change . addEdit ( group . getTextEdits ( ) [ <NUM_LIT:0> ] ) ; } return stat ; } @ Override public Change createChange ( IProgressMonitor pm ) throws CoreException , OperationCanceledException { return change ; } @ Override public String getName ( ) { return "<STR_LIT>" ; } public void setPreferences ( IPreferenceStore preferences ) { this . refactoringPreferences = preferences ; } private RefactoringStatus initialize ( JavaRefactoringArguments arguments ) { final String selection = arguments . getAttribute ( JavaRefactoringDescriptorUtil . ATTRIBUTE_SELECTION ) ; if ( selection == null ) { return RefactoringStatus . createFatalErrorStatus ( Messages . format ( RefactoringCoreMessages . InitializableRefactoring_argument_not_exist , JavaRefactoringDescriptorUtil . ATTRIBUTE_SELECTION ) ) ; } int offset = - <NUM_LIT:1> ; int length = - <NUM_LIT:1> ; final StringTokenizer tokenizer = new StringTokenizer ( selection ) ; if ( tokenizer . hasMoreTokens ( ) ) offset = Integer . valueOf ( tokenizer . nextToken ( ) ) . intValue ( ) ; if ( tokenizer . hasMoreTokens ( ) ) length = Integer . valueOf ( tokenizer . nextToken ( ) ) . intValue ( ) ; if ( offset < <NUM_LIT:0> || length < <NUM_LIT:0> ) return RefactoringStatus . createFatalErrorStatus ( Messages . format ( RefactoringCoreMessages . InitializableRefactoring_illegal_argument , new Object [ ] { selection , JavaRefactoringDescriptorUtil . ATTRIBUTE_SELECTION } ) ) ; selectedText = new Region ( offset , length ) ; final String handle = arguments . getAttribute ( JavaRefactoringDescriptorUtil . ATTRIBUTE_INPUT ) ; if ( handle == null ) return RefactoringStatus . createFatalErrorStatus ( Messages . format ( RefactoringCoreMessages . InitializableRefactoring_argument_not_exist , JavaRefactoringDescriptorUtil . ATTRIBUTE_INPUT ) ) ; IJavaElement element = JavaRefactoringDescriptorUtil . handleToElement ( arguments . getProject ( ) , handle , false ) ; if ( element == null || ! element . exists ( ) || element . getElementType ( ) != IJavaElement . COMPILATION_UNIT || ! ( element instanceof GroovyCompilationUnit ) ) return JavaRefactoringDescriptorUtil . createInputFatalStatus ( element , getName ( ) , IJavaRefactorings . EXTRACT_METHOD ) ; unit = ( GroovyCompilationUnit ) element ; final String name = arguments . getAttribute ( JavaRefactoringDescriptorUtil . ATTRIBUTE_NAME ) ; if ( name == null || name . length ( ) == <NUM_LIT:0> ) return RefactoringStatus . createFatalErrorStatus ( Messages . format ( RefactoringCoreMessages . InitializableRefactoring_argument_not_exist , JavaRefactoringDescriptorUtil . ATTRIBUTE_NAME ) ) ; newMethodName = name ; return new RefactoringStatus ( ) ; } private void saveOriginalParameters ( ) { originalParametersBeforeRename = new ArrayList < Variable > ( ) ; if ( newMethod != null && newMethod . getParameters ( ) != null ) { for ( Parameter p : newMethod . getParameters ( ) ) { originalParametersBeforeRename . add ( p ) ; } } } public void addObserver ( Observer observer ) { observable . addObserver ( observer ) ; } public void setNewMethodname ( String newMethodname ) { this . newMethodName = newMethodname ; updateMethod ( ) ; observable . setChanged ( ) ; observable . notifyObservers ( ) ; } public String getNewMethodName ( ) { return newMethodName ; } public void setModifier ( int modifier ) { this . newMethodModifier = modifier ; updateMethod ( ) ; observable . setChanged ( ) ; observable . notifyObservers ( ) ; } public int getModifier ( ) { return newMethodModifier ; } private void setCallAndMethHeadParameters ( List < Variable > params ) { actualParameters = params ; inferredTypeOfActualParameters . clear ( ) ; for ( Variable variable : params ) { inferredTypeOfActualParameters . add ( variable . getType ( ) ) ; } updateMethod ( ) ; } public Parameter [ ] getCallAndMethHeadParameters ( ) { Parameter [ ] params = new Parameter [ actualParameters . size ( ) ] ; for ( int i = <NUM_LIT:0> ; i < params . length ; i ++ ) { Variable v = actualParameters . get ( i ) ; ClassNode t = inferredTypeOfActualParameters . get ( i ) ; Parameter tmpParam = new Parameter ( t , v . getName ( ) ) ; params [ i ] = tmpParam ; } return params ; } public String getMethodCall ( ) { Expression objExp = new VariableExpression ( "<STR_LIT>" ) ; ArgumentListExpression arguments = new ArgumentListExpression ( ) ; for ( Variable param : originalParametersBeforeRename ) { arguments . addExpression ( new VariableExpression ( param . getName ( ) , param . getOriginType ( ) == null ? ClassHelper . DYNAMIC_TYPE : param . getOriginType ( ) ) ) ; } MethodCallExpression newMethodCall = new MethodCallExpression ( objExp , newMethodName , arguments ) ; ASTWriter writer = new ASTWriter ( unit . getModuleNode ( ) , replaceScope . getOffset ( ) , null ) ; if ( returnParameters . size ( ) > <NUM_LIT:0> ) { visitExpressionsForReturnStmt ( newMethodCall , writer ) ; } else { writer . visitMethodCallExpression ( newMethodCall ) ; } return writer . getGroovyCode ( ) ; } private void visitExpressionsForReturnStmt ( MethodCallExpression newMethodCall , ASTWriter astw ) { Assert . isTrue ( returnParameters . size ( ) > <NUM_LIT:0> ) ; Variable retVar = returnParameters . iterator ( ) . next ( ) ; if ( returnMustBeDeclared ) { VariableExpression varExp = new VariableExpression ( retVar ) ; DeclarationExpression declarationExpression = new DeclarationExpression ( varExp , Token . newSymbol ( Types . ASSIGN , - <NUM_LIT:1> , - <NUM_LIT:1> ) , newMethodCall ) ; astw . visitDeclarationExpression ( declarationExpression ) ; } else { BinaryExpression binaryExpression = new BinaryExpression ( new VariableExpression ( retVar ) , Token . newSymbol ( Types . ASSIGN , - <NUM_LIT:1> , - <NUM_LIT:1> ) , newMethodCall ) ; astw . visitBinaryExpression ( binaryExpression ) ; } } public String getMethodHead ( ) { updateMethod ( ) ; ASTWriter astw = new ASTWriter ( unit . getModuleNode ( ) , null ) ; astw . visitMethod ( newMethod ) ; String head = astw . getGroovyCode ( ) ; int headEndPos = head . indexOf ( "<STR_LIT:)>" ) ; return head . substring ( <NUM_LIT:0> , headEndPos + <NUM_LIT:1> ) . trim ( ) ; } private void updateMethod ( ) { if ( block . getStatements ( ) . size ( ) > <NUM_LIT:0> ) { Parameter [ ] params = getCallAndMethHeadParameters ( ) ; ClassNode returnType = ClassHelper . DYNAMIC_TYPE ; if ( returnParameters . size ( ) > <NUM_LIT:0> ) { returnType = inferredReturnTypes . get ( <NUM_LIT:0> ) ; if ( returnType . equals ( VariableScope . OBJECT_CLASS_NODE ) ) { returnType = ClassHelper . DYNAMIC_TYPE ; } } newMethod = new MethodNode ( newMethodName , <NUM_LIT:0> , returnType , params , null , block ) ; checkStaticModifier ( ) ; } } private void checkStaticModifier ( ) { if ( methodCodeFinder . isStatic ( ) ) { newMethod . setModifiers ( newMethodModifier | Opcodes . ACC_STATIC ) ; } else { newMethod . setModifiers ( newMethodModifier ) ; } } public boolean isStatic ( ) { return methodCodeFinder . isStatic ( ) ; } private void createBlockStatement ( ) { block = new BlockStatement ( ) ; block . addStatements ( methodCodeFinder . getInSelection ( ) ) ; replaceScope = ASTTools . getPositionOfBlockStatements ( block ) ; defineActualAndReturnParameters ( ) ; } private void defineActualAndReturnParameters ( ) { ASTVariableScanner scanner = new ASTVariableScanner ( methodCodeFinder . isInLoopOrClosure ( ) ) ; scanner . visitNode ( block ) ; ASTVariableScanner postSelectionScanner = new ASTVariableScanner ( methodCodeFinder . isInLoopOrClosure ( ) ) ; BlockStatement postBlock = new BlockStatement ( ) ; postBlock . addStatements ( methodCodeFinder . getPostSelection ( ) ) ; postSelectionScanner . visitNode ( postBlock ) ; Set < Variable > postUsedVar = postSelectionScanner . getUsedVariables ( ) ; Set < Variable > selReturnVar = scanner . getAssignedVariables ( ) ; Set < Variable > innerLoopAssigned = scanner . getInnerLoopAssignedVariables ( ) ; actualParameters = new ArrayList < Variable > ( scanner . getUsedVariables ( ) ) ; inferredTypeOfActualParameters = new ArrayList < ClassNode > ( actualParameters . size ( ) ) ; returnParameters = new HashSet < Variable > ( ) ; inferredReturnTypes = new ArrayList < ClassNode > ( ) ; Set < Variable > assignedInBlockAndUsedAfterBlock = new HashSet < Variable > ( postUsedVar ) ; assignedInBlockAndUsedAfterBlock . retainAll ( selReturnVar ) ; returnParameters . addAll ( assignedInBlockAndUsedAfterBlock ) ; returnParameters . addAll ( innerLoopAssigned ) ; for ( Variable variable : returnParameters ) { if ( postUsedVar . contains ( variable ) && scanner . getDeclaratedVariables ( ) . contains ( variable ) ) { returnMustBeDeclared = true ; break ; } } InferParameterAndReturnTypesRequestor inferRequestor = new InferParameterAndReturnTypesRequestor ( actualParameters , returnParameters , selectedText ) ; TypeInferencingVisitorWithRequestor visitor = new TypeInferencingVisitorFactory ( ) . createVisitor ( unit ) ; visitor . visitCompilationUnit ( inferRequestor ) ; Map < Variable , ClassNode > inferredTypes = inferRequestor . getInferredTypes ( ) ; for ( Variable variable : actualParameters ) { if ( inferredTypes . containsKey ( variable ) ) { ClassNode type = inferredTypes . get ( variable ) ; if ( type == null || VariableScope . isVoidOrObject ( type ) ) { inferredTypeOfActualParameters . add ( ClassHelper . DYNAMIC_TYPE ) ; } else { inferredTypeOfActualParameters . add ( maybeConvertToPrimitiveType ( type ) ) ; } } else { inferredTypeOfActualParameters . add ( ClassHelper . DYNAMIC_TYPE ) ; } } for ( Variable variable : returnParameters ) { if ( inferredTypes . containsKey ( variable ) ) { inferredReturnTypes . add ( maybeConvertToPrimitiveType ( inferredTypes . get ( variable ) ) ) ; } else { inferredReturnTypes . add ( variable . getOriginType ( ) ) ; } } } private ClassNode maybeConvertToPrimitiveType ( ClassNode type ) { return ClassHelper . getUnwrapper ( type ) . getPlainNodeReference ( ) ; } private RefactoringStatus checkDuplicateMethod ( IProgressMonitor pm ) { SubProgressMonitor sub = new SubProgressMonitor ( pm , <NUM_LIT> ) ; sub . beginTask ( "<STR_LIT>" , <NUM_LIT> ) ; RefactoringStatus stat = new RefactoringStatus ( ) ; if ( getMethodNames ( ) . contains ( newMethodName ) ) { Object [ ] message = { newMethodName , getClassName ( ) } ; String messageString = MessageFormat . format ( GroovyRefactoringMessages . ExtractMethodWizard_MethodNameAlreadyExists , message ) ; stat . addError ( messageString ) ; } sub . done ( ) ; return stat ; } private RefactoringStatus checkExtractFromConstructor ( IProgressMonitor pm ) { SubProgressMonitor sub = new SubProgressMonitor ( pm , <NUM_LIT> ) ; sub . beginTask ( "<STR_LIT>" , <NUM_LIT> ) ; RefactoringStatus stat = new RefactoringStatus ( ) ; if ( methodCodeFinder . isInConstructor ( ) ) { if ( new ExtractConstructorTest ( ) . containsConstructorCall ( newMethod ) ) { stat . addFatalError ( GroovyRefactoringMessages . ExtractMethodInfo_NoExtractionOfConstructorCallinConstructor , createErrorContext ( ) ) ; } } sub . done ( ) ; return stat ; } private RefactoringStatus checkStatementSelection ( IProgressMonitor pm ) { SubProgressMonitor sub = new SubProgressMonitor ( pm , <NUM_LIT> ) ; sub . beginTask ( "<STR_LIT>" , <NUM_LIT> ) ; RefactoringStatus stat = new RefactoringStatus ( ) ; int selectionLength = selectedText . getLength ( ) ; if ( block . isEmpty ( ) && selectionLength >= <NUM_LIT:0> ) { stat . addFatalError ( GroovyRefactoringMessages . ExtractMethodInfo_NoStatementSelected , createErrorContext ( ) ) ; } sub . done ( ) ; return stat ; } private RefactoringStatus checkNrOfReturnValues ( IProgressMonitor pm ) { SubProgressMonitor sub = new SubProgressMonitor ( pm , <NUM_LIT> ) ; sub . beginTask ( "<STR_LIT>" , <NUM_LIT> ) ; RefactoringStatus stat = new RefactoringStatus ( ) ; if ( returnParameters != null && returnParameters . size ( ) > <NUM_LIT:1> ) { StringBuilder retValues = new StringBuilder ( ) ; for ( Variable var : returnParameters ) { retValues . append ( var . getType ( ) . getNameWithoutPackage ( ) + "<STR_LIT:U+0020>" + var . getName ( ) + "<STR_LIT:n>" ) ; } String errorMsg = GroovyRefactoringMessages . ExtractMethodInfo_ToMuchReturnValues + retValues . toString ( ) ; stat . addFatalError ( errorMsg , createErrorContext ( ) ) ; } sub . done ( ) ; return stat ; } private String createCopiedMethodCode ( RefactoringStatus status ) { IDocument unitDocument = new Document ( String . valueOf ( unit . getContents ( ) ) ) ; String lineDelimiter = TextUtilities . getDefaultLineDelimiter ( unitDocument ) ; StringBuilder sb = new StringBuilder ( ) ; try { final FormatterPreferencesOnStore formmatterPrefs = new FormatterPreferencesOnStore ( refactoringPreferences ) ; int indentation = calculateIndentation ( ) ; sb . append ( lineDelimiter + lineDelimiter + GroovyIndentationService . createIndentation ( formmatterPrefs , indentation * formmatterPrefs . getIndentationSize ( ) ) ) ; sb . append ( getMethodHead ( ) ) . append ( "<STR_LIT>" ) . append ( lineDelimiter ) ; String copyOfSourceCode = unitDocument . get ( replaceScope . getOffset ( ) , replaceScope . getLength ( ) ) ; sb . append ( copyOfSourceCode ) ; sb . append ( lineDelimiter ) ; ASTWriter astw = writeReturnStatements ( unitDocument ) ; if ( astw . getGroovyCode ( ) . length ( ) > <NUM_LIT:0> ) { sb . append ( astw . getGroovyCode ( ) ) ; } sb . append ( "<STR_LIT:}>" ) ; MethodNode newMethod = createNewMethodForValidation ( sb . toString ( ) , status ) ; IDocument newMethodDocument = new Document ( sb . toString ( ) ) ; if ( newMethod != null && variablesToRename != null ) { MultiTextEdit edits = renameVariableInExtractedMethod ( newMethod ) ; edits . apply ( newMethodDocument ) ; } DefaultGroovyFormatter formatter = new DefaultGroovyFormatter ( newMethodDocument , formmatterPrefs , indentation ) ; formatter . format ( ) . apply ( newMethodDocument ) ; return newMethodDocument . get ( ) ; } catch ( BadLocationException e ) { status . addFatalError ( "<STR_LIT>" + e . getMessage ( ) , createErrorContext ( ) ) ; GroovyCore . logException ( "<STR_LIT>" , e ) ; } return sb . toString ( ) ; } private MethodNode createNewMethodForValidation ( String methodText , RefactoringStatus status ) { try { GroovySnippetParser parser = new GroovySnippetParser ( ) ; ModuleNode module = parser . parse ( methodText ) ; if ( module . getMethods ( ) == null || module . getMethods ( ) . size ( ) != <NUM_LIT:1> ) { status . addError ( "<STR_LIT>" , createErrorContext ( ) ) ; if ( module . getMethods ( ) == null ) { return null ; } } MethodNode method = ( MethodNode ) module . getMethods ( ) . get ( <NUM_LIT:0> ) ; new VariableScopeVisitor ( null ) . visitClass ( method . getDeclaringClass ( ) ) ; return method ; } catch ( Exception e ) { status . addError ( "<STR_LIT>" + e . getMessage ( ) , createErrorContext ( ) ) ; } return null ; } private FileStatusContext createErrorContext ( ) { return new FileStatusContext ( ( IFile ) unit . getResource ( ) , new org . eclipse . jface . text . Region ( selectedText . getOffset ( ) , selectedText . getLength ( ) ) ) ; } private int calculateIndentation ( ) { int defaultIndentation ; if ( methodCodeFinder . getClassNode ( ) . isScript ( ) ) { defaultIndentation = <NUM_LIT:0> ; } else { int innerClassCount = <NUM_LIT:0> ; ClassNode current = methodCodeFinder . getClassNode ( ) ; while ( current != null ) { innerClassCount ++ ; if ( current . getEnclosingMethod ( ) != null ) { innerClassCount ++ ; current = current . getEnclosingMethod ( ) . getDeclaringClass ( ) ; continue ; } current = current . getDeclaringClass ( ) ; } defaultIndentation = innerClassCount ; } return defaultIndentation ; } private MultiTextEdit renameVariableInExtractedMethod ( MethodNode method ) { VariableRenamer renamer = new VariableRenamer ( ) ; return renamer . rename ( method , variablesToRename ) ; } private ASTWriter writeReturnStatements ( IDocument document ) { ASTWriter astw = new ASTWriter ( unit . getModuleNode ( ) , document ) ; for ( Variable var : returnParameters ) { ReturnStatement ret = new ReturnStatement ( new VariableExpression ( var ) ) ; astw . visitReturnStatement ( ret ) ; astw . insertLineFeed ( ) ; } return astw ; } private InsertEdit createMethodDeclarationEdit ( RefactoringStatus status ) { String newMethodCode = createCopiedMethodCode ( status ) ; return new InsertEdit ( methodCodeFinder . getSelectedDeclaration ( ) . getEnd ( ) , newMethodCode ) ; } private ReplaceEdit createMethodCallEdit ( ) { int offset = replaceScope . getOffset ( ) ; int length = replaceScope . getLength ( ) ; ReplaceEdit insertMethodCall = new ReplaceEdit ( offset , length , getMethodCall ( ) ) ; return insertMethodCall ; } public List < String > getMethodNames ( ) { return methodCodeFinder . getMethodNames ( ) ; } public String getClassName ( ) { return methodCodeFinder . getClassName ( ) ; } public int setMoveParameter ( String variName , boolean upEvent , int numberOfMoves ) { Parameter [ ] originalParams = getCallAndMethHeadParameters ( ) ; List < Variable > newParamList = new ArrayList < Variable > ( ) ; int indexOfSelectedParam = - <NUM_LIT:1> ; for ( Parameter param : originalParams ) { newParamList . add ( param ) ; if ( param . getName ( ) . equals ( variName ) ) { indexOfSelectedParam = newParamList . indexOf ( param ) ; } } indexOfSelectedParam = reorderParameters ( upEvent , numberOfMoves , newParamList , indexOfSelectedParam ) ; setCallAndMethHeadParameters ( newParamList ) ; return indexOfSelectedParam ; } private int reorderParameters ( boolean upEvent , int numberOfMoves , List < Variable > newParamList , int index ) { int indexOfSelectedParam = index ; Variable variToMove = newParamList . remove ( indexOfSelectedParam ) ; Variable originalToMove = originalParametersBeforeRename . remove ( indexOfSelectedParam ) ; indexOfSelectedParam = calculateNewIndexAfterMove ( upEvent , numberOfMoves , newParamList , indexOfSelectedParam ) ; newParamList . add ( indexOfSelectedParam , variToMove ) ; originalParametersBeforeRename . add ( indexOfSelectedParam , originalToMove ) ; return indexOfSelectedParam ; } private int calculateNewIndexAfterMove ( boolean upEvent , int numberOfMoves , List < Variable > newParamList , int index ) { int indexOfSelectedParam = index ; if ( upEvent ) { if ( indexOfSelectedParam < <NUM_LIT:1> ) indexOfSelectedParam = <NUM_LIT:0> ; else indexOfSelectedParam -= numberOfMoves ; } else { if ( indexOfSelectedParam > newParamList . size ( ) - <NUM_LIT:1> ) indexOfSelectedParam = newParamList . size ( ) - <NUM_LIT:1> ; else indexOfSelectedParam += numberOfMoves ; } return indexOfSelectedParam ; } public void setParameterRename ( Map < String , String > variablesToRename ) { this . variablesToRename = variablesToRename ; List < Variable > newParamList = new ArrayList < Variable > ( ) ; for ( Variable param : originalParametersBeforeRename ) { if ( variablesToRename . containsKey ( param . getName ( ) ) ) { newParamList . add ( new Parameter ( param . getOriginType ( ) , variablesToRename . get ( param . getName ( ) ) ) ) ; } else { newParamList . add ( param ) ; } } setCallAndMethHeadParameters ( newParamList ) ; observable . setChanged ( ) ; observable . notifyObservers ( ) ; } public String getOriginalParameterName ( int selectionIndex ) { return originalParametersBeforeRename . get ( selectionIndex ) . getName ( ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . convert ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . FieldNode ; import org . codehaus . groovy . ast . Parameter ; import org . codehaus . groovy . ast . expr . ClosureExpression ; import org . codehaus . groovy . eclipse . core . GroovyCore ; import org . codehaus . jdt . groovy . model . GroovyCompilationUnit ; import org . eclipse . jdt . core . IField ; import org . eclipse . jdt . core . IJavaElement ; import org . eclipse . jdt . core . JavaModelException ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . text . edits . MultiTextEdit ; import org . eclipse . text . edits . ReplaceEdit ; import org . eclipse . text . edits . TextEdit ; public class ConvertToMethodRefactoring { private final FieldNode targetField ; private IField field ; public ConvertToMethodRefactoring ( GroovyCompilationUnit unit , int offset ) { this . targetField = getTargetField ( unit , offset ) ; } private FieldNode getTargetField ( GroovyCompilationUnit unit , int offset ) { if ( unit . isOnBuildPath ( ) ) { return null ; } try { FieldNode targetField = null ; IJavaElement maybeField = unit . getElementAt ( offset ) ; boolean result = maybeField instanceof IField && ( ( IField ) maybeField ) . getNameRange ( ) . getOffset ( ) > <NUM_LIT:0> ; if ( result ) { field = ( IField ) maybeField ; for ( ClassNode clazz : unit . getModuleNode ( ) . getClasses ( ) ) { if ( clazz . getNameWithoutPackage ( ) . equals ( maybeField . getParent ( ) . getElementName ( ) ) ) { targetField = clazz . getDeclaredField ( field . getElementName ( ) ) ; if ( targetField != null && targetField . getInitialExpression ( ) instanceof ClosureExpression ) { result = true ; break ; } } } } if ( result ) { return targetField ; } } catch ( JavaModelException e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; } return null ; } public boolean isApplicable ( ) { return targetField != null && field != null && field . exists ( ) ; } public void applyRefactoring ( IDocument document ) { if ( targetField != null ) { TextEdit thisEdit = findReplacement ( document ) ; try { if ( thisEdit != null ) { thisEdit . apply ( document ) ; } } catch ( Exception e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; } } } private TextEdit findReplacement ( IDocument doc ) { try { int afterName = targetField . getNameEnd ( ) + <NUM_LIT:1> ; int openingBracket = findOpenBracket ( doc , targetField , afterName ) ; int afterLastParam = findAfterLastParam ( targetField ) ; int afterArrow = findAfterArrow ( doc , afterLastParam ) ; return createEdit ( doc , afterName , openingBracket , afterLastParam , afterArrow ) ; } catch ( Exception e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; return null ; } } private static int findOpenBracket ( IDocument doc , FieldNode targetField , int afterName ) throws BadLocationException { int offset = afterName ; while ( offset < doc . getLength ( ) && doc . getChar ( offset ) != '<CHAR_LIT>' ) { offset ++ ; } Parameter [ ] parameters = getClosureParameters ( targetField ) ; if ( parameters != null && parameters . length > <NUM_LIT:0> ) { int firstParameterStart = parameters [ <NUM_LIT:0> ] . getStart ( ) ; offset ++ ; while ( offset < firstParameterStart && Character . isWhitespace ( doc . getChar ( offset ) ) ) { offset ++ ; } offset -- ; } return offset ; } private static int findAfterLastParam ( FieldNode targetField ) { Parameter [ ] parameters = getClosureParameters ( targetField ) ; if ( parameters == null || parameters . length == <NUM_LIT:0> ) { return - <NUM_LIT:1> ; } else { Parameter lastParam = parameters [ parameters . length - <NUM_LIT:1> ] ; if ( lastParam . getInitialExpression ( ) != null ) { return lastParam . getInitialExpression ( ) . getEnd ( ) ; } else { return lastParam . getNameEnd ( ) ; } } } private static Parameter [ ] getClosureParameters ( FieldNode targetField ) { ClosureExpression closure = ( ClosureExpression ) targetField . getInitialExpression ( ) ; Parameter [ ] parameters = closure . getParameters ( ) ; return parameters ; } private static int findAfterArrow ( IDocument doc , int afterLastParam ) throws BadLocationException { if ( afterLastParam == - <NUM_LIT:1> ) { return - <NUM_LIT:1> ; } int offset = afterLastParam ; while ( offset < doc . getLength ( ) - <NUM_LIT:1> ) { if ( doc . getChar ( offset ) == '<CHAR_LIT:->' && doc . getChar ( offset + <NUM_LIT:1> ) == '<CHAR_LIT:>>' ) { return ++ offset ; } offset ++ ; } return - <NUM_LIT:1> ; } private static TextEdit createEdit ( IDocument doc , int afterName , int openingBracket , int afterLastParam , int afterArrow ) throws BadLocationException { if ( ! ( openingBracket < doc . getLength ( ) && ( doc . getChar ( openingBracket ) == '<CHAR_LIT>' ) || Character . isWhitespace ( doc . getChar ( openingBracket ) ) ) ) { return null ; } if ( afterLastParam > - <NUM_LIT:1> && afterArrow == - <NUM_LIT:1> ) { return null ; } TextEdit edit ; if ( afterLastParam > - <NUM_LIT:1> ) { edit = new MultiTextEdit ( ) ; edit . addChild ( new ReplaceEdit ( afterName , openingBracket - afterName + <NUM_LIT:1> , "<STR_LIT:(>" ) ) ; edit . addChild ( new ReplaceEdit ( afterLastParam , afterArrow - afterLastParam + <NUM_LIT:1> , "<STR_LIT>" ) ) ; } else { edit = new ReplaceEdit ( afterName , openingBracket - afterName + <NUM_LIT:1> , "<STR_LIT>" ) ; } return edit ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . convert ; import java . util . List ; import java . util . Set ; import org . codehaus . groovy . ast . ClassCodeVisitorSupport ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . ModuleNode ; import org . codehaus . groovy . ast . Variable ; import org . codehaus . groovy . ast . expr . BinaryExpression ; import org . codehaus . groovy . ast . expr . ClassExpression ; import org . codehaus . groovy . ast . expr . ConstantExpression ; import org . codehaus . groovy . ast . expr . Expression ; import org . codehaus . groovy . ast . expr . ListExpression ; import org . codehaus . groovy . ast . expr . MapExpression ; import org . codehaus . groovy . ast . expr . MethodCallExpression ; import org . codehaus . groovy . ast . expr . StaticMethodCallExpression ; import org . codehaus . groovy . ast . expr . VariableExpression ; import org . codehaus . groovy . ast . stmt . ExpressionStatement ; import org . codehaus . groovy . control . SourceUnit ; import org . codehaus . groovy . eclipse . codebrowsing . requestor . Region ; import org . codehaus . groovy . eclipse . core . GroovyCore ; import org . codehaus . groovy . eclipse . core . util . VisitCompleteException ; import org . codehaus . groovy . eclipse . refactoring . core . utils . ASTTools ; import org . codehaus . jdt . groovy . model . GroovyCompilationUnit ; import org . eclipse . jdt . core . NamingConventions ; import org . eclipse . jface . text . IDocument ; import org . eclipse . swt . graphics . Point ; import org . eclipse . text . edits . InsertEdit ; import org . eclipse . text . edits . MultiTextEdit ; import org . eclipse . text . edits . TextEdit ; public class AssignStatementToNewLocalRefactoring { private final GroovyCompilationUnit unit ; private final int length ; private final int offset ; private int newLength ; private int newOffset ; private boolean atExpressionStatement ; private Region region ; private Expression expression ; public AssignStatementToNewLocalRefactoring ( GroovyCompilationUnit unit , int offset ) { this . unit = unit ; length = <NUM_LIT:0> ; this . offset = offset ; } public void applyRefactoring ( IDocument document ) { if ( atExpressionStatement ) { TextEdit thisEdit = findReplacement ( document ) ; try { if ( thisEdit != null ) { thisEdit . apply ( document ) ; } } catch ( Exception e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; } } } public boolean isApplicable ( ) { if ( unit == null ) { return false ; } return this . atExpressionStatement ( ) ; } private boolean atExpressionStatement ( ) { region = new Region ( offset , length ) ; atExpressionStatement = false ; ClassCodeVisitorSupport visitor = new ClassCodeVisitorSupport ( ) { @ Override public void visitExpressionStatement ( ExpressionStatement statement ) { if ( region . regionIsCoveredByNode ( statement ) ) { if ( statement . getExpression ( ) instanceof org . codehaus . groovy . ast . expr . BinaryExpression ) { BinaryExpression bexp = ( BinaryExpression ) statement . getExpression ( ) ; if ( ! bexp . getOperation ( ) . getText ( ) . equals ( "<STR_LIT:=>" ) ) { expression = statement . getExpression ( ) ; atExpressionStatement = true ; } else { throw new VisitCompleteException ( ) ; } } else { expression = statement . getExpression ( ) ; atExpressionStatement = true ; } } super . visitExpressionStatement ( statement ) ; } @ Override protected SourceUnit getSourceUnit ( ) { return null ; } } ; ModuleNode moduleNode = unit . getModuleNode ( ) ; List < ClassNode > classes = moduleNode . getClasses ( ) ; if ( classes . isEmpty ( ) ) { classes . add ( moduleNode . getScriptClassDummy ( ) ) ; } for ( ClassNode classNode : classes ) { try { visitor . visitClass ( classNode ) ; } catch ( VisitCompleteException expected ) { break ; } } return atExpressionStatement ; } private TextEdit findReplacement ( IDocument doc ) { try { return createEdit ( doc , expression ) ; } catch ( Exception e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; return null ; } } private TextEdit createEdit ( IDocument doc , Expression expression ) { TextEdit edit = new MultiTextEdit ( ) ; String candidate ; if ( expression instanceof ConstantExpression ) { candidate = ( ( ConstantExpression ) expression ) . getText ( ) ; } else if ( expression instanceof VariableExpression ) { candidate = ( ( VariableExpression ) expression ) . getName ( ) ; } else if ( expression instanceof ClassExpression ) { candidate = ( ( ClassExpression ) expression ) . getType ( ) . getNameWithoutPackage ( ) ; } else if ( expression instanceof MethodCallExpression ) { candidate = ( ( MethodCallExpression ) expression ) . getMethodAsString ( ) ; } else if ( expression instanceof StaticMethodCallExpression ) { candidate = ( ( StaticMethodCallExpression ) expression ) . getMethod ( ) ; } else if ( expression instanceof MapExpression ) { candidate = "<STR_LIT>" ; } else if ( expression instanceof ListExpression ) { candidate = "<STR_LIT:list>" ; } else { candidate = "<STR_LIT>" ; } Set < Variable > vars = ASTTools . getVariablesInScope ( unit . getModuleNode ( ) , expression ) ; String [ ] variableNames = new String [ vars . size ( ) ] ; int i = <NUM_LIT:0> ; for ( Variable v : vars ) { variableNames [ i ] = v . getName ( ) ; i ++ ; } String [ ] names = NamingConventions . suggestVariableNames ( NamingConventions . VK_LOCAL , NamingConventions . BK_NAME , candidate , null , <NUM_LIT:0> , variableNames , true ) ; edit . addChild ( new InsertEdit ( expression . getStart ( ) , "<STR_LIT>" + names [ <NUM_LIT:0> ] + "<STR_LIT:U+0020=U+0020>" ) ) ; newOffset = expression . getStart ( ) + <NUM_LIT:4> ; newLength = names [ <NUM_LIT:0> ] . length ( ) ; return edit ; } public Point getNewSelection ( ) { return new Point ( newOffset , newLength ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . convert ; import javax . swing . text . BadLocationException ; import org . codehaus . groovy . eclipse . core . GroovyCore ; import org . codehaus . jdt . groovy . model . GroovyCompilationUnit ; import org . eclipse . jdt . core . IJavaElement ; import org . eclipse . jdt . core . IMethod ; import org . eclipse . jdt . core . ISourceRange ; import org . eclipse . jdt . core . JavaModelException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . text . edits . DeleteEdit ; import org . eclipse . text . edits . MultiTextEdit ; import org . eclipse . text . edits . ReplaceEdit ; import org . eclipse . text . edits . TextEdit ; public class ConvertToClosureRefactoring { private final IMethod targetMethod ; public ConvertToClosureRefactoring ( GroovyCompilationUnit unit , int offset ) { targetMethod = findMethod ( unit , offset ) ; } private IMethod findMethod ( GroovyCompilationUnit unit , int offset ) { if ( unit . isOnBuildPath ( ) ) { return null ; } try { IJavaElement maybeMethod = unit . getElementAt ( offset ) ; if ( ! ( maybeMethod instanceof IMethod ) ) { return null ; } ISourceRange nameRange = ( ( IMethod ) maybeMethod ) . getNameRange ( ) ; if ( nameRange . getLength ( ) == maybeMethod . getElementName ( ) . length ( ) ) { return ( ( IMethod ) maybeMethod ) ; } char [ ] contents = unit . getContents ( ) ; if ( contents . length > nameRange . getOffset ( ) && contents [ nameRange . getOffset ( ) ] == '<CHAR_LIT:">' ) { return ( ( IMethod ) maybeMethod ) ; } } catch ( JavaModelException e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; } return null ; } public void applyRefactoring ( IDocument document ) { if ( targetMethod != null ) { TextEdit thisEdit = findReplacement ( document , targetMethod ) ; try { if ( thisEdit != null ) { thisEdit . apply ( document ) ; } } catch ( Exception e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; } } } public boolean isApplicable ( ) { return targetMethod != null && targetMethod . exists ( ) ; } private TextEdit findReplacement ( IDocument doc , IMethod targetMethod ) { try { ISourceRange nameRange = targetMethod . getSourceRange ( ) ; int openingParen = findOpenParen ( doc , targetMethod , nameRange ) ; int closingParen = findCloseParen ( doc , openingParen ) ; int openingBracket = findOpenBracket ( doc , closingParen ) ; return createEdit ( doc , targetMethod , openingParen , closingParen , openingBracket ) ; } catch ( Exception e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; return null ; } } private int findOpenParen ( IDocument doc , IMethod targetMethod , ISourceRange nameRange ) throws BadLocationException , org . eclipse . jface . text . BadLocationException { int offset = nameRange . getOffset ( ) + targetMethod . getElementName ( ) . length ( ) ; while ( offset < doc . getLength ( ) && doc . getChar ( offset ) != '<CHAR_LIT:(>' ) { offset ++ ; } return offset ; } private int findOpenBracket ( IDocument doc , int closingParen ) throws BadLocationException , org . eclipse . jface . text . BadLocationException { int offset = closingParen ; while ( offset < doc . getLength ( ) && doc . getChar ( offset ) != '<CHAR_LIT>' ) { offset ++ ; } return offset ; } private int findCloseParen ( IDocument doc , int open ) throws BadLocationException , org . eclipse . jface . text . BadLocationException { int offset = open ; while ( offset < doc . getLength ( ) && doc . getChar ( offset ) != '<CHAR_LIT:)>' ) { offset ++ ; } return offset ; } private TextEdit createEdit ( IDocument doc , IMethod targetMethod , int openingParen , int closingParen , int openingBracket ) throws BadLocationException , org . eclipse . jface . text . BadLocationException { if ( ! ( openingParen < doc . getLength ( ) && doc . getChar ( openingParen ) == '<CHAR_LIT:(>' ) ) { return null ; } if ( ! ( closingParen < doc . getLength ( ) && doc . getChar ( closingParen ) == '<CHAR_LIT:)>' ) ) { return null ; } if ( ! ( openingBracket < doc . getLength ( ) && doc . getChar ( openingBracket ) == '<CHAR_LIT>' ) ) { return null ; } TextEdit edit = new MultiTextEdit ( ) ; if ( targetMethod . getParameterTypes ( ) . length > <NUM_LIT:0> ) { edit . addChild ( new ReplaceEdit ( openingParen , <NUM_LIT:1> , "<STR_LIT>" ) ) ; edit . addChild ( new ReplaceEdit ( closingParen , openingBracket - closingParen + <NUM_LIT:1> , "<STR_LIT>" ) ) ; } else { edit . addChild ( new ReplaceEdit ( openingParen , <NUM_LIT:1> , "<STR_LIT>" ) ) ; edit . addChild ( new DeleteEdit ( closingParen , openingBracket - closingParen + <NUM_LIT:1> ) ) ; } return edit ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . GroovyCodeVisitor ; public class StaticClassImport extends RefactoringImportNode { public StaticClassImport ( ClassNode type ) { super ( type , null ) ; } @ Override public String getText ( ) { return "<STR_LIT>" + newClassName + "<STR_LIT>" ; } @ Override public void visit ( GroovyCodeVisitor visitor ) { if ( visitor instanceof AbstractRefactoringCodeVisitor ) { ( ( AbstractRefactoringCodeVisitor ) visitor ) . visitStaticClassImport ( this ) ; } } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner ; import org . codehaus . groovy . ast . ASTNode ; import org . codehaus . groovy . ast . ModuleNode ; import org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner . predicates . IASTNodePredicate ; public abstract class ASTScannerPredicate extends RefactoringCodeVisitorSupport { protected IASTNodePredicate predicate ; public ASTScannerPredicate ( ModuleNode rootNode , IASTNodePredicate predicate ) { super ( rootNode ) ; this . predicate = predicate ; } @ Override protected void analyzeNode ( ASTNode node ) { ASTNode evaluatedNode ; if ( ( evaluatedNode = predicate . evaluate ( node ) ) != null ) { doOnPredicate ( evaluatedNode ) ; } } @ Override public void visitStaticFieldImport ( StaticFieldImport staticAliasImport ) { analyzeNode ( staticAliasImport ) ; } @ Override public void visitStaticClassImport ( StaticClassImport staticClassImport ) { analyzeNode ( staticClassImport ) ; } @ Override public void visitClassImport ( ClassImport classImport ) { analyzeNode ( classImport ) ; } abstract void doOnPredicate ( ASTNode node ) ; } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . ImportNode ; public abstract class RefactoringImportNode extends ImportNode { protected String newClassName ; public RefactoringImportNode ( ImportNode importNode ) { super ( importNode . getType ( ) , importNode . getAlias ( ) ) ; init ( ) ; } public RefactoringImportNode ( ClassNode type , String alias ) { super ( type , alias ) ; init ( ) ; } public void setNewClassName ( String newName ) { this . newClassName = getType ( ) . getPackageName ( ) + "<STR_LIT:.>" + newName ; } @ Override public abstract String getText ( ) ; private void init ( ) { this . newClassName = getType ( ) . getName ( ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner ; import java . util . Collection ; import java . util . Iterator ; import java . util . List ; import java . util . Map . Entry ; import org . codehaus . groovy . ast . ASTNode ; import org . codehaus . groovy . ast . AnnotatedNode ; import org . codehaus . groovy . ast . AnnotationNode ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . ConstructorNode ; import org . codehaus . groovy . ast . FieldNode ; import org . codehaus . groovy . ast . GenericsType ; import org . codehaus . groovy . ast . ImportNode ; import org . codehaus . groovy . ast . MethodNode ; import org . codehaus . groovy . ast . ModuleNode ; import org . codehaus . groovy . ast . Parameter ; import org . codehaus . groovy . ast . PropertyNode ; import org . codehaus . groovy . ast . expr . ArgumentListExpression ; import org . codehaus . groovy . ast . expr . ArrayExpression ; import org . codehaus . groovy . ast . expr . AttributeExpression ; import org . codehaus . groovy . ast . expr . BinaryExpression ; import org . codehaus . groovy . ast . expr . BitwiseNegationExpression ; import org . codehaus . groovy . ast . expr . BooleanExpression ; import org . codehaus . groovy . ast . expr . CastExpression ; import org . codehaus . groovy . ast . expr . ClassExpression ; import org . codehaus . groovy . ast . expr . ClosureExpression ; import org . codehaus . groovy . ast . expr . ClosureListExpression ; import org . codehaus . groovy . ast . expr . ConstantExpression ; import org . codehaus . groovy . ast . expr . ConstructorCallExpression ; import org . codehaus . groovy . ast . expr . DeclarationExpression ; import org . codehaus . groovy . ast . expr . ElvisOperatorExpression ; import org . codehaus . groovy . ast . expr . Expression ; import org . codehaus . groovy . ast . expr . FieldExpression ; import org . codehaus . groovy . ast . expr . GStringExpression ; import org . codehaus . groovy . ast . expr . ListExpression ; import org . codehaus . groovy . ast . expr . MapEntryExpression ; import org . codehaus . groovy . ast . expr . MapExpression ; import org . codehaus . groovy . ast . expr . MethodCallExpression ; import org . codehaus . groovy . ast . expr . MethodPointerExpression ; import org . codehaus . groovy . ast . expr . NotExpression ; import org . codehaus . groovy . ast . expr . PostfixExpression ; import org . codehaus . groovy . ast . expr . PrefixExpression ; import org . codehaus . groovy . ast . expr . PropertyExpression ; import org . codehaus . groovy . ast . expr . RangeExpression ; import org . codehaus . groovy . ast . expr . SpreadExpression ; import org . codehaus . groovy . ast . expr . SpreadMapExpression ; import org . codehaus . groovy . ast . expr . StaticMethodCallExpression ; import org . codehaus . groovy . ast . expr . TernaryExpression ; import org . codehaus . groovy . ast . expr . TupleExpression ; import org . codehaus . groovy . ast . expr . UnaryMinusExpression ; import org . codehaus . groovy . ast . expr . UnaryPlusExpression ; import org . codehaus . groovy . ast . expr . VariableExpression ; import org . codehaus . groovy . ast . stmt . AssertStatement ; import org . codehaus . groovy . ast . stmt . BlockStatement ; import org . codehaus . groovy . ast . stmt . BreakStatement ; import org . codehaus . groovy . ast . stmt . CaseStatement ; import org . codehaus . groovy . ast . stmt . CatchStatement ; import org . codehaus . groovy . ast . stmt . ContinueStatement ; import org . codehaus . groovy . ast . stmt . DoWhileStatement ; import org . codehaus . groovy . ast . stmt . ExpressionStatement ; import org . codehaus . groovy . ast . stmt . ForStatement ; import org . codehaus . groovy . ast . stmt . IfStatement ; import org . codehaus . groovy . ast . stmt . ReturnStatement ; import org . codehaus . groovy . ast . stmt . Statement ; import org . codehaus . groovy . ast . stmt . SwitchStatement ; import org . codehaus . groovy . ast . stmt . SynchronizedStatement ; import org . codehaus . groovy . ast . stmt . ThrowStatement ; import org . codehaus . groovy . ast . stmt . TryCatchStatement ; import org . codehaus . groovy . ast . stmt . WhileStatement ; public abstract class RefactoringCodeVisitorSupport extends AbstractRefactoringCodeVisitor { protected ModuleNode rootNode ; public RefactoringCodeVisitorSupport ( ModuleNode rootNode ) { this . rootNode = rootNode ; } @ Override public void visitClassImport ( ClassImport classImport ) { } protected void analyzeNode ( ASTNode node ) { } protected void clear ( ASTNode node ) { } @ Override public void visitStaticClassImport ( StaticClassImport staticClassImport ) { } @ Override public void visitStaticFieldImport ( StaticFieldImport staticAliasImport ) { } @ Override public void scanAST ( ) { analyseClassImports ( ) ; analyseStaticClassImport ( ) ; analyseStaticFieldImport ( ) ; if ( ! rootNode . getStatementBlock ( ) . isEmpty ( ) ) { for ( Statement statement : ( Iterable < Statement > ) rootNode . getStatementBlock ( ) . getStatements ( ) ) { statement . visit ( this ) ; } } List < ClassNode > classes = rootNode . getClasses ( ) ; for ( ClassNode classNode : classes ) { if ( ! classNode . isScript ( ) ) { visitClass ( classNode ) ; } else { List < MethodNode > methods = rootNode . getMethods ( ) ; for ( MethodNode method : methods ) { visitMethod ( method ) ; } } } } private void analyseStaticFieldImport ( ) { for ( Entry < String , ImportNode > aliasOrField : rootNode . getStaticImports ( ) . entrySet ( ) ) { StaticFieldImport staticAliasImport = new StaticFieldImport ( aliasOrField . getValue ( ) . getType ( ) , aliasOrField . getKey ( ) , aliasOrField . getValue ( ) . getFieldName ( ) ) ; staticAliasImport . setSourcePosition ( aliasOrField . getValue ( ) ) ; visitStaticFieldImport ( staticAliasImport ) ; } } private void analyseStaticClassImport ( ) { Collection < ImportNode > staticImportClasses = rootNode . getStaticImports ( ) . values ( ) ; for ( ImportNode staticImp : staticImportClasses ) { ClassNode type = staticImp . getType ( ) ; StaticClassImport staticClassImport = new StaticClassImport ( type ) ; staticClassImport . setSourcePosition ( type ) ; visitStaticClassImport ( staticClassImport ) ; } } private void analyseClassImports ( ) { List < ImportNode > imports = rootNode . getImports ( ) ; for ( ImportNode importNode : imports ) { ClassImport classImport = new ClassImport ( importNode ) ; classImport . setSourcePosition ( importNode . getType ( ) ) ; visitClassImport ( classImport ) ; } } protected void analyzeNodes ( ASTNode [ ] nodes ) { if ( nodes != null ) { for ( int i = <NUM_LIT:0> ; i < nodes . length ; i ++ ) { analyzeNode ( nodes [ i ] ) ; clear ( nodes [ i ] ) ; } } } protected void analyzeTypes ( ClassNode [ ] classNodes ) { if ( classNodes != null ) { for ( int i = <NUM_LIT:0> ; i < classNodes . length ; i ++ ) { if ( classNodes [ i ] != null ) { analyzeType ( classNodes [ i ] ) ; clear ( classNodes [ i ] ) ; } } } } private void analyzeTypeInternal ( ClassNode classNode ) { ClassNode node = classNode ; while ( node . isArray ( ) ) { node = node . getComponentType ( ) ; } analyzeNode ( node ) ; analyzeGenerics ( node ) ; } @ Override public void analyzeType ( ClassNode node ) { analyzeTypeInternal ( node ) ; } @ Override public void analyzeParameter ( Parameter parameter ) { analyzeNode ( parameter ) ; } protected void analyzeGenerics ( ClassNode node ) { if ( node . getGenericsTypes ( ) != null ) { GenericsType [ ] generics = node . getGenericsTypes ( ) ; for ( int i = <NUM_LIT:0> ; i < generics . length ; i ++ ) { GenericsType genericType = generics [ i ] ; if ( ! node . getName ( ) . equals ( genericType . getType ( ) . getName ( ) ) ) { analyzeType ( genericType . getType ( ) ) ; clear ( genericType . getType ( ) ) ; if ( genericType . getLowerBound ( ) != null ) { analyzeType ( genericType . getLowerBound ( ) ) ; clear ( genericType . getLowerBound ( ) ) ; } if ( genericType . getUpperBounds ( ) != null ) { ClassNode [ ] upperBounds = genericType . getUpperBounds ( ) . clone ( ) ; for ( int j = <NUM_LIT:0> ; j < upperBounds . length ; j ++ ) { if ( upperBounds [ i ] . getName ( ) . equals ( node . getName ( ) ) ) { upperBounds [ i ] = null ; } } analyzeTypes ( upperBounds ) ; } } } } } protected void analyseParameters ( Parameter [ ] parameters ) { if ( parameters != null ) { for ( Parameter parameter : parameters ) { analyzeParameter ( parameter ) ; analyzeType ( parameter . getOriginType ( ) ) ; clear ( parameter . getOriginType ( ) ) ; if ( parameter . hasInitialExpression ( ) ) { parameter . getInitialExpression ( ) . visit ( this ) ; } clear ( parameter ) ; } } } public void visitAnnotations ( AnnotatedNode node ) { List < AnnotationNode > annotionMap = node . getAnnotations ( ) ; if ( annotionMap . isEmpty ( ) ) return ; Iterator < AnnotationNode > it = annotionMap . iterator ( ) ; while ( it . hasNext ( ) ) { AnnotationNode an = ( AnnotationNode ) it . next ( ) ; if ( an . isBuiltIn ( ) ) continue ; for ( Entry < String , Expression > element : ( Iterable < Entry < String , Expression > > ) an . getMembers ( ) . entrySet ( ) ) { element . getValue ( ) . visit ( this ) ; } } } public void visitClass ( ClassNode node ) { analyzeTypeInternal ( node ) ; analyzeType ( node . getUnresolvedSuperClass ( ) ) ; clear ( node . getUnresolvedSuperClass ( ) ) ; analyzeTypes ( node . getInterfaces ( ) ) ; node . visitContents ( this ) ; clear ( node ) ; } public void visitField ( FieldNode node ) { analyzeNode ( node ) ; analyzeType ( node . getOriginType ( ) ) ; clear ( node . getOriginType ( ) ) ; Expression initExp = node . getInitialValueExpression ( ) ; if ( initExp != null ) { analyzeNode ( initExp ) ; initExp . visit ( this ) ; clear ( initExp ) ; } clear ( node ) ; } protected void visitClassCodeContainer ( Statement code ) { if ( code != null ) code . visit ( this ) ; } protected void visitConstructorOrMethod ( MethodNode node , boolean isConstructor ) { visitAnnotations ( node ) ; analyseMethodHead ( node ) ; Statement code = node . getCode ( ) ; visitClassCodeContainer ( code ) ; } public void visitConstructor ( ConstructorNode node ) { analyzeNode ( node ) ; visitConstructorOrMethod ( node , true ) ; clear ( node ) ; } public void visitMethod ( MethodNode node ) { analyzeNode ( node ) ; visitConstructorOrMethod ( node , false ) ; clear ( node ) ; } private void analyseMethodHead ( MethodNode node ) { analyzeType ( node . getReturnType ( ) ) ; clear ( node . getReturnType ( ) ) ; analyseParameters ( node . getParameters ( ) ) ; analyzeTypes ( node . getExceptions ( ) ) ; } public void visitProperty ( PropertyNode node ) { } @ Override public void visitVariableExpression ( VariableExpression expression ) { analyzeNode ( expression ) ; analyzeType ( expression . getOriginType ( ) ) ; clear ( expression . getOriginType ( ) ) ; super . visitVariableExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitClosureExpression ( ClosureExpression expression ) { analyzeNode ( expression ) ; analyseParameters ( expression . getParameters ( ) ) ; super . visitClosureExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitArgumentlistExpression ( ArgumentListExpression ale ) { analyzeNode ( ale ) ; super . visitArgumentlistExpression ( ale ) ; clear ( ale ) ; } @ Override public void visitArrayExpression ( ArrayExpression expression ) { analyzeNode ( expression ) ; analyzeType ( expression . getElementType ( ) ) ; clear ( expression . getElementType ( ) ) ; super . visitArrayExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitAssertStatement ( AssertStatement statement ) { analyzeNode ( statement ) ; super . visitAssertStatement ( statement ) ; clear ( statement ) ; } @ Override public void visitAttributeExpression ( AttributeExpression expression ) { analyzeNode ( expression ) ; super . visitAttributeExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitBinaryExpression ( BinaryExpression expression ) { analyzeNode ( expression ) ; super . visitBinaryExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitBitwiseNegationExpression ( BitwiseNegationExpression expression ) { analyzeNode ( expression ) ; super . visitBitwiseNegationExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitBlockStatement ( BlockStatement block ) { analyzeNode ( block ) ; super . visitBlockStatement ( block ) ; clear ( block ) ; } @ Override public void visitBooleanExpression ( BooleanExpression expression ) { analyzeNode ( expression ) ; super . visitBooleanExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitBreakStatement ( BreakStatement statement ) { analyzeNode ( statement ) ; super . visitBreakStatement ( statement ) ; clear ( statement ) ; } @ Override public void visitCaseStatement ( CaseStatement statement ) { analyzeNode ( statement ) ; super . visitCaseStatement ( statement ) ; clear ( statement ) ; } @ Override public void visitCastExpression ( CastExpression expression ) { analyzeNode ( expression ) ; analyzeType ( expression . getType ( ) ) ; clear ( expression . getType ( ) ) ; super . visitCastExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitCatchStatement ( CatchStatement statement ) { analyzeNode ( statement ) ; analyzeType ( statement . getExceptionType ( ) ) ; clear ( statement . getExceptionType ( ) ) ; super . visitCatchStatement ( statement ) ; clear ( statement ) ; } @ Override public void visitClassExpression ( ClassExpression expression ) { analyzeNode ( expression ) ; super . visitClassExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitClosureListExpression ( ClosureListExpression cle ) { analyzeNode ( cle ) ; super . visitClosureListExpression ( cle ) ; clear ( cle ) ; } @ Override public void visitConstantExpression ( ConstantExpression expression ) { analyzeNode ( expression ) ; super . visitConstantExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitConstructorCallExpression ( ConstructorCallExpression call ) { analyzeNode ( call ) ; analyzeType ( call . getType ( ) ) ; clear ( call . getType ( ) ) ; super . visitConstructorCallExpression ( call ) ; clear ( call ) ; } @ Override public void visitContinueStatement ( ContinueStatement statement ) { analyzeNode ( statement ) ; super . visitContinueStatement ( statement ) ; clear ( statement ) ; } @ Override public void visitDeclarationExpression ( DeclarationExpression expression ) { super . visitDeclarationExpression ( expression ) ; } @ Override public void visitDoWhileLoop ( DoWhileStatement loop ) { analyzeNode ( loop ) ; super . visitDoWhileLoop ( loop ) ; clear ( loop ) ; } @ Override public void visitExpressionStatement ( ExpressionStatement statement ) { analyzeNode ( statement ) ; super . visitExpressionStatement ( statement ) ; clear ( statement ) ; } @ Override public void visitFieldExpression ( FieldExpression expression ) { if ( ! expression . getType ( ) . getNameWithoutPackage ( ) . equals ( "<STR_LIT>" ) ) { analyzeNode ( expression ) ; super . visitFieldExpression ( expression ) ; clear ( expression ) ; } } @ Override public void visitForLoop ( ForStatement forLoop ) { analyzeNode ( forLoop ) ; super . visitForLoop ( forLoop ) ; clear ( forLoop ) ; } @ Override public void visitGStringExpression ( GStringExpression expression ) { analyzeNode ( expression ) ; super . visitGStringExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitIfElse ( IfStatement ifElse ) { analyzeNode ( ifElse ) ; super . visitIfElse ( ifElse ) ; clear ( ifElse ) ; } @ Override public void visitListExpression ( ListExpression expression ) { analyzeNode ( expression ) ; super . visitListExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitMapEntryExpression ( MapEntryExpression expression ) { analyzeNode ( expression ) ; super . visitMapEntryExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitMapExpression ( MapExpression expression ) { analyzeNode ( expression ) ; super . visitMapExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitMethodCallExpression ( MethodCallExpression call ) { analyzeNode ( call ) ; super . visitMethodCallExpression ( call ) ; clear ( call ) ; } @ Override public void visitMethodPointerExpression ( MethodPointerExpression expression ) { analyzeNode ( expression ) ; super . visitMethodPointerExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitNotExpression ( NotExpression expression ) { analyzeNode ( expression ) ; super . visitNotExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitPostfixExpression ( PostfixExpression expression ) { analyzeNode ( expression ) ; super . visitPostfixExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitPrefixExpression ( PrefixExpression expression ) { analyzeNode ( expression ) ; super . visitPrefixExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitPropertyExpression ( PropertyExpression expression ) { analyzeNode ( expression ) ; super . visitPropertyExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitRangeExpression ( RangeExpression expression ) { analyzeNode ( expression ) ; super . visitRangeExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitReturnStatement ( ReturnStatement statement ) { analyzeNode ( statement ) ; super . visitReturnStatement ( statement ) ; clear ( statement ) ; } @ Override public void visitShortTernaryExpression ( ElvisOperatorExpression expression ) { analyzeNode ( expression ) ; super . visitShortTernaryExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitSpreadExpression ( SpreadExpression expression ) { analyzeNode ( expression ) ; super . visitSpreadExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitSpreadMapExpression ( SpreadMapExpression expression ) { analyzeNode ( expression ) ; super . visitSpreadMapExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitStaticMethodCallExpression ( StaticMethodCallExpression call ) { analyzeNode ( call ) ; super . visitStaticMethodCallExpression ( call ) ; clear ( call ) ; } @ Override public void visitSwitch ( SwitchStatement statement ) { analyzeNode ( statement ) ; super . visitSwitch ( statement ) ; clear ( statement ) ; } @ Override public void visitSynchronizedStatement ( SynchronizedStatement statement ) { analyzeNode ( statement ) ; super . visitSynchronizedStatement ( statement ) ; clear ( statement ) ; } @ Override public void visitTernaryExpression ( TernaryExpression expression ) { analyzeNode ( expression ) ; super . visitTernaryExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitThrowStatement ( ThrowStatement statement ) { analyzeNode ( statement ) ; super . visitThrowStatement ( statement ) ; clear ( statement ) ; } @ Override public void visitTryCatchFinally ( TryCatchStatement statement ) { analyzeNode ( statement ) ; super . visitTryCatchFinally ( statement ) ; clear ( statement ) ; } @ Override public void visitTupleExpression ( TupleExpression expression ) { super . visitTupleExpression ( expression ) ; } @ Override public void visitUnaryMinusExpression ( UnaryMinusExpression expression ) { analyzeNode ( expression ) ; super . visitUnaryMinusExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitUnaryPlusExpression ( UnaryPlusExpression expression ) { analyzeNode ( expression ) ; super . visitUnaryPlusExpression ( expression ) ; clear ( expression ) ; } @ Override public void visitWhileLoop ( WhileStatement loop ) { analyzeNode ( loop ) ; super . visitWhileLoop ( loop ) ; clear ( loop ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner ; public class NodeNotFoundException extends RuntimeException { private static final long serialVersionUID = <NUM_LIT> ; public NodeNotFoundException ( String message ) { super ( message ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner ; import org . codehaus . groovy . ast . ASTNode ; public class ASTNodeInfo { private ASTNode parent ; private int offset , length ; public ASTNode getParent ( ) { return parent ; } public void setParent ( ASTNode parrent ) { this . parent = parrent ; } public int getOffset ( ) { return offset ; } public void setOffset ( int offset ) { this . offset = offset ; } public int getLength ( ) { return length ; } public void setLength ( int length ) { this . length = length ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . GroovyCodeVisitor ; public class StaticFieldImport extends RefactoringImportNode { private final String field ; private String newField ; private String newAlias ; public StaticFieldImport ( ClassNode type , String alias , String field ) { super ( type , alias ) ; this . field = field ; this . newClassName = type . getName ( ) ; this . newField = field ; this . newAlias = getAlias ( ) ; } @ Override public String getText ( ) { if ( field . equals ( newAlias ) ) { return "<STR_LIT>" + newClassName + "<STR_LIT:.>" + newField ; } return "<STR_LIT>" + newClassName + "<STR_LIT:.>" + newField + "<STR_LIT>" + newAlias ; } public String getField ( ) { return field ; } public void setNewField ( String field ) { this . newField = field ; } public void setNewAlias ( String newAlias ) { this . newAlias = newAlias ; } @ Override public boolean equals ( Object obj ) { if ( obj instanceof StaticFieldImport ) { StaticFieldImport other = ( StaticFieldImport ) obj ; return ( this . getType ( ) . equals ( other . getType ( ) ) && this . field . equals ( other . getField ( ) ) && this . getAlias ( ) . equals ( other . getAlias ( ) ) ) ; } return false ; } @ Override public void visit ( GroovyCodeVisitor visitor ) { if ( visitor instanceof AbstractRefactoringCodeVisitor ) { ( ( AbstractRefactoringCodeVisitor ) visitor ) . visitStaticFieldImport ( this ) ; } } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . CodeVisitorSupport ; import org . codehaus . groovy . ast . GroovyClassVisitor ; import org . codehaus . groovy . ast . Parameter ; public abstract class AbstractRefactoringCodeVisitor extends CodeVisitorSupport implements GroovyClassVisitor { public abstract void visitStaticFieldImport ( StaticFieldImport staticAliasImport ) ; public abstract void visitStaticClassImport ( StaticClassImport staticClassImport ) ; public abstract void visitClassImport ( ClassImport classImport ) ; public abstract void analyzeParameter ( Parameter parameter ) ; public abstract void analyzeType ( ClassNode node ) ; public abstract void scanAST ( ) ; } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner . predicates ; import org . codehaus . groovy . ast . ASTNode ; import org . codehaus . groovy . ast . expr . VariableExpression ; public class Variables implements IASTNodePredicate { public ASTNode evaluate ( ASTNode input ) { if ( input instanceof VariableExpression ) { return input ; } return null ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner . predicates ; import org . codehaus . groovy . ast . expr . ClosureExpression ; import org . codehaus . groovy . ast . expr . ListExpression ; import org . codehaus . groovy . ast . expr . MapExpression ; import org . codehaus . groovy . eclipse . refactoring . core . utils . ASTVisitorDecorator ; public class IncludesClosureOrListPredicate extends ASTVisitorDecorator < Boolean > { private final int line ; public IncludesClosureOrListPredicate ( Boolean container , int line ) { super ( container ) ; this . line = line ; } @ Override public void visitClosureExpression ( ClosureExpression expression ) { if ( expression . getLineNumber ( ) == line ) { container = true ; } } @ Override public void visitListExpression ( ListExpression expression ) { if ( expression . getLineNumber ( ) == line ) { container = true ; } } @ Override public void visitMapExpression ( MapExpression expression ) { if ( expression . getLineNumber ( ) == line ) { container = true ; } } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner . predicates ; import org . codehaus . groovy . ast . ASTNode ; import org . codehaus . groovy . ast . expr . ClosureExpression ; import org . codehaus . groovy . eclipse . refactoring . core . utils . ASTTools ; public class ClosuresInCodePredicate implements IASTNodePredicate { public ASTNode evaluate ( ASTNode input ) { if ( input instanceof ClosureExpression ) { ClosureExpression cl = ( ClosureExpression ) input ; if ( ASTTools . hasValidPosition ( cl ) ) return cl ; } return null ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner . predicates ; import org . codehaus . groovy . ast . ASTNode ; public class SourceCodePredicate implements IASTNodePredicate { int line , col ; public SourceCodePredicate ( int line , int col ) { this . line = line ; this . col = col ; } public ASTNode evaluate ( ASTNode input ) { if ( input . getLineNumber ( ) == line && input . getColumnNumber ( ) == col ) return input ; return null ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner . predicates ; import org . codehaus . groovy . ast . ASTNode ; import org . codehaus . groovy . ast . expr . * ; public class AssignmentAndCall implements IASTNodePredicate { public ASTNode evaluate ( ASTNode input ) { if ( input instanceof ClosureExpression ) { return input ; } else if ( isAssignment ( input ) || isMethodCall ( input ) ) { return input ; } return null ; } public static boolean isAssignment ( ASTNode node ) { if ( node instanceof DeclarationExpression ) { return true ; } else if ( node instanceof BinaryExpression ) { return true ; } else if ( node instanceof PostfixExpression ) { return true ; } else if ( node instanceof PrefixExpression ) { return true ; } return false ; } public static boolean isMethodCall ( ASTNode node ) { if ( node instanceof StaticMethodCallExpression ) { return true ; } if ( node instanceof MethodCallExpression ) { return true ; } return false ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner . predicates ; import org . codehaus . groovy . ast . ASTNode ; public interface IASTNodePredicate { public ASTNode evaluate ( ASTNode input ) ; } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner ; import java . util . LinkedHashMap ; import java . util . Stack ; import org . codehaus . groovy . ast . ASTNode ; import org . codehaus . groovy . ast . ModuleNode ; import org . codehaus . groovy . eclipse . refactoring . core . utils . ASTTools ; import org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner . predicates . IASTNodePredicate ; import org . eclipse . jface . text . IDocument ; public class ASTScanner extends ASTScannerPredicate { protected IDocument document ; private final LinkedHashMap < ASTNode , ASTNodeInfo > astMap ; private final Stack < ASTNode > nodeStack ; public ASTScanner ( ModuleNode rootNode , IASTNodePredicate predicate , IDocument document ) { super ( rootNode , predicate ) ; this . document = document ; astMap = new LinkedHashMap < ASTNode , ASTNodeInfo > ( ) ; nodeStack = new Stack < ASTNode > ( ) ; } public void startASTscan ( ) { if ( astMap . isEmpty ( ) ) { scanAST ( ) ; } } public ASTNodeInfo getInfo ( ASTNode node ) throws NodeNotFoundException { ASTNodeInfo ret = astMap . get ( node ) ; if ( ret != null ) { return ret ; } if ( node != null ) { throw new NodeNotFoundException ( node . getText ( ) ) ; } throw new NodeNotFoundException ( "<STR_LIT>" ) ; } public LinkedHashMap < ASTNode , ASTNodeInfo > getMatchedNodes ( ) { return astMap ; } @ Override protected void doOnPredicate ( ASTNode node ) { ASTNodeInfo info = new ASTNodeInfo ( ) ; if ( ! nodeStack . isEmpty ( ) && nodeStack . peek ( ) != node ) info . setParent ( nodeStack . peek ( ) ) ; if ( ASTTools . hasValidPosition ( node ) ) { info . setOffset ( node . getStart ( ) ) ; info . setLength ( node . getEnd ( ) - node . getStart ( ) ) ; } astMap . put ( node , info ) ; nodeStack . push ( node ) ; } @ Override protected void clear ( ASTNode node ) { if ( ! nodeStack . isEmpty ( ) && nodeStack . peek ( ) == node ) nodeStack . pop ( ) ; } public boolean hasMatches ( ) { return ! astMap . isEmpty ( ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner ; import org . codehaus . groovy . ast . GroovyCodeVisitor ; import org . codehaus . groovy . ast . ImportNode ; import org . codehaus . groovy . eclipse . refactoring . core . utils . ImportResolver ; public class ClassImport extends RefactoringImportNode { private String newAlias ; public ClassImport ( ImportNode importNode ) { super ( importNode ) ; newAlias = getAlias ( ) ; } @ Override public String getText ( ) { if ( ImportResolver . isExplicitAlias ( this ) ) { return "<STR_LIT>" + newClassName + "<STR_LIT>" + newAlias ; } return "<STR_LIT>" + newClassName ; } public void setNewAlias ( String newAlias ) { this . newAlias = newAlias ; } @ Override public void visit ( GroovyCodeVisitor visitor ) { if ( visitor instanceof AbstractRefactoringCodeVisitor ) { ( ( AbstractRefactoringCodeVisitor ) visitor ) . visitClassImport ( this ) ; } } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Set ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . codehaus . groovy . ast . ASTNode ; import org . codehaus . groovy . ast . ASTNodeCompatibilityWrapper ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . InnerClassNode ; import org . codehaus . groovy . ast . MethodNode ; import org . codehaus . groovy . ast . ModuleNode ; import org . codehaus . groovy . ast . Variable ; import org . codehaus . groovy . ast . VariableScope ; import org . codehaus . groovy . ast . expr . ClosureExpression ; import org . codehaus . groovy . ast . expr . Expression ; import org . codehaus . groovy . ast . stmt . BlockStatement ; import org . codehaus . groovy . ast . stmt . ReturnStatement ; import org . codehaus . groovy . ast . stmt . Statement ; import org . codehaus . groovy . eclipse . codebrowsing . fragments . ASTFragmentKind ; import org . codehaus . groovy . eclipse . codebrowsing . fragments . IASTFragment ; import org . codehaus . groovy . eclipse . codebrowsing . requestor . Region ; import org . codehaus . groovy . eclipse . codebrowsing . selection . FindSurroundingNode ; import org . codehaus . groovy . eclipse . codebrowsing . selection . FindSurroundingNode . VisitKind ; import org . codehaus . groovy . eclipse . core . compiler . GroovySnippetParser ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . TextSelection ; import org . eclipse . text . edits . MultiTextEdit ; import org . eclipse . text . edits . ReplaceEdit ; public class ASTTools { public static final int SPACE = <NUM_LIT:1> ; public static final int TAB = <NUM_LIT:2> ; public static Region getPositionOfBlockStatements ( BlockStatement block ) { int startPosition , endPosition ; Region methodStatements = new Region ( <NUM_LIT:0> , <NUM_LIT:0> ) ; if ( block . getStatements ( ) . size ( ) > <NUM_LIT:0> ) { Statement firstStmt = ( Statement ) block . getStatements ( ) . get ( <NUM_LIT:0> ) ; Statement lastStmt = ( Statement ) block . getStatements ( ) . get ( block . getStatements ( ) . size ( ) - <NUM_LIT:1> ) ; if ( firstStmt instanceof ReturnStatement && firstStmt . getLineNumber ( ) == - <NUM_LIT:1> ) { Expression exp = ( ( ReturnStatement ) firstStmt ) . getExpression ( ) ; startPosition = exp . getStart ( ) ; } else { startPosition = firstStmt . getStart ( ) ; } if ( lastStmt instanceof ReturnStatement && lastStmt . getLineNumber ( ) == - <NUM_LIT:1> ) { Expression exp = ( ( ReturnStatement ) lastStmt ) . getExpression ( ) ; endPosition = exp . getEnd ( ) ; } else { endPosition = lastStmt . getEnd ( ) ; } methodStatements = new Region ( startPosition , endPosition - startPosition ) ; } return methodStatements ; } public static boolean hasValidPosition ( ASTNode node ) { return node . getEnd ( ) > <NUM_LIT:0> ; } public static String trimLeadingGap ( String text ) { return text . replaceFirst ( "<STR_LIT>" , "<STR_LIT>" ) ; } public static String getLeadingGap ( String text ) { return text . replace ( trimLeadingGap ( text ) , "<STR_LIT>" ) ; } public static String setIndentationTo ( String text , int intentation , int modus ) { StringBuilder retString = new StringBuilder ( ) ; String patternStr = "<STR_LIT>" ; Pattern pattern = Pattern . compile ( patternStr , Pattern . DOTALL ) ; Matcher matcher = pattern . matcher ( text ) ; while ( matcher . find ( ) ) { String line = matcher . group ( <NUM_LIT:0> ) ; int currentIntetnation = getCurrentIntentation ( line ) ; String space ; switch ( modus ) { case SPACE : space = "<STR_LIT:U+0020U+0020U+0020U+0020>" ; break ; default : space = "<STR_LIT:t>" ; break ; } for ( int i = <NUM_LIT:0> ; i < ( currentIntetnation + intentation ) ; i ++ ) { retString . append ( space ) ; } retString . append ( trimLeadingGap ( line ) ) ; } return retString . toString ( ) ; } public static int getCurrentIntentation ( String line ) { String leadingGap = getLeadingGap ( line ) ; int tabs = <NUM_LIT:0> , spaces = <NUM_LIT:0> ; for ( int i = <NUM_LIT:0> ; i < leadingGap . length ( ) ; i ++ ) { switch ( leadingGap . charAt ( i ) ) { case '<STR_LIT:\t>' : tabs ++ ; break ; case '<CHAR_LIT:U+0020>' : spaces ++ ; break ; default : break ; } } int currentIntetnation = tabs + ( spaces / <NUM_LIT:4> ) ; return currentIntetnation ; } public static IDocument getDocumentWithSystemLineBreak ( String text ) { Document document = new Document ( ) ; String linebreak = document . getDefaultLineDelimiter ( ) ; document . set ( text ) ; try { int lineCount = document . getNumberOfLines ( ) ; MultiTextEdit multiEdit = new MultiTextEdit ( ) ; for ( int i = <NUM_LIT:0> ; i < lineCount ; i ++ ) { final String delimiter = document . getLineDelimiter ( i ) ; if ( delimiter != null && delimiter . length ( ) > <NUM_LIT:0> && ! delimiter . equals ( linebreak ) ) { IRegion region = document . getLineInformation ( i ) ; multiEdit . addChild ( new ReplaceEdit ( region . getOffset ( ) + region . getLength ( ) , delimiter . length ( ) , linebreak ) ) ; } } multiEdit . apply ( document ) ; } catch ( Exception e ) { } return document ; } public static ModuleNode getASTNodeFromSource ( String source ) { GroovySnippetParser parser = new GroovySnippetParser ( ) ; ModuleNode node = parser . parse ( source ) ; return node ; } public static boolean hasMultipleReturnStatements ( Statement statement ) { List < ReturnStatement > returns = new ArrayList < ReturnStatement > ( ) ; statement . visit ( new FindReturns ( returns ) ) ; return returns . size ( ) > <NUM_LIT:1> ; } private static class FindReturns extends ASTVisitorDecorator < List < ReturnStatement > > { public FindReturns ( List < ReturnStatement > container ) { super ( container ) ; } @ Override public void visitReturnStatement ( ReturnStatement statement ) { container . add ( statement ) ; super . visitReturnStatement ( statement ) ; } } public static String getTextofNode ( ASTNode node , IDocument document ) { TextSelection sel = new TextSelection ( document , node . getStart ( ) , node . getEnd ( ) - node . getStart ( ) ) ; try { return document . get ( sel . getOffset ( ) , sel . getLength ( ) ) ; } catch ( BadLocationException e ) { return "<STR_LIT>" ; } } public static Set < Variable > getVariablesInScope ( ModuleNode moduleNode , ASTNode node ) { FindSurroundingNode find = new FindSurroundingNode ( new Region ( node ) , VisitKind . PARENT_STACK ) ; find . doVisitSurroundingNode ( moduleNode ) ; List < IASTFragment > parentStack = new ArrayList < IASTFragment > ( find . getParentStack ( ) ) ; Collections . reverse ( parentStack ) ; Set < Variable > vars = new HashSet < Variable > ( ) ; for ( IASTFragment fragment : parentStack ) { ASTNode astNode = fragment . getAssociatedNode ( ) ; VariableScope scope ; if ( astNode instanceof BlockStatement ) { scope = ( ( BlockStatement ) astNode ) . getVariableScope ( ) ; } else if ( astNode instanceof MethodNode ) { scope = ( ( MethodNode ) astNode ) . getVariableScope ( ) ; } else if ( astNode instanceof ClosureExpression ) { scope = ( ( ClosureExpression ) astNode ) . getVariableScope ( ) ; } else { scope = null ; } if ( scope != null ) { Iterator < Variable > declaredVariables = scope . getDeclaredVariablesIterator ( ) ; while ( declaredVariables . hasNext ( ) ) { vars . add ( declaredVariables . next ( ) ) ; } } } return vars ; } public static ClassNode getContainingClassNode ( ModuleNode moduleNode , int offset ) { ClassNode containingClassNode = null ; ClassNode scriptClass = null ; List < ClassNode > classes = moduleNode . getClasses ( ) ; for ( ClassNode clazz : ( Iterable < ClassNode > ) classes ) { if ( clazz . isScript ( ) ) { scriptClass = clazz ; } else { if ( clazz . getStart ( ) <= offset && clazz . getEnd ( ) >= offset ) { containingClassNode = clazz ; } } } if ( containingClassNode == null ) { if ( scriptClass != null && scriptClass . getStart ( ) <= offset && scriptClass . getEnd ( ) >= offset ) { containingClassNode = scriptClass ; } else { containingClassNode = ASTNodeCompatibilityWrapper . getScriptClassDummy ( moduleNode ) ; } } else { Iterator < InnerClassNode > innerClasses = ASTNodeCompatibilityWrapper . getInnerClasses ( containingClassNode ) ; while ( innerClasses != null && innerClasses . hasNext ( ) ) { InnerClassNode inner = innerClasses . next ( ) ; if ( inner . getStart ( ) <= offset && inner . getEnd ( ) >= offset ) { containingClassNode = inner ; innerClasses = ASTNodeCompatibilityWrapper . getInnerClasses ( inner ) ; } } } return containingClassNode ; } public static IASTFragment getSelectionFragment ( ModuleNode moduleNode , int selectionStart , int selectionLength ) { FindSurroundingNode finder = new FindSurroundingNode ( new Region ( selectionStart , selectionLength ) , VisitKind . SURROUNDING_NODE ) ; IASTFragment selectionFragment = null ; IASTFragment fragment = finder . doVisitSurroundingNode ( moduleNode ) ; if ( ASTFragmentKind . isExpressionKind ( fragment ) ) { selectionFragment = fragment ; } return selectionFragment ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils ; import java . util . Collection ; import java . util . List ; import org . codehaus . groovy . ast . ClassHelper ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . ImportNode ; import org . codehaus . groovy . ast . ModuleNode ; import org . codehaus . groovy . control . ResolveVisitor ; public class ImportResolver { public static String getResolvedClassName ( ModuleNode root , ClassNode classType , boolean defaultImports ) { String alias = ImportResolver . asAlias ( root , classType ) ; if ( alias . equals ( "<STR_LIT>" ) ) { ImportNode found = findImportNodeForClass ( classType , root . getImports ( ) ) ; if ( found != null ) { return found . getType ( ) . getNameWithoutPackage ( ) ; } found = findImportNodeForClass ( classType , root . getStaticStarImports ( ) . values ( ) ) ; if ( found != null ) { return found . getType ( ) . getNameWithoutPackage ( ) ; } found = findImportNodeForClass ( classType , root . getStaticImports ( ) . values ( ) ) ; if ( found != null ) { return found . getType ( ) . getNameWithoutPackage ( ) ; } String packageNameWithDot = classType . getPackageName ( ) + "<STR_LIT:.>" ; if ( root . hasPackageName ( ) ) { if ( root . getPackageName ( ) . equals ( packageNameWithDot ) ) { return classType . getNameWithoutPackage ( ) ; } } List < ImportNode > packageImports = root . getStarImports ( ) ; for ( ImportNode imp : packageImports ) { if ( imp . getPackageName ( ) . equals ( packageNameWithDot ) ) { return classType . getNameWithoutPackage ( ) ; } } if ( defaultImports ) { for ( String packageName : ResolveVisitor . DEFAULT_IMPORTS ) { if ( packageName . equals ( packageNameWithDot ) ) { return classType . getNameWithoutPackage ( ) ; } } if ( classType . equals ( ClassHelper . BigDecimal_TYPE ) ) { return classType . getNameWithoutPackage ( ) ; } else if ( classType . equals ( ClassHelper . BigInteger_TYPE ) ) { return classType . getNameWithoutPackage ( ) ; } } return classType . getName ( ) ; } return alias ; } private static ImportNode findImportNodeForClass ( ClassNode toFind , Collection < ImportNode > imports ) { for ( ImportNode imp : imports ) { if ( imp . getType ( ) != null && imp . getType ( ) . getName ( ) . equals ( toFind . getName ( ) ) ) { return imp ; } } return null ; } public static String asAlias ( ModuleNode root , ClassNode type ) { ImportNode imp = findImportNodeForClass ( type , root . getImports ( ) ) ; if ( imp != null && isExplicitAlias ( imp ) ) { return imp . getAlias ( ) ; } return "<STR_LIT>" ; } public static boolean isExplicitAlias ( ImportNode importNode ) { return ! importNode . getType ( ) . getNameWithoutPackage ( ) . equals ( importNode . getAlias ( ) ) ; } public static String asFieldName ( ModuleNode root , ClassNode type , String possibleField ) { ImportNode imp = root . getStaticImports ( ) . get ( possibleField ) ; if ( imp != null && imp . getType ( ) != null && imp . getType ( ) . getName ( ) . equals ( type . getName ( ) ) ) { return possibleField ; } imp = findImportNodeForClass ( type , root . getStaticStarImports ( ) . values ( ) ) ; if ( imp != null ) { return possibleField ; } return "<STR_LIT>" ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils ; import org . codehaus . groovy . ast . ASTNode ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; public class SourceCodePoint implements Comparable < SourceCodePoint > { public static final int BEGIN = <NUM_LIT:0> ; public static final int END = <NUM_LIT:1> ; private final int row , col ; public SourceCodePoint ( int row , int col ) { assert row > - <NUM_LIT:1> ; assert col > - <NUM_LIT:1> ; this . row = row ; this . col = col ; } public SourceCodePoint ( int offset , IDocument doc ) { int row = <NUM_LIT:0> , col = <NUM_LIT:0> ; try { row = doc . getLineOfOffset ( offset ) ; col = offset - doc . getLineOffset ( row ) ; } catch ( BadLocationException e ) { e . printStackTrace ( ) ; throw new RuntimeException ( e ) ; } this . row = row + <NUM_LIT:1> ; this . col = col + <NUM_LIT:1> ; } public SourceCodePoint ( ASTNode node , int pos ) { switch ( pos ) { case BEGIN : row = node . getLineNumber ( ) ; col = node . getColumnNumber ( ) ; break ; case END : row = node . getLastLineNumber ( ) ; col = node . getLastColumnNumber ( ) ; break ; default : row = col = - <NUM_LIT:1> ; break ; } } public boolean isAfter ( SourceCodePoint p2 ) { if ( this . row > p2 . row ) return true ; if ( this . row == p2 . row && this . col >= p2 . col ) return true ; return false ; } public boolean isBefore ( SourceCodePoint p2 ) { if ( this . row < p2 . row ) return true ; if ( this . row == p2 . row && this . col <= p2 . col ) return true ; return false ; } public int getCol ( ) { return col ; } public int getRow ( ) { return row ; } public int getOffset ( IDocument doc ) { try { return doc . getLineOffset ( row - <NUM_LIT:1> ) + ( col - <NUM_LIT:1> ) ; } catch ( BadLocationException e ) { e . printStackTrace ( ) ; throw new RuntimeException ( e ) ; } } public static int getOffset ( int row , int col , IDocument doc ) { return new SourceCodePoint ( row , col ) . getOffset ( doc ) ; } public static int getRow ( int offset , IDocument doc ) { return new SourceCodePoint ( offset , doc ) . getRow ( ) ; } public static int getCol ( int offset , IDocument doc ) { return new SourceCodePoint ( offset , doc ) . getCol ( ) ; } public int compareTo ( SourceCodePoint arg0 ) { if ( this . row > arg0 . row ) return <NUM_LIT:1> ; if ( this . row == arg0 . row && this . col > arg0 . col ) return <NUM_LIT:1> ; if ( this . row < arg0 . row ) return - <NUM_LIT:1> ; if ( this . row == arg0 . row && this . col < arg0 . col ) return - <NUM_LIT:1> ; return <NUM_LIT:0> ; } @ Override public boolean equals ( Object obj ) { if ( obj != null && obj instanceof SourceCodePoint ) { return ( ( ( SourceCodePoint ) obj ) . col == col && ( ( SourceCodePoint ) obj ) . row == row ) ; } return false ; } @ Override public int hashCode ( ) { return ( String . valueOf ( col ) + "<STR_LIT:/>" + String . valueOf ( row ) ) . hashCode ( ) ; } public boolean isInvalid ( ) { return ( col < <NUM_LIT:1> || row < <NUM_LIT:1> ) ; } public boolean isValid ( ) { return ! isInvalid ( ) ; } @ Override public String toString ( ) { return "<STR_LIT:(>" + row + "<STR_LIT>" + col + "<STR_LIT:)>" ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils ; import org . eclipse . text . edits . MultiTextEdit ; public class EditMerger { public static MultiTextEdit difference ( MultiTextEdit base , MultiTextEdit minus ) { return base ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils ; import org . codehaus . groovy . ast . ASTNode ; import org . codehaus . groovy . ast . AnnotatedNode ; import org . codehaus . groovy . ast . expr . MethodCallExpression ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . FindReplaceDocumentAdapter ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . TextSelection ; import org . eclipse . text . edits . ReplaceEdit ; public class EditHelper { private EditHelper ( ) { } public static ReplaceEdit getDefaultReplaceEdit ( ASTNode node , boolean execute , IDocument document , String oldClassName , String newClassName ) { TextSelection sel = new TextSelection ( document , node . getStart ( ) , node . getEnd ( ) - node . getStart ( ) ) ; int offset = sel . getOffset ( ) ; if ( execute ) { return new ReplaceEdit ( offset , oldClassName . length ( ) , newClassName ) ; } return new ReplaceEdit ( offset , oldClassName . length ( ) , oldClassName ) ; } public static ReplaceEdit getLookupReplaceEdit ( ASTNode node , boolean execute , IDocument document , String oldName , String newName ) { TextSelection sel = new TextSelection ( document , node . getStart ( ) , node . getEnd ( ) - node . getStart ( ) ) ; int offset = sel . getOffset ( ) ; if ( execute ) { if ( node instanceof AnnotatedNode && ( ( AnnotatedNode ) node ) . getNameEnd ( ) > <NUM_LIT:0> ) { AnnotatedNode aNode = ( AnnotatedNode ) node ; return new ReplaceEdit ( aNode . getNameStart ( ) , aNode . getNameEnd ( ) - aNode . getNameStart ( ) + <NUM_LIT:1> , newName ) ; } try { FindReplaceDocumentAdapter finder = new FindReplaceDocumentAdapter ( document ) ; IRegion foundRegion = finder . find ( offset , oldName , true , true , true , false ) ; IRegion lineInfoAtOffset = document . getLineInformationOfOffset ( foundRegion . getOffset ( ) ) ; String definitionLine = document . get ( lineInfoAtOffset . getOffset ( ) , lineInfoAtOffset . getLength ( ) ) ; offset = lineInfoAtOffset . getOffset ( ) + definitionLine . indexOf ( oldName ) ; if ( definitionLine . indexOf ( oldName ) != definitionLine . lastIndexOf ( oldName ) ) { offset = lineInfoAtOffset . getOffset ( ) + node . getColumnNumber ( ) - <NUM_LIT:1> ; } return new ReplaceEdit ( offset , oldName . length ( ) , newName ) ; } catch ( BadLocationException e ) { throw new RuntimeException ( e ) ; } } return new ReplaceEdit ( offset , oldName . length ( ) , oldName ) ; } public static ReplaceEdit getRenameMethodCallEdit ( MethodCallExpression node , IDocument document , String newName ) { TextSelection sel = new TextSelection ( document , node . getStart ( ) , node . getEnd ( ) - node . getStart ( ) ) ; int offset = sel . getOffset ( ) ; offset += node . getMethod ( ) . getColumnNumber ( ) - node . getColumnNumber ( ) ; return new ReplaceEdit ( offset , node . getMethod ( ) . getText ( ) . length ( ) , newName ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils ; public class StringUtils { public static String capitalize ( String str ) { int strLen ; if ( str == null || ( strLen = str . length ( ) ) == <NUM_LIT:0> ) { return str ; } return new StringBuffer ( strLen ) . append ( Character . toTitleCase ( str . charAt ( <NUM_LIT:0> ) ) ) . append ( str . substring ( <NUM_LIT:1> ) ) . toString ( ) ; } public static String uncapitalize ( String str ) { int strLen ; if ( str == null || ( strLen = str . length ( ) ) == <NUM_LIT:0> ) { return str ; } return new StringBuffer ( strLen ) . append ( Character . toLowerCase ( str . charAt ( <NUM_LIT:0> ) ) ) . append ( str . substring ( <NUM_LIT:1> ) ) . toString ( ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils ; import java . io . Reader ; import java . io . StringReader ; import java . text . MessageFormat ; import java . util . ArrayList ; import java . util . List ; import java . util . Vector ; import org . codehaus . greclipse . GroovyTokenTypeBridge ; import org . codehaus . groovy . antlr . parser . GroovyLexer ; import org . codehaus . groovy . eclipse . refactoring . Activator ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . core . runtime . MultiStatus ; import org . eclipse . core . runtime . Status ; import antlr . Token ; import antlr . TokenStream ; import antlr . TokenStreamException ; public final class GroovyConventionsBuilder { public static final String CLASS = "<STR_LIT:class>" ; public static final String VARIABLE = "<STR_LIT>" ; public static final String METHOD = "<STR_LIT>" ; public static final String FIELD = "<STR_LIT:field>" ; private List < String > names = new ArrayList < String > ( ) ; private String element ; private MultiStatus state = new MultiStatus ( Activator . PLUGIN_ID , IStatus . OK , "<STR_LIT>" , null ) ; public GroovyConventionsBuilder ( String name , String element ) { this . names . add ( name ) ; this . element = element ; validateNotNull ( ) ; } public GroovyConventionsBuilder ( List < String > names , String element ) { this . names = names ; this . element = element ; validateNotNull ( ) ; } public GroovyConventionsBuilder validateUpperCase ( int status ) { for ( String name : names ) { if ( name . length ( ) > <NUM_LIT:0> && Character . isLowerCase ( name . charAt ( <NUM_LIT:0> ) ) ) { state . add ( new Status ( status , Activator . PLUGIN_ID , MessageFormat . format ( "<STR_LIT>" , element ) ) ) ; } } return this ; } public GroovyConventionsBuilder validateLowerCase ( int status ) { for ( String name : names ) { if ( name . length ( ) > <NUM_LIT:0> && Character . isUpperCase ( name . charAt ( <NUM_LIT:0> ) ) ) { state . add ( new Status ( status , Activator . PLUGIN_ID , MessageFormat . format ( "<STR_LIT>" , element ) ) ) ; } } return this ; } public GroovyConventionsBuilder validateGroovyIdentifier ( ) { for ( String name : names ) { List < Token > tokenList = tokenizeString ( name ) ; if ( ! ( tokenList . size ( ) == <NUM_LIT:1> && tokenList . get ( <NUM_LIT:0> ) . getType ( ) == GroovyTokenTypeBridge . IDENT ) ) { state . add ( new Status ( IStatus . ERROR , Activator . PLUGIN_ID , MessageFormat . format ( "<STR_LIT>" , name ) ) ) ; } } return this ; } public IStatus done ( ) { return state ; } private void validateNotNull ( ) { for ( String name : names ) { if ( name . length ( ) == <NUM_LIT:0> ) { state . add ( new Status ( IStatus . ERROR , Activator . PLUGIN_ID , MessageFormat . format ( "<STR_LIT>" , element ) ) ) ; } } } public static List < Token > tokenizeString ( String name ) { Reader input = new StringReader ( name ) ; GroovyLexer lexer = new GroovyLexer ( input ) ; TokenStream stream = ( TokenStream ) lexer . plumb ( ) ; List < Token > tokenList = new Vector < Token > ( ) ; Token token = null ; try { while ( ( token = stream . nextToken ( ) ) . getType ( ) != Token . EOF_TYPE ) { tokenList . add ( token ) ; } } catch ( TokenStreamException e ) { e . printStackTrace ( ) ; } return tokenList ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils ; import org . codehaus . groovy . ast . CodeVisitorSupport ; public abstract class ASTVisitorDecorator < Container > extends CodeVisitorSupport { protected Container container ; public ASTVisitorDecorator ( Container container ) { this . container = container ; } public Container getContainer ( ) { return container ; } public void setContainer ( Container container ) { this . container = container ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . core . utils ; import org . eclipse . core . runtime . IStatus ; import org . eclipse . ltk . core . refactoring . RefactoringStatus ; public class StatusHelper { public static RefactoringStatus convertStatus ( IStatus stat ) { RefactoringStatus refStatus = new RefactoringStatus ( ) ; for ( IStatus st : stat . getChildren ( ) ) { refStatus . addEntry ( st . getSeverity ( ) , st . getMessage ( ) , null , st . getPlugin ( ) , st . getCode ( ) ) ; } return refStatus ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . formatter ; public interface IFormatterPreferences { int getBracesEnd ( ) ; int getBracesStart ( ) ; boolean useTabs ( ) ; int getIndentationSize ( ) ; int getTabSize ( ) ; int getIndentationMultiline ( ) ; int getMaxLineLength ( ) ; boolean isSmartPaste ( ) ; boolean isIndentEmptyLines ( ) ; boolean isRemoveUnnecessarySemicolons ( ) ; int getLongListLength ( ) ; } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . formatter ; import java . util . List ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . codehaus . greclipse . GroovyTokenTypeBridge ; import org . codehaus . groovy . ast . ASTNode ; import org . codehaus . groovy . ast . ClassNode ; import org . codehaus . groovy . ast . MethodNode ; import org . codehaus . groovy . ast . ModuleNode ; import org . codehaus . groovy . ast . Parameter ; import org . codehaus . groovy . ast . stmt . BlockStatement ; import org . codehaus . groovy . ast . stmt . CaseStatement ; import org . codehaus . groovy . ast . stmt . Statement ; import org . codehaus . groovy . ast . stmt . SwitchStatement ; import org . codehaus . groovy . eclipse . core . GroovyCore ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . text . edits . DeleteEdit ; import org . eclipse . text . edits . InsertEdit ; import org . eclipse . text . edits . MalformedTreeException ; import org . eclipse . text . edits . MultiTextEdit ; import org . eclipse . text . edits . ReplaceEdit ; import org . eclipse . text . edits . TextEdit ; import antlr . Token ; public class GroovyIndentation { private static boolean DEBUG = false ; private void debug ( String msg ) { if ( DEBUG ) { System . out . println ( msg ) ; } } private final DefaultGroovyFormatter formatter ; private final IFormatterPreferences pref ; private int indentation = <NUM_LIT:0> ; private final int [ ] tempIndentation ; private final LineIndentations lineInd ; TextEdit indentationEdits ; private final KlenkDocumentScanner tokens ; public GroovyIndentation ( DefaultGroovyFormatter formatter , IFormatterPreferences pref , int indentationLevel ) { this . formatter = formatter ; tempIndentation = new int [ formatter . getProgressDocument ( ) . getNumberOfLines ( ) ] ; lineInd = new LineIndentations ( formatter . getProgressDocument ( ) . getNumberOfLines ( ) ) ; this . tokens = formatter . getTokens ( ) ; this . pref = pref ; this . indentation = indentationLevel ; } public TextEdit getIndentationEdits ( ) { indentationEdits = new MultiTextEdit ( ) ; handleMultilineMethodParameters ( ) ; try { if ( formatter . isMultilineStatement ( tokens . get ( <NUM_LIT:0> ) ) ) { setAdditionalIndentation ( tokens . get ( <NUM_LIT:0> ) , pref . getIndentationMultiline ( ) , false ) ; lineInd . setMultilineToken ( tokens . get ( <NUM_LIT:0> ) . getLine ( ) , tokens . get ( <NUM_LIT:0> ) ) ; } Token token = null ; for ( int i = <NUM_LIT:0> ; i < tokens . size ( ) ; i ++ ) { token = tokens . get ( i ) ; int offsetToken = formatter . getOffsetOfToken ( token ) ; int offsetNextToken = formatter . getOffsetOfToken ( formatter . getNextTokenIncludingNLS ( i ) ) ; int ttype = token . getType ( ) ; if ( ttype == GroovyTokenTypeBridge . LITERAL_if || ttype == GroovyTokenTypeBridge . LITERAL_while || ttype == GroovyTokenTypeBridge . LITERAL_for ) { setAdditionalIndentation ( formatter . getTokenAfterParenthesis ( i ) ) ; } else if ( ttype == GroovyTokenTypeBridge . LCURLY || ttype == GroovyTokenTypeBridge . LBRACK ) { indentation ++ ; } else if ( ttype == GroovyTokenTypeBridge . LITERAL_switch ) { indentendSwitchStatement ( token ) ; } else if ( ttype == GroovyTokenTypeBridge . RCURLY || ttype == GroovyTokenTypeBridge . RBRACK ) { indentation -- ; } else if ( ttype == GroovyTokenTypeBridge . LITERAL_else ) { int nextToken = formatter . getNextToken ( i ) . getType ( ) ; if ( nextToken != GroovyTokenTypeBridge . LCURLY && nextToken != GroovyTokenTypeBridge . LITERAL_if ) { setAdditionalIndentation ( formatter . getNextToken ( i ) ) ; } } else if ( ttype == GroovyTokenTypeBridge . EOF || ttype == GroovyTokenTypeBridge . NLS ) { int nextTokenType = formatter . getNextTokenIncludingNLS ( i ) . getType ( ) ; if ( nextTokenType == GroovyTokenTypeBridge . RCURLY || nextTokenType == GroovyTokenTypeBridge . RBRACK ) { tempIndentation [ token . getLine ( ) ] -- ; } deleteWhiteSpaceBefore ( token ) ; if ( ttype != GroovyTokenTypeBridge . EOF ) { Token nextMultiToken = formatter . getNextTokenIncludingNLS ( i ) ; int offsetAfterNLS = offsetToken + formatter . getProgressDocument ( ) . getLineDelimiter ( token . getLine ( ) - <NUM_LIT:1> ) . length ( ) ; if ( ! isEmptyLine ( token . getLine ( ) ) || formatter . pref . isIndentEmptyLines ( ) ) { addEdit ( new ReplaceEdit ( offsetAfterNLS , ( offsetNextToken - offsetAfterNLS ) , formatter . getLeadingGap ( indentation + tempIndentation [ token . getLine ( ) ] ) ) ) ; } lineInd . setLineIndentation ( token . getLine ( ) + <NUM_LIT:1> , indentation + tempIndentation [ token . getLine ( ) ] ) ; if ( formatter . isMultilineStatement ( nextMultiToken ) ) { setAdditionalIndentation ( nextMultiToken , pref . getIndentationMultiline ( ) , false ) ; lineInd . setMultilineToken ( token . getLine ( ) , token ) ; } } } else if ( ttype == GroovyTokenTypeBridge . ML_COMMENT ) { addEdit ( new ReplaceEdit ( offsetToken , ( offsetNextToken - offsetToken ) , formatMultilineComment ( formatter . getProgressDocument ( ) . get ( offsetToken , ( offsetNextToken - offsetToken ) ) , indentation ) ) ) ; } } } catch ( BadLocationException e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; } return indentationEdits ; } private void handleMultilineMethodParameters ( ) { ModuleNode rootNode = formatter . getProgressRootNode ( ) ; List < ClassNode > classes = rootNode . getClasses ( ) ; int indentationMultiline = pref . getIndentationMultiline ( ) ; for ( ClassNode classNode : classes ) { List < MethodNode > methods = classNode . getMethods ( ) ; for ( MethodNode method : methods ) { if ( method . getEnd ( ) > <NUM_LIT:1> && method . getParameters ( ) != null && method . getParameters ( ) . length > <NUM_LIT:0> ) { Parameter [ ] ps = method . getParameters ( ) ; Statement code = method . getCode ( ) ; Parameter lastP = ps [ ps . length - <NUM_LIT:1> ] ; int maybeMethodStart = ( method . getAnnotations ( ) != null && method . getAnnotations ( ) . size ( ) > <NUM_LIT:0> ) ? method . getAnnotations ( ) . get ( method . getAnnotations ( ) . size ( ) - <NUM_LIT:1> ) . getEnd ( ) : method . getStart ( ) ; List < Token > methodTokens = tokens . getTokens ( maybeMethodStart , method . getParameters ( ) [ <NUM_LIT:0> ] . getStart ( ) ) ; int lineStart = method . getLineNumber ( ) ; for ( int i = methodTokens . size ( ) - <NUM_LIT:1> ; i >= <NUM_LIT:0> ; i -- ) { Token token = methodTokens . get ( i ) ; if ( token . getType ( ) == GroovyTokenTypeBridge . LPAREN ) { lineStart = token . getLine ( ) ; break ; } } int lineEnd = code != null ? code . getLineNumber ( ) : lastP . getLastLineNumber ( ) ; if ( lineStart != lineEnd ) { int tokenIndex = tokens . findTokenFrom ( lastP . getEnd ( ) ) ; Token lastParamToken = tokens . get ( tokenIndex - <NUM_LIT:1> ) ; Token openingBracket = null ; while ( ++ tokenIndex < tokens . size ( ) ) { openingBracket = tokens . get ( tokenIndex ) ; if ( openingBracket . getType ( ) == GroovyTokenTypeBridge . LCURLY ) { break ; } } boolean doLastLineIndent = openingBracket != null && lastParamToken . getLine ( ) == openingBracket . getLine ( ) ; for ( int i = lineStart + <NUM_LIT:1> ; i < lineEnd ; i ++ ) { tempIndentation [ i - <NUM_LIT:1> ] += indentationMultiline ; } if ( doLastLineIndent ) { tempIndentation [ lineEnd - <NUM_LIT:1> ] += indentationMultiline ; } } } } } } private boolean isEmptyLine ( int line ) { try { IDocument d = formatter . getProgressDocument ( ) ; int lineStart = d . getLineOffset ( line ) ; int lineLen = d . getLineLength ( line ) ; String lineTxt = d . get ( lineStart , lineLen ) ; boolean result = lineTxt . trim ( ) . equals ( "<STR_LIT>" ) ; return result ; } catch ( BadLocationException e ) { return true ; } } private void deleteWhiteSpaceBefore ( Token token ) throws BadLocationException { int endPos = tokens . getOffset ( token ) ; int startPos = endPos ; IDocument d = formatter . getProgressDocument ( ) ; while ( startPos > <NUM_LIT:0> && isTabOrSpace ( d . getChar ( startPos - <NUM_LIT:1> ) ) ) { startPos -- ; } if ( ! formatter . pref . isIndentEmptyLines ( ) || ! isEmptyLine ( formatter . getProgressDocument ( ) . getLineOfOffset ( startPos ) ) ) { addEdit ( new DeleteEdit ( startPos , endPos - startPos ) ) ; } } private boolean isTabOrSpace ( char c ) { return c == '<CHAR_LIT:U+0020>' || c == '<STR_LIT:\t>' ; } private void indentendSwitchStatement ( Token token ) { if ( token != null ) { ASTNode node = formatter . findCorrespondingNode ( token ) ; if ( node instanceof SwitchStatement ) { SwitchStatement switchstmt = ( SwitchStatement ) node ; for ( CaseStatement cs : ( List < CaseStatement > ) switchstmt . getCaseStatements ( ) ) { indentendBlockStatement ( cs . getCode ( ) , cs . getLineNumber ( ) ) ; } Statement defaultstmt = switchstmt . getDefaultStatement ( ) ; int posDef = formatter . getPosOfToken ( defaultstmt . getLineNumber ( ) , defaultstmt . getColumnNumber ( ) ) ; if ( posDef != - <NUM_LIT:1> ) { Token def = formatter . getPreviousToken ( posDef ) ; indentendBlockStatement ( switchstmt . getDefaultStatement ( ) , def . getLine ( ) ) ; } } } } private void indentendBlockStatement ( Statement stmt , int currentLine ) { if ( stmt instanceof BlockStatement ) { BlockStatement defaultBlock = ( BlockStatement ) stmt ; for ( Statement sm : ( List < Statement > ) defaultBlock . getStatements ( ) ) { if ( sm . getLineNumber ( ) > currentLine ) { for ( int i = sm . getLineNumber ( ) ; i <= sm . getLastLineNumber ( ) ; i ++ ) { tempIndentation [ i - <NUM_LIT:1> ] += <NUM_LIT:1> ; } } } } } private void addEdit ( TextEdit edit ) { if ( edit instanceof DeleteEdit && edit . getLength ( ) == <NUM_LIT:0> ) { return ; } if ( edit instanceof ReplaceEdit && edit . getLength ( ) == <NUM_LIT:0> && ( ( ReplaceEdit ) edit ) . getText ( ) . isEmpty ( ) ) { return ; } if ( edit instanceof InsertEdit && ( ( InsertEdit ) edit ) . getText ( ) . isEmpty ( ) ) { return ; } if ( edit != null && edit . getOffset ( ) >= formatter . formatOffset && edit . getOffset ( ) + edit . getLength ( ) <= formatter . formatOffset + formatter . formatLength ) { if ( edit instanceof DeleteEdit ) { debug ( "<STR_LIT>" + edit . getOffset ( ) + "<STR_LIT::>" + edit . getLength ( ) ) ; debug ( "<STR_LIT>" ) ; IDocument doc = formatter . getProgressDocument ( ) ; try { debug ( doc . get ( <NUM_LIT:0> , edit . getOffset ( ) ) + "<STR_LIT>" + doc . get ( edit . getOffset ( ) , edit . getLength ( ) ) + "<STR_LIT>" + doc . get ( edit . getOffset ( ) + edit . getLength ( ) , doc . getLength ( ) - ( edit . getOffset ( ) + edit . getLength ( ) ) ) ) ; } catch ( BadLocationException e ) { e . printStackTrace ( ) ; } debug ( "<STR_LIT>" ) ; } try { indentationEdits . addChild ( edit ) ; } catch ( MalformedTreeException e ) { debug ( "<STR_LIT>" + edit ) ; GroovyCore . logException ( "<STR_LIT>" , e ) ; } } } private void setAdditionalIndentation ( Token t , int i , boolean firstLineInlcuded ) { if ( t != null ) { if ( t . getType ( ) != GroovyTokenTypeBridge . LCURLY ) { ASTNode node = formatter . findCorrespondingNode ( t ) ; if ( node != null ) { int r = node . getLineNumber ( ) ; if ( ! firstLineInlcuded ) { r ++ ; } for ( ; r <= node . getLastLineNumber ( ) ; r ++ ) { if ( isLastClosureArg ( r - <NUM_LIT:1> , node ) ) break ; tempIndentation [ r - <NUM_LIT:1> ] += i ; lineInd . setMultilineIndentation ( r , true ) ; } } } } } private boolean isLastClosureArg ( int line , ASTNode node ) { try { Token token = tokens . getTokenFrom ( tokens . getDocument ( ) . getLineOffset ( line ) ) ; if ( token == null ) return false ; else if ( "<STR_LIT:{>" . equals ( token . getText ( ) ) ) { ASTNode nestedNode = formatter . findCorrespondingNode ( token ) ; return node . getEnd ( ) == nestedNode . getEnd ( ) ; } return false ; } catch ( Throwable e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; return false ; } } private void setAdditionalIndentation ( Token t ) { setAdditionalIndentation ( t , <NUM_LIT:1> , true ) ; } public LineIndentations getLineIndentations ( ) { return lineInd ; } private String formatMultilineComment ( String str , int ind ) throws BadLocationException { String string = str ; Matcher m = Pattern . compile ( "<STR_LIT>" , Pattern . MULTILINE ) . matcher ( string ) ; string = m . replaceAll ( formatter . getNewLine ( ) + formatter . getLeadingGap ( ind ) + "<STR_LIT:U+0020>" ) ; return string ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . formatter ; import java . util . Map ; import org . eclipse . jdt . core . IJavaProject ; import org . eclipse . jdt . core . JavaCore ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . util . IPropertyChangeListener ; public class JavaProjectPreferences implements IPreferenceStore { private Map < String , String > options ; private IJavaProject javaProject ; public void refresh ( ) { if ( javaProject != null ) { this . options = javaProject . getOptions ( true ) ; } else { this . options = JavaCore . getOptions ( ) ; } } public JavaProjectPreferences ( IJavaProject javaProject ) { this . javaProject = javaProject ; refresh ( ) ; } public void addPropertyChangeListener ( IPropertyChangeListener listener ) { } public void removePropertyChangeListener ( IPropertyChangeListener listener ) { } public boolean contains ( String name ) { return options . containsKey ( name ) ; } public void firePropertyChangeEvent ( String name , Object oldValue , Object newValue ) { } public boolean getBoolean ( String name ) { return Boolean . valueOf ( getString ( name ) ) ; } public boolean getDefaultBoolean ( String name ) { return BOOLEAN_DEFAULT_DEFAULT ; } public double getDefaultDouble ( String name ) { return DOUBLE_DEFAULT_DEFAULT ; } public float getDefaultFloat ( String name ) { return FLOAT_DEFAULT_DEFAULT ; } public int getDefaultInt ( String name ) { return INT_DEFAULT_DEFAULT ; } public long getDefaultLong ( String name ) { return LONG_DEFAULT_DEFAULT ; } public String getDefaultString ( String name ) { return STRING_DEFAULT_DEFAULT ; } public double getDouble ( String name ) { return Double . valueOf ( getString ( name ) ) ; } public float getFloat ( String name ) { return Float . valueOf ( getString ( name ) ) ; } public int getInt ( String name ) { return Integer . valueOf ( getString ( name ) ) ; } public long getLong ( String name ) { return Long . valueOf ( getString ( name ) ) ; } public String getString ( String name ) { String result = options . get ( name ) ; if ( result == null ) result = getDefaultString ( name ) ; return result ; } public boolean isDefault ( String name ) { return getDefaultString ( name ) . equals ( getString ( name ) ) ; } public boolean needsSaving ( ) { return false ; } public void putValue ( String name , String value ) { throw new UnsupportedOperationException ( "<STR_LIT>" ) ; } public void setDefault ( String name , double value ) { throw new UnsupportedOperationException ( "<STR_LIT>" ) ; } public void setDefault ( String name , float value ) { throw new UnsupportedOperationException ( "<STR_LIT>" ) ; } public void setDefault ( String name , int value ) { throw new UnsupportedOperationException ( "<STR_LIT>" ) ; } public void setDefault ( String name , long value ) { throw new UnsupportedOperationException ( "<STR_LIT>" ) ; } public void setDefault ( String name , String defaultObject ) { throw new UnsupportedOperationException ( "<STR_LIT>" ) ; } public void setDefault ( String name , boolean value ) { throw new UnsupportedOperationException ( "<STR_LIT>" ) ; } public void setToDefault ( String name ) { throw new UnsupportedOperationException ( "<STR_LIT>" ) ; } public void setValue ( String name , double value ) { throw new UnsupportedOperationException ( "<STR_LIT>" ) ; } public void setValue ( String name , float value ) { throw new UnsupportedOperationException ( "<STR_LIT>" ) ; } public void setValue ( String name , int value ) { throw new UnsupportedOperationException ( "<STR_LIT>" ) ; } public void setValue ( String name , long value ) { throw new UnsupportedOperationException ( "<STR_LIT>" ) ; } public void setValue ( String name , String value ) { throw new UnsupportedOperationException ( "<STR_LIT>" ) ; } public void setValue ( String name , boolean value ) { throw new UnsupportedOperationException ( "<STR_LIT>" ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . formatter ; import antlr . Token ; import java . util . Vector ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . text . edits . MultiTextEdit ; import org . eclipse . text . edits . ReplaceEdit ; import org . eclipse . text . edits . TextEdit ; public class GroovyLineWrapper { public DefaultGroovyFormatter formatter ; private final IFormatterPreferences preferences ; private final LineIndentations lineIndentation ; MultiTextEdit lineWraps ; public GroovyLineWrapper ( DefaultGroovyFormatter defaultGroovyFormatter , IFormatterPreferences pref , LineIndentations lineIndentations ) { this . formatter = defaultGroovyFormatter ; this . preferences = pref ; this . lineIndentation = lineIndentations ; lineWraps = new MultiTextEdit ( ) ; } public TextEdit getLineWrapEdits ( ) throws BadLocationException { Vector < Vector < Token > > tokenLines = formatter . getLineTokens ( ) ; for ( int line = <NUM_LIT:0> ; line < tokenLines . size ( ) ; line ++ ) { Token lastTokenOnLine = tokenLines . get ( line ) . get ( tokenLines . get ( line ) . size ( ) - <NUM_LIT:1> ) ; if ( lastTokenOnLine . getColumn ( ) >= preferences . getMaxLineLength ( ) ) { int offsetInLine = <NUM_LIT:0> ; while ( true ) { int lastToken = getLastTokenPositionUnderMaximum ( tokenLines . get ( line ) , offsetInLine ) ; if ( lastToken > <NUM_LIT:0> && lastToken != tokenLines . get ( line ) . size ( ) - <NUM_LIT:2> ) { int replOffset = formatter . getOffsetOfTokenEnd ( tokenLines . get ( line ) . get ( lastToken ) ) ; int replLength = formatter . getOffsetOfToken ( tokenLines . get ( line ) . get ( lastToken + <NUM_LIT:1> ) ) - replOffset ; String insert = formatter . getNewLine ( ) ; int indentationLevel = lineIndentation . getLineIndentation ( lastTokenOnLine . getLine ( ) ) ; if ( ! lineIndentation . isMultilineIndentation ( lastTokenOnLine . getLine ( ) ) ) indentationLevel += preferences . getIndentationMultiline ( ) ; String leadingGap = formatter . getLeadingGap ( indentationLevel ) ; lineWraps . addChild ( new ReplaceEdit ( replOffset , replLength , insert + leadingGap ) ) ; offsetInLine = tokenLines . get ( line ) . get ( lastToken + <NUM_LIT:1> ) . getColumn ( ) - leadingGap . length ( ) ; } else break ; } } } return lineWraps ; } private int getLastTokenPositionUnderMaximum ( Vector < Token > vector , int offsetInLine ) throws BadLocationException { for ( int i = vector . size ( ) - <NUM_LIT:2> ; i >= <NUM_LIT:0> ; i -- ) { Token token = vector . get ( i ) ; if ( token . getColumn ( ) - offsetInLine + formatter . getTokenLength ( token ) <= preferences . getMaxLineLength ( ) ) { return i ; } } return <NUM_LIT:0> ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . formatter ; import java . util . HashSet ; import java . util . List ; import java . util . Set ; import org . codehaus . greclipse . GroovyTokenTypeBridge ; import org . codehaus . groovy . ast . ASTNode ; import org . codehaus . groovy . ast . expr . ArgumentListExpression ; import org . codehaus . groovy . ast . expr . ClosureExpression ; import org . codehaus . groovy . ast . expr . Expression ; import org . codehaus . groovy . ast . expr . ListExpression ; import org . codehaus . groovy . ast . stmt . BlockStatement ; import org . codehaus . groovy . eclipse . core . GroovyCore ; import org . codehaus . groovy . eclipse . refactoring . PreferenceConstants ; import org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner . ASTScanner ; import org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner . predicates . ClosuresInCodePredicate ; import org . codehaus . groovy . eclipse . refactoring . formatter . lineWrap . CorrectLineWrap ; import org . codehaus . groovy . eclipse . refactoring . formatter . lineWrap . NextLine ; import org . codehaus . groovy . eclipse . refactoring . formatter . lineWrap . SameLine ; import org . eclipse . jdt . internal . core . util . Util ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . text . edits . InsertEdit ; import org . eclipse . text . edits . MalformedTreeException ; import org . eclipse . text . edits . MultiTextEdit ; import org . eclipse . text . edits . ReplaceEdit ; import org . eclipse . text . edits . TextEdit ; import antlr . Token ; public class GroovyBeautifier { private static final boolean DEBUG_EDITS = false ; public DefaultGroovyFormatter formatter ; private final IFormatterPreferences preferences ; private final Set < Token > ignoreToken ; public GroovyBeautifier ( DefaultGroovyFormatter defaultGroovyFormatter , IFormatterPreferences pref ) { this . formatter = defaultGroovyFormatter ; this . preferences = pref ; ignoreToken = new HashSet < Token > ( ) ; } public TextEdit getBeautifiEdits ( ) throws MalformedTreeException , BadLocationException { MultiTextEdit edits = new MultiTextEdit ( ) ; combineClosures ( edits ) ; formatLists ( edits ) ; correctBraces ( edits ) ; removeUnnecessarySemicolons ( edits ) ; formatter . getTokens ( ) . dispose ( ) ; return edits ; } private void formatLists ( MultiTextEdit edits ) { ASTScanner scanner = new ASTScanner ( formatter . getProgressRootNode ( ) , new ListInCodePredicate ( ) , formatter . getProgressDocument ( ) ) ; scanner . startASTscan ( ) ; for ( ASTNode _node : scanner . getMatchedNodes ( ) . keySet ( ) ) { ListExpression node = ( ( ListExpression ) _node ) ; GroovyDocumentScanner tokens = formatter . getTokens ( ) ; Token lastToken = null ; try { lastToken = tokens . getLastNonWhitespaceTokenBefore ( node . getEnd ( ) - <NUM_LIT:1> ) ; if ( lastToken == null || lastToken . getType ( ) == GroovyTokenTypeBridge . STRING_CTOR_START ) { continue ; } } catch ( BadLocationException e ) { Util . log ( e ) ; continue ; } int nodeStart = node . getStart ( ) ; int nodeEnd = node . getEnd ( ) ; int nodeLen = nodeEnd - nodeStart ; boolean isLong = nodeLen > preferences . getLongListLength ( ) ; List < Expression > exps = node . getExpressions ( ) ; Token maybeAs ; try { maybeAs = tokens . getNextToken ( lastToken ) ; } catch ( BadLocationException e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; maybeAs = null ; } boolean nextTokenAs = maybeAs != null && maybeAs . getType ( ) == GroovyTokenTypeBridge . LITERAL_as ; if ( isLong || ( hasClosureElement ( node ) && node . getExpressions ( ) . size ( ) > <NUM_LIT:1> ) ) { for ( int i = <NUM_LIT:0> ; i < exps . size ( ) ; i ++ ) { Expression exp = exps . get ( i ) ; Token before = tokens . getLastTokenBefore ( exp . getStart ( ) ) ; try { while ( before . getType ( ) != GroovyTokenTypeBridge . LBRACK && before . getType ( ) != GroovyTokenTypeBridge . COMMA ) { before = tokens . getLastTokenBefore ( before ) ; } replaceWhiteSpaceAfter ( edits , before , formatter . getNewLine ( ) ) ; } catch ( BadLocationException e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; } } if ( ! nextTokenAs ) { replaceWhiteSpaceAfter ( edits , lastToken , formatter . getNewLine ( ) ) ; } } else { for ( int i = <NUM_LIT:0> ; i < exps . size ( ) ; i ++ ) { Expression exp = exps . get ( i ) ; Token before = tokens . getLastTokenBefore ( exp . getStart ( ) ) ; try { while ( before . getType ( ) != GroovyTokenTypeBridge . LBRACK && before . getType ( ) != GroovyTokenTypeBridge . COMMA ) { before = tokens . getLastTokenBefore ( before ) ; } replaceWhiteSpaceAfter ( edits , before , before . getType ( ) == GroovyTokenTypeBridge . LBRACK ? "<STR_LIT>" : "<STR_LIT:U+0020>" ) ; } catch ( BadLocationException e ) { Util . log ( e ) ; } } if ( ! nextTokenAs ) { replaceWhiteSpaceAfter ( edits , lastToken , lastToken . getType ( ) == GroovyTokenTypeBridge . SL_COMMENT ? formatter . getNewLine ( ) : "<STR_LIT>" ) ; } } } } private void replaceWhiteSpaceAfter ( MultiTextEdit edits , Token token , String replaceWith ) { GroovyDocumentScanner tokens = formatter . getTokens ( ) ; try { int editStart = tokens . getEnd ( token ) ; Token first = tokens . getNextToken ( token ) ; Token last = first ; while ( isWhiteSpace ( last . getType ( ) ) ) { last = tokens . getNextToken ( last ) ; } replaceFromTo ( editStart , tokens . getOffset ( last ) , replaceWith , edits ) ; } catch ( BadLocationException e ) { Util . log ( e ) ; } } private boolean isWhiteSpace ( int type ) { return type == GroovyTokenTypeBridge . WS || type == GroovyTokenTypeBridge . NLS ; } private boolean hasClosureElement ( ListExpression node ) { List < Expression > list = node . getExpressions ( ) ; for ( int i = <NUM_LIT:0> ; i < list . size ( ) ; i ++ ) { if ( list . get ( i ) instanceof ClosureExpression ) return true ; } return false ; } private void combineClosures ( MultiTextEdit edits ) throws BadLocationException { ASTScanner scanner = new ASTScanner ( formatter . getProgressRootNode ( ) , new ClosuresInCodePredicate ( ) , formatter . getProgressDocument ( ) ) ; scanner . startASTscan ( ) ; for ( ASTNode node : scanner . getMatchedNodes ( ) . keySet ( ) ) { ClosureExpression clExp = ( ( ClosureExpression ) node ) ; int posClStart = formatter . getPosOfToken ( GroovyTokenTypeBridge . LCURLY , clExp . getLineNumber ( ) , clExp . getColumnNumber ( ) , "<STR_LIT:{>" ) ; if ( posClStart == - <NUM_LIT:1> ) { continue ; } int posCLEnd = formatter . getPosOfToken ( GroovyTokenTypeBridge . RCURLY , clExp . getLastLineNumber ( ) , clExp . getLastColumnNumber ( ) - <NUM_LIT:1> , "<STR_LIT:}>" ) ; if ( posCLEnd == - <NUM_LIT:1> ) { int positionLastTokenOfClosure = formatter . getPosOfToken ( clExp . getLastLineNumber ( ) , clExp . getLastColumnNumber ( ) ) ; while ( formatter . getTokens ( ) . get ( positionLastTokenOfClosure ) . getType ( ) != GroovyTokenTypeBridge . RCURLY ) { positionLastTokenOfClosure -- ; } posCLEnd = positionLastTokenOfClosure ; } if ( clExp . getLineNumber ( ) == clExp . getLastLineNumber ( ) ) { ignoreToken . add ( formatter . getTokens ( ) . get ( posCLEnd ) ) ; continue ; } if ( clExp . getCode ( ) instanceof BlockStatement ) { BlockStatement codeblock = ( BlockStatement ) clExp . getCode ( ) ; int posParamDelim = posClStart ; if ( clExp . getParameters ( ) != null && clExp . getParameters ( ) . length > <NUM_LIT:0> ) { posParamDelim = formatter . getPosOfNextTokenOfType ( posClStart , GroovyTokenTypeBridge . CLOSABLE_BLOCK_OP ) ; replaceNLSWithSpace ( edits , posClStart , posParamDelim ) ; } if ( codeblock . getStatements ( ) . size ( ) == <NUM_LIT:1> && ( posCLEnd - posClStart ) < <NUM_LIT:10> ) { replaceNLSWithSpace ( edits , posParamDelim , posCLEnd ) ; ignoreToken . add ( formatter . getTokens ( ) . get ( posCLEnd ) ) ; } else { if ( posParamDelim > <NUM_LIT:0> && formatter . getNextTokenIncludingNLS ( posParamDelim ) . getType ( ) != GroovyTokenTypeBridge . NLS ) { addEdit ( new InsertEdit ( formatter . getOffsetOfTokenEnd ( formatter . getTokens ( ) . get ( posParamDelim ) ) , formatter . getNewLine ( ) ) , edits ) ; } else { if ( posParamDelim == <NUM_LIT:0> && formatter . getNextTokenIncludingNLS ( posClStart ) . getType ( ) != GroovyTokenTypeBridge . NLS ) { addEdit ( new InsertEdit ( formatter . getOffsetOfTokenEnd ( formatter . getTokens ( ) . get ( posClStart ) ) , formatter . getNewLine ( ) ) , edits ) ; } } } } } } private void replaceNLSWithSpace ( MultiTextEdit container , int startPos , int endPos ) throws BadLocationException { Token fromToken = null ; int p = startPos + <NUM_LIT:1> ; while ( p < endPos ) { Token token = formatter . getTokens ( ) . get ( p ) ; int ttype = token . getType ( ) ; if ( ttype == GroovyTokenTypeBridge . NLS ) { if ( fromToken == null ) fromToken = token ; } else { if ( ttype == GroovyTokenTypeBridge . SL_COMMENT ) { ++ p ; } if ( fromToken != null ) { replaceFromTo ( fromToken , token , "<STR_LIT:U+0020>" , container ) ; fromToken = null ; } } ++ p ; } if ( fromToken != null ) { Token token = formatter . getTokens ( ) . get ( p ) ; replaceFromTo ( fromToken , token , "<STR_LIT:U+0020>" , container ) ; } } private void replaceFromTo ( Token fromToken , Token toToken , String with , MultiTextEdit container ) throws BadLocationException { int startEdit = formatter . getOffsetOfToken ( fromToken ) ; int endEdit = formatter . getOffsetOfToken ( toToken ) ; addEdit ( new ReplaceEdit ( startEdit , endEdit - startEdit , with ) , container ) ; } private void replaceFromTo ( int startEdit , int endEdit , String with , MultiTextEdit container ) { addEdit ( new ReplaceEdit ( startEdit , endEdit - startEdit , with ) , container ) ; } private void correctBraces ( MultiTextEdit edits ) throws BadLocationException { CorrectLineWrap lCurlyCorrector = null ; CorrectLineWrap rCurlyCorrector = null ; if ( preferences . getBracesStart ( ) == PreferenceConstants . SAME_LINE ) { lCurlyCorrector = new SameLine ( this ) ; } else if ( preferences . getBracesStart ( ) == PreferenceConstants . NEXT_LINE ) { lCurlyCorrector = new NextLine ( this ) ; } if ( preferences . getBracesEnd ( ) == PreferenceConstants . SAME_LINE ) { rCurlyCorrector = new SameLine ( this ) ; } else if ( preferences . getBracesEnd ( ) == PreferenceConstants . NEXT_LINE ) { rCurlyCorrector = new NextLine ( this ) ; } assert lCurlyCorrector != null ; assert rCurlyCorrector != null ; Token token ; boolean skipNextNLS = false ; for ( int i = <NUM_LIT:0> ; i < formatter . getTokens ( ) . size ( ) ; i ++ ) { token = formatter . getTokens ( ) . get ( i ) ; if ( ignoreToken . contains ( token ) ) continue ; int ttype = formatter . getTokens ( ) . get ( i ) . getType ( ) ; if ( ttype == GroovyTokenTypeBridge . LCURLY ) { KlenkDocumentScanner tokens = formatter . getTokens ( ) ; if ( skipNextNLS ) { skipNextNLS = false ; break ; } ClosureExpression maybeClosure = formatter . findCorrespondingClosure ( token ) ; if ( maybeClosure == null || maybeClosure . getLineNumber ( ) != maybeClosure . getLastLineNumber ( ) ) { addEdit ( lCurlyCorrector . correctLineWrap ( i , token ) , edits ) ; ASTNode node = formatter . findCorrespondingNode ( token ) ; if ( node == null || ! ( node instanceof ClosureExpression || node instanceof ArgumentListExpression ) ) { Token nextToken = tokens . getNextToken ( token ) ; if ( nextToken != null ) { int type = nextToken . getType ( ) ; if ( type != GroovyTokenTypeBridge . NLS ) { int start = tokens . getEnd ( token ) ; int end = tokens . getOffset ( nextToken ) ; addEdit ( new ReplaceEdit ( start , end - start , formatter . getNewLine ( ) ) , edits ) ; } } } } } else if ( ttype == GroovyTokenTypeBridge . RCURLY ) { if ( skipNextNLS ) { skipNextNLS = false ; } else { addEdit ( rCurlyCorrector . correctLineWrap ( i , token ) , edits ) ; } } else if ( ttype == GroovyTokenTypeBridge . NLS ) { } else if ( ttype == GroovyTokenTypeBridge . SL_COMMENT ) { skipNextNLS = true ; } } } private void removeUnnecessarySemicolons ( MultiTextEdit edits ) throws BadLocationException { if ( preferences . isRemoveUnnecessarySemicolons ( ) ) { GroovyFormatter semicolonRemover = new SemicolonRemover ( formatter . selection , formatter . document , edits ) ; semicolonRemover . format ( ) ; } } private void addEdit ( TextEdit edit , TextEdit container ) { if ( edit != null && edit . getOffset ( ) >= formatter . formatOffset && edit . getOffset ( ) + edit . getLength ( ) <= formatter . formatOffset + formatter . formatLength ) { if ( DEBUG_EDITS ) { try { IDocument doc = formatter . getProgressDocument ( ) ; System . out . println ( "<STR_LIT>" + edit ) ; int startLine = doc . getLineOfOffset ( edit . getOffset ( ) ) ; int endLine = doc . getLineOfOffset ( edit . getOffset ( ) + edit . getLength ( ) ) ; for ( int line = startLine - <NUM_LIT:1> ; line < endLine + <NUM_LIT:1> ; line ++ ) { if ( line >= <NUM_LIT:0> && line < doc . getNumberOfLines ( ) ) { for ( int i = doc . getLineOffset ( line ) ; i < doc . getLineOffset ( line ) + doc . getLineLength ( line ) ; i ++ ) { if ( i == edit . getOffset ( ) ) System . out . print ( "<STR_LIT>" ) ; if ( i == edit . getOffset ( ) + edit . getLength ( ) ) System . out . print ( "<STR_LIT>" ) ; System . out . print ( doc . getChar ( i ) ) ; } } } System . out . println ( "<STR_LIT>" + edit ) ; } catch ( BadLocationException e ) { e . printStackTrace ( ) ; } } try { container . addChild ( edit ) ; } catch ( MalformedTreeException e ) { if ( DEBUG_EDITS ) System . out . println ( "<STR_LIT>" + e . getMessage ( ) ) ; } } } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . formatter ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . codehaus . groovy . eclipse . core . GroovyCore ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . text . edits . DeleteEdit ; import org . eclipse . text . edits . MalformedTreeException ; import org . eclipse . text . edits . MultiTextEdit ; import org . eclipse . text . edits . TextEdit ; public class WhitespaceRemover extends GroovyFormatter { private static final Pattern TRAILING_WHITESPACE_PATTERN = Pattern . compile ( "<STR_LIT>" ) ; private final MultiTextEdit edits ; public WhitespaceRemover ( ITextSelection sel , IDocument doc ) { this ( sel , doc , new MultiTextEdit ( ) ) ; } public WhitespaceRemover ( ITextSelection sel , IDocument doc , MultiTextEdit edits ) { super ( sel , doc ) ; this . edits = edits ; } @ Override public TextEdit format ( ) { try { for ( int i = <NUM_LIT:0> ; i < document . getNumberOfLines ( ) ; i ++ ) { IRegion lineInfo = document . getLineInformation ( i ) ; String line = document . get ( lineInfo . getOffset ( ) , lineInfo . getLength ( ) ) ; Matcher matcher = TRAILING_WHITESPACE_PATTERN . matcher ( line ) ; if ( matcher . find ( ) ) { int whitespaceOffset = lineInfo . getOffset ( ) + matcher . start ( ) ; int whitespaceLength = matcher . end ( ) - matcher . start ( ) ; addWhitespaceRemoval ( whitespaceOffset , whitespaceLength ) ; } } } catch ( BadLocationException e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; } return edits ; } private void addWhitespaceRemoval ( int whitespaceOffset , int whitespaceLength ) { TextEdit deleteWhitespace = new DeleteEdit ( whitespaceOffset , whitespaceLength ) ; try { edits . addChild ( deleteWhitespace ) ; } catch ( MalformedTreeException e ) { GroovyCore . logWarning ( "<STR_LIT>" + deleteWhitespace , e ) ; } } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . formatter ; import java . util . Map . Entry ; import java . util . Vector ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . codehaus . greclipse . GroovyTokenTypeBridge ; import org . codehaus . groovy . ast . ASTNode ; import org . codehaus . groovy . ast . AnnotatedNode ; import org . codehaus . groovy . ast . ModuleNode ; import org . codehaus . groovy . ast . expr . ClosureExpression ; import org . codehaus . groovy . ast . expr . VariableExpression ; import org . codehaus . groovy . ast . stmt . ExpressionStatement ; import org . codehaus . groovy . ast . stmt . Statement ; import org . codehaus . groovy . eclipse . core . GroovyCore ; import org . codehaus . groovy . eclipse . refactoring . core . utils . ASTTools ; import org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner . ASTNodeInfo ; import org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner . ASTScanner ; import org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner . predicates . IncludesClosureOrListPredicate ; import org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner . predicates . SourceCodePredicate ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . jface . text . TextSelection ; import org . eclipse . text . edits . MultiTextEdit ; import org . eclipse . text . edits . ReplaceEdit ; import org . eclipse . text . edits . TextEdit ; import org . eclipse . text . edits . UndoEdit ; import antlr . Token ; public class DefaultGroovyFormatter extends GroovyFormatter { private static final boolean DEGUG = false ; protected IFormatterPreferences pref ; private ModuleNode rootNode ; private Document formattedDocument ; private final boolean indentOnly ; public int formatOffset , formatLength ; private KlenkDocumentScanner tokens ; private int indentationLevel = <NUM_LIT:0> ; public DefaultGroovyFormatter ( ITextSelection sel , IDocument doc , IFormatterPreferences pref , boolean indentOnly ) { super ( sel , doc ) ; this . indentOnly = indentOnly ; this . pref = pref ; if ( selection . getLength ( ) != <NUM_LIT:0> ) { try { int startLine = document . getLineOfOffset ( selection . getOffset ( ) ) ; IRegion startLineInfo = document . getLineInformation ( startLine ) ; int endLine = document . getLineOfOffset ( selection . getOffset ( ) + selection . getLength ( ) - <NUM_LIT:1> ) ; IRegion endLineInfo = document . getLineInformation ( endLine ) ; formatOffset = startLineInfo . getOffset ( ) ; formatLength = endLineInfo . getOffset ( ) + endLineInfo . getLength ( ) - formatOffset ; } catch ( BadLocationException e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; formatOffset = selection . getOffset ( ) ; formatLength = selection . getLength ( ) ; } } else { formatOffset = <NUM_LIT:0> ; formatLength = document . getLength ( ) ; } } public DefaultGroovyFormatter ( IDocument doc , IFormatterPreferences prefs , int indentationLevel ) { this ( new TextSelection ( <NUM_LIT:0> , <NUM_LIT:0> ) , doc , prefs , true ) ; this . indentationLevel = indentationLevel ; } private void initCodebase ( ) throws Exception { GroovyCore . trace ( formattedDocument . get ( ) ) ; tokens = new KlenkDocumentScanner ( formattedDocument ) ; rootNode = ASTTools . getASTNodeFromSource ( formattedDocument . get ( ) ) ; if ( rootNode == null ) { throw new Exception ( "<STR_LIT>" ) ; } } @ Override public TextEdit format ( ) { formattedDocument = new Document ( document . get ( ) ) ; try { if ( ! indentOnly ) { initCodebase ( ) ; GroovyBeautifier beautifier = new GroovyBeautifier ( this , pref ) ; int lengthBefore = formattedDocument . getLength ( ) ; beautifier . getBeautifiEdits ( ) . apply ( formattedDocument ) ; int lengthAfter = formattedDocument . getLength ( ) ; formatLength += lengthAfter - lengthBefore ; } initCodebase ( ) ; GroovyIndentation indent = new GroovyIndentation ( this , pref , indentationLevel ) ; UndoEdit undo2 = indent . getIndentationEdits ( ) . apply ( formattedDocument ) ; formatLength += undo2 . getLength ( ) ; } catch ( Exception e ) { GroovyCore . logWarning ( "<STR_LIT>" , e ) ; } if ( formattedDocument . get ( ) . equals ( document . get ( ) ) ) { return new MultiTextEdit ( ) ; } return new ReplaceEdit ( <NUM_LIT:0> , document . getLength ( ) , formattedDocument . get ( ) ) ; } public boolean isMultilineStatement ( Token t ) { if ( t != null ) { ASTNode node = findCorrespondingNode ( t ) ; if ( DEGUG ) { System . out . println ( "<STR_LIT>" + t ) ; System . out . println ( "<STR_LIT>" ) ; System . out . println ( ASTTools . getTextofNode ( node , formattedDocument ) ) ; System . out . println ( "<STR_LIT>" ) ; } if ( isMultilineNodeType ( node ) ) { IncludesClosureOrListPredicate cltest = new IncludesClosureOrListPredicate ( false , t . getLine ( ) ) ; node . visit ( cltest ) ; if ( ! cltest . getContainer ( ) ) { String text = ASTTools . getTextofNode ( node , formattedDocument ) ; Matcher m = Pattern . compile ( "<STR_LIT>" , Pattern . DOTALL ) . matcher ( trimEnd ( text ) ) ; return m . matches ( ) ; } } } return false ; } public String trimEnd ( String s ) { int len = s . length ( ) ; while ( len > <NUM_LIT:0> ) { String w = s . substring ( len - <NUM_LIT:1> , len ) ; if ( w . matches ( "<STR_LIT>" ) ) { len -- ; } else { break ; } } return s . substring ( <NUM_LIT:0> , len ) ; } private boolean isMultilineNodeType ( ASTNode node ) { if ( node != null && node . getLineNumber ( ) < node . getLastLineNumber ( ) ) { if ( node instanceof ExpressionStatement ) { return true ; } else if ( node instanceof Statement ) { return false ; } else if ( node instanceof VariableExpression ) { return false ; } else if ( node instanceof AnnotatedNode ) { return false ; } else { return true ; } } return false ; } public ASTNode findCorrespondingNode ( Token t ) { ASTScanner scanner = new ASTScanner ( rootNode , new SourceCodePredicate ( t . getLine ( ) , t . getColumn ( ) ) , formattedDocument ) ; scanner . startASTscan ( ) ; Entry < ASTNode , ASTNodeInfo > found = null ; if ( scanner . hasMatches ( ) ) { for ( Entry < ASTNode , ASTNodeInfo > e : scanner . getMatchedNodes ( ) . entrySet ( ) ) { if ( found == null || ( found . getValue ( ) . getLength ( ) < e . getValue ( ) . getLength ( ) ) ) found = e ; } } if ( found != null ) { return found . getKey ( ) ; } else { return null ; } } public ClosureExpression findCorrespondingClosure ( Token t ) { ASTScanner scanner = new ASTScanner ( rootNode , new SourceCodePredicate ( t . getLine ( ) , t . getColumn ( ) ) , formattedDocument ) ; scanner . startASTscan ( ) ; ClosureExpression found = null ; if ( scanner . hasMatches ( ) ) { for ( Entry < ASTNode , ASTNodeInfo > e : scanner . getMatchedNodes ( ) . entrySet ( ) ) { if ( e . getKey ( ) instanceof ClosureExpression ) { found = ( ClosureExpression ) e . getKey ( ) ; } } } return found ; } public Token getTokenAfterParenthesis ( int index ) { int i = index ; int countParenthesis = <NUM_LIT:1> ; while ( tokens . get ( i ) . getType ( ) != GroovyTokenTypeBridge . LPAREN ) { i ++ ; } i ++ ; while ( countParenthesis > <NUM_LIT:0> && i < tokens . size ( ) - <NUM_LIT:1> ) { int ttype = tokens . get ( i ) . getType ( ) ; if ( ttype == GroovyTokenTypeBridge . LPAREN ) { countParenthesis ++ ; } else if ( ttype == GroovyTokenTypeBridge . RPAREN ) { countParenthesis -- ; } i ++ ; } if ( tokens . get ( i ) . getType ( ) == GroovyTokenTypeBridge . LCURLY || i >= tokens . size ( ) ) { return null ; } return getNextToken ( i ) ; } public String getLeadingGap ( int indent ) { int spaces = indent * pref . getIndentationSize ( ) ; return GroovyIndentationService . createIndentation ( pref , spaces ) ; } public String getNewLine ( ) { return formattedDocument . getDefaultLineDelimiter ( ) ; } public int getPositionOfNextToken ( int cPos , boolean includingNLS ) { if ( cPos == tokens . size ( ) - <NUM_LIT:1> ) { return cPos ; } int currentPos = cPos ; int type ; do { type = tokens . get ( ++ currentPos ) . getType ( ) ; } while ( ( type == GroovyTokenTypeBridge . WS || ( type == GroovyTokenTypeBridge . NLS && ! includingNLS ) ) && currentPos < tokens . size ( ) - <NUM_LIT:2> ) ; return currentPos ; } public Token getNextToken ( int currentPos ) { return tokens . get ( getPositionOfNextToken ( currentPos , false ) ) ; } public Token getNextTokenIncludingNLS ( int currentPos ) { return tokens . get ( getPositionOfNextToken ( currentPos , true ) ) ; } public int getPositionOfPreviousToken ( int cPos , boolean includingNLS ) { int currentPos = cPos ; int type ; do { type = tokens . get ( -- currentPos ) . getType ( ) ; } while ( ( type == GroovyTokenTypeBridge . NLS && ! includingNLS ) && currentPos >= <NUM_LIT:0> ) ; return currentPos ; } public Token getPreviousToken ( int currentPos ) { return tokens . get ( getPositionOfPreviousToken ( currentPos , false ) ) ; } public Token getPreviousTokenIncludingNLS ( int currentPos ) { return tokens . get ( getPositionOfPreviousToken ( currentPos , true ) ) ; } public int getOffsetOfToken ( Token token ) throws BadLocationException { return formattedDocument . getLineOffset ( token . getLine ( ) - <NUM_LIT:1> ) + token . getColumn ( ) - <NUM_LIT:1> ; } public int getOffsetOfTokenEnd ( Token token ) throws BadLocationException { int offsetToken = getOffsetOfToken ( token ) ; int offsetNextToken = getOffsetOfToken ( getNextTokenIncludingNLS ( getPosOfToken ( token ) ) ) ; String tokenWithGap = formattedDocument . get ( offsetToken , offsetNextToken - offsetToken ) ; return offsetToken + trimEnd ( tokenWithGap ) . length ( ) ; } public int getTokenLength ( Token token ) throws BadLocationException { return getOffsetOfTokenEnd ( token ) - getOffsetOfToken ( token ) ; } public Vector < Vector < Token > > getLineTokens ( ) { return tokens . getLineTokensVector ( ) ; } public int getPosOfToken ( Token token ) throws BadLocationException { return tokens . indexOf ( token ) ; } public int getPosOfToken ( int tokenType , int line , int column , String tokenText ) { for ( int p = <NUM_LIT:0> ; p < tokens . size ( ) ; p ++ ) { Token a = tokens . get ( p ) ; if ( a . getType ( ) == tokenType && a . getColumn ( ) == column && a . getLine ( ) == line && a . getText ( ) . equals ( tokenText ) ) return p ; } return - <NUM_LIT:1> ; } public int getPosOfToken ( int lineNumber , int columnNumber ) { for ( int p = <NUM_LIT:0> ; p < tokens . size ( ) ; p ++ ) { Token a = tokens . get ( p ) ; if ( a . getColumn ( ) == columnNumber && a . getLine ( ) == lineNumber ) return p ; } return - <NUM_LIT:1> ; } public IDocument getProgressDocument ( ) { return formattedDocument ; } public ModuleNode getProgressRootNode ( ) { return rootNode ; } public KlenkDocumentScanner getTokens ( ) { return tokens ; } public void setIndentationLevel ( int indentationLevel ) { this . indentationLevel = indentationLevel ; } public int getPosOfNextTokenOfType ( int pClStart , int expectedType ) { int posClStart = pClStart ; int type ; do { type = tokens . get ( ++ posClStart ) . getType ( ) ; } while ( type != expectedType ) ; return posClStart ; } public int computeIndentLevel ( String line ) { int accumulatedSpaces = <NUM_LIT:0> ; int tabSize = pref . getTabSize ( ) ; for ( int currPos = <NUM_LIT:0> ; currPos < line . length ( ) ; currPos ++ ) { char c = line . charAt ( currPos ) ; if ( c != '<CHAR_LIT:U+0020>' && c != '<STR_LIT:\t>' ) { break ; } else if ( c == '<STR_LIT:\t>' ) { accumulatedSpaces = nextTabStop ( accumulatedSpaces , tabSize ) ; } else if ( c == '<CHAR_LIT:U+0020>' ) { accumulatedSpaces ++ ; } } int indentSize = pref . getIndentationSize ( ) ; return accumulatedSpaces / indentSize ; } private int nextTabStop ( int spaces , int tabSize ) { int tabs = spaces / tabSize + <NUM_LIT:1> ; return tabs * tabSize ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . formatter ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . ITextSelection ; import org . eclipse . text . edits . TextEdit ; public abstract class GroovyFormatter { protected ITextSelection selection ; protected IDocument document ; public GroovyFormatter ( ITextSelection sel , IDocument doc ) { this . selection = sel ; this . document = doc ; } public abstract TextEdit format ( ) ; } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . formatter ; import org . eclipse . core . runtime . preferences . InstanceScope ; import org . eclipse . jdt . core . ICompilationUnit ; import org . eclipse . jdt . core . IJavaProject ; import org . eclipse . jdt . internal . ui . JavaPlugin ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . ui . preferences . ScopedPreferenceStore ; import org . eclipse . ui . texteditor . ChainedPreferenceStore ; public class FormatterPreferences extends FormatterPreferencesOnStore implements IFormatterPreferences { public FormatterPreferences ( ICompilationUnit gunit ) { super ( preferencesFor ( gunit ) ) ; } public FormatterPreferences ( IJavaProject project ) { super ( preferencesFor ( project ) ) ; } private static IPreferenceStore preferencesFor ( ICompilationUnit gunit ) { return preferencesFor ( gunit . getJavaProject ( ) ) ; } private static IPreferenceStore preferencesFor ( IJavaProject javaProject ) { IPreferenceStore javaPrefs = new JavaProjectPreferences ( javaProject ) ; IPreferenceStore groovyPrefs = new ScopedPreferenceStore ( new InstanceScope ( ) , "<STR_LIT>" ) ; IPreferenceStore javaUIprefs = JavaPlugin . getDefault ( ) . getCombinedPreferenceStore ( ) ; return new ChainedPreferenceStore ( new IPreferenceStore [ ] { groovyPrefs , javaPrefs , javaUIprefs } ) ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . formatter ; import static org . codehaus . groovy . eclipse . refactoring . PreferenceConstants . DEFAULT_BRACES_END ; import static org . codehaus . groovy . eclipse . refactoring . PreferenceConstants . DEFAULT_BRACES_START ; import static org . codehaus . groovy . eclipse . refactoring . PreferenceConstants . DEFAULT_INDENT_EMPTY_LINES ; import static org . codehaus . groovy . eclipse . refactoring . PreferenceConstants . DEFAULT_INDENT_MULTILINE ; import static org . codehaus . groovy . eclipse . refactoring . PreferenceConstants . DEFAULT_INDENT_SIZE ; import static org . codehaus . groovy . eclipse . refactoring . PreferenceConstants . DEFAULT_LONG_LIST_LENGTH ; import static org . codehaus . groovy . eclipse . refactoring . PreferenceConstants . DEFAULT_MAX_LINE_LEN ; import static org . codehaus . groovy . eclipse . refactoring . PreferenceConstants . DEFAULT_REMOVE_UNNECESSARY_SEMICOLONS ; import static org . codehaus . groovy . eclipse . refactoring . PreferenceConstants . DEFAULT_SMART_PASTE ; import static org . codehaus . groovy . eclipse . refactoring . PreferenceConstants . DEFAULT_TAB_SIZE ; import static org . codehaus . groovy . eclipse . refactoring . PreferenceConstants . DEFAULT_USE_TABS ; import static org . codehaus . groovy . eclipse . refactoring . PreferenceConstants . NEXT_LINE ; import static org . codehaus . groovy . eclipse . refactoring . PreferenceConstants . SAME_LINE ; import org . codehaus . groovy . eclipse . refactoring . PreferenceConstants ; import org . eclipse . jdt . core . JavaCore ; import org . eclipse . jdt . core . formatter . DefaultCodeFormatterConstants ; import org . eclipse . jface . preference . IPreferenceStore ; import org . eclipse . jface . preference . PreferenceStore ; public class FormatterPreferencesOnStore implements IFormatterPreferences { private boolean useTabs ; private int tabSize ; private int indentSize ; private int indentationMultiline ; private int bracesStart ; private int bracesEnd ; private int maxLineLength ; private boolean smartPaste ; private boolean indentEmptyLines ; private boolean removeUnnecessarySemicolons ; private int longListLength ; public FormatterPreferencesOnStore ( IPreferenceStore preferences ) { if ( preferences == null ) preferences = new PreferenceStore ( ) ; refresh ( preferences ) ; } private void refresh ( IPreferenceStore preferences ) { indentEmptyLines = DEFAULT_INDENT_EMPTY_LINES ; String pIndentEmpty = preferences . getString ( DefaultCodeFormatterConstants . FORMATTER_INDENT_EMPTY_LINES ) ; if ( pIndentEmpty != null ) { indentEmptyLines = pIndentEmpty . equals ( DefaultCodeFormatterConstants . TRUE ) ; } bracesStart = DEFAULT_BRACES_START ; String pBracesStart = preferences . getString ( PreferenceConstants . GROOVY_FORMATTER_BRACES_START ) ; if ( pBracesStart != null && pBracesStart . equals ( PreferenceConstants . NEXT ) ) bracesStart = NEXT_LINE ; bracesEnd = DEFAULT_BRACES_END ; String pBracesEnd = preferences . getString ( PreferenceConstants . GROOVY_FORMATTER_BRACES_END ) ; if ( pBracesEnd != null && pBracesEnd . equals ( "<STR_LIT>" ) ) bracesEnd = SAME_LINE ; tabSize = DEFAULT_TAB_SIZE ; int pTabSize = preferences . getInt ( PreferenceConstants . GROOVY_FORMATTER_TAB_SIZE ) ; if ( pTabSize != <NUM_LIT:0> ) tabSize = pTabSize ; indentSize = DEFAULT_INDENT_SIZE ; int pIndentSize = preferences . getInt ( PreferenceConstants . GROOVY_FORMATTER_INDENTATION_SIZE ) ; if ( pIndentSize != <NUM_LIT:0> ) { indentSize = pIndentSize ; } useTabs = DEFAULT_USE_TABS ; String pTab = preferences . getString ( PreferenceConstants . GROOVY_FORMATTER_INDENTATION ) ; if ( pTab != null ) { if ( pTab . equals ( JavaCore . SPACE ) ) { useTabs = false ; indentSize = tabSize ; } else if ( pTab . equals ( JavaCore . TAB ) ) { useTabs = true ; indentSize = tabSize ; } else if ( pTab . equals ( DefaultCodeFormatterConstants . MIXED ) ) { useTabs = true ; } } indentationMultiline = DEFAULT_INDENT_MULTILINE ; int pIndeMulti = preferences . getInt ( PreferenceConstants . GROOVY_FORMATTER_MULTILINE_INDENTATION ) ; if ( pIndeMulti != <NUM_LIT:0> ) indentationMultiline = pIndeMulti ; int pMaxLine = preferences . getInt ( PreferenceConstants . GROOVY_FORMATTER_MAX_LINELENGTH ) ; maxLineLength = DEFAULT_MAX_LINE_LEN ; if ( pMaxLine != <NUM_LIT:0> ) maxLineLength = pMaxLine ; String pSmartPaste = preferences . getString ( org . eclipse . jdt . ui . PreferenceConstants . EDITOR_SMART_PASTE ) ; smartPaste = DEFAULT_SMART_PASTE ; if ( "<STR_LIT:true>" . equals ( pSmartPaste ) ) smartPaste = true ; else if ( "<STR_LIT:false>" . equals ( pSmartPaste ) ) smartPaste = false ; removeUnnecessarySemicolons = DEFAULT_REMOVE_UNNECESSARY_SEMICOLONS ; String pRemoveUnnecessarySemicolons = preferences . getString ( PreferenceConstants . GROOVY_FORMATTER_REMOVE_UNNECESSARY_SEMICOLONS ) ; if ( pRemoveUnnecessarySemicolons != null ) { removeUnnecessarySemicolons = pRemoveUnnecessarySemicolons . equals ( "<STR_LIT:true>" ) ; } longListLength = DEFAULT_LONG_LIST_LENGTH ; int pLongListLength = preferences . getInt ( PreferenceConstants . GROOVY_FORMATTER_LONG_LIST_LENGTH ) ; if ( pLongListLength > <NUM_LIT:0> ) { longListLength = pLongListLength ; } } public int getIndentationMultiline ( ) { return indentationMultiline ; } public int getBracesStart ( ) { return bracesStart ; } public boolean useTabs ( ) { return useTabs ; } public int getBracesEnd ( ) { return bracesEnd ; } public int getMaxLineLength ( ) { return maxLineLength ; } public boolean isSmartPaste ( ) { return smartPaste ; } public boolean isIndentEmptyLines ( ) { return indentEmptyLines ; } public int getIndentationSize ( ) { return indentSize ; } public int getTabSize ( ) { return tabSize ; } public boolean isRemoveUnnecessarySemicolons ( ) { return removeUnnecessarySemicolons ; } public int getLongListLength ( ) { return longListLength ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . formatter ; import antlr . Token ; public class LineIndentations { private boolean [ ] multilineIndentation ; private int [ ] indentation ; private Token [ ] multilineToken ; public LineIndentations ( int lines ) { multilineIndentation = new boolean [ lines + <NUM_LIT:1> ] ; indentation = new int [ lines + <NUM_LIT:1> ] ; multilineToken = new Token [ lines + <NUM_LIT:1> ] ; } public void setLineIndentation ( int line , int ind ) { indentation [ line ] = ind ; } public int getLineIndentation ( int line ) { return indentation [ line ] ; } public void setMultilineIndentation ( int line , boolean state ) { multilineIndentation [ line ] = state ; } public boolean isMultilineIndentation ( int line ) { return multilineIndentation [ line ] ; } public void setMultilineToken ( int line , Token node ) { multilineToken [ line ] = node ; } public Token getMultiToken ( int line ) { return multilineToken [ line ] ; } public boolean isMultilineStatement ( int line ) { return multilineToken [ line ] != null ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . formatter ; import org . codehaus . groovy . ast . ASTNode ; import org . codehaus . groovy . ast . expr . ListExpression ; import org . codehaus . groovy . eclipse . refactoring . core . utils . ASTTools ; import org . codehaus . groovy . eclipse . refactoring . core . utils . astScanner . predicates . IASTNodePredicate ; public class ListInCodePredicate implements IASTNodePredicate { public ASTNode evaluate ( ASTNode input ) { if ( input . getClass ( ) == ListExpression . class ) { if ( ASTTools . hasValidPosition ( input ) ) return input ; } return null ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . formatter ; import java . util . ArrayList ; import java . util . List ; import org . codehaus . greclipse . GroovyTokenTypeBridge ; import org . codehaus . groovy . antlr . GroovySourceToken ; import org . codehaus . groovy . eclipse . core . GroovyCore ; import org . eclipse . core . runtime . Assert ; import org . eclipse . jdt . groovy . core . util . GroovyScanner ; import org . eclipse . jdt . internal . core . util . Util ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . DocumentEvent ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IDocumentListener ; import org . eclipse . jface . text . ITextSelection ; import antlr . Token ; import antlr . TokenStreamException ; public class GroovyDocumentScanner implements IDocumentListener { private static final boolean TOKEN_POSITION_ASSERTS = true ; private IDocument document ; protected List < Token > tokens ; private GroovyScanner tokenScanner ; private static int logLimit = <NUM_LIT:4> ; private static final int NOT_FOUND = - <NUM_LIT:1> ; public GroovyDocumentScanner ( IDocument document ) { this . document = document ; this . document . addDocumentListener ( this ) ; reset ( ) ; } public void documentChanged ( DocumentEvent event ) { reset ( ) ; } public void documentAboutToBeChanged ( DocumentEvent event ) { } protected void ensureScanned ( int end ) { if ( tokens == null ) { tokenScanner = new GroovyScanner ( document . get ( ) ) ; tokens = getTokensIncludingEOF ( ) ; } } private List < Token > getTokensIncludingEOF ( ) { List < Token > result = new ArrayList < Token > ( ) ; Token token ; try { do { token = nextToken ( ) ; result . add ( token ) ; } while ( token . getType ( ) != GroovyTokenTypeBridge . EOF ) ; } catch ( Exception e ) { if ( logLimit -- > <NUM_LIT:0> ) { Util . log ( e ) ; } } return result ; } private Token nextToken ( ) throws TokenStreamException , BadLocationException { Token token ; try { token = tokenScanner . nextToken ( ) ; } catch ( TokenStreamException e ) { tokenScanner . recover ( document ) ; token = tokenScanner . nextToken ( ) ; } return token ; } private void reset ( ) { tokens = null ; } public int getOffset ( Token token ) throws BadLocationException { int offset = GroovyScanner . getOffset ( document , token . getLine ( ) , token . getColumn ( ) ) ; if ( TOKEN_POSITION_ASSERTS ) { if ( token . getType ( ) == GroovyTokenTypeBridge . EOF ) { } else { int col = token . getColumn ( ) - <NUM_LIT:1> ; int line = token . getLine ( ) - <NUM_LIT:1> ; Assert . isTrue ( col >= <NUM_LIT:0> ) ; Assert . isTrue ( col < document . getLineLength ( line ) , "<STR_LIT>" + token ) ; Assert . isTrue ( offset < document . getLength ( ) ) ; if ( token . getType ( ) == GroovyTokenTypeBridge . IDENT ) { String antlrText = token . getText ( ) ; String eclipseText = document . get ( offset , antlrText . length ( ) ) ; Assert . isTrue ( eclipseText . equals ( antlrText ) ) ; } } } return offset ; } public int getEnd ( Token token ) throws BadLocationException { GroovySourceToken gToken = ( GroovySourceToken ) token ; return GroovyScanner . getOffset ( document , gToken . getLineLast ( ) , gToken . getColumnLast ( ) ) ; } public void dispose ( ) { if ( this . document != null ) { document . removeDocumentListener ( this ) ; this . document = null ; } } @ Override protected void finalize ( ) throws Throwable { this . dispose ( ) ; super . finalize ( ) ; } public IDocument getDocument ( ) { return document ; } public List < Token > getTokens ( ITextSelection selection ) { int start ; int end ; if ( selection == null || selection . getLength ( ) == <NUM_LIT:0> ) { start = <NUM_LIT:0> ; end = document . getLength ( ) ; } else { start = selection . getOffset ( ) ; end = start + selection . getLength ( ) ; } return getTokens ( start , end ) ; } public List < Token > getTokens ( int start , int end ) { if ( start >= end ) return new ArrayList < Token > ( ) ; try { int startTokenIndex = findTokenFrom ( start ) ; if ( startTokenIndex == NOT_FOUND ) return new ArrayList < Token > ( ) ; if ( getOffset ( tokens . get ( startTokenIndex ) ) >= end ) return new ArrayList < Token > ( ) ; int endTokenIndex = findTokenFrom ( end ) ; if ( endTokenIndex == NOT_FOUND ) { endTokenIndex = tokens . size ( ) - <NUM_LIT:1> ; } else { endTokenIndex = endTokenIndex - <NUM_LIT:1> ; } Assert . isTrue ( startTokenIndex <= endTokenIndex ) ; return tokens . subList ( startTokenIndex , endTokenIndex + <NUM_LIT:1> ) ; } catch ( BadLocationException e ) { throw new Error ( e ) ; } } public List < Token > getLineTokensUpto ( int offset ) { try { int start = document . getLineOffset ( document . getLineOfOffset ( offset ) ) ; return getTokens ( start , offset ) ; } catch ( BadLocationException e ) { return new ArrayList < Token > ( ) ; } } public List < Token > getLineTokensFrom ( int offset ) { try { int line = document . getLineOfOffset ( offset ) ; int lineEnd = document . getLineOffset ( line ) + document . getLineLength ( line ) ; return getTokens ( offset , lineEnd ) ; } catch ( BadLocationException e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; return new ArrayList < Token > ( ) ; } } protected int findTokenFrom ( int offset ) { Assert . isLegal ( offset >= <NUM_LIT:0> ) ; ensureScanned ( offset ) ; try { int start = <NUM_LIT:0> ; int end = tokens . size ( ) - <NUM_LIT:1> ; while ( start <= end ) { if ( getOffset ( tokens . get ( start ) ) >= offset ) { return start ; } else { start ++ ; if ( start > end ) return NOT_FOUND ; } int mid = ( start + end ) / <NUM_LIT:2> ; int midOfs = getOffset ( tokens . get ( mid ) ) ; if ( midOfs >= offset ) { end = mid ; } else { start = mid + <NUM_LIT:1> ; } } return NOT_FOUND ; } catch ( BadLocationException e ) { throw new Error ( e ) ; } } public Token getLastTokenBefore ( int offset ) { int index = findTokenFrom ( offset ) ; if ( index == NOT_FOUND ) { return getLastToken ( ) ; } if ( index > <NUM_LIT:0> ) { return tokens . get ( index - <NUM_LIT:1> ) ; } return null ; } public Token getLastTokenBefore ( Token token ) throws BadLocationException { return getLastTokenBefore ( getOffset ( token ) ) ; } public Token getLastToken ( ) { ensureScanned ( Integer . MAX_VALUE ) ; return tokens . get ( tokens . size ( ) - <NUM_LIT:1> ) ; } public List < Token > getLineTokens ( int line ) throws BadLocationException { int lineOffset = document . getLineOffset ( line ) ; return getTokens ( lineOffset , lineOffset + document . getLineLength ( line ) ) ; } public Token getTokenFrom ( int offset ) { int index = findTokenFrom ( offset ) ; if ( index == NOT_FOUND ) return null ; return tokens . get ( index ) ; } public Token getNextToken ( Token token ) throws BadLocationException { return getTokenFrom ( getOffset ( token ) + <NUM_LIT:1> ) ; } public Token getLastNonWhitespaceTokenBefore ( int offset ) throws BadLocationException { Token result = getLastTokenBefore ( offset ) ; while ( result != null && isWhitespace ( result ) ) result = getLastTokenBefore ( result ) ; return result ; } private boolean isWhitespace ( Token result ) { int type = result . getType ( ) ; return type == GroovyTokenTypeBridge . WS || type == GroovyTokenTypeBridge . NLS ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . formatter ; import static org . codehaus . greclipse . GroovyTokenTypeBridge . EOF ; import static org . codehaus . greclipse . GroovyTokenTypeBridge . LBRACK ; import static org . codehaus . greclipse . GroovyTokenTypeBridge . LCURLY ; import static org . codehaus . greclipse . GroovyTokenTypeBridge . LPAREN ; import static org . codehaus . greclipse . GroovyTokenTypeBridge . NLS ; import static org . codehaus . greclipse . GroovyTokenTypeBridge . RBRACK ; import static org . codehaus . greclipse . GroovyTokenTypeBridge . RCURLY ; import static org . codehaus . greclipse . GroovyTokenTypeBridge . RPAREN ; import static org . codehaus . greclipse . GroovyTokenTypeBridge . STRING_CTOR_END ; import static org . codehaus . greclipse . GroovyTokenTypeBridge . STRING_CTOR_START ; import java . util . HashMap ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import java . util . Set ; import org . codehaus . greclipse . GroovyTokenTypeBridge ; import org . codehaus . groovy . eclipse . core . GroovyCore ; import org . eclipse . core . runtime . Assert ; import org . eclipse . jdt . core . IJavaProject ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . Document ; import org . eclipse . jface . text . IDocument ; import org . eclipse . jface . text . IRegion ; import org . eclipse . jface . text . TextUtilities ; import antlr . Token ; public class GroovyIndentationService { public static synchronized GroovyIndentationService get ( IJavaProject javaProject ) { if ( lastIndentor == null || lastIndentor . getJavaProject ( ) != javaProject ) { lastIndentor = new GroovyIndentationService ( javaProject ) ; } return lastIndentor ; } public static String getLeadingWhiteSpace ( String text ) { int i = <NUM_LIT:0> ; while ( i < text . length ( ) && Character . isWhitespace ( text . charAt ( i ) ) ) i ++ ; return text . substring ( <NUM_LIT:0> , i ) ; } public static String getLine ( IDocument d , int lineNum ) { try { String delim = d . getLineDelimiter ( lineNum ) ; int delimLen = delim == null ? <NUM_LIT:0> : delim . length ( ) ; String string = d . get ( d . getLineOffset ( lineNum ) , d . getLineLength ( lineNum ) - delimLen ) ; return string ; } catch ( BadLocationException e ) { return "<STR_LIT>" ; } } public static String getLineLeadingWhiteSpace ( IDocument d , int line ) { return getLeadingWhiteSpace ( getLine ( d , line ) ) ; } public static String getLineTextUpto ( IDocument d , int offset ) throws BadLocationException { int line = d . getLineOfOffset ( offset ) ; int lineStart = d . getLineOffset ( line ) ; String lineStartText = d . get ( lineStart , offset - lineStart ) ; return lineStartText ; } private static void openClosePair ( int opener , int closer ) { Assert . isTrue ( ! closer2opener . containsKey ( closer ) ) ; closer2opener . put ( closer , opener ) ; jumpIn . add ( opener ) ; jumpOut . add ( closer ) ; } private IJavaProject project ; private IFormatterPreferences prefs ; private GroovyDocumentScanner cachedScanner ; private static Set < Integer > jumpIn = new HashSet < Integer > ( ) ; private static Set < Integer > jumpOut = new HashSet < Integer > ( ) ; private static Map < Integer , Integer > closer2opener = new HashMap < Integer , Integer > ( ) ; private static GroovyIndentationService lastIndentor ; static { openClosePair ( LCURLY , RCURLY ) ; openClosePair ( LBRACK , RBRACK ) ; openClosePair ( LPAREN , RPAREN ) ; openClosePair ( STRING_CTOR_START , STRING_CTOR_END ) ; } public GroovyIndentationService ( IJavaProject project ) { this . project = project ; } public int computeIndentAfterNewline ( IDocument d , int offset ) throws BadLocationException { Token token = getTokenBefore ( d , offset ) ; int line = token == null ? <NUM_LIT:0> : getLine ( token ) ; int orgIndentLevel = token == null ? <NUM_LIT:0> : getLineIndentLevel ( d , line ) ; List < Token > tokens = getTokens ( d , d . getLineOffset ( line ) , offset ) ; int indentLevel = simpleComputeNextLineIndentLevel ( orgIndentLevel , tokens ) ; if ( indentLevel < orgIndentLevel ) { Token lastToken = tokens . get ( tokens . size ( ) - <NUM_LIT:1> ) ; if ( lastToken . getType ( ) == GroovyTokenTypeBridge . NLS ) lastToken = getTokenBefore ( d , lastToken ) ; if ( isCloserOfPair ( lastToken ) ) { indentLevel = getIndentLevelForCloserPair ( d , lastToken ) ; } } return indentLevel ; } private int getLine ( Token token ) { return token . getLine ( ) - <NUM_LIT:1> ; } public int computeIndentForLine ( IDocument d , int line ) { try { if ( line == <NUM_LIT:0> ) { return <NUM_LIT:0> ; } else { Token nextToken = getTokenFrom ( d , d . getLineOffset ( line ) ) ; if ( isCloserOfPair ( nextToken ) ) { return getIndentLevelForCloserPair ( d , nextToken ) ; } else { IRegion prevLine = d . getLineInformation ( line - <NUM_LIT:1> ) ; return computeIndentAfterNewline ( d , prevLine . getOffset ( ) + prevLine . getLength ( ) ) ; } } } catch ( BadLocationException e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; return <NUM_LIT:0> ; } } public String createIndentation ( int spaces ) { return createIndentation ( getPrefs ( ) , spaces ) ; } public void dispose ( ) { this . project = null ; if ( this . cachedScanner != null ) { this . cachedScanner . dispose ( ) ; this . cachedScanner = null ; } this . prefs = null ; } public void disposePrefs ( ) { this . prefs = null ; } @ Override protected void finalize ( ) throws Throwable { this . dispose ( ) ; super . finalize ( ) ; } public void fixIndentation ( Document workCopy , int line , int newIndentLevel ) { try { IRegion lineRegion = workCopy . getLineInformation ( line ) ; String text = workCopy . get ( lineRegion . getOffset ( ) , lineRegion . getLength ( ) ) . trim ( ) ; text = createIndentation ( newIndentLevel ) + text ; workCopy . replace ( lineRegion . getOffset ( ) , lineRegion . getLength ( ) , text ) ; } catch ( BadLocationException e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; } } private GroovyDocumentScanner getGroovyDocumentScanner ( IDocument d ) { if ( cachedScanner != null && cachedScanner . getDocument ( ) == d ) return cachedScanner ; if ( cachedScanner != null ) { cachedScanner . dispose ( ) ; cachedScanner = null ; } cachedScanner = new GroovyDocumentScanner ( d ) ; return cachedScanner ; } public int getIndentLevel ( IDocument d , int offset ) { try { return getLineIndentLevel ( d , d . getLineOfOffset ( offset ) ) ; } catch ( BadLocationException e ) { return <NUM_LIT:0> ; } } private int getIndentLevelForCloserPair ( IDocument d , Token closer ) { GroovyDocumentScanner scanner = getGroovyDocumentScanner ( d ) ; int closerType = closer . getType ( ) ; int openerType = closer2opener . get ( closerType ) ; int closeCount = <NUM_LIT:1> ; Token token = closer ; try { while ( closeCount != <NUM_LIT:0> && ( token = scanner . getLastTokenBefore ( token ) ) != null ) { if ( token . getType ( ) == openerType ) closeCount -- ; if ( token . getType ( ) == closerType ) closeCount ++ ; } return getIndentLevel ( d , scanner . getOffset ( token ) ) ; } catch ( BadLocationException e ) { try { return getIndentLevel ( d , scanner . getOffset ( closer ) ) ; } catch ( BadLocationException e1 ) { return <NUM_LIT:0> ; } } } public IJavaProject getJavaProject ( ) { return project ; } public String getLineDelimiter ( IDocument d , int lineNum ) throws BadLocationException { String result = d . getLineDelimiter ( lineNum ) ; if ( result == null ) return "<STR_LIT>" ; else return result ; } public int getLineIndentLevel ( IDocument d , int lineNum ) { return indentLevel ( getLine ( d , lineNum ) ) ; } private List < Token > getLineTokensUpto ( IDocument d , int offset ) { return getGroovyDocumentScanner ( d ) . getLineTokensUpto ( offset ) ; } public IFormatterPreferences getPrefs ( ) { if ( prefs == null ) refreshPrefs ( ) ; return prefs ; } public String getTabString ( ) { return createIndentation ( getPrefs ( ) . getTabSize ( ) ) ; } private Token getTokenBefore ( IDocument d , Token token ) throws BadLocationException { return getGroovyDocumentScanner ( d ) . getLastTokenBefore ( token ) ; } private Token getTokenBefore ( IDocument d , int offset ) throws BadLocationException { return getGroovyDocumentScanner ( d ) . getLastTokenBefore ( offset ) ; } private Token getTokenFrom ( IDocument d , int offset ) { return getGroovyDocumentScanner ( d ) . getTokenFrom ( offset ) ; } private List < Token > getTokens ( IDocument d , int start , int end ) { return getGroovyDocumentScanner ( d ) . getTokens ( start , end ) ; } public int indentLevel ( String lineText ) { int level = <NUM_LIT:0> ; for ( int i = <NUM_LIT:0> ; i < lineText . length ( ) ; i ++ ) { switch ( lineText . charAt ( i ) ) { case '<CHAR_LIT:U+0020>' : level ++ ; break ; case '<STR_LIT:\t>' : level += getPrefs ( ) . getTabSize ( ) ; break ; default : return level ; } } return level ; } public boolean isAfterOpeningBrace ( IDocument d , int pos ) { Token token = getGroovyDocumentScanner ( d ) . getLastTokenBefore ( pos ) ; return token != null && token . getType ( ) == LCURLY ; } private boolean isCloserOfPair ( Token lastToken ) { return closer2opener . containsKey ( lastToken . getType ( ) ) ; } public boolean isEndOfLine ( IDocument d , int pos ) { Token token = getGroovyDocumentScanner ( d ) . getTokenFrom ( pos ) ; return token == null || token . getType ( ) == NLS || token . getType ( ) == EOF ; } public boolean isInEmptyLine ( IDocument d , int offset ) { int line ; try { line = d . getLineOfOffset ( offset ) ; String text = getLine ( d , line ) ; return text . trim ( ) . length ( ) == <NUM_LIT:0> ; } catch ( BadLocationException e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; return false ; } } public String newline ( IDocument d ) { return TextUtilities . getDefaultLineDelimiter ( d ) ; } public void refreshPrefs ( ) { this . prefs = new FormatterPreferences ( project ) ; } private int simpleComputeNextLineIndentLevel ( int indentLevel , List < Token > tokens ) { int adjust = getOpenVersusCloseBalance ( tokens ) ; if ( adjust > <NUM_LIT:0> ) indentLevel += getPrefs ( ) . getIndentationSize ( ) ; else if ( adjust < <NUM_LIT:0> ) indentLevel = indentLevel - getPrefs ( ) . getIndentationSize ( ) ; return indentLevel ; } public int getOpenVersusCloseBalance ( List < Token > tokens ) { int adjust = <NUM_LIT:0> ; for ( Token tok : tokens ) { if ( jumpIn . contains ( tok . getType ( ) ) ) adjust ++ ; if ( jumpOut . contains ( tok . getType ( ) ) ) adjust -- ; } return adjust ; } public static String createIndentation ( IFormatterPreferences pref , int spaces ) { StringBuilder gap = new StringBuilder ( ) ; if ( pref . useTabs ( ) ) { int tabSize = pref . getTabSize ( ) ; while ( spaces >= tabSize ) { gap . append ( '<STR_LIT:\t>' ) ; spaces -= tabSize ; } while ( spaces > <NUM_LIT:0> ) { gap . append ( '<CHAR_LIT:U+0020>' ) ; spaces -- ; } } else { for ( int i = <NUM_LIT:0> ; i < spaces ; i ++ ) { gap . append ( '<CHAR_LIT:U+0020>' ) ; } } return gap . toString ( ) ; } public boolean moreOpenThanCloseBefore ( IDocument d , int offset ) { return getOpenVersusCloseBalance ( getLineTokensUpto ( d , offset ) ) > <NUM_LIT:0> ; } public int lengthToNextCurly ( IDocument d , int offset ) throws BadLocationException { Token token = getTokenFrom ( d , offset ) ; if ( ! isEndOfLine ( d , offset ) && RCURLY == token . getType ( ) ) { return token . getColumn ( ) - offset + d . getLineOffset ( d . getLineOfOffset ( offset ) ) ; } else { return <NUM_LIT:0> ; } } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . formatter . lineWrap ; import org . codehaus . groovy . eclipse . refactoring . formatter . GroovyBeautifier ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . text . edits . ReplaceEdit ; import antlr . Token ; public class NextLine extends CorrectLineWrap { public NextLine ( GroovyBeautifier beautifier ) { super ( beautifier ) ; } @ Override public ReplaceEdit correctLineWrap ( int pos , Token token ) throws BadLocationException { ReplaceEdit correctEdit = null ; Token lastNotNLSToken = beautifier . formatter . getPreviousToken ( pos ) ; int replaceStart = beautifier . formatter . getOffsetOfTokenEnd ( lastNotNLSToken ) ; int replaceEnd = beautifier . formatter . getOffsetOfToken ( token ) ; correctEdit = new ReplaceEdit ( replaceStart , replaceEnd - replaceStart , beautifier . formatter . getNewLine ( ) ) ; return correctEdit ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . formatter . lineWrap ; import org . codehaus . greclipse . GroovyTokenTypeBridge ; import org . codehaus . groovy . eclipse . refactoring . formatter . GroovyBeautifier ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . text . edits . ReplaceEdit ; import antlr . Token ; public class SameLine extends CorrectLineWrap { public SameLine ( GroovyBeautifier beautifier ) { super ( beautifier ) ; } @ Override public ReplaceEdit correctLineWrap ( int pos , Token token ) throws BadLocationException { ReplaceEdit correctEdit = null ; if ( beautifier . formatter . getPreviousTokenIncludingNLS ( pos ) . getType ( ) == GroovyTokenTypeBridge . NLS ) { Token lastNotNLSToken = beautifier . formatter . getPreviousToken ( pos ) ; int replaceStart = beautifier . formatter . getOffsetOfTokenEnd ( lastNotNLSToken ) ; int replaceEnd = beautifier . formatter . getOffsetOfToken ( token ) ; correctEdit = new ReplaceEdit ( replaceStart , replaceEnd - replaceStart , "<STR_LIT:U+0020>" ) ; } return correctEdit ; } } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . formatter . lineWrap ; import antlr . Token ; import org . codehaus . groovy . eclipse . refactoring . formatter . GroovyBeautifier ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . text . edits . ReplaceEdit ; public abstract class CorrectLineWrap { protected GroovyBeautifier beautifier ; public CorrectLineWrap ( GroovyBeautifier beautifier ) { this . beautifier = beautifier ; } public abstract ReplaceEdit correctLineWrap ( int pos , Token token ) throws BadLocationException ; } </s>
|
<s> package org . codehaus . groovy . eclipse . refactoring . formatter ; import java . io . Reader ; import java . io . StringReader ; import java . util . ArrayList ; import java . util . Vector ; import org . codehaus . greclipse . GroovyTokenTypeBridge ; import org . codehaus . groovy . antlr . parser . GroovyLexer ; import org . codehaus . groovy . eclipse . core . GroovyCore ; import org . eclipse . core . runtime . Assert ; import org . eclipse . jface . text . BadLocationException ; import org . eclipse . jface . text . IDocument ; import antlr . Token ; import antlr . TokenStream ; import antlr . TokenStreamException ; public class KlenkDocumentScanner extends GroovyDocumentScanner { private Vector < Vector < Token > > tokenLines ; public KlenkDocumentScanner ( IDocument doc ) { super ( doc ) ; } @ Override protected void ensureScanned ( int end ) { if ( tokens != null ) return ; Reader input = new StringReader ( getDocument ( ) . get ( ) ) ; GroovyLexer lexer = new GroovyLexer ( input ) ; lexer . setWhitespaceIncluded ( true ) ; TokenStream stream = ( TokenStream ) lexer . plumb ( ) ; Token token = null ; tokens = new ArrayList < Token > ( ) ; tokenLines = new Vector < Vector < Token > > ( ) ; Vector < Token > line = new Vector < Token > ( ) ; try { while ( ( token = stream . nextToken ( ) ) . getType ( ) != GroovyTokenTypeBridge . EOF ) { if ( token . getType ( ) != GroovyTokenTypeBridge . WS ) { if ( token . getType ( ) == GroovyTokenTypeBridge . STRING_CTOR_START ) { tokens . add ( token ) ; Token prevToken = token ; inner : while ( ( token = stream . nextToken ( ) ) . getType ( ) != GroovyTokenTypeBridge . STRING_CTOR_END ) { if ( equalTokens ( prevToken , token ) ) { break inner ; } prevToken = token ; } } tokens . add ( token ) ; line . add ( token ) ; if ( token . getType ( ) == GroovyTokenTypeBridge . NLS ) { tokenLines . add ( line ) ; line = new Vector < Token > ( ) ; } } } } catch ( TokenStreamException e ) { GroovyCore . logException ( "<STR_LIT>" , e ) ; } tokens . add ( token ) ; line . add ( token ) ; tokenLines . add ( line ) ; } private boolean equalTokens ( Token t1 , Token t2 ) { return t1 . getType ( ) == t2 . getType ( ) && t1 . getColumn ( ) == t2 . getColumn ( ) && t1 . getLine ( ) == t2 . getLine ( ) && nullEquals ( t1 . getFilename ( ) , t2 . getFilename ( ) ) && nullEquals ( t1 . getText ( ) , t2 . getText ( ) ) ; } private boolean nullEquals ( String s1 , String s2 ) { if ( s1 == null && s2 == null ) { return true ; } else if ( s1 == null || s2 == null ) { return false ; } return s1 . equals ( s2 ) ; } @ Deprecated public Vector < Vector < Token > > getLineTokensVector ( ) { ensureScanned ( Integer . MAX_VALUE ) ; return tokenLines ; } @ Deprecated ( ) public Token get ( int i ) { ensureScanned ( Integer . MAX_VALUE ) ; if ( i < tokens . size ( ) ) { return tokens . get ( i ) ; } else { return null ; } } @ Deprecated public int size ( ) { ensureScanned ( Integer . MAX_VALUE ) ; return tokens . size ( ) ; } @ Deprecated public int indexOf ( Token token ) throws BadLocationException { int pos = findTokenFrom ( getOffset ( token ) ) ; Assert . isTrue ( token == tokens . get ( pos ) ) ; return pos ; } } </s>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.