Exemplo n.º 1
0
        public static VCExpr Block(Block b, VCExpr N, VCContext ctxt)
        //modifies ctxt.*;
        {
            Contract.Requires(b != null);
            Contract.Requires(N != null);
            Contract.Requires(ctxt != null);
            Contract.Ensures(Contract.Result <VCExpr>() != null);

            VCExpressionGenerator gen = ctxt.Ctxt.ExprGen;

            Contract.Assert(gen != null);

            VCExpr res = N;

            for (int i = b.Cmds.Count; --i >= 0;)
            {
                res = Cmd(b, cce.NonNull(b.Cmds[i]), res, ctxt);
            }

            int id = b.UniqueId;

            if (ctxt.Label2absy != null)
            {
                ctxt.Label2absy[id] = b;
            }

            try {
                cce.BeginExpose(ctxt);
                return(res);
            } finally {
                cce.EndExpose();
            }
        }
Exemplo n.º 2
0
            public ClusteringMatrix(List <Cluster> clusters, IDictionary <VCExprVar /*!*/, VCExprVar /*!*/> /*!*/ globalVars,
                                    VCExpressionGenerator gen)
            {
                Contract.Requires(gen != null);
                Contract.Requires(clusters != null);
                Contract.Requires(cce.NonNullDictionaryAndValues(globalVars));
                List <Cluster> c = new List <Cluster>();

                c.AddRange(clusters);
                Clusters = c;

                GlobalVariables = globalVars;
                Gen             = gen;

                bool[] remaining = new bool[clusters.Count];
                RemainingClusters = remaining;
                for (int i = 0; i < remaining.Length; ++i)
                {
                    remaining[i] = true;
                }

                Distance[,] /*!*/
                distances = new Distance[clusters.Count, clusters.Count];
                Distances = distances;
                for (int i = 1; i < clusters.Count; ++i)
                {
                    for (int j = 0; j < i; ++j)
                    {
                        distances[i, j] =
                            new Distance(clusters[i], clusters[j], GlobalVariables, Gen);
                    }
                }
            }
Exemplo n.º 3
0
        public TypeAxiomBuilderArguments(VCExpressionGenerator gen)
            : base(gen)
        {
            Contract.Requires(gen != null);

            Typed2UntypedFunctions = new Dictionary <Function /*!*/, Function /*!*/>();
        }
Exemplo n.º 4
0
        public TypeEraserArguments(TypeAxiomBuilderArguments axBuilder, VCExpressionGenerator gen) : base(axBuilder, gen)
        {
            Contract.Requires(gen != null);
            Contract.Requires(axBuilder != null);

            this.AxBuilderArguments = axBuilder;
        }
Exemplo n.º 5
0
        public VCExpr GetSummaryExpr(Dictionary <string, VCExpr> incarnations, VCExpressionGenerator gen)
        {
            VCExpr ret = VCExpressionGenerator.True;

            if (val.Values.Any(v => v == null))
            {
                return(VCExpressionGenerator.False);
            }

            foreach (var v in vars)
            {
                var consts = val[v.Name];
                Debug.Assert(consts != null);

                if (consts.Count == 0)
                {
                    continue;
                }

                var vexpr = VCExpressionGenerator.False;
                consts.Iter(c => vexpr = gen.OrSimp(vexpr, gen.Eq(incarnations[v.Name], gen.Integer(Microsoft.BaseTypes.BigNum.FromInt(c)))));
                ret = gen.AndSimp(ret, vexpr);
            }

            return(ret);
        }
Exemplo n.º 6
0
    public TPTPProcessTheoremProver(ProverOptions options, VCExpressionGenerator gen,
                                      DeclFreeProverContext ctx)
      : base(options, "", "", "", "", gen)
    {
      Contract.Requires(options != null);
      Contract.Requires(gen != null);
      Contract.Requires(ctx != null);

      // No bg predicate at the moment
      // InitializeGlobalInformation("UnivBackPred.tptp");

      this.ctx = ctx;
      this.Gen = gen;

      TypeAxiomBuilder axBuilder;
      switch (CommandLineOptions.Clo.TypeEncodingMethod) {
        case CommandLineOptions.TypeEncoding.Arguments:
          axBuilder = new TypeAxiomBuilderArguments(gen);
          axBuilder.Setup();
          break;
        case CommandLineOptions.TypeEncoding.Monomorphic:
          axBuilder = new TypeAxiomBuilderPremisses(gen);
          break;
        default:
          axBuilder = new TypeAxiomBuilderPremisses(gen);
          axBuilder.Setup();
          break;
      }
      AxBuilder = axBuilder;
      UniqueNamer namer = new UniqueNamer();      
      Namer = namer;
      Namer.Spacer = "__";
      this.DeclCollector = new TypeDeclCollector(namer);

    }
Exemplo n.º 7
0
 public BigLiteralAbstracter(VCExpressionGenerator gen)
     : base(gen)
 {
     Contract.Requires(gen != null);
     DummyVar  = gen.Variable("x", Type.Int);
     IncAxioms = new List <VCExpr>();
     Literals  = new List <KeyValuePair <BigNum, VCExprVar> >();
 }
Exemplo n.º 8
0
    public TypeAxiomBuilderPremisses(VCExpressionGenerator gen)
      : base(gen) {
      Contract.Requires(gen != null);

      TypeFunction = HelperFuns.BoogieFunction("dummy", Type.Int);
      Typed2UntypedFunctions = new Dictionary<Function/*!*/, UntypedFunction>();
      MapTypeAbstracterAttr = null;
    }
Exemplo n.º 9
0
 public TermClustersSameHead(VCExprOp op, IDictionary <VCExprVar /*!*/, VCExprVar /*!*/> /*!*/ globalVars, VCExpressionGenerator /*!*/ gen)
 {
     Contract.Requires(cce.NonNullDictionaryAndValues(globalVars));
     Contract.Requires(gen != null);
     Contract.Requires(op != null);
     Op = op;
     GlobalVariables = globalVars;
     Gen             = gen;
 }
 /// <summary>
 ///     Initializes a new instance of the <see cref="TypePremiseEraserFactory" /> class.
 ///     This factory can be used to produce <see cref="TypePremiseEraserProvider" /> objects.
 /// </summary>
 /// <param name="vcExprGen"></param>
 /// <param name="vcTranslator"></param>
 /// <param name="programIsPolymorphic">Set to true iff the input program is polymorphic</param>
 public TypePremiseEraserFactory(
     VCExpressionGenerator vcExprGen,
     Boogie2VCExprTranslator vcTranslator,
     bool programIsPolymorphic)
 {
     _vcExprGen           = vcExprGen;
     _vcTranslator        = vcTranslator;
     ProgramIsPolymorphic = programIsPolymorphic;
 }
Exemplo n.º 11
0
 public fromZ3(VCExpressionGenerator _gen,
               BacktrackDictionary <Term, VCExpr> _constants_inv,
               BacktrackDictionary <FuncDecl, Function> _functions_inv)
 {
     gen           = _gen;
     constants_inv = _constants_inv;
     functions_inv = _functions_inv;
     memo          = new Dictionary <Term, VCExpr>();
     lets          = new List <VCExprLetBinding>();
 }
Exemplo n.º 12
0
        public static VCExpr Instantiate(Implementation impl, VCExpressionGenerator vcExprGen, Boogie2VCExprTranslator exprTranslator, VCExpr vcExpr)
        {
            if (!InstantiationSourceChecker.HasInstantiationSources(impl))
            {
                return(vcExpr);
            }
            var qiEngine = new QuantifierInstantiationEngine(vcExprGen, exprTranslator);

            return(qiEngine.Execute(impl, vcExpr));
        }
Exemplo n.º 13
0
 public static void InitializeVCGen(Program prog)
 {
     //create VC.vcgen/VC.proverInterface
     VC.vcgen = new VCGen(prog, CommandLineOptions.Clo.SimplifyLogFilePath,
                          CommandLineOptions.Clo.SimplifyLogFileAppend, new List <Checker>());
     VC.proverInterface = ProverInterface.CreateProver(prog, CommandLineOptions.Clo.SimplifyLogFilePath, CommandLineOptions.Clo.SimplifyLogFileAppend, CommandLineOptions.Clo.ProverKillTime);
     VC.translator      = VC.proverInterface.Context.BoogieExprTranslator;
     VC.exprGen         = VC.proverInterface.Context.ExprGen;
     VC.collector       = new ConditionGeneration.CounterexampleCollector();
 }
Exemplo n.º 14
0
        protected virtual TPTPProcessTheoremProver SpawnProver(ProverOptions options,
                                                               VCExpressionGenerator gen,
                                                               DeclFreeProverContext ctx)
        {
            Contract.Requires(options != null);
            Contract.Requires(gen != null);
            Contract.Requires(ctx != null);
            Contract.Ensures(Contract.Result <TPTPProcessTheoremProver>() != null);

            return(new TPTPProcessTheoremProver(options, gen, ctx));
        }
Exemplo n.º 15
0
        public override object NewProverContext(ProverOptions opts)
        {
            if (CommandLineOptions.Clo.BracketIdsInVC < 0)
            {
                CommandLineOptions.Clo.BracketIdsInVC = 0;
            }

            VCExpressionGenerator gen = new VCExpressionGenerator();

            return(new Z3apiProverContext((Z3InstanceOptions)opts, gen));
        }
Exemplo n.º 16
0
        protected virtual SMTLibProcessTheoremProver SpawnProver(ProverOptions options,
            VCExpressionGenerator gen,
            SMTLibProverContext ctx)
        {
            Contract.Requires(options != null);
              Contract.Requires(gen != null);
              Contract.Requires(ctx != null);
              Contract.Ensures(Contract.Result<SMTLibProcessTheoremProver>() != null);

              return new SMTLibProcessTheoremProver(options, gen, ctx);
        }
Exemplo n.º 17
0
        private VCExpr ToVcExpr(Expr expr, Dictionary <string, VCExpr> incarnations, VCExpressionGenerator gen)
        {
            if (expr is LiteralExpr)
            {
                var val = (expr as LiteralExpr).Val;
                if (val is bool)
                {
                    if ((bool)val)
                    {
                        return(VCExpressionGenerator.True);
                    }
                    else
                    {
                        return(VCExpressionGenerator.False);
                    }
                }
                else if (val is Microsoft.BaseTypes.BigNum)
                {
                    return(gen.Integer((Microsoft.BaseTypes.BigNum)val));
                }

                throw new NotImplementedException("Cannot handle literals of this type");
            }

            if (expr is IdentifierExpr)
            {
                return(ToVcVar((expr as IdentifierExpr).Name, incarnations, false));
            }

            if (expr is OldExpr)
            {
                var ide = (expr as OldExpr).Expr as IdentifierExpr;
                Debug.Assert(ide != null);

                return(ToVcVar(ide.Name, incarnations, true));
            }

            if (expr is NAryExpr)
            {
                var nary = expr as NAryExpr;
                if (nary.Fun is UnaryOperator)
                {
                    Debug.Assert((nary.Fun as UnaryOperator).Op == UnaryOperator.Opcode.Not);
                    return(gen.Not(ToVcExpr(nary.Args[0], incarnations, gen)));
                }
                if (nary.Fun is BinaryOperator)
                {
                    return(gen.Function(Translate(nary.Fun as BinaryOperator), ToVcExpr(nary.Args[0], incarnations, gen), ToVcExpr(nary.Args[1], incarnations, gen)));
                }
                Debug.Assert(false, "No other op is handled");
            }
            throw new NotImplementedException(string.Format("Expr of type {0} is not handled", expr.GetType().ToString()));
        }
Exemplo n.º 18
0
        public Distance(Cluster a, Cluster b, IDictionary<VCExprVar /*!*/, VCExprVar /*!*/> /*!*/ globalVars,
          VCExpressionGenerator gen)
        {
          Contract.Requires(gen != null);
          Contract.Requires(cce.NonNullDictionaryAndValues(globalVars));
          AntiUnificationVisitor /*!*/
            visitor = new AntiUnificationVisitor(gen);
          Generator = (VCExprNAry) visitor.AntiUnify(a.Generator, b.Generator);

          visitor.RepresentationSize(globalVars, out var reprSizeA, out var reprSizeB);
          Dist = (a.Size - 1) * reprSizeA + (b.Size - 1) * reprSizeB;
        }
Exemplo n.º 19
0
 public OrderingAxiomBuilder(VCExpressionGenerator gen,
                             Boogie2VCExprTranslator translator) {
   Contract.Requires(gen != null);
   Contract.Requires(translator != null);
   this.Gen = gen;
   this.Translator = translator;
   OneStepFuns = new Dictionary<Type, Function>();
   Constants = new List<Constant>();
   CompleteConstantsOpen = new List<Constant>();
   AllAxioms = new List<VCExpr>();
   IncAxioms = new List<VCExpr>();
 }
Exemplo n.º 20
0
        private VCExpr BuildAxiom(ProverInterface proverInterface, Dictionary <Variable, bool> currentAssignment)
        {
            ProverContext           proverContext  = proverInterface.Context;
            Boogie2VCExprTranslator exprTranslator = proverContext.BoogieExprTranslator;
            VCExpressionGenerator   exprGen        = proverInterface.VCExprGen;

            VCExpr expr = VCExpressionGenerator.True;

            foreach (KeyValuePair <Variable, bool> kv in currentAssignment)
            {
                Variable  constant = kv.Key;
                VCExprVar exprVar  = exprTranslator.LookupVariable(constant);
                if (kv.Value)
                {
                    expr = exprGen.And(expr, exprVar);
                }
                else
                {
                    expr = exprGen.And(expr, exprGen.Not(exprVar));
                }
            }

            if (CommandLineOptions.Clo.ExplainHoudini)
            {
                // default values for ExplainHoudini control variables
                foreach (var constant in explainConstantsNegative.Concat(explainConstantsPositive))
                {
                    expr = exprGen.And(expr, exprTranslator.LookupVariable(constant));
                }
            }

            /*
             * foreach (Variable constant in this.houdiniConstants) {
             * VCExprVar exprVar = exprTranslator.LookupVariable(constant);
             * if (currentAssignment[constant]) {
             *  expr = exprGen.And(expr, exprVar);
             * }
             * else {
             *  expr = exprGen.And(expr, exprGen.Not(exprVar));
             * }
             * }
             */

            if (CommandLineOptions.Clo.Trace)
            {
                Console.WriteLine("Houdini assignment axiom: " + expr);
            }

            return(expr);
        }
Exemplo n.º 21
0
        public Z3apiProverContext(Context ctx, VCExpressionGenerator gen)
            : base(gen, new VCGenerationOptions(new List <string>()))
        {
            z3 = ctx;

            this.z3log = null;
            this.tm    = new Z3TypeCachedBuilder(this);
            this.namer = new UniqueNamer();

            // For external

            constants_inv = new BacktrackDictionary <Term, VCExpr>();
            functions_inv = new BacktrackDictionary <FuncDecl, Function>();
        }
Exemplo n.º 22
0
 private QuantifierInstantiationEngine(VCExpressionGenerator vcExprGen, Boogie2VCExprTranslator exprTranslator)
 {
     this.quantifierBinding           = new Dictionary <VCExprVar, VCExprQuantifier>();
     this.lambdaDefinition            = new Dictionary <Function, VCExprQuantifier>();
     this.quantifierInstantiationInfo = new Dictionary <VCExprQuantifier, QuantifierInstantiationInfo>();
     this.skolemConstants             = new HashSet <VCExprVar>();
     this.labelToInstances            = new Dictionary <string, HashSet <VCExpr> >();
     this.accLabelToInstances         = new Dictionary <string, HashSet <VCExpr> >();
     this.lambdaToInstances           = new Dictionary <Function, HashSet <List <VCExpr> > >();
     this.accLambdaToInstances        = new Dictionary <Function, HashSet <List <VCExpr> > >();
     this.quantifierBindingNamePrefix = "quantifierBinding";
     this.skolemConstantNamePrefix    = "skolemConstant";
     this.vcExprGen      = vcExprGen;
     this.exprTranslator = exprTranslator;
 }
Exemplo n.º 23
0
        private static VCExpr MaybeWrapWithOptimization(VCContext ctxt, VCExpressionGenerator gen, QKeyValue attrs, VCExpr expr)
        {
            var min = QKeyValue.FindExprAttribute(attrs, "minimize");

            if (min != null)
            {
                expr = gen.Function(VCExpressionGenerator.MinimizeOp, ctxt.Ctxt.BoogieExprTranslator.Translate(min), expr);
            }
            var max = QKeyValue.FindExprAttribute(attrs, "maximize");

            if (max != null)
            {
                expr = gen.Function(VCExpressionGenerator.MaximizeOp, ctxt.Ctxt.BoogieExprTranslator.Translate(max), expr);
            }
            return(expr);
        }
Exemplo n.º 24
0
        public override object NewProverContext(ProverOptions options)
        {
            //Contract.Requires(options != null);
              Contract.Ensures(Contract.Result<object>() != null);

              VCExpressionGenerator gen = new VCExpressionGenerator();
              List<string>/*!>!*/ proverCommands = new List<string/*!*/>();
              proverCommands.Add("smtlib");
              var opts = (SMTLibProverOptions)options ;
              if (opts.Solver == SolverKind.Z3)
            proverCommands.Add("z3");
              else
            proverCommands.Add("external");
              VCGenerationOptions genOptions = new VCGenerationOptions(proverCommands);
              return new SMTLibProverContext(gen, genOptions);
        }
Exemplo n.º 25
0
        public VCExpr GetSummaryExpr(Dictionary <string, VCExpr> incarnations, VCExpressionGenerator gen)
        {
            if (isFalse)
            {
                return(VCExpressionGenerator.False);
            }

            var ret = VCExpressionGenerator.True;

            foreach (var expr in preds)
            {
                ret = gen.AndSimp(ret, ToVcExpr(expr, incarnations, gen));
            }

            return(ret);
        }
Exemplo n.º 26
0
        public DeclFreeProverContext(VCExpressionGenerator gen,
            VCGenerationOptions genOptions)
        {
            Contract.Requires(gen != null);
              Contract.Requires(genOptions != null);
              this.gen = gen;
              this.genOptions = genOptions;
              Boogie2VCExprTranslator t = new Boogie2VCExprTranslator (gen, genOptions);
              this.translator = t;

              SetupOrderingAxiomBuilder(gen, t);

              distincts = new List<Variable>();
              axiomConjuncts = new List<VCExpr>();

              exprTranslator = null;
        }
Exemplo n.º 27
0
        public Z3apiProverContext(Z3InstanceOptions opts, VCExpressionGenerator gen)
            : base(gen, new VCGenerationOptions(new List <string>()))
        {
            int timeout = opts.Timeout * 1000;

            config = new Config();
            config.SetParamValue("MODEL", "true");
            config.SetParamValue("MODEL_V2", "true");
            config.SetParamValue("MODEL_COMPLETION", "true");
            config.SetParamValue("MBQI", "false");
            config.SetParamValue("TYPE_CHECK", "true");
            if (0 <= timeout)
            {
                config.SetParamValue("SOFT_TIMEOUT", timeout.ToString());
            }

            if (0 <= CommandLineOptions.Clo.ProverCCLimit)
            {
                this.counterexamples = CommandLineOptions.Clo.ProverCCLimit;
            }
            if (CommandLineOptions.Clo.SimplifyLogFilePath != null)
            {
                logFilename = CommandLineOptions.Clo.SimplifyLogFilePath;
            }
            this.debugTraces = new List <string>();

            z3 = new Context(config);
            z3.SetPrintMode(PrintMode.Smtlib2Compliant);
            if (logFilename != null)
            {
#if true
                z3log = new StreamWriter(logFilename);
                //Z3Log.Open(logFilename);
#else
                z3.OpenLog(logFilename);
#endif
            }
            foreach (string tag in debugTraces)
            {
                z3.EnableDebugTrace(tag);
            }

            //this.z3log = null;
            this.tm    = new Z3TypeCachedBuilder(this);
            this.namer = new UniqueNamer();
        }
Exemplo n.º 28
0
    public VCExpr Attach(StratifiedVC svc)
    {
      Contract.Assert(interfaceExprs.Count == svc.interfaceExprVars.Count);
      StratifiedInliningInfo info = svc.info;
      ProverInterface prover = info.vcgen.prover;
      VCExpressionGenerator gen = prover.VCExprGen;

      Dictionary<VCExprVar, VCExpr> substDict = new Dictionary<VCExprVar, VCExpr>();
      for (int i = 0; i < svc.interfaceExprVars.Count; i++)
      {
        VCExprVar v = svc.interfaceExprVars[i];
        substDict.Add(v, interfaceExprs[i]);
      }

      VCExprSubstitution subst =
        new VCExprSubstitution(substDict, new Dictionary<TypeVariable, Microsoft.Boogie.Type>());
      SubstitutingVCExprVisitor substVisitor = new SubstitutingVCExprVisitor(prover.VCExprGen);
      svc.vcexpr = substVisitor.Mutate(svc.vcexpr, subst);
      foreach (StratifiedCallSite scs in svc.CallSites)
      {
        List<VCExpr> newInterfaceExprs = new List<VCExpr>();
        foreach (VCExpr expr in scs.interfaceExprs)
        {
          newInterfaceExprs.Add(substVisitor.Mutate(expr, subst));
        }

        scs.interfaceExprs = newInterfaceExprs;
      }

      foreach (StratifiedCallSite scs in svc.RecordProcCallSites)
      {
        List<VCExpr> newInterfaceExprs = new List<VCExpr>();
        foreach (VCExpr expr in scs.interfaceExprs)
        {
          newInterfaceExprs.Add(substVisitor.Mutate(expr, subst));
        }

        scs.interfaceExprs = newInterfaceExprs;
      }

      //return gen.Implies(callSiteExpr, svc.vcexpr);
      return svc.vcexpr;
    }
Exemplo n.º 29
0
        public static VCExpr P_Block(Block b, HashSet <string> constantsAssumed, VCExpr N, VCContext ctxt)
        //modifies ctxt.*;
        {
            Contract.Requires(b != null);
            Contract.Requires(N != null);
            Contract.Requires(ctxt != null);
            Contract.Ensures(Contract.Result <VCExpr>() != null);

            VCExpressionGenerator gen = ctxt.Ctxt.ExprGen;

            Contract.Assert(gen != null);

            VCExpr res = N;

            for (int i = b.Cmds.Count; --i >= 0;)
            {
                res = P_Cmd(b, constantsAssumed, cce.NonNull(b.Cmds[i]), res, ctxt);
            }

            int id = b.UniqueId;

            if (ctxt.Label2absy != null)
            {
                ctxt.Label2absy[id] = b;
            }

            try
            {
                cce.BeginExpose(ctxt);
                if (ctxt.Label2absy == null)
                {
                    return(res);
                }
                else
                {
                    return(gen.Implies(gen.LabelPos(cce.NonNull(id.ToString()), VCExpressionGenerator.True), res));
                }
            }
            finally
            {
                cce.EndExpose();
            }
        }
Exemplo n.º 30
0
        protected DeclFreeProverContext(DeclFreeProverContext ctxt)
        {
            Contract.Requires(ctxt != null);
              this.gen = ctxt.gen;
              this.genOptions = ctxt.genOptions;
              Boogie2VCExprTranslator t = (Boogie2VCExprTranslator)ctxt.translator.Clone();
              Contract.Assert(t != null);
              this.translator = t;
              this.orderingAxiomBuilder = new OrderingAxiomBuilder(ctxt.gen, t, ctxt.orderingAxiomBuilder);

              StringBuilder cmds = new StringBuilder ();

              distincts = new List<Variable>(ctxt.distincts);
              axiomConjuncts = new List<VCExpr>(ctxt.axiomConjuncts);

              if (ctxt.exprTranslator == null)
            exprTranslator = null;
              else
            exprTranslator = (VCExprTranslator)cce.NonNull(ctxt.exprTranslator.Clone());
        }
Exemplo n.º 31
0
        public override object NewProverContext(ProverOptions options)
        {
            //Contract.Requires(options != null);
            Contract.Ensures(Contract.Result <object>() != null);

            if (CommandLineOptions.Clo.BracketIdsInVC < 0)
            {
                CommandLineOptions.Clo.BracketIdsInVC = 0;
            }

            VCExpressionGenerator gen            = new VCExpressionGenerator();
            List <string> /*!>!*/ proverCommands = new List <string /*!*/>();

            proverCommands.Add("tptp");
            proverCommands.Add("external");
            VCGenerationOptions genOptions = new VCGenerationOptions(proverCommands);

            Contract.Assert(genOptions != null);

            return(new DeclFreeProverContext(gen, genOptions));
        }
        public TypePremiseEraserProvider(
            VCExpressionGenerator vcExprGen,
            Boogie2VCExprTranslator vcTranslator,
            bool programIsPolymorphic,
            bool extractTypeArgs = true)
        {
            _vcExprGen           = vcExprGen;
            ProgramIsPolymorphic = programIsPolymorphic;
            if (programIsPolymorphic)
            {
                AxiomBuilder = new TypeAxiomBuilderPremisses(vcExprGen);
                AxiomBuilder.Setup();
            }
            else
            {
                AxiomBuilder = null;
            }

            Eraser        = new TypeEraserPremisses(AxiomBuilder, vcExprGen, extractTypeArgs);
            _vcTranslator = vcTranslator;
        }
Exemplo n.º 33
0
    public SMTLibProcessTheoremProver(ProverOptions options, VCExpressionGenerator gen,
                                      SMTLibProverContext ctx)
    {
      Contract.Requires(options != null);
      Contract.Requires(gen != null);
      Contract.Requires(ctx != null);
      
      InitializeGlobalInformation();
      
      this.options = (SMTLibProverOptions)options;
      this.ctx = ctx;
      this.gen = gen;
      this.usingUnsatCore = false;

      SetupAxiomBuilder(gen);

      Namer = new SMTLibNamer();
      ctx.parent = this;
      this.DeclCollector = new TypeDeclCollector((SMTLibProverOptions)options, Namer);

      if (CommandLineOptions.Clo.PrintFixedPoint != null || CommandLineOptions.Clo.PrintConjectures != null)
      {
          declHandler = new MyDeclHandler();
          DeclCollector.SetDeclHandler(declHandler);
      }

      SetupProcess();

      if (CommandLineOptions.Clo.StratifiedInlining > 0 || CommandLineOptions.Clo.ContractInfer
          || CommandLineOptions.Clo.SecureVcGen != null)
      {
          // Prepare for ApiChecker usage
          if (options.LogFilename != null && currentLogFile == null)
          {
              currentLogFile = OpenOutputFile("");
          }
          PrepareCommon();
      }
    }
Exemplo n.º 34
0
        public TPTPProcessTheoremProver(ProverOptions options, VCExpressionGenerator gen,
                                        DeclFreeProverContext ctx)
            : base(options, "", "", "", "", gen)
        {
            Contract.Requires(options != null);
            Contract.Requires(gen != null);
            Contract.Requires(ctx != null);

            // No bg predicate at the moment
            // InitializeGlobalInformation("UnivBackPred.tptp");

            this.ctx = ctx;
            this.Gen = gen;

            TypeAxiomBuilder axBuilder;

            switch (CommandLineOptions.Clo.TypeEncodingMethod)
            {
            case CommandLineOptions.TypeEncoding.Arguments:
                axBuilder = new TypeAxiomBuilderArguments(gen);
                axBuilder.Setup();
                break;

            case CommandLineOptions.TypeEncoding.Monomorphic:
                axBuilder = new TypeAxiomBuilderPremisses(gen);
                break;

            default:
                axBuilder = new TypeAxiomBuilderPremisses(gen);
                axBuilder.Setup();
                break;
            }
            AxBuilder = axBuilder;
            UniqueNamer namer = new UniqueNamer();

            Namer              = namer;
            Namer.Spacer       = "__";
            this.DeclCollector = new TypeDeclCollector(namer);
        }
Exemplo n.º 35
0
    public TypeAxiomBuilderArguments(VCExpressionGenerator gen)
      : base(gen) {
      Contract.Requires(gen != null);

      Typed2UntypedFunctions = new Dictionary<Function/*!*/, Function/*!*/>();
    }
Exemplo n.º 36
0
        /// <summary>
        /// Generate all proofs for the current procedure.
        /// </summary>
        /// <param name="vc">WP of the procedure body</param>
        /// <param name="vcAxioms">VC assumptions for the Boogie axioms</param>
        /// <param name="typeAxioms">VC assumptions for the Boogie type encoding</param>
        /// <param name="typeAxiomInfo">Hints about the type encoding</param>
        /// <param name="gen"></param>
        /// <param name="translator"></param>
        /// <param name="axiomBuilder"></param>
        /// <exception cref="ArgumentException">
        /// axiom builder must be null iff types are not erased (since no polymorphism in vc), otherwise exception is
        /// thrown
        /// </exception>
        public static void VCGenerateAllProofs(
            VCExpr vc,
            VCExpr vcAxioms,
            VCExpr typeAxioms,
            List <VCAxiomInfo> typeAxiomInfo,
            VCExpressionGenerator gen,
            Boogie2VCExprTranslator translator,
            TypeAxiomBuilderPremisses axiomBuilder)
        {
            var uniqueNamer = new IsaUniqueNamer();
            var theories    = new List <Theory>();

            if (axiomBuilder == null && typeAxioms != null)
            {
                throw new ArgumentException("type axioms can only be null if axiom builder is null");
            }

            /* Since in the proofs calls are desugared, there can be more variables in "beforePassiveData". If only
             * the progam should be generaed, then these variables should be ignored. */
            var mainData = CommandLineOptions.Clo.GenerateIsaProgNoProofs ? beforeDagData : beforePassiveData;

            var fixedVarTranslation2   = new DeBruijnFixedVarTranslation(mainData);
            var fixedTyVarTranslation2 = new DeBruijnFixedTVarTranslation(mainData);
            var varTranslationFactory2 =
                new DeBruijnVarFactory(fixedVarTranslation2, fixedTyVarTranslation2, boogieGlobalData);

            #region before cfg to dag program
            var beforeCfgToDagTheoryName = uniqueNamer.GetName(afterPassificationImpl.Name + "_before_cfg_to_dag_prog");
            //Hack: specs config used to distinguish between all (free + checks) (--> expression tuples) or just checked (no tuples)
            var specsConfig              = CommandLineOptions.Clo.GenerateIsaProgNoProofs ? SpecsConfig.All : SpecsConfig.AllPreCheckedPost;
            var beforeCfgToDagConfig     = new IsaProgramGeneratorConfig(globalDataProgAccess, false, false, false, true, specsConfig, true);
            var beforeCfgToDagProgAccess = new IsaProgramGenerator().GetIsaProgram(
                beforeCfgToDagTheoryName,
                afterPassificationImpl.Name,
                mainData, beforeCfgToDagConfig, varTranslationFactory2,
                beforeDagCfg,
                out var programDeclsBeforeCfgToDag,
                !CommandLineOptions.Clo.GenerateIsaProgNoProofs);
            procNameToTopLevelPrograms.Add(afterPassificationImpl.Proc.Name, beforeCfgToDagProgAccess);

            var beforeCfgToDagProgTheory = new Theory(beforeCfgToDagTheoryName,
                                                      new List <string> {
                "Boogie_Lang.Semantics", "Boogie_Lang.TypeSafety", "Boogie_Lang.Util", "\"../" + globalDataProgAccess.TheoryName() + "\""
            },
                                                      programDeclsBeforeCfgToDag);
            theories.Add(beforeCfgToDagProgTheory);
            #endregion

            if (CommandLineOptions.Clo.GenerateIsaProgNoProofs)
            {
                StoreResult("program_" + afterPassificationImpl.Proc.Name, theories);
                return;
            }

            #region before passive program

            var beforePassiveProgTheoryName = uniqueNamer.GetName(afterPassificationImpl.Name + "_before_passive_prog");
            var beforePassiveConfig         =
                new IsaProgramGeneratorConfig(beforeCfgToDagProgAccess, false, false, false, false, SpecsConfig.None, false);
            var beforePassiveProgAccess = new IsaProgramGenerator().GetIsaProgram(beforePassiveProgTheoryName,
                                                                                  afterPassificationImpl.Name,
                                                                                  mainData, beforePassiveConfig, varTranslationFactory2,
                                                                                  beforePassificationCfg,
                                                                                  out var programDeclsBeforePassive,
                                                                                  !CommandLineOptions.Clo.GenerateIsaProgNoProofs);

            #endregion

            var vcAllAxioms = AxiomHandler.AxiomInfo(
                axiomBuilder != null,
                boogieGlobalData.Axioms,
                vcAxioms,
                typeAxioms,
                typeAxiomInfo,
                out var allAxiomsInfo);

            var vcLocale = VCToIsaInterface.ConvertVC(
                "vc",
                vc,
                vcAllAxioms,
                new StandardActiveDecl(),
                translator,
                axiomBuilder,
                finalProgData,
                afterUnreachablePruningCfg,
                out var vcinst,
                out var vcinstAxiom,
                out var vcTranslator,
                out var vcFunctions);

            //use global version map for translation
            var fixedVarTranslation   = new SimpleFixedVarTranslation(globalVersionMap);
            var fixedTyVarTranslation = new DeBruijnFixedTVarTranslation(finalProgData);
            varTranslationFactory =
                new DeBruijnVarFactory(fixedVarTranslation, fixedTyVarTranslation, boogieGlobalData);

            var finalProgTheoryName = uniqueNamer.GetName(afterPassificationImpl.Name + "_passive_prog");
            var passiveProgConfig   =
                new IsaProgramGeneratorConfig(beforePassiveProgAccess, false, false, false, true, SpecsConfig.None, false);
            var passiveProgAccess = new IsaProgramGenerator().GetIsaProgram(finalProgTheoryName,
                                                                            afterPassificationImpl.Name,
                                                                            finalProgData, passiveProgConfig, varTranslationFactory,
                                                                            //we use the CFG before the peep-hole transformations, so that we can directly use the VC to program proof in the passification phase
                                                                            afterPassificationCfg,
                                                                            out var programDecls,
                                                                            !CommandLineOptions.Clo.GenerateIsaProgNoProofs);

            var finalProgTheory =
                new Theory(finalProgTheoryName,
                           new List <string>
            {
                "Boogie_Lang.Semantics", "Boogie_Lang.Util", beforePassiveProgAccess.TheoryName()
            },
                           programDecls);
            theories.Add(finalProgTheory);

            var vcBoogieInfo = new VcBoogieInfo(vcinst, vcinstAxiom, vcAllAxioms, allAxiomsInfo);

            var vcProofData = new ProgramVcProofData(
                vcFunctions,
                vcBoogieInfo,
                vcHintManager,
                vcLocale,
                vcTranslator
                );

            var phasesTheories = new PhasesTheories(afterPassificationImpl.Name);

            var theoryPassive = VcPhaseManager.ProgramToVcProof(
                phasesTheories.TheoryName(PhasesTheories.Phase.Vc),
                _proofGenConfig.GenerateVcE2E,
                afterUnreachablePruningCfg,
                afterPassificationCfg,
                afterPassificationToAfterUnreachableBlock,
                afterPassificationToOrigBlock,
                passiveProgAccess,
                beforePassiveProgAccess,
                finalProgData,
                vcProofData,
                varTranslationFactory,
                typePremiseEraserFactory,
                gen,
                out var vcAssm,
                out var endToEndLemma
                );
            theories.Add(theoryPassive);

            #region before passive

            var passificationProgTheory = new Theory(beforePassiveProgTheoryName,
                                                     new List <string> {
                "Boogie_Lang.Semantics", "Boogie_Lang.Util", beforeCfgToDagTheoryName
            },
                                                     programDeclsBeforePassive);
            theories.Add(passificationProgTheory);

            /*
             * Console.WriteLine("Passive prog mapping: " + fixedVarTranslation.OutputMapping());
             * Console.WriteLine("Before passive prog mapping: " + fixedVarTranslation2.OutputMapping());
             */

            var passificationProofTheory = PassificationManager.PassificationProof(
                phasesTheories.TheoryName(PhasesTheories.Phase.Passification),
                theoryPassive.TheoryName,
                _proofGenConfig.GeneratePassifE2E,
                endToEndLemma,
                vcAssm,
                beforePassificationCfg,
                beforePassiveToAfterPassiveBlock,
                passiveRelationGen,
                beforePassiveProgAccess,
                passiveProgAccess,
                mainData,
                varTranslationFactory2,
                varTranslationFactory
                );
            theories.Add(passificationProofTheory);

            #endregion

            #region cfg to dag

            var uniqueExitBlock =
                uniqueExitBlockOrig != null
                    ? beforePassiveOrigBlock.First(kv => kv.Value == uniqueExitBlockOrig).Key
                    : null;


            var cfgToDagProofTheory = CfgToDagManager.CfgToDagProof(
                phasesTheories,
                _proofGenConfig.GenerateCfgDagE2E,
                vcAssm,
                beforeDagCfg,
                beforePassificationCfg,
                uniqueExitBlock,
                beforeDagData,
                cfgToDagHintManager,
                beforeDagAfterDagBlock,
                beforeCfgToDagProgAccess,
                beforePassiveProgAccess,
                varTranslationFactory2);
            theories.Add(cfgToDagProofTheory);
            #endregion

            StoreResult(afterPassificationImpl.Proc.Name, theories);
        }
Exemplo n.º 37
0
        public override object NewProverContext(ProverOptions opts)
        {
            if (CommandLineOptions.Clo.BracketIdsInVC < 0)
            {
                CommandLineOptions.Clo.BracketIdsInVC = 0;
            }

            VCExpressionGenerator gen = new VCExpressionGenerator();
            return new Z3apiProverContext((Z3InstanceOptions)opts, gen);
        }
Exemplo n.º 38
0
        // constructor for cloning
        internal MapTypeAbstractionBuilderPremisses(TypeAxiomBuilderPremisses axBuilder, VCExpressionGenerator gen, MapTypeAbstractionBuilderPremisses builder)
            : base(axBuilder, gen, builder)
        {
            Contract.Requires(builder != null);
              Contract.Requires(gen != null);
              Contract.Requires(axBuilder != null);

              this.AxBuilderPremisses = axBuilder;
        }
Exemplo n.º 39
0
 public OpTypeEraserPremisses(TypeEraserPremisses eraser, TypeAxiomBuilderPremisses axBuilder, VCExpressionGenerator gen)
     : base(eraser, axBuilder, gen)
 {
     Contract.Requires(gen != null);
       Contract.Requires(axBuilder != null);
       Contract.Requires(eraser != null);
       this.AxBuilderPremisses = axBuilder;
 }
Exemplo n.º 40
0
 private static VCExpr MaybeWrapWithOptimization(VCContext ctxt, VCExpressionGenerator gen, QKeyValue attrs, VCExpr expr)
 {
   var min = QKeyValue.FindExprAttribute(attrs, "minimize");
   if (min != null)
   {
     expr = gen.Function(VCExpressionGenerator.MinimizeOp, ctxt.Ctxt.BoogieExprTranslator.Translate(min), expr);
   }
   var max = QKeyValue.FindExprAttribute(attrs, "maximize");
   if (max != null)
   {
     expr = gen.Function(VCExpressionGenerator.MaximizeOp, ctxt.Ctxt.BoogieExprTranslator.Translate(max), expr);
   }
   return expr;
 }
Exemplo n.º 41
0
        public SMTLibProcessTheoremProver(ProverOptions options, VCExpressionGenerator gen,
            SMTLibProverContext ctx)
        {
            Contract.Requires(options != null);
              Contract.Requires(gen != null);
              Contract.Requires(ctx != null);

              InitializeGlobalInformation();

              this.options = (SMTLibProverOptions)options;
              this.ctx = ctx;
              this.gen = gen;
              this.usingUnsatCore = false;

              SetupAxiomBuilder(gen);

              Namer = new SMTLibNamer();
              ctx.parent = this;
              this.DeclCollector = new TypeDeclCollector((SMTLibProverOptions)options, Namer);

              SetupProcess();

              if (CommandLineOptions.Clo.StratifiedInlining > 0 || CommandLineOptions.Clo.ContractInfer)
              {
              // Prepare for ApiChecker usage
              if (options.LogFilename != null && currentLogFile == null)
              {
              currentLogFile = OpenOutputFile("");
              }
              if (CommandLineOptions.Clo.ContractInfer)
              {
              SendThisVC("(set-option :produce-unsat-cores true)");
              this.usingUnsatCore = true;
              }
              PrepareCommon();
              }
        }
Exemplo n.º 42
0
 public TypeEraserArguments(TypeAxiomBuilderArguments axBuilder, VCExpressionGenerator gen) :base(axBuilder, gen){
   Contract.Requires(gen != null);
   Contract.Requires(axBuilder != null);
   
   this.AxBuilderArguments = axBuilder;
 }
Exemplo n.º 43
0
 public abstract void Reset(VCExpressionGenerator gen);
Exemplo n.º 44
0
 private void SetupAxiomBuilder(VCExpressionGenerator gen)
 {
   switch (CommandLineOptions.Clo.TypeEncodingMethod)
   {
     case CommandLineOptions.TypeEncoding.Arguments:
       AxBuilder = new TypeAxiomBuilderArguments(gen);
       AxBuilder.Setup();
       break;
     case CommandLineOptions.TypeEncoding.Monomorphic:
       AxBuilder = new TypeAxiomBuilderPremisses(gen);
       break;
     default:
       AxBuilder = new TypeAxiomBuilderPremisses(gen);
       AxBuilder.Setup();
       break;
   }
 }
Exemplo n.º 45
0
        // MAXSAT
        public void Explain(ProverInterface proverInterface,
                            Dictionary <Variable, bool> assignment, Variable refutedConstant)
        {
            Contract.Assert(CommandLineOptions.Clo.ExplainHoudini);

            collector.examples.Clear();

            // debugging
            houdiniAssertConstants.Iter(v => System.Diagnostics.Debug.Assert(assignment.ContainsKey(v)));
            houdiniAssumeConstants.Iter(v => System.Diagnostics.Debug.Assert(assignment.ContainsKey(v)));
            Contract.Assert(assignment.ContainsKey(refutedConstant));
            Contract.Assert(houdiniAssertConstants.Contains(refutedConstant));

            var hardAssumptions = new List <VCExpr>();
            var softAssumptions = new List <VCExpr>();

            Boogie2VCExprTranslator exprTranslator = proverInterface.Context.BoogieExprTranslator;
            VCExpressionGenerator   exprGen        = proverInterface.VCExprGen;
            var controlExpr = VCExpressionGenerator.True;

            foreach (var tup in assignment)
            {
                Variable  constant = tup.Key;
                VCExprVar exprVar  = exprTranslator.LookupVariable(constant);
                var       val      = tup.Value;

                if (houdiniAssumeConstants.Contains(constant))
                {
                    if (tup.Value)
                    {
                        hardAssumptions.Add(exprVar);
                    }
                    else
                    {
                        // Previously removed assumed candidates are the soft constraints
                        softAssumptions.Add(exprVar);
                    }
                }
                else if (houdiniAssertConstants.Contains(constant))
                {
                    if (constant == refutedConstant)
                    {
                        hardAssumptions.Add(exprVar);
                    }
                    else
                    {
                        hardAssumptions.Add(exprGen.Not(exprVar));
                    }
                }
                else
                {
                    if (tup.Value)
                    {
                        hardAssumptions.Add(exprVar);
                    }
                    else
                    {
                        hardAssumptions.Add(exprGen.Not(exprVar));
                    }
                }

                // For an asserted condition (c ==> \phi),
                // ExplainHoudini's extra control constants (c_pos, c_neg) are used as follows:
                //   (true, true): "assert \phi"
                //   (false, _): "assert false"
                //   (true, false): "assert true"
                if (constant != refutedConstant && constantToControl.ContainsKey(constant.Name))
                {
                    var posControl = constantToControl[constant.Name].Item1;
                    var negControl = constantToControl[constant.Name].Item2;

                    // Handle self-recursion
                    if (houdiniAssertConstants.Contains(constant) && houdiniAssumeConstants.Contains(constant))
                    {
                        // disable this assert
                        controlExpr = exprGen.And(controlExpr, exprGen.And(exprTranslator.LookupVariable(posControl), exprGen.Not(exprTranslator.LookupVariable(negControl))));
                    }
                    else
                    {
                        // default values for control variables
                        controlExpr = exprGen.And(controlExpr, exprGen.And(exprTranslator.LookupVariable(posControl), exprTranslator.LookupVariable(negControl)));
                    }
                }
            }

            hardAssumptions.Add(exprGen.Not(conjecture));

            // default values for control variables
            Contract.Assert(constantToControl.ContainsKey(refutedConstant.Name));
            var pc = constantToControl[refutedConstant.Name].Item1;
            var nc = constantToControl[refutedConstant.Name].Item2;

            var controlExprNoop = exprGen.And(controlExpr,
                                              exprGen.And(exprTranslator.LookupVariable(pc), exprTranslator.LookupVariable(nc)));

            var controlExprFalse = exprGen.And(controlExpr,
                                               exprGen.And(exprGen.Not(exprTranslator.LookupVariable(pc)), exprGen.Not(exprTranslator.LookupVariable(nc))));

            if (CommandLineOptions.Clo.Trace)
            {
                Console.WriteLine("Verifying (MaxSat) " + descriptiveName);
            }
            DateTime now = DateTime.UtcNow;

            var el = CommandLineOptions.Clo.ProverCCLimit;

            CommandLineOptions.Clo.ProverCCLimit = 1;

            var outcome = ProverInterface.Outcome.Undetermined;

            do
            {
                List <int> unsatisfiedSoftAssumptions;

                hardAssumptions.Add(controlExprNoop);
                outcome = proverInterface.CheckAssumptions(hardAssumptions, softAssumptions, out unsatisfiedSoftAssumptions, handler);
                hardAssumptions.RemoveAt(hardAssumptions.Count - 1);

                if (outcome == ProverInterface.Outcome.TimeOut || outcome == ProverInterface.Outcome.OutOfMemory || outcome == ProverInterface.Outcome.OutOfResource || outcome == ProverInterface.Outcome.Undetermined)
                {
                    break;
                }

                var reason = new HashSet <string>();
                unsatisfiedSoftAssumptions.Iter(i => reason.Add(softAssumptions[i].ToString()));
                if (CommandLineOptions.Clo.Trace)
                {
                    Console.Write("Reason for removal of {0}: ", refutedConstant.Name);
                    reason.Iter(r => Console.Write("{0} ", r));
                    Console.WriteLine();
                }

                // Get rid of those constants from the "reason" that can even make
                // "assert false" pass

                hardAssumptions.Add(controlExprFalse);
                var softAssumptions2 = new List <VCExpr>();
                for (int i = 0; i < softAssumptions.Count; i++)
                {
                    if (unsatisfiedSoftAssumptions.Contains(i))
                    {
                        softAssumptions2.Add(softAssumptions[i]);
                        continue;
                    }
                    hardAssumptions.Add(softAssumptions[i]);
                }

                var unsatisfiedSoftAssumptions2 = new List <int>();
                outcome = proverInterface.CheckAssumptions(hardAssumptions, softAssumptions2, out unsatisfiedSoftAssumptions2, handler);

                if (outcome == ProverInterface.Outcome.TimeOut || outcome == ProverInterface.Outcome.OutOfMemory || outcome == ProverInterface.Outcome.OutOfResource || outcome == ProverInterface.Outcome.Undetermined)
                {
                    break;
                }

                unsatisfiedSoftAssumptions2.Iter(i => reason.Remove(softAssumptions2[i].ToString()));
                var reason1 = new HashSet <string>(); //these are the reasons for inconsistency
                unsatisfiedSoftAssumptions2.Iter(i => reason1.Add(softAssumptions2[i].ToString()));

                if (CommandLineOptions.Clo.Trace)
                {
                    Console.Write("Revised reason for removal of {0}: ", refutedConstant.Name);
                    reason.Iter(r => Console.Write("{0} ", r));
                    Console.WriteLine();
                }
                foreach (var r in reason)
                {
                    Houdini.explainHoudiniDottyFile.WriteLine("{0} -> {1} [ label = \"{2}\" color=red ];", refutedConstant.Name, r, descriptiveName);
                }
                //also add the removed reasons using dotted edges (requires- x != 0, requires- x == 0 ==> assert x != 0)
                foreach (var r in reason1)
                {
                    Houdini.explainHoudiniDottyFile.WriteLine("{0} -> {1} [ label = \"{2}\" color=blue style=dotted ];", refutedConstant.Name, r, descriptiveName);
                }
            } while (false);

            if (outcome == ProverInterface.Outcome.TimeOut || outcome == ProverInterface.Outcome.OutOfMemory || outcome == ProverInterface.Outcome.OutOfResource || outcome == ProverInterface.Outcome.Undetermined)
            {
                Houdini.explainHoudiniDottyFile.WriteLine("{0} -> {1} [ label = \"{2}\" color=red ];", refutedConstant.Name, "TimeOut", descriptiveName);
            }

            CommandLineOptions.Clo.ProverCCLimit = el;

            double queryTime = (DateTime.UtcNow - now).TotalSeconds;

            stats.proverTime += queryTime;
            stats.numProverQueries++;
            if (CommandLineOptions.Clo.Trace)
            {
                Console.WriteLine("Time taken = " + queryTime);
            }
        }
Exemplo n.º 46
0
      public SMTLibInterpolatingProcessTheoremProver(ProverOptions options, VCExpressionGenerator gen,
                                        SMTLibProverContext ctx)
          : base(AddInterpOption(options), gen, ctx)
      {

      }
Exemplo n.º 47
0
    public override void Reset(VCExpressionGenerator gen)
    {
      if (options.Solver == SolverKind.Z3)
      {
        this.gen = gen;
        SendThisVC("(reset)");

        if (0 < common.Length)
        {
          var c = common.ToString();
          Process.Send(c);
          if (currentLogFile != null)
          {
            currentLogFile.WriteLine(c);
          }
        }
      }
    }
Exemplo n.º 48
0
 public override void FullReset(VCExpressionGenerator gen)
 {
   if (options.Solver == SolverKind.Z3)
   {
     this.gen = gen;
     SendThisVC("(reset)");
     Namer.Reset();
     common.Clear();
     SetupAxiomBuilder(gen);
     Axioms.Clear();
     TypeDecls.Clear();
     AxiomsAreSetup = false;
     ctx.Reset();
     ctx.KnownDatatypeConstructors.Clear();
     ctx.parent = this;
     DeclCollector.Reset();
     NamedAssumes.Clear();
     UsedNamedAssumes = null;
     SendThisVC("; did a full reset");
   }
 }
Exemplo n.º 49
0
 private void SetupOrderingAxiomBuilder(VCExpressionGenerator gen, Boogie2VCExprTranslator t)
 {
     OrderingAxiomBuilder oab = new OrderingAxiomBuilder(gen, t);
       Contract.Assert(oab != null);
       oab.Setup();
       this.orderingAxiomBuilder = oab;
 }
Exemplo n.º 50
0
        /////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Constructor.  Initialize a checker with the program and log file.
        /// Optionally, use prover context provided by parameter "ctx". 
        /// </summary>
        public Checker(VC.ConditionGeneration vcgen, Program prog, string/*?*/ logFilePath, bool appendLogFile, int timeout, ProverContext ctx = null)
        {
            Contract.Requires(vcgen != null);
              Contract.Requires(prog != null);
              this.timeout = timeout;
              this.Program = prog;

              ProverOptions options = cce.NonNull(CommandLineOptions.Clo.TheProverFactory).BlankProverOptions();

              if (logFilePath != null) {
            options.LogFilename = logFilePath;
            if (appendLogFile)
              options.AppendLogFile = appendLogFile;
              }

              if (timeout > 0) {
            options.TimeLimit = timeout * 1000;
              }

              options.Parse(CommandLineOptions.Clo.ProverOptions);

              ContextCacheKey key = new ContextCacheKey(prog);
              ProverInterface prover;

              if (vcgen.CheckerCommonState == null) {
            vcgen.CheckerCommonState = new Dictionary<ContextCacheKey, ProverContext>();
              }
              IDictionary<ContextCacheKey, ProverContext>/*!>!*/ cachedContexts = (IDictionary<ContextCacheKey, ProverContext/*!*/>)vcgen.CheckerCommonState;

              if (ctx == null && cachedContexts.TryGetValue(key, out ctx))
              {
            ctx = (ProverContext)cce.NonNull(ctx).Clone();
            prover = (ProverInterface)
              CommandLineOptions.Clo.TheProverFactory.SpawnProver(options, ctx);
              } else {
            if (ctx == null) ctx = (ProverContext)CommandLineOptions.Clo.TheProverFactory.NewProverContext(options);

            Setup(prog, ctx);

            // we first generate the prover and then store a clone of the
            // context in the cache, so that the prover can setup stuff in
            // the context to be cached
            prover = (ProverInterface)
              CommandLineOptions.Clo.TheProverFactory.SpawnProver(options, ctx);
            cachedContexts.Add(key, cce.NonNull((ProverContext)ctx.Clone()));
              }

              this.thmProver = prover;
              this.gen = prover.VCExprGen;
        }
Exemplo n.º 51
0
    internal MapTypeAbstractionBuilderArguments(TypeAxiomBuilderArguments axBuilder, VCExpressionGenerator gen)
      : base(axBuilder, gen) {
      Contract.Requires(gen != null);
      Contract.Requires(axBuilder != null);

      this.AxBuilderArguments = axBuilder;
    }
Exemplo n.º 52
0
 public override void Reset(VCExpressionGenerator gen)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 53
0
        /// <summary>
        /// Computes the wlp for an assert or assume command "cmd".
        /// </summary>
        public static VCExpr Cmd(Block b, Cmd cmd, VCExpr N, VCContext ctxt)
        {
            Contract.Requires(cmd != null);
            Contract.Requires(N != null);
            Contract.Requires(ctxt != null);
            Contract.Ensures(Contract.Result <VCExpr>() != null);

            VCExpressionGenerator gen = ctxt.Ctxt.ExprGen;

            Contract.Assert(gen != null);
            if (cmd is AssertCmd)
            {
                AssertCmd ac = (AssertCmd)cmd;

                var isFullyVerified = false;
                if (ac.VerifiedUnder != null)
                {
                    var litExpr = ac.VerifiedUnder as LiteralExpr;
                    isFullyVerified = litExpr != null && litExpr.IsTrue;
                }

                if (!isFullyVerified)
                {
                    ctxt.Ctxt.BoogieExprTranslator.isPositiveContext = !ctxt.Ctxt.BoogieExprTranslator.isPositiveContext;
                }

                VCExpr C = ctxt.Ctxt.BoogieExprTranslator.Translate(ac.Expr);

                VCExpr VU = null;
                if (!isFullyVerified)
                {
                    if (ac.VerifiedUnder != null)
                    {
                        VU = ctxt.Ctxt.BoogieExprTranslator.Translate(ac.VerifiedUnder);
                    }
                    ctxt.Ctxt.BoogieExprTranslator.isPositiveContext = !ctxt.Ctxt.BoogieExprTranslator.isPositiveContext;
                }

                VCExpr R = null;
                if (CommandLineOptions.Clo.vcVariety == CommandLineOptions.VCVariety.Doomed)
                {
                    R = gen.Implies(C, N);
                }
                else
                {
                    var subsumption = Subsumption(ac);
                    if (subsumption == CommandLineOptions.SubsumptionOption.Always ||
                        (subsumption == CommandLineOptions.SubsumptionOption.NotForQuantifiers && !(C is VCExprQuantifier)))
                    {
                        N = gen.ImpliesSimp(C, N, false);
                    }

                    if (isFullyVerified)
                    {
                        return(N);
                    }
                    else if (VU != null)
                    {
                        C = gen.OrSimp(VU, C);
                    }

                    int id = ac.UniqueId;
                    if (ctxt.Label2absy != null)
                    {
                        ctxt.Label2absy[id] = ac;
                    }

                    ctxt.AssertionCount++;

                    if (ctxt.ControlFlowVariableExpr == null)
                    {
                        Contract.Assert(ctxt.Label2absy != null);
                        R = gen.AndSimp(gen.LabelNeg(cce.NonNull(id.ToString()), C), N);
                    }
                    else
                    {
                        VCExpr controlFlowFunctionAppl = gen.ControlFlowFunctionApplication(ctxt.ControlFlowVariableExpr, gen.Integer(BigNum.FromInt(b.UniqueId)));
                        Contract.Assert(controlFlowFunctionAppl != null);
                        VCExpr assertFailure = gen.Eq(controlFlowFunctionAppl, gen.Integer(BigNum.FromInt(-ac.UniqueId)));
                        if (ctxt.Label2absy == null)
                        {
                            R = gen.AndSimp(gen.Implies(assertFailure, C), N);
                        }
                        else
                        {
                            R = gen.AndSimp(gen.LabelNeg(cce.NonNull(id.ToString()), gen.Implies(assertFailure, C)), N);
                        }
                    }
                }
                return(R);
            }
            else if (cmd is AssumeCmd)
            {
                AssumeCmd ac = (AssumeCmd)cmd;

                if (CommandLineOptions.Clo.StratifiedInlining > 0)
                {
                    // Label the assume if it is a procedure call
                    NAryExpr naryExpr = ac.Expr as NAryExpr;
                    if (naryExpr != null)
                    {
                        if (naryExpr.Fun is FunctionCall)
                        {
                            int id = ac.UniqueId;
                            ctxt.Label2absy[id] = ac;
                            return(gen.ImpliesSimp(gen.LabelPos(cce.NonNull("si_fcall_" + id.ToString()), ctxt.Ctxt.BoogieExprTranslator.Translate(ac.Expr)), N));
                        }
                    }
                }
                return(gen.ImpliesSimp(ctxt.Ctxt.BoogieExprTranslator.Translate(ac.Expr), N));
            }
            else
            {
                Console.WriteLine(cmd.ToString());
                Contract.Assert(false); throw new cce.UnreachableException(); // unexpected command
            }
        }
Exemplo n.º 54
0
Arquivo: Wlp.cs Projeto: wrwg/boogie
        /// <summary>
        /// Computes the wlp for an assert or assume command "cmd".
        /// </summary>
        internal static VCExpr Cmd(Block b, Cmd cmd, VCExpr N, VCContext ctxt)
        {
            Contract.Requires(cmd != null);
            Contract.Requires(N != null);
            Contract.Requires(ctxt != null);
            Contract.Ensures(Contract.Result <VCExpr>() != null);

            VCExpressionGenerator gen = ctxt.Ctxt.ExprGen;

            Contract.Assert(gen != null);
            if (cmd is AssertCmd)
            {
                AssertCmd ac = (AssertCmd)cmd;

                var isFullyVerified = false;
                if (ac.VerifiedUnder != null)
                {
                    var litExpr = ac.VerifiedUnder as LiteralExpr;
                    isFullyVerified = litExpr != null && litExpr.IsTrue;
                }

                if (!isFullyVerified)
                {
                    ctxt.Ctxt.BoogieExprTranslator.isPositiveContext = !ctxt.Ctxt.BoogieExprTranslator.isPositiveContext;
                }

                VCExpr C = ctxt.Ctxt.BoogieExprTranslator.Translate(ac.Expr);

                VCExpr VU = null;
                if (!isFullyVerified)
                {
                    if (ac.VerifiedUnder != null)
                    {
                        VU = ctxt.Ctxt.BoogieExprTranslator.Translate(ac.VerifiedUnder);

                        if (CommandLineOptions.Clo.RunDiagnosticsOnTimeout)
                        {
                            ctxt.Ctxt.TimeoutDiagnosticIDToAssertion[ctxt.Ctxt.TimeoutDiagnosticsCount] =
                                new Tuple <AssertCmd, TransferCmd>(ac, b.TransferCmd);
                            VU = gen.Or(VU,
                                        gen.Function(VCExpressionGenerator.TimeoutDiagnosticsOp,
                                                     gen.Integer(BigNum.FromInt(ctxt.Ctxt.TimeoutDiagnosticsCount++))));
                        }
                    }
                    else if (CommandLineOptions.Clo.RunDiagnosticsOnTimeout)
                    {
                        ctxt.Ctxt.TimeoutDiagnosticIDToAssertion[ctxt.Ctxt.TimeoutDiagnosticsCount] =
                            new Tuple <AssertCmd, TransferCmd>(ac, b.TransferCmd);
                        VU = gen.Function(VCExpressionGenerator.TimeoutDiagnosticsOp,
                                          gen.Integer(BigNum.FromInt(ctxt.Ctxt.TimeoutDiagnosticsCount++)));
                    }

                    ctxt.Ctxt.BoogieExprTranslator.isPositiveContext = !ctxt.Ctxt.BoogieExprTranslator.isPositiveContext;
                }

                {
                    var subsumption = Subsumption(ac);
                    if (subsumption == CommandLineOptions.SubsumptionOption.Always ||
                        (subsumption == CommandLineOptions.SubsumptionOption.NotForQuantifiers && !(C is VCExprQuantifier)))
                    {
                        N = gen.ImpliesSimp(C, N, false);
                    }

                    if (isFullyVerified)
                    {
                        return(N);
                    }
                    else if (VU != null)
                    {
                        C = gen.OrSimp(VU, C);
                    }

                    int id = ac.UniqueId;
                    if (ctxt.Label2absy != null)
                    {
                        ctxt.Label2absy[id] = ac;
                    }

                    ctxt.AssertionCount++;

                    if (ctxt.ControlFlowVariableExpr == null)
                    {
                        Contract.Assert(ctxt.Label2absy != null);
                        return(gen.AndSimp(C, N));
                    }
                    else
                    {
                        VCExpr controlFlowFunctionAppl = gen.ControlFlowFunctionApplication(ctxt.ControlFlowVariableExpr,
                                                                                            gen.Integer(BigNum.FromInt(b.UniqueId)));
                        Contract.Assert(controlFlowFunctionAppl != null);
                        VCExpr assertFailure = gen.Eq(controlFlowFunctionAppl, gen.Integer(BigNum.FromInt(-ac.UniqueId)));
                        return(gen.AndSimp(gen.Implies(assertFailure, C), N));
                    }
                }
            }
            else if (cmd is AssumeCmd)
            {
                AssumeCmd ac = (AssumeCmd)cmd;

                if (CommandLineOptions.Clo.StratifiedInlining > 0)
                {
                    // Label the assume if it is a procedure call
                    NAryExpr naryExpr = ac.Expr as NAryExpr;
                    if (naryExpr != null)
                    {
                        if (naryExpr.Fun is FunctionCall)
                        {
                            int id = ac.UniqueId;
                            ctxt.Label2absy[id] = ac;
                            return(MaybeWrapWithOptimization(ctxt, gen, ac.Attributes,
                                                             gen.ImpliesSimp(ctxt.Ctxt.BoogieExprTranslator.Translate(ac.Expr), N)));
                        }
                    }
                }

                var expr = ctxt.Ctxt.BoogieExprTranslator.Translate(ac.Expr);

                var aid = QKeyValue.FindStringAttribute(ac.Attributes, "id");
                if (aid != null)
                {
                    var isTry = QKeyValue.FindBoolAttribute(ac.Attributes, "try");
                    var v     = gen.Variable((isTry ? "try$$" : "assume$$") + aid, Microsoft.Boogie.Type.Bool);
                    expr = gen.Function(VCExpressionGenerator.NamedAssumeOp, v, gen.ImpliesSimp(v, expr));
                }

                var soft       = QKeyValue.FindBoolAttribute(ac.Attributes, "soft");
                var softWeight = QKeyValue.FindIntAttribute(ac.Attributes, "soft", 0);
                if ((soft || 0 < softWeight) && aid != null)
                {
                    var v = gen.Variable("soft$$" + aid, Microsoft.Boogie.Type.Bool);
                    expr = gen.Function(new VCExprSoftOp(Math.Max(softWeight, 1)), v, gen.ImpliesSimp(v, expr));
                }

                return(MaybeWrapWithOptimization(ctxt, gen, ac.Attributes, gen.ImpliesSimp(expr, N)));
            }
            else
            {
                Console.WriteLine(cmd.ToString());
                Contract.Assert(false);
                throw new cce.UnreachableException(); // unexpected command
            }
        }
Exemplo n.º 55
0
 public SMTLibProverContext(VCExpressionGenerator gen,
                            VCGenerationOptions genOptions)
   : base(gen, genOptions)
 {
 }
Exemplo n.º 56
0
    public override object NewProverContext(ProverOptions options)
    {
      //Contract.Requires(options != null);
      Contract.Ensures(Contract.Result<object>() != null);

      if (CommandLineOptions.Clo.BracketIdsInVC < 0) {
        CommandLineOptions.Clo.BracketIdsInVC = 0;
      }

      VCExpressionGenerator gen = new VCExpressionGenerator();
      List<string>/*!>!*/ proverCommands = new List<string/*!*/>();
      proverCommands.Add("tptp");
      proverCommands.Add("external");
      VCGenerationOptions genOptions = new VCGenerationOptions(proverCommands);
      Contract.Assert(genOptions != null);

      return new DeclFreeProverContext(gen, genOptions);
    }