idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
6,800
public Object run ( final String scriptText , final String fileName , String [ ] args ) throws CompilationFailedException { GroovyCodeSource gcs = AccessController . doPrivileged ( new PrivilegedAction < GroovyCodeSource > ( ) { public GroovyCodeSource run ( ) { return new GroovyCodeSource ( scriptText , fileName , DEFAULT_CODE_BASE ) ; } } ) ; return run ( gcs , args ) ; }
Runs the given script text with command line arguments
6,801
public Object evaluate ( final String scriptText , final String fileName , final String codeBase ) throws CompilationFailedException { SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) { sm . checkPermission ( new GroovyCodeSourcePermission ( codeBase ) ) ; } GroovyCodeSource gcs = AccessController . doPrivileged ( new PrivilegedAction < GroovyCodeSource > ( ) { public GroovyCodeSource run ( ) { return new GroovyCodeSource ( scriptText , fileName , codeBase ) ; } } ) ; return evaluate ( gcs ) ; }
Evaluates some script against the current Binding and returns the result . The . class file created from the script is given the supplied codeBase
6,802
public static Integer getIntegerSafe ( String name , Integer def ) { try { return Integer . getInteger ( name , def ) ; } catch ( SecurityException ignore ) { } return def ; }
Retrieves an Integer System property
6,803
private static BinaryExpression compareExpr ( Expression lhv , Expression rhv , boolean reversed ) { return ( reversed ) ? cmpX ( rhv , lhv ) : cmpX ( lhv , rhv ) ; }
Helper method used to build a binary expression that compares two values with the option to handle reverse order .
6,804
public Token dup ( ) { Token token = new Token ( this . type , this . text , this . startLine , this . startColumn ) ; token . setMeaning ( this . meaning ) ; return token ; }
Returns a copy of this Token .
6,805
public static Token newKeyword ( String text , int startLine , int startColumn ) { int type = Types . lookupKeyword ( text ) ; if ( type != Types . UNKNOWN ) { return new Token ( type , text , startLine , startColumn ) ; } return null ; }
Creates a token that represents a keyword . Returns null if the specified text isn t a keyword .
6,806
public static Token newString ( String text , int startLine , int startColumn ) { return new Token ( Types . STRING , text , startLine , startColumn ) ; }
Creates a token that represents a double - quoted string .
6,807
public static Token newIdentifier ( String text , int startLine , int startColumn ) { return new Token ( Types . IDENTIFIER , text , startLine , startColumn ) ; }
Creates a token that represents an identifier .
6,808
public static Token newInteger ( String text , int startLine , int startColumn ) { return new Token ( Types . INTEGER_NUMBER , text , startLine , startColumn ) ; }
Creates a token that represents an integer .
6,809
public static Token newDecimal ( String text , int startLine , int startColumn ) { return new Token ( Types . DECIMAL_NUMBER , text , startLine , startColumn ) ; }
Creates a token that represents a decimal number .
6,810
public static Token newSymbol ( int type , int startLine , int startColumn ) { return new Token ( type , Types . getText ( type ) , startLine , startColumn ) ; }
Creates a token that represents a symbol using a library for the text .
6,811
public static Token newSymbol ( String type , int startLine , int startColumn ) { return new Token ( Types . lookupSymbol ( type ) , type , startLine , startColumn ) ; }
Creates a token that represents a symbol using a library for the type .
6,812
public static Token newPlaceholder ( int type ) { Token token = new Token ( Types . UNKNOWN , "" , - 1 , - 1 ) ; token . setMeaning ( type ) ; return token ; }
Creates a token with the specified meaning .
6,813
public MethodNode makeDynamic ( MethodCall call , ClassNode returnType ) { TypeCheckingContext . EnclosingClosure enclosingClosure = context . getEnclosingClosure ( ) ; MethodNode enclosingMethod = context . getEnclosingMethod ( ) ; ( ( ASTNode ) call ) . putNodeMetaData ( StaticTypesMarker . DYNAMIC_RESOLUTION , returnType ) ; if ( enclosingClosure != null ) { enclosingClosure . getClosureExpression ( ) . putNodeMetaData ( StaticTypesMarker . DYNAMIC_RESOLUTION , Boolean . TRUE ) ; } else { enclosingMethod . putNodeMetaData ( StaticTypesMarker . DYNAMIC_RESOLUTION , Boolean . TRUE ) ; } setHandled ( true ) ; if ( debug ) { LOG . info ( "Turning " + call . getText ( ) + " into a dynamic method call returning " + returnType . toString ( false ) ) ; } return new MethodNode ( call . getMethodAsString ( ) , 0 , returnType , Parameter . EMPTY_ARRAY , ClassNode . EMPTY_ARRAY , EmptyStatement . INSTANCE ) ; }
Used to instruct the type checker that the call is a dynamic method call . Calling this method automatically sets the handled flag to true .
6,814
public void makeDynamic ( PropertyExpression pexp , ClassNode returnType ) { context . getEnclosingMethod ( ) . putNodeMetaData ( StaticTypesMarker . DYNAMIC_RESOLUTION , Boolean . TRUE ) ; pexp . putNodeMetaData ( StaticTypesMarker . DYNAMIC_RESOLUTION , returnType ) ; storeType ( pexp , returnType ) ; setHandled ( true ) ; if ( debug ) { LOG . info ( "Turning '" + pexp . getText ( ) + "' into a dynamic property access of type " + returnType . toString ( false ) ) ; } }
Instructs the type checker that a property access is dynamic . Calling this method automatically sets the handled flag to true .
6,815
public ClassNode getFromClassCache ( String name ) { ClassNode cached = cachedClasses . get ( name ) ; return cached ; }
returns whatever is stored in the class cache for the given name
6,816
private static LookupResult findByClassLoading ( String name , CompilationUnit compilationUnit , GroovyClassLoader loader ) { Class cls ; try { cls = loader . loadClass ( name , false , true ) ; } catch ( ClassNotFoundException cnfe ) { LookupResult lr = tryAsScript ( name , compilationUnit , null ) ; return lr ; } catch ( CompilationFailedException cfe ) { throw new GroovyBugError ( "The lookup for " + name + " caused a failed compilation. There should not have been any compilation from this call." , cfe ) ; } if ( cls == null ) return null ; ClassNode cn = ClassHelper . make ( cls ) ; if ( cls . getClassLoader ( ) != loader ) { return tryAsScript ( name , compilationUnit , cn ) ; } return new LookupResult ( null , cn ) ; }
Search for classes using class loading
6,817
private LookupResult findDecompiled ( String name , CompilationUnit compilationUnit , GroovyClassLoader loader ) { ClassNode node = ClassHelper . make ( name ) ; if ( node . isResolved ( ) ) { return new LookupResult ( null , node ) ; } DecompiledClassNode asmClass = null ; String fileName = name . replace ( '.' , '/' ) + ".class" ; URL resource = loader . getResource ( fileName ) ; if ( resource != null ) { try { asmClass = new DecompiledClassNode ( AsmDecompiler . parseClass ( resource ) , new AsmReferenceResolver ( this , compilationUnit ) ) ; if ( ! asmClass . getName ( ) . equals ( name ) ) { asmClass = null ; } } catch ( IOException e ) { } } if ( asmClass != null ) { if ( isFromAnotherClassLoader ( loader , fileName ) ) { return tryAsScript ( name , compilationUnit , asmClass ) ; } return new LookupResult ( null , asmClass ) ; } return null ; }
Search for classes using ASM decompiler
6,818
private static LookupResult tryAsScript ( String name , CompilationUnit compilationUnit , ClassNode oldClass ) { LookupResult lr = null ; if ( oldClass != null ) { lr = new LookupResult ( null , oldClass ) ; } if ( name . startsWith ( "java." ) ) return lr ; if ( name . indexOf ( '$' ) != - 1 ) return lr ; GroovyClassLoader gcl = compilationUnit . getClassLoader ( ) ; URL url = null ; try { url = gcl . getResourceLoader ( ) . loadGroovySource ( name ) ; } catch ( MalformedURLException e ) { } if ( url != null && ( oldClass == null || isSourceNewer ( url , oldClass ) ) ) { SourceUnit su = compilationUnit . addSource ( url ) ; return new LookupResult ( su , null ) ; } return lr ; }
try to find a script using the compilation unit class loader .
6,819
public void setDelegate ( Object delegate ) { this . delegate = delegate ; this . metaClass = InvokerHelper . getMetaClass ( delegate . getClass ( ) ) ; }
Sets the delegation target .
6,820
protected void writeRaw ( CharSequence seq , CharBuf buffer ) { if ( seq != null ) { buffer . add ( seq . toString ( ) ) ; } }
Serializes any char sequence and writes it into specified buffer without performing any manipulation of the given text .
6,821
protected void writeMapEntry ( String key , Object value , CharBuf buffer ) { buffer . addJsonFieldName ( key , disableUnicodeEscaping ) ; writeObject ( key , value , buffer ) ; }
Serializes a map entry and writes it into specified buffer .
6,822
protected boolean shouldExcludeType ( Class < ? > type ) { for ( Class < ? > t : excludedFieldTypes ) { if ( t . isAssignableFrom ( type ) ) { return true ; } } return false ; }
Indicates whether the given type should be excluded from the generated output .
6,823
public void addCell ( groovy . swing . impl . TableLayoutCell tag ) { int gridx = 0 ; for ( Iterator iter = cells . iterator ( ) ; iter . hasNext ( ) ; ) { groovy . swing . impl . TableLayoutCell cell = ( groovy . swing . impl . TableLayoutCell ) iter . next ( ) ; gridx += cell . getColspan ( ) ; } tag . getConstraints ( ) . gridx = gridx ; cells . add ( tag ) ; }
Adds a new cell to this row
6,824
public static Class [ ] convertToTypeArray ( Object [ ] args ) { if ( args == null ) return null ; int s = args . length ; Class [ ] ans = new Class [ s ] ; for ( int i = 0 ; i < s ; i ++ ) { Object o = args [ i ] ; ans [ i ] = getClassWithNullAndWrapper ( o ) ; } return ans ; }
param instance array to the type array
6,825
public void addFile ( File file ) { if ( file != null && file . exists ( ) ) { try { classPath . add ( file . toURI ( ) . toURL ( ) ) ; } catch ( MalformedURLException e ) { throw new AssertionError ( "converting an existing file to an url should have never thrown an exception!" ) ; } } }
Adds a file to the classpath if it exists .
6,826
public static < T > T withObjectOutputStream ( File file , @ ClosureParams ( value = SimpleType . class , options = "java.io.ObjectOutputStream" ) Closure < T > closure ) throws IOException { return IOGroovyMethods . withStream ( newObjectOutputStream ( file ) , closure ) ; }
Create a new ObjectOutputStream for this file and then pass it to the closure . This method ensures the stream is closed after the closure returns .
6,827
public static ObjectInputStream newObjectInputStream ( File file , final ClassLoader classLoader ) throws IOException { return IOGroovyMethods . newObjectInputStream ( new FileInputStream ( file ) , classLoader ) ; }
Create an object input stream for this file using the given class loader .
6,828
public static void eachObject ( File self , Closure closure ) throws IOException , ClassNotFoundException { IOGroovyMethods . eachObject ( newObjectInputStream ( self ) , closure ) ; }
Iterates through the given file object by object .
6,829
public static < T > T eachLine ( File self , @ ClosureParams ( value = FromString . class , options = { "String" , "String,Integer" } ) Closure < T > closure ) throws IOException { return eachLine ( self , 1 , closure ) ; }
Iterates through this file line by line . Each line is passed to the given 1 or 2 arg closure . The file is read using a reader which is closed before this method returns .
6,830
public static List < String > readLines ( File file ) throws IOException { return IOGroovyMethods . readLines ( newReader ( file ) ) ; }
Reads the file into a list of Strings with one item for each line .
6,831
public static List < String > readLines ( URL self , String charset ) throws IOException { return IOGroovyMethods . readLines ( newReader ( self , charset ) ) ; }
Reads the URL contents into a list with one element for each line .
6,832
public static String getText ( File file , String charset ) throws IOException { return IOGroovyMethods . getText ( newReader ( file , charset ) ) ; }
Read the content of the File using the specified encoding and return it as a String .
6,833
public static String getText ( URL url ) throws IOException { return getText ( url , CharsetToolkit . getDefaultSystemCharset ( ) . name ( ) ) ; }
Read the content of this URL and returns it as a String .
6,834
public static String getText ( URL url , String charset ) throws IOException { BufferedReader reader = newReader ( url , charset ) ; return IOGroovyMethods . getText ( reader ) ; }
Read the data from this URL and return it as a String . The connection stream is closed before this method returns .
6,835
public static void setBytes ( File file , byte [ ] bytes ) throws IOException { IOGroovyMethods . setBytes ( new FileOutputStream ( file ) , bytes ) ; }
Write the bytes from the byte array to the File .
6,836
public static File leftShift ( File file , byte [ ] bytes ) throws IOException { append ( file , bytes ) ; return file ; }
Write bytes to a File .
6,837
public static void write ( File file , String text , String charset ) throws IOException { write ( file , text , charset , false ) ; }
Write the text to the File without writing a BOM using the specified encoding .
6,838
public static void append ( File file , Object text ) throws IOException { append ( file , text , false ) ; }
Append the text at the end of the File without writing a BOM .
6,839
public static void append ( File file , Object text , String charset ) throws IOException { append ( file , text , charset , false ) ; }
Append the text at the end of the File without writing a BOM using a specified encoding .
6,840
public static void append ( File file , Reader reader , String charset ) throws IOException { append ( file , reader , charset , false ) ; }
Append the text supplied by the Reader at the end of the File without writing a BOM using a specified encoding .
6,841
public static String relativePath ( File self , File to ) throws IOException { String fromPath = self . getCanonicalPath ( ) ; String toPath = to . getCanonicalPath ( ) ; String [ ] fromPathStack = getPathStack ( fromPath ) ; String [ ] toPathStack = getPathStack ( toPath ) ; if ( 0 < toPathStack . length && 0 < fromPathStack . length ) { if ( ! fromPathStack [ 0 ] . equals ( toPathStack [ 0 ] ) ) { return getPath ( Arrays . asList ( toPathStack ) ) ; } } else { return getPath ( Arrays . asList ( toPathStack ) ) ; } int minLength = Math . min ( fromPathStack . length , toPathStack . length ) ; int same = 1 ; while ( same < minLength && fromPathStack [ same ] . equals ( toPathStack [ same ] ) ) { same ++ ; } List < String > relativePathStack = new ArrayList < String > ( ) ; for ( int i = same ; i < fromPathStack . length ; i ++ ) { relativePathStack . add ( ".." ) ; } relativePathStack . addAll ( Arrays . asList ( toPathStack ) . subList ( same , toPathStack . length ) ) ; return getPath ( relativePathStack ) ; }
Relative path to file .
6,842
public static < T > T withInputStream ( URL url , @ ClosureParams ( value = SimpleType . class , options = "java.io.InputStream" ) Closure < T > closure ) throws IOException { return IOGroovyMethods . withStream ( newInputStream ( url ) , closure ) ; }
Creates a new InputStream for this URL and passes it into the closure . This method ensures the stream is closed after the closure returns .
6,843
public static BufferedWriter newWriter ( File file , String charset ) throws IOException { return newWriter ( file , charset , false ) ; }
Creates a buffered writer for this file writing data without writing a BOM using a specified encoding .
6,844
public static < T > T withWriter ( File file , @ ClosureParams ( value = SimpleType . class , options = "java.io.BufferedWriter" ) Closure < T > closure ) throws IOException { return IOGroovyMethods . withWriter ( newWriter ( file ) , closure ) ; }
Creates a new BufferedWriter for this file passes it to the closure and ensures the stream is flushed and closed after the closure returns .
6,845
public static < T > T withReader ( URL url , @ ClosureParams ( value = SimpleType . class , options = "java.io.Reader" ) Closure < T > closure ) throws IOException { return IOGroovyMethods . withReader ( url . openConnection ( ) . getInputStream ( ) , closure ) ; }
Helper method to create a new BufferedReader for a URL and then passes it to the closure . The reader is closed after the closure returns .
6,846
public static BufferedInputStream newInputStream ( URL url ) throws MalformedURLException , IOException { return new BufferedInputStream ( configuredInputStream ( null , url ) ) ; }
Creates a buffered input stream for this URL .
6,847
public static BufferedReader newReader ( URL url ) throws MalformedURLException , IOException { return IOGroovyMethods . newReader ( configuredInputStream ( null , url ) ) ; }
Creates a buffered reader for this URL .
6,848
public static void eachByte ( URL url , @ ClosureParams ( value = SimpleType . class , options = "byte" ) Closure closure ) throws IOException { InputStream is = url . openConnection ( ) . getInputStream ( ) ; IOGroovyMethods . eachByte ( is , closure ) ; }
Reads the InputStream from this URL passing each byte to the given closure . The URL stream will be closed before this method returns .
6,849
public static Writable filterLine ( File self , @ ClosureParams ( value = SimpleType . class , options = "java.lang.String" ) Closure closure ) throws IOException { return IOGroovyMethods . filterLine ( newReader ( self ) , closure ) ; }
Filters the lines of a File and creates a Writable in return to stream the filtered lines .
6,850
public static byte [ ] readBytes ( File file ) throws IOException { byte [ ] bytes = new byte [ ( int ) file . length ( ) ] ; FileInputStream fileInputStream = new FileInputStream ( file ) ; DataInputStream dis = new DataInputStream ( fileInputStream ) ; try { dis . readFully ( bytes ) ; InputStream temp = dis ; dis = null ; temp . close ( ) ; } finally { closeWithWarning ( dis ) ; } return bytes ; }
Reads the content of the file into a byte array .
6,851
public static Tuple2 < ClassNode [ ] , ClassNode > parameterizeSAM ( ClassNode sam ) { MethodNode methodNode = ClassHelper . findSAM ( sam ) ; final Map < GenericsType , GenericsType > map = makeDeclaringAndActualGenericsTypeMapOfExactType ( methodNode . getDeclaringClass ( ) , sam ) ; ClassNode [ ] parameterTypes = Arrays . stream ( methodNode . getParameters ( ) ) . map ( e -> { ClassNode originalParameterType = e . getType ( ) ; return originalParameterType . isGenericsPlaceHolder ( ) ? findActualTypeByGenericsPlaceholderName ( originalParameterType . getUnresolvedName ( ) , map ) : originalParameterType ; } ) . toArray ( ClassNode [ ] :: new ) ; ClassNode originalReturnType = methodNode . getReturnType ( ) ; ClassNode returnType = originalReturnType . isGenericsPlaceHolder ( ) ? findActualTypeByGenericsPlaceholderName ( originalReturnType . getUnresolvedName ( ) , map ) : originalReturnType ; return tuple ( parameterTypes , returnType ) ; }
Get the parameter and return types of the abstract method of SAM
6,852
public static ClassNode findActualTypeByGenericsPlaceholderName ( String placeholderName , Map < GenericsType , GenericsType > genericsPlaceholderAndTypeMap ) { for ( Map . Entry < GenericsType , GenericsType > entry : genericsPlaceholderAndTypeMap . entrySet ( ) ) { GenericsType declaringGenericsType = entry . getKey ( ) ; if ( placeholderName . equals ( declaringGenericsType . getName ( ) ) ) { return entry . getValue ( ) . getType ( ) . redirect ( ) ; } } return null ; }
Get the actual type according to the placeholder name
6,853
protected static MethodHandle addTransformer ( MethodHandle handle , int pos , Object arg , Class parameter ) { MethodHandle transformer = null ; if ( arg instanceof GString ) { transformer = TO_STRING ; } else if ( arg instanceof Closure ) { transformer = createSAMTransform ( arg , parameter ) ; } else if ( Number . class . isAssignableFrom ( parameter ) ) { transformer = selectNumberTransformer ( parameter , arg ) ; } else if ( parameter . isArray ( ) ) { transformer = MethodHandles . insertArguments ( AS_ARRAY , 1 , parameter ) ; } if ( transformer == null ) throw new GroovyBugError ( "Unknown transformation for argument " + arg + " at position " + pos + " with " + arg . getClass ( ) + " for parameter of type " + parameter ) ; return applyUnsharpFilter ( handle , pos , transformer ) ; }
Adds a type transformer applied at runtime . This method handles transformations to String from GString array transformations and number based transformations
6,854
private static MethodHandle createSAMTransform ( Object arg , Class parameter ) { Method method = CachedSAMClass . getSAMMethod ( parameter ) ; if ( method == null ) return null ; if ( parameter . isInterface ( ) ) { if ( Traits . isTrait ( parameter ) ) { MethodHandle ret = TO_SAMTRAIT_PROXY ; ret = MethodHandles . insertArguments ( ret , 2 , ProxyGenerator . INSTANCE , Collections . singletonList ( parameter ) ) ; ret = MethodHandles . insertArguments ( ret , 0 , method . getName ( ) ) ; return ret ; } MethodHandle ret = TO_REFLECTIVE_PROXY ; ret = MethodHandles . insertArguments ( ret , 1 , method . getName ( ) , arg . getClass ( ) . getClassLoader ( ) , new Class [ ] { parameter } ) ; return ret ; } else { MethodHandle ret = TO_GENERATED_PROXY ; ret = MethodHandles . insertArguments ( ret , 2 , ProxyGenerator . INSTANCE , parameter ) ; ret = MethodHandles . insertArguments ( ret , 0 , method . getName ( ) ) ; return ret ; } }
creates a method handle able to transform the given Closure into a SAM type if the given parameter is a SAM type
6,855
private static MethodHandle selectNumberTransformer ( Class param , Object arg ) { param = TypeHelper . getWrapperClass ( param ) ; if ( param == Byte . class ) { return TO_BYTE ; } else if ( param == Character . class || param == Integer . class ) { return TO_INT ; } else if ( param == Long . class ) { return TO_LONG ; } else if ( param == Float . class ) { return TO_FLOAT ; } else if ( param == Double . class ) { return TO_DOUBLE ; } else if ( param == BigInteger . class ) { return TO_BIG_INT ; } else if ( param == BigDecimal . class ) { if ( arg instanceof Double ) { return DOUBLE_TO_BIG_DEC ; } else if ( arg instanceof Long ) { return LONG_TO_BIG_DEC ; } else if ( arg instanceof BigInteger ) { return BIG_INT_TO_BIG_DEC ; } else { return DOUBLE_TO_BIG_DEC_WITH_CONVERSION ; } } else if ( param == Short . class ) { return TO_SHORT ; } else { return null ; } }
returns a transformer later applied as filter to transform one number into another
6,856
public static Iterator < Node > iterator ( final NodeList nodeList ) { return new Iterator < Node > ( ) { private int current ; public boolean hasNext ( ) { return current < nodeList . getLength ( ) ; } public Node next ( ) { return nodeList . item ( current ++ ) ; } public void remove ( ) { throw new UnsupportedOperationException ( "Cannot remove() from a NodeList iterator" ) ; } } ; }
Makes NodeList iterable by returning a read - only Iterator which traverses over each Node .
6,857
private boolean setField ( PropertyExpression expression , Expression objectExpression , ClassNode rType , String name ) { if ( expression . isSafe ( ) ) return false ; FieldNode fn = AsmClassGenerator . getDeclaredFieldOfCurrentClassOrAccessibleFieldOfSuper ( controller . getClassNode ( ) , rType , name , false ) ; if ( fn == null ) return false ; OperandStack stack = controller . getOperandStack ( ) ; stack . doGroovyCast ( fn . getType ( ) ) ; MethodVisitor mv = controller . getMethodVisitor ( ) ; String ownerName = BytecodeHelper . getClassInternalName ( fn . getOwner ( ) ) ; if ( ! fn . isStatic ( ) ) { controller . getCompileStack ( ) . pushLHS ( false ) ; objectExpression . visit ( controller . getAcg ( ) ) ; controller . getCompileStack ( ) . popLHS ( ) ; if ( ! rType . equals ( stack . getTopOperand ( ) ) ) { BytecodeHelper . doCast ( mv , rType ) ; stack . replace ( rType ) ; } stack . swap ( ) ; mv . visitFieldInsn ( PUTFIELD , ownerName , name , BytecodeHelper . getTypeDescription ( fn . getType ( ) ) ) ; stack . remove ( 1 ) ; } else { mv . visitFieldInsn ( PUTSTATIC , ownerName , name , BytecodeHelper . getTypeDescription ( fn . getType ( ) ) ) ; } return true ; }
this is just a simple set field handling static and non - static but not Closure and inner classes
6,858
public void add ( T value ) { Element < T > e = new Element < T > ( value ) ; queue . offer ( e ) ; }
Adds the specified value to the queue .
6,859
public List < T > values ( ) { List < T > result = new ArrayList < T > ( ) ; for ( Iterator < T > itr = iterator ( ) ; itr . hasNext ( ) ; ) { result . add ( itr . next ( ) ) ; } return result ; }
Returns a list containing all values from this queue in the sequence they were added .
6,860
protected boolean writeBitwiseOp ( int type , boolean simulate ) { type = type - BITWISE_OR ; if ( type < 0 || type > 2 ) return false ; if ( ! simulate ) { int bytecode = getBitwiseOperationBytecode ( type ) ; controller . getMethodVisitor ( ) . visitInsn ( bytecode ) ; controller . getOperandStack ( ) . replace ( getNormalOpResultType ( ) , 2 ) ; } return true ; }
writes some the bitwise operations . type is one of BITWISE_OR BITWISE_AND BITWISE_XOR
6,861
protected boolean writeShiftOp ( int type , boolean simulate ) { type = type - LEFT_SHIFT ; if ( type < 0 || type > 2 ) return false ; if ( ! simulate ) { int bytecode = getShiftOperationBytecode ( type ) ; controller . getMethodVisitor ( ) . visitInsn ( bytecode ) ; controller . getOperandStack ( ) . replace ( getNormalOpResultType ( ) , 2 ) ; } return true ; }
Write shifting operations . Type is one of LEFT_SHIFT RIGHT_SHIFT or RIGHT_SHIFT_UNSIGNED
6,862
public void handleNotification ( Notification notification , Object handback ) { Map event = ( Map ) handback ; if ( event != null ) { Object del = event . get ( "managedObject" ) ; Object callback = event . get ( "callback" ) ; if ( callback != null && callback instanceof Closure ) { Closure closure = ( Closure ) callback ; closure . setDelegate ( del ) ; if ( closure . getMaximumNumberOfParameters ( ) == 1 ) closure . call ( buildOperationNotificationPacket ( notification ) ) ; else closure . call ( ) ; } } }
This is the implemented method for NotificationListener . It is called by an event emitter to dispatch JMX events to listeners . Here it handles internal JmxBuilder events .
6,863
private AnnotationNode visitAnnotation ( AnnotationNode unvisited ) { ErrorCollector errorCollector = new ErrorCollector ( this . source . getConfiguration ( ) ) ; AnnotationVisitor visitor = new AnnotationVisitor ( this . source , errorCollector ) ; AnnotationNode visited = visitor . visit ( unvisited ) ; this . source . getErrorCollector ( ) . addCollectorContents ( errorCollector ) ; return visited ; }
Resolve metadata and details of the annotation .
6,864
public void setClasspath ( String classpath ) { this . classpath = new LinkedList < String > ( ) ; StringTokenizer tokenizer = new StringTokenizer ( classpath , File . pathSeparator ) ; while ( tokenizer . hasMoreTokens ( ) ) { this . classpath . add ( tokenizer . nextToken ( ) ) ; } }
Sets the classpath .
6,865
public void setOptimizationOptions ( Map < String , Boolean > options ) { if ( options == null ) throw new IllegalArgumentException ( "provided option map must not be null" ) ; optimizationOptions = options ; }
Sets the optimization options for this configuration . No entry or a true for that entry means to enable that optimization a false means the optimization is disabled . Valid keys are all and int .
6,866
public CompilerConfiguration addCompilationCustomizers ( CompilationCustomizer ... customizers ) { if ( customizers == null ) throw new IllegalArgumentException ( "provided customizers list must not be null" ) ; compilationCustomizers . addAll ( Arrays . asList ( customizers ) ) ; return this ; }
Adds compilation customizers to the compilation process . A compilation customizer is a class node operation which performs various operations going from adding imports to access control .
6,867
public boolean isIndyEnabled ( ) { Boolean indyEnabled = this . getOptimizationOptions ( ) . get ( INVOKEDYNAMIC ) ; if ( null == indyEnabled ) { return false ; } return indyEnabled ; }
Check whether invoke dynamic enabled
6,868
public boolean isGroovydocEnabled ( ) { Boolean groovydocEnabled = this . getOptimizationOptions ( ) . get ( GROOVYDOC ) ; if ( null == groovydocEnabled ) { return false ; } return groovydocEnabled ; }
Check whether groovydoc enabled
6,869
public boolean isRuntimeGroovydocEnabled ( ) { Boolean runtimeGroovydocEnabled = this . getOptimizationOptions ( ) . get ( RUNTIME_GROOVYDOC ) ; if ( null == runtimeGroovydocEnabled ) { return false ; } return runtimeGroovydocEnabled ; }
Check whether runtime groovydoc enabled
6,870
public boolean isMemStubEnabled ( ) { Object memStubEnabled = this . getJointCompilationOptions ( ) . get ( MEM_STUB ) ; if ( null == memStubEnabled ) { return false ; } return "true" . equals ( memStubEnabled . toString ( ) ) ; }
Check whether mem stub enabled
6,871
public void cleanUpNullReferences ( ) { synchronized ( map ) { final Iterator < Map . Entry < K , V > > iterator = map . entrySet ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { final Map . Entry < K , V > entry = iterator . next ( ) ; final Object value = entry . getValue ( ) ; if ( ! ( value instanceof SoftReference ) ) continue ; if ( ( ( SoftReference ) value ) . get ( ) == null ) iterator . remove ( ) ; } } }
Remove all entries holding SoftReferences to gc - evicted objects .
6,872
public Object apply ( String source , int lineNo , int columnNo , Object funcBody , Vector paramNames , Vector arguments ) throws BSFException { Object object = eval ( source , lineNo , columnNo , funcBody ) ; if ( object instanceof Closure ) { Closure closure = ( Closure ) object ; return closure . call ( arguments . toArray ( ) ) ; } return object ; }
Allow an anonymous function to be declared and invoked
6,873
public Object call ( Object object , String method , Object [ ] args ) throws BSFException { return InvokerHelper . invokeMethod ( object , method , args ) ; }
Call the named method of the given object .
6,874
public void declareBean ( BSFDeclaredBean bean ) throws BSFException { shell . setVariable ( bean . name , bean . bean ) ; }
Declare a bean
6,875
private static ConstructorNode getMatchingConstructor ( List < ConstructorNode > constructors , List < Expression > argumentList ) { ConstructorNode lastMatch = null ; for ( int i = 0 ; i < constructors . size ( ) ; i ++ ) { ConstructorNode cn = constructors . get ( i ) ; Parameter [ ] params = cn . getParameters ( ) ; if ( argumentList . size ( ) != params . length ) continue ; if ( lastMatch == null ) { lastMatch = cn ; } else { return null ; } } return lastMatch ; }
we match only on the number of arguments not anything else
6,876
public static Number plus ( Number left , Number right ) { return NumberMath . add ( left , right ) ; }
Add two numbers and return the result .
6,877
protected void checkType ( Object object ) { if ( object == null ) { throw new NullPointerException ( "Sequences cannot contain null, use a List instead" ) ; } if ( type != null ) { if ( ! type . isInstance ( object ) ) { throw new IllegalArgumentException ( "Invalid type of argument for sequence of type: " + type . getName ( ) + " cannot add object: " + object ) ; } } }
Checks that the given object instance is of the correct type otherwise a runtime exception is thrown
6,878
public void visitType ( GroovySourceAST t , int visit ) { GroovySourceAST parent = getParentNode ( ) ; GroovySourceAST modifiers = parent . childOfType ( GroovyTokenTypes . MODIFIERS ) ; if ( modifiers == null || modifiers . getNumberOfChildren ( ) == 0 ) { if ( visit == OPENING_VISIT ) { if ( t . getNumberOfChildren ( ) == 0 && parent . getType ( ) != GroovyTokenTypes . PARAMETER_DEF ) { print ( t , visit , "def" ) ; } } if ( visit == CLOSING_VISIT ) { if ( parent . getType ( ) == GroovyTokenTypes . VARIABLE_DEF || parent . getType ( ) == GroovyTokenTypes . METHOD_DEF || parent . getType ( ) == GroovyTokenTypes . ANNOTATION_FIELD_DEF || ( parent . getType ( ) == GroovyTokenTypes . PARAMETER_DEF && t . getNumberOfChildren ( ) != 0 ) ) { print ( t , visit , " " ) ; } } } else { if ( visit == CLOSING_VISIT ) { if ( t . getNumberOfChildren ( ) != 0 ) { print ( t , visit , " " ) ; } } } }
visit TripleDot not used in the AST
6,879
public void visitDefault ( GroovySourceAST t , int visit ) { if ( visit == OPENING_VISIT ) { print ( t , visit , "<" + tokenNames [ t . getType ( ) ] + ">" ) ; } else { print ( t , visit , "</" + tokenNames [ t . getType ( ) ] + ">" ) ; } }
visit WS - only used by lexer
6,880
private static Object [ ] fitToVargs ( Object [ ] argumentArrayOrig , CachedClass [ ] paramTypes ) { Class vargsClassOrig = paramTypes [ paramTypes . length - 1 ] . getTheClass ( ) . getComponentType ( ) ; Class vargsClass = ReflectionCache . autoboxType ( vargsClassOrig ) ; Object [ ] argumentArray = argumentArrayOrig . clone ( ) ; MetaClassHelper . unwrap ( argumentArray ) ; if ( argumentArray . length == paramTypes . length - 1 ) { Object [ ] newArgs = new Object [ paramTypes . length ] ; System . arraycopy ( argumentArray , 0 , newArgs , 0 , argumentArray . length ) ; Object vargs = Array . newInstance ( vargsClass , 0 ) ; newArgs [ newArgs . length - 1 ] = vargs ; return newArgs ; } else if ( argumentArray . length == paramTypes . length ) { Object lastArgument = argumentArray [ argumentArray . length - 1 ] ; if ( lastArgument != null && ! lastArgument . getClass ( ) . isArray ( ) ) { Object wrapped = makeCommonArray ( argumentArray , paramTypes . length - 1 , vargsClass ) ; Object [ ] newArgs = new Object [ paramTypes . length ] ; System . arraycopy ( argumentArray , 0 , newArgs , 0 , paramTypes . length - 1 ) ; newArgs [ newArgs . length - 1 ] = wrapped ; return newArgs ; } else { return argumentArray ; } } else if ( argumentArray . length > paramTypes . length ) { Object [ ] newArgs = new Object [ paramTypes . length ] ; System . arraycopy ( argumentArray , 0 , newArgs , 0 , paramTypes . length - 1 ) ; Object vargs = makeCommonArray ( argumentArray , paramTypes . length - 1 , vargsClass ) ; newArgs [ newArgs . length - 1 ] = vargs ; return newArgs ; } else { throw new GroovyBugError ( "trying to call a vargs method without enough arguments" ) ; } }
this method is called when the number of arguments to a method is greater than 1 and if the method is a vargs method . This method will then transform the given arguments to make the method callable
6,881
private void checkPropertyOnExplicitThis ( PropertyExpression pe ) { if ( ! currentScope . isInStaticContext ( ) ) return ; Expression object = pe . getObjectExpression ( ) ; if ( ! ( object instanceof VariableExpression ) ) return ; VariableExpression ve = ( VariableExpression ) object ; if ( ! ve . getName ( ) . equals ( "this" ) ) return ; String name = pe . getPropertyAsString ( ) ; if ( name == null || name . equals ( "class" ) ) return ; Variable member = findClassMember ( currentClass , name ) ; if ( member == null ) return ; checkVariableContextAccess ( member , pe ) ; }
a property on this like this . x is transformed to a direct field access so we need to check the static context here
6,882
private void fixVar ( Variable var ) { if ( getTarget ( var ) == null && var instanceof VariableExpression && getState ( ) != null && var . getName ( ) != null ) { for ( Variable v : getState ( ) . keySet ( ) ) { if ( var . getName ( ) . equals ( v . getName ( ) ) ) { ( ( VariableExpression ) var ) . setAccessedVariable ( v ) ; break ; } } } }
This fixes xform declaration expressions but not other synthetic fields which aren t set up correctly
6,883
protected void nodeCompleted ( final Object parent , final Object node ) { if ( parent == null ) insideTask = false ; antElementHandler . onEndElement ( null , null , antXmlContext ) ; lastCompletedNode = node ; if ( parent != null && ! ( parent instanceof Target ) ) { log . finest ( "parent is not null: no perform on nodeCompleted" ) ; return ; } if ( definingTarget != null && definingTarget == parent && node instanceof Task ) return ; if ( definingTarget == node ) { definingTarget = null ; } if ( node instanceof Task ) { Task task = ( Task ) node ; final String taskName = task . getTaskName ( ) ; if ( "antcall" . equals ( taskName ) && parent == null ) { throw new BuildException ( "antcall not supported within AntBuilder, consider using 'ant.project.executeTarget('targetName')' instead." ) ; } if ( saveStreams ) { synchronized ( AntBuilder . class ) { int currentStreamCount = streamCount ++ ; if ( currentStreamCount == 0 ) { savedProjectInputStream = project . getDefaultInputStream ( ) ; savedIn = System . in ; savedErr = System . err ; savedOut = System . out ; if ( ! ( savedIn instanceof DemuxInputStream ) ) { project . setDefaultInputStream ( savedIn ) ; demuxInputStream = new DemuxInputStream ( project ) ; System . setIn ( demuxInputStream ) ; } demuxOutputStream = new DemuxOutputStream ( project , false ) ; System . setOut ( new PrintStream ( demuxOutputStream ) ) ; demuxErrorStream = new DemuxOutputStream ( project , true ) ; System . setErr ( new PrintStream ( demuxErrorStream ) ) ; } } } try { lastCompletedNode = performTask ( task ) ; } finally { if ( saveStreams ) { synchronized ( AntBuilder . class ) { int currentStreamCount = -- streamCount ; if ( currentStreamCount == 0 ) { project . setDefaultInputStream ( savedProjectInputStream ) ; System . setOut ( savedOut ) ; System . setErr ( savedErr ) ; if ( demuxInputStream != null ) { System . setIn ( savedIn ) ; DefaultGroovyMethodsSupport . closeQuietly ( demuxInputStream ) ; demuxInputStream = null ; } DefaultGroovyMethodsSupport . closeQuietly ( demuxOutputStream ) ; DefaultGroovyMethodsSupport . closeQuietly ( demuxErrorStream ) ; demuxOutputStream = null ; demuxErrorStream = null ; } } } } if ( "import" . equals ( taskName ) ) { antXmlContext . setCurrentTarget ( collectorTarget ) ; } } else if ( node instanceof Target ) { antXmlContext . setCurrentTarget ( collectorTarget ) ; } else { final RuntimeConfigurable r = ( RuntimeConfigurable ) node ; r . maybeConfigure ( project ) ; } }
Determines when the ANT Task that is represented by the node should perform . Node must be an ANT Task or no perform is called . If node is an ANT Task it performs right after complete construction . If node is nested in a TaskContainer calling perform is delegated to that TaskContainer .
6,884
private Object performTask ( Task task ) { Throwable reason = null ; try { final Method fireTaskStarted = Project . class . getDeclaredMethod ( "fireTaskStarted" , Task . class ) ; fireTaskStarted . setAccessible ( true ) ; fireTaskStarted . invoke ( project , task ) ; Object realThing ; realThing = task ; task . maybeConfigure ( ) ; if ( task instanceof UnknownElement ) { realThing = ( ( UnknownElement ) task ) . getRealThing ( ) ; } DispatchUtils . execute ( task ) ; return realThing != null ? realThing : task ; } catch ( BuildException ex ) { if ( ex . getLocation ( ) == Location . UNKNOWN_LOCATION ) { ex . setLocation ( task . getLocation ( ) ) ; } reason = ex ; throw ex ; } catch ( Exception ex ) { reason = ex ; BuildException be = new BuildException ( ex ) ; be . setLocation ( task . getLocation ( ) ) ; throw be ; } catch ( Error ex ) { reason = ex ; throw ex ; } finally { try { final Method fireTaskFinished = Project . class . getDeclaredMethod ( "fireTaskFinished" , Task . class , Throwable . class ) ; fireTaskFinished . setAccessible ( true ) ; fireTaskFinished . invoke ( project , task , reason ) ; } catch ( Exception e ) { BuildException be = new BuildException ( e ) ; be . setLocation ( task . getLocation ( ) ) ; throw be ; } } }
Copied from org . apache . tools . ant . Task since we need to get a real thing before it gets nulled in DispatchUtils . execute
6,885
public String getSnippet ( LineColumn start , LineColumn end ) { if ( start == null || end == null ) { return null ; } if ( start . equals ( end ) ) { return null ; } if ( lines . size ( ) == 1 && current . length ( ) == 0 ) { return null ; } int startLine = start . getLine ( ) ; int startColumn = start . getColumn ( ) ; int endLine = end . getLine ( ) ; int endColumn = end . getColumn ( ) ; if ( startLine < 1 ) { startLine = 1 ; } if ( endLine < 1 ) { endLine = 1 ; } if ( startColumn < 1 ) { startColumn = 1 ; } if ( endColumn < 1 ) { endColumn = 1 ; } if ( startLine > lines . size ( ) ) { startLine = lines . size ( ) ; } if ( endLine > lines . size ( ) ) { endLine = lines . size ( ) ; } StringBuilder snippet = new StringBuilder ( ) ; for ( int i = startLine - 1 ; i < endLine ; i ++ ) { String line = ( ( StringBuilder ) lines . get ( i ) ) . toString ( ) ; if ( startLine == endLine ) { if ( startColumn > line . length ( ) ) { startColumn = line . length ( ) ; } if ( startColumn < 1 ) { startColumn = 1 ; } if ( endColumn > line . length ( ) ) { endColumn = line . length ( ) + 1 ; } if ( endColumn < 1 ) { endColumn = 1 ; } if ( endColumn < startColumn ) { endColumn = startColumn ; } line = line . substring ( startColumn - 1 , endColumn - 1 ) ; } else { if ( i == startLine - 1 ) { if ( startColumn - 1 < line . length ( ) ) { line = line . substring ( startColumn - 1 ) ; } } if ( i == endLine - 1 ) { if ( endColumn - 1 < line . length ( ) ) { line = line . substring ( 0 , endColumn - 1 ) ; } } } snippet . append ( line ) ; } return snippet . toString ( ) ; }
Obtains a snippet of the source code within the bounds specified
6,886
static Throwable tryClose ( AutoCloseable closeable , boolean logWarning ) { Throwable thrown = null ; if ( closeable != null ) { try { closeable . close ( ) ; } catch ( Exception e ) { thrown = e ; if ( logWarning ) { LOG . warning ( "Caught exception during close(): " + e ) ; } } } return thrown ; }
Attempts to close the closeable returning rather than throwing any Exception that may occur .
6,887
@ SuppressWarnings ( "unchecked" ) protected static boolean sameType ( Collection [ ] cols ) { List all = new LinkedList ( ) ; for ( Collection col : cols ) { all . addAll ( col ) ; } if ( all . isEmpty ( ) ) return true ; Object first = all . get ( 0 ) ; Class baseClass ; if ( first instanceof Number ) { baseClass = Number . class ; } else if ( first == null ) { baseClass = NullObject . class ; } else { baseClass = first . getClass ( ) ; } for ( Collection col : cols ) { for ( Object o : col ) { if ( ! baseClass . isInstance ( o ) ) { return false ; } } } return true ; }
Determines if all items of this array are of the same type .
6,888
private static TemporalUnit defaultUnitFor ( Temporal temporal ) { return DEFAULT_UNITS . entrySet ( ) . stream ( ) . filter ( e -> e . getKey ( ) . isAssignableFrom ( temporal . getClass ( ) ) ) . findFirst ( ) . map ( Map . Entry :: getValue ) . orElse ( ChronoUnit . SECONDS ) ; }
A number of extension methods permit a long or int to be provided as a parameter . This method determines what the unit should be for this number .
6,889
public static void negateBoolean ( MethodVisitor mv ) { Label endLabel = new Label ( ) ; Label falseLabel = new Label ( ) ; mv . visitJumpInsn ( IFNE , falseLabel ) ; mv . visitInsn ( ICONST_1 ) ; mv . visitJumpInsn ( GOTO , endLabel ) ; mv . visitLabel ( falseLabel ) ; mv . visitInsn ( ICONST_0 ) ; mv . visitLabel ( endLabel ) ; }
Negate a boolean on stack .
6,890
public static void unbox ( MethodVisitor mv , Class type ) { if ( type . isPrimitive ( ) && type != Void . TYPE ) { String returnString = "(Ljava/lang/Object;)" + BytecodeHelper . getTypeDescription ( type ) ; mv . visitMethodInsn ( INVOKESTATIC , DTT_CLASSNAME , type . getName ( ) + "Unbox" , returnString , false ) ; } }
Generates the bytecode to unbox the current value on the stack
6,891
public static boolean box ( MethodVisitor mv , ClassNode type ) { if ( type . isPrimaryClassNode ( ) ) return false ; return box ( mv , type . getTypeClass ( ) ) ; }
box top level operand
6,892
public static boolean box ( MethodVisitor mv , Class type ) { if ( ReflectionCache . getCachedClass ( type ) . isPrimitive && type != void . class ) { String returnString = "(" + BytecodeHelper . getTypeDescription ( type ) + ")Ljava/lang/Object;" ; mv . visitMethodInsn ( INVOKESTATIC , DTT_CLASSNAME , "box" , returnString , false ) ; return true ; } return false ; }
Generates the bytecode to autobox the current value on the stack
6,893
public static void visitClassLiteral ( MethodVisitor mv , ClassNode classNode ) { if ( ClassHelper . isPrimitiveType ( classNode ) ) { mv . visitFieldInsn ( GETSTATIC , getClassInternalName ( ClassHelper . getWrapper ( classNode ) ) , "TYPE" , "Ljava/lang/Class;" ) ; } else { mv . visitLdcInsn ( org . objectweb . asm . Type . getType ( getTypeDescription ( classNode ) ) ) ; } }
Visits a class literal . If the type of the classnode is a primitive type the generated bytecode will be a GETSTATIC Integer . TYPE . If the classnode is not a primitive type we will generate a LDC instruction .
6,894
public static boolean isSameCompilationUnit ( ClassNode a , ClassNode b ) { CompileUnit cu1 = a . getCompileUnit ( ) ; CompileUnit cu2 = b . getCompileUnit ( ) ; return cu1 != null && cu1 == cu2 ; }
Returns true if the two classes share the same compilation unit .
6,895
public static void convertPrimitiveToBoolean ( MethodVisitor mv , ClassNode type ) { if ( type == boolean_TYPE ) { return ; } if ( type == double_TYPE ) { convertDoubleToBoolean ( mv ) ; return ; } else if ( type == float_TYPE ) { convertFloatToBoolean ( mv ) ; return ; } Label trueLabel = new Label ( ) ; Label falseLabel = new Label ( ) ; if ( type == long_TYPE ) { mv . visitInsn ( LCONST_0 ) ; mv . visitInsn ( LCMP ) ; } mv . visitJumpInsn ( IFEQ , falseLabel ) ; mv . visitInsn ( ICONST_1 ) ; mv . visitJumpInsn ( GOTO , trueLabel ) ; mv . visitLabel ( falseLabel ) ; mv . visitInsn ( ICONST_0 ) ; mv . visitLabel ( trueLabel ) ; }
Converts a primitive type to boolean .
6,896
public static List < PropertyNode > getAllProperties ( ClassNode type , boolean includeSuperProperties , boolean includeStatic , boolean includePseudoGetters ) { return getAllProperties ( type , includeSuperProperties , includeStatic , includePseudoGetters , false , false ) ; }
Get all properties including JavaBean pseudo properties matching getter conventions .
6,897
public static List < PropertyNode > getAllProperties ( ClassNode type , boolean includeSuperProperties , boolean includeStatic , boolean includePseudoGetters , boolean includePseudoSetters , boolean superFirst ) { return getAllProperties ( type , type , new HashSet < String > ( ) , includeSuperProperties , includeStatic , includePseudoGetters , includePseudoSetters , superFirst ) ; }
Get all properties including JavaBean pseudo properties matching JavaBean getter or setter conventions .
6,898
public void handle ( ASTNode node , GroovyParser . GroovyParserRuleContext ctx ) { if ( ! ( groovydocEnabled || runtimeGroovydocEnabled ) ) { return ; } if ( ! asBoolean ( node ) || ! asBoolean ( ctx ) ) { return ; } String docCommentNodeText = this . findDocCommentByNode ( ctx ) ; if ( null == docCommentNodeText ) { return ; } attachDocCommentAsMetaData ( node , docCommentNodeText ) ; attachGroovydocAnnotation ( node , docCommentNodeText ) ; }
Attach doc comment to member node as meta data
6,899
protected Class findClass ( String name ) throws ClassNotFoundException { if ( delegatationLoader == null ) return super . findClass ( name ) ; return delegatationLoader . loadClass ( name ) ; }
Tries to find a Groovy class .