コード例 #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="line"></param>
        /// <param name="ns"></param>
        /// <param name="datatype"></param>
        /// <param name="fL"></param>a function list which contains a function to generate stetment list with given line number
        /// <returns></returns>
        private MatchStmt GenerateMatchStmt(int line, NameSegment ns, DatatypeDecl datatype, List <Func <int, List <Statement> > > fL)
        {
            Contract.Requires(ns != null);
            Contract.Requires(datatype != null);
            Contract.Ensures(Contract.Result <MatchStmt>() != null);
            List <MatchCaseStmt> cases = new List <MatchCaseStmt>();
            int index = TacnyDriver.TacticCodeTokLine;//line + 1;


            for (int j = 0; j < datatype.Ctors.Count; j++)
            {
                var dc = datatype.Ctors[j];
                Func <int, List <Statement> > f = _ => new List <Statement>();
                if (j < fL.Count)
                {
                    f = fL[j];
                }

                MatchCaseStmt mcs = GenerateMatchCaseStmt(index, dc, f);

                cases.Add(mcs);
                line += mcs.Body.Count + 1;
            }

            return(new MatchStmt(new Token(index, 0)
            {
                val = "match"
            },
                                 new Token(index, 0)
            {
                val = "=>"
            },
                                 ns, cases, false));
        }
コード例 #2
0
ファイル: Explore.cs プロジェクト: ggrov/tacny
        private static IEnumerable <List <NameSegment> > PermuteArguments(List <List <IVariable> > args, int depth, List <NameSegment> current)
        {
            if (args.Count == 0)
            {
                yield break;
            }
            if (depth == args.Count)
            {
                yield return(current);

                yield break;
            }
            if (args[depth].Count == 0)
            {
                yield return(new List <NameSegment>());

                yield break;
            }
            for (int i = 0; i < args[depth].Count; ++i)
            {
                List <NameSegment> tmp = new List <NameSegment>();
                tmp.AddRange(current);
                IVariable   iv = args[depth][i];
                NameSegment ns = new NameSegment(iv.Tok, iv.Name, null);
                tmp.Add(ns);
                foreach (var item in PermuteArguments(args, depth + 1, tmp))
                {
                    yield return(item);
                }
            }
        }
コード例 #3
0
ファイル: Context.cs プロジェクト: ggrov/tacny
        public bool HasLocalWithName(NameSegment ns)
        {
            Contract.Requires <ArgumentNullException>(ns != null);
            List <IVariable> ins = new List <IVariable>(localDeclarations.Keys);
            var key = ins.FirstOrDefault(i => i.Name == ns.Name);

            return(key != null);
        }
コード例 #4
0
        /// <summary>
        /// Resolve all variables in expression to either literal values
        /// or to orignal declared nameSegments
        /// </summary>
        /// <param name="guard"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public static IEnumerable <ExpressionTree> ResolveExpression(ExpressionTree guard, ProofState state)
        {
            Contract.Requires <ArgumentNullException>(guard != null, "guard");
            Contract.Requires <ArgumentNullException>(state != null, "state");

            if (guard.IsLeaf())
            {
                if (!(guard.Data is NameSegment))
                {
                    yield return(guard.Copy());
                }
                var newGuard = guard.Copy();
                var result   = EvaluateLeaf(newGuard, state);
                foreach (var item in result)
                {
                    Contract.Assert(result != null);
                    Expression newNs = null; // potential encapsulation problems
                    if (item is MemberDecl)
                    {
                        var md = item as MemberDecl;
                        newNs = new StringLiteralExpr(new Token(), md.Name, true);
                    }
                    else if (item is Formal)
                    {
                        var tmp = item as Formal;
                        newNs = new NameSegment(tmp.tok, tmp.Name, null);
                    }
                    else if (item is NameSegment)
                    {
                        newNs = item as NameSegment;
                    }
                    else
                    {
                        newNs = item as Expression; // Dafny.LiteralExpr;
                    }
                    newGuard.Data = newNs;
                    yield return(newGuard);
                }
            }
            else
            {
                foreach (var lChild in ResolveExpression(guard.LChild, state))
                {
                    if (guard.RChild != null)
                    {
                        foreach (var rChild in ResolveExpression(guard.RChild, state))
                        {
                            yield return(new ExpressionTree(guard.Data, null, lChild, rChild));
                        }
                    }
                    else
                    {
                        yield return(new ExpressionTree(guard.Data, null, lChild, null));
                    }
                }
            }
        }
コード例 #5
0
        private void IsDatatype(Statement st, ref List <Solution> solution_list)
        {
            List <Expression> call_arguments = null;
            IVariable         lv             = null;
            IVariable         declaration    = null;

            Dafny.LiteralExpr lit  = null;
            Dafny.Type        type = null;

            InitArgs(st, out lv, out call_arguments);
            Contract.Assert(tcce.OfSize(call_arguments, 1), Util.Error.MkErr(st, 0, 1, call_arguments.Count));

            NameSegment argument = call_arguments[0] as NameSegment;

            Contract.Assert(argument != null, Util.Error.MkErr(st, 1, typeof(NameSegment)));

            declaration = GetLocalValueByName(argument) as IVariable;
            Contract.Assert(declaration != null, Util.Error.MkErr(st, 1, typeof(IVariable)));

            if (declaration.Type == null)
            {
                type = globalContext.GetVariableType(declaration.Name);
            }
            else
            {
                type = declaration.Type;
            }
            // type of the argument is unknown thus it's not a datatype
            if (type != null && type.IsDatatype)
            {
                lit = new Dafny.LiteralExpr(st.Tok, true);
            }
            else
            {
                // check if the argument is a nested data type
                Dafny.UserDefinedType udt = type as Dafny.UserDefinedType;
                if (udt != null)
                {
                    if (globalContext.datatypes.ContainsKey(udt.Name))
                    {
                        lit = new Dafny.LiteralExpr(st.Tok, true);
                    }
                    else
                    {
                        lit = new Dafny.LiteralExpr(st.Tok, false);
                    }
                }
                else
                {
                    lit = new Dafny.LiteralExpr(st.Tok, false);
                }
            }

            Contract.Assert(lit != null);
            localContext.AddLocal(lv, lit);
        }
コード例 #6
0
        private void ReplaceTerm(Expression old_singleton, Expression new_term, ExpressionTree formula, ref List <Expression> nexp)
        {
            Contract.Requires(nexp != null);
            Contract.Requires(old_singleton != null);
            Contract.Requires(new_term != null);
            NameSegment curNs = null;
            NameSegment oldNs = null;

            if (formula == null)
            {
                return;
            }

            if (formula.isLeaf())
            {
                if (formula.data.GetType() == old_singleton.GetType() && formula.was_replaced == false)
                {
                    if (formula.data is NameSegment)
                    {
                        curNs = (NameSegment)formula.data;
                        oldNs = (NameSegment)old_singleton;
                    }
                    else if (formula.data is UnaryOpExpr)
                    {
                        curNs = (NameSegment)((UnaryOpExpr)formula.data).E;
                        oldNs = (NameSegment)((UnaryOpExpr)old_singleton).E;
                    }
                    else
                    {
                        Contract.Assert(false, Util.Error.MkErr(formula.data, -1));
                    }

                    if (curNs.Name == oldNs.Name)
                    {
                        ExpressionTree nt = formula.Copy();
                        nt.data = new_term;

                        if (nt.parent.lChild == nt)
                        {
                            nt.parent.lChild = nt;
                        }
                        else
                        {
                            nt.parent.rChild = nt;
                        }

                        nexp.Add(nt.root.TreeToExpression());
                    }
                }
                return;
            }
            ReplaceTerm(old_singleton, new_term, formula.lChild, ref nexp);
            ReplaceTerm(old_singleton, new_term, formula.rChild, ref nexp);
        }
コード例 #7
0
ファイル: SuchThatAtomic.cs プロジェクト: ggrov/tacny
        private IEnumerable <object> ResolveExpression(Expression expr, IVariable declaration)
        {
            Contract.Requires(expr != null);

            if (expr is BinaryExpr)
            {
                BinaryExpr bexp = expr as BinaryExpr;
                switch (bexp.Op)
                {
                case BinaryExpr.Opcode.In:
                    NameSegment var = bexp.E0 as NameSegment;
                    Contract.Assert(var != null, Error.MkErr(bexp, 6, declaration.Name));
                    Contract.Assert(var.Name == declaration.Name, Error.MkErr(bexp, 6, var.Name));
                    foreach (var result in ResolveExpression(bexp.E1))
                    {
                        if (result is IEnumerable)
                        {
                            dynamic resultList = result;
                            foreach (var item in resultList)
                            {
                                yield return(item);
                            }
                        }
                    }
                    yield break;

                case BinaryExpr.Opcode.And:
                    // for each item in the resolved lhs of the expression
                    foreach (var item in ResolveExpression(bexp.E0, declaration))
                    {
                        Atomic copy = Copy();
                        copy.AddLocal(declaration, item);
                        // resolve the rhs expression
                        foreach (var res in copy.ResolveExpression(bexp.E1))
                        {
                            LiteralExpr lit = res as LiteralExpr;
                            // sanity check
                            Contract.Assert(lit != null, Error.MkErr(expr, 17));
                            if (lit.Value is bool)
                            {
                                // if resolved to true
                                if ((bool)lit.Value)
                                {
                                    yield return(item);
                                }
                            }
                        }
                    }
                    yield break;
                }
            }
        }
コード例 #8
0
        public string GenerateConditionString(NameSegment expression, IDictionary <string, string> rename)
        {
            var isFormal = !expression.Type.IsArrowType;

            if (isFormal)
            {
                if (rename.ContainsKey(expression.tok.val))
                {
                    return(rename[expression.tok.val]);
                }
                else
                {
                    return(expression.tok.val);
                }
            }
            else
            {
                return(expression.tok.val);
            }
        }
コード例 #9
0
ファイル: MatchAtomic.cs プロジェクト: ggrov/tacny
        private MatchStmt GenerateMatchStmt(int index, NameSegment ns, DatatypeDecl datatype, List <Solution> body)
        {
            Contract.Requires(ns != null);
            Contract.Requires(datatype != null);
            Contract.Ensures(Contract.Result <MatchStmt>() != null);
            List <MatchCaseStmt> cases = new List <MatchCaseStmt>();

            int line = index + 1;
            int i    = 0;

            foreach (DatatypeCtor dc in datatype.Ctors)
            {
                MatchCaseStmt mcs;
                GenerateMatchCaseStmt(line, dc, body[i], out mcs);

                cases.Add(mcs);
                line += mcs.Body.Count + 1;
                i++;
            }

            return(new MatchStmt(CreateToken("match", index, 0), CreateToken("=>", index, 0), ns, cases, false));
        }
コード例 #10
0
        public override void Visit(NameSegment e)
        {
            var nav            = new SymbolNavigator();
            var resolvedSymbol = nav.TopDown(RootNode, e.ResolvedExpression.tok);

            var declaration = FindDeclaration(e.Name, resolvedSymbol);

            CreateSymbol(
                name: e.Name,
                kind: null,
                type: e.Type,

                positionAsToken: e.tok,
                bodyStartPosAsToken: null,
                bodyEndPosAsToken: null,

                isDeclaration: false,
                declarationSymbol: declaration,
                addUsageAtDeclaration: true,

                canHaveChildren: false,
                canBeUsed: false
                );
        }
コード例 #11
0
ファイル: MatchAtomic.cs プロジェクト: ggrov/tacny
        /// <summary>
        /// TODO: Resolve the bodies lazily
        /// </summary>
        /// <param name="datatype"></param>
        /// <param name="casesGuard"></param>
        /// <param name="st"></param>
        /// <returns></returns>
        private IEnumerable <Solution> GenerateStmt(DatatypeDecl datatype, NameSegment casesGuard, TacnyCasesBlockStmt st)
        {
            List <List <Solution> > allCtorBodies = Repeated(new List <Solution>(), datatype.Ctors.Count);
            int ctor = 0;

            foreach (var list in allCtorBodies)
            {
                list.Add(null);

                RegisterLocals(datatype, ctor);
                foreach (var result in ResolveBody(st.Body))
                {
                    list.Add(result);
                }

                RemoveLocals(datatype, ctor);
                ctor++;
            }

            foreach (var stmt in GenerateAllMatchStmt(DynamicContext.tac_call.Tok.line, 0, Util.Copy.CopyNameSegment(casesGuard), datatype, allCtorBodies, new List <Solution>()))
            {
                yield return(CreateSolution(this, stmt));
            }
        }
コード例 #12
0
ファイル: Context.cs プロジェクト: ggrov/tacny
 public bool HasLocalWithName(NameSegment ns) {
   Contract.Requires<ArgumentNullException>(ns != null);
   List<IVariable> ins = new List<IVariable>(localDeclarations.Keys);
   var key = ins.FirstOrDefault(i => i.Name == ns.Name);
   return key != null;
 }
コード例 #13
0
ファイル: ProofState.cs プロジェクト: ggrov/tacny
 /// <summary>
 /// Get the value of local variable
 /// </summary>
 /// <param name="key"></param>
 /// <returns></returns>
 public object GetLocalValue(NameSegment key) {
   Contract.Requires<ArgumentNullException>(key != null, "key");
   Contract.Ensures(Contract.Result<object>() != null);
   return GetLocalValue(key.Name);
 }
コード例 #14
0
ファイル: Context.cs プロジェクト: ggrov/tacny
 public object GetLocalValueByName(NameSegment ns) {
   Contract.Requires<ArgumentNullException>(ns != null);
   return GetLocalValueByName(ns.Name);
 }
コード例 #15
0
 public virtual void Visit(NameSegment nameSegment)
 {
 }
コード例 #16
0
ファイル: ProofState.cs プロジェクト: ggrov/tacny
 /// <summary>
 ///   Return Dafny key
 /// </summary>
 /// <param name="key">Variable name</param>
 /// <returns>bool</returns>
 /// <exception cref="KeyNotFoundException">Variable does not exist in the current context</exception>
 public IVariable GetVariable(NameSegment key) {
   Contract.Requires<ArgumentNullException>(tcce.NonNull(key));
   Contract.Ensures(Contract.Result<IVariable>() != null);
   return GetVariable(key.Name);
 }
コード例 #17
0
ファイル: Explore.cs プロジェクト: ggrov/tacny
 private static IEnumerable<List<NameSegment>> PermuteArguments(List<List<IVariable>> args, int depth, List<NameSegment> current) {
   if(args.Count == 0)
     yield break;
   if(depth == args.Count) {
     yield return current;
     yield break;
   }
   if (args[depth].Count == 0){
     yield return new List<NameSegment>();
     yield break;
   }
   for(int i = 0; i < args[depth].Count; ++i) {
     List<NameSegment> tmp = new List<NameSegment>();
     tmp.AddRange(current);
     IVariable iv = args[depth][i];
     NameSegment ns = new NameSegment(iv.Tok, iv.Name, null);
     tmp.Add(ns);
     foreach(var item in PermuteArguments(args, depth + 1, tmp))
       yield return item;
   }
 }
コード例 #18
0
 public string GenerateString(NameSegment expression)
 {
     return(expression.tok.val);
 }
コード例 #19
0
ファイル: Match.cs プロジェクト: ggrov/tacny
    /// <summary>
    /// 
    /// </summary>
    /// <param name="line"></param>
    /// <param name="ns"></param>
    /// <param name="datatype"></param>
    /// <param name="f"></param>a function list which contains a function to generate stetment list with given line number
    /// <returns></returns>
    private MatchStmt GenerateMatchStmt (int line, NameSegment ns, DatatypeDecl datatype, List<Func<int, List<Statement>>> fL) {
      Contract.Requires(ns != null);
      Contract.Requires(datatype != null);
      Contract.Ensures(Contract.Result<MatchStmt>() != null);
      List<MatchCaseStmt> cases = new List<MatchCaseStmt>();
      int index = Interpreter.TACNY_CODE_TOK_LINE;//line + 1;
      int i = 0;


      for (int j = 0; j < datatype.Ctors.Count; j++){
        var dc = datatype.Ctors[j];
        Func<int, List<Statement>> f = _=> new List<Statement>();
        if (j < fL.Count) f = fL[j];

        MatchCaseStmt mcs = GenerateMatchCaseStmt(index, dc, f);

        cases.Add(mcs);
        line += mcs.Body.Count + 1;
        i++;
      }

      return new MatchStmt(new Token(index, 0) { val = "match" },
        new Token(index, 0) { val = "=>"}, 
        ns, cases, false);
    }
コード例 #20
0
 public override void Visit(NameSegment nameSegment)
 {
     _cancellationToken.ThrowIfCancellationRequested();
     RegisterDesignator(_currentScope, nameSegment, nameSegment.tok, nameSegment.Name);
 }
コード例 #21
0
 /// <summary>
 ///   Check if Dafny key exists in the current context
 /// </summary>
 /// <param name="key">Variable</param>
 /// <returns>bool</returns>
 public bool ContainsVariable(NameSegment key)
 {
     Contract.Requires <ArgumentNullException>(tcce.NonNull(key));
     return(ContainsVariable(key.Name));
 }
コード例 #22
0
 internal bool HasLocal(NameSegment key)
 {
     Contract.Requires <ArgumentNullException>(key != null, "key");
     return(HasLocal(key.Name));
 }
コード例 #23
0
ファイル: VariantAtomic.cs プロジェクト: ggrov/tacny
        private void AddVariant(Statement st, ref List<Solution> solution_list)
        {
            List<Expression> call_arguments = null;
            List<Expression> dec_list = null;
            Expression input = null;

            InitArgs(st, out call_arguments);
            Contract.Assert(tcce.OfSize(call_arguments, 1), Util.Error.MkErr(st, 0, 1, call_arguments.Count));

            StringLiteralExpr wildCard = call_arguments[0] as StringLiteralExpr;
            if (wildCard != null)
            {
                if (wildCard.Value.Equals("*"))
                    input = new WildcardExpr(wildCard.tok);
            }
            else
            {
                // hack
                /*
                 * TODO:
                 * Implement propper variable replacement
                 */
                object tmp;
                ProcessArg(call_arguments[0], out tmp);
                Contract.Assert(tmp != null);
                IVariable form = tmp as IVariable;
                if (form != null)
                    input = new NameSegment(form.Tok, form.Name, null);
                else if (tmp is BinaryExpr)
                {
                    input = tmp as BinaryExpr;
                }
                else if (tmp is NameSegment)
                {
                    input = tmp as NameSegment;
                }
            }
            WhileStmt ws = FindWhileStmt(globalContext.tac_call, globalContext.md);

            if (ws != null)
            {
                WhileStmt nws = null;
                dec_list = new List<Expression>(ws.Decreases.Expressions.ToArray());

                dec_list.Add(input);
                Specification<Expression> decreases = new Specification<Expression>(dec_list, ws.Attributes);
                nws = new WhileStmt(ws.Tok, ws.EndTok, ws.Guard, ws.Invariants, decreases, ws.Mod, ws.Body);
                AddUpdated(ws, nws);

            }
            else
            {
                Method target = Program.FindMember(globalContext.program.ParseProgram(), localContext.md.Name) as Method;
                if (GetNewTarget() != null && GetNewTarget().Name == target.Name)
                    target = GetNewTarget();
                Contract.Assert(target != null, Util.Error.MkErr(st, 3));
                
                dec_list = target.Decreases.Expressions;
                // insert new variants at the end of the existing variants list
                Contract.Assert(input != null);
                dec_list.Add(input);

                Specification<Expression> decreases = new Specification<Expression>(dec_list, target.Decreases.Attributes);
                Method result = null;
                dynamic lemma = null;
                if ((lemma = target as Lemma) != null)
                {
                    result = new Lemma(lemma.tok, lemma.Name, lemma.HasStaticKeyword, lemma.TypeArgs, lemma.Ins, lemma.Outs,
                        lemma.Req, lemma.Mod, lemma.Ens, decreases, lemma.Body, lemma.Attributes, lemma.SignatureEllipsis);
                }
                else if ((lemma = target as CoLemma) != null)
                {
                    result = new CoLemma(lemma.tok, lemma.Name, lemma.HasStaticKeyword, lemma.TypeArgs, lemma.Ins, lemma.Outs,
                        lemma.Req, lemma.Mod, lemma.Ens, decreases, lemma.Body, lemma.Attributes, lemma.SignatureEllipsis);

                } else
                    result = new Method(target.tok, target.Name, target.HasStaticKeyword, target.IsGhost, target.TypeArgs,
                        target.Ins, target.Outs, target.Req, target.Mod, target.Ens, decreases, target.Body, target.Attributes,
                        target.SignatureEllipsis);
                
                // register new method
                this.localContext.new_target = result;
                globalContext.program.IncTotalBranchCount(globalContext.program.currentDebug);
            }

            solution_list.Add(new Solution(this.Copy()));
        }
コード例 #24
0
ファイル: ProofState.cs プロジェクト: ggrov/tacny
 public bool ContainTacnyVal(NameSegment key) {
   Contract.Requires<ArgumentNullException>(key != null, "key");
   return ContainTacnyVal(key.Name);
 }
コード例 #25
0
        public override IEnumerable <ProofState> EvalInit(Statement statement, ProofState state)
        {
            Contract.Assume(statement != null);
            Contract.Assume(statement is TacticForallStmt);

            _stmt = statement as TacticForallStmt;

            Contract.Assert(_stmt != null);

            // do basic simplification
            // maybe do a check and throw an error instead?
            // fixme: error returns null!
            //var e = (ForallExpr) SimpTacticExpr.SimpTacExpr(state0, _stmt.Spec);
            var e = (ForallExpr)SimpExpr.SimpTacticExpr(state, _stmt.Spec);

            // var e = _stmt.Spec as ForallExpr;
            // to rename expressions
            RenameVar rn = new RenameVar();
            // to rename in the body of statement
            RenameVar     rnBody   = new RenameVar();
            List <String> usedVars = state.GetAllDafnyVars().Keys.ToList();

            usedVars.AddRange(state.GetAllTVars().Keys.ToList());

            //List<String> tmp = new List<string>();
            AllVars.DeclaredVars(_stmt.Body.Body[0], ref usedVars);



            if (_stmt.Attributes != null && _stmt.Attributes.Name.Equals("vars"))
            {
                var attrs = _stmt.Attributes.Args;
                for (int i = 0; i < attrs.Count; i++)
                {
                    // todo: should really report an errors if first condition does not hold
                    var segment = attrs[i] as NameSegment;
                    if (segment != null && i < e.BoundVars.Count)
                    {
                        NameSegment ns = segment;
                        String      fv;
                        if (GenFreeVar(ns.Name, usedVars, out fv))
                        {
                            rnBody.AddRename(ns.Name, fv);
                        }
                        rn.AddRename(e.BoundVars[i].Name, fv);
                    } // else we should have an error
                    _vars = new List <BoundVar>();
                    foreach (BoundVar bv in e.BoundVars)
                    {
                        _vars.Add(rn.CloneBoundVar(bv));
                    }
                }
            }
            else
            {
                _vars = e.BoundVars;
            }

            foreach (var tmp in _vars)
            {
                state.AddDafnyVar(tmp.Name, new ProofState.VariableData {
                    Variable = tmp, Type = tmp.Type
                });
            }


            // we could even break  _ens into a set of all conjunctions?
            // what about forall x (forall y) x
            var expr = e.Term as BinaryExpr;

            if (expr != null && (expr.Op.Equals(BinaryExpr.Opcode.Imp)))
            {
                var be = expr;
                _range = rn.CloneExpr(be.E0);
                var t = new MaybeFreeExpression(rn.CloneExpr(be.E1));
                var l = new List <MaybeFreeExpression> {
                    t
                };
                _ens = l;
            }
            else
            {
                _range = new LiteralExpr(_stmt.Tok, true);
                var t = new MaybeFreeExpression(rn.CloneExpr(e.Term));
                var l = new List <MaybeFreeExpression> {
                    t
                };
                _ens = l;
            }

            // Note that we do not need to rename variables in the body (unless the variables in vars is changed)
            InitBasicFrameCtrl(new List <Statement>(), state.IsCurFramePartial(), null, VerifyN);

            state.AddNewFrame(this);

            var bodyFrame = new DefaultTacticFrameCtrl();

            var newBody = rnBody.CloneBlockStmt(_stmt.Body);

            bodyFrame.InitBasicFrameCtrl(newBody.Body, state.IsCurFramePartial(), null, VerifyN);
            bodyFrame.IsPartial = IsPartial;
            state.AddNewFrame(bodyFrame);

            yield return(state);
        }
コード例 #26
0
ファイル: ProofState.cs プロジェクト: ggrov/dafny
 /// <summary>
 ///   Return Dafny key
 /// </summary>
 /// <param name="key">Variable name</param>
 /// <returns>bool</returns>
 /// <exception cref="KeyNotFoundException">Variable does not exist in the current context</exception>
 public IVariable GetDafnyVar(NameSegment key)
 {
     Contract.Requires <ArgumentNullException>(Tcce.NonNull(key));
     Contract.Ensures(Contract.Result <IVariable>() != null);
     return(GetDafnyVar(key.Name));
 }
コード例 #27
0
ファイル: Parser.cs プロジェクト: Chris-Hawblitzel/dafny
 void NameSegmentForTypeName(out Expression e, bool inExpressionContext)
 {
     IToken id;  List<Type> typeArgs;
     Ident(out id);
     OptGenericInstantiation(out typeArgs, inExpressionContext);
     e = new NameSegment(id, id.val, typeArgs);
 }
コード例 #28
0
ファイル: ProofState.cs プロジェクト: ggrov/dafny
 public bool ContainTVal(NameSegment key)
 {
     Contract.Requires <ArgumentNullException>(key != null, "key");
     return(ContainTVal(key.Name));
 }
コード例 #29
0
ファイル: ExpressionTree.cs プロジェクト: ggrov/tacny
    /// <summary>
    /// Resolve all variables in expression to either literal values
    /// or to orignal declared nameSegments
    /// </summary>
    /// <param name="guard"></param>
    /// <param name="state"></param>
    /// <returns></returns>
    public static IEnumerable<ExpressionTree> ResolveExpression(ExpressionTree guard, ProofState state) {
      Contract.Requires<ArgumentNullException>(guard != null, "guard");
      Contract.Requires<ArgumentNullException>(state != null, "state");

      if (guard.IsLeaf()) {
        if (!(guard.Data is NameSegment)) {
          yield return guard.Copy();
        }
        var newGuard = guard.Copy();
        var result = EvaluateLeaf(newGuard, state);
        foreach (var item in result) {
          Contract.Assert(result != null);
          Expression newNs = null; // potential encapsulation problems
          if (item is MemberDecl) {
            var md = item as MemberDecl;
            newNs = new StringLiteralExpr(new Token(), md.Name, true);
          } else if (item is Formal) {
            var tmp = item as Formal;
            newNs = new NameSegment(tmp.tok, tmp.Name, null);
          } else if (item is NameSegment) {
            newNs = item as NameSegment;
          } else {
            newNs = item as Expression; // Dafny.LiteralExpr;
          }
          newGuard.Data = newNs;
          yield return newGuard;
        }
      } else {
        foreach (var lChild in ResolveExpression(guard.LChild, state)) {
          if (guard.RChild != null) {
            foreach (var rChild in ResolveExpression(guard.RChild, state)) {
              yield return new ExpressionTree(guard.Data, null, lChild, rChild);
            }
          } else {
            yield return new ExpressionTree(guard.Data, null, lChild, null);
          }
        }
      }
    }
コード例 #30
0
ファイル: Copy.cs プロジェクト: ggrov/tacny
 /// <summary>
 /// Deep copy nameSegment
 /// </summary>
 /// <param name="old"></param>
 /// <returns></returns>
 public static NameSegment CopyNameSegment(NameSegment old) {
   return new NameSegment(old.tok, old.Name, old.OptTypeArguments);
 }
コード例 #31
0
ファイル: Context.cs プロジェクト: ggrov/tacny
 public object GetLocalValueByName(NameSegment ns)
 {
     Contract.Requires <ArgumentNullException>(ns != null);
     return(GetLocalValueByName(ns.Name));
 }
コード例 #32
0
ファイル: MatchAtomic.cs プロジェクト: ggrov/tacny
        private IEnumerable <MatchStmt> GenerateAllMatchStmt(int line_index, int depth, NameSegment ns, DatatypeDecl datatype, List <List <Solution> > bodies, List <Solution> curBody)
        {
            if (bodies.Count == 0)
            {
                yield break;
            }
            if (depth == bodies.Count)
            {
                MatchStmt ms = GenerateMatchStmt(line_index, Util.Copy.CopyNameSegment(ns), datatype, curBody);
                yield return(ms);

                yield break;
            }
            for (int i = 0; i < bodies[depth].Count; ++i)
            {
                List <Solution> tmp = new List <Solution>();
                tmp.AddRange(curBody);
                tmp.Add(bodies[depth][i]);
                foreach (var item in GenerateAllMatchStmt(line_index, depth + 1, ns, datatype, bodies, tmp))
                {
                    yield return(item);
                }
            }
        }
コード例 #33
0
ファイル: MatchAtomic.cs プロジェクト: ggrov/tacny
        private IEnumerable <Solution> GenerateMatch(TacnyCasesBlockStmt st)
        {
            NameSegment     casesGuard;
            UserDefinedType datatypeType = null;
            var             isElement    = false;

            var guard = st.Guard as ParensExpression;

            if (guard == null)
            {
                casesGuard = st.Guard as NameSegment;
            }
            else
            {
                casesGuard = guard.E as NameSegment;
            }

            Contract.Assert(casesGuard != null, Error.MkErr(st, 2));

            IVariable tacInput = GetLocalKeyByName(casesGuard);

            Contract.Assert(tacInput != null, Error.MkErr(st, 9, casesGuard.Name));


            if (!(tacInput is Formal))
            {
                tacInput = GetLocalValueByName(casesGuard) as IVariable;
                Contract.Assert(tacInput != null, Error.MkErr(st, 9, casesGuard.Name));
                // the original
                if (tacInput != null)
                {
                    casesGuard = new NameSegment(tacInput.Tok, tacInput.Name, null);
                }
            }
            else
            {
                // get the original declaration inside the method
                casesGuard = GetLocalValueByName(tacInput) as NameSegment;
            }
            string datatypeName = tacInput?.Type.ToString();

            /**
             * TODO cleanup
             * if datatype is Element lookup the formal in global variable registry
             */

            if (datatypeName == "Element")
            {
                isElement = true;
                var val  = GetLocalValueByName(tacInput.Name);
                var decl = val as NameSegment;
                Contract.Assert(decl != null, Error.MkErr(st, 9, tacInput.Name));

                var originalDecl = StaticContext.GetGlobalVariable(decl?.Name);
                if (originalDecl != null)
                {
                    datatypeType = originalDecl.Type as UserDefinedType;
                    datatypeName = datatypeType != null ? datatypeType.Name : originalDecl.Type.ToString();
                }
                else
                {
                    Contract.Assert(false, Error.MkErr(st, 9, tacInput.Name));
                }
            }

            if (!StaticContext.ContainsGlobalKey(datatypeName))
            {
                Contract.Assert(false, Error.MkErr(st, 12, datatypeName));
            }

            var datatype = StaticContext.GetGlobal(datatypeName);

            if (datatype.TypeArgs != null)
            {
                _ctorTypes = new Dictionary <string, Type>();

                if (datatype.TypeArgs.Count == datatypeType.TypeArgs.Count)
                {
                    for (int i = 0; i < datatype.TypeArgs.Count; i++)
                    {
                        var genericType = datatype.TypeArgs[i];
                        var definedType = datatypeType.TypeArgs[i];
                        _ctorTypes.Add(genericType.Name, definedType);
                    }
                }
            }

            if (isElement)
            {
                yield return(GenerateVerifiedStmt(datatype, casesGuard, st));
            }
            else
            {
                foreach (var item in GenerateStmt(datatype, casesGuard, st))
                {
                    yield return(item);
                }
            }
        }
コード例 #34
0
ファイル: ProofState.cs プロジェクト: ggrov/tacny
 /// <summary>
 /// Get the value of local variable
 /// </summary>
 /// <param name="key"></param>
 /// <returns></returns>
 public object GetTacnyVarValue(NameSegment key)
 {
     Contract.Requires <ArgumentNullException>(key != null, "key");
     Contract.Ensures(Contract.Result <object>() != null);
     return(GetTacnyVarValue(key.Name));
 }
コード例 #35
0
ファイル: Cloner.cs プロジェクト: ggrov/tacny
 public override AssignmentRhs CloneRHS(AssignmentRhs rhs) {
   var r = rhs as ExprRhs;
   if (r != null && r.Expr is ApplySuffix) {
     var apply = (ApplySuffix)r.Expr;
     var mse = apply.Lhs.Resolved as MemberSelectExpr;
     if (mse != null && mse.Member is FixpointLemma && ModuleDefinition.InSameSCC(context, (FixpointLemma)mse.Member)) {
       // we're looking at a recursive call to a fixpoint lemma
       Contract.Assert(apply.Lhs is NameSegment || apply.Lhs is ExprDotName);  // this is the only way a call statement can have been parsed
       // clone "apply.Lhs", changing the inductive/co lemma to the prefix lemma; then clone "apply", adding in the extra argument
       Expression lhsClone;
       if (apply.Lhs is NameSegment) {
         var lhs = (NameSegment)apply.Lhs;
         lhsClone = new NameSegment(Tok(lhs.tok), lhs.Name + "#", lhs.OptTypeArguments == null ? null : lhs.OptTypeArguments.ConvertAll(CloneType));
       } else {
         var lhs = (ExprDotName)apply.Lhs;
         lhsClone = new ExprDotName(Tok(lhs.tok), CloneExpr(lhs.Lhs), lhs.SuffixName + "#", lhs.OptTypeArguments == null ? null : lhs.OptTypeArguments.ConvertAll(CloneType));
       }
       var args = new List<Expression>();
       args.Add(k);
       apply.Args.ForEach(arg => args.Add(CloneExpr(arg)));
       var applyClone = new ApplySuffix(Tok(apply.tok), lhsClone, args);
       var c = new ExprRhs(applyClone);
       reporter.Info(MessageSource.Cloner, apply.Lhs.tok, mse.Member.Name + suffix);
       return c;
     }
   }
   return base.CloneRHS(rhs);
 }
コード例 #36
0
ファイル: ProofState.cs プロジェクト: ggrov/tacny
 /// <summary>
 ///   Check if Dafny key exists in the current context
 /// </summary>
 /// <param name="key">Variable</param>
 /// <returns>bool</returns>
 public bool ContainsVariable(NameSegment key) {
   Contract.Requires<ArgumentNullException>(tcce.NonNull(key));
   return ContainsVariable(key.Name);
 }
コード例 #37
0
ファイル: VariantAtomic.cs プロジェクト: ggrov/tacny
        private void AddVariant(Statement st, ref List <Solution> solution_list)
        {
            List <Expression> call_arguments = null;
            List <Expression> dec_list       = null;
            Expression        input          = null;

            InitArgs(st, out call_arguments);
            Contract.Assert(tcce.OfSize(call_arguments, 1), Util.Error.MkErr(st, 0, 1, call_arguments.Count));

            StringLiteralExpr wildCard = call_arguments[0] as StringLiteralExpr;

            if (wildCard != null)
            {
                if (wildCard.Value.Equals("*"))
                {
                    input = new WildcardExpr(wildCard.tok);
                }
            }
            else
            {
                // hack

                /*
                 * TODO:
                 * Implement propper variable replacement
                 */
                object tmp;
                ProcessArg(call_arguments[0], out tmp);
                Contract.Assert(tmp != null);
                IVariable form = tmp as IVariable;
                if (form != null)
                {
                    input = new NameSegment(form.Tok, form.Name, null);
                }
                else if (tmp is BinaryExpr)
                {
                    input = tmp as BinaryExpr;
                }
                else if (tmp is NameSegment)
                {
                    input = tmp as NameSegment;
                }
            }
            WhileStmt ws = FindWhileStmt(globalContext.tac_call, globalContext.md);

            if (ws != null)
            {
                WhileStmt nws = null;
                dec_list = new List <Expression>(ws.Decreases.Expressions.ToArray());

                dec_list.Add(input);
                Specification <Expression> decreases = new Specification <Expression>(dec_list, ws.Attributes);
                nws = new WhileStmt(ws.Tok, ws.EndTok, ws.Guard, ws.Invariants, decreases, ws.Mod, ws.Body);
                AddUpdated(ws, nws);
            }
            else
            {
                Method target = Program.FindMember(globalContext.program.ParseProgram(), localContext.md.Name) as Method;
                if (GetNewTarget() != null && GetNewTarget().Name == target.Name)
                {
                    target = GetNewTarget();
                }
                Contract.Assert(target != null, Util.Error.MkErr(st, 3));

                dec_list = target.Decreases.Expressions;
                // insert new variants at the end of the existing variants list
                Contract.Assert(input != null);
                dec_list.Add(input);

                Specification <Expression> decreases = new Specification <Expression>(dec_list, target.Decreases.Attributes);
                Method  result = null;
                dynamic lemma  = null;
                if ((lemma = target as Lemma) != null)
                {
                    result = new Lemma(lemma.tok, lemma.Name, lemma.HasStaticKeyword, lemma.TypeArgs, lemma.Ins, lemma.Outs,
                                       lemma.Req, lemma.Mod, lemma.Ens, decreases, lemma.Body, lemma.Attributes, lemma.SignatureEllipsis);
                }
                else if ((lemma = target as CoLemma) != null)
                {
                    result = new CoLemma(lemma.tok, lemma.Name, lemma.HasStaticKeyword, lemma.TypeArgs, lemma.Ins, lemma.Outs,
                                         lemma.Req, lemma.Mod, lemma.Ens, decreases, lemma.Body, lemma.Attributes, lemma.SignatureEllipsis);
                }
                else
                {
                    result = new Method(target.tok, target.Name, target.HasStaticKeyword, target.IsGhost, target.TypeArgs,
                                        target.Ins, target.Outs, target.Req, target.Mod, target.Ens, decreases, target.Body, target.Attributes,
                                        target.SignatureEllipsis);
                }

                // register new method
                this.localContext.new_target = result;
                globalContext.program.IncTotalBranchCount(globalContext.program.currentDebug);
            }

            solution_list.Add(new Solution(this.Copy()));
        }
コード例 #38
0
ファイル: ProofState.cs プロジェクト: ggrov/tacny
 internal bool HasLocal(NameSegment key) {
   Contract.Requires<ArgumentNullException>(key != null, "key");
   return HasLocal(key.Name);
 }
コード例 #39
0
 public override void Visit(NameSegment e)
 {
 }
コード例 #40
0
ファイル: Context.cs プロジェクト: ggrov/tacny
 public Type GetVariableType(NameSegment ns) {
   Contract.Requires(ns != null);
   return GetVariableType(ns.Name);
 }
コード例 #41
0
 public override void Leave(NameSegment e)
 {
 }
コード例 #42
0
ファイル: ProofState.cs プロジェクト: ggrov/dafny
        /// <summary>
        ///   Check if Dafny key exists in the current context
        /// </summary>
        /// <param name="key">Variable</param>
        /// <returns>bool</returns>

        public bool ContainDafnyVar(NameSegment key)
        {
            Contract.Requires <ArgumentNullException>(Tcce.NonNull(key));
            return(ContainDafnyVar(key.Name));
        }
コード例 #43
0
ファイル: Parser.cs プロジェクト: dbremner/dafny
        void NameSegment(out Expression e)
        {
            IToken id;
            IToken openParen = null;  List<Type> typeArgs = null;  List<Expression> args = null;

            Ident(out id);
            if (IsGenericInstantiation()) {
            typeArgs = new List<Type>();
            GenericInstantiation(typeArgs);
            } else if (la.kind == 106) {
            HashCall(id, out openParen, out typeArgs, out args);
            } else if (StartOf(30)) {
            } else SynErr(231);
            e = new NameSegment(id, id.val, typeArgs);
            if (openParen != null) {
             e = new ApplySuffix(openParen, e, args);
            }
        }
コード例 #44
0
ファイル: ProofState.cs プロジェクト: ggrov/dafny
 /// <summary>
 /// Get the value of local variable
 /// </summary>
 /// <param name="key"></param>
 /// <returns></returns>
 public Expression GetTVarValue(NameSegment key)
 {
     Contract.Requires <ArgumentNullException>(key != null, "key");
     Contract.Ensures(Contract.Result <Expression>() != null);
     return(GetTVarValue(key.Name));
 }
コード例 #45
0
ファイル: Parser.cs プロジェクト: dbremner/dafny
        void NameSegmentForTypeName(out Expression e)
        {
            IToken id;
            List<Type> typeArgs = null;

            Ident(out id);
            if (la.kind == 52) {
            typeArgs = new List<Type>();
            GenericInstantiation(typeArgs);
            }
            e = new NameSegment(id, id.val, typeArgs);
        }
コード例 #46
0
ファイル: Context.cs プロジェクト: ggrov/tacny
 public Type GetVariableType(NameSegment ns)
 {
     Contract.Requires(ns != null);
     return(GetVariableType(ns.Name));
 }
コード例 #47
0
ファイル: Copy.cs プロジェクト: ggrov/tacny
 /// <summary>
 /// Deep copy nameSegment
 /// </summary>
 /// <param name="old"></param>
 /// <returns></returns>
 public static NameSegment CopyNameSegment(NameSegment old)
 {
     return(new NameSegment(old.tok, old.Name, old.OptTypeArguments));
 }