idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
40,700
public Font getFont ( int code ) { Style s = _tokenStyles . get ( new Integer ( code ) ) ; if ( s == null ) { s = getStyle ( DEFAULT_STYLE ) ; } return getFont ( s ) ; }
Fetch the font to use for a lexical token with the given scan value .
40,701
public Style getStyleForScanValue ( int code ) { Style s = _tokenStyles . get ( new Integer ( code ) ) ; if ( s == null ) { s = getStyle ( DEFAULT_STYLE ) ; } return s ; }
Fetches the attribute set to use for the given scan code . The set is stored in a table to facilitate relatively fast access to use in conjunction with the scanner .
40,702
public Font getFont ( AttributeSet attr ) { boolean bUnderline = StyleConstants . isUnderline ( attr ) ; boolean bStrikethrough = StyleConstants . isStrikeThrough ( attr ) ; if ( ! bUnderline && ! bStrikethrough ) { return getFont ( attr , getFontFamily ( attr ) ) ; } Map < TextAttribute , Object > map = new HashMap < TextAttribute , Object > ( ) ; map . put ( TextAttribute . FAMILY , getFontFamily ( attr ) ) ; map . put ( TextAttribute . SIZE , ( float ) getFontSize ( ) ) ; map . put ( TextAttribute . WEIGHT , StyleConstants . isBold ( attr ) ? TextAttribute . WEIGHT_BOLD : TextAttribute . WEIGHT_REGULAR ) ; map . put ( TextAttribute . POSTURE , StyleConstants . isItalic ( attr ) ? TextAttribute . POSTURE_OBLIQUE : TextAttribute . POSTURE_REGULAR ) ; if ( bUnderline ) { map . put ( TextAttribute . UNDERLINE , TextAttribute . UNDERLINE_ON ) ; if ( attr . getAttribute ( DASHED ) != null ) { map . put ( TextAttribute . UNDERLINE , TextAttribute . UNDERLINE_LOW_GRAY ) ; } } if ( bStrikethrough ) { map . put ( TextAttribute . STRIKETHROUGH , TextAttribute . STRIKETHROUGH_ON ) ; } Font font = _fontCache . get ( attr ) ; if ( font == null ) { font = new Font ( map ) ; _fontCache . put ( attr , font ) ; } return font ; }
Fetch the font to use for a given attribute set .
40,703
public static GosuPathEntry createPathEntryForModuleFile ( IFile moduleFile ) { try { InputStream is = moduleFile . openInputStream ( ) ; try { SimpleXmlNode moduleNode = SimpleXmlNode . parse ( is ) ; IDirectory rootDir = moduleFile . getParent ( ) ; List < IDirectory > sourceDirs = new ArrayList < IDirectory > ( ) ; for ( String child : new String [ ] { "gsrc" , "gtest" } ) { IDirectory dir = rootDir . dir ( child ) ; if ( dir . exists ( ) ) { sourceDirs . add ( dir ) ; } } return new GosuPathEntry ( rootDir , sourceDirs ) ; } finally { is . close ( ) ; } } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }
Reads a pom . xml file into a GosuPathEntry object
40,704
private static int minLen ( String ... patterns ) { int minLen = patterns [ 0 ] . length ( ) ; for ( String str : patterns ) { if ( str . length ( ) < minLen ) { minLen = str . length ( ) ; } } return minLen ; }
Find the shortest of all patterns .
40,705
private int rollHash ( int hashvalue , String str , int i ) { char outchar = str . charAt ( str . length ( ) - 1 - i ) ; char inchar = str . charAt ( str . length ( ) - _block - 1 - i ) ; hashvalue = A * hashvalue + CHAR_HASHES [ inchar ] - _Apowblock * CHAR_HASHES [ outchar ] ; return hashvalue ; }
Update rolling hash values .
40,706
private int reverseHash ( String str ) { int hash = 0 ; int len = str . length ( ) ; for ( int i = 0 ; i < _block ; i ++ ) { char c = str . charAt ( len - i - 1 ) ; hash = A * hash + CHAR_HASHES [ c ] ; } return hash ; }
Take rolling hash of last block characters . Start from the end of the string .
40,707
public void insertString ( int offset , String str , AttributeSet a ) throws BadLocationException { switch ( str ) { case "(" : str = addParenthesis ( ) ; break ; case "\n" : str = addWhiteSpace ( offset ) ; break ; case "\"" : str = addMatchingQuotationMark ( ) ; break ; case "{" : str = addMatchingBrace ( offset ) ; break ; } super . insertString ( offset , str , a ) ; processChangedLines ( offset , str . length ( ) ) ; }
Override to apply syntax highlighting after the document has been updated
40,708
public void stopWatching ( ) { try { _watchService . close ( ) ; _watchService = null ; _watchedDirectories = null ; } catch ( IOException e ) { throw new RuntimeException ( "Could not stop watching directories!" , e ) ; } }
Close the watch service . Releases resources . After calling this instance becomes invalid and can t be used any more .
40,709
public void watchDirectoryTree ( Path dir ) { if ( _watchedDirectories == null ) { throw new IllegalStateException ( "DirectoryWatcher.close() was called. Please make a new instance." ) ; } try { if ( Files . exists ( dir ) ) { Files . walkFileTree ( dir , new SimpleFileVisitor < Path > ( ) { public FileVisitResult preVisitDirectory ( Path dir , BasicFileAttributes attrs ) throws IOException { watchDirectory ( dir ) ; return FileVisitResult . CONTINUE ; } } ) ; } } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }
Walk the directories under given path and register a watcher for every directory .
40,710
public List getModelUpdatedOrFilteredByPredicate ( ) { List model = getModel ( ) ; if ( _filter != null ) { model = new ArrayList ( model ) ; for ( Iterator it = model . iterator ( ) ; it . hasNext ( ) ; ) { Object o = it . next ( ) ; if ( ! _filter . evaluate ( o ) ) { it . remove ( ) ; } } } return model ; }
Returns the underlying list filtered by the predicate if it exists
40,711
private Class getMapType ( ) { Class mapType = Map . class ; IParsedElement parent = getParsedElement ( ) . getParent ( ) ; if ( parent instanceof NewExpression ) { IType newType = ( ( NewExpression ) parent ) . getType ( ) ; IJavaClassInfo classInfo = IRTypeResolver . getJavaBackedClass ( newType ) ; Class javaBackedClass = classInfo != null ? classInfo . getBackingClass ( ) : null ; if ( classInfo != null && javaBackedClass != null ) { mapType = javaBackedClass ; } else if ( JavaTypes . getJreType ( AbstractMap . class ) . isAssignableFrom ( newType ) ) { mapType = AbstractMap . class ; } } return mapType ; }
Try to get a more specific class instead of using the Map interface i . e . invokevirtual is significantly faster then invokeinterface .
40,712
private Class getCollectionType ( ) { Class collectionType = Collection . class ; IParsedElement parent = getParsedElement ( ) . getParent ( ) ; if ( parent instanceof NewExpression ) { IType newType = ( ( NewExpression ) parent ) . getType ( ) ; IJavaClassInfo classInfo = IRTypeResolver . getJavaBackedClass ( newType ) ; Class javaBackedClass = classInfo != null ? classInfo . getBackingClass ( ) : null ; if ( classInfo != null && javaBackedClass != null ) { collectionType = javaBackedClass ; } else if ( JavaTypes . getJreType ( AbstractCollection . class ) . isAssignableFrom ( newType ) ) { collectionType = AbstractCollection . class ; } } return collectionType ; }
Try to get a more specific class instead of using the Collection interface i . e . invokevirtual is significantly faster then invokeinterface .
40,713
public static IRStatement compileInitializerAssignment ( TopLevelTransformationContext context , InitializerAssignment stmt , IRExpression root ) { return InitializerAssignmentTransformer . compile ( context , stmt , root ) ; }
This is in its own method because it requires additional context
40,714
public void setParent ( IParseTree l ) { if ( l != null && ! l . contains ( this ) && getLength ( ) > 0 ) { throw new IllegalArgumentException ( "Attempted set the parent location, but the parent location's area is not a superset of this location's area." ) ; } if ( _pe != null ) { ParsedElement parentElement = ( ParsedElement ) _pe . getParent ( ) ; if ( parentElement != null ) { ParseTree oldParent = parentElement . getLocation ( ) ; if ( oldParent != null ) { oldParent . _children . remove ( this ) ; } } _pe . setParent ( l == null ? null : ( ( ParseTree ) l ) . _pe ) ; } }
Sets the parent location . Note the parent location must cover a superset of the specified location s area .
40,715
public boolean areOffsetAndExtentEqual ( IParseTree location ) { return location != null && location . getOffset ( ) == getOffset ( ) && location . getExtent ( ) == getExtent ( ) ; }
Is just the physical location equal?
40,716
public IType getFeatureType ( ) { if ( _delegate . getFeatureType ( ) . isArray ( ) ) { return _delegate . getFeatureType ( ) ; } return _delegate . getFeatureType ( ) . getArrayType ( ) ; }
Make an array type from the delegate s type if it s not already an array . The idea with array expansion is to allow access to properties of X from an array of X . We call the accessor For each X in the array we call the
40,717
public static < E > StringBuffer join ( String glue , Collection < E > charSequences ) { StringBuffer buf = new StringBuffer ( ) ; int i = 0 ; for ( Object charSequence : charSequences ) { if ( i > 0 ) { buf . append ( glue ) ; } buf . append ( charSequence ) ; i ++ ; } return buf ; }
Takes a string glue and collection of CharSequences and returns a StringBuffer containing the CharSequences joined with the glue between each of them . They are joined in the order returned by the iterator of the colection
40,718
public static String escapeForJava ( String string ) { String result ; StringBuffer resultBuffer = null ; for ( int i = 0 , length = string . length ( ) ; i < length ; i ++ ) { char ch = string . charAt ( i ) ; String escape = escapeForJava ( ch ) ; if ( escape != null ) { if ( resultBuffer == null ) { resultBuffer = new StringBuffer ( string ) ; resultBuffer . setLength ( i ) ; } resultBuffer . append ( escape ) ; } else if ( resultBuffer != null ) { resultBuffer . append ( ch ) ; } } result = ( resultBuffer != null ) ? resultBuffer . toString ( ) : string ; return result ; }
Escape any special characters in the string using the Java escape syntax . For example any tabs become \ t newlines become \ n etc .
40,719
public static < Q > LockingLazyVar < Q > make ( final LazyVarInit < Q > init ) { return new LockingLazyVar < Q > ( ) { protected Q init ( ) { return init . init ( ) ; } } ; }
Creates a new LockingLazyVar based on the type of the LazyVarInit passed in . This method is intended to be called with blocks from Gosu .
40,720
private List < List < IType > > extractContextTypes ( List < ? extends IInvocableType > funcTypes ) { if ( funcTypes != null ) { ArrayList < List < IType > > returnList = new ArrayList < > ( ) ; for ( IInvocableType funcType : funcTypes ) { for ( int i = 0 ; i < funcType . getParameterTypes ( ) . length ; i ++ ) { IType paramType = funcType . getParameterTypes ( ) [ i ] ; if ( i >= returnList . size ( ) ) { returnList . add ( new ArrayList < > ( ) ) ; } List < IType > paramTypeList = returnList . get ( i ) ; if ( ! paramTypeList . contains ( paramType ) ) { paramTypeList . add ( paramType ) ; } } } return returnList ; } else { return Collections . emptyList ( ) ; } }
returns a list of lists of unique types at each argument position
40,721
private List < IFunctionSymbol > maybeAddPrivateFunctionsIfSuperInSamePackage ( String name , List < IFunctionSymbol > functions ) { ICompilableTypeInternal gsClass = getGosuClass ( ) ; if ( gsClass == null ) { return functions ; } IType supertype = gsClass . getSupertype ( ) ; if ( gsClass instanceof IGosuClass && supertype != null ) { if ( TypeLord . getOuterMostEnclosingClass ( supertype ) . getNamespace ( ) . equals ( TypeLord . getOuterMostEnclosingClass ( gsClass ) . getNamespace ( ) ) ) { functions = new ArrayList < > ( functions ) ; addAllNonstaticPrivateMethods ( name , ( ( IGosuClassInternal ) gsClass ) . getSuperClass ( ) , functions ) ; } } return functions ; }
the super class is in the same package as the subclass .
40,722
public IConstructorType getConstructorType ( IType classBean , Expression [ ] eArgs , List < IConstructorType > listAllMatchingMethods , ParserBase parserState ) throws ParseException { if ( classBean == null ) { throw new ParseException ( parserState == null ? null : parserState . makeFullParserState ( ) , Res . MSG_BEAN_CLASS_IS_NULL ) ; } if ( ErrorType . shouldHandleAsErrorType ( classBean ) ) { return ErrorType . getInstance ( ) . getErrorTypeConstructorType ( eArgs , listAllMatchingMethods ) ; } if ( classBean instanceof TypeVariableType ) { IType [ ] paramTypes = new IType [ eArgs == null ? 0 : eArgs . length ] ; for ( int i = 0 ; i < paramTypes . length ; i ++ ) { paramTypes [ i ] = eArgs [ i ] . getType ( ) ; } ConstructorType ctorType = new ConstructorType ( new DynamicConstructorInfo ( classBean . getTypeInfo ( ) , paramTypes ) ) ; if ( listAllMatchingMethods != null ) { listAllMatchingMethods . add ( ctorType ) ; } return ctorType ; } ITypeInfo typeInfo = classBean . getTypeInfo ( ) ; if ( typeInfo != null ) { List < ? extends IConstructorInfo > constructors ; if ( typeInfo instanceof IRelativeTypeInfo ) { while ( classBean instanceof ITypeVariableType ) { classBean = ( ( ITypeVariableType ) classBean ) . getBoundingType ( ) ; } constructors = ( ( IRelativeTypeInfo ) typeInfo ) . getConstructors ( classBean ) ; } else { constructors = typeInfo . getConstructors ( ) ; } for ( IConstructorInfo constructor : constructors ) { if ( typeInfo instanceof JavaTypeInfo ) { if ( constructor . isPrivate ( ) ) { continue ; } } IParameterInfo [ ] paramTypes = constructor . getParameters ( ) ; if ( eArgs == null || paramTypes . length == eArgs . length ) { if ( listAllMatchingMethods == null ) { return new ConstructorType ( constructor ) ; } listAllMatchingMethods . add ( new ConstructorType ( constructor ) ) ; } } if ( listAllMatchingMethods != null && listAllMatchingMethods . size ( ) > 0 ) { return listAllMatchingMethods . get ( 0 ) ; } } throw new NoCtorFoundException ( parserState == null ? null : parserState . makeFullParserState ( ) , TypeSystem . getUnqualifiedClassName ( classBean ) , eArgs == null ? 0 : eArgs . length ) ; }
Get the type of the method specified in the member path .
40,723
public Value evaluate ( Debugger debugger ) throws InvocationException { RuntimeState runtimeState = getRuntimeState ( debugger ) ; Location suspendedLoc = debugger . getSuspendedLocation ( ) ; VirtualMachine vm = suspendedLoc . virtualMachine ( ) ; ClassType classType = runtimeState . getCodeRunnerClass ( vm ) ; Value thisObject = findThisObjectFromCtx ( debugger . getSuspendedThread ( ) ) ; try { Value value = classType . invokeMethod ( debugger . getSuspendedThread ( ) , runtimeState . getRunMeSomeCodeMethod ( ) , Arrays . asList ( thisObject , suspendedLoc . declaringType ( ) . classLoader ( ) , makeExternalsSymbolsForLocals ( runtimeState , vm , debugger ) , vm . mirrorOf ( _strText ) , vm . mirrorOf ( _strClassContext ) , vm . mirrorOf ( _strContextElementClass ) , vm . mirrorOf ( _iContextLocation ) ) , 0 ) ; return unboxIfBoxed ( runtimeState , debugger . getSuspendedThread ( ) , value ) ; } catch ( Exception e ) { throw GosuExceptionUtil . forceThrow ( e ) ; } }
EvaluationContextImpl should be at the same stackFrame as it was in the call to EvaluatorBuilderImpl . build
40,724
public static List < String > getJreJars ( ) { String javaHome = System . getProperty ( "java.home" ) ; Path libsDir = FileSystems . getDefault ( ) . getPath ( javaHome , "/lib" ) ; List < String > retval = GosucUtil . getIbmClasspath ( ) ; try { retval . addAll ( Files . walk ( libsDir ) . filter ( path -> path . toFile ( ) . isFile ( ) ) . filter ( path -> path . toString ( ) . endsWith ( ".jar" ) ) . map ( Path :: toString ) . collect ( Collectors . toList ( ) ) ) ; } catch ( SecurityException | IOException e ) { e . printStackTrace ( ) ; throw new RuntimeException ( e ) ; } return retval ; }
Get all JARs from the lib directory of the System s java . home property
40,725
protected static List < String > getIbmClasspath ( ) { List < String > retval = new ArrayList < > ( ) ; if ( System . getProperty ( "java.vendor" ) . equals ( "IBM Corporation" ) ) { String fileSeparator = System . getProperty ( "file.separator" ) ; String classpathSeparator = System . getProperty ( "path.separator" ) ; String [ ] bootClasspath = System . getProperty ( "sun.boot.class.path" ) . split ( classpathSeparator ) ; for ( String entry : bootClasspath ) { if ( entry . endsWith ( fileSeparator + "vm.jar" ) ) { retval . add ( entry ) ; break ; } } } return retval ; }
Special handling for the unusual structure of the IBM JDK .
40,726
public void refresh ( Path file ) { EditorHost editor = findTab ( file ) ; if ( editor != null ) { try ( Reader reader = PathUtil . createReader ( file ) ) { editor . refresh ( StreamUtil . getContent ( reader ) ) ; setDirty ( editor , false ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } FileTree root = FileTreeUtil . getRoot ( ) ; FileTree node = root . find ( file ) ; if ( node != null ) { IType type = node . getType ( ) ; if ( type != null ) { reload ( type ) ; } } }
This should only be called when either the file s contents change externally or when the file saves to disk .
40,727
public static Expression getUnwrappedExpression ( Expression expression ) { while ( expression instanceof ImplicitTypeAsExpression ) { expression = ( ( ImplicitTypeAsExpression ) expression ) . getLHS ( ) ; } return expression ; }
If the expression is wrapped in ImplicitTypeAsExpressions this will will unwrap them back down to the original expression .
40,728
private boolean isReadObjectOrWriteObjectMethod ( Symbol symbol ) { if ( symbol instanceof DynamicFunctionSymbol ) { DynamicFunctionSymbol dfs = ( DynamicFunctionSymbol ) symbol ; if ( dfs . getDisplayName ( ) . equals ( "readObject" ) ) { IType [ ] argTypes = dfs . getArgTypes ( ) ; return argTypes != null && argTypes . length == 1 && argTypes [ 0 ] . equals ( JavaTypes . getJreType ( java . io . ObjectInputStream . class ) ) && dfs . getReturnType ( ) . equals ( JavaTypes . pVOID ( ) ) ; } else if ( dfs . getDisplayName ( ) . equals ( "writeObject" ) ) { IType [ ] argTypes = dfs . getArgTypes ( ) ; return argTypes != null && argTypes . length == 1 && argTypes [ 0 ] . equals ( JavaTypes . getJreType ( java . io . ObjectOutputStream . class ) ) && dfs . getReturnType ( ) . equals ( JavaTypes . pVOID ( ) ) ; } else { return false ; } } else { return false ; } }
Returns true if that is the case false otherwise
40,729
private boolean areTypeNamesEqual ( String name1 , String name2 ) { return name1 . replace ( '$' , '.' ) . equals ( name2 . replace ( '$' , '.' ) ) ; }
rather we just didn t care about the difference
40,730
public IType getType ( ) { IType type = getTypeImpl ( ) ; if ( TypeSystem . isDeleted ( type ) ) { type = TypeSystem . getErrorType ( ) ; } return type ; }
Returns this Expression s IType .
40,731
private static String xmlEncode ( String input , boolean attribute ) { if ( input == null || input . length ( ) == 0 ) { return attribute ? "\"\"" : input ; } StringBuilder output = new StringBuilder ( ) ; if ( attribute ) { output . append ( 0 ) ; } char quoteChar = 0 ; for ( int i = 0 ; i < input . length ( ) ; i ++ ) { char ch = input . charAt ( i ) ; switch ( ch ) { case '<' : output . append ( "&lt;" ) ; break ; case '>' : output . append ( "&gt;" ) ; break ; case '&' : output . append ( "&amp;" ) ; break ; case '"' : if ( attribute && quoteChar == '"' ) { output . append ( "&quot;" ) ; } else { output . append ( ch ) ; quoteChar = '\'' ; } break ; case '\'' : if ( attribute && quoteChar == '\'' ) { output . append ( "&apos;" ) ; } else { output . append ( ch ) ; quoteChar = '"' ; } break ; case 0x0009 : case 0x000A : case 0x000D : if ( attribute ) { output . append ( "&#" ) ; output . append ( ( int ) ch ) ; output . append ( ";" ) ; } else { output . append ( ch ) ; } break ; default : if ( ch < 32 || ch >= 0xFFFE ) { throw new IllegalArgumentException ( "UTF-16 Codepoint 0x" + Integer . toString ( ch , 16 ) + " is not valid for XML content" ) ; } output . append ( ch ) ; } } if ( attribute ) { if ( quoteChar == 0 ) { quoteChar = '"' ; } output . setCharAt ( 0 , quoteChar ) ; output . append ( quoteChar ) ; } return output . toString ( ) ; }
Properly encodes user input for inclusion in an XML document .
40,732
public void reassignClassLoader ( ) { ClassLoader loader = _module . getModuleClassLoader ( ) ; if ( loader . getParent ( ) instanceof IInjectableClassLoader ) { ( ( IInjectableClassLoader ) loader . getParent ( ) ) . dispose ( ) ; _module . disposeLoader ( ) ; } }
Called in Single module mode . If the parent loader of the ModuleClassLoader is the GosuPluginContainer we drop the ModuleClassLoader and its parent the GosuPluginContainer . New ones are created and assigned here . Note this is a giant hack among many gianter hacks that keep the old test framework floating .
40,733
public Object invoke ( Object [ ] args ) { Object value = getValue ( ) ; if ( value instanceof ISymbol ) { return ( ( Symbol ) value ) . invoke ( args ) ; } if ( value instanceof IBlock ) { return ( ( IBlock ) value ) . invokeWithArgs ( args ) ; } Method method = ( Method ) value ; Object ret ; try { ret = method . invoke ( null , args ) ; } catch ( Exception e ) { throw GosuExceptionUtil . forceThrow ( e ) ; } return ret ; }
Invokes function .
40,734
public static ObjectSize deepSizeOf ( Object obj , IObjectSizeFilter filter , int maxObjects ) { Map < Object , Object > visited = new IdentityHashMap < Object , Object > ( ) ; Stack < ObjectEntry > stack = new Stack < ObjectEntry > ( ) ; InvocationCounter sizeHistogram = new InvocationCounter ( false ) ; long result = internalSizeOf ( new ObjectEntry ( obj , "" , "" ) , stack , visited , filter , "" ) ; sizeHistogram . recordInvocation ( obj . getClass ( ) . getName ( ) , ( int ) result ) ; int n = 1 ; while ( ! stack . isEmpty ( ) ) { ObjectEntry entry = stack . pop ( ) ; long size = internalSizeOf ( entry , stack , visited , filter , entry . indent ) ; result += size ; n ++ ; sizeHistogram . recordInvocation ( entry . object . getClass ( ) . getName ( ) , ( int ) size ) ; if ( n >= maxObjects ) { return new ObjectSize ( result , false ) ; } } visited . clear ( ) ; if ( VERBOSE ) { System . out . println ( ) ; System . out . println ( "-------------------------------------------------" ) ; sizeHistogram . print ( ) ; } return new ObjectSize ( result , true ) ; }
Calculates full size of object iterating over its hierarchy graph .
40,735
public Object evaluate ( ) { if ( ! isCompileTimeConstant ( ) ) { return super . evaluate ( ) ; } return ( Boolean ) getCondition ( ) . evaluate ( ) ? getFirst ( ) . evaluate ( ) : getSecond ( ) . evaluate ( ) ; }
Evaluates this Expression and returns the result .
40,736
public static int arrayHashCode ( Object array ) { if ( array == null ) { return 0 ; } IType arrayType = TypeSystem . getFromObject ( array ) ; int iLen = arrayType . getArrayLength ( array ) ; int hashCode = 0 ; for ( int i = 0 ; i < iLen ; i ++ ) { Object value = arrayType . getArrayComponent ( array , i ) ; if ( value != null ) { IType valueType = TypeSystem . getFromObject ( value ) ; if ( valueType . isArray ( ) ) { hashCode = 31 * hashCode + hashCode ( value ) ; } else { hashCode = 31 * hashCode + value . hashCode ( ) ; } } } return hashCode * 31 + iLen ; }
Return the hash code for an array
40,737
public Integer getStyleCodeAtPosition ( int iPosition ) { if ( _locations == null || _locations . isEmpty ( ) ) { return null ; } IParseTree l ; try { l = IParseTree . Search . getDeepestLocation ( _locations , iPosition - _locationsOffset , true ) ; } catch ( Throwable t ) { return null ; } if ( l == null ) { return null ; } if ( ! l . contains ( iPosition - _locationsOffset ) ) { return null ; } IParsedElement parsedElem = l . getParsedElement ( ) ; try { return getStyleCodeForParsedElement ( iPosition , parsedElem ) ; } catch ( Throwable t ) { return null ; } }
Returns a style code for the absolute position in the document or null if no code is mapped .
40,738
private Integer getStyleCodeForParsedElement ( int iPosition , IParsedElement parsedElem ) { if ( parsedElem instanceof IBeanMethodCallStatement ) { parsedElem = ( ( IBeanMethodCallStatement ) parsedElem ) . getBeanMethodCall ( ) ; } if ( parsedElem instanceof IBeanMethodCallExpression ) { if ( iPosition >= ( ( IBeanMethodCallExpression ) parsedElem ) . getStartOffset ( ) ) { IMethodInfo md = ( ( IBeanMethodCallExpression ) parsedElem ) . getMethodDescriptor ( ) ; if ( md != null ) { if ( md . getOwnersType ( ) instanceof IGosuEnhancement ) { return GosuStyleContext . ENHANCEMENT_METHOD_CALL_KEY ; } else { return GosuStyleContext . METHOD_CALL_KEY ; } } } return null ; } if ( ( parsedElem instanceof IExpression && ( ( IExpression ) parsedElem ) . getType ( ) instanceof INamespaceType ) && ! parsedElem . hasParseExceptions ( ) ) { return GosuStyleContext . NESTED_TYPE_LITERAL_KEY ; } if ( parsedElem instanceof IFieldAccessExpression ) { IFieldAccessExpression ma = ( IFieldAccessExpression ) parsedElem ; try { if ( iPosition < ma . getStartOffset ( ) ) { return null ; } if ( ! GosuEditorKit . getStylePreferences ( ) . areStylesEquivalent ( GosuStyleContext . STYLE_EnhancementProperty , GosuStyleContext . STYLE_Property ) ) { IPropertyInfo pi = ( ( IFieldAccessExpression ) parsedElem ) . getPropertyInfo ( ) ; if ( pi != null && pi . getOwnersType ( ) instanceof IGosuEnhancement ) { return GosuStyleContext . ENHANCEMENT_PROPERTY_KEY ; } else { return GosuStyleContext . PROPERTY_KEY ; } } else { return GosuStyleContext . PROPERTY_KEY ; } } catch ( Exception e ) { } } if ( parsedElem instanceof ITypeLiteralExpression ) { ITypeLiteralExpression tl = ( ITypeLiteralExpression ) parsedElem ; if ( ! ( tl . getType ( ) . getType ( ) instanceof IErrorType ) ) { IParsedElement parent = tl . getParent ( ) ; if ( parent instanceof IUsesStatement ) { return GosuStyleContext . USES_KEY ; } else { int segLength = Math . min ( 5 , getContent ( ) . length ( ) - iPosition ) ; Segment txt = new Segment ( _charArray , iPosition , segLength ) ; try { getContent ( ) . getChars ( iPosition , segLength , txt ) ; if ( Character . isJavaIdentifierPart ( txt . first ( ) ) ) { if ( parent instanceof ITypeLiteralExpression && ! ( parent instanceof ICompoundTypeLiteral ) ) { if ( parent instanceof IBlockLiteralExpression ) { return GosuStyleContext . TYPE_LITERAL_KEY ; } else { return GosuStyleContext . NESTED_TYPE_LITERAL_KEY ; } } else if ( parsedElem instanceof IBlockLiteralExpression && ! "block" . equals ( txt . toString ( ) ) ) { return GosuStyleContext . NESTED_TYPE_LITERAL_KEY ; } else { return GosuStyleContext . TYPE_LITERAL_KEY ; } } } catch ( BadLocationException e ) { } } } else { return GosuStyleContext . PARSE_ERROR_KEY ; } } if ( parsedElem instanceof INamespaceStatement ) { return GosuStyleContext . PACKAGE_KEY ; } return null ; }
Given a IParsedElement return a special Style . Or return null if no special style exists for the IParsedElement .
40,739
public int getScannerStart ( int p ) { Element elem = getDefaultRootElement ( ) ; int lineNum = elem . getElementIndex ( p ) ; Element line = elem . getElement ( lineNum ) ; AttributeSet a = line . getAttributes ( ) ; while ( a . isDefined ( CommentAttribute ) && lineNum > 0 ) { lineNum -= 1 ; line = elem . getElement ( lineNum ) ; a = line . getAttributes ( ) ; } return line . getStartOffset ( ) ; }
Fetch a reasonable location to start scanning given the desired start location . This allows for adjustments needed to accomodate multiline comments .
40,740
protected void insertUpdate ( DefaultDocumentEvent chng , AttributeSet attr ) { super . insertUpdate ( chng , attr ) ; Element root = getDefaultRootElement ( ) ; DocumentEvent . ElementChange ec = chng . getChange ( root ) ; if ( ec != null ) { Element [ ] added = ec . getChildrenAdded ( ) ; boolean inComment = false ; for ( Element elem : added ) { int p0 = elem . getStartOffset ( ) ; int p1 = elem . getEndOffset ( ) ; String s ; try { s = getText ( p0 , p1 - p0 ) ; } catch ( BadLocationException bl ) { s = "" ; } if ( inComment ) { MutableAttributeSet a = ( MutableAttributeSet ) elem . getAttributes ( ) ; a . addAttribute ( CommentAttribute , CommentAttribute ) ; int index = s . indexOf ( "*/" ) ; if ( index >= 0 ) { inComment = false ; } } else { int index = s . indexOf ( "/*" ) ; if ( index >= 0 ) { index = s . indexOf ( "*/" , index ) ; if ( index < 0 ) { inComment = true ; } } } } } }
Updates document structure as a result of text insertion . This will happen within a write lock . The superclass behavior of updating the line map is executed followed by marking any comment areas that should backtracked before scanning .
40,741
public static < Q > LocklessLazyVar < Q > make ( final LazyVarInit < Q > closure ) { return new LocklessLazyVar < Q > ( ) { protected Q init ( ) { return closure . init ( ) ; } } ; }
Creates a new LockingLazyVar based on the type of the LazyVarInit passed in . This method is intended to be called with a lambda or block from Gosu .
40,742
public static IParsedElement boundingParent ( List < IParseTree > locations , int position , Class < ? extends IParsedElement > ... possibleTypes ) { IParseTree location = IParseTree . Search . getDeepestLocation ( locations , position , true ) ; IParsedElement pe = null ; if ( location != null ) { pe = location . getParsedElement ( ) ; while ( pe != null && ! isOneOfTypes ( pe , possibleTypes ) ) { pe = pe . getParent ( ) ; } } return pe ; }
Finds a bounding parent of any of the possible types passed in from the list of locations starting at the position given .
40,743
public static IParseTree [ ] findSpanningLogicalRange ( IParseTree start , IParseTree end ) { while ( end != null ) { IParseTree deepestAtStart = start ; while ( deepestAtStart != null ) { if ( deepestAtStart . isSiblingOf ( end ) ) { IParseTree [ ] returnVal = new IParseTree [ 2 ] ; if ( deepestAtStart . getOffset ( ) < end . getOffset ( ) ) { returnVal [ 0 ] = deepestAtStart ; } else { returnVal [ 0 ] = end ; } if ( deepestAtStart . getExtent ( ) > end . getExtent ( ) ) { returnVal [ 1 ] = deepestAtStart ; } else { returnVal [ 1 ] = end ; } return returnVal ; } deepestAtStart = deepestAtStart . getParent ( ) ; } end = end . getParent ( ) ; } return null ; }
Given two parse tree positions find the bounding pair that captures the start and end in one logical unit
40,744
public static List < GosuPathEntry > convertClasspathToGosuPathEntries ( List < File > classpath ) { boolean loadingGosuFromJarsForbidden = Boolean . getBoolean ( GW_FORBID_GOSU_JARS ) ; ClassPathToGosuPathConverterBlock pathConverterBlock = new ClassPathToGosuPathConverterBlock ( ) ; for ( File f : classpath ) { IDirectory dir = CommonServices . getFileSystem ( ) . getIDirectory ( f ) ; if ( ! f . getName ( ) . endsWith ( ".jar" ) || ! loadingGosuFromJarsForbidden ) { executeOnSourceDirectory ( dir , pathConverterBlock ) ; } else { } } return ( List < GosuPathEntry > ) pathConverterBlock . getPathEntries ( ) ; }
Converts a set of Files into a list of GosuPathEntries . The algorithm is as follows . For each File in the list if that file is a directory or a jar file see if there s a module . xml file in the root . If so parse that file and add in a GosuPathEntry based on the module definition . If not if the file is a directory look for a module . xml file in the parent directory . If such a file exists add in a GosuPathEntry based on that file . If no module . xml file has been found in either case add a GosuPath entry for the directory or jar file using the directory or jar as the root and as the only source directory and with an empty list of custom typeloaders . If the file is not a directory and not a jar file ignore it entirely .
40,745
protected ITerminalStatement getLeastSignificantTerminalStatement_internal ( boolean [ ] bAbsolute ) { ITerminalStatement termRet = null ; bAbsolute [ 0 ] = true ; boolean bBreak = false ; ITerminalStatement lastCaseTerm = null ; if ( _cases != null ) { for ( int i = 0 ; i < _cases . length ; i ++ ) { List caseStatements = _cases [ i ] . getStatements ( ) ; if ( caseStatements != null && caseStatements . size ( ) > 0 ) { boolean bCaseAbs = true ; for ( int iStmt = 0 ; iStmt < caseStatements . size ( ) ; iStmt ++ ) { boolean [ ] bCsr = { false } ; ITerminalStatement terminalStmt = ( ( Statement ) caseStatements . get ( iStmt ) ) . getLeastSignificantTerminalStatement ( bCsr ) ; if ( terminalStmt != null ) { bCaseAbs = bCsr [ 0 ] ; if ( ! ( terminalStmt instanceof IBreakStatement ) ) { termRet = getLeastSignificant ( termRet , terminalStmt ) ; if ( i == _cases . length - 1 ) { lastCaseTerm = termRet ; } } else { bAbsolute [ 0 ] = bCaseAbs = false ; bBreak = true ; } } } bAbsolute [ 0 ] = bAbsolute [ 0 ] && bCaseAbs ; } } } boolean bDefaultContributed = false ; if ( _defaultStatements != null ) { if ( _defaultStatements . size ( ) > 0 ) { if ( ! bBreak ) { bAbsolute [ 0 ] = true ; } boolean bDefaultAbs = false ; for ( int i = 0 ; i < _defaultStatements . size ( ) ; i ++ ) { boolean [ ] bCsr = { false } ; ITerminalStatement terminalStmt = _defaultStatements . get ( i ) . getLeastSignificantTerminalStatement ( bCsr ) ; if ( terminalStmt != null ) { if ( ! ( terminalStmt instanceof IBreakStatement ) ) { bDefaultAbs = bCsr [ 0 ] ; termRet = getLeastSignificant ( termRet , terminalStmt ) ; bDefaultContributed = true ; } } } bAbsolute [ 0 ] = bAbsolute [ 0 ] && bDefaultAbs ; } } else if ( ! bBreak && lastCaseTerm != null && isCoveredEnumSwitch ( ) ) { termRet = getLeastSignificant ( new ThrowStatement ( ) , lastCaseTerm ) ; bAbsolute [ 0 ] = bDefaultContributed = true ; } bAbsolute [ 0 ] = bAbsolute [ 0 ] && termRet != null && bDefaultContributed ; return termRet ; }
bAbsolute is true iff there are no break terminals anywhere in any cases and the default clause s terminator is non - break and absolute
40,746
public static < T extends Annotation > Builder < T > builder ( Class < T > annotationType ) { return new Builder < T > ( annotationType ) ; }
Returns a builder that can be used to construct an annotation instance .
40,747
public static < T extends Annotation > T create ( Class < T > annotationType , Object value ) { return new Builder < T > ( annotationType ) . withValue ( value ) . create ( ) ; }
Convenience method that constructs an annotation instance with a single value element .
40,748
public static < T extends Annotation > T create ( Class < T > annotationType ) { return new Builder < T > ( annotationType ) . create ( ) ; }
Convenience method that constructs an annotation instance with no elements .
40,749
public Object evaluate ( ) { if ( ! isCompileTimeConstant ( ) ) { return super . evaluate ( ) ; } Object lhsValue = getLHS ( ) . evaluate ( ) ; Object rhsValue = getRHS ( ) . evaluate ( ) ; IType lhsType = getLHS ( ) . getType ( ) ; IType rhsType = getRHS ( ) . getType ( ) ; if ( _strOperator . equals ( ">" ) ) { if ( BeanAccess . isNumericType ( lhsType ) ) { return compareNumbers ( lhsValue , rhsValue , lhsType , rhsType ) > 0 ; } else { if ( BeanAccess . isBeanType ( lhsType ) ) { if ( BeanAccess . isBeanType ( rhsType ) ) { if ( lhsType . isAssignableFrom ( rhsType ) ) { if ( JavaTypes . COMPARABLE ( ) . isAssignableFrom ( lhsType ) ) { return ( ( Comparable ) lhsValue ) . compareTo ( rhsValue ) > 0 ; } } } } } } else if ( _strOperator . equals ( "<" ) ) { if ( BeanAccess . isNumericType ( lhsType ) ) { return compareNumbers ( lhsValue , rhsValue , lhsType , rhsType ) < 0 ; } else { if ( BeanAccess . isBeanType ( lhsType ) ) { if ( BeanAccess . isBeanType ( rhsType ) ) { if ( lhsType . isAssignableFrom ( rhsType ) ) { if ( JavaTypes . COMPARABLE ( ) . isAssignableFrom ( lhsType ) ) { return ( ( Comparable ) lhsValue ) . compareTo ( rhsValue ) < 0 ; } } } } } } else if ( _strOperator . equals ( ">=" ) ) { if ( BeanAccess . isNumericType ( lhsType ) ) { return compareNumbers ( lhsValue , rhsValue , lhsType , rhsType ) >= 0 ; } else { if ( BeanAccess . isBeanType ( lhsType ) ) { if ( BeanAccess . isBeanType ( rhsType ) ) { if ( lhsType . isAssignableFrom ( rhsType ) ) { if ( JavaTypes . COMPARABLE ( ) . isAssignableFrom ( lhsType ) ) { return ( ( Comparable ) lhsValue ) . compareTo ( rhsValue ) >= 0 ; } } } } } } else { if ( BeanAccess . isNumericType ( lhsType ) ) { return compareNumbers ( lhsValue , rhsValue , lhsType , rhsType ) <= 0 ; } else { if ( BeanAccess . isBeanType ( lhsType ) ) { if ( BeanAccess . isBeanType ( rhsType ) ) { if ( lhsType . isAssignableFrom ( rhsType ) ) { if ( JavaTypes . COMPARABLE ( ) . isAssignableFrom ( lhsType ) ) { return ( ( Comparable ) lhsValue ) . compareTo ( rhsValue ) <= 0 ; } } } } } } throw new UnsupportedOperationException ( "Operands are not compile-time constants.\n" + "(see http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#5313)" ) ; }
Perform a relational comparison .
40,750
public static byte [ ] toBytes ( CharSequence seq ) { try { return seq . toString ( ) . getBytes ( "UTF-8" ) ; } catch ( UnsupportedEncodingException ex ) { throw new RuntimeException ( ex ) ; } }
Converts the specified character sequence to bytes using UTF - 8 .
40,751
public static Properties toProperties ( String propFileText ) throws CharacterCodingException { CharsetEncoder encoder = Charset . forName ( "ISO-8859-1" ) . newEncoder ( ) . onUnmappableCharacter ( CodingErrorAction . REPORT ) ; byte [ ] bytes = encoder . encode ( CharBuffer . wrap ( propFileText ) ) . array ( ) ; Properties props = new Properties ( ) ; try { props . load ( new ByteArrayInputStream ( bytes ) ) ; } catch ( IOException ex ) { throw new RuntimeException ( ex ) ; } return props ; }
Converts the specified property file text to a Properties object .
40,752
public static Reader getInputStreamReader ( InputStream in , String charset ) { try { return new InputStreamReader ( in , charset ) ; } catch ( UnsupportedEncodingException ex ) { throw new RuntimeException ( ex ) ; } }
Returns a reader for the specified input stream using specified encoding .
40,753
public static Writer getOutputStreamWriter ( OutputStream out ) { try { return new OutputStreamWriter ( out , "UTF-8" ) ; } catch ( UnsupportedEncodingException ex ) { throw new RuntimeException ( ex ) ; } }
Returns a writer for the specified output stream using UTF - 8 encoding .
40,754
public static byte [ ] getContent ( InputStream in ) throws IOException { try { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; copy ( in , baos ) ; return baos . toByteArray ( ) ; } finally { in . close ( ) ; } }
Returns the content of the specified input stream . The stream will be closed after calling this method .
40,755
public static String getContent ( Reader in ) throws IOException { try { StringWriter sw = new StringWriter ( ) ; copy ( in , sw ) ; return sw . toString ( ) ; } finally { in . close ( ) ; } }
Returns the content of the specified reader . The reader will be closed after calling this method .
40,756
public static void copy ( InputStream in , Writer writer ) throws IOException { copy ( getInputStreamReader ( in ) , writer ) ; writer . flush ( ) ; }
Copies the content of an input stream to a writer .
40,757
public static void copy ( Reader reader , OutputStream out ) throws IOException { copy ( reader , getOutputStreamWriter ( out ) ) ; out . flush ( ) ; }
Copies the content of a reader to an output stream .
40,758
public static void copy ( Reader in , Writer out ) throws IOException { char [ ] buf = new char [ 1024 ] ; while ( true ) { int count = in . read ( buf ) ; if ( count < 0 ) { break ; } out . write ( buf , 0 , count ) ; } out . flush ( ) ; }
Copies the content of a reader to a writer .
40,759
private void forward ( MouseWheelEvent e ) { e = new MouseWheelEvent ( e . getComponent ( ) . getParent ( ) , e . getID ( ) , e . getWhen ( ) , e . getModifiers ( ) , e . getX ( ) , e . getY ( ) , e . getClickCount ( ) , e . isPopupTrigger ( ) , e . getScrollType ( ) , e . getScrollAmount ( ) , e . getWheelRotation ( ) ) ; Toolkit . getDefaultToolkit ( ) . getSystemEventQueue ( ) . postEvent ( e ) ; }
For some reason the parent does not get mouse wheel
40,760
public static IType parseTypeLiteral ( String typeName ) { try { IType type = GosuParserFactory . createParser ( typeName ) . parseTypeLiteral ( null ) . getType ( ) . getType ( ) ; if ( type instanceof IErrorType ) { throw new RuntimeException ( "Type not found: " + typeName ) ; } return type ; } catch ( ParseResultsException e ) { throw new RuntimeException ( "Type not found: " + typeName , e ) ; } }
Parses a type name such as Iterable&lt ; Claim&gt ; .
40,761
public static TaskQueue getInstance ( ILogger logger , String strQueueName ) { if ( strQueueName == null ) { return null ; } TaskQueue taskQueue = QUEUE_MAP . get ( strQueueName ) ; if ( taskQueue == null ) { taskQueue = new TaskQueue ( logger , strQueueName ) ; QUEUE_MAP . put ( strQueueName , taskQueue ) ; } return taskQueue ; }
Fetch a TaskQueue by name . If the TaskQueue doesn t already exist creates the TaskQueue .
40,762
public static void emptyAndRemoveQueue ( String strQueueName ) { TaskQueue taskQueue = QUEUE_MAP . get ( strQueueName ) ; if ( taskQueue != null ) { taskQueue . emptyQueue ( ) ; synchronized ( taskQueue . _queue ) { taskQueue . _shutdown = true ; taskQueue . _queue . notifyAll ( ) ; } QUEUE_MAP . remove ( strQueueName ) ; } }
Clears all the inactive tasks in the specified queue .
40,763
public void run ( ) { while ( ! _shutdown ) { try { Runnable task ; synchronized ( _queue ) { while ( _queue . isEmpty ( ) ) { if ( _shutdown ) { return ; } _queue . wait ( ) ; } task = _queue . get ( 0 ) ; _queue . notifyAll ( ) ; } try { task . run ( ) ; } catch ( Exception t ) { log ( t ) ; } synchronized ( _queue ) { if ( _queue . size ( ) > 0 ) { _queue . removeFirst ( ) ; } } } catch ( Exception t ) { log ( t ) ; } } }
Do NOT ever call this! Public only by contract .
40,764
protected void log ( Throwable t ) { if ( _logger == null ) { t . printStackTrace ( ) ; } else { _logger . warn ( "Error running job." , t ) ; } }
Log an exception or error .
40,765
public String toDebugString ( ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "GosuPathEntry:\n" ) ; sb . append ( " root: " ) . append ( _root . toJavaFile ( ) . getAbsolutePath ( ) ) . append ( "\n" ) ; for ( IDirectory src : _srcs ) { sb . append ( " src: " ) . append ( src . toJavaFile ( ) . getAbsolutePath ( ) ) . append ( "\n" ) ; } return sb . toString ( ) ; }
Returns a String representation of this path entry suitable for use in debugging .
40,766
public static MethodDescriptor buildScriptableMethodDescriptorNoArgs ( Class actionClass , String methodName ) { MethodDescriptor md = _buildMethodDescriptor ( actionClass , methodName , EMPTY_STRING_ARRAY , EMPTY_CLASS_ARRAY , EMPTY_CLASS_ARRAY ) ; makeScriptable ( md ) ; return md ; }
Builds a no - arg method descriptor that is exposed for scripting everywhere .
40,767
public static MethodDescriptor buildScriptableMethodDescriptor ( Class actionClass , String methodName , String [ ] parameterNames , Class [ ] parameterTypes ) { MethodDescriptor md = _buildMethodDescriptor ( actionClass , methodName , parameterNames , parameterTypes , parameterTypes ) ; makeScriptable ( md ) ; return md ; }
Builds a method descriptor that is exposed for scripting everywhere .
40,768
public static MethodDescriptor buildScriptableDeprecatedMethodDescriptor ( Class actionClass , String methodName , String [ ] parameterNames , Class [ ] parameterTypes ) { MethodDescriptor md = _buildMethodDescriptor ( actionClass , methodName , parameterNames , parameterTypes , parameterTypes ) ; makeScriptableDeprecated ( md ) ; return md ; }
Builds a deprecated method descriptor that is exposed for scripting everywhere .
40,769
public static MethodDescriptor buildHiddenMethodDescriptor ( Class actionClass , String methodName , String [ ] parameterNames , Class [ ] parameterTypes ) { MethodDescriptor md = _buildMethodDescriptor ( actionClass , methodName , parameterNames , parameterTypes , parameterTypes ) ; md . setHidden ( true ) ; return md ; }
Completely hides a method from scripting .
40,770
static public TypedPropertyDescriptor buildScriptablePropertyDescriptor ( String propertyName , Class beanClass , String getterName , String setterName ) { TypedPropertyDescriptor pd = _buildPropertyDescriptor ( propertyName , beanClass , getterName , setterName ) ; makeScriptable ( pd ) ; return pd ; }
Builds a scriptable property descriptor with the given information .
40,771
public static boolean isVisible ( FeatureDescriptor descriptor , IScriptabilityModifier constraint ) { if ( constraint == null ) { return true ; } IScriptabilityModifier modifier = getVisibilityModifier ( descriptor ) ; if ( modifier == null ) { return true ; } return modifier . satisfiesConstraint ( constraint ) ; }
Determine if the descriptor is visible given a visibility constraint .
40,772
protected static MethodDescriptor _buildMethodDescriptor ( Class actionClass , String methodName , String [ ] parameterNames , Class [ ] parameterTypes , Class [ ] actualParameterTypes ) { MethodDescriptor method ; assert ( parameterNames . length == parameterTypes . length ) : "Number of parameter names different from number of parameter types." ; assert ( parameterNames . length == actualParameterTypes . length ) : "Number of parameter names different from number of actual parameters." ; try { int numParams = parameterNames . length ; ParameterDescriptor [ ] parameters = new ParameterDescriptor [ numParams ] ; for ( int i = 0 ; i < numParams ; i ++ ) { parameters [ i ] = new TypedParameterDescriptor ( parameterNames [ i ] , parameterTypes [ i ] ) ; } method = new MethodDescriptor ( actionClass . getMethod ( methodName , actualParameterTypes ) , parameters ) ; } catch ( NoSuchMethodException e ) { throw new RuntimeException ( e ) ; } catch ( SecurityException e ) { throw new RuntimeException ( e ) ; } return method ; }
Builds a method descriptor with no explicit visibility .
40,773
protected static TypedPropertyDescriptor _buildPropertyDescriptor ( String propertyName , Class beanClass , String getterName , String setterName ) { try { return new TypedPropertyDescriptor ( propertyName , beanClass , getterName , setterName ) ; } catch ( IntrospectionException e ) { throw new RuntimeException ( "Failed to create property \"" + propertyName + "\" on class \"" + beanClass + "\": " + e . getClass ( ) + " - " + e . getMessage ( ) ) ; } }
Builds a property descriptor with no explicit visibility .
40,774
private static String makeFqn ( File file ) { String path = file . getAbsolutePath ( ) ; int srcIndex = path . indexOf ( "src" + File . separatorChar ) ; if ( srcIndex >= 0 ) { String fqn = path . substring ( srcIndex + 4 ) . replace ( File . separatorChar , '.' ) ; return fqn . substring ( 0 , fqn . lastIndexOf ( '.' ) ) ; } else { String fqn = file . getName ( ) ; fqn = NOPACKAGE + '.' + fqn . substring ( 0 , fqn . lastIndexOf ( '.' ) ) . replace ( " " , "" ) ; return fqn ; } }
Note this is a giant hack we need to instead get the type name from the psiClass
40,775
private void assignSuperDfs ( IDynamicFunctionSymbol dfsDelegate , IGosuClass owner ) { IDynamicFunctionSymbol rawSuperDfs = dfsDelegate . getSuperDfs ( ) ; if ( rawSuperDfs instanceof DynamicFunctionSymbol ) { while ( rawSuperDfs . getBackingDfs ( ) instanceof DynamicFunctionSymbol && rawSuperDfs . getBackingDfs ( ) != rawSuperDfs ) { rawSuperDfs = rawSuperDfs . getBackingDfs ( ) ; } IType ownersType = rawSuperDfs . getDeclaringTypeInfo ( ) . getOwnersType ( ) ; if ( ! IGosuClass . ProxyUtil . isProxy ( ownersType ) ) { IType superOwner = TypeLord . findParameterizedType ( owner , ownersType ) ; if ( superOwner == null ) { superOwner = ownersType ; } setSuperDfs ( ( ( DynamicFunctionSymbol ) rawSuperDfs ) . getParameterizedVersion ( ( IGosuClass ) superOwner ) ) ; } } }
Assign the super dfs in terms of the deriving class s type parameters
40,776
public static Throwable findExceptionCause ( Throwable e ) { Throwable error = e ; Throwable cause = e ; while ( ( error . getCause ( ) != null ) && ( error . getCause ( ) != error ) ) { cause = error . getCause ( ) ; error = cause ; } return cause ; }
Given an Exception finds the root cause and returns it . This may end up returning the originally passed exception if that was the root cause .
40,777
public static void throwArgMismatchException ( IllegalArgumentException exceptionToWrap , String featureName , Class [ ] actualParameters , Object [ ] args ) { String argTypes = "(" ; for ( int i = 0 ; i < actualParameters . length ; i ++ ) { Class aClass = actualParameters [ i ] ; if ( i > 0 ) { argTypes += " ," ; } argTypes += aClass . getName ( ) ; } argTypes += ")" ; String rttTypes = "(" ; for ( int i = 0 ; i < args . length ; i ++ ) { if ( i > 0 ) { rttTypes += " ," ; } if ( args [ i ] != null ) { rttTypes += args [ i ] . getClass ( ) . getName ( ) ; } else { rttTypes += "null" ; } } rttTypes += ")" ; throw new RuntimeException ( "Tried to pass values of types: " + rttTypes + " into " + featureName + " that takes types " + argTypes , exceptionToWrap ) ; }
This method can be used to provide a more informative type - mismatch exception message than the standard java reflection does with its IllegalArgumentException .
40,778
public static < T extends Throwable > T findException ( Class < T > exceptionTypeToFind , Throwable t ) { Throwable cause = t ; while ( cause != null ) { if ( exceptionTypeToFind . isAssignableFrom ( cause . getClass ( ) ) ) { return ( T ) cause ; } if ( cause == cause . getCause ( ) ) { return null ; } cause = cause . getCause ( ) ; } return null ; }
Given an Exception and an Exception type to look for finds the exception of that type or returns null if none of that type exist .
40,779
public ParseException removeParseException ( ResourceKey keyToRemove ) { if ( _lnf != null ) { return ( ParseException ) removeParseIssue ( keyToRemove , _lnf . _parseExceptions ) ; } return null ; }
Removes the specified parse exception or removes them all if the specified exception is null .
40,780
@ SuppressWarnings ( "unchecked" ) public < E extends IParsedElement > boolean getContainedParsedElementsByType ( Class < E > parsedElementType , List < E > listResults ) { return getContainedParsedElementsByTypes ( ( List < IParsedElement > ) listResults , parsedElementType ) ; }
Find all the parsed elements of a given type contained within this parsed element .
40,781
public String readUntil ( String character , boolean includeDeliminator ) { return readStreamUntil ( _javaProcess . getInputStream ( ) , includeDeliminator , character . toCharArray ( ) ) ; }
Reads a group of text from stdout . The line will start from the previous point until the read character . This method will block until the specified character is read .
40,782
protected < T extends IService , Q extends T > void defineService ( Class < ? extends T > service , Q defaultImplementation ) { if ( ! _definingServices ) { throw new IllegalStateException ( "Service definition must be done only in the defineServices() method." ) ; } if ( ! service . isInterface ( ) ) { throw new IllegalArgumentException ( "Services may only be defined as interfaces, and " + service . getName ( ) + " is not an interface" ) ; } IService existingServiceImpl = _services . get ( service ) ; if ( existingServiceImpl != null ) { throw new IllegalStateException ( "Service " + service . getName ( ) + " has already been " + "defined with the " + existingServiceImpl . getClass ( ) . getName ( ) + " default implementation" ) ; } _services . put ( service , defaultImplementation ) ; }
Defines a service provided by this ServiceKernel
40,783
public void updateState ( ) { resetSmartHelpState ( ) ; if ( isOtherPopupShowing ( ) ) { return ; } final List < IParseIssue > parseIssues = findParseIssuesOrderedByDistanceFromCaret ( 1 ) ; setMode ( SmartFixMode . NONE ) ; for ( Highlighter . Highlight highlight : _editor . getHighlighter ( ) . getHighlights ( ) ) { if ( highlight . getPainter ( ) instanceof SmartFixHighlightPainter ) { _editor . getHighlighter ( ) . removeHighlight ( highlight ) ; } } final Set < String > processed = new HashSet < String > ( ) ; final ITypeUsesMap [ ] uses = new ITypeUsesMap [ ] { _gosuEditor . getTypeUsesMapFromMostRecentParse ( ) } ; Runnable runnable = new Runnable ( ) { public void run ( ) { if ( uses [ 0 ] == null ) { _gosuEditor . waitForParser ( ) ; uses [ 0 ] = _gosuEditor . getTypeUsesMapFromMostRecentParse ( ) ; } for ( IParseIssue parseIssue : parseIssues ) { IParsedElement source = parseIssue . getSource ( ) ; if ( isModeAvailable ( SmartFixMode . IMPORT ) && _gosuEditor . acceptsUses ( ) && handlePossibleImportFix ( source , uses [ 0 ] , processed ) ) { setMode ( SmartFixMode . IMPORT ) ; return ; } else if ( isModeAvailable ( SmartFixMode . FIX_IMPLICIT_CAST ) && isImplictCoercion ( parseIssue ) ) { setMode ( SmartFixMode . FIX_IMPLICIT_CAST ) ; return ; } else if ( isModeAvailable ( SmartFixMode . FIX_CTOR_SYNTAX ) && isObsoleteConstructor ( parseIssue ) ) { setMode ( SmartFixMode . FIX_CTOR_SYNTAX ) ; return ; } else if ( isModeAvailable ( SmartFixMode . FIX_JAVA_STYLE_CAST ) && isJavaStyleCast ( parseIssue ) ) { setMode ( SmartFixMode . FIX_JAVA_STYLE_CAST ) ; return ; } if ( isModeAvailable ( SmartFixMode . ADD_MISSING_OVERRIDE ) && isMissingOverride ( parseIssue ) ) { setMode ( SmartFixMode . ADD_MISSING_OVERRIDE ) ; return ; } else if ( isModeAvailable ( SmartFixMode . FIX_CASE ) && isCaseIssue ( parseIssue ) ) { setMode ( SmartFixMode . FIX_CASE ) ; return ; } else if ( isModeAvailable ( SmartFixMode . FIX_RETURN_TYPE ) && isVoidReturnTypeIssue ( parseIssue ) ) { setMode ( SmartFixMode . FIX_RETURN_TYPE ) ; return ; } else if ( isModeAvailable ( SmartFixMode . GENERATE_CONSTRUCTORS ) && isMissingConstructor ( parseIssue ) ) { setMode ( SmartFixMode . GENERATE_CONSTRUCTORS ) ; return ; } else if ( isModeAvailable ( SmartFixMode . GENERATE_SUPER_CALL ) && isMissingSuperCall ( parseIssue ) ) { setMode ( SmartFixMode . GENERATE_SUPER_CALL ) ; return ; } } } } ; editor . util . EditorUtilities . doBackgroundOp ( runnable ) ; }
Updates the state of the SmartFixManager which may display tool tips and offer to fix issues in the gosu program .
40,784
public String getCurrentFunctionName ( ) { DynamicFunctionSymbol functionSymbol = _bodyContext . getCurrentDFS ( ) ; return ( functionSymbol == null ? null : functionSymbol . getName ( ) ) ; }
These methods should all be rolled directly onto FunctionBodyContext I believe
40,785
private static boolean isGosuClassAccessingProtectedOrInternalMethodOfClassInDifferentClassloader ( ICompilableTypeInternal callingClass , IType declaringClass , IRelativeTypeInfo . Accessibility accessibility ) { return ( accessibility != IRelativeTypeInfo . Accessibility . PUBLIC || AccessibilityUtil . forType ( declaringClass ) == IRelativeTypeInfo . Accessibility . INTERNAL || AccessibilityUtil . forType ( declaringClass ) == IRelativeTypeInfo . Accessibility . PRIVATE ) && getTopLevelNamespace ( callingClass ) . equals ( getTopLevelNamespace ( declaringClass ) ) && ( isInSeparateClassLoader ( callingClass , declaringClass ) || classesLoadInSeparateLoader ( callingClass , declaringClass ) ) ; }
Java will blow up if the package - level access is relied upon across class loaders though so we make the call reflectively .
40,786
@ SuppressWarnings ( "UnusedDeclaration" ) public static Bindings fromJson ( String json ) { try { return PARSER . get ( ) . parseJson ( json ) ; } catch ( ScriptException e ) { throw new RuntimeException ( e ) ; } }
Parse the JSON string as one of a javax . script . Bindings instance .
40,787
public static < S , T > Map < S , T > compactAndLockHashMap ( HashMap < S , T > map ) { if ( map == null || map . isEmpty ( ) ) { return Collections . emptyMap ( ) ; } if ( map . size ( ) == 1 ) { Map . Entry < S , T > stEntry = map . entrySet ( ) . iterator ( ) . next ( ) ; return Collections . singletonMap ( stEntry . getKey ( ) , stEntry . getValue ( ) ) ; } Map < S , T > newMap = new HashMap < S , T > ( map . size ( ) , 1 ) ; newMap . putAll ( map ) ; return Collections . unmodifiableMap ( newMap ) ; }
Returns a compacted and locked map representing the map passed in . This method can freely change the implementation type of the map . I . e . it can return an emptyMap singletonMap or even a completely different map implementation .
40,788
public String parseDotPathWord ( String t ) { StringBuilder sb = t == null ? null : new StringBuilder ( t == null ? "" : t ) ; SourceCodeTokenizer tokenizer = getTokenizer ( ) ; while ( match ( null , '.' ) ) { if ( sb != null ) { sb . append ( '.' ) ; } int mark = tokenizer . mark ( ) ; if ( match ( null , null , SourceCodeTokenizer . TT_WORD ) || match ( null , null , SourceCodeTokenizer . TT_KEYWORD ) ) { if ( sb != null ) { sb . append ( tokenizer . getTokenAt ( mark ) . getStringValue ( ) ) ; } } } if ( sb != null ) { t = sb . toString ( ) ; } return t ; }
Parse a dot separated path as a single logical token
40,789
final void addError ( ParsedElement parsedElement , ResourceKey errorMsg ) { verify ( parsedElement , false , errorMsg , EMPTY_ARRAY ) ; }
Optimizations to avoid creating vararg array
40,790
protected IRExpression compileExpansionUsingArrayList ( IType rootType , IType rootComponentType , IType resultType , IType resultCompType , IType propertyType ) { IRSymbol tempRoot = _cc ( ) . makeAndIndexTempSymbol ( getDescriptor ( rootType ) ) ; IRStatement tempRootAssignment = buildAssignment ( tempRoot , ExpressionTransformer . compile ( _expr ( ) . getRootExpression ( ) , _cc ( ) ) ) ; IRSymbol resultArrayList = _cc ( ) . makeAndIndexTempSymbol ( getDescriptor ( JavaTypes . ARRAY_LIST ( ) ) ) ; IRStatement arrayListCreation = buildAssignment ( resultArrayList , buildNewExpression ( ArrayList . class , new Class [ 0 ] , exprList ( ) ) ) ; IRForEachStatement forLoop = createArrayListAddLoop ( rootType , rootComponentType , resultCompType , tempRoot , resultArrayList , propertyType ) ; IRExpression listToArrayConversion = convertListToArray ( resultType , resultCompType , resultArrayList ) ; return buildComposite ( tempRootAssignment , arrayListCreation , forLoop , listToArrayConversion ) ; }
This method will compile the expansion using an ArrayList to collect temporary results . This is appropriate if the right - hand - side is a Collection or array if the root is an Iterable or Iterator or other object whose size can t easily be determined up - front or if the root is a nested Collection or array that will require additional unwrapping .
40,791
private IType cacheType ( String name , Pair < IType , ITypeLoader > pair ) { if ( pair != null ) { IType type = pair . getFirst ( ) ; IType oldType = _typesByName . get ( name ) ; if ( oldType != null && oldType != CACHE_MISS ) { return oldType ; } _typesByName . add ( name , type ) ; ITypeLoader typeLoader = pair . getSecond ( ) ; if ( typeLoader != null && ! typeLoader . isCaseSensitive ( ) ) { _typesByCaseInsensitiveName . put ( name , type ) ; } } return pair != null ? pair . getFirst ( ) : null ; }
Adds the type to the cache .
40,792
public ITypeRef create ( IType type ) { if ( type instanceof ITypeRef ) { return ( ITypeRef ) type ; } if ( type instanceof INonLoadableType ) { throw new UnsupportedOperationException ( "Type references are not supported for nonloadable types: " + type . getName ( ) ) ; } String strTypeName = TypeLord . getNameWithQualifiedTypeVariables ( type , true ) ; if ( strTypeName == null || strTypeName . length ( ) == 0 ) { throw new IllegalStateException ( "Type has no name" ) ; } ITypeRef ref ; if ( ExecutionMode . isRuntime ( ) ) { ref = getRefTheFastWay ( type , strTypeName ) ; } else { ref = getRefTheSafeWay ( type , strTypeName ) ; } return ref ; }
Wraps the actual class with a proxy .
40,793
private static void setupLoaderChainWithGosuUrl ( ClassLoader loader ) { UrlClassLoaderWrapper wrapped = UrlClassLoaderWrapper . wrapIfNotAlreadyVisited ( loader ) ; if ( wrapped == null ) { return ; } addGosuClassUrl ( wrapped ) ; if ( canWrapChain ( ) ) { if ( loader != ClassLoader . getSystemClassLoader ( ) ) { loader = loader . getParent ( ) ; if ( loader != null ) { setupLoaderChainWithGosuUrl ( loader ) ; } } } }
= null ;
40,794
public void update ( EditorHost editor ) { _editor = editor ; _icon . setIcon ( findIconForResults ( ) ) ; _feedback . repaint ( ) ; repaint ( ) ; editor . repaint ( ) ; }
Updates this panel with current parser feedback .
40,795
public final Object convertValue ( Object value , IType intrType ) { if ( intrType == null ) { return null ; } intrType = getBoundingTypeOfTypeVariable ( intrType ) ; if ( value == null ) { return intrType . isPrimitive ( ) ? convertNullAsPrimitive ( intrType , true ) : null ; } IType runtimeType = TypeSystem . getFromObject ( value ) ; if ( ( intrType instanceof IPlaceholder && ( ( IPlaceholder ) intrType ) . isPlaceholder ( ) ) || ( runtimeType instanceof IPlaceholder && ( ( IPlaceholder ) runtimeType ) . isPlaceholder ( ) ) ) { return value ; } if ( intrType == runtimeType ) { return value ; } if ( intrType . equals ( runtimeType ) ) { return value ; } if ( intrType . isAssignableFrom ( runtimeType ) ) { value = extractObjectArray ( intrType , value ) ; return value ; } if ( intrType . isArray ( ) && runtimeType . isArray ( ) ) { if ( intrType . getComponentType ( ) . isAssignableFrom ( runtimeType . getComponentType ( ) ) ) { value = extractObjectArray ( intrType , value ) ; return value ; } else if ( intrType instanceof IGosuArrayClass && value instanceof IGosuObject [ ] ) { return value ; } } if ( intrType instanceof IJavaType && IGosuClass . ProxyUtil . isProxy ( intrType ) && runtimeType instanceof IGosuClass && intrType . getSupertype ( ) != null && intrType . getSupertype ( ) . isAssignableFrom ( runtimeType ) ) { return value ; } if ( intrType instanceof IJavaType && ( ( IJavaType ) intrType ) . getIntrinsicClass ( ) . isAssignableFrom ( value . getClass ( ) ) ) { return value ; } if ( intrType instanceof IGosuClass && ( ( IGosuClass ) intrType ) . isStructure ( ) ) { return value ; } Object convertedValue = coerce ( intrType , runtimeType , value ) ; if ( convertedValue != null ) { return convertedValue ; } else { if ( canCoerce ( intrType , runtimeType ) ) { return convertedValue ; } else { if ( ! runtimeType . isArray ( ) ) { return NO_DICE ; } return value ; } } }
Given a value and a target Class return a compatible value via the target Class .
40,796
public Date makeDateFrom ( Object obj ) { if ( obj == null ) { return null ; } if ( obj instanceof IDimension ) { obj = ( ( IDimension ) obj ) . toNumber ( ) ; } if ( obj instanceof Date ) { return ( Date ) obj ; } if ( obj instanceof Number ) { return new Date ( ( ( Number ) obj ) . longValue ( ) ) ; } if ( obj instanceof Calendar ) { return ( ( Calendar ) obj ) . getTime ( ) ; } if ( ! ( obj instanceof String ) ) { obj = obj . toString ( ) ; } try { return parseDateTime ( ( String ) obj ) ; } catch ( Exception e ) { } return null ; }
Returns a new Date instance representing the object .
40,797
public Date parseDateTime ( String str ) throws java . text . ParseException { if ( str == null ) { return null ; } return DateFormat . getDateInstance ( ) . parse ( str ) ; }
Produce a date from a string using standard DateFormat parsing .
40,798
public static int getLineAtPosition ( JTextComponent editor , int position ) { if ( position <= 0 ) { return 1 ; } String s = editor . getText ( ) ; if ( position > s . length ( ) ) { position = s . length ( ) ; } try { return GosuStringUtil . countMatches ( editor . getText ( 0 , position ) , "\n" ) + 1 ; } catch ( BadLocationException e ) { throw new RuntimeException ( e ) ; } }
Gets the line at a given position in the editor
40,799
public static int getDeepestWhiteSpaceLineStartAfter ( String script , int offset ) { if ( offset < 0 ) { return offset ; } int i = offset ; while ( true ) { int lineStartAfter = getWhiteSpaceLineStartAfter ( script , i ) ; if ( lineStartAfter == - 1 ) { return i ; } else { i = lineStartAfter ; } } }
Eats whitespace lines after the given offset until it finds a non - whitespace line and returns the start of the last whitespace line found or the initial value if none was .