Beispiel #1
0
        public QuantifierExpr RewriteMatchingLoops(QuantifierWithTriggers q)
        {
            // rewrite quantifier to avoid mathing loops
            // before:
            //    assert forall i :: 0 <= i < a.Length-1 ==> a[i] <= a[i+1];
            // after:
            //    assert forall i,j :: j == i+1 ==> 0 <= i < a.Length-1 ==> a[i] <= a[i+1];
            substMap = new Dictionary <Expression, IdentifierExpr>();
            usedMap  = new Dictionary <Expression, IdentifierExpr>();
            foreach (var m in q.LoopingMatches)
            {
                var e = m.OriginalExpr;
                if (TriggersCollector.IsPotentialTriggerCandidate(e) && triggersCollector.IsTriggerKiller(e))
                {
                    foreach (var sub in e.SubExpressions)
                    {
                        if (triggersCollector.IsTriggerKiller(sub) && (!TriggersCollector.IsPotentialTriggerCandidate(sub)))
                        {
                            IdentifierExpr ie;
                            if (!substMap.TryGetValue(sub, out ie))
                            {
                                var newBv = new BoundVar(sub.tok, "_t#" + substMap.Count, sub.Type);
                                ie            = new IdentifierExpr(sub.tok, newBv.Name);
                                ie.Var        = newBv;
                                ie.Type       = newBv.Type;
                                substMap[sub] = ie;
                            }
                        }
                    }
                }
            }

            var expr = (QuantifierExpr)q.quantifier;

            if (substMap.Count > 0)
            {
                var s = new Translator.ExprSubstituter(substMap);
                expr = s.Substitute(q.quantifier) as QuantifierExpr;
            }
            else
            {
                // make a copy of the expr
                if (expr is ForallExpr)
                {
                    expr = new ForallExpr(expr.tok, expr.TypeArgs, expr.BoundVars, expr.Range, expr.Term, TriggerUtils.CopyAttributes(expr.Attributes))
                    {
                        Type = expr.Type
                    };
                }
                else
                {
                    expr = new ExistsExpr(expr.tok, expr.TypeArgs, expr.BoundVars, expr.Range, expr.Term, TriggerUtils.CopyAttributes(expr.Attributes))
                    {
                        Type = expr.Type
                    };
                }
            }
            return(expr);
        }
Beispiel #2
0
        public override Expr VisitExistsExpr(ExistsExpr node)
        {
            BoundVariables.UnionWith(node.Dummies);
            var toReturn = base.VisitExistsExpr(node);

            BoundVariables.RemoveWhere(e => node.Dummies.Contains(e));
            return(toReturn);
        }
 public override Expr VisitExistsExpr(ExistsExpr node)
 {
     if (GetReplacementVariable(node, out var variable))
     {
         return(new IdentifierExpr(variable.tok, variable));
     }
     return(base.VisitExistsExpr(node));
 }
Beispiel #4
0
        public QuantifierExpr RewriteMatchingLoops(QuantifierWithTriggers q)
        {
            // rewrite quantifier to avoid matching loops
            // before:
            //    assert forall i :: 0 <= i < a.Length-1 ==> a[i] <= a[i+1];
            // after:
            //    assert forall i,j :: j == i+1 ==> 0 <= i < a.Length-1 ==> a[i] <= a[j];
            substMap = new List <Tuple <Expression, IdentifierExpr> >();
            foreach (var m in q.LoopingMatches)
            {
                var e = m.OriginalExpr;
                if (TriggersCollector.IsPotentialTriggerCandidate(e) && triggersCollector.IsTriggerKiller(e))
                {
                    foreach (var sub in e.SubExpressions)
                    {
                        if (triggersCollector.IsTriggerKiller(sub) && (!TriggersCollector.IsPotentialTriggerCandidate(sub)))
                        {
                            var entry = substMap.Find(x => ExprExtensions.ExpressionEq(sub, x.Item1));
                            if (entry == null)
                            {
                                var newBv = new BoundVar(sub.tok, "_t#" + substMap.Count, sub.Type);
                                var ie    = new IdentifierExpr(sub.tok, newBv.Name);
                                ie.Var  = newBv;
                                ie.Type = newBv.Type;
                                substMap.Add(new Tuple <Expression, IdentifierExpr>(sub, ie));
                            }
                        }
                    }
                }
            }

            var expr = (QuantifierExpr)q.quantifier;

            if (substMap.Count > 0)
            {
                var s = new ExprSubstituter(substMap);
                expr = s.Substitute(q.quantifier) as QuantifierExpr;
            }
            else
            {
                // make a copy of the expr
                if (expr is ForallExpr)
                {
                    expr = new ForallExpr(expr.tok, expr.TypeArgs, expr.BoundVars, expr.Range, expr.Term, TriggerUtils.CopyAttributes(expr.Attributes))
                    {
                        Type = expr.Type, Bounds = expr.Bounds
                    };
                }
                else
                {
                    expr = new ExistsExpr(expr.tok, expr.TypeArgs, expr.BoundVars, expr.Range, expr.Term, TriggerUtils.CopyAttributes(expr.Attributes))
                    {
                        Type = expr.Type, Bounds = expr.Bounds
                    };
                }
            }
            return(expr);
        }
Beispiel #5
0
 public void CachedHashCodeExistsExpr()
 {
   var x = new BoundVariable(Token.NoToken, new TypedIdent(Token.NoToken, "x", BasicType.Int));
   var y = new BoundVariable(Token.NoToken, new TypedIdent(Token.NoToken, "x", BasicType.Int));
   var body = Expr.Gt(new IdentifierExpr(Token.NoToken, x, /*immutable=*/true),
     new IdentifierExpr(Token.NoToken, y, /*immutable=*/true));
   var exists = new ExistsExpr(Token.NoToken, new List<Variable>() {x, y}, body, /*immutable=*/ true);
   Assert.AreEqual(exists.ComputeHashCode(), exists.GetHashCode());
 }
Beispiel #6
0
 public void ProtectedExistsExprBody()
 {
   var x = new BoundVariable(Token.NoToken, new TypedIdent(Token.NoToken, "x", BasicType.Int));
   var y = new BoundVariable(Token.NoToken, new TypedIdent(Token.NoToken, "x", BasicType.Int));
   var xId = new IdentifierExpr(Token.NoToken, x, /*immutable=*/true);
   var yId = new IdentifierExpr(Token.NoToken, y, /*immutable=*/true);
   var body = Expr.Gt(xId, yId);
   var exists = new ExistsExpr(Token.NoToken, new List<Variable>() {x, y}, body, /*immutable=*/true);
   // Changing the body of an immutable ExistsExpr should fail
   Assert.Throws(typeof(InvalidOperationException), () => exists.Body = Expr.Lt(xId, yId));
 }
        public static Expr GetChild(this ExistsExpr e, int number)
        {
            switch (number)
            {
            case 0:
                return(e.Body);

            default:
                throw new InvalidOperationException("ExistsExpr only has one child");
            }
        }
        public static void SetChild(this ExistsExpr e, int number, Expr NewChild)
        {
            switch (number)
            {
            case 0:
                e.Body = NewChild;
                return;

            default:
                throw new InvalidOperationException("ExistsExpr only has one child");
            }
        }
Beispiel #9
0
        public override Expr VisitExistsExpr(ExistsExpr node)
        {
            var bodyCopy = this.Visit(node.Body) as Expr;

            Debug.Assert(bodyCopy != null);
            var freeVars    = new List <Variable>(node.Dummies);
            var newTriggers = this.VisitTrigger(node.Triggers);
            var newNode     = Builder.Exists(freeVars, bodyCopy, newTriggers);

            Debug.Assert(newNode != null);
            return(newNode);
        }
Beispiel #10
0
        public override QuantifierExpr VisitQuantifierExpr(QuantifierExpr node)
        {
            var oldE = existentialExpr;

            if (node is ExistsExpr)
            {
                existentialExpr = (node as ExistsExpr);
            }

            node = base.VisitQuantifierExpr(node);

            existentialExpr = oldE;
            return(node);
        }
Beispiel #11
0
        public Expr Exists(IList <Variable> freeVars, Expr body, Trigger triggers = null)
        {
            if (!body.Type.IsBool)
            {
                throw new ExprTypeCheckException("body must be of type bool");
            }

            if (freeVars.Count < 1)
            {
                throw new ArgumentException("ExistsExpr must have at least one free variable");
            }

            TypeCheckTriggers(freeVars, body, triggers);

            // Should we check the free variables are actually used? This could be quite expensive to do!
            var result = new ExistsExpr(Token.NoToken, new List <Variable>(freeVars), triggers, body, Immutable);

            result.Type = BasicType.Bool;
            return(result);
        }
Beispiel #12
0
        public void SimpleExists()
        {
            var boundVar = new BoundVariable(Token.NoToken, new TypedIdent(Token.NoToken, "foo", Microsoft.Boogie.Type.Bool));
            var id       = new IdentifierExpr(Token.NoToken, boundVar);
            var exists   = new ExistsExpr(Token.NoToken, new List <Variable>()
            {
                boundVar
            }, id);

            var id2     = new IdentifierExpr(Token.NoToken, boundVar);
            var exists2 = new ExistsExpr(Token.NoToken, new List <Variable>()
            {
                boundVar
            }, id2);

            Assert.AreNotSame(exists, exists2);                           // These are different references

            Assert.IsTrue(exists.Equals(exists2));                        // These are "structurally equal"
            Assert.AreEqual(exists.GetHashCode(), exists2.GetHashCode()); // If the .Equals() is true then hash codes must be the same
        }
Beispiel #13
0
 private static bool ShallowEq(ExistsExpr expr1, ExistsExpr expr2)
 {
     return(true);
 }
Beispiel #14
0
 public override Expr VisitExistsExpr(ExistsExpr node)
 {
     return(node);
 }
        public Expression GetNode(ExpressionParser parser)
        {
            Lexem      lex = parser.Collection.CurrentLexem();
            Expression res = null;

            if (lex.LexemType == LexType.Command)
            {
                string lowerLexem = lex.LexemText.ToLower();
                if (ParserUtils.ParseCommandPhrase(parser.Collection, "create view", false, false))
                {
                    res = new CreateView();
                }
                if (ParserUtils.ParseCommandPhrase(parser.Collection, "create table", false, false))
                {
                    res = new CreateTable();
                }
                if (res == null && ParserUtils.ParseCommandPhrase(parser.Collection, "alter table", false, false))
                {
                    res = new AlterTable();
                }
                if (res == null && ParserUtils.ParseCommandPhrase(parser.Collection, "drop table", false, false))
                {
                    res = new DropTable();
                }
                if (res == null && ParserUtils.ParseCommandPhrase(parser.Collection, "drop index", false, false))
                {
                    res = new DropIndex();
                }
                if (res == null && (ParserUtils.ParseCommandPhrase(parser.Collection, "create unique index", false, false) ||
                                    ParserUtils.ParseCommandPhrase(parser.Collection, "create index", false, false)))
                {
                    res = new CreateIndex();
                }
                if (res == null)
                {
                    if (parser.Collection.GetNext() != null && parser.Collection.GetNext().IsSkobraOpen())
                    {
                        switch (lowerLexem)
                        {
                        case "count":
                            res = new CountExpr();
                            break;

                        case "sum":
                            res = new SumExpr();
                            break;

                        case "min":
                            res = new MinExpr();
                            break;

                        case "max":
                            res = new MaxExpr();
                            break;

                        case "avg":
                            res = new AvgExpr();
                            break;

                        case "lastinsertrowid":
                            res = new LastInsertRowidExpr();
                            break;

                        case "exists":
                            res = new ExistsExpr();
                            break;

                        case "any":
                            res = new AnyExpr();
                            break;
                        }
                    }

                    switch (lowerLexem)
                    {
                    case "between":    //не функция
                        res = new Between();
                        break;

                    case "select":
                        res = new SelectExpresion();
                        break;

                    case "update":
                        res = new UpdateStatement();
                        break;

                    case "insert":
                        res = new InsertStatement();
                        break;

                    case "delete":
                        res = new DeleteStatement();
                        break;
                    }
                }
            }
            if (res != null)
            {
                return(res);
            }
            return(res);
        }
Beispiel #16
0
 // group split quantifier by what triggers they got, and merged them back into one quantifier.
 private void CombineSplitQuantifier()
 {
     if (quantifiers.Count > 1)
     {
         List <QuantifierGroup> groups = new List <QuantifierGroup>();
         groups.Add(new QuantifierGroup(quantifiers[0], new List <ComprehensionExpr> {
             quantifiers[0].quantifier
         }));
         for (int i = 1; i < quantifiers.Count; i++)
         {
             bool found = false;
             for (int j = 0; j < groups.Count; j++)
             {
                 if (HasSameTriggers(quantifiers[i], groups[j].quantifier))
                 {
                     // belong to the same group
                     groups[j].expressions.Add(quantifiers[i].quantifier);
                     found = true;
                     break;
                 }
             }
             if (!found)
             {
                 // start a new group
                 groups.Add(new QuantifierGroup(quantifiers[i], new List <ComprehensionExpr> {
                     quantifiers[i].quantifier
                 }));
             }
         }
         if (groups.Count == quantifiers.Count)
         {
             // have the same number of splits, so no splits are combined.
             return;
         }
         // merge expressions in each group back to one quantifier.
         List <QuantifierWithTriggers> list   = new List <QuantifierWithTriggers>();
         List <Expression>             splits = new List <Expression>();
         foreach (var group in groups)
         {
             QuantifierWithTriggers q = group.quantifier;
             if (q.quantifier is ForallExpr)
             {
                 ForallExpr quantifier = (ForallExpr)q.quantifier;
                 Expression expr       = QuantifiersToExpression(quantifier.tok, BinaryExpr.ResolvedOpcode.And, group.expressions);
                 q.quantifier = new ForallExpr(quantifier.tok, quantifier.TypeArgs, quantifier.BoundVars, quantifier.Range, expr, TriggerUtils.CopyAttributes(quantifier.Attributes))
                 {
                     Type = quantifier.Type, Bounds = quantifier.Bounds
                 };
             }
             else if (q.quantifier is ExistsExpr)
             {
                 ExistsExpr quantifier = (ExistsExpr)q.quantifier;
                 Expression expr       = QuantifiersToExpression(quantifier.tok, BinaryExpr.ResolvedOpcode.Or, group.expressions);
                 q.quantifier = new ExistsExpr(quantifier.tok, quantifier.TypeArgs, quantifier.BoundVars, quantifier.Range, expr, TriggerUtils.CopyAttributes(quantifier.Attributes))
                 {
                     Type = quantifier.Type, Bounds = quantifier.Bounds
                 };
             }
             list.Add(q);
             splits.Add(q.quantifier);
         }
         this.quantifiers = list;
         Contract.Assert(this.expr is QuantifierExpr); // only QuantifierExpr has SplitQuantifier
         ((QuantifierExpr)this.expr).SplitQuantifier = splits;
     }
 }
Beispiel #17
0
 public override Expr VisitExistsExpr(ExistsExpr node)
 {
     add(node);
     return(base.VisitExistsExpr(node));
 }
Beispiel #18
0
 public Expr VisitExistExpr(ExistsExpr e)
 {
     return(PrintQuantifierExpr(e));
 }
Beispiel #19
0
 public override Expr VisitExistsExpr(ExistsExpr node)
 {
     return(base.VisitExistsExpr((ExistsExpr)node.Clone()));
 }
Beispiel #20
0
        public override Expression Substitute(Expression expr)
        {
            if (TryGetExprSubst(expr, out var ie))
            {
                Contract.Assert(ie != null);
                return(ie);
            }
            if (expr is QuantifierExpr e)
            {
                var newAttrs  = SubstAttributes(e.Attributes);
                var newRange  = e.Range == null ? null : Substitute(e.Range);
                var newTerm   = Substitute(e.Term);
                var newBounds = SubstituteBoundedPoolList(e.Bounds);
                if (newAttrs == e.Attributes && newRange == e.Range && newTerm == e.Term && newBounds == e.Bounds)
                {
                    return(e);
                }

                var newBoundVars = new List <BoundVar>(e.BoundVars);
                if (newBounds == null)
                {
                    newBounds = new List <ComprehensionExpr.BoundedPool>();
                }
                else if (newBounds == e.Bounds)
                {
                    // create a new list with the same elements, since the .Add operations below would otherwise add elements to the original e.Bounds
                    newBounds = new List <ComprehensionExpr.BoundedPool>(newBounds);
                }

                // conjoin all the new equalities to the range of the quantifier
                foreach (var entry in usedSubstMap)
                {
                    var eq = new BinaryExpr(e.tok, BinaryExpr.ResolvedOpcode.EqCommon, entry.Item2, entry.Item1);
                    newRange = newRange == null ? eq : new BinaryExpr(e.tok, BinaryExpr.ResolvedOpcode.And, eq, newRange);
                    newBoundVars.Add((BoundVar)entry.Item2.Var);
                    newBounds.Add(new ComprehensionExpr.ExactBoundedPool(entry.Item1));
                }

                QuantifierExpr newExpr;
                if (expr is ForallExpr)
                {
                    newExpr = new ForallExpr(e.tok, e.TypeArgs, newBoundVars, newRange, newTerm, newAttrs)
                    {
                        Bounds = newBounds
                    };
                }
                else
                {
                    Contract.Assert(expr is ExistsExpr);
                    newExpr = new ExistsExpr(e.tok, e.TypeArgs, newBoundVars, newRange, newTerm, newAttrs)
                    {
                        Bounds = newBounds
                    };
                }
                usedSubstMap.Clear();

                newExpr.Type = expr.Type;
                return(newExpr);
            }
            return(base.Substitute(expr));
        }
Beispiel #21
0
    public RtlExp GhostExpressionRec(Expression exp, bool inRecSpec = false, bool inRequiresOrOld = false)
    {
        Util.Assert(!isPrinting);
        exp = GetExp(exp);
        StmtExpr         stmtExpr    = exp as StmtExpr;
        IdentifierExpr   idExp       = exp as IdentifierExpr;
        LiteralExpr      literal     = exp as LiteralExpr;
        BinaryExpr       binary      = exp as BinaryExpr;
        UnaryExpr        unary       = exp as UnaryExpr;
        ITEExpr          ite         = exp as ITEExpr;
        ExistsExpr       existsExp   = exp as ExistsExpr;
        ForallExpr       forallExp   = exp as ForallExpr;
        LetExpr          letExp      = exp as LetExpr;
        MatchExpr        matchExp    = exp as MatchExpr;
        OldExpr          oldExp      = exp as OldExpr;
        FreshExpr        freshExp    = exp as FreshExpr;
        FunctionCallExpr funCall     = exp as FunctionCallExpr;
        DatatypeValue    dataVal     = exp as DatatypeValue;
        FieldSelectExpr  fieldSelect = exp as FieldSelectExpr;
        SeqSelectExpr    seqSelect   = exp as SeqSelectExpr;
        SeqUpdateExpr    seqUpdate   = exp as SeqUpdateExpr;
        SeqDisplayExpr   seqDisplay  = exp as SeqDisplayExpr;

        Func <Expression, RtlExp> G = e => GhostExpression(e, inRecSpec, inRequiresOrOld);

        if (stmtExpr != null)
        {
            if (stmtExprEnabled)
            {
                if (ignoreStmtExpr == 0)
                {
                    AddGhostStatement(stmtExpr.S);
                }
                return(G(stmtExpr.E));
            }
            else
            {
                throw new Exception("not implemented: cannot handle statement expression here");
            }
        }
        else if (idExp != null)
        {
            return(AsVar(idExp));
        }
        else if (literal != null && literal.Value is BigInteger)
        {
            return(new RtlInt((BigInteger)(literal.Value)));
        }
        else if (literal != null && literal.Value is bool)
        {
            return(new RtlLiteral((bool)(literal.Value) ? "true" : "false"));
        }
        else if (literal != null && literal.Value == null)
        {
            return(new RtlLiteral("ArrayOfInt(0 - 1, NO_ABS)"));
        }
        else if (literal != null && literal.Value is Microsoft.Basetypes.BigDec)
        {
            return(new RtlLiteral(((Microsoft.Basetypes.BigDec)literal.Value).ToDecimalString()));
        }
        else if (binary != null)
        {
            string          op              = null;
            string          internalOp      = null;
            CompileFunction compileFunction = this as CompileFunction;
            string          thisFuncName    = (compileFunction == null) ? null : compileFunction.function.Name;
            switch (binary.ResolvedOp)
            {
            case BinaryExpr.ResolvedOpcode.SeqEq:
                return(new RtlApply(dafnySpec.GetSeqOperationName(AppType(binary.E0.Type), "Seq_Equal"),
                                    new RtlExp[] { G(binary.E0), G(binary.E1) }));

            case BinaryExpr.ResolvedOpcode.SeqNeq:
                return(new RtlLiteral("(!" +
                                      new RtlApply(dafnySpec.GetSeqOperationName(AppType(binary.E0.Type), "Seq_Equal"),
                                                   new RtlExp[] { G(binary.E0), G(binary.E1) }) + ")"));

            case BinaryExpr.ResolvedOpcode.Concat:
                return(new RtlApply(dafnySpec.GetSeqOperationName(AppType(binary.Type), "Seq_Append"),
                                    new RtlExp[] { G(binary.E0), G(binary.E1) }));
            }
            if (binary.Op == BinaryExpr.Opcode.Exp)
            {
                binary = new BinaryExpr(binary.tok, BinaryExpr.Opcode.Imp, binary.E0, binary.E1);
            }
            switch (binary.Op)
            {
            case BinaryExpr.Opcode.Disjoint:
            case BinaryExpr.Opcode.In:
            case BinaryExpr.Opcode.NotIn:
                throw new Exception("not implemented: binary operator '" + BinaryExpr.OpcodeString(binary.Op) + "'");
            }
            if (AppType(binary.E0.Type) is IntType && AppType(binary.E1.Type) is IntType)
            {
                switch (binary.Op)
                {
                case BinaryExpr.Opcode.Le: internalOp = "INTERNAL_le_boogie"; break;

                case BinaryExpr.Opcode.Lt: internalOp = "INTERNAL_lt_boogie"; break;

                case BinaryExpr.Opcode.Ge: internalOp = "INTERNAL_ge_boogie"; break;

                case BinaryExpr.Opcode.Gt: internalOp = "INTERNAL_gt_boogie"; break;

                case BinaryExpr.Opcode.Add: internalOp = "INTERNAL_add_boogie"; break;

                case BinaryExpr.Opcode.Sub: internalOp = "INTERNAL_sub_boogie"; break;

                case BinaryExpr.Opcode.Mul:
                    op = "*";
                    if (thisFuncName != "INTERNAL_mul")
                    {
                        internalOp = FunName("INTERNAL__mul");
                    }
                    break;

                case BinaryExpr.Opcode.Div:
                    op = "div";
                    if (thisFuncName != "INTERNAL_div")
                    {
                        internalOp = FunName("INTERNAL__div");
                    }
                    break;

                case BinaryExpr.Opcode.Mod:
                    op = "mod";
                    if (thisFuncName != "INTERNAL_mod")
                    {
                        internalOp = FunName("INTERNAL__mod");
                    }
                    break;

                default:
                    op = BinaryExpr.OpcodeString(binary.Op);
                    break;
                }
            }
            else
            {
                op = BinaryExpr.OpcodeString(binary.Op);
            }
            if (internalOp == null)
            {
                return(new RtlBinary(op, G(binary.E0), G(binary.E1)));
            }
            else
            {
                return(new RtlApply(internalOp, new RtlExp[]
                                    { G(binary.E0), G(binary.E1) }));
            }
        }
        else if (unary != null && unary.Op == UnaryExpr.Opcode.Not)
        {
            return(new RtlLiteral("(!(" + G(unary.E) + "))"));
        }
        else if (unary != null && unary.Op == UnaryExpr.Opcode.SeqLength)
        {
            return(new RtlApply(dafnySpec.GetSeqOperationName(AppType(unary.E.Type), "Seq_Length"),
                                new RtlExp[] { G(unary.E) }));
        }
        else if (ite != null)
        {
            return(GhostIfThenElse(G(ite.Test), () => G(ite.Thn), () => G(ite.Els)));
        }
        else if (funCall != null)
        {
            switch (funCall.Function.Name)
            {
            case "left":
            case "right":
            case "relation":
            case "public":
                Util.Assert(funCall.Args.Count == 1);
                return(new RtlApply(funCall.Function.Name, new RtlExp[] { G(funCall.Args[0]) }));

            case "sizeof":
                Util.Assert(funCall.Args.Count == 1);
                return(new RtlApply(funCall.Function.Name + "##" + TypeString(AppType(funCall.Args[0].Type)),
                                    new RtlExp[] { G(funCall.Args[0]) }));

            case "INTERNAL_add_raw":
                Util.Assert(funCall.Args.Count == 2);
                return(new RtlBinary("+", G(funCall.Args[0]), G(funCall.Args[1])));

            case "INTERNAL_sub_raw":
                Util.Assert(funCall.Args.Count == 2);
                return(new RtlBinary("-", G(funCall.Args[0]), G(funCall.Args[1])));

            case "IntToReal":
                Util.Assert(funCall.Args.Count == 1);
                return(new RtlApply("real", new RtlExp[] { G(funCall.Args[0]) }));

            case "RealToInt":
                Util.Assert(funCall.Args.Count == 1);
                return(new RtlApply("int", new RtlExp[] { G(funCall.Args[0]) }));
            }
            TypeApply app = dafnySpec.Compile_Function(funCall.Function,
                                                       funCall.TypeArgumentSubstitutions.ToDictionary(p => p.Key, p => AppType(p.Value)));
            string        name     = FunName(SimpleName(app.AppName()));
            string        fullName = FunName(SimpleName(app.AppFullName()));
            List <RtlExp> rtlArgs  = funCall.Args.Select(G).ToList();
            List <RtlExp> rtlReads = funCall.Function.Reads.Where(e => e.Field != null).ToList()
                                     .ConvertAll(e => (RtlExp) new RtlVar(
                                                     GhostVar(e.FieldName), e.Field.IsGhost, AppType(e.Field.Type)));
            rtlArgs = rtlReads.Concat(rtlArgs).ToList();
            if (name.EndsWith("__INTERNAL__HEAP"))
            {
                name = name.Substring(0, name.Length - "__INTERNAL__HEAP".Length);
            }
            else if (DafnySpec.IsHeapFunction(funCall.Function))
            {
                rtlArgs.Insert(0, new RtlLiteral(inRequiresOrOld ? "$absMem_old" : "$absMem"));
            }
            if (Attributes.Contains(funCall.Function.Attributes, "opaque") &&
                funCall.Function.Formals.Count + rtlReads.Count == 0)
            {
                rtlArgs.Insert(0, new RtlLiteral("true"));
            }
            if (fullName == recFunName)
            {
                name = fullName;
            }
            if (name == recFunName)
            {
                recCalls.Add(new List <RtlExp>(rtlArgs));
                rtlArgs.Insert(0, new RtlApply("decreases_" + name, new List <RtlExp>(rtlArgs)));
                rtlArgs.Insert(1, new RtlLiteral(inRecSpec ? "__unroll" : "__unroll + 1"));
                name = "rec_" + name;
            }
            return(new RtlApply(name, rtlArgs));
        }
        else if (dataVal != null)
        {
            bool isSeq = dataVal.Type.TypeName(null).StartsWith("Seq<");
            return(new RtlApply((isSeq ? "_" : "") + dafnySpec.Compile_Constructor(
                                    dataVal.Type, dataVal.Ctor.Name, dataVal.InferredTypeArgs, typeApply.typeArgs).AppName(),
                                dataVal.Arguments.Select(G)));
        }
        else if (existsExp != null || forallExp != null)
        {
            QuantifierExpr qExp               = (QuantifierExpr)exp;
            bool           isForall           = forallExp != null;
            var            varTuples          = qExp.BoundVars.Select(v => Tuple.Create(GhostVar(v.Name), v.IsGhost, v.Type));
            var            oldRenamer         = PushRename(qExp.BoundVars.Select(v => v.Name));
            var            oldStmtExprEnabled = stmtExprEnabled;
            stmtExprEnabled = false;
            RtlExp rExp = new RtlLiteral((isForall ? "(forall " : "(exists ")
                                         + string.Join(", ", qExp.BoundVars.Select(v => GhostVar(v.Name) + ":" + TypeString(AppType(v.Type))))
                                         + " :: " + Triggers(qExp.Attributes, G) + " "
                                         + GetTypeWellFormedExp(varTuples.ToList(), isForall ? "==>" : "&&", G(qExp.Term)) + ")");
            stmtExprEnabled = oldStmtExprEnabled;
            PopRename(oldRenamer);
            return(rExp);
        }
        else if (letExp != null)
        {
            List <RtlExp> rhss;
            if (letExp.Exact)
            {
                rhss = letExp.RHSs.ConvertAll(e => G(e));
            }
            else if (letExp.LHSs.Count == 1 && LiteralExpr.IsTrue(letExp.RHSs[0]) && AppType(letExp.LHSs[0].Var.Type) is IntType)
            {
                rhss = new List <RtlExp> {
                    new RtlLiteral("0")
                };
            }
            else
            {
                throw new Exception("not implemented: LetExpr: " + letExp);
            }
            return(GhostLet(exp.tok, letExp.LHSs.ConvertAll(lhs => lhs.Var), rhss, () => G(letExp.Body)));
        }
        else if (matchExp != null)
        {
            if (matchExp.MissingCases.Count != 0)
            {
                throw new Exception("not implemented: MatchExpr with missing cases: " + matchExp);
            }
            //- match src case c1(ps1) => e1 ... cn(psn) => en
            //-   -->
            //- let x := src in
            //-   if x is c1 then let ps1 := ...x.f1... in e1 else
            //-   if x is c2 then let ps2 := ...x.f2... in e2 else
            //-                   let ps3 := ...x.f3... in e3
            var           src   = G(matchExp.Source);
            var           cases = matchExp.Cases;
            string        x     = TempName();
            Func <RtlExp> body  = null;
            for (int i = cases.Count; i > 0;)
            {
                i--;
                MatchCaseExpr         c     = cases[i];
                Func <List <RtlExp> > cRhss = () => c.Ctor.Formals.ConvertAll(f => (RtlExp) new RtlLiteral("("
                                                                                                           + f.Name + "#" + c.Ctor.Name + "(" + GhostVar(x) + "))"));
                Func <RtlExp> ec = () => GhostLet(exp.tok, c.Arguments, cRhss(), () => G(c.Body));
                if (body == null)
                {
                    body = ec;
                }
                else
                {
                    var prevBody = body;
                    body = () => GhostIfThenElse(new RtlLiteral("(" + GhostVar(x) + " is " + c.Ctor.Name + ")"),
                                                 ec, prevBody);
                }
            }
            return(GhostLet(exp.tok, new List <BoundVar> {
                new BoundVar(exp.tok, x, matchExp.Source.Type)
            },
                            new List <RtlExp> {
                src
            }, body));
        }
        else if (oldExp != null)
        {
            return(new RtlLiteral("old(" + GhostExpression(oldExp.E, inRecSpec, true) + ")"));
        }
        else if (freshExp != null)
        {
            Util.Assert(DafnySpec.IsArrayType(freshExp.E.Type));
            string abs = G(freshExp.E) + ".arrAbs";
            return(new RtlLiteral("(heap_old.absData[" + abs + "] is AbsNone)"));
        }
        else if (fieldSelect != null && fieldSelect.FieldName.EndsWith("?"))
        {
            string constructor = fieldSelect.FieldName.Substring(0, fieldSelect.FieldName.Length - 1);
            constructor = dafnySpec.Compile_Constructor(fieldSelect.Obj.Type, constructor, null, typeApply.typeArgs).AppName();
            bool isSeq = fieldSelect.Obj.Type.TypeName(null).StartsWith("Seq<");
            return(isSeq
                ? new RtlLiteral("is_" + constructor + "(" + G(fieldSelect.Obj) + ")")
                : new RtlLiteral("((" + G(fieldSelect.Obj) + ") is " + constructor + ")"));
        }
        else if (fieldSelect != null && !fieldSelect.Field.IsStatic && AppType(fieldSelect.Obj.Type) is UserDefinedType &&
                 fieldSelect.Field is DatatypeDestructor)
        {
            DatatypeDestructor field       = (DatatypeDestructor)fieldSelect.Field;
            string             constructor = dafnySpec.Compile_Constructor(fieldSelect.Obj.Type,
                                                                           field.EnclosingCtor.Name, null, typeApply.typeArgs).AppName();
            bool isSeq = fieldSelect.Obj.Type.TypeName(null).StartsWith("Seq<");
            return(new RtlLiteral("(" + fieldSelect.FieldName + (isSeq ? "_" : "#") + constructor
                                  + "(" + G(fieldSelect.Obj) + "))"));
        }
        else if (fieldSelect != null && DafnySpec.IsArrayType(AppType(fieldSelect.Obj.Type)) &&
                 fieldSelect.FieldName == "Length")
        {
            return(new RtlLiteral("(Arr_Length(" + G(fieldSelect.Obj) + "))"));
        }
        else if (fieldSelect != null && fieldSelect.Obj is ImplicitThisExpr)
        {
            //- we don't support objects yet, so interpret this as a global variable
            return(new RtlVar(GhostVar(fieldSelect.FieldName), true, fieldSelect.Type));
        }
        else if (seqSelect != null)
        {
            if (seqSelect.SelectOne && DafnySpec.IsArrayType(AppType(seqSelect.Seq.Type)))
            {
                return(new RtlExpComputed(e => "fun_INTERNAL__array__elems__index("
                                          + (inRequiresOrOld ? "$absMem_old" : "$absMem") + "[" + e.args[0] + ".arrAbs], ("
                                          + e.args[1] + "))", new RtlExp[] { G(seqSelect.Seq), G(seqSelect.E0) }));
            }
            else if (seqSelect.SelectOne)
            {
                return(new RtlApply(dafnySpec.GetSeqOperationName(AppType(seqSelect.Seq.Type), "Seq_Index"),
                                    new RtlExp[] { G(seqSelect.Seq), G(seqSelect.E0) }));
            }
            else
            {
                RtlExp seq = G(seqSelect.Seq);
                if (DafnySpec.IsArrayType(AppType(seqSelect.Seq.Type)))
                {
                    seq = new RtlApply(FunName("Seq__FromArray"), new RtlExp[] {
                        new RtlLiteral(inRequiresOrOld ? "$absMem_old" : "$absMem"), seq
                    });
                }
                if (seqSelect.E1 != null)
                {
                    seq = new RtlApply(dafnySpec.GetSeqOperationName(AppType(seqSelect.Type), "Seq_Take"),
                                       new RtlExp[] { seq, G(seqSelect.E1) });
                }
                if (seqSelect.E0 != null)
                {
                    seq = new RtlApply(dafnySpec.GetSeqOperationName(AppType(seqSelect.Type), "Seq_Drop"),
                                       new RtlExp[] { seq, G(seqSelect.E0) });
                }
                return(seq);
            }
        }
        else if (seqUpdate != null)
        {
            if (seqUpdate.ResolvedUpdateExpr != null)
            {
                return(GhostExpressionRec(seqUpdate.ResolvedUpdateExpr, inRecSpec, inRequiresOrOld));
            }
            return(new RtlApply(dafnySpec.GetSeqOperationName(AppType(seqUpdate.Seq.Type), "Seq_Update"),
                                new RtlExp[] { G(seqUpdate.Seq), G(seqUpdate.Index), G(seqUpdate.Value) }));
        }
        else if (seqDisplay != null)
        {
            RtlExp seq = new RtlApply(dafnySpec.GetSeqOperationName(AppType(seqDisplay.Type), "Seq_Empty"), new RtlExp[0]);
            foreach (Expression ei in seqDisplay.Elements)
            {
                seq = new RtlApply(dafnySpec.GetSeqOperationName(AppType(seqDisplay.Type), "Seq_Build"),
                                   new RtlExp[] { seq, G(ei) });
            }
            return(seq);
        }
        else
        {
            throw new Exception("not implemented: " + exp);
        }
    }
Beispiel #22
0
 public FunctionCollector()
 {
     functionsUsed   = new List <Tuple <Function, ExistsExpr> >();
     existentialExpr = null;
 }
 // ExistsExpr
 public static int GetNumberOfChildren(this ExistsExpr e)
 {
     return(1);
 }