idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
38,300 | public String translate ( String text , List < String [ ] > patterns ) { String res = text ; for ( String [ ] each : patterns ) { res = res . replaceAll ( "(?ms)" + each [ 0 ] , each [ 1 ] ) ; } return res ; } | Clone the python unicode translate method in legacy languages younger than python . python docutils is public domain . |
38,301 | public Result generateCode ( ) throws JsonIOException , IOException { if ( moduleManager == null ) { loadModulesFromKmdFiles ( ) ; } if ( internalTemplates != null ) { templatesDir = getInternalTemplatesDir ( internalTemplates ) ; } if ( templatesDir != null ) { Path configFile = templatesDir . resolve ( CONFIG_FILE_NAME ) ; if ( Files . exists ( configFile ) ) { JsonObject internalConfig = loadConfigFile ( configFile ) ; overrideConfig ( internalConfig , config ) ; config = internalConfig ; } } try { if ( deleteGenDir ) { PathUtils . delete ( codegenDir , loadNoDeleteFiles ( config ) ) ; } if ( codegenDir != null && ! Files . exists ( codegenDir ) ) { Files . createDirectories ( codegenDir ) ; } CodeGen codeGen = new CodeGen ( templatesDir , codegenDir , verbose , listGeneratedFiles , overwrite , config ) ; for ( ModuleDefinition module : moduleManager . getModules ( ) ) { if ( config . has ( "expandMethodsWithOpsParams" ) && config . get ( "expandMethodsWithOpsParams" ) . getAsBoolean ( ) ) { module . expandMethodsWithOpsParams ( ) ; } if ( templatesDir != null && codegenDir != null ) { codeGen . generateCode ( module ) ; } if ( outputModuleFile != null ) { JsonModuleSaverLoader . getInstance ( ) . writeToFile ( module , new File ( outputModuleFile . toFile ( ) , module . getName ( ) + ".kmd.json" ) ) ; } if ( generateMavenPom ) { codeGen . setTemplatesDir ( getInternalTemplatesDir ( "maven" ) ) ; codeGen . generateMavenPom ( module , searchFiles ( this . kmdFilesToGen , "pom.xml" ) ) ; } if ( generateNpmPackage ) { codeGen . setTemplatesDir ( getInternalTemplatesDir ( "npm" ) ) ; codeGen . generateNpmPackage ( module , searchFiles ( this . kmdFilesToGen , "package.json" ) , searchFiles ( this . kmdFilesToGen , "bower.json" ) ) ; } } return new Result ( ) ; } catch ( KurentoModuleCreatorException e ) { return new Result ( new Error ( "Error: " + e . getMessage ( ) ) ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return new Result ( new Error ( "Unexpected error: " + e . getClass ( ) . getName ( ) + " " + e . getMessage ( ) ) ) ; } } | Genarates the code . |
38,302 | private CharType nearestCharType ( CharType ... types ) { for ( Character chr : chars ) { for ( CharType type : types ) { if ( type . isMatchedBy ( chr ) ) { return type ; } } } return CharType . EOL ; } | Finds the nearest character type . |
38,303 | private void checkForLeadingZeroes ( ) { Character la1 = chars . lookahead ( 1 ) ; Character la2 = chars . lookahead ( 2 ) ; if ( la1 != null && la1 == '0' && CharType . DIGIT . isMatchedBy ( la2 ) ) { throw new ParseException ( "Numeric identifier MUST NOT contain leading zeroes" ) ; } } | Checks for leading zeroes in the numeric identifiers . |
38,304 | private void checkForEmptyIdentifier ( ) { Character la = chars . lookahead ( 1 ) ; if ( CharType . DOT . isMatchedBy ( la ) || CharType . PLUS . isMatchedBy ( la ) || CharType . EOL . isMatchedBy ( la ) ) { throw new ParseException ( "Identifiers MUST NOT be empty" , new UnexpectedCharacterException ( la , chars . currentOffset ( ) , CharType . DIGIT , CharType . LETTER , CharType . HYPHEN ) ) ; } } | Checks for empty identifiers in the pre - release version or build metadata . |
38,305 | private void consConstructorCallContext ( ) { proposalPrefix = rawScan . subSequence ( rawScan . indexOf ( "new" ) , rawScan . length ( ) ) . toString ( ) ; processedScan = rawScan ; type = SearchType . New ; } | Constructs the completion context for a constructor call |
38,306 | private void consMkContext ( ) { final int MK_LENGTH = "mk_" . length ( ) ; CharSequence subSeq = rawScan . subSequence ( MK_LENGTH , rawScan . length ( ) ) ; processedScan = new StringBuffer ( subSeq ) ; proposalPrefix = processedScan . toString ( ) . trim ( ) ; type = SearchType . Mk ; } | Constructs the completion context for a mk_ call |
38,307 | private void consQuoteContext ( int index ) { processedScan = new StringBuffer ( proposalPrefix . subSequence ( index , proposalPrefix . length ( ) ) ) ; proposalPrefix = processedScan . substring ( processedScan . lastIndexOf ( "<" ) ) ; type = SearchType . Quote ; } | Constructs the completion context for quotes |
38,308 | private void setMeasureExp ( TypeCheckInfo question , SFunctionDefinitionBase node , Environment base , Environment local , NameScope scope ) throws AnalysisException { PType actual = node . getMeasure ( ) . apply ( THIS , question . newInfo ( local ) ) ; node . setMeasureName ( node . getName ( ) . getMeasureName ( node . getName ( ) . getLocation ( ) ) ) ; checkMeasure ( question , node , node . getMeasureName ( ) , actual ) ; List < List < PPattern > > cpll = new Vector < List < PPattern > > ( ) ; boolean isCurried ; if ( node instanceof AExplicitFunctionDefinition ) { List < PPattern > all = new Vector < PPattern > ( ) ; AExplicitFunctionDefinition ex = ( AExplicitFunctionDefinition ) node ; for ( List < PPattern > pl : ex . getParamPatternList ( ) ) { for ( PPattern p : pl ) { all . add ( p . clone ( ) ) ; } } cpll . add ( all ) ; isCurried = ex . getIsCurried ( ) ; } else { List < PPattern > all = new Vector < PPattern > ( ) ; AImplicitFunctionDefinition imp = ( AImplicitFunctionDefinition ) node ; for ( APatternListTypePair ptp : imp . getParamPatterns ( ) ) { for ( PPattern p : ptp . getPatterns ( ) ) { all . add ( p . clone ( ) ) ; } } cpll . add ( all ) ; isCurried = false ; } AFunctionType mtype = question . assistantFactory . createAFunctionTypeAssistant ( ) . getMeasureType ( ( AFunctionType ) node . getType ( ) , isCurried , actual ) ; AExplicitFunctionDefinition def = AstFactory . newAExplicitFunctionDefinition ( node . getMeasureName ( ) , scope , ( List < ILexNameToken > ) node . getTypeParams ( ) . clone ( ) , mtype , cpll , node . getMeasure ( ) , null , null , false , null ) ; def . setClassDefinition ( node . getClassDefinition ( ) == null ? null : node . getClassDefinition ( ) . clone ( ) ) ; def . setAccess ( node . getAccess ( ) . clone ( ) ) ; question . assistantFactory . createPDefinitionAssistant ( ) . typeResolve ( def , THIS , question ) ; def . apply ( THIS , question ) ; node . setMeasureDef ( def ) ; } | Set measureDef to a newly created function based on the measure expression . |
38,309 | private void checkMeasure ( TypeCheckInfo question , SFunctionDefinitionBase node , ILexNameToken iLexNameToken , PType result ) { PTypeAssistantTC assistant = question . assistantFactory . createPTypeAssistant ( ) ; if ( ! assistant . isNumeric ( result ) ) { if ( assistant . isProduct ( result ) ) { AProductType pt = assistant . getProduct ( result ) ; for ( PType t : pt . getTypes ( ) ) { if ( ! assistant . isNumeric ( t ) ) { TypeCheckerErrors . report ( 3272 , "Measure range is not a nat, or a nat tuple" , node . getMeasure ( ) . getLocation ( ) , node . getMeasure ( ) ) ; TypeCheckerErrors . detail ( "Actual" , result ) ; break ; } } } else { TypeCheckerErrors . report ( 3272 , "Measure range is not a nat, or a nat tuple" , node . getMeasure ( ) . getLocation ( ) , node . getMeasure ( ) ) ; TypeCheckerErrors . detail ( "Actual" , result ) ; } } } | A measure must return a nat or nat - tuple . |
38,310 | private int getFirstCompleteLineOfRegion ( IRegion region , IDocument document ) { try { int startLine = document . getLineOfOffset ( region . getOffset ( ) ) ; int offset = document . getLineOffset ( startLine ) ; if ( offset >= region . getOffset ( ) ) return startLine ; offset = document . getLineOffset ( startLine + 1 ) ; return ( offset > region . getOffset ( ) + region . getLength ( ) ? - 1 : startLine + 1 ) ; } catch ( BadLocationException x ) { VdmUIPlugin . log ( x ) ; } return - 1 ; } | Returns the index of the first line whose start offset is in the given text range . |
38,311 | private boolean isBlockCommented ( int startLine , int endLine , String [ ] prefixes , IDocument document ) { try { for ( int i = startLine ; i <= endLine ; i ++ ) { IRegion line = document . getLineInformation ( i ) ; String text = document . get ( line . getOffset ( ) , line . getLength ( ) ) ; int [ ] found = TextUtilities . indexOf ( prefixes , text , 0 ) ; if ( found [ 0 ] == - 1 ) return false ; String s = document . get ( line . getOffset ( ) , found [ 0 ] ) ; s = s . trim ( ) ; if ( s . length ( ) != 0 ) return false ; } return true ; } catch ( BadLocationException x ) { VdmUIPlugin . log ( x ) ; } return false ; } | Determines whether each line is prefixed by one of the prefixes . |
38,312 | PType typeCheckAElseIf ( INode elseIfNode , ILexLocation elseIfLocation , INode test , INode thenNode , TypeCheckInfo question ) throws AnalysisException { if ( ! question . assistantFactory . createPTypeAssistant ( ) . isType ( test . apply ( THIS , question . newConstraint ( null ) ) , ABooleanBasicType . class ) ) { boolean isExpression = elseIfNode . parent ( ) instanceof PExp ; TypeCheckerErrors . report ( ( isExpression ? 3086 : 3218 ) , "Expression is not boolean" , elseIfLocation , elseIfNode ) ; } List < QualifiedDefinition > qualified = test . apply ( question . assistantFactory . getQualificationVisitor ( ) , question ) ; for ( QualifiedDefinition qdef : qualified ) { qdef . qualifyType ( ) ; } PType type = thenNode . apply ( THIS , question ) ; for ( QualifiedDefinition qdef : qualified ) { qdef . resetType ( ) ; } return type ; } | Type checks a AElseIf node |
38,313 | protected PType typeCheckLet ( INode node , LinkedList < PDefinition > localDefs , INode body , TypeCheckInfo question ) throws AnalysisException { Environment local = question . env ; for ( PDefinition d : localDefs ) { if ( d instanceof AExplicitFunctionDefinition ) { local = new FlatCheckedEnvironment ( question . assistantFactory , d , local , question . scope ) ; question . assistantFactory . createPDefinitionAssistant ( ) . implicitDefinitions ( d , local ) ; question . assistantFactory . createPDefinitionAssistant ( ) . typeResolve ( d , THIS , new TypeCheckInfo ( question . assistantFactory , local , question . scope , question . qualifiers ) ) ; if ( question . env . isVDMPP ( ) ) { SClassDefinition cdef = question . env . findClassDefinition ( ) ; d . setClassDefinition ( cdef ) ; d . setAccess ( question . assistantFactory . createPAccessSpecifierAssistant ( ) . getStatic ( d , true ) ) ; } d . apply ( THIS , new TypeCheckInfo ( question . assistantFactory , local , question . scope , question . qualifiers ) ) ; } else { question . assistantFactory . createPDefinitionAssistant ( ) . implicitDefinitions ( d , local ) ; question . assistantFactory . createPDefinitionAssistant ( ) . typeResolve ( d , THIS , new TypeCheckInfo ( question . assistantFactory , local , question . scope , question . qualifiers ) ) ; d . apply ( THIS , new TypeCheckInfo ( question . assistantFactory , local , question . scope ) ) ; local = new FlatCheckedEnvironment ( question . assistantFactory , d , local , question . scope ) ; } } PType r = body . apply ( THIS , new TypeCheckInfo ( question . assistantFactory , local , question . scope , null , question . constraint , null ) ) ; local . unusedCheck ( question . env ) ; return r ; } | Type checks a let node |
38,314 | protected Map . Entry < PType , AMultiBindListDefinition > typecheckLetBeSt ( INode node , ILexLocation nodeLocation , PMultipleBind bind , PExp suchThat , INode body , TypeCheckInfo question ) throws AnalysisException { final PDefinition def = AstFactory . newAMultiBindListDefinition ( nodeLocation , question . assistantFactory . createPMultipleBindAssistant ( ) . getMultipleBindList ( ( PMultipleBind ) bind ) ) ; def . apply ( THIS , question . newConstraint ( null ) ) ; List < PDefinition > qualified = new Vector < PDefinition > ( ) ; for ( PDefinition d : question . assistantFactory . createPDefinitionAssistant ( ) . getDefinitions ( def ) ) { PDefinition copy = d . clone ( ) ; copy . setNameScope ( NameScope . LOCAL ) ; qualified . add ( copy ) ; } Environment local = new FlatCheckedEnvironment ( question . assistantFactory , qualified , question . env , question . scope ) ; TypeCheckInfo newInfo = new TypeCheckInfo ( question . assistantFactory , local , question . scope , question . qualifiers , question . constraint , null ) ; if ( suchThat != null && ! question . assistantFactory . createPTypeAssistant ( ) . isType ( suchThat . apply ( THIS , newInfo . newConstraint ( null ) ) , ABooleanBasicType . class ) ) { boolean isExpression = node instanceof PExp ; TypeCheckerErrors . report ( ( isExpression ? 3117 : 3225 ) , "Such that clause is not boolean" , nodeLocation , node ) ; } newInfo . qualifiers = null ; final PType r = body . apply ( THIS , newInfo ) ; local . unusedCheck ( ) ; return new Map . Entry < PType , AMultiBindListDefinition > ( ) { public AMultiBindListDefinition setValue ( AMultiBindListDefinition value ) { return null ; } public AMultiBindListDefinition getValue ( ) { return ( AMultiBindListDefinition ) def ; } public PType getKey ( ) { return r ; } } ; } | Type check method for let be such that |
38,315 | public String hackResultName ( AFuncDeclIR func ) throws AnalysisException { SourceNode x = func . getSourceNode ( ) ; if ( x . getVdmNode ( ) instanceof AImplicitFunctionDefinition ) { AImplicitFunctionDefinition iFunc = ( AImplicitFunctionDefinition ) x . getVdmNode ( ) ; return iFunc . getResult ( ) . getPattern ( ) . toString ( ) ; } throw new AnalysisException ( "Expected AFuncDeclIR in implicit function source. Got: " + x . getVdmNode ( ) . getClass ( ) . toString ( ) ) ; } | FIXME Unhack result name extraction for implicit functions |
38,316 | public String hackInv ( ANamedTypeDeclIR type ) { ATypeDeclIR tDecl = ( ATypeDeclIR ) type . parent ( ) ; if ( tDecl . getInv ( ) != null ) { AFuncDeclIR invFunc = ( AFuncDeclIR ) tDecl . getInv ( ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( "inv " ) ; sb . append ( invFunc . getFormalParams ( ) . get ( 0 ) . getPattern ( ) . toString ( ) ) ; sb . append ( " == " ) ; sb . append ( invFunc . getName ( ) ) ; sb . append ( "(" ) ; sb . append ( "&" ) ; sb . append ( invFunc . getFormalParams ( ) . get ( 0 ) . getPattern ( ) . toString ( ) ) ; sb . append ( ")" ) ; return sb . toString ( ) ; } return "" ; } | FIXME Unhack invariant extraction for named types |
38,317 | public String hackInv ( ARecordDeclIR type ) { if ( type . getInvariant ( ) != null ) { AFuncDeclIR invFunc = ( AFuncDeclIR ) type . getInvariant ( ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( "inv " ) ; sb . append ( invFunc . getFormalParams ( ) . get ( 0 ) . getPattern ( ) . toString ( ) ) ; sb . append ( " == " ) ; sb . append ( invFunc . getName ( ) ) ; sb . append ( "(" ) ; sb . append ( "&" ) ; sb . append ( invFunc . getFormalParams ( ) . get ( 0 ) . getPattern ( ) . toString ( ) ) ; sb . append ( ")" ) ; return sb . toString ( ) ; } return "" ; } | FIXME Unhack invariant extraction for namedt ypes |
38,318 | public static String wrap ( String s ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "(" ) ; sb . append ( s ) ; sb . append ( ")" ) ; return sb . toString ( ) ; } | Wrap a string in parenthesis . |
38,319 | protected synchronized Long getStaticId ( String name , CPUResource cpuId ) { String nameFinal = name + cpuId . getNumber ( ) ; if ( staticIds . containsKey ( nameFinal ) ) { return staticIds . get ( nameFinal ) ; } else { RTDeployStaticMessage deployMessage = new RTDeployStaticMessage ( name , cpuId ) ; cachedStaticDeploys . add ( deployMessage ) ; staticIds . put ( nameFinal , deployMessage . getObjectReference ( ) ) ; return deployMessage . getObjectReference ( ) ; } } | Timestamp the message |
38,320 | public void addListener ( IProblemChangedListener listener ) { if ( fListeners . isEmpty ( ) ) { VdmUIPlugin . getWorkspace ( ) . addResourceChangeListener ( this ) ; } fListeners . add ( listener ) ; } | Adds a listener for problem marker changes . |
38,321 | private void runPendingUpdates ( ) { IResource [ ] markerResources = null ; IResource [ ] annotationResources = null ; synchronized ( this ) { if ( ! fResourcesWithMarkerChanges . isEmpty ( ) ) { markerResources = ( IResource [ ] ) fResourcesWithMarkerChanges . toArray ( new IResource [ fResourcesWithMarkerChanges . size ( ) ] ) ; fResourcesWithMarkerChanges . clear ( ) ; } if ( ! fResourcesWithAnnotationChanges . isEmpty ( ) ) { annotationResources = ( IResource [ ] ) fResourcesWithAnnotationChanges . toArray ( new IResource [ fResourcesWithAnnotationChanges . size ( ) ] ) ; fResourcesWithAnnotationChanges . clear ( ) ; } } Object [ ] listeners = fListeners . getListeners ( ) ; for ( int i = 0 ; i < listeners . length ; i ++ ) { IProblemChangedListener curr = ( IProblemChangedListener ) listeners [ i ] ; if ( markerResources != null ) { curr . problemsChanged ( markerResources , true ) ; } if ( annotationResources != null ) { curr . problemsChanged ( annotationResources , false ) ; } } } | Notify all IProblemChangedListener . Must be called in the display thread . |
38,322 | protected void createTypeSpecificEditors ( Composite parent ) throws CoreException { setTitle ( "Line Breakpoint" ) ; IVdmLineBreakpoint breakpoint = ( IVdmLineBreakpoint ) getBreakpoint ( ) ; createConditionEditor ( parent ) ; } | Create the condition editor and associated editors . |
38,323 | private void createConditionEditor ( Composite parent ) throws CoreException { IVdmLineBreakpoint breakpoint = ( IVdmLineBreakpoint ) getBreakpoint ( ) ; String label = null ; if ( label == null ) { label = "Enable Condition" ; } Composite conditionComposite = SWTFactory . createGroup ( parent , EMPTY_STRING , 1 , 1 , GridData . FILL_BOTH ) ; fEnableConditionButton = createCheckButton ( conditionComposite , label ) ; fEnableConditionButton . setSelection ( breakpoint . getExpressionState ( ) ) ; fEnableConditionButton . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { setConditionEnabled ( fEnableConditionButton . getSelection ( ) ) ; } } ) ; fConditionEditor = new BreakpointConditionEditor ( conditionComposite , this ) ; fSuspendWhenLabel = createLabel ( conditionComposite , "Suspend when:" ) ; fConditionIsTrue = createRadioButton ( conditionComposite , "condition is 'true'" ) ; fConditionHasChanged = createRadioButton ( conditionComposite , "value of condition changes" ) ; fConditionHasChanged . setSelection ( true ) ; setConditionEnabled ( fEnableConditionButton . getSelection ( ) ) ; } | Creates the controls that allow the user to specify the breakpoint s condition |
38,324 | private void setConditionEnabled ( boolean enabled ) { fConditionEditor . setEnabled ( enabled ) ; fSuspendWhenLabel . setEnabled ( enabled ) ; fConditionIsTrue . setEnabled ( enabled ) ; fConditionHasChanged . setEnabled ( enabled ) ; } | Sets the enabled state of the condition editing controls . |
38,325 | public static Value freadval ( Value fval , Context ctxt ) { ValueList result = new ValueList ( ) ; try { File file = getFile ( fval ) ; LexTokenReader ltr = new LexTokenReader ( file , Dialect . VDM_PP , VDMJ . filecharset ) ; ExpressionReader reader = new ExpressionReader ( ltr ) ; reader . setCurrentModule ( "IO" ) ; PExp exp = reader . readExpression ( ) ; Interpreter ip = Interpreter . getInstance ( ) ; ip . typeCheck ( exp , ip . getGlobalEnvironment ( ) ) ; result . add ( new BooleanValue ( true ) ) ; result . add ( exp . apply ( VdmRuntime . getExpressionEvaluator ( ) , ctxt ) ) ; } catch ( Exception e ) { lastError = e . toString ( ) ; result = new ValueList ( ) ; result . add ( new BooleanValue ( false ) ) ; result . add ( new NilValue ( ) ) ; } return new TupleValue ( result ) ; } | reading the data . |
38,326 | protected static File getFile ( Value fval ) { String path = stringOf ( fval ) . replace ( '/' , File . separatorChar ) ; File file = new File ( path ) ; if ( ! file . isAbsolute ( ) ) { file = new File ( Settings . baseDir , path ) ; } return file ; } | Gets the absolute path the file based on the filename parsed and the working dir of the IDE or the execution dir of VDMJ |
38,327 | protected static String stringOf ( Value val ) { StringBuilder s = new StringBuilder ( ) ; val = val . deref ( ) ; if ( val instanceof SeqValue ) { SeqValue sv = ( SeqValue ) val ; for ( Value v : sv . values ) { v = v . deref ( ) ; if ( v instanceof CharacterValue ) { CharacterValue cv = ( CharacterValue ) v ; s . append ( cv . unicode ) ; } else { s . append ( "?" ) ; } } return s . toString ( ) ; } else { return val . toString ( ) ; } } | characters back to their quoted form . |
38,328 | protected void cyclicDependencyCheck ( List < PDefinition > defs ) { if ( System . getProperty ( "skip.cyclic.check" ) != null ) { return ; } if ( getErrorCount ( ) > 0 ) { return ; } Map < ILexNameToken , LexNameSet > dependencies = new HashMap < ILexNameToken , LexNameSet > ( ) ; LexNameSet skip = new LexNameSet ( ) ; PDefinitionAssistantTC assistant = assistantFactory . createPDefinitionAssistant ( ) ; Environment globals = new FlatEnvironment ( assistantFactory , defs , null ) ; for ( PDefinition def : defs ) { Environment env = new FlatEnvironment ( assistantFactory , new Vector < PDefinition > ( ) ) ; FreeVarInfo empty = new FreeVarInfo ( globals , env , false ) ; LexNameSet freevars = assistant . getFreeVariables ( def , empty ) ; if ( ! freevars . isEmpty ( ) ) { for ( ILexNameToken name : assistant . getVariableNames ( def ) ) { dependencies . put ( nameFix ( name . getExplicit ( true ) ) , nameFix ( freevars ) ) ; } } if ( assistant . isTypeDefinition ( def ) || assistant . isOperation ( def ) ) { if ( def . getName ( ) != null ) { skip . add ( nameFix ( def . getName ( ) . getExplicit ( true ) ) ) ; } } } for ( ILexNameToken sought : dependencies . keySet ( ) ) { if ( ! skip . contains ( sought ) ) { Stack < ILexNameToken > stack = new Stack < ILexNameToken > ( ) ; stack . push ( sought ) ; if ( reachable ( sought , dependencies . get ( sought ) , dependencies , stack ) ) { report ( 3355 , "Cyclic dependency detected for " + sought , sought . getLocation ( ) ) ; detail ( "Cycle" , stack . toString ( ) ) ; } stack . pop ( ) ; } } } | Check for cyclic dependencies between the free variables that definitions depend on and the definition of those variables . |
38,329 | private boolean reachable ( ILexNameToken sought , LexNameSet nextset , Map < ILexNameToken , LexNameSet > dependencies , Stack < ILexNameToken > stack ) { if ( nextset == null ) { return false ; } if ( nextset . contains ( sought ) ) { stack . push ( sought ) ; return true ; } for ( ILexNameToken nextname : nextset ) { if ( stack . contains ( nextname ) ) { return false ; } stack . push ( nextname ) ; if ( reachable ( sought , dependencies . get ( nextname ) , dependencies , stack ) ) { return true ; } stack . pop ( ) ; } return false ; } | Return true if the name sought is reachable via the next set of names passed using the dependency map . The stack passed records the path taken to find a cycle . |
38,330 | @ SuppressWarnings ( "unchecked" ) public void fillContextMenu ( IMenuManager menu ) { IStructuredSelection selection = ( IStructuredSelection ) getContext ( ) . getSelection ( ) ; boolean hasClosedProjects = false ; Iterator < Object > resources = selection . iterator ( ) ; while ( resources . hasNext ( ) && ( ! hasClosedProjects ) ) { Object next = resources . next ( ) ; IProject project = null ; if ( next instanceof IProject ) { project = ( IProject ) next ; } else if ( next instanceof IAdaptable ) { project = ( IProject ) ( ( IAdaptable ) next ) . getAdapter ( IProject . class ) ; } if ( project == null ) { continue ; } if ( ! project . isOpen ( ) ) { hasClosedProjects = true ; } } if ( ! hasClosedProjects ) { refreshAction . selectionChanged ( selection ) ; menu . appendToGroup ( ICommonMenuConstants . GROUP_BUILD , refreshAction ) ; } } | Adds the refresh resource actions to the context menu . |
38,331 | public void handleSuspend ( int detail ) { DebugEventHelper . fireExtendedEvent ( this , ExtendedDebugEventDetails . BEFORE_SUSPEND ) ; this . target . printLog ( new LogItem ( this . session . getInfo ( ) , "Break" , false , "Suspend" ) ) ; DebugEventHelper . fireChangeEvent ( this ) ; DebugEventHelper . fireSuspendEvent ( this , detail ) ; stack . update ( true ) ; } | VdmThreadStateManager . IStateChangeHandler |
38,332 | public static boolean isValidJavaIdentifier ( String s ) { if ( s == null || s . length ( ) == 0 ) { return false ; } if ( isJavaKeyword ( s ) ) { return false ; } char [ ] c = s . toCharArray ( ) ; if ( ! Character . isJavaIdentifierStart ( c [ 0 ] ) ) { return false ; } for ( int i = 1 ; i < c . length ; i ++ ) { if ( ! Character . isJavaIdentifierPart ( c [ i ] ) ) { return false ; } } return true ; } | Checks whether the given String is a valid Java identifier . |
38,333 | public static List < Integer > computeJavaIdentifierCorrections ( String s ) { List < Integer > correctionIndices = new LinkedList < Integer > ( ) ; if ( s == null || s . length ( ) == 0 ) { return correctionIndices ; } char [ ] c = s . toCharArray ( ) ; if ( ! Character . isJavaIdentifierStart ( c [ 0 ] ) ) { correctionIndices . add ( 0 ) ; } for ( int i = 1 ; i < c . length ; i ++ ) { if ( ! Character . isJavaIdentifierPart ( c [ i ] ) ) { correctionIndices . add ( i ) ; } } return correctionIndices ; } | Computes the indices of characters that need to be replaced with valid characters in order to make s a valid Java identifier . Please note that this method assumes that s is NOT a keyword . |
38,334 | protected VdmContentOutlinePage createOutlinePage ( ) { VdmContentOutlinePage page = new VdmContentOutlinePage ( this ) ; setOutlinePageInput ( page , getEditorInput ( ) ) ; page . addSelectionChangedListener ( createOutlineSelectionChangedListener ( ) ) ; return page ; } | Creates the outline page used with this editor . |
38,335 | public void selectAndReveal ( INode node ) { int [ ] offsetLength = this . locationSearcher . getNodeOffset ( node ) ; selectAndReveal ( offsetLength [ 0 ] , offsetLength [ 1 ] ) ; } | Selects a node existing within the ast presented by the editor |
38,336 | public void setHighlightRange ( INode node ) { try { int [ ] offsetLength = this . locationSearcher . getNodeOffset ( node ) ; Assert . isNotNull ( offsetLength ) ; Assert . isTrue ( offsetLength [ 0 ] > 0 , "Illegal start offset" ) ; Assert . isTrue ( offsetLength [ 0 ] > 0 , "Illegal offset length" ) ; super . setHighlightRange ( offsetLength [ 0 ] , offsetLength [ 1 ] , true ) ; } catch ( IllegalArgumentException e ) { super . resetHighlightRange ( ) ; } } | highlights a node in the text editor . |
38,337 | private IPreferenceStore createCombinedPreferenceStore ( IEditorInput input ) { List < IPreferenceStore > stores = new ArrayList < IPreferenceStore > ( 3 ) ; stores . add ( VdmUIPlugin . getDefault ( ) . getPreferenceStore ( ) ) ; stores . add ( EditorsUI . getPreferenceStore ( ) ) ; stores . add ( PlatformUI . getPreferenceStore ( ) ) ; return new ChainedPreferenceStore ( ( IPreferenceStore [ ] ) stores . toArray ( new IPreferenceStore [ stores . size ( ) ] ) ) ; } | Creates and returns the preference store for this Java editor with the given input . |
38,338 | protected void setOutlinePageInput ( VdmContentOutlinePage page , IEditorInput input ) { if ( page == null ) return ; IVdmElement je = getInputVdmElement ( ) ; if ( je != null && je . exists ( ) ) page . setInput ( je ) ; else page . setInput ( null ) ; } | Sets the input of the editor s outline page . |
38,339 | protected void selectionChanged ( ) { if ( getSelectionProvider ( ) == null ) return ; INode element = computeHighlightRangeSourceReference ( ) ; synchronizeOutlinePage ( element ) ; setSelection ( element , false ) ; } | React to changed selection . |
38,340 | protected INode computeHighlightRangeSourceReference ( ) { ISourceViewer sourceViewer = getSourceViewer ( ) ; if ( sourceViewer == null ) return null ; StyledText styledText = sourceViewer . getTextWidget ( ) ; if ( styledText == null ) return null ; int caret = 0 ; if ( sourceViewer instanceof ITextViewerExtension5 ) { ITextViewerExtension5 extension = ( ITextViewerExtension5 ) sourceViewer ; caret = extension . widgetOffset2ModelOffset ( styledText . getCaretOffset ( ) ) ; } else { int offset = sourceViewer . getVisibleRegion ( ) . getOffset ( ) ; caret = offset + styledText . getCaretOffset ( ) ; } INode element = getElementAt ( caret , false ) ; return element ; } | Computes and returns the source reference that includes the caret and serves as provider for the outline page selection and the editor range indication . |
38,341 | private void writeObject ( java . io . ObjectOutputStream out ) throws IOException { if ( delegateMethods != null ) { delegateMethods . clear ( ) ; } out . defaultWriteObject ( ) ; } | The Method objects in the delegateMethods map cannot be serialized which means that deep copies fail . So here we clear the map when serialization occurs . The map is re - build later on demand . |
38,342 | public void saveState ( IMemento memento ) { memento . putString ( TAG_HIDEFIELDS , String . valueOf ( hasMemberFilter ( FILTER_FIELDS ) ) ) ; memento . putString ( TAG_HIDESTATIC , String . valueOf ( hasMemberFilter ( FILTER_STATIC ) ) ) ; memento . putString ( TAG_HIDENONPUBLIC , String . valueOf ( hasMemberFilter ( FILTER_NONPUBLIC ) ) ) ; memento . putString ( TAG_HIDELOCALTYPES , String . valueOf ( hasMemberFilter ( FILTER_LOCALTYPES ) ) ) ; } | Saves the state of the filter actions in a memento . |
38,343 | public void contributeToToolBar ( IToolBarManager tbm ) { if ( fInViewMenu ) return ; for ( int i = 0 ; i < fFilterActions . length ; i ++ ) { tbm . add ( fFilterActions [ i ] ) ; } } | Adds the filter actions to the given tool bar |
38,344 | public void contributeToViewMenu ( IMenuManager menu ) { if ( ! fInViewMenu ) return ; final String filters = "filters" ; if ( menu . find ( filters ) != null ) { for ( int i = 0 ; i < fFilterActions . length ; i ++ ) { menu . prependToGroup ( filters , fFilterActions [ i ] ) ; } } else { for ( int i = 0 ; i < fFilterActions . length ; i ++ ) { menu . add ( fFilterActions [ i ] ) ; } } } | Adds the filter actions to the given menu manager . |
38,345 | protected int computeAdornmentFlags ( Object obj ) { if ( obj instanceof IVdmElement ) { IVdmElement element = ( IVdmElement ) obj ; int type = element . getElementType ( ) ; switch ( type ) { case IVdmElement . VDM_MODEL : case IVdmElement . VDM_PROJECT : case IVdmElement . COMPILATION_UNIT : case IVdmElement . TYPE : case IVdmElement . INITIALIZER : case IVdmElement . METHOD : case IVdmElement . FIELD : break ; default : } } return 0 ; } | Computes the adornment flags for the given element . |
38,346 | public Image get ( ImageDescriptor descriptor ) { if ( descriptor == null ) descriptor = ImageDescriptor . getMissingImageDescriptor ( ) ; Image result = ( Image ) fRegistry . get ( descriptor ) ; if ( result != null ) return result ; Assert . isTrue ( fDisplay == SWTUtil . getStandardDisplay ( ) , "Allocating image for wrong display." ) ; result = descriptor . createImage ( ) ; if ( result != null ) fRegistry . put ( descriptor , result ) ; return result ; } | Returns the image associated with the given image descriptor . |
38,347 | public void dispose ( ) { for ( Iterator < Image > iter = fRegistry . values ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { Image image = ( Image ) iter . next ( ) ; image . dispose ( ) ; } fRegistry . clear ( ) ; } | Disposes all images managed by this registry . |
38,348 | public static void addAstNode ( LexLocation location , INode node ) { synchronized ( locationToAstNode ) { locationToAstNode . put ( location , node ) ; } } | FIXME we know this is never called a new solutions is needed |
38,349 | private static List < ILexLocation > removeDuplicates ( List < ILexLocation > locations ) { BinaryOperator < Vector < ILexLocation > > merge = ( old , latest ) -> { for ( ILexLocation location : latest ) { if ( location . getHits ( ) > 0 ) { for ( ILexLocation loc : old ) if ( loc . getHits ( ) == 0 ) old . remove ( loc ) ; old . add ( location ) ; } else { boolean allZeroHits = true ; for ( ILexLocation loc : old ) if ( loc . getHits ( ) > 0 ) { allZeroHits = false ; break ; } if ( allZeroHits ) old . add ( location ) ; } } return old ; } ; Map < String , Vector < ILexLocation > > map = locations . stream ( ) . collect ( Collectors . toMap ( loc -> ( ( ILexLocation ) loc ) . getFile ( ) + ( ( ILexLocation ) loc ) . getModule ( ) + "l" + ( ( ILexLocation ) loc ) . getStartLine ( ) + "p" + ( ( ILexLocation ) loc ) . getStartPos ( ) , loc -> new Vector < ILexLocation > ( Arrays . asList ( loc ) ) , merge ) ) ; return map . values ( ) . parallelStream ( ) . collect ( ArrayList :: new , ArrayList :: addAll , ArrayList :: addAll ) ; } | This method handles the case where a location exist both with hits > 0 and hits == 0 . It will remove the location with hits == 0 when another location hits > 0 exists . |
38,350 | protected void dupHideCheck ( List < PDefinition > list , NameScope scope ) { LexNameList allnames = af . createPDefinitionListAssistant ( ) . getVariableNames ( list ) ; for ( ILexNameToken n1 : allnames ) { LexNameList done = new LexNameList ( ) ; for ( ILexNameToken n2 : allnames ) { if ( n1 != n2 && n1 . equals ( n2 ) && ! done . contains ( n1 ) ) { TypeChecker . warning ( 5007 , "Duplicate definition: " + n1 , n1 . getLocation ( ) ) ; done . add ( n1 ) ; } } if ( outer != null ) { PDefinition def = outer . findName ( n1 , NameScope . NAMESANDSTATE ) ; if ( def != null && def . getNameScope ( ) == null ) { def . setNameScope ( NameScope . GLOBAL ) ; } if ( def != null && ! def . getLocation ( ) . equals ( n1 . getLocation ( ) ) && def . getNameScope ( ) . matches ( scope ) ) { String message = null ; if ( def . getLocation ( ) . getFile ( ) . equals ( n1 . getLocation ( ) . getFile ( ) ) ) { message = def . getName ( ) + " " + def . getLocation ( ) . toShortString ( ) + " hidden by " + n1 . getFullName ( ) ; } else { message = def . getName ( ) + " " + def . getLocation ( ) + " hidden by " + n1 . getFullName ( ) ; } TypeChecker . warning ( 5008 , message , n1 . getLocation ( ) ) ; } } } } | Check whether the list of definitions passed contains any duplicates or whether any names in the list hide the same name further down the environment chain . |
38,351 | public void unusedCheck ( Environment downTo ) { Environment p = this ; while ( p != null && p != downTo ) { p . unusedCheck ( ) ; p = p . outer ; } } | Unravelling unused check . |
38,352 | public void setDefaultName ( String mname ) throws Exception { if ( mname == null ) { defaultModule = AstFactory . newAModuleModules ( ) ; } else { for ( AModuleModules m : modules ) { if ( m . getName ( ) . getName ( ) . equals ( mname ) ) { defaultModule = m ; return ; } } throw new Exception ( "Module " + mname + " not loaded" ) ; } } | Set the default module to the name given . |
38,353 | private synchronized void setCreator ( ObjectValue newCreator ) { if ( newCreator != null && newCreator . type . getClassdef ( ) instanceof ASystemClassDefinition ) { return ; } newCreator . addChild ( this ) ; } | Sets the creator of this object value and adds this to the newCreator parsed as argument |
38,354 | public void formatTo ( Formatter formatter , int flags , int width , int precision ) { formatTo ( this . toString ( ) , formatter , flags , width , precision ) ; } | This is overridden in the few classes that need to change formatting |
38,355 | public static synchronized void enable ( boolean on ) { for ( IRTLogger logger : loggers ) { logger . enable ( on ) ; } enabled = on ; } | Turns the logging on or off |
38,356 | public static void setLogfile ( Class < ? extends IRTLogger > loggerClass , File outputFile ) throws FileNotFoundException { for ( IRTLogger logger : loggers ) { if ( logger . getClass ( ) == loggerClass ) { logger . setLogfile ( outputFile ) ; logger . dump ( true ) ; } } enable ( true ) ; } | Configure the logger output types |
38,357 | public ISourceParser getSourceParser ( IVdmProject project ) throws CoreException { IConfigurationElement [ ] config = Platform . getExtensionRegistry ( ) . getConfigurationElementsFor ( ICoreConstants . EXTENSION_PARSER_ID ) ; IConfigurationElement selectedParser = getParserWithHeighestPriority ( project . getVdmNature ( ) , config ) ; if ( selectedParser != null ) { final Object o = selectedParser . createExecutableExtension ( "class" ) ; if ( o instanceof AbstractParserParticipant ) { AbstractParserParticipant parser = ( AbstractParserParticipant ) o ; parser . setProject ( project ) ; return parser ; } } return null ; } | Loads a source parser for the given project |
38,358 | private IConfigurationElement getParserWithHeighestPriority ( String natureId , IConfigurationElement [ ] config ) { IConfigurationElement selectedParser = null ; int selectedParserPriority = 0 ; for ( IConfigurationElement e : config ) { if ( e . getAttribute ( "nature" ) . equals ( natureId ) ) { if ( selectedParser == null ) { selectedParser = e ; String selectedParserPriorityString = selectedParser . getAttribute ( "priority" ) ; if ( selectedParserPriorityString != null ) selectedParserPriority = Integer . parseInt ( selectedParserPriorityString ) ; } else { String parserPriorityString = selectedParser . getAttribute ( "priority" ) ; if ( parserPriorityString != null ) { int parserPriority = Integer . parseInt ( parserPriorityString ) ; if ( parserPriority > selectedParserPriority ) { selectedParser = e ; selectedParserPriority = parserPriority ; } } } } } return selectedParser ; } | Gets the parser available for the given nature having the highest priority |
38,359 | public static void parseFile ( final IVdmSourceUnit source ) throws CoreException , IOException { try { ISourceParser parser = SourceParserManager . getInstance ( ) . getSourceParser ( source . getProject ( ) ) ; Assert . isNotNull ( parser , "No parser for file : " + source . toString ( ) + " in project " + source . getProject ( ) . toString ( ) ) ; parser . parse ( source ) ; } catch ( Exception e ) { if ( VdmCore . DEBUG ) { VdmCore . log ( "SourceParseManager-Error in parseFile" , e ) ; } } } | Parse a single file from a project |
38,360 | public synchronized IDbgpService getDbgpService ( int freePort ) { dbgpService = new DbgpService ( freePort ) ; getPluginPreferences ( ) . addPropertyChangeListener ( new DbgpServicePreferenceUpdater ( ) ) ; return dbgpService ; } | Inefficient use getDbgpService |
38,361 | private static int b64decode ( char c ) { int i = c ; if ( i >= 'A' && i <= 'Z' ) { return i - 'A' ; } if ( i >= 'a' && i <= 'z' ) { return i - 'a' + 26 ; } if ( i >= '0' && i <= '9' ) { return i - '0' + 52 ; } if ( i == '+' ) { return 62 ; } if ( i == '/' ) { return 63 ; } return - 1 ; } | Return the 6 - bit value corresponding to a base64 encoded char . If the character is the base64 padding character = - 1 is returned . |
38,362 | private static char b64encode ( int b ) { if ( b >= 0 && b <= 25 ) { return ( char ) ( 'A' + b ) ; } if ( b >= 26 && b <= 51 ) { return ( char ) ( 'a' + b - 26 ) ; } if ( b >= 52 && b <= 61 ) { return ( char ) ( '0' + b - 52 ) ; } if ( b == 62 ) { return '+' ; } if ( b == 63 ) { return '/' ; } return '?' ; } | Encode a 6 - bit quantity as a base64 character . |
38,363 | public static byte [ ] decode ( String text ) throws Exception { if ( text . length ( ) % 4 != 0 ) { throw new Exception ( "Base64 not a multiple of 4 bytes" ) ; } byte [ ] result = new byte [ text . length ( ) / 4 * 3 ] ; int p = 0 ; for ( int i = 0 ; i < text . length ( ) ; ) { if ( text . charAt ( i ) == '\n' ) { continue ; } int b1 = b64decode ( text . charAt ( i ++ ) ) ; int b2 = b64decode ( text . charAt ( i ++ ) ) ; int b3 = b64decode ( text . charAt ( i ++ ) ) ; int b4 = b64decode ( text . charAt ( i ++ ) ) ; if ( b4 >= 0 ) { int three = b4 | b3 << 6 | b2 << 12 | b1 << 18 ; result [ p ++ ] = ( byte ) ( ( three & 0xff0000 ) >> 16 ) ; result [ p ++ ] = ( byte ) ( ( three & 0xff00 ) >> 8 ) ; result [ p ++ ] = ( byte ) ( three & 0xff ) ; } else if ( b3 >= 0 ) { int two = b3 << 6 | b2 << 12 | b1 << 18 ; result [ p ++ ] = ( byte ) ( ( two & 0xff0000 ) >> 16 ) ; result [ p ++ ] = ( byte ) ( ( two & 0xff00 ) >> 8 ) ; } else { int one = b2 << 12 | b1 << 18 ; result [ p ++ ] = ( byte ) ( ( one & 0xff0000 ) >> 16 ) ; } } byte [ ] output = new byte [ p ] ; System . arraycopy ( result , 0 , output , 0 , p ) ; return output ; } | Base64 decode a string into a byte array . |
38,364 | public static StringBuffer encode ( byte [ ] data ) { int rem = data . length % 3 ; int num = data . length / 3 ; StringBuffer result = new StringBuffer ( ) ; int p = 0 ; for ( int i = 0 ; i < num ; i ++ ) { int b1 = ( data [ p ] & 0xfc ) >> 2 ; int b2 = ( data [ p ] & 0x03 ) << 4 | ( data [ p + 1 ] & 0xf0 ) >> 4 ; int b3 = ( data [ p + 1 ] & 0x0f ) << 2 | ( data [ p + 2 ] & 0xc0 ) >> 6 ; int b4 = data [ p + 2 ] & 0x3f ; result . append ( b64encode ( b1 ) ) ; result . append ( b64encode ( b2 ) ) ; result . append ( b64encode ( b3 ) ) ; result . append ( b64encode ( b4 ) ) ; p += 3 ; } switch ( rem ) { case 0 : break ; case 1 : { int b1 = ( data [ p ] & 0xfc ) >> 2 ; int b2 = ( data [ p ] & 0x03 ) << 4 ; result . append ( b64encode ( b1 ) ) ; result . append ( b64encode ( b2 ) ) ; result . append ( '=' ) ; result . append ( '=' ) ; break ; } case 2 : { int b1 = ( data [ p ] & 0xfc ) >> 2 ; int b2 = ( data [ p ] & 0x03 ) << 4 | ( data [ p + 1 ] & 0xf0 ) >> 4 ; int b3 = ( data [ p + 1 ] & 0x0f ) << 2 ; result . append ( b64encode ( b1 ) ) ; result . append ( b64encode ( b2 ) ) ; result . append ( b64encode ( b3 ) ) ; result . append ( '=' ) ; break ; } } return result ; } | Base64 encode a byte array . |
38,365 | public boolean reschedule ( ) { if ( swappedIn != null && swappedIn . getRunState ( ) == RunState . TIMESTEP ) { return false ; } if ( policy . reschedule ( ) ) { ISchedulableThread best = policy . getThread ( ) ; if ( swappedIn != best ) { if ( swappedIn != null ) { RTLogger . log ( new RTThreadSwapMessage ( SwapType . Out , swappedIn , this , 0 , 0 ) ) ; } long delay = SystemClock . getWallTime ( ) - best . getSwapInBy ( ) ; if ( best . getSwapInBy ( ) > 0 && delay > 0 ) { RTLogger . log ( new RTThreadSwapMessage ( SwapType . DelayedIn , best , this , 0 , delay ) ) ; } else { RTLogger . log ( new RTThreadSwapMessage ( SwapType . In , best , this , 0 , 0 ) ) ; } } swappedIn = best ; swappedIn . runslice ( policy . getTimeslice ( ) ) ; switch ( swappedIn . getRunState ( ) ) { case COMPLETE : RTLogger . log ( new RTThreadSwapMessage ( SwapType . Out , swappedIn , this , 0 , 0 ) ) ; RTLogger . log ( new RTThreadKillMessage ( swappedIn , this ) ) ; swappedIn = null ; return true ; case TIMESTEP : return false ; default : return true ; } } else { return false ; } } | may be due to a time step including a swap delay ) . |
38,366 | public Value eval ( ACaseAlternative node , Value val , Context ctxt ) throws AnalysisException { Context evalContext = new Context ( ctxt . assistantFactory , node . getLocation ( ) , "case alternative" , ctxt ) ; try { evalContext . putList ( ctxt . assistantFactory . createPPatternAssistant ( ) . getNamedValues ( node . getPattern ( ) , val , ctxt ) ) ; return node . getResult ( ) . apply ( VdmRuntime . getExpressionEvaluator ( ) , evalContext ) ; } catch ( PatternMatchException e ) { } return null ; } | Utility method for ACaseAlternative |
38,367 | protected Value evalIf ( INode node , ILexLocation ifLocation , PExp testExp , INode thenNode , List < ? extends INode > elseIfNodeList , INode elseNode , Context ctxt ) throws AnalysisException { BreakpointManager . getBreakpoint ( node ) . check ( ifLocation , ctxt ) ; try { if ( testExp . apply ( VdmRuntime . getStatementEvaluator ( ) , ctxt ) . boolValue ( ctxt ) ) { return thenNode . apply ( VdmRuntime . getStatementEvaluator ( ) , ctxt ) ; } else { for ( INode elseif : elseIfNodeList ) { Value r = elseif . apply ( VdmRuntime . getStatementEvaluator ( ) , ctxt ) ; if ( r != null ) { return r ; } } if ( elseNode != null ) { return elseNode . apply ( VdmRuntime . getStatementEvaluator ( ) , ctxt ) ; } return new VoidValue ( ) ; } } catch ( ValueException e ) { return VdmRuntimeError . abort ( ifLocation , e ) ; } } | Utility method to evaluate both if expressions and statements |
38,368 | protected Value evalElseIf ( INode node , ILexLocation location , PExp test , INode then , Context ctxt ) throws AnalysisException { BreakpointManager . getBreakpoint ( node ) . check ( location , ctxt ) ; try { return test . apply ( VdmRuntime . getExpressionEvaluator ( ) , ctxt ) . boolValue ( ctxt ) ? then . apply ( THIS , ctxt ) : null ; } catch ( ValueException e ) { return VdmRuntimeError . abort ( location , e ) ; } } | Utility method to evaluate elseif nodes |
38,369 | public void init ( EvaluatePP inst , long nrf ) { instance = inst ; act = new long [ ( int ) nrf ] ; fin = new long [ ( int ) nrf ] ; req = new long [ ( int ) nrf ] ; active = new long [ ( int ) nrf ] ; waiting = new long [ ( int ) nrf ] ; } | and the number of methods to define the size of the arrays . |
38,370 | public synchronized void entering ( long fnr2 ) { int fnr = ( int ) fnr2 ; requesting ( fnr ) ; try { if ( ! instance . evaluatePP ( fnr ) . booleanValue ( ) ) { waiting ( fnr , + 1 ) ; while ( ! instance . evaluatePP ( fnr ) . booleanValue ( ) ) { this . wait ( ) ; } waiting ( fnr , - 1 ) ; } } catch ( InterruptedException e ) { } activating ( fnr ) ; } | This methods is used to enable the activation of a method . |
38,371 | public void createPageControlsPostconfig ( ) { try { getMainPageButton ( "projectFromArchiveRadio" ) . setSelection ( true ) ; getMainPageButton ( "projectFromArchiveRadio" ) . setEnabled ( false ) ; getMainPageButton ( "projectFromDirectoryRadio" ) . setSelection ( false ) ; getMainPageButton ( "projectFromDirectoryRadio" ) . setEnabled ( false ) ; getMainPageButton ( "browseDirectoriesButton" ) . setEnabled ( false ) ; getMainPageButton ( "browseArchivesButton" ) . setEnabled ( false ) ; invokeMainPageMethod ( "archiveRadioSelected" ) ; Control pathfield = getMainPageField ( "archivePathField" ) ; if ( pathfield instanceof Text ) { ( ( Text ) pathfield ) . setText ( this . inputPath ) ; } else if ( pathfield instanceof Combo ) { ( ( Combo ) pathfield ) . setText ( this . inputPath ) ; } pathfield . setEnabled ( false ) ; } catch ( Exception e ) { VdmUIPlugin . log ( "Failed to configure throug reflection WizardProjectsImportPage" , e ) ; } } | This initializes the page with the graphical selection and sets the input path . The input path must be set prior to the call to this method |
38,372 | public static void init ( ) { try { init ( "vdmj.properties" , Properties . class ) ; } catch ( Exception e ) { System . err . println ( e . getMessage ( ) ) ; } InputStream fis = ConfigBase . class . getResourceAsStream ( "/" + "overture.properties" ) ; if ( fis != null ) { try { java . util . Properties overtureProperties = new java . util . Properties ( ) ; overtureProperties . load ( fis ) ; final String SYSTEM_KEY = "system." ; for ( Entry < Object , Object > entry : overtureProperties . entrySet ( ) ) { String key = entry . getKey ( ) . toString ( ) ; String value = entry . getValue ( ) . toString ( ) ; if ( value . indexOf ( "/" ) != - 1 ) { value = value . replace ( '/' , File . separatorChar ) ; } int index = key . indexOf ( SYSTEM_KEY ) ; if ( index == 0 ) { String newKey = key . substring ( SYSTEM_KEY . length ( ) ) ; System . setProperty ( newKey , value ) ; } } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } } | When the class is initialized we call the ConfigBase init method which uses the properties file passed to update the static fields above . |
38,373 | protected List < AVarDeclIR > replaceArgsWithVars ( SStmIR callStm ) { List < AVarDeclIR > decls = new LinkedList < AVarDeclIR > ( ) ; if ( Settings . dialect != Dialect . VDM_SL ) { return decls ; } List < SExpIR > args = null ; if ( callStm instanceof SCallStmIR ) { args = ( ( SCallStmIR ) callStm ) . getArgs ( ) ; } else if ( callStm instanceof ACallObjectExpStmIR ) { args = ( ( ACallObjectExpStmIR ) callStm ) . getArgs ( ) ; } else { log . error ( "Expected a call statement or call object statement. Got: " + callStm ) ; return decls ; } for ( SExpIR arg : args ) { String argName = getInfo ( ) . getTempVarNameGen ( ) . nextVarName ( traceTrans . getTracePrefixes ( ) . callStmArgNamePrefix ( ) ) ; STypeIR type = arg . getType ( ) ; AVarDeclIR argDecl = getTransAssist ( ) . consDecl ( argName , type . clone ( ) , arg . clone ( ) ) ; argDecl . setFinal ( true ) ; decls . add ( argDecl ) ; getTransAssist ( ) . replaceNodeWith ( arg , getInfo ( ) . getExpAssistant ( ) . consIdVar ( argName , type . clone ( ) ) ) ; } return decls ; } | Assumes dialect is VDM - SL . This method does not work with store lookups for local variables and since code generated VDM - SL traces do not rely on this then it is safe to use this method for this dialect . |
38,374 | protected void collectOpCtxt ( AExplicitOperationDefinition node , IPOContextStack question , Boolean precond ) throws AnalysisException { question . push ( new POOperationDefinitionContext ( node , precond , node . getState ( ) ) ) ; } | Operation processing is identical in extension except for context generation . So a quick trick here . |
38,375 | public ValueList getValues ( PDefinition def , ObjectContext ctxt ) { try { return def . apply ( af . getValuesDefinitionLocator ( ) , ctxt ) ; } catch ( AnalysisException e ) { return null ; } } | Return a list of external values that are read by the definition . |
38,376 | public Value execute ( String line , DBGPReader dbgp ) throws Exception { PExp expr = parseExpression ( line , getDefaultName ( ) ) ; Environment env = getGlobalEnvironment ( ) ; Environment created = new FlatCheckedEnvironment ( assistantFactory , createdDefinitions . asList ( ) , env , NameScope . NAMESANDSTATE ) ; typeCheck ( expr , created ) ; return execute ( expr , dbgp ) ; } | Parse the line passed type check it and evaluate it as an expression in the initial context . |
38,377 | static int decodeDigit ( byte data ) { char charData = ( char ) data ; if ( charData <= 'Z' && charData >= 'A' ) { return charData - 'A' ; } if ( charData <= 'z' && charData >= 'a' ) { return charData - 'a' + 26 ; } if ( charData <= '9' && charData >= '0' ) { return charData - '0' + 52 ; } switch ( charData ) { case '+' : return 62 ; case '/' : return 63 ; default : throw new IllegalArgumentException ( "Invalid char to decode: " + data ) ; } } | This method converts a Base 64 digit to its numeric value . |
38,378 | public ExitStatus run ( ) { synchronized ( DebuggerReader . class ) { println ( "Stopped " + breakpoint ) ; println ( interpreter . getSourceLine ( breakpoint . location ) ) ; try { interpreter . setDefaultName ( breakpoint . location . getModule ( ) ) ; } catch ( Exception e ) { throw new InternalException ( 52 , "Cannot set default name at breakpoint" ) ; } ExitStatus status = super . run ( new Vector < File > ( ) ) ; return status ; } } | This first prints out the current breakpoint source location before calling the superclass run method . The synchronization prevents more than one debugging session on the console . |
38,379 | protected boolean doEvaluate ( String line ) { line = line . substring ( line . indexOf ( ' ' ) + 1 ) ; try { println ( line + " = " + interpreter . evaluate ( line , getFrame ( ) ) ) ; } catch ( ParserException e ) { println ( "Syntax: " + e ) ; } catch ( ContextException e ) { println ( "Runtime: " + e . getMessage ( ) ) ; } catch ( RuntimeException e ) { println ( "Runtime: " + e . getMessage ( ) ) ; } catch ( Exception e ) { println ( "Error: " + e . getMessage ( ) ) ; } return true ; } | Evaluate an expression in the breakpoint s context . This is similar to the superclass method except that the context is the one taken from the breakpoint and the execution is not timed . |
38,380 | private void updateCPUandChildCPUs ( ObjectValue obj , CPUValue cpu ) { if ( cpu != obj . getCPU ( ) ) { for ( ObjectValue superObj : obj . superobjects ) { updateCPUandChildCPUs ( superObj , cpu ) ; } obj . setCPU ( cpu ) ; } for ( ObjectValue objVal : obj . children ) { updateCPUandChildCPUs ( objVal , cpu ) ; } } | Recursively updates all transitive references with the new CPU but without removing the parent - child relation unlike the deploy method . |
38,381 | public static ImageDescriptor getDescriptor ( String key ) { if ( fgImageRegistry == null ) { return fgAvoidSWTErrorMap . get ( key ) ; } return getImageRegistry ( ) . getDescriptor ( key ) ; } | Returns the image descriptor for the given key in this registry . Might be called in a non - UI thread . |
38,382 | private IContainer getActualTarget ( IResource mouseTarget ) { if ( mouseTarget . getType ( ) == IResource . FILE ) { return mouseTarget . getParent ( ) ; } return ( IContainer ) mouseTarget ; } | Returns the actual target of the drop given the resource under the mouse . If the mouse target is a file then the drop actually occurs in its parent . If the drop location is before or after the mouse target and feedback is enabled the target is also the parent . |
38,383 | private IStatus performResourceCopy ( CommonDropAdapter dropAdapter , Shell shell , IResource [ ] sources ) { MultiStatus problems = new MultiStatus ( PlatformUI . PLUGIN_ID , 1 , WorkbenchNavigatorMessages . DropAdapter_problemsMoving , null ) ; mergeStatus ( problems , validateTarget ( dropAdapter . getCurrentTarget ( ) , dropAdapter . getCurrentTransfer ( ) , dropAdapter . getCurrentOperation ( ) ) ) ; IContainer target = null ; if ( dropAdapter . getCurrentTarget ( ) instanceof IVdmContainer ) { target = ( ( IVdmContainer ) dropAdapter . getCurrentTarget ( ) ) . getContainer ( ) ; } else { target = getActualTarget ( ( IResource ) dropAdapter . getCurrentTarget ( ) ) ; } CopyFilesAndFoldersOperation operation = new CopyFilesAndFoldersOperation ( shell ) ; operation . copyResources ( sources , target ) ; return problems ; } | Performs a resource copy |
38,384 | private IStatus performResourceMove ( CommonDropAdapter dropAdapter , IResource [ ] sources ) { MultiStatus problems = new MultiStatus ( PlatformUI . PLUGIN_ID , 1 , WorkbenchNavigatorMessages . DropAdapter_problemsMoving , null ) ; mergeStatus ( problems , validateTarget ( dropAdapter . getCurrentTarget ( ) , dropAdapter . getCurrentTransfer ( ) , dropAdapter . getCurrentOperation ( ) ) ) ; IContainer target = null ; if ( dropAdapter . getCurrentTarget ( ) instanceof IVdmContainer ) { target = ( ( IVdmContainer ) dropAdapter . getCurrentTarget ( ) ) . getContainer ( ) ; } else { target = getActualTarget ( ( IResource ) dropAdapter . getCurrentTarget ( ) ) ; } ReadOnlyStateChecker checker = new ReadOnlyStateChecker ( getShell ( ) , WorkbenchNavigatorMessages . MoveResourceAction_title , WorkbenchNavigatorMessages . MoveResourceAction_checkMoveMessage ) ; sources = checker . checkReadOnlyResources ( sources ) ; MoveFilesAndFoldersOperation operation = new MoveFilesAndFoldersOperation ( getShell ( ) ) ; operation . copyResources ( sources , target ) ; return problems ; } | Performs a resource move |
38,385 | private IStatus performFileDrop ( CommonDropAdapter anAdapter , Object data ) { MultiStatus problems = new MultiStatus ( PlatformUI . PLUGIN_ID , 0 , WorkbenchNavigatorMessages . DropAdapter_problemImporting , null ) ; mergeStatus ( problems , validateTarget ( anAdapter . getCurrentTarget ( ) , anAdapter . getCurrentTransfer ( ) , anAdapter . getCurrentOperation ( ) ) ) ; IContainer target = null ; if ( anAdapter . getCurrentTarget ( ) instanceof IVdmContainer ) { target = ( ( IVdmContainer ) anAdapter . getCurrentTarget ( ) ) . getContainer ( ) ; } else { target = getActualTarget ( ( IResource ) anAdapter . getCurrentTarget ( ) ) ; } final IContainer ftarget = target ; final String [ ] names = ( String [ ] ) data ; Display . getCurrent ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { getShell ( ) . forceActive ( ) ; CopyFilesAndFoldersOperation operation = new CopyFilesAndFoldersOperation ( getShell ( ) ) ; operation . copyFiles ( names , ftarget ) ; } } ) ; return problems ; } | Performs a drop using the FileTransfer transfer type . |
38,386 | private IStatus validateTarget ( Object target , TransferData transferType , int dropOperation ) { if ( target instanceof IVdmContainer ) { target = ( ( IVdmContainer ) target ) . getContainer ( ) ; } if ( ! ( target instanceof IResource ) ) { return WorkbenchNavigatorPlugin . createInfoStatus ( WorkbenchNavigatorMessages . DropAdapter_targetMustBeResource ) ; } IResource resource = ( IResource ) target ; if ( ! resource . isAccessible ( ) ) { return WorkbenchNavigatorPlugin . createErrorStatus ( WorkbenchNavigatorMessages . DropAdapter_canNotDropIntoClosedProject ) ; } IContainer destination = getActualTarget ( resource ) ; if ( destination . getType ( ) == IResource . ROOT ) { return WorkbenchNavigatorPlugin . createErrorStatus ( WorkbenchNavigatorMessages . DropAdapter_resourcesCanNotBeSiblings ) ; } String message = null ; if ( LocalSelectionTransfer . getTransfer ( ) . isSupportedType ( transferType ) ) { IResource [ ] selectedResources = getSelectedResources ( ) ; if ( selectedResources . length == 0 ) { message = WorkbenchNavigatorMessages . DropAdapter_dropOperationErrorOther ; } else { CopyFilesAndFoldersOperation operation ; if ( dropOperation == DND . DROP_COPY ) { operation = new CopyFilesAndFoldersOperation ( getShell ( ) ) ; } else { operation = new MoveFilesAndFoldersOperation ( getShell ( ) ) ; } message = operation . validateDestination ( destination , selectedResources ) ; } } else if ( FileTransfer . getInstance ( ) . isSupportedType ( transferType ) ) { String [ ] sourceNames = ( String [ ] ) FileTransfer . getInstance ( ) . nativeToJava ( transferType ) ; if ( sourceNames == null ) { sourceNames = new String [ 0 ] ; } CopyFilesAndFoldersOperation copyOperation = new CopyFilesAndFoldersOperation ( getShell ( ) ) ; message = copyOperation . validateImportDestination ( destination , sourceNames ) ; } if ( message != null ) { return WorkbenchNavigatorPlugin . createErrorStatus ( message ) ; } return Status . OK_STATUS ; } | Ensures that the drop target meets certain criteria |
38,387 | private void mergeStatus ( MultiStatus status , IStatus toMerge ) { if ( ! toMerge . isOK ( ) ) { status . merge ( toMerge ) ; } } | Adds the given status to the list of problems . Discards OK statuses . If the status is a multi - status only its children are added . |
38,388 | private void openError ( IStatus status ) { if ( status == null ) { return ; } String genericTitle = WorkbenchNavigatorMessages . DropAdapter_title ; int codes = IStatus . ERROR | IStatus . WARNING ; if ( ! status . isMultiStatus ( ) ) { ErrorDialog . openError ( getShell ( ) , genericTitle , null , status , codes ) ; return ; } IStatus [ ] children = status . getChildren ( ) ; if ( children . length == 1 ) { ErrorDialog . openError ( getShell ( ) , status . getMessage ( ) , null , children [ 0 ] , codes ) ; return ; } ErrorDialog . openError ( getShell ( ) , genericTitle , null , status , codes ) ; } | Opens an error dialog if necessary . Takes care of complex rules necessary for making the error dialog look nice . |
38,389 | private AFromModuleImports importAll ( ILexIdentifierToken from ) { List < List < PImport > > types = new Vector < List < PImport > > ( ) ; ILexNameToken all = new LexNameToken ( from . getName ( ) , "all" , from . getLocation ( ) ) ; List < PImport > impAll = new Vector < PImport > ( ) ; AAllImport iport = AstFactory . newAAllImport ( all ) ; iport . setLocation ( all . getLocation ( ) ) ; iport . setName ( all ) ; iport . setRenamed ( all ) ; iport . setFrom ( null ) ; impAll . add ( iport ) ; types . add ( impAll ) ; return AstFactory . newAFromModuleImports ( from , types ) ; } | This function is copied from the module reader |
38,390 | public static String toCpEnvString ( Collection < ? extends String > entries ) { if ( entries . size ( ) > 0 ) { StringBuffer classPath = new StringBuffer ( "" ) ; for ( String cp : new HashSet < String > ( entries ) ) { if ( cp == null ) { continue ; } classPath . append ( cp ) ; classPath . append ( System . getProperty ( "path.separator" ) ) ; } classPath . deleteCharAt ( classPath . length ( ) - 1 ) ; return classPath . toString ( ) . trim ( ) ; } return "" ; } | Creates a class path string from the entries using the path . seperator |
38,391 | private void searchAndLaunch ( Object [ ] scope , String mode , String selectTitle , String emptyMessage ) { INode [ ] types = null ; try { project = findProject ( scope , PlatformUI . getWorkbench ( ) . getProgressService ( ) ) ; ILaunchConfiguration config = findLaunchConfiguration ( project . getName ( ) , getConfigurationType ( ) ) ; if ( config != null ) { launch ( config , mode ) ; return ; } types = findTypes ( scope , PlatformUI . getWorkbench ( ) . getProgressService ( ) ) ; } catch ( InterruptedException e ) { return ; } catch ( CoreException e ) { MessageDialog . openError ( getShell ( ) , LauncherMessages . VdmLaunchShortcut_0 , e . getMessage ( ) ) ; return ; } INode type = null ; if ( types == null || types . length == 0 ) { MessageDialog . openError ( getShell ( ) , LauncherMessages . VdmLaunchShortcut_1 , emptyMessage ) ; } else if ( types . length > 1 ) { type = chooseType ( types , selectTitle ) ; } else { type = types [ 0 ] ; } if ( type != null && project != null ) { launch ( type , mode , project . getName ( ) ) ; } } | Resolves a type that can be launched from the given scope and launches in the specified mode . |
38,392 | protected INode chooseType ( INode [ ] types , String title ) { try { DebugTypeSelectionDialog mmsd = new DebugTypeSelectionDialog ( VdmDebugPlugin . getActiveWorkbenchShell ( ) , types , title , project ) ; if ( mmsd . open ( ) == Window . OK ) { return ( INode ) mmsd . getResult ( ) [ 0 ] ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } return null ; } | Prompts the user to select a type from the given types . |
38,393 | public static InputStreamReader readerFactory ( File file , String charset ) throws IOException { String name = file . getName ( ) ; if ( name . toLowerCase ( ) . endsWith ( ".doc" ) ) { return new DocStreamReader ( new FileInputStream ( file ) , charset ) ; } else if ( name . toLowerCase ( ) . endsWith ( ".docx" ) ) { return new DocxStreamReader ( new FileInputStream ( file ) ) ; } else if ( name . toLowerCase ( ) . endsWith ( ".odt" ) ) { return new ODFStreamReader ( new FileInputStream ( file ) ) ; } else { return new LatexStreamReader ( new FileInputStream ( file ) , charset ) ; } } | Create an InputStreamReader from a File depending on the filename . |
38,394 | public int read ( char [ ] cbuf , int off , int len ) { int n = 0 ; while ( pos != max && n < len ) { cbuf [ off + n ++ ] = data [ pos ++ ] ; } return n == 0 ? - 1 : n ; } | Read characters into the array passed . |
38,395 | public void toFile ( ) throws IOException { if ( logFile != null ) { FileWriter fstream = new FileWriter ( logFile + ".rttxt" ) ; BufferedWriter out = new BufferedWriter ( fstream ) ; writeCPUdecls ( out ) ; writeBUSdecls ( out ) ; writeDeployObjs ( out ) ; writeEvents ( out ) ; out . flush ( ) ; out . close ( ) ; } } | Writing to log |
38,396 | public Context getGlobal ( ) { Context op = this ; while ( op . outer != null ) { op = op . outer ; } return op ; } | Find the outermost context from this one . |
38,397 | public Context deepCopy ( ) { Context below = null ; if ( outer != null ) { below = outer . deepCopy ( ) ; } Context result = new Context ( assistantFactory , location , title , below ) ; result . threadState = threadState ; for ( ILexNameToken var : keySet ( ) ) { Value v = get ( var ) ; result . put ( var , v . deepCopy ( ) ) ; } return result ; } | Make a deep copy of the context using Value . deepCopy . Every concrete subclass must implements its own version of this method . |
38,398 | public Context getVisibleVariables ( ) { Context visible = new Context ( assistantFactory , location , title , null ) ; if ( outer != null ) { visible . putAll ( outer . getVisibleVariables ( ) ) ; } visible . putAll ( this ) ; return visible ; } | Get all visible names from this Context with more visible values overriding those below . |
38,399 | public Value check ( ILexNameToken name ) { Value v = get ( name ) ; if ( v == null ) { if ( outer != null ) { return outer . check ( name ) ; } } return v ; } | Get the value for a given name . This searches outer contexts if any are present . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.