private void TryElimination(IEnumerable <Variable> extraDefinedVariables)
            {
                bool Defined(Variable v) => varToExpr.ContainsKey(v) || extraDefinedVariables.Contains(v);

                bool changed;

                do
                {
                    changed = false;
                    var remainingAssignments = new List <Assignment>();
                    foreach (var assignment in assignments)
                    {
                        if (!Defined(assignment.Var) &&
                            VariableCollector.Collect(assignment.Expr).
                            Intersect(AllIntroducedVariables).All(Defined))
                        {
                            varToExpr[assignment.Var] = SubstitutionHelper.Apply(varToExpr, assignment.Expr);
                            changed = true;
                        }
                        else
                        {
                            remainingAssignments.Add(assignment);
                        }
                    }
                    Substitution sub = Substituter.SubstitutionFromHashtable(varToExpr);
                    foreach (var assignment in remainingAssignments)
                    {
                        assignment.Expr = Substituter.Apply(sub, assignment.Expr);
                    }
                    assignments = remainingAssignments;
                    assumes     = SubstitutionHelper.Apply(sub, assumes).ToList();
                } while (changed);
            }
Exemplo n.º 2
0
        private HashSet <VariableDescriptor> GetControlDependencyVariables(string proc, Block b)
        {
            // This method works under the assumption that assume statements
            // relevant to control flow between basic blocks have the "partition" attribute

            HashSet <VariableDescriptor> result = new HashSet <VariableDescriptor>();
            var gotoCmd = b.TransferCmd as GotoCmd;

            if (gotoCmd != null && gotoCmd.labelTargets.Count >= 2)
            {
                foreach (Block succ in gotoCmd.labelTargets)
                {
                    foreach (Cmd c in succ.Cmds)
                    {
                        AssumeCmd a = c as AssumeCmd;
                        if (a != null && QKeyValue.FindBoolAttribute(a.Attributes, "partition"))
                        {
                            var VarCollector = new VariableCollector();
                            VarCollector.VisitExpr(a.Expr);
                            result.UnionWith(VarCollector.usedVars.Where(Item => VariableRelevantToAnalysis(Item, proc)).
                                             Select(Item => MakeDescriptor(proc, Item)));
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
            return(result);
        }
 private static void SubstituteBackwardAssignments(AtomicAction action)
 {
     foreach (Block block in action.impl.Blocks)
     {
         List <Cmd> cmds = new List <Cmd>();
         foreach (Cmd cmd in block.cmds)
         {
             if (cmd is AssignCmd _assignCmd &&
                 QKeyValue.FindBoolAttribute(_assignCmd.Attributes, CivlAttributes.BACKWARD))
             {
                 AssignCmd assignCmd = _assignCmd.AsSimpleAssignCmd;
                 var       lhss      = assignCmd.Lhss;
                 var       rhss      = assignCmd.Rhss;
                 var       rhssVars  = rhss.SelectMany(x => VariableCollector.Collect(x));
                 var       lhssVars  = lhss.SelectMany(x => VariableCollector.Collect(x));
                 if (rhssVars.Intersect(lhssVars).Any())
                 {
                     // TODO
                     throw new NotImplementedException("Substitution of backward assignment where lhs appears on rhs");
                 }
                 else
                 {
                     List <Expr> assumeExprs = new List <Expr>();
                     for (int k = 0; k < lhss.Count; k++)
                     {
                         assumeExprs.Add(Expr.Eq(lhss[k].AsExpr, rhss[k]));
                     }
                     cmds.Add(new AssumeCmd(Token.NoToken, Expr.And(assumeExprs)));
                     cmds.Add(new HavocCmd(Token.NoToken, lhss.Select(x => x.DeepAssignedIdentifier).ToList()));
                 }
             }
 public EPModuleVariableInitServicesImpl(
     VariableCollector variableCollector,
     EventTypeResolver eventTypeResolver)
 {
     VariableCollector = variableCollector;
     EventTypeResolver = eventTypeResolver;
 }
Exemplo n.º 5
0
        public AtomicAction(Procedure proc, Implementation impl, MoverType moverType, LayerRange layerRange)
        {
            this.proc       = proc;
            this.impl       = impl;
            this.moverType  = moverType;
            this.layerRange = layerRange;

            CivlUtil.AddInlineAttribute(proc);
            CivlUtil.AddInlineAttribute(impl);

            // The gate of an atomic action is represented as asserts at the beginning of the procedure body.
            this.gate = impl.Blocks[0].cmds.TakeWhile((c, i) => c is AssertCmd).Cast <AssertCmd>().ToList();
            impl.Blocks[0].cmds.RemoveRange(0, gate.Count);

            gateUsedGlobalVars   = new HashSet <Variable>(VariableCollector.Collect(gate).Where(x => x is GlobalVariable));
            actionUsedGlobalVars = new HashSet <Variable>(VariableCollector.Collect(impl).Where(x => x is GlobalVariable));
            modifiedGlobalVars   = new HashSet <Variable>(AssignedVariables().Where(x => x is GlobalVariable));

            // We usually declare the Boogie procedure and implementation of an atomic action together.
            // Since Boogie only stores the supplied attributes (in particular linearity) in the procedure parameters,
            // we copy them into the implementation parameters here.
            for (int i = 0; i < proc.InParams.Count; i++)
            {
                impl.InParams[i].Attributes = proc.InParams[i].Attributes;
            }
            for (int i = 0; i < proc.OutParams.Count; i++)
            {
                impl.OutParams[i].Attributes = proc.OutParams[i].Attributes;
            }

            AtomicActionDuplicator.SetupCopy(this, ref firstGate, ref firstImpl, "first_");
            AtomicActionDuplicator.SetupCopy(this, ref secondGate, ref secondImpl, "second_");

            DeclareTriggerFunctions();
        }
        private bool OnlyRefersToConstants(Expr e)
        {
            VariableCollector vc = new VariableCollector();

            vc.Visit(e);
            return(vc.usedVars.OfType <Constant>().Count() == vc.usedVars.Count());
        }
Exemplo n.º 7
0
        private IEnumerable <VariableDescriptor> GetReferencedVariables(Absy node, string proc)
        {
            var VarCollector = new VariableCollector();

            VarCollector.Visit(node);
            return(VarCollector.usedVars.Where(Item => VariableRelevantToAnalysis(Item, proc)).
                   Select(Item => MakeDescriptor(proc, Item)));
        }
Exemplo n.º 8
0
        public override Expr VisitIdentifierExpr(IdentifierExpr node)
        {
            VariableCollector vc = new VariableCollector();

            vc.Visit(node);
            var existConsts = vc.usedVars.Where(x => QKeyValue.FindBoolAttribute(x.Attributes, "existential"));

            existConsts.Iter(x => usedExistentialConstants.Add(x));
            return(base.VisitIdentifierExpr(node));
        }
Exemplo n.º 9
0
 public override Expr VisitExpr(Expr node)
 {
     if (node is NAryExpr nary &&
         nary.Fun is BinaryOperator op &&
         op.Op == BinaryOperator.Opcode.Eq &&
         VariableCollector.Collect(node).Contains(choice))
     {
         return(Expr.True);
     }
     return(base.VisitExpr(node));
 }
Exemplo n.º 10
0
 public FOLKnowledgeBase(FOLDomain domain, InferenceProcedure inferenceProcedure, Unifier unifier)
 {
     this.parser             = new FOLParser(new FOLDomain(domain));
     this.inferenceProcedure = inferenceProcedure;
     this.unifier            = unifier;
     //
     this.substVisitor      = new SubstVisitor();
     this.variableCollector = new VariableCollector();
     this._standardizeApart = new StandardizeApart(variableCollector, substVisitor);
     this.cnfConverter      = new CNFConverter(parser);
 }
Exemplo n.º 11
0
        private void propagateInfosToRefinedLocations(AssumePoint p)
        {
            var visitor = new VariableCollector();

            p.Condition.Parts.First().SourceElement.VisitMe(visitor);
            var variables = visitor.Variables;

            foreach (var variable in variables)
            {
                copyInfoFromInToOutSnapshot(variable, p, p.Log);
            }
        }
Exemplo n.º 12
0
 private void checkDefiniteVariablesInAssumption(AssumePoint p)
 {
     foreach (var conditionPart in p.Condition.Parts)
     {
         var visitor = new VariableCollector();
         conditionPart.SourceElement.VisitMe(visitor);
         var variables = visitor.Variables;
         foreach (var variable in variables)
         {
             checkDefiniteVariableInAssumption(variable, p);
         }
     }
 }
        private void MergeIgnoredAnnotations()
        {
            var IgnoredAnnotationsToVariables = new Dictionary <string, HashSet <Variable> >();

            foreach (var c in AllAnnotationIdentifiers())
            {
                IgnoredAnnotationsToVariables[c] = new HashSet <Variable>();
            }

            foreach (var ci in AnnotationInstances())
            {
                if (!IgnoredAnnotationsToVariables.ContainsKey(ci.AnnotationIdentifier))
                {
                    continue;
                }

                VariableCollector vc = new VariableCollector();
                vc.Visit(ci.Expr);
                if (vc.usedVars.Select(Item => varDepAnalyser.VariableRelevantToAnalysis(Item, ci.Proc)).Count() != 0)
                {
                    continue;
                }

                foreach (var v in vc.usedVars)
                {
                    if (varDepAnalyser.Ignoring(v, ci.Proc))
                    {
                        IgnoredAnnotationsToVariables[ci.AnnotationIdentifier].Add(v);
                    }
                }
            }

            foreach (var c in IgnoredAnnotationsToVariables.Keys)
            {
                foreach (var d in IgnoredAnnotationsToVariables.Keys)
                {
                    if (c == d)
                    {
                        continue;
                    }

                    if (IgnoredAnnotationsToVariables[c].Equals(IgnoredAnnotationsToVariables[d]))
                    {
                        AnnotationDependences.AddEdge(c, d);
                    }
                }
            }
        }
Exemplo n.º 14
0
            private bool TryElimination(IEnumerable <Variable> extraDefinedVariables)
            {
                bool changed       = false;
                var  remainingCmds = new List <Cmd>();

                foreach (var cmd in newCmds)
                {
                    if (cmd is AssignCmd assignCmd)
                    {
                        var lhss = new List <AssignLhs>();
                        var rhss = new List <Expr>();
                        for (int k = 0; k < assignCmd.Lhss.Count; k++)
                        {
                            var      lhs         = assignCmd.Lhss[k];
                            var      rhs         = assignCmd.Rhss[k];
                            Variable assignedVar = lhs.DeepAssignedVariable;

                            var allDefinedVars = varToExpr.Keys.Union(extraDefinedVariables);
                            if (!allDefinedVars.Contains(assignedVar) &&
                                !VariableCollector.Collect(rhs).Intersect(AllIntroducedVariables).
                                Except(allDefinedVars).Any())
                            {
                                varToExpr[assignedVar] = rhs;
                                changed = true;
                            }
                            else
                            {
                                lhss.Add(lhs);
                                rhss.Add(rhs);
                            }
                        }
                        if (lhss.Any())
                        {
                            remainingCmds.Add(new AssignCmd(cmd.tok, lhss, rhss, assignCmd.Attributes));
                        }
                    }
                    else if (cmd is AssumeCmd)
                    {
                        remainingCmds.Add(cmd);
                    }
                }
                Substitution sub = Substituter.SubstitutionFromHashtable(varToExpr);

                newCmds = remainingCmds.Select(cmd => ApplyOnRhss(sub, cmd)).ToList();
                return(changed);
            }
Exemplo n.º 15
0
        private HashSet <VariableDescriptor> UsedVars(Expr e)
        {
            VariableCollector vc = new VariableCollector();

            vc.Visit(e);
            HashSet <VariableDescriptor> result = new HashSet <VariableDescriptor>();

            foreach (var v in vc.usedVars)
            {
                var vd = MakeDescriptor(v);
                if (vd != null)
                {
                    result.Add(vd);
                }
            }
            return(result);
        }
Exemplo n.º 16
0
        public Tuple <string, IEnumerable <LemmaDecl> > GenerateTactic(Expr e)
        {
            var varCollector = new VariableCollector();

            varCollector.Visit(e);

            var lookupTyThms = new List <string>();
            var funMemThms   = new List <string>();

            foreach (var v in varCollector.usedVars)
            {
                try
                {
                    lookupTyThms.Add(programAccessor.LookupVarTyLemma(v));
                }
                catch
                {
                    //variable not found, possible if, for example, v is bound
                }
            }

            var usedFuncs = functionCollector.UsedFunctions(e);

            foreach (var f in usedFuncs)
            {
                funMemThms.Add(programAccessor.MembershipLemma(f));
            }

            var hintLemmas = equalityHintGenerator.GetHints(e);

            var hintsML    = MLUtil.IsaToMLThms(hintLemmas.Select(lemma => lemma.Name));
            var lookupTyML = MLUtil.IsaToMLThms(lookupTyThms);
            var funMemML   = MLUtil.IsaToMLThms(funMemThms);

            var args = new List <string>
            {
                MLUtil.ContextAntiquotation(),
                hintsML,
                lookupTyML,
                funMemML
            };

            var tactic = ProofUtil.Apply(ProofUtil.MLTactic("typing_tac " + string.Join(" ", args), 1));

            return(Tuple.Create(tactic, hintLemmas));
        }
        private void PendingPropagate(HashSet <Variable> allExistsVars, Dictionary <Variable, Expr> existsSubstitutionMap, Variable eVar, Expr eVarSubstExpr, Dictionary <Variable, Expr> pendingMap)
        {
            var usedExistsVars = VariableCollector.Collect(eVarSubstExpr).Intersect(allExistsVars);

            if (usedExistsVars.Count() == 0)
            {
                existsSubstitutionMap[eVar] = eVarSubstExpr;
            }
            else if (usedExistsVars.Except(existsSubstitutionMap.Keys).Count() == 0)
            {
                Substitution subst = Substituter.SubstitutionFromHashtable(existsSubstitutionMap);
                existsSubstitutionMap[eVar] = Substituter.Apply(subst, eVarSubstExpr);
            }
            else
            {
                pendingMap[eVar] = eVarSubstExpr;
            }
        }
Exemplo n.º 18
0
        public override Expr VisitNAryExpr(NAryExpr node)
        {
            if (node.Fun is FunctionCall)
            {
                var collector = new VariableCollector();
                collector.Visit(node);

                if (existentialExpr != null && existentialExpr.Dummies.Intersect(collector.usedVars).Any())
                {
                    functionsUsed.Add(Tuple.Create((node.Fun as FunctionCall).Func, existentialExpr));
                }
                else
                {
                    functionsUsed.Add(Tuple.Create <Function, ExistsExpr>((node.Fun as FunctionCall).Func, null));
                }
            }

            return(base.VisitNAryExpr(node));
        }
Exemplo n.º 19
0
        private void AddDependences(AnnotationInstance ci)
        {
            VariableCollector vc = new VariableCollector();

            vc.VisitExpr(ci.Expr);

            foreach (var v in vc.usedVars.Where(Item => varDepAnalyser.VariableRelevantToAnalysis(Item, ci.Proc)))
            {
                VariableDescriptor vd =
                    varDepAnalyser.MakeDescriptor(ci.Proc, v);
                if (!variableDirectlyReferredToByAnnotations.ContainsKey(vd))
                {
                    variableDirectlyReferredToByAnnotations[vd] = new HashSet <string>();
                }
                variableDirectlyReferredToByAnnotations[vd].Add(ci.AnnotationIdentifier);

                foreach (var w in varDepAnalyser.DependsOn(vd))
                {
                    annotationDependsOn[ci.AnnotationIdentifier].Add(w);
                }
            }
        }
Exemplo n.º 20
0
    private static void PropagateCall(CallCmd cc, HashSet <Variable> liveVarsAfter, Program program)
    {
        // globals U in-params U (after - out-params)
        cc.Outs.Where(ie => ie != null).Iter(ie => liveVarsAfter.Remove(ie.Decl));
        if (program != null)
        {
            program.TopLevelDeclarations
            .OfType <GlobalVariable>()
            .Iter(v => liveVarsAfter.Add(v));
        }

        VariableCollector /*!*/ collector = new VariableCollector();

        cc.Ins.Where(e => e != null).Iter(e => collector.Visit(e));
        if (program == null)
        {
            liveVarsAfter.UnionWith(collector.usedVars.Where(v => v is LocalVariable || v is Formal));
        }
        else
        {
            liveVarsAfter.UnionWith(collector.usedVars);
        }
    }
        private static void UpdateLiveSet(Cmd cmd, HashSet <Variable> liveVars)
        {
            if (cmd is AssignCmd assignCmd)
            {
                foreach (var lhs in assignCmd.Lhss)
                {
                    liveVars.Remove(lhs.DeepAssignedVariable);
                }

                foreach (var rhs in assignCmd.Rhss)
                {
                    var collector = new VariableCollector();
                    collector.Visit(rhs);
                    //we neglect that the corresponding lhs may be dead
                    liveVars.UnionWith(collector.usedVars);
                }
            }
            else if (cmd is HavocCmd havocCmd)
            {
                foreach (var ie in havocCmd.Vars)
                {
                    liveVars.Remove(ie.Decl);
                }
            }
            else if (cmd is PredicateCmd predicateCmd)
            {
                //live set is not cleared when reaching "assert false" or "assume false"
                var collector = new VariableCollector();
                collector.Visit(predicateCmd.Expr);
                liveVars.UnionWith(collector.usedVars);
            }
            else
            {
                throw new ProofGenUnexpectedStateException(
                          "Unsupported command in program right before passification.");
            }
        }
        private void AddDependences(CandidateInstance ci)
        {
            VariableCollector vc = new VariableCollector();
              vc.VisitExpr(ci.Expr);

              foreach (var v in vc.usedVars.Where(Item => varDepAnalyser.VariableRelevantToAnalysis(Item, ci.Proc))) {
            VariableDescriptor vd =
              varDepAnalyser.MakeDescriptor(ci.Proc, v);
            if (!variableDirectlyReferredToByCandidates.ContainsKey(vd)) {
              variableDirectlyReferredToByCandidates[vd] = new HashSet<string>();
            }
            variableDirectlyReferredToByCandidates[vd].Add(ci.Candidate);

            foreach (var w in varDepAnalyser.DependsOn(vd)) {
              candidateDependsOn[ci.Candidate].Add(w);
            }
              }
        }
Exemplo n.º 23
0
 private bool OnlyRefersToConstants(Expr e) {
   VariableCollector vc = new VariableCollector();
   vc.Visit(e);
   return vc.usedVars.OfType<Constant>().Count() == vc.usedVars.Count();
 }
 private void MergeIgnoredCandidates()
 {
     var IgnoredCandidatesToVariables = new Dictionary<string, HashSet<Variable>>();
       foreach(var c in candidates) {
     IgnoredCandidatesToVariables[c] = new HashSet<Variable>();
       }
       foreach(var ci in CandidateInstances()) {
     if(!IgnoredCandidatesToVariables.ContainsKey(ci.Candidate)) {
       continue;
     }
     VariableCollector vc = new VariableCollector();
     vc.Visit(ci.Expr);
     if(vc.usedVars.Select(Item => varDepAnalyser.VariableRelevantToAnalysis(Item, ci.Proc)).Count() != 0) {
       continue;
     }
     foreach(var v in vc.usedVars) {
       if(varDepAnalyser.Ignoring(v, ci.Proc)) {
     IgnoredCandidatesToVariables[ci.Candidate].Add(v);
       }
     }
       }
       foreach(var c in IgnoredCandidatesToVariables.Keys) {
     foreach(var d in IgnoredCandidatesToVariables.Keys) {
       if(c == d) {
     continue;
       }
       if(IgnoredCandidatesToVariables[c].Equals(IgnoredCandidatesToVariables[d])) {
     CandidateDependences.AddEdge(c, d);
       }
     }
       }
 }
Exemplo n.º 25
0
        public AtomicActionInfo(Procedure proc, Ensures ensures, MoverType moverType, int layerNum, int availableUptoLayerNum)
            : base(proc, layerNum, availableUptoLayerNum)
        {
            this.ensures       = ensures;
            this.moverType     = moverType;
            this.gate          = new List <AssertCmd>();
            this.action        = ensures.Condition as CodeExpr;
            this.thisGate      = new List <AssertCmd>();
            this.thisInParams  = new List <Variable>();
            this.thisOutParams = new List <Variable>();
            this.thatGate      = new List <AssertCmd>();
            this.thatInParams  = new List <Variable>();
            this.thatOutParams = new List <Variable>();
            this.hasAssumeCmd  = false;
            this.thisMap       = new Dictionary <Variable, Expr>();
            this.thatMap       = new Dictionary <Variable, Expr>();

            foreach (Block block in this.action.Blocks)
            {
                block.Cmds.ForEach(x => this.hasAssumeCmd = this.hasAssumeCmd || x is AssumeCmd);
            }

            foreach (Block block in this.action.Blocks)
            {
                if (block.TransferCmd is ReturnExprCmd)
                {
                    block.TransferCmd = new ReturnCmd(block.TransferCmd.tok);
                }
            }

            var cmds = this.action.Blocks[0].Cmds;

            for (int i = 0; i < cmds.Count; i++)
            {
                AssertCmd assertCmd = cmds[i] as AssertCmd;
                if (assertCmd == null)
                {
                    break;
                }
                this.gate.Add(assertCmd);
                cmds[i] = new AssumeCmd(assertCmd.tok, Expr.True);
            }

            foreach (Variable x in proc.InParams)
            {
                Variable thisx = new Formal(Token.NoToken, new TypedIdent(Token.NoToken, "this_" + x.Name, x.TypedIdent.Type), true, x.Attributes);
                this.thisInParams.Add(thisx);
                this.thisMap[x] = Expr.Ident(thisx);
                Variable thatx = new Formal(Token.NoToken, new TypedIdent(Token.NoToken, "that_" + x.Name, x.TypedIdent.Type), true, x.Attributes);
                this.thatInParams.Add(thatx);
                this.thatMap[x] = Expr.Ident(thatx);
            }
            foreach (Variable x in proc.OutParams)
            {
                Variable thisx = new Formal(Token.NoToken, new TypedIdent(Token.NoToken, "this_" + x.Name, x.TypedIdent.Type), false, x.Attributes);
                this.thisOutParams.Add(thisx);
                this.thisMap[x] = Expr.Ident(thisx);
                Variable thatx = new Formal(Token.NoToken, new TypedIdent(Token.NoToken, "that_" + x.Name, x.TypedIdent.Type), false, x.Attributes);
                this.thatOutParams.Add(thatx);
                this.thatMap[x] = Expr.Ident(thatx);
            }
            List <Variable> thisLocVars = new List <Variable>();
            List <Variable> thatLocVars = new List <Variable>();

            foreach (Variable x in this.action.LocVars)
            {
                Variable thisx = new Formal(Token.NoToken, new TypedIdent(Token.NoToken, "this_" + x.Name, x.TypedIdent.Type), false);
                thisMap[x] = Expr.Ident(thisx);
                thisLocVars.Add(thisx);
                Variable thatx = new Formal(Token.NoToken, new TypedIdent(Token.NoToken, "that_" + x.Name, x.TypedIdent.Type), false);
                thatMap[x] = Expr.Ident(thatx);
                thatLocVars.Add(thatx);
            }
            Contract.Assume(proc.TypeParameters.Count == 0);
            Substitution thisSubst = Substituter.SubstitutionFromHashtable(this.thisMap);
            Substitution thatSubst = Substituter.SubstitutionFromHashtable(this.thatMap);

            foreach (AssertCmd assertCmd in this.gate)
            {
                this.thisGate.Add((AssertCmd)Substituter.Apply(thisSubst, assertCmd));
                this.thatGate.Add((AssertCmd)Substituter.Apply(thatSubst, assertCmd));
            }
            this.thisAction = new CodeExpr(thisLocVars, SubstituteBlocks(this.action.Blocks, thisSubst, "this_"));
            this.thatAction = new CodeExpr(thatLocVars, SubstituteBlocks(this.action.Blocks, thatSubst, "that_"));

            {
                VariableCollector collector = new VariableCollector();
                collector.Visit(this.action);
                this.actionUsedGlobalVars = new HashSet <Variable>(collector.usedVars.Where(x => x is GlobalVariable));
            }

            List <Variable> modifiedVars = new List <Variable>();

            foreach (Block block in this.action.Blocks)
            {
                block.Cmds.ForEach(cmd => cmd.AddAssignedVariables(modifiedVars));
            }
            this.modifiedGlobalVars = new HashSet <Variable>(modifiedVars.Where(x => x is GlobalVariable));

            {
                VariableCollector collector = new VariableCollector();
                this.gate.ForEach(assertCmd => collector.Visit(assertCmd));
                this.gateUsedGlobalVars = new HashSet <Variable>(collector.usedVars.Where(x => x is GlobalVariable));
            }
        }
Exemplo n.º 26
0
        public AtomicActionInfo(Procedure proc, Ensures ensures, MoverType moverType, int layerNum, int availableUptoLayerNum)
            : base(proc, layerNum, availableUptoLayerNum)
        {
            CodeExpr codeExpr = ensures.Condition as CodeExpr;

            this.ensures       = ensures;
            this.moverType     = moverType;
            this.thisGate      = new List <AssertCmd>();
            this.thisAction    = codeExpr;
            this.thisInParams  = new List <Variable>();
            this.thisOutParams = new List <Variable>();
            this.thatGate      = new List <AssertCmd>();
            this.thatInParams  = new List <Variable>();
            this.thatOutParams = new List <Variable>();
            this.hasAssumeCmd  = false;

            foreach (Block block in codeExpr.Blocks)
            {
                block.Cmds.ForEach(x => this.hasAssumeCmd = this.hasAssumeCmd || x is AssumeCmd);
            }

            var cmds = thisAction.Blocks[0].Cmds;

            for (int i = 0; i < cmds.Count; i++)
            {
                AssertCmd assertCmd = cmds[i] as AssertCmd;
                if (assertCmd == null)
                {
                    break;
                }
                thisGate.Add(assertCmd);
                cmds[i] = new AssumeCmd(assertCmd.tok, Expr.True);
            }

            Dictionary <Variable, Expr> map = new Dictionary <Variable, Expr>();

            foreach (Variable x in proc.InParams)
            {
                this.thisInParams.Add(x);
                Variable y = new Formal(Token.NoToken, new TypedIdent(Token.NoToken, "that_" + x.Name, x.TypedIdent.Type), true, x.Attributes);
                this.thatInParams.Add(y);
                map[x] = Expr.Ident(y);
            }
            foreach (Variable x in proc.OutParams)
            {
                this.thisOutParams.Add(x);
                Variable y = new Formal(Token.NoToken, new TypedIdent(Token.NoToken, "that_" + x.Name, x.TypedIdent.Type), false, x.Attributes);
                this.thatOutParams.Add(y);
                map[x] = Expr.Ident(y);
            }
            List <Variable> thatLocVars = new List <Variable>();

            foreach (Variable x in thisAction.LocVars)
            {
                Variable y = new Formal(Token.NoToken, new TypedIdent(Token.NoToken, "that_" + x.Name, x.TypedIdent.Type), false);
                map[x] = Expr.Ident(y);
                thatLocVars.Add(y);
            }
            Contract.Assume(proc.TypeParameters.Count == 0);
            Substitution subst = Substituter.SubstitutionFromHashtable(map);

            foreach (AssertCmd assertCmd in thisGate)
            {
                thatGate.Add((AssertCmd)Substituter.Apply(subst, assertCmd));
            }
            Dictionary <Block, Block> blockMap = new Dictionary <Block, Block>();
            List <Block> thatBlocks            = new List <Block>();

            foreach (Block block in thisAction.Blocks)
            {
                List <Cmd> otherCmds = new List <Cmd>();
                foreach (Cmd cmd in block.Cmds)
                {
                    otherCmds.Add(Substituter.Apply(subst, cmd));
                }
                Block thatBlock = new Block();
                thatBlock.Cmds  = otherCmds;
                thatBlock.Label = "that_" + block.Label;
                block.Label     = "this_" + block.Label;
                thatBlocks.Add(thatBlock);
                blockMap[block] = thatBlock;
                if (block.TransferCmd is GotoCmd)
                {
                    GotoCmd gotoCmd = block.TransferCmd as GotoCmd;
                    for (int i = 0; i < gotoCmd.labelNames.Count; i++)
                    {
                        gotoCmd.labelNames[i] = "this_" + gotoCmd.labelNames[i];
                    }
                }
            }
            foreach (Block block in thisAction.Blocks)
            {
                if (block.TransferCmd is ReturnExprCmd)
                {
                    block.TransferCmd           = new ReturnCmd(block.TransferCmd.tok);
                    blockMap[block].TransferCmd = new ReturnCmd(block.TransferCmd.tok);
                    continue;
                }
                List <Block>  thatGotoCmdLabelTargets = new List <Block>();
                List <string> thatGotoCmdLabelNames   = new List <string>();
                GotoCmd       gotoCmd = block.TransferCmd as GotoCmd;
                foreach (Block target in gotoCmd.labelTargets)
                {
                    thatGotoCmdLabelTargets.Add(blockMap[target]);
                    thatGotoCmdLabelNames.Add(blockMap[target].Label);
                }
                blockMap[block].TransferCmd = new GotoCmd(block.TransferCmd.tok, thatGotoCmdLabelNames, thatGotoCmdLabelTargets);
            }
            this.thatAction = new CodeExpr(thatLocVars, thatBlocks);

            {
                VariableCollector collector = new VariableCollector();
                collector.Visit(codeExpr);
                this.actionUsedGlobalVars = new HashSet <Variable>(collector.usedVars.Where(x => x is GlobalVariable));
            }

            List <Variable> modifiedVars = new List <Variable>();

            foreach (Block block in codeExpr.Blocks)
            {
                block.Cmds.ForEach(cmd => cmd.AddAssignedVariables(modifiedVars));
            }
            this.modifiedGlobalVars = new HashSet <Variable>(modifiedVars.Where(x => x is GlobalVariable));

            {
                VariableCollector collector = new VariableCollector();
                this.thisGate.ForEach(assertCmd => collector.Visit(assertCmd));
                this.gateUsedGlobalVars = new HashSet <Variable>(collector.usedVars.Where(x => x is GlobalVariable));
            }
        }
Exemplo n.º 27
0
 public void setUp()
 {
     parser = new FOLParser(DomainFactory.crusadesDomain());
     vc     = new VariableCollector();
 }
        private Expr CalculatePathCondition(PathInfo path)
        {
            HashSet <Variable>          allExistsVars         = new HashSet <Variable>(firstExistsVars.Union(secondExistsVars));
            HashSet <Variable>          usedExistsVars        = new HashSet <Variable>();
            Dictionary <Variable, Expr> existsSubstitutionMap = new Dictionary <Variable, Expr>();
            List <Expr> inferredSelectEqualities = new List <Expr>();

            foreach (Variable v in path.varToExpr.Keys.Except(postExistVars))
            {
                var expr = path.varToExpr[v];
                usedExistsVars.UnionWith(VariableCollector.Collect(expr).Intersect(allExistsVars));
                IdentifierExpr ie = expr as IdentifierExpr;
                if (ie != null && IsExistsVar(ie.Decl) && !existsSubstitutionMap.ContainsKey(ie.Decl))
                {
                    existsSubstitutionMap[ie.Decl] = Expr.Ident(v);
                }
                else if (IsMapStoreExpr(expr))
                {
                    inferredSelectEqualities.Add(GenerateEqualityWithSelect(expr as NAryExpr, Expr.Ident(v)));
                }
            }

            foreach (Expr expr in path.pathExprs)
            {
                usedExistsVars.UnionWith(VariableCollector.Collect(expr).Intersect(allExistsVars));
            }
            InferSubstitution(allExistsVars, existsSubstitutionMap, path.pathExprs, inferredSelectEqualities);

            List <Expr>     triggerExprs   = new List <Expr>();
            List <Variable> quantifiedVars = new List <Variable>();

            foreach (var v in usedExistsVars.Except(existsSubstitutionMap.Keys))
            {
                var triggerFun    = TriggerFunction(v); // this call populates existsVars[v]
                var quantifiedVar = existsVars[v];
                triggerExprs.Add(
                    new NAryExpr(Token.NoToken,
                                 new FunctionCall(triggerFun),
                                 new Expr[] { Expr.Ident(quantifiedVar) }));
                quantifiedVars.Add(quantifiedVar);
                existsSubstitutionMap[v] = Expr.Ident(quantifiedVar);
            }

            Substitution subst       = Substituter.SubstitutionFromHashtable(existsSubstitutionMap);
            List <Expr>  returnExprs = new List <Expr>();

            foreach (Variable v in path.varToExpr.Keys.Except(postExistVars))
            {
                Expr withOldExpr = MyDuplicator.Duplicate(path.varToExpr[v]);
                var  substExpr   = Expr.Eq(Expr.Ident(v), Substituter.Apply(subst, withOldExpr));
                substExpr.Type = Type.Bool;
                returnExprs.Add(substExpr);
            }

            foreach (Expr x in path.pathExprs)
            {
                var withOldExpr = MyDuplicator.Duplicate(x);
                returnExprs.Add(Substituter.Apply(subst, withOldExpr));
            }

            var returnExpr = Expr.And(returnExprs);

            if (quantifiedVars.Count > 0)
            {
                if (first == null)
                {
                    returnExpr = new ExistsExpr(Token.NoToken, quantifiedVars, returnExpr);
                }
                else
                {
                    returnExpr = new ExistsExpr(Token.NoToken,
                                                quantifiedVars,
                                                new Trigger(Token.NoToken, true, triggerExprs),
                                                returnExpr);
                }
            }
            return(returnExpr);
        }
Exemplo n.º 29
0
    // perform in place update of liveSet
    public static void Propagate(Cmd cmd, HashSet <Variable /*!*/> /*!*/ liveSet, bool allGlobalsAreLive)
    {
        Contract.Requires(cmd != null);
        Contract.Requires(cce.NonNullElements(liveSet));
        if (cmd is AssignCmd)
        {
            AssignCmd /*!*/ assignCmd = (AssignCmd)cce.NonNull(cmd);
            // I must first iterate over all the targets and remove the live ones.
            // After the removals are done, I must add the variables referred on
            // the right side of the removed targets

            AssignCmd     simpleAssignCmd = assignCmd.AsSimpleAssignCmd;
            HashSet <int> indexSet        = new HashSet <int>();
            int           index           = 0;
            foreach (AssignLhs /*!*/ lhs in simpleAssignCmd.Lhss)
            {
                Contract.Assert(lhs != null);
                SimpleAssignLhs salhs = lhs as SimpleAssignLhs;
                Contract.Assert(salhs != null);
                Variable var = salhs.DeepAssignedVariable;
                if (var != null && (liveSet.Contains(var) || (allGlobalsAreLive && var is GlobalVariable)))
                {
                    indexSet.Add(index);
                    liveSet.Remove(var);
                }
                index++;
            }
            index = 0;
            foreach (Expr /*!*/ expr in simpleAssignCmd.Rhss)
            {
                Contract.Assert(expr != null);
                if (indexSet.Contains(index))
                {
                    VariableCollector /*!*/ collector = new VariableCollector();
                    collector.Visit(expr);
                    if (allGlobalsAreLive)
                    {
                        liveSet.UnionWith(collector.usedVars.Where(v => v is LocalVariable || v is Formal));
                    }
                    else
                    {
                        liveSet.UnionWith(collector.usedVars);
                    }
                }
                index++;
            }
        }
        else if (cmd is HavocCmd)
        {
            HavocCmd /*!*/ havocCmd = (HavocCmd)cmd;
            foreach (IdentifierExpr /*!*/ expr in havocCmd.Vars)
            {
                Contract.Assert(expr != null);
                if (expr.Decl != null)
                {
                    liveSet.Remove(expr.Decl);
                }
            }
        }
        else if (cmd is PredicateCmd)
        {
            Contract.Assert((cmd is AssertCmd || cmd is AssumeCmd));
            PredicateCmd /*!*/ predicateCmd = (PredicateCmd)cce.NonNull(cmd);
            if (predicateCmd.Expr is LiteralExpr)
            {
                LiteralExpr le = (LiteralExpr)predicateCmd.Expr;
                if (le.IsFalse)
                {
                    liveSet.Clear();
                }
            }
            else
            {
                VariableCollector /*!*/ collector = new VariableCollector();
                collector.Visit(predicateCmd.Expr);
                if (allGlobalsAreLive)
                {
                    liveSet.UnionWith(collector.usedVars.Where(v => v is LocalVariable || v is Formal));
                }
                else
                {
                    liveSet.UnionWith(collector.usedVars);
                }
            }
        }
        else if (cmd is CommentCmd)
        {
            // comments are just for debugging and don't affect verification
        }
        else if (cmd is SugaredCmd)
        {
            SugaredCmd /*!*/ sugCmd = (SugaredCmd)cce.NonNull(cmd);
            Propagate(sugCmd.Desugaring, liveSet, allGlobalsAreLive);
        }
        else if (cmd is StateCmd)
        {
            StateCmd /*!*/   stCmd = (StateCmd)cce.NonNull(cmd);
            List <Cmd> /*!*/ cmds  = cce.NonNull(stCmd.Cmds);
            int len = cmds.Count;
            for (int i = len - 1; i >= 0; i--)
            {
                Propagate(cmds[i], liveSet, allGlobalsAreLive);
            }
            foreach (Variable /*!*/ v in stCmd.Locals)
            {
                Contract.Assert(v != null);
                liveSet.Remove(v);
            }
        }
        else
        {
            {
                Contract.Assert(false);
                throw new cce.UnreachableException();
            }
        }
    }