idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
35,300
public static Expr . VariableAccess extractAssignedVariable ( LVal lval ) { if ( lval instanceof Expr . VariableAccess ) { return ( Expr . VariableAccess ) lval ; } else if ( lval instanceof Expr . RecordAccess ) { Expr . RecordAccess e = ( Expr . RecordAccess ) lval ; return extractAssignedVariable ( ( LVal ) e . getOperand ( ) ) ; } else if ( lval instanceof Expr . ArrayAccess ) { Expr . ArrayAccess e = ( Expr . ArrayAccess ) lval ; return extractAssignedVariable ( ( LVal ) e . getFirstOperand ( ) ) ; } else if ( lval instanceof Expr . Dereference ) { return null ; } else { syntaxError ( lval , WyilFile . INVALID_LVAL_EXPRESSION ) ; return null ; } }
Determine the modified variable for a given LVal . Almost all lvals modify exactly one variable though dereferences don t .
35,301
public static boolean isPure ( SyntacticItem item ) { if ( item instanceof Expr . StaticVariableAccess || item instanceof Expr . Dereference || item instanceof Expr . New ) { return false ; } else if ( item instanceof Expr . Invoke ) { Expr . Invoke e = ( Expr . Invoke ) item ; Decl . Link < Decl . Callable > l = e . getLink ( ) ; if ( l . getTarget ( ) instanceof Decl . Method ) { return false ; } } else if ( item instanceof Expr . IndirectInvoke ) { Expr . IndirectInvoke e = ( Expr . IndirectInvoke ) item ; internalFailure ( "purity checking currently does not support indirect invocation" , item ) ; } boolean result = true ; for ( int i = 0 ; i != item . size ( ) ; ++ i ) { result &= isPure ( item . get ( i ) ) ; } return result ; }
Determine whether a given expression calls an impure method dereferences a reference or accesses a static variable . This is done by exploiting the uniform nature of syntactic items . Essentially we just traverse the entire tree representing the syntactic item looking for expressions of any kind .
35,302
private void translateConstantDeclaration ( WyilFile . Decl . StaticVariable decl ) { if ( decl . hasInitialiser ( ) ) { GlobalEnvironment globalEnvironment = new GlobalEnvironment ( decl ) ; LocalEnvironment localEnvironment = new LocalEnvironment ( globalEnvironment ) ; List < VerificationCondition > vcs = new ArrayList < > ( ) ; Context context = new Context ( wyalFile , AssumptionSet . ROOT , localEnvironment , localEnvironment , null , vcs ) ; Pair < Expr , Context > rp = translateExpressionWithChecks ( decl . getInitialiser ( ) , null , context ) ; generateTypeInvariantCheck ( decl . getType ( ) , rp . first ( ) , context ) ; createAssertions ( decl , vcs , globalEnvironment ) ; } }
Translate a constant declaration into WyAL . At the moment this does nothing because constant declarations are not supported in WyAL files .
35,303
private void translateTypeDeclaration ( WyilFile . Decl . Type declaration ) { WyilFile . Tuple < WyilFile . Expr > invariants = declaration . getInvariant ( ) ; WyalFile . Stmt . Block [ ] invariant = new WyalFile . Stmt . Block [ invariants . size ( ) ] ; WyalFile . Type type = convert ( declaration . getType ( ) , declaration ) ; WyalFile . VariableDeclaration var ; if ( invariants . size ( ) > 0 ) { WyilFile . Decl . Variable v = declaration . getVariableDeclaration ( ) ; GlobalEnvironment globalEnvironment = new GlobalEnvironment ( declaration ) ; LocalEnvironment localEnvironment = new LocalEnvironment ( globalEnvironment ) ; var = localEnvironment . read ( v ) ; for ( int i = 0 ; i != invariant . length ; ++ i ) { invariant [ i ] = translateAsBlock ( invariants . get ( i ) , localEnvironment ) ; } } else { var = new WyalFile . VariableDeclaration ( type , new WyalFile . Identifier ( "self" ) ) ; } Name name = declaration . getQualifiedName ( ) . toName ( ) ; WyalFile . Declaration td = new WyalFile . Declaration . Named . Type ( name , var , invariant ) ; allocate ( td , declaration . getParent ( WyilFile . Attribute . Span . class ) ) ; }
Transform a type declaration into verification conditions as necessary . In particular the type should be inhabitable . This means for example that the invariant does not contradict itself . Furthermore we need to translate the type invariant into a macro block .
35,304
private void translateFunctionOrMethodDeclaration ( WyilFile . Decl . FunctionOrMethod declaration ) { createFunctionOrMethodPrototype ( declaration ) ; translatePreconditionMacros ( declaration ) ; translatePostconditionMacros ( declaration ) ; GlobalEnvironment globalEnvironment = new GlobalEnvironment ( declaration ) ; LocalEnvironment localEnvironment = new LocalEnvironment ( globalEnvironment ) ; AssumptionSet assumptions = generateFunctionOrMethodAssumptionSet ( declaration , localEnvironment ) ; List < VerificationCondition > vcs = new ArrayList < > ( ) ; Context context = new Context ( wyalFile , assumptions , localEnvironment , localEnvironment , null , vcs ) ; translateStatementBlock ( declaration . getBody ( ) , context ) ; createAssertions ( declaration , vcs , globalEnvironment ) ; }
Transform a function or method declaration into verification conditions as necessary . This is done by traversing the control - flow graph of the function or method in question . Verifications are emitted when conditions are encountered which must be checked . For example that the preconditions are met at a function invocation .
35,305
private void translatePreconditionMacros ( WyilFile . Decl . FunctionOrMethod declaration ) { Tuple < WyilFile . Expr > invariants = declaration . getRequires ( ) ; for ( int i = 0 ; i != invariants . size ( ) ; ++ i ) { GlobalEnvironment globalEnvironment = new GlobalEnvironment ( declaration ) ; LocalEnvironment localEnvironment = new LocalEnvironment ( globalEnvironment ) ; WyalFile . VariableDeclaration [ ] type = generatePreconditionParameters ( declaration , localEnvironment ) ; WyalFile . Stmt . Block clause = translateAsBlock ( invariants . get ( i ) , localEnvironment ) ; clause = captureFreeVariables ( declaration , globalEnvironment , clause ) ; Name ident = convert ( declaration . getQualifiedName ( ) , "_requires_" + i , declaration . getName ( ) ) ; WyalFile . Declaration md = new WyalFile . Declaration . Named . Macro ( ident , type , clause ) ; allocate ( md , invariants . get ( i ) . getParent ( WyilFile . Attribute . Span . class ) ) ; } }
Translate the sequence of invariant expressions which constitute the precondition of a function or method into corresponding macro declarations .
35,306
private Context translateAssert ( WyilFile . Stmt . Assert stmt , Context context ) { Pair < Expr , Context > p = translateExpressionWithChecks ( stmt . getCondition ( ) , null , context ) ; Expr condition = p . first ( ) ; context = p . second ( ) ; VerificationCondition verificationCondition = new VerificationCondition ( "assertion failed" , context . assumptions , condition , stmt . getCondition ( ) . getParent ( WyilFile . Attribute . Span . class ) ) ; context . emit ( verificationCondition ) ; return context . assume ( condition ) ; }
Translate an assert statement . This emits a verification condition which ensures the assert condition holds given the current context .
35,307
private Context translateAssign ( WyilFile . Stmt . Assign stmt , Context context ) { Tuple < WyilFile . LVal > lhs = stmt . getLeftHandSide ( ) ; Tuple < WyilFile . Expr > rhs = stmt . getRightHandSide ( ) ; WyilFile . LVal [ ] [ ] lvals = new LVal [ rhs . size ( ) ] [ ] ; Expr [ ] [ ] rvals = new Expr [ rhs . size ( ) ] [ ] ; for ( int i = 0 , j = 0 ; i != rhs . size ( ) ; ++ i ) { WyilFile . Expr rval = rhs . get ( i ) ; lvals [ i ] = generateEmptyLValBundle ( rval . getTypes ( ) , lhs , j ) ; j += lvals [ i ] . length ; Pair < Expr [ ] , Context > p = generateRValBundle ( rval , context ) ; rvals [ i ] = p . first ( ) ; context = p . second ( ) ; } for ( int i = 0 ; i != rhs . size ( ) ; ++ i ) { context = translateAssign ( lvals [ i ] , rvals [ i ] , context ) ; } return context ; }
Translate an assign statement . This updates the version number of the underlying assigned variable .
35,308
private Context translateAssign ( WyilFile . LVal [ ] lval , Expr [ ] rval , Context context ) { Expr [ ] ls = new Expr [ lval . length ] ; for ( int i = 0 ; i != ls . length ; ++ i ) { WyilFile . LVal lhs = lval [ i ] ; generateTypeInvariantCheck ( lhs . getType ( ) , rval [ i ] , context ) ; context = translateSingleAssignment ( lval [ i ] , rval [ i ] , context ) ; } return context ; }
Translate an individual assignment from one rval to one or more lvals . If there are multiple lvals then a tuple is created to represent the left - hand side .
35,309
private Context translateSingleAssignment ( WyilFile . LVal lval , Expr rval , Context context ) { switch ( lval . getOpcode ( ) ) { case WyilFile . EXPR_arrayaccess : case WyilFile . EXPR_arrayborrow : return translateArrayAssign ( ( WyilFile . Expr . ArrayAccess ) lval , rval , context ) ; case WyilFile . EXPR_dereference : return translateDereference ( ( WyilFile . Expr . Dereference ) lval , rval , context ) ; case WyilFile . EXPR_recordaccess : case WyilFile . EXPR_recordborrow : return translateRecordAssign ( ( WyilFile . Expr . RecordAccess ) lval , rval , context ) ; case WyilFile . EXPR_variablemove : case WyilFile . EXPR_variablecopy : return translateVariableAssign ( ( WyilFile . Expr . VariableAccess ) lval , rval , context ) ; default : throw new SyntacticException ( "unknown lval encountered (" + lval + ")" , context . getEnclosingFile ( ) . getEntry ( ) , lval ) ; } }
Translate an individual assignment from one rval to exactly one lval .
35,310
private Context translateRecordAssign ( WyilFile . Expr . RecordAccess lval , Expr rval , Context context ) { Pair < Expr , Context > p1 = translateExpressionWithChecks ( lval . getOperand ( ) , null , context ) ; Expr source = p1 . first ( ) ; WyalFile . Identifier field = new WyalFile . Identifier ( lval . getField ( ) . toString ( ) ) ; Expr update = new Expr . RecordUpdate ( source , field , rval ) ; return translateSingleAssignment ( ( WyilFile . LVal ) lval . getOperand ( ) , update , p1 . second ( ) ) ; }
Translate an assignment to a field .
35,311
private Context translateArrayAssign ( WyilFile . Expr . ArrayAccess lval , Expr rval , Context context ) { Pair < Expr , Context > p1 = translateExpressionWithChecks ( lval . getFirstOperand ( ) , null , context ) ; Pair < Expr , Context > p2 = translateExpressionWithChecks ( lval . getSecondOperand ( ) , null , p1 . second ( ) ) ; Expr source = p1 . first ( ) ; Expr index = p2 . first ( ) ; checkExpressionPreconditions ( lval , p2 . second ( ) ) ; Expr . Operator update = new Expr . ArrayUpdate ( source , index , rval ) ; return translateSingleAssignment ( ( LVal ) lval . getFirstOperand ( ) , update , p2 . second ( ) ) ; }
Translate an assignment to an array element .
35,312
private Context translateDereference ( WyilFile . Expr . Dereference lval , Expr rval , Context context ) { Expr e = translateDereference ( lval , context . getEnvironment ( ) ) ; return context . assume ( new Expr . Equal ( e , rval ) ) ; }
Translate an indirect assignment through a reference .
35,313
private Context translateVariableAssign ( WyilFile . Expr . VariableAccess lval , Expr rval , Context context ) { WyilFile . Decl . Variable decl = lval . getVariableDeclaration ( ) ; context = context . havoc ( decl ) ; WyalFile . VariableDeclaration nVersionedVar = context . read ( decl ) ; Expr . VariableAccess var = new Expr . VariableAccess ( nVersionedVar ) ; return context . assume ( new Expr . Equal ( var , rval ) ) ; }
Translate an assignment to a variable
35,314
private WyilFile . Expr . VariableAccess extractAssignedVariable ( WyilFile . LVal lval ) { switch ( lval . getOpcode ( ) ) { case WyilFile . EXPR_arrayaccess : case WyilFile . EXPR_arrayborrow : Expr . ArrayAccess ae = ( Expr . ArrayAccess ) lval ; return extractAssignedVariable ( ( LVal ) ae . getSource ( ) ) ; case WyilFile . EXPR_dereference : return null ; case WyilFile . EXPR_recordaccess : case WyilFile . EXPR_recordborrow : Expr . RecordAccess ar = ( Expr . RecordAccess ) lval ; return extractAssignedVariable ( ( LVal ) ar . getSource ( ) ) ; case WyilFile . EXPR_variablemove : case WyilFile . EXPR_variablecopy : return ( WyilFile . Expr . VariableAccess ) lval ; default : throw new SyntacticException ( "unknown lval encountered (" + lval + ")" , ( ( WyilFile ) lval . getHeap ( ) ) . getEntry ( ) , lval ) ; } }
Determine the variable at the root of a given sequence of assignments or return null if there is no statically determinable variable .
35,315
private Context translateBreak ( WyilFile . Stmt . Break stmt , Context context ) { LoopScope enclosingLoop = context . getEnclosingLoopScope ( ) ; enclosingLoop . addBreakContext ( context ) ; return null ; }
Translate a break statement . This takes the current context and pushes it into the enclosing loop scope . It will then be extracted later and used .
35,316
private Context translateContinue ( WyilFile . Stmt . Continue stmt , Context context ) { LoopScope enclosingLoop = context . getEnclosingLoopScope ( ) ; enclosingLoop . addContinueContext ( context ) ; return null ; }
Translate a continue statement . This takes the current context and pushes it into the enclosing loop scope . It will then be extracted later and used .
35,317
private Context translateDoWhile ( WyilFile . Stmt . DoWhile stmt , Context context ) { WyilFile . Decl . FunctionOrMethod declaration = ( WyilFile . Decl . FunctionOrMethod ) context . getEnvironment ( ) . getParent ( ) . enclosingDeclaration ; translateLoopInvariantMacros ( stmt , declaration , context . wyalFile ) ; LoopScope firstScope = new LoopScope ( ) ; Context beforeFirstBodyContext = context . newLoopScope ( firstScope ) ; Context afterFirstBodyContext = translateStatementBlock ( stmt . getBody ( ) , beforeFirstBodyContext ) ; afterFirstBodyContext = joinDescendants ( beforeFirstBodyContext , afterFirstBodyContext , firstScope . continueContexts ) ; checkLoopInvariant ( "loop invariant may not be established by first iteration" , stmt , afterFirstBodyContext ) ; LoopScope arbitraryScope = new LoopScope ( ) ; Context beforeArbitraryBodyContext = context . newLoopScope ( arbitraryScope ) . havoc ( stmt . getModified ( ) ) ; beforeArbitraryBodyContext = assumeLoopInvariant ( stmt , beforeArbitraryBodyContext ) ; Pair < Expr , Context > p = translateExpressionWithChecks ( stmt . getCondition ( ) , null , beforeArbitraryBodyContext ) ; Expr trueCondition = p . first ( ) ; beforeArbitraryBodyContext = p . second ( ) . assume ( trueCondition ) ; Context afterArbitraryBodyContext = translateStatementBlock ( stmt . getBody ( ) , beforeArbitraryBodyContext ) ; afterArbitraryBodyContext = joinDescendants ( beforeArbitraryBodyContext , afterArbitraryBodyContext , arbitraryScope . continueContexts ) ; checkLoopInvariant ( "loop invariant may not be restored" , stmt , afterArbitraryBodyContext ) ; Context exitContext = context . havoc ( stmt . getModified ( ) ) ; exitContext = assumeLoopInvariant ( stmt , exitContext ) ; Expr falseCondition = invertCondition ( translateExpression ( stmt . getCondition ( ) , null , exitContext . getEnvironment ( ) ) , stmt . getCondition ( ) ) ; exitContext = exitContext . assume ( falseCondition ) ; exitContext = joinDescendants ( context , exitContext , firstScope . breakContexts , arbitraryScope . breakContexts ) ; return exitContext ; }
Translate a DoWhile statement .
35,318
private Context translateFail ( WyilFile . Stmt . Fail stmt , Context context ) { Expr condition = new Expr . Constant ( new Value . Bool ( false ) ) ; VerificationCondition verificationCondition = new VerificationCondition ( "possible panic" , context . assumptions , condition , stmt . getParent ( WyilFile . Attribute . Span . class ) ) ; context . emit ( verificationCondition ) ; return null ; }
Translate a fail statement . Execution should never reach such a statement . Hence we need to emit a verification condition to ensure this is the case .
35,319
private Context translateIf ( WyilFile . Stmt . IfElse stmt , Context context ) { Pair < Expr , Context > p = translateExpressionWithChecks ( stmt . getCondition ( ) , null , context ) ; Expr trueCondition = p . first ( ) ; context = p . second ( ) ; Expr falseCondition = invertCondition ( trueCondition , stmt . getCondition ( ) ) ; Context trueContext = context . assume ( trueCondition ) ; Context falseContext = context . assume ( falseCondition ) ; trueContext = translateStatementBlock ( stmt . getTrueBranch ( ) , trueContext ) ; if ( stmt . hasFalseBranch ( ) ) { falseContext = translateStatementBlock ( stmt . getFalseBranch ( ) , falseContext ) ; } return joinDescendants ( context , new Context [ ] { trueContext , falseContext } ) ; }
Translate an if statement . This translates the true and false branches and then recombines them together to form an updated environment . This is challenging when the environments are updated independently in both branches .
35,320
private Context translateNamedBlock ( WyilFile . Stmt . NamedBlock stmt , Context context ) { return translateStatementBlock ( stmt . getBlock ( ) , context ) ; }
Translate a named block
35,321
private Context translateReturn ( WyilFile . Stmt . Return stmt , Context context ) { Tuple < WyilFile . Expr > returns = stmt . getReturns ( ) ; if ( returns . size ( ) > 0 ) { Pair < Expr [ ] , Context > p = translateExpressionsWithChecks ( returns , context ) ; Expr [ ] exprs = p . first ( ) ; context = p . second ( ) ; generateReturnTypeInvariantCheck ( stmt , exprs , context ) ; generatePostconditionChecks ( stmt , exprs , context ) ; } return null ; }
Translate a return statement . If a return value is given then this must ensure that the post - condition of the enclosing function or method is met
35,322
private void generateReturnTypeInvariantCheck ( WyilFile . Stmt . Return stmt , Expr [ ] exprs , Context context ) { WyilFile . Decl . FunctionOrMethod declaration = ( WyilFile . Decl . FunctionOrMethod ) context . getEnvironment ( ) . getParent ( ) . enclosingDeclaration ; Tuple < WyilFile . Type > returnTypes = declaration . getType ( ) . getReturns ( ) ; for ( int i = 0 ; i != exprs . length ; ++ i ) { WyilFile . Type returnType = returnTypes . get ( i ) ; generateTypeInvariantCheck ( returnType , exprs [ i ] , context ) ; } }
Generate a return type check in the case that it is necessary . For example if the return type contains a type invariant then it is likely to be necessary . However in the special case that the value being returned is already of appropriate type then it is not .
35,323
private void generatePostconditionChecks ( WyilFile . Stmt . Return stmt , Expr [ ] exprs , Context context ) { WyilFile . Decl . FunctionOrMethod declaration = ( WyilFile . Decl . FunctionOrMethod ) context . getEnvironment ( ) . getParent ( ) . enclosingDeclaration ; WyilFile . Tuple < WyilFile . Expr > postcondition = declaration . getEnsures ( ) ; Tuple < WyilFile . Decl . Variable > parameters = declaration . getParameters ( ) ; Tuple < WyilFile . Decl . Variable > returns = declaration . getReturns ( ) ; if ( postcondition . size ( ) > 0 ) { Expr [ ] arguments = new Expr [ parameters . size ( ) + returns . size ( ) ] ; for ( int i = 0 ; i != parameters . size ( ) ; ++ i ) { WyilFile . Decl . Variable var = parameters . get ( i ) ; WyalFile . VariableDeclaration vd = context . readFirst ( var ) ; arguments [ i ] = new Expr . VariableAccess ( vd ) ; } System . arraycopy ( exprs , 0 , arguments , parameters . size ( ) , exprs . length ) ; for ( int i = 0 ; i != postcondition . size ( ) ; ++ i ) { Name ident = convert ( declaration . getQualifiedName ( ) , "_ensures_" + i , declaration . getName ( ) ) ; Expr clause = new Expr . Invoke ( null , ident , null , arguments ) ; context . emit ( new VerificationCondition ( "postcondition may not be satisfied" , context . assumptions , clause , stmt . getParent ( WyilFile . Attribute . Span . class ) ) ) ; } } }
Generate the post - condition checks necessary at a return statement in a function or method .
35,324
private Context translateSwitch ( WyilFile . Stmt . Switch stmt , Context context ) { Tuple < WyilFile . Stmt . Case > cases = stmt . getCases ( ) ; Pair < Expr , Context > p = translateExpressionWithChecks ( stmt . getCondition ( ) , null , context ) ; Expr value = p . first ( ) ; context = p . second ( ) ; WyalFile . Stmt defaultValue = null ; Context [ ] descendants = new Context [ cases . size ( ) + 1 ] ; Context defaultContext = null ; boolean hasDefault = false ; for ( int i = 0 ; i != cases . size ( ) ; ++ i ) { WyilFile . Stmt . Case caSe = cases . get ( i ) ; Context caseContext ; if ( ! caSe . isDefault ( ) ) { WyalFile . Stmt e = null ; for ( WyilFile . Expr constant : caSe . getConditions ( ) ) { Expr v = translateExpression ( constant , null , context . getEnvironment ( ) ) ; e = or ( e , new Expr . Equal ( value , v ) ) ; defaultValue = and ( defaultValue , new Expr . NotEqual ( value , v ) ) ; } caseContext = context . assume ( e ) ; descendants [ i ] = translateStatementBlock ( caSe . getBlock ( ) , caseContext ) ; } else { defaultContext = context . assume ( defaultValue ) ; defaultContext = translateStatementBlock ( caSe . getBlock ( ) , defaultContext ) ; hasDefault = true ; } } if ( ! hasDefault ) { defaultContext = context . assume ( defaultValue ) ; } descendants [ descendants . length - 1 ] = defaultContext ; return joinDescendants ( context , descendants ) ; }
Translate a switch statement .
35,325
private Context translateWhile ( WyilFile . Stmt . While stmt , Context context ) { WyilFile . Decl . FunctionOrMethod declaration = ( WyilFile . Decl . FunctionOrMethod ) context . getEnvironment ( ) . getParent ( ) . enclosingDeclaration ; translateLoopInvariantMacros ( stmt , declaration , context . wyalFile ) ; checkLoopInvariant ( "loop invariant may not hold on entry" , stmt , context ) ; LoopScope scope = new LoopScope ( ) ; Context beforeBodyContext = context . newLoopScope ( scope ) . havoc ( stmt . getModified ( ) ) ; beforeBodyContext = assumeLoopInvariant ( stmt , beforeBodyContext ) ; Pair < Expr , Context > p = translateExpressionWithChecks ( stmt . getCondition ( ) , null , beforeBodyContext ) ; Expr trueCondition = p . first ( ) ; beforeBodyContext = p . second ( ) . assume ( trueCondition ) ; Context afterBodyContext = translateStatementBlock ( stmt . getBody ( ) , beforeBodyContext ) ; afterBodyContext = joinDescendants ( beforeBodyContext , afterBodyContext , scope . continueContexts ) ; checkLoopInvariant ( "loop invariant may not be restored" , stmt , afterBodyContext ) ; Context exitContext = context . havoc ( stmt . getModified ( ) ) ; exitContext = assumeLoopInvariant ( stmt , exitContext ) ; Expr falseCondition = invertCondition ( translateExpression ( stmt . getCondition ( ) , null , exitContext . getEnvironment ( ) ) , stmt . getCondition ( ) ) ; exitContext = exitContext . assume ( falseCondition ) ; exitContext = joinDescendants ( context , exitContext , scope . breakContexts ) ; return exitContext ; }
Translate a While statement .
35,326
private void translateLoopInvariantMacros ( Stmt . Loop stmt , WyilFile . Decl . FunctionOrMethod declaration , WyalFile wyalFile ) { Identifier [ ] prefix = declaration . getQualifiedName ( ) . toName ( ) . getAll ( ) ; Tuple < WyilFile . Expr > loopInvariant = stmt . getInvariant ( ) ; for ( int i = 0 ; i != loopInvariant . size ( ) ; ++ i ) { WyilFile . Expr clause = loopInvariant . get ( i ) ; Name ident = convert ( declaration . getQualifiedName ( ) , "_loopinvariant_" + clause . getIndex ( ) , declaration . getName ( ) ) ; GlobalEnvironment globalEnvironment = new GlobalEnvironment ( declaration ) ; LocalEnvironment localEnvironment = new LocalEnvironment ( globalEnvironment ) ; WyalFile . VariableDeclaration [ ] vars = generateLoopInvariantParameterDeclarations ( stmt , localEnvironment ) ; WyalFile . Stmt . Block e = translateAsBlock ( clause , localEnvironment . clone ( ) ) ; Named . Macro macro = new Named . Macro ( ident , vars , e ) ; wyalFile . allocate ( macro ) ; } }
Translate the sequence of invariant expressions which constitute the loop invariant of a loop into one or more macros
35,327
private Context translateVariableDeclaration ( WyilFile . Decl . Variable stmt , Context context ) { if ( stmt . hasInitialiser ( ) ) { Pair < Expr , Context > p = translateExpressionWithChecks ( stmt . getInitialiser ( ) , null , context ) ; context = p . second ( ) ; generateTypeInvariantCheck ( stmt . getType ( ) , p . first ( ) , context ) ; context = context . write ( stmt , p . first ( ) ) ; } return context ; }
Translate a variable declaration .
35,328
private Expr translateAsUnknown ( WyilFile . Expr expr , LocalEnvironment environment ) { String name = "r" + Integer . toString ( expr . getIndex ( ) ) ; WyalFile . Type type = convert ( expr . getType ( ) , expr ) ; WyalFile . VariableDeclaration vf = allocate ( new WyalFile . VariableDeclaration ( type , new WyalFile . Identifier ( name ) ) , null ) ; return new Expr . VariableAccess ( vf ) ; }
Translating as unknown basically means we re not representing the operation in question at the verification level . This could be something that we ll implement in the future or maybe not .
35,329
private WyalFile . VariableDeclaration [ ] generateQuantifierTypePattern ( WyilFile . Expr . Quantifier expr , LocalEnvironment environment ) { Tuple < WyilFile . Decl . Variable > params = expr . getParameters ( ) ; WyalFile . VariableDeclaration [ ] vardecls = new WyalFile . VariableDeclaration [ params . size ( ) ] ; for ( int i = 0 ; i != params . size ( ) ; ++ i ) { WyilFile . Decl . Variable var = params . get ( i ) ; vardecls [ i ] = environment . read ( var ) ; } return vardecls ; }
Generate a type pattern representing the type and name of all quantifier variables described by this quantifier .
35,330
private WyalFile . Stmt implies ( WyalFile . Stmt antecedent , WyalFile . Stmt consequent ) { if ( antecedent == null ) { return consequent ; } else { WyalFile . Stmt . Block antecedentBlock = new WyalFile . Stmt . Block ( antecedent ) ; WyalFile . Stmt . Block consequentBlock = new WyalFile . Stmt . Block ( consequent ) ; return new WyalFile . Stmt . IfThen ( antecedentBlock , consequentBlock ) ; } }
Construct an implication from one expression to another
35,331
private WyalFile . Stmt and ( WyalFile . Stmt lhs , WyalFile . Stmt rhs ) { if ( lhs == null ) { return rhs ; } else if ( rhs == null ) { return rhs ; } else { return new WyalFile . Stmt . Block ( lhs , rhs ) ; } }
Construct a conjunction of two expressions
35,332
private WyalFile . Stmt or ( WyalFile . Stmt lhs , WyalFile . Stmt rhs ) { if ( lhs == null ) { return rhs ; } else if ( rhs == null ) { return rhs ; } else { WyalFile . Stmt . Block lhsBlock = new WyalFile . Stmt . Block ( lhs ) ; WyalFile . Stmt . Block rhsBlock = new WyalFile . Stmt . Block ( rhs ) ; return new WyalFile . Stmt . CaseOf ( lhsBlock , rhsBlock ) ; } }
Construct a disjunct of two expressions
35,333
private AssumptionSet updateVariableVersions ( AssumptionSet assumptions , LocalEnvironment original , LocalEnvironment updated ) { for ( Map . Entry < WyilFile . Decl . Variable , WyalFile . VariableDeclaration > e : updated . locals . entrySet ( ) ) { WyilFile . Decl . Variable var = e . getKey ( ) ; WyalFile . VariableDeclaration newVarVersionedName = e . getValue ( ) ; WyalFile . VariableDeclaration oldVarVersionedName = original . read ( var ) ; if ( ! oldVarVersionedName . equals ( newVarVersionedName ) ) { Expr . VariableAccess oldVar = new Expr . VariableAccess ( oldVarVersionedName ) ; Expr . VariableAccess newVar = new Expr . VariableAccess ( newVarVersionedName ) ; assumptions = assumptions . add ( new Expr . Equal ( newVar , oldVar ) ) ; } } return assumptions ; }
Bring a given assumption set which is consistent with an original environment up - to - date with a new environment .
35,334
private LocalEnvironment joinEnvironments ( Context ... contexts ) { Context head = contexts [ 0 ] ; GlobalEnvironment global = head . getEnvironment ( ) . getParent ( ) ; HashSet < WyilFile . Decl . Variable > modified = new HashSet < > ( ) ; HashSet < WyilFile . Decl . Variable > deleted = new HashSet < > ( ) ; Map < WyilFile . Decl . Variable , WyalFile . VariableDeclaration > headLocals = head . environment . locals ; for ( int i = 1 ; i < contexts . length ; ++ i ) { Context ithContext = contexts [ i ] ; Map < WyilFile . Decl . Variable , WyalFile . VariableDeclaration > ithLocals = ithContext . environment . locals ; for ( Map . Entry < WyilFile . Decl . Variable , WyalFile . VariableDeclaration > e : ithLocals . entrySet ( ) ) { WyilFile . Decl . Variable key = e . getKey ( ) ; WyalFile . VariableDeclaration s1 = e . getValue ( ) ; WyalFile . VariableDeclaration s2 = headLocals . get ( key ) ; if ( s1 == null ) { deleted . add ( key ) ; } else if ( ! s1 . equals ( s2 ) ) { modified . add ( key ) ; } } for ( Map . Entry < WyilFile . Decl . Variable , WyalFile . VariableDeclaration > e : headLocals . entrySet ( ) ) { WyilFile . Decl . Variable key = e . getKey ( ) ; WyalFile . VariableDeclaration s1 = e . getValue ( ) ; WyalFile . VariableDeclaration s2 = ithLocals . get ( key ) ; if ( s1 == null ) { deleted . add ( key ) ; } else if ( ! s1 . equals ( s2 ) ) { modified . add ( key ) ; } } } IdentityHashMap < WyilFile . Decl . Variable , WyalFile . VariableDeclaration > combinedLocals = new IdentityHashMap < > ( ) ; for ( Map . Entry < WyilFile . Decl . Variable , WyalFile . VariableDeclaration > e : headLocals . entrySet ( ) ) { WyilFile . Decl . Variable key = e . getKey ( ) ; WyalFile . VariableDeclaration value = e . getValue ( ) ; if ( deleted . contains ( key ) ) { continue ; } else if ( modified . contains ( key ) ) { value = global . allocateVersion ( key ) ; } combinedLocals . put ( key , value ) ; } return new LocalEnvironment ( global , combinedLocals ) ; }
Join the local environments of one or more context s together . This means retaining variable versions which are the same for all context s allocating new versions for those which are different in at least one case and removing those which aren t present it at least one .
35,335
private void createFunctionOrMethodPrototype ( WyilFile . Decl . FunctionOrMethod declaration ) { Tuple < WyilFile . Decl . Variable > params = declaration . getParameters ( ) ; Tuple < WyilFile . Decl . Variable > returns = declaration . getReturns ( ) ; WyalFile . VariableDeclaration [ ] parameters = new WyalFile . VariableDeclaration [ params . size ( ) ] ; for ( int i = 0 ; i != params . size ( ) ; ++ i ) { WyilFile . Decl . Variable var = params . get ( i ) ; WyalFile . Type parameterType = convert ( var . getType ( ) , declaration ) ; WyalFile . Identifier parameterName = new WyalFile . Identifier ( var . getName ( ) . get ( ) ) ; parameters [ i ] = new WyalFile . VariableDeclaration ( parameterType , parameterName ) ; } WyalFile . VariableDeclaration [ ] wyalReturns = new WyalFile . VariableDeclaration [ returns . size ( ) ] ; for ( int i = 0 ; i != returns . size ( ) ; ++ i ) { WyilFile . Decl . Variable var = returns . get ( i ) ; WyalFile . Type returnType = convert ( var . getType ( ) , declaration ) ; WyalFile . Identifier returnName = new WyalFile . Identifier ( var . getName ( ) . get ( ) ) ; wyalReturns [ i ] = new WyalFile . VariableDeclaration ( returnType , returnName ) ; } Name name = declaration . getQualifiedName ( ) . toName ( ) ; wyalFile . allocate ( new Declaration . Named . Function ( name , parameters , wyalReturns ) ) ; }
Construct a function or method prototype with a given name and type . The function or method can then be called elsewhere as an uninterpreted function . The function or method doesn t have a body but is used as a name to be referred to from assertions .
35,336
private void createAssertions ( WyilFile . Decl declaration , List < VerificationCondition > vcs , GlobalEnvironment environment ) { for ( int i = 0 ; i != vcs . size ( ) ; ++ i ) { VerificationCondition vc = vcs . get ( i ) ; WyalFile . Stmt . Block verificationCondition = buildVerificationCondition ( declaration , environment , vc ) ; Decl . Unit unit = declaration . getAncestor ( Decl . Unit . class ) ; Path . ID id = Trie . fromString ( unit . getName ( ) . toString ( ) . replaceAll ( "::" , "/" ) ) ; WyalFile . Declaration . Assert assrt = new WyalFile . Declaration . Assert ( verificationCondition , vc . description , id , WhileyFile . ContentType ) ; allocate ( assrt , vc . getSpan ( ) ) ; } }
Turn each verification condition into an assertion in the underlying WyalFile being generated . The main challenge here is to ensure that all variables used in the assertion are properly typed .
35,337
public WyalFile . Stmt . Block buildVerificationCondition ( WyilFile . Decl declaration , GlobalEnvironment environment , VerificationCondition vc ) { WyalFile . Stmt antecedent = flatten ( vc . antecedent ) ; Expr consequent = vc . consequent ; HashSet < WyalFile . VariableDeclaration > freeVariables = new HashSet < > ( ) ; freeVariables ( antecedent , freeVariables ) ; freeVariables ( consequent , freeVariables ) ; Expr aliases = determineVariableAliases ( environment , freeVariables ) ; WyalFile . Stmt verificationCondition = implies ( and ( aliases , antecedent ) , vc . consequent ) ; if ( freeVariables . size ( ) > 0 ) { WyalFile . VariableDeclaration [ ] parameters = freeVariables . toArray ( new WyalFile . VariableDeclaration [ freeVariables . size ( ) ] ) ; WyalFile . Stmt . Block qfBody = new WyalFile . Stmt . Block ( verificationCondition ) ; verificationCondition = new WyalFile . Stmt . UniversalQuantifier ( parameters , qfBody ) ; } return new WyalFile . Stmt . Block ( verificationCondition ) ; }
Construct a fully typed and quantified expression for representing a verification condition . Aside from flattening the various components it must also determine appropriate variable types including those for aliased variables .
35,338
private WyalFile . Stmt flatten ( AssumptionSet assumptions ) { WyalFile . Stmt result = flattenUpto ( assumptions , null ) ; if ( result == null ) { return new Expr . Constant ( new Value . Bool ( true ) ) ; } else { return result ; } }
Flatten a given assumption set into a single logical condition . The key challenge here is to try and do this as efficiency as possible .
35,339
private WyalFile . Stmt flattenUpto ( AssumptionSet assumptions , AssumptionSet ancestor ) { if ( assumptions == ancestor ) { return null ; } else { AssumptionSet [ ] parents = assumptions . parents ; WyalFile . Stmt e = null ; switch ( parents . length ) { case 0 : break ; case 1 : e = flattenUpto ( parents [ 0 ] , ancestor ) ; break ; default : AssumptionSet lca = assumptions . commonAncestor ; WyalFile . Stmt factor = flattenUpto ( lca , ancestor ) ; for ( int i = 0 ; i != parents . length ; ++ i ) { e = or ( e , flattenUpto ( parents [ i ] , lca ) ) ; } e = and ( factor , e ) ; } WyalFile . Stmt [ ] local = assumptions . assumptions ; for ( int i = 0 ; i != local . length ; ++ i ) { e = and ( e , local [ i ] ) ; } return e ; } }
Flatten an assumption set upto a given ancestor . That is do not include the ancestor or any of its ancestors in the results . This is a little like taking the difference of the given assumptions and the given ancestor s assumptions .
35,340
private Expr determineVariableAliases ( GlobalEnvironment environment , Set < WyalFile . VariableDeclaration > freeVariables ) { Expr aliases = null ; for ( WyalFile . VariableDeclaration var : freeVariables ) { WyalFile . VariableDeclaration parent = environment . getParent ( var ) ; if ( parent != null ) { Expr . VariableAccess lhs = new Expr . VariableAccess ( var ) ; Expr . VariableAccess rhs = new Expr . VariableAccess ( parent ) ; Expr aliasEquality = new Expr . Equal ( lhs , rhs ) ; aliases = and ( aliases , aliasEquality ) ; } } return aliases ; }
Determine any variable aliases which need to be accounted for . This is done by adding an equality between the aliased variables to ensure they have the same value .
35,341
private WyalFile . VariableDeclaration [ ] generatePreconditionParameters ( WyilFile . Decl . Callable declaration , LocalEnvironment environment ) { Tuple < WyilFile . Decl . Variable > params = declaration . getParameters ( ) ; WyalFile . VariableDeclaration [ ] vars = new WyalFile . VariableDeclaration [ params . size ( ) ] ; for ( int i = 0 ; i != params . size ( ) ; ++ i ) { WyilFile . Decl . Variable var = params . get ( i ) ; vars [ i ] = environment . read ( var ) ; } return vars ; }
Convert the parameter types for a given function or method declaration into a corresponding list of type patterns . This is primarily useful for generating declarations from functions or method .
35,342
private WyalFile . VariableDeclaration [ ] generatePostconditionTypePattern ( WyilFile . Decl . FunctionOrMethod declaration , LocalEnvironment environment ) { Tuple < Decl . Variable > params = declaration . getParameters ( ) ; Tuple < Decl . Variable > returns = declaration . getReturns ( ) ; WyalFile . VariableDeclaration [ ] vars = new WyalFile . VariableDeclaration [ params . size ( ) + returns . size ( ) ] ; for ( int i = 0 ; i != params . size ( ) ; ++ i ) { WyilFile . Decl . Variable var = params . get ( i ) ; vars [ i ] = environment . read ( var ) ; } for ( int i = 0 ; i != returns . size ( ) ; ++ i ) { WyilFile . Decl . Variable var = returns . get ( i ) ; vars [ i + params . size ( ) ] = environment . read ( var ) ; } return vars ; }
Convert the return types for a given function or method declaration into a corresponding list of type patterns . This is primarily useful for generating declarations from functions or method .
35,343
private WyalFile . VariableDeclaration [ ] generateLoopInvariantParameterDeclarations ( Stmt . Loop loop , LocalEnvironment environment ) { Tuple < Decl . Variable > modified = determineUsedVariables ( loop . getInvariant ( ) ) ; WyalFile . VariableDeclaration [ ] vars = new WyalFile . VariableDeclaration [ modified . size ( ) ] ; for ( int i = 0 ; i != modified . size ( ) ; ++ i ) { WyilFile . Decl . Variable var = modified . get ( i ) ; vars [ i ] = environment . read ( var ) ; } return vars ; }
Convert the types of local variables in scope at a given position within a function or method into a type pattern . This is primarily useful for determining the types for a loop invariant macro .
35,344
public Tuple < Decl . Variable > determineUsedVariables ( Tuple < WyilFile . Expr > exprs ) { HashSet < Decl . Variable > used = new HashSet < > ( ) ; usedVariableExtractor . visitExpressions ( exprs , used ) ; return new Tuple < > ( used ) ; }
Determine the set of used variables in a given set of expressions . A used variable is one referred to by a VariableAccess expression .
35,345
public WyalFile . Name convert ( QualifiedName id , SyntacticItem context ) { return convert ( id . getUnit ( ) , id . getName ( ) . get ( ) , context ) ; }
Convert a Name identifier from a WyIL into one suitable for a WyAL file .
35,346
public WyalFile . Name convert ( QualifiedName id , String suffix , SyntacticItem context ) { return convert ( id . getUnit ( ) , id . getName ( ) . get ( ) . concat ( suffix ) , context ) ; }
Convert a qualified name along with an additional suffix into one suitable for a WyAL file .
35,347
private static boolean typeMayHaveInvariant ( Type type , Context context ) { if ( type instanceof Type . Void ) { return false ; } else if ( type instanceof Type . Null ) { return false ; } else if ( type instanceof Type . Bool ) { return false ; } else if ( type instanceof Type . Byte ) { return false ; } else if ( type instanceof Type . Int ) { return false ; } else if ( type instanceof Type . Array ) { Type . Array lt = ( Type . Array ) type ; return typeMayHaveInvariant ( lt . getElement ( ) , context ) ; } else if ( type instanceof Type . Record ) { Type . Record rt = ( Type . Record ) type ; Tuple < Type . Field > fields = rt . getFields ( ) ; for ( int i = 0 ; i != fields . size ( ) ; ++ i ) { Type . Field field = fields . get ( i ) ; if ( typeMayHaveInvariant ( field . getType ( ) , context ) ) { return true ; } } return false ; } else if ( type instanceof Type . Reference ) { Type . Reference lt = ( Type . Reference ) type ; return typeMayHaveInvariant ( lt . getElement ( ) , context ) ; } else if ( type instanceof Type . Union ) { Type . Union t = ( Type . Union ) type ; for ( int i = 0 ; i != t . size ( ) ; ++ i ) { if ( typeMayHaveInvariant ( t . get ( i ) , context ) ) { return true ; } } return false ; } else if ( type instanceof Type . Callable ) { Type . Callable ft = ( Type . Callable ) type ; return typeMayHaveInvariant ( ft . getParameters ( ) , context ) || typeMayHaveInvariant ( ft . getReturns ( ) , context ) ; } else if ( type instanceof Type . Nominal ) { Type . Nominal nt = ( Type . Nominal ) type ; return true ; } else if ( type instanceof Type . Variable ) { return true ; } else { throw new RuntimeException ( "unknown type encountered (" + type + ")" ) ; } }
Perform a simple check to see whether or not a given type may have an invariant or not .
35,348
public void freeVariables ( SyntacticItem e , Set < WyalFile . VariableDeclaration > freeVars ) { if ( e instanceof Expr . VariableAccess ) { Expr . VariableAccess va = ( Expr . VariableAccess ) e ; freeVars . add ( va . getVariableDeclaration ( ) ) ; } else if ( e instanceof Expr . Quantifier ) { Expr . Quantifier q = ( Expr . Quantifier ) e ; freeVariables ( q . getBody ( ) , freeVars ) ; for ( WyalFile . VariableDeclaration vd : q . getParameters ( ) ) { freeVars . remove ( vd ) ; } } else { for ( int i = 0 ; i != e . size ( ) ; ++ i ) { SyntacticItem item = e . get ( i ) ; if ( item != null ) { freeVariables ( item , freeVars ) ; } } } }
Determine all free variables which are used within the given expression . A free variable is one which is not bound within the expression itself .
35,349
private static < T > T [ ] removeNull ( T [ ] items ) { int count = 0 ; for ( int i = 0 ; i != items . length ; ++ i ) { if ( items [ i ] == null ) { count = count + 1 ; } } if ( count == 0 ) { return items ; } else { T [ ] rs = java . util . Arrays . copyOf ( items , items . length - count ) ; for ( int i = 0 , j = 0 ; i != items . length ; ++ i ) { T item = items [ i ] ; if ( item != null ) { rs [ j ++ ] = item ; } } return rs ; } }
Create exact copy of a given array but with evey null element removed .
35,350
private boolean isApplicable ( Type . Callable candidate , LifetimeRelation lifetimes , Tuple < ? extends SemanticType > args ) { Tuple < Type > parameters = candidate . getParameters ( ) ; if ( parameters . size ( ) != args . size ( ) ) { return false ; } else { for ( int i = 0 ; i != args . size ( ) ; ++ i ) { SemanticType param = parameters . get ( i ) ; if ( ! subtypeOperator . isSubtype ( param , args . get ( i ) , lifetimes ) ) { return false ; } } return true ; } }
Determine whether a given function or method declaration is applicable to a given set of argument types . If there number of arguments differs it s definitely not applicable . Otherwise we need every argument type to be a subtype of its corresponding parameter type .
35,351
private Binding selectCallableCandidate ( Name name , List < Binding > candidates , LifetimeRelation lifetimes ) { Binding best = null ; Type . Callable bestType = null ; boolean bestValidWinner = false ; for ( int i = 0 ; i != candidates . size ( ) ; ++ i ) { Binding candidate = candidates . get ( i ) ; Type . Callable candidateType = candidate . getConcreteType ( ) ; if ( best == null ) { best = candidate ; bestType = candidateType ; bestValidWinner = true ; } else { boolean csubb = isSubtype ( bestType , candidateType , lifetimes ) ; boolean bsubc = isSubtype ( candidateType , bestType , lifetimes ) ; if ( csubb && ! bsubc ) { best = candidate ; bestType = candidate . getConcreteType ( ) ; bestValidWinner = true ; } else if ( bsubc && ! csubb ) { } else if ( ! csubb && ! bsubc ) { return null ; } else { bestValidWinner = false ; } } } return bestValidWinner ? best : null ; }
Given a list of candidate function or method declarations determine the most precise match for the supplied argument types . The given argument types must be applicable to this function or macro declaration and it must be a subtype of all other applicable candidates .
35,352
private boolean isSubtype ( Type . Callable lhs , Type . Callable rhs , LifetimeRelation lifetimes ) { Tuple < Type > parentParams = lhs . getParameters ( ) ; Tuple < Type > childParams = rhs . getParameters ( ) ; if ( parentParams . size ( ) != childParams . size ( ) ) { return false ; } for ( int i = 0 ; i != parentParams . size ( ) ; ++ i ) { SemanticType parentParam = parentParams . get ( i ) ; SemanticType childParam = childParams . get ( i ) ; if ( ! subtypeOperator . isSubtype ( parentParam , childParam , lifetimes ) ) { return false ; } } return true ; }
Check whether the type signature for a given function or method declaration is a super type of a given child declaration .
35,353
private static int extractNonMatchingFields ( Tuple < Type . Field > lhsFields , Tuple < Type . Field > rhsFields , Type . Field [ ] result , int index ) { outer : for ( int i = 0 ; i != lhsFields . size ( ) ; ++ i ) { for ( int j = 0 ; j != rhsFields . size ( ) ; ++ j ) { Type . Field lhsField = lhsFields . get ( i ) ; Type . Field rhsField = rhsFields . get ( j ) ; Identifier lhsFieldName = lhsField . getName ( ) ; Identifier rhsFieldName = rhsField . getName ( ) ; if ( lhsFieldName . equals ( rhsFieldName ) ) { continue outer ; } } result [ index ++ ] = lhsFields . get ( i ) ; } return index ; }
Extract fields from lhs which do not match any field in the rhs . That is there is no field in the rhs with the same name .
35,354
public boolean apply ( ) { List < Patch > patches = resolver . apply ( target ) ; while ( patches . size ( ) > 0 ) { Importer importer = new Importer ( target , true ) ; for ( int i = 0 ; i != patches . size ( ) ; ++ i ) { patches . get ( i ) . apply ( importer ) ; } patches = importer . getPatches ( ) ; } symbolTable . consolidate ( ) ; return status ; }
Apply this name resolver to a given WyilFile .
35,355
private List < WyilFile > getExternals ( ) throws IOException { ArrayList < WyilFile > externals = new ArrayList < > ( ) ; List < Build . Package > pkgs = project . getPackages ( ) ; for ( int i = 0 ; i != pkgs . size ( ) ; ++ i ) { Build . Package p = pkgs . get ( i ) ; List < Path . Entry < WyilFile > > entries = p . getRoot ( ) . get ( Content . filter ( "**/*" , WyilFile . ContentType ) ) ; for ( int j = 0 ; j != entries . size ( ) ; ++ j ) { externals . add ( entries . get ( j ) . read ( ) ) ; } } return externals ; }
Read in all external packages so they can be used for name resolution . This amounts to loading in every WyilFile contained within an external package dependency .
35,356
public void checkTypeDeclaration ( Decl . Type decl ) { Environment environment = new Environment ( ) ; checkContractive ( decl ) ; checkVariableDeclaration ( decl . getVariableDeclaration ( ) , environment ) ; checkConditions ( decl . getInvariant ( ) , true , environment ) ; }
Resolve types for a given type declaration . If an invariant expression is given then we have to check and resolve types throughout the expression .
35,357
public void checkStaticVariableDeclaration ( Decl . StaticVariable decl ) { Environment environment = new Environment ( ) ; checkVariableDeclaration ( decl , environment ) ; }
check and check types for a given constant declaration .
35,358
public void checkFunctionOrMethodDeclaration ( Decl . FunctionOrMethod d ) { Environment environment = new Environment ( ) ; environment = FlowTypeUtils . declareThisWithin ( d , environment ) ; checkVariableDeclarations ( d . getParameters ( ) , environment ) ; checkVariableDeclarations ( d . getReturns ( ) , environment ) ; checkConditions ( d . getRequires ( ) , true , environment ) ; checkConditions ( d . getEnsures ( ) , true , environment ) ; if ( d . getModifiers ( ) . match ( Modifier . Native . class ) == null ) { EnclosingScope scope = new FunctionOrMethodScope ( d ) ; Environment last = checkBlock ( d . getBody ( ) , environment , scope ) ; checkReturnValue ( d , last ) ; } else { } }
Type check a given function or method declaration .
35,359
private void checkReturnValue ( Decl . FunctionOrMethod d , Environment last ) { if ( d . match ( Modifier . Native . class ) == null && last != FlowTypeUtils . BOTTOM && d . getReturns ( ) . size ( ) != 0 ) { syntaxError ( d , MISSING_RETURN_STATEMENT ) ; } }
Check that a return value is provided when it is needed . For example a return value is not required for a method that has no return type . Likewise we don t expect one from a native method since there was no body to analyse .
35,360
private Environment checkBlock ( Stmt . Block block , Environment environment , EnclosingScope scope ) { for ( int i = 0 ; i != block . size ( ) ; ++ i ) { Stmt stmt = block . get ( i ) ; environment = checkStatement ( stmt , environment , scope ) ; } return environment ; }
check type information in a flow - sensitive fashion through a block of statements whilst type checking each statement and expression .
35,361
private Environment checkFail ( Stmt . Fail stmt , Environment environment , EnclosingScope scope ) { return FlowTypeUtils . BOTTOM ; }
Type check a fail statement . The environment after a fail statement is bottom because that represents an unreachable program point .
35,362
private Environment checkVariableDeclarations ( Tuple < Decl . Variable > decls , Environment environment ) { for ( int i = 0 ; i != decls . size ( ) ; ++ i ) { environment = checkVariableDeclaration ( decls . get ( i ) , environment ) ; } return environment ; }
Type check a given sequence of variable declarations .
35,363
private Environment checkVariableDeclaration ( Decl . Variable decl , Environment environment ) { checkNonEmpty ( decl , environment ) ; if ( decl . hasInitialiser ( ) ) { SemanticType type = checkExpression ( decl . getInitialiser ( ) , environment ) ; checkIsSubtype ( decl . getType ( ) , type , environment , decl . getInitialiser ( ) ) ; } return environment ; }
Type check a variable declaration statement . In particular when an initialiser is given we must check it is well - formed and that it is a subtype of the declared type .
35,364
private Environment checkAssign ( Stmt . Assign stmt , Environment environment , EnclosingScope scope ) throws IOException { Tuple < LVal > lvals = stmt . getLeftHandSide ( ) ; Type [ ] types = new Type [ lvals . size ( ) ] ; for ( int i = 0 ; i != lvals . size ( ) ; ++ i ) { types [ i ] = checkLVal ( lvals . get ( i ) , environment ) ; } checkMultiExpressions ( stmt . getRightHandSide ( ) , environment , new Tuple < > ( types ) ) ; return environment ; }
Type check an assignment statement .
35,365
private Environment checkBreak ( Stmt . Break stmt , Environment environment , EnclosingScope scope ) { return FlowTypeUtils . BOTTOM ; }
Type check a break statement . This requires propagating the current environment to the block destination to ensure that the actual types of all variables at that point are precise .
35,366
private Environment checkContinue ( Stmt . Continue stmt , Environment environment , EnclosingScope scope ) { return FlowTypeUtils . BOTTOM ; }
Type check a continue statement . This requires propagating the current environment to the block destination to ensure that the actual types of all variables at that point are precise .
35,367
private Environment checkDebug ( Stmt . Debug stmt , Environment environment , EnclosingScope scope ) { Type std_ascii = new Type . Array ( Type . Int ) ; SemanticType type = checkExpression ( stmt . getOperand ( ) , environment ) ; checkIsSubtype ( std_ascii , type , environment , stmt . getOperand ( ) ) ; return environment ; }
Type check an assume statement . This requires checking that the expression being printed is well - formed and has string type .
35,368
private Environment checkDoWhile ( Stmt . DoWhile stmt , Environment environment , EnclosingScope scope ) { environment = checkBlock ( stmt . getBody ( ) , environment , scope ) ; checkConditions ( stmt . getInvariant ( ) , true , environment ) ; Tuple < Decl . Variable > modified = FlowTypeUtils . determineModifiedVariables ( stmt . getBody ( ) ) ; stmt . setModified ( stmt . getHeap ( ) . allocate ( modified ) ) ; return checkCondition ( stmt . getCondition ( ) , false , environment ) ; }
Type check a do - while statement .
35,369
public Type checkLVal ( LVal lval , Environment environment ) { Type type ; switch ( lval . getOpcode ( ) ) { case EXPR_variablecopy : type = checkVariableLVal ( ( Expr . VariableAccess ) lval , environment ) ; break ; case EXPR_staticvariable : type = checkStaticVariableLVal ( ( Expr . StaticVariableAccess ) lval , environment ) ; break ; case EXPR_arrayaccess : case EXPR_arrayborrow : type = checkArrayLVal ( ( Expr . ArrayAccess ) lval , environment ) ; break ; case EXPR_recordaccess : case EXPR_recordborrow : type = checkRecordLVal ( ( Expr . RecordAccess ) lval , environment ) ; break ; case EXPR_dereference : type = checkDereferenceLVal ( ( Expr . Dereference ) lval , environment ) ; break ; default : return internalFailure ( "unknown lval encountered (" + lval . getClass ( ) . getSimpleName ( ) + ")" , lval ) ; } if ( type != null ) { lval . setType ( lval . getHeap ( ) . allocate ( type ) ) ; } return type ; }
Type check a given lval assuming an initial environment . This returns the largest type which can be safely assigned to the lval . Observe that this type is determined by the declared type of the variable being assigned .
35,370
public final void checkMultiExpressions ( Tuple < Expr > expressions , Environment environment , Tuple < Type > expected ) { for ( int i = 0 , j = 0 ; i != expressions . size ( ) ; ++ i ) { Expr expression = expressions . get ( i ) ; switch ( expression . getOpcode ( ) ) { case EXPR_invoke : { Tuple < Type > results = checkInvoke ( ( Expr . Invoke ) expression , environment ) ; if ( results == null ) { j = j + 1 ; } else { for ( int k = 0 ; k != results . size ( ) ; ++ k ) { checkIsSubtype ( expected . get ( j + k ) , results . get ( k ) , environment , expression ) ; } j = j + results . size ( ) ; } break ; } case EXPR_indirectinvoke : { Tuple < Type > results = checkIndirectInvoke ( ( Expr . IndirectInvoke ) expression , environment ) ; if ( results == null ) { j = j + 1 ; } else { for ( int k = 0 ; k != results . size ( ) ; ++ k ) { checkIsSubtype ( expected . get ( j + k ) , results . get ( k ) , environment , expression ) ; } j = j + results . size ( ) ; } break ; } default : SemanticType type = checkExpression ( expression , environment ) ; if ( ( expected . size ( ) - j ) < 1 ) { syntaxError ( expression , TOO_MANY_RETURNS ) ; } else if ( ( i + 1 ) == expressions . size ( ) && ( expected . size ( ) - j ) > 1 ) { syntaxError ( expression , INSUFFICIENT_RETURNS ) ; } else { checkIsSubtype ( expected . get ( j ) , type , environment , expression ) ; } j = j + 1 ; } } }
Type check a sequence of zero or more multi - expressions assuming a given initial environment . A multi - expression is one which may have multiple return values . There are relatively few situations where this can arise particular assignments and return statements . This returns a sequence of one or more pairs each of which corresponds to a single return for a given expression . Thus each expression generates one or more pairs in the result .
35,371
private SemanticType checkConstant ( Expr . Constant expr , Environment env ) { Value item = expr . getValue ( ) ; switch ( item . getOpcode ( ) ) { case ITEM_null : return Type . Null ; case ITEM_bool : return Type . Bool ; case ITEM_int : return Type . Int ; case ITEM_byte : return Type . Byte ; case ITEM_utf8 : return new SemanticType . Array ( Type . Int ) ; default : return internalFailure ( "unknown constant encountered: " + expr , expr ) ; } }
Check the type of a given constant expression . This is straightforward since the determine is fully determined by the kind of constant we have .
35,372
private SemanticType checkVariable ( Expr . VariableAccess expr , Environment environment ) { Decl . Variable var = expr . getVariableDeclaration ( ) ; return environment . getType ( var ) ; }
Check the type of a given variable access . This is straightforward since the determine is fully determined by the declared type for the variable in question .
35,373
private SemanticType checkIntegerOperator ( Expr . BinaryOperator expr , Environment environment ) { checkOperand ( Type . Int , expr . getFirstOperand ( ) , environment ) ; checkOperand ( Type . Int , expr . getSecondOperand ( ) , environment ) ; return Type . Int ; }
Check the type for a given arithmetic operator . Such an operator has the type int and all children should also produce values of type int .
35,374
private void checkNonEmpty ( Tuple < Decl . Variable > decls , LifetimeRelation lifetimes ) { for ( int i = 0 ; i != decls . size ( ) ; ++ i ) { checkNonEmpty ( decls . get ( i ) , lifetimes ) ; } }
Check a given set of variable declarations are not empty . That is their declared type is not equivalent to void .
35,375
private void checkNonEmpty ( Decl . Variable d , LifetimeRelation lifetimes ) { if ( relaxedSubtypeOperator . isVoid ( d . getType ( ) , lifetimes ) ) { syntaxError ( d . getType ( ) , EMPTY_TYPE ) ; } }
Check that a given variable declaration is not empty . That is the declared type is not equivalent to void . This is an important sanity check .
35,376
public SemanticType . Array extractArrayType ( SemanticType type , Environment environment , ReadWriteTypeExtractor . Combinator < SemanticType . Array > combinator , SyntacticItem item ) { if ( type != null ) { SemanticType . Array sourceArrayT = rwTypeExtractor . apply ( type , environment , combinator ) ; if ( sourceArrayT == null ) { syntaxError ( item , EXPECTED_ARRAY ) ; } else { return sourceArrayT ; } } return null ; }
From an arbitrary type extract the array type it represents which is either readable or writeable depending on the context .
35,377
public SemanticType extractElementType ( SemanticType . Array type , SyntacticItem item ) { if ( type == null ) { return null ; } else { return type . getElement ( ) ; } }
Extract the element type from an array . The array type can be null if some earlier part of type checking generated an error message and we are just continuing after that .
35,378
public SemanticType . Record extractRecordType ( SemanticType type , Environment environment , ReadWriteTypeExtractor . Combinator < SemanticType . Record > combinator , SyntacticItem item ) { if ( type != null ) { SemanticType . Record recordT = rwTypeExtractor . apply ( type , environment , combinator ) ; if ( recordT == null ) { syntaxError ( item , EXPECTED_RECORD ) ; } else { return recordT ; } } return null ; }
From an arbitrary type extract the record type it represents which is either readable or writeable depending on the context .
35,379
public SemanticType extractFieldType ( SemanticType . Record type , Identifier field ) { if ( type == null ) { return null ; } else { SemanticType fieldType = type . getField ( field ) ; if ( fieldType == null ) { syntaxError ( field , INVALID_FIELD ) ; } return fieldType ; } }
From a given record type extract type for a given field .
35,380
public SemanticType . Reference extractReferenceType ( SemanticType type , Environment environment , ReadWriteTypeExtractor . Combinator < SemanticType . Reference > combinator , SyntacticItem item ) { if ( type != null ) { SemanticType . Reference refT = rwTypeExtractor . apply ( type , environment , combinator ) ; if ( refT == null ) { syntaxError ( item , EXPECTED_REFERENCE ) ; } else { return refT ; } } return null ; }
From an arbitrary type extract the reference type it represents which is either readable or writeable depending on the context .
35,381
public SemanticType extractElementType ( SemanticType . Reference type , SyntacticItem item ) { if ( type == null ) { return null ; } else { return type . getElement ( ) ; } }
Extract the element type from a reference . The array type can be null if some earlier part of type checking generated an error message and we are just continuing after that .
35,382
public Type . Callable extractLambdaType ( SemanticType type , Environment environment , ReadWriteTypeExtractor . Combinator < Type . Callable > combinator , SyntacticItem item ) { if ( type != null ) { Type . Callable refT = rwTypeExtractor . apply ( type , environment , combinator ) ; if ( refT == null ) { syntaxError ( item , EXPECTED_LAMBDA ) ; } else { return refT ; } } return null ; }
From an arbitrary type extract the lambda type it represents which is either readable or writeable depending on the context .
35,383
public List < Token > scan ( ) { ArrayList < Token > tokens = new ArrayList < > ( ) ; pos = 0 ; while ( pos < input . length ( ) ) { char c = input . charAt ( pos ) ; if ( isDigit ( c ) ) { tokens . add ( scanNumericLiteral ( ) ) ; } else if ( c == '"' ) { tokens . add ( scanStringLiteral ( ) ) ; } else if ( c == '\'' ) { tokens . add ( scanCharacterLiteral ( ) ) ; } else if ( isOperatorStart ( c ) ) { tokens . add ( scanOperator ( ) ) ; } else if ( isLetter ( c ) || c == '_' ) { tokens . add ( scanIdentifier ( ) ) ; } else if ( Character . isWhitespace ( c ) ) { scanWhiteSpace ( tokens ) ; } else { syntaxError ( "unknown token encountered" , pos ) ; } } return tokens ; }
Scan all characters from the input stream and generate a corresponding list of tokens whilst discarding all whitespace and comments .
35,384
public Token scanIndent ( ) { int start = pos ; while ( pos < input . length ( ) && ( input . charAt ( pos ) == ' ' || input . charAt ( pos ) == '\t' ) ) { pos ++ ; } return new Token ( Token . Kind . Indent , input . substring ( start , pos ) , start ) ; }
Scan one or more spaces or tab characters combining them to form an indent .
35,385
public void skipWhitespace ( List < Token > tokens ) { while ( pos < input . length ( ) && ( input . charAt ( pos ) == '\n' || input . charAt ( pos ) == '\t' ) ) { pos ++ ; } }
Skip over any whitespace at the current index position in the input string .
35,386
private static WyilFile compile ( List < Path . Entry < WhileyFile > > sources , Path . Entry < WyilFile > target ) throws IOException { WyilFile wyil = target . read ( ) ; for ( int i = 0 ; i != sources . size ( ) ; ++ i ) { Path . Entry < WhileyFile > source = sources . get ( i ) ; WhileyFileParser wyp = new WhileyFileParser ( wyil , source . read ( ) ) ; wyil . getModule ( ) . putUnit ( wyp . read ( ) ) ; } return wyil ; }
Compile one or more WhileyFiles into a given WyilFile
35,387
public boolean contains ( QualifiedName name ) { Name unit = name . getUnit ( ) ; SymbolTable . Group group = symbolTable . get ( unit ) ; return group != null && group . isValid ( name . getName ( ) ) ; }
Check whether a given name is registered . That is whether or not there is a corresponding name or not .
35,388
public boolean isAvailable ( QualifiedName name ) { SymbolTable . Group group = symbolTable . get ( name . getUnit ( ) ) ; return group != null && group . isAvailable ( name . getName ( ) ) ; }
Check whether a given symbol is currently external to the enclosing WyilFile . Specifically this indicates whether or not a stub is available for it .
35,389
public List < Decl . Named > getRegisteredDeclarations ( QualifiedName name ) { Group g = symbolTable . get ( name . getUnit ( ) ) ; if ( g != null ) { return g . getRegisteredDeclarations ( name . getName ( ) ) ; } else { return Collections . EMPTY_LIST ; } }
Get the actual declarations associated with a given symbol .
35,390
public void addAvailable ( QualifiedName name , List < Decl . Named > available ) { ExternalGroup group = ( ExternalGroup ) symbolTable . get ( name . getUnit ( ) ) ; for ( int i = 0 ; i != available . size ( ) ; ++ i ) { group . addAvailable ( available . get ( i ) ) ; } }
Make available declarations for an external symbol . This makes those declarations available within the target for linking .
35,391
public void consolidate ( ) { Decl . Module module = target . getModule ( ) ; for ( ExternalGroup group : consolidations ) { module . putExtern ( group . consolidate ( ) ) ; } consolidations . clear ( ) ; }
Consolidate the status of external symbols . For example this will ensure all external units which have imported symbols are made available . Likewise it may garbage collect available symbols and units which are no longer required .
35,392
private Type . Field [ ] determinePivotFields ( Tuple < Type . Field > lhsFields , Tuple < Type . Field > rhsFields , LifetimeRelation lifetimes , LinkageStack stack ) { Type . Field [ ] pivots = new Type . Field [ lhsFields . size ( ) ] ; for ( int i = 0 ; i != lhsFields . size ( ) ; ++ i ) { Type . Field lhsField = lhsFields . get ( i ) ; Identifier lhsFieldName = lhsField . getName ( ) ; for ( int j = 0 ; j != rhsFields . size ( ) ; ++ j ) { Type . Field rhsField = rhsFields . get ( j ) ; Identifier rhsFieldName = rhsField . getName ( ) ; if ( lhsFieldName . equals ( rhsFieldName ) ) { Type type = apply ( lhsField . getType ( ) , rhsField . getType ( ) , lifetimes , stack ) ; if ( ! ( type instanceof Type . Void ) ) { pivots [ i ] = new Type . Field ( lhsFieldName , type ) ; } break ; } } } return pivots ; }
Find all pivots between the lhs and rhs fields and calculate their types .
35,393
public ControlFlow visitBlock ( Stmt . Block block , DefinitelyAssignedSet environment ) { DefinitelyAssignedSet nextEnvironment = environment ; DefinitelyAssignedSet breakEnvironment = null ; for ( int i = 0 ; i != block . size ( ) ; ++ i ) { Stmt s = block . get ( i ) ; ControlFlow nf = visitStatement ( s , nextEnvironment ) ; nextEnvironment = nf . nextEnvironment ; breakEnvironment = join ( breakEnvironment , nf . breakEnvironment ) ; if ( nextEnvironment == null ) { break ; } } return new ControlFlow ( nextEnvironment , breakEnvironment ) ; }
Check that all variables used in a given list of statements are definitely assigned . Furthermore update the set of definitely assigned variables to include any which are definitely assigned at the end of these statements .
35,394
public static void syntaxError ( SyntacticItem e , int code , SyntacticItem ... context ) { WyilFile wf = ( WyilFile ) e . getHeap ( ) ; SyntacticItem . Marker m = wf . allocate ( new WyilFile . SyntaxError ( code , e , new Tuple < > ( context ) ) ) ; wf . getModule ( ) . addAttribute ( m ) ; }
Report an error message . This may additionally sanity check the supplied context .
35,395
private RValue [ ] packReturns ( CallStack frame , Decl . Callable decl ) { if ( decl instanceof Decl . Property ) { return new RValue [ ] { RValue . True } ; } else { Tuple < Decl . Variable > returns = decl . getReturns ( ) ; RValue [ ] values = new RValue [ returns . size ( ) ] ; for ( int i = 0 ; i != values . length ; ++ i ) { values [ i ] = frame . getLocal ( returns . get ( i ) . getName ( ) ) ; } return values ; } }
Given an execution frame extract the return values from a given function or method . The parameters of the function or method are located first in the frame followed by the return values .
35,396
private Status executeBlock ( Stmt . Block block , CallStack frame , EnclosingScope scope ) { for ( int i = 0 ; i != block . size ( ) ; ++ i ) { Stmt stmt = block . get ( i ) ; Status r = executeStatement ( stmt , frame , scope ) ; if ( r != Status . NEXT ) { return r ; } } return Status . NEXT ; }
Execute a given block of statements starting from the beginning . Control may terminate prematurely in a number of situations . For example when a return or break statement is encountered .
35,397
private Status executeStatement ( Stmt stmt , CallStack frame , EnclosingScope scope ) { switch ( stmt . getOpcode ( ) ) { case WyilFile . STMT_assert : return executeAssert ( ( Stmt . Assert ) stmt , frame , scope ) ; case WyilFile . STMT_assume : return executeAssume ( ( Stmt . Assume ) stmt , frame , scope ) ; case WyilFile . STMT_assign : return executeAssign ( ( Stmt . Assign ) stmt , frame , scope ) ; case WyilFile . STMT_break : return executeBreak ( ( Stmt . Break ) stmt , frame , scope ) ; case WyilFile . STMT_continue : return executeContinue ( ( Stmt . Continue ) stmt , frame , scope ) ; case WyilFile . STMT_debug : return executeDebug ( ( Stmt . Debug ) stmt , frame , scope ) ; case WyilFile . STMT_dowhile : return executeDoWhile ( ( Stmt . DoWhile ) stmt , frame , scope ) ; case WyilFile . STMT_fail : return executeFail ( ( Stmt . Fail ) stmt , frame , scope ) ; case WyilFile . STMT_if : case WyilFile . STMT_ifelse : return executeIf ( ( Stmt . IfElse ) stmt , frame , scope ) ; case WyilFile . EXPR_indirectinvoke : executeIndirectInvoke ( ( Expr . IndirectInvoke ) stmt , frame ) ; return Status . NEXT ; case WyilFile . EXPR_invoke : executeInvoke ( ( Expr . Invoke ) stmt , frame ) ; return Status . NEXT ; case WyilFile . STMT_namedblock : return executeNamedBlock ( ( Stmt . NamedBlock ) stmt , frame , scope ) ; case WyilFile . STMT_while : return executeWhile ( ( Stmt . While ) stmt , frame , scope ) ; case WyilFile . STMT_return : return executeReturn ( ( Stmt . Return ) stmt , frame , scope ) ; case WyilFile . STMT_skip : return executeSkip ( ( Stmt . Skip ) stmt , frame , scope ) ; case WyilFile . STMT_switch : return executeSwitch ( ( Stmt . Switch ) stmt , frame , scope ) ; case WyilFile . DECL_variableinitialiser : case WyilFile . DECL_variable : return executeVariableDeclaration ( ( Decl . Variable ) stmt , frame ) ; } deadCode ( stmt ) ; return null ; }
Execute a statement at a given point in the function or method body
35,398
private Status executeBreak ( Stmt . Break stmt , CallStack frame , EnclosingScope scope ) { return Status . BREAK ; }
Execute a break statement . This transfers to control out of the nearest enclosing loop .
35,399
private Status executeContinue ( Stmt . Continue stmt , CallStack frame , EnclosingScope scope ) { return Status . CONTINUE ; }
Execute a continue statement . This transfers to control back to the start the nearest enclosing loop .