Exemplo n.º 1
0
        public void AddItemWithSize(Address addr, ImageMapItem itemNew)
        {
            ImageMapItem item;

            if (!TryFindItem(addr, out item))
            {
                throw new ArgumentException(string.Format("Address {0} is not within the image range.", addr));
            }
            long delta = addr - item.Address;

            Debug.Assert(delta >= 0, "Should have found an item at the supplied address.");
            if (delta > 0)
            {
                int          afterOffset = (int)(delta + itemNew.Size);
                ImageMapItem itemAfter   = null;
                if (item.Size > afterOffset)
                {
                    itemAfter = new ImageMapItem
                    {
                        Address  = addr + itemNew.Size,
                        Size     = (uint)(item.Size - afterOffset),
                        DataType = ChopBefore(item.DataType, afterOffset),
                    };
                }
                item.Size     = (uint)delta;
                item.DataType = ChopAfter(item.DataType, (int)delta);      // Shrink the existing mofo.

                Items.Add(addr, itemNew);
                if (itemAfter != null)
                {
                    Items.Add(itemAfter.Address, itemAfter);
                }
            }
            else
            {
                if (!(item.DataType is UnknownType) &&
                    !(item.DataType is CodeType))
                {
                    var u = new Unifier();
                    if (u.AreCompatible(item.DataType, itemNew.DataType))
                    {
                        item.DataType = u.Unify(item.DataType, itemNew.DataType);
                    }
                    else
                    {
                        throw new NotSupportedException("Haven't handled this case yet.");
                    }
                }
                Items.Remove(item.Address);
                item.Address += itemNew.Size;
                item.Size    -= itemNew.Size;

                Items.Add(addr, itemNew);
                if (item.Size > 0 && !Items.ContainsKey(item.Address))
                {
                    Items.Add(item.Address, item);
                }
            }
            FireMapChanged();
        }
Exemplo n.º 2
0
        public void Unify_UnifiableNames_True(string n1, string n2, string[] result, Refactorization r)
        {
            var expectedBindings = result.Select(s => new Substitution(s));
            IEnumerable <Substitution> bindings = null;
            var isUnifiable = false;

            if (r == Refactorization.Current)
            {
                var name1 = Name.BuildName(n1);
                var name2 = Name.BuildName(n2);
                for (int i = 0; i < unifierReps; i++)
                {
                    isUnifiable = Unifier.Unify(name1, name2, out bindings);
                }
            }
            else if (r == Refactorization.New)
            {
                var name1 = new SimpleName(n1);
                var name2 = new SimpleName(n2);

                for (int i = 0; i < unifierReps; i++)
                {
                    isUnifiable = SimpleUnifier.Unify(name1, name2, out bindings);
                }
            }
            Assert.That(isUnifiable);
            if (result.Any())
            {
                Assert.That(bindings, Is.EquivalentTo(expectedBindings));
            }
            else
            {
                Assert.That(bindings.Count() == 0);
            }
        }
Exemplo n.º 3
0
        public void Unify_NonUnifiableNames_False(string n1, string n2, Refactorization r)
        {
            IEnumerable <Substitution> bindings = new List <Substitution>();
            var isUnifiable = true;

            if (r == Refactorization.Current)
            {
                var name1 = Name.BuildName(n1);
                var name2 = Name.BuildName(n2);
                for (int i = 0; i < unifierReps; i++)
                {
                    isUnifiable = Unifier.Unify(name1, name2, out bindings);
                }
            }
            else if (r == Refactorization.New)
            {
                var name1 = new SimpleName(n1);
                var name2 = new SimpleName(n2);
                for (int i = 0; i < unifierReps; i++)
                {
                    isUnifiable = SimpleUnifier.Unify(name1, name2, out bindings);
                }
            }
            Assert.That(!isUnifiable);
            Assert.That(bindings == null);
        }
Exemplo n.º 4
0
        /// <summary>
        /// If a constant pointer into a structure is found, make sure there is a variable there.
        /// </summary>
        /// <param name="offset"></param>
        /// <param name="mptr"></param>
        private void VisitConstantMemberPointer(int offset, MemberPointer mptr)
        {
            TypeVariable?tvField = GetTypeVariableForField(mptr.Pointee);

            if (tvField == null)
            {
                return;
            }

            TypeVariable tvBase = (TypeVariable)mptr.BasePointer;
            Pointer      ptr    = CreatePointerToField(offset, tvField);

            tvBase.OriginalDataType =
                unifier.Unify(tvBase.OriginalDataType, ptr) !;

            ptr = CreatePointerToField(offset, tvField);
            tvBase.Class.DataType =
                unifier.Unify(tvBase.Class.DataType, ptr) !;
        }
Exemplo n.º 5
0
        public void Unify_NonUnifiableNames_False(string n1, string n2)
        {
            var name1 = Name.BuildName(n1);
            var name2 = Name.BuildName(n2);
            IEnumerable <Substitution> bindings = new List <Substitution>();
            var isUnifiable = Unifier.Unify(name1, name2, out bindings);

            Assert.That(!isUnifiable);
            Assert.That(bindings == null);
        }
Exemplo n.º 6
0
		// T_1 --> C_1 --> S_1
		// T_2 --> C_2 --> S_2
		// T_3 --> C_3 --> S_3

		// T_1 --> C_1 --> S_New
		// T_2 --> C_1
		// T_3 --> C_1
        public void Merge()
        {
            Unifier un = new Unifier(new TypeFactory());
            DataType dt = null;
            foreach (StructureType str in structures)
            {
                dt = un.Unify(dt, str);
            }
            StructureType strNew = (StructureType) dt;
            eqMin.DataType = strNew;
        }
Exemplo n.º 7
0
        public ISet <IDictionary <Variable, ITerm> > Fetch(Literal l)
        {
            // Get all of the substitutions in the KB that p unifies with
            ISet <IDictionary <Variable, ITerm> > allUnifiers = new HashedSet <IDictionary <Variable, ITerm> >();

            IList <Literal> matchingFacts = this.FetchMatchingFacts(l);

            if (null != matchingFacts)
            {
                foreach (Literal fact in matchingFacts)
                {
                    IDictionary <Variable, ITerm> substitution = unifier.Unify(l
                                                                               .AtomicSentence, fact.AtomicSentence);
                    if (null != substitution)
                    {
                        allUnifiers.Add(substitution);
                    }
                }
            }

            return(allUnifiers);
        }
Exemplo n.º 8
0
        // T_1 --> C_1 --> S_1
        // T_2 --> C_2 --> S_2
        // T_3 --> C_3 --> S_3

        // T_1 --> C_1 --> S_New
        // T_2 --> C_1
        // T_3 --> C_1
        public void Merge()
        {
            Unifier  un = new Unifier(new TypeFactory());
            DataType?dt = null;

            foreach (StructureType str in structures)
            {
                dt = un.Unify(dt, str);
            }
            StructureType strNew = (StructureType)dt !;

            eqMin !.DataType = strNew;
        }
Exemplo n.º 9
0
        public void TestOccurs()
        {
            Dictionary <string, object> dict;

            Assert.Equal("{ a -> 9 }", (dict = Unifier.Unify(V("a"), 9)).ToRepr());
            Assert.False(Occurs("a", new Stack()));
            Assert.True(Occurs("a", new Stack(new object[] { V("a") })));
            Assert.True(Occurs("a", new Stack(new object[] { 9, 3, V("a") })));
            Assert.True(Occurs("a", new Stack(new object[] { 9, 3, new Stack(new object[] { 1, V("a"), 2 }) })));

            Assert.False(Occurs("a", new Stack(new object[] { 9, 3, new Stack(new object[] { 1, 2 }) })));
            Assert.True(Occurs("a", new Stack(new object[] { 9, 3, new Stack(new object[] { 1, 2 }), V("a") })));
        }
Exemplo n.º 10
0
        public Expression Transform()
        {
            ctx.RemoveIdentifierUse(idDst);
            if (!cSrc.IsValid)
            {
                return(cSrc);
            }
            DataType dt = unifier.Unify(cSrc.DataType, idDst.DataType);

            if (dt is PrimitiveType)
            {
                return(Constant.Create(dt, cSrc.ToInt64()));
            }
            throw new NotSupportedException(string.Format("Resulting type is {0}, which isn't supported yet.", dt));
        }
Exemplo n.º 11
0
        public IEnumerable <AppraisalRule> Evaluate(IBaseEvent evt, IQueryable kb, Name perspective)
        {
            // Switching the SELF term for the correct name withint the event

            var auxEvt = evt.EventName.SwapTerms(perspective, Name.SELF_SYMBOL);
            var result = new List <AppraisalRule>();

            foreach (var r in this.Rules)
            {
                // Trying to find all possible initial substitutions;
                var initialSubSet = Unifier.Unify(r.EventName, auxEvt);


                if (initialSubSet == null)
                {
                    initialSubSet = new SubstitutionSet();
                }


                if (auxEvt.Match(r.EventName) || initialSubSet.Any())
                {
                    var finalSubSet = r.Conditions.Unify(kb, perspective, new List <SubstitutionSet>()
                    {
                        new SubstitutionSet(initialSubSet)
                    });
                    if (finalSubSet != null)
                    {
                        //TODO: Handle uncertainty in beliefs
                        foreach (var set in finalSubSet)
                        {
                            var a = new AppraisalRule(r);
                            a.EventName.MakeGround(set);
                            foreach (var variable in a.getAppraisalVariables())
                            {
                                variable.Value = variable.Value.MakeGround(set);
                                if (variable.Target != null && variable.Target != (Name)"-")
                                {
                                    variable.Target = variable.Target.MakeGround(set);
                                }
                            }
                            result.Add(a);
                        }
                    }
                }
            }
            return(result);
        }
Exemplo n.º 12
0
            public void Unify()
            {
                var str = unifier.factory.CreateStructureType(null, 0);

                str.Fields.Add(
                    fOther !.Offset - fNestedStruct !.Offset,
                    fOther.DataType);

                var fieldType = unifier.Unify(fNestedStruct.DataType, str) !;
                var field     = new StructureField(
                    fNestedStruct.Offset,
                    fieldType,
                    fNestedStruct.Name);

                NextFieldA = (fOther == fa) ? null : field;
                NextFieldB = (fOther == fb) ? null : field;
            }
Exemplo n.º 13
0
        public bool Match(Identifier id)
        {
            this.src = ctx.GetValue(id);
            var cSrc = src as Constant;

            if (cSrc == null || !cSrc.IsValid)
            {
                if (!(src is Address))
                {
                    return(false);
                }
            }
            idDst    = id;
            this.dt  = unifier.Unify(src.DataType, idDst.DataType);
            this.pt  = dt.ResolveAs <PrimitiveType>();
            this.ptr = dt.ResolveAs <Pointer>();
            return(pt != null || this.ptr != null);
        }
Exemplo n.º 14
0
        public void Unify_UnifiableNames_True(string n1, string n2, string[] result)
        {
            var name1            = Name.BuildName(n1);
            var name2            = Name.BuildName(n2);
            var expectedBindings = result.Select(s => new Substitution(s));
            IEnumerable <Substitution> bindings;
            var isUnifiable = Unifier.Unify(name1, name2, out bindings);

            Assert.That(isUnifiable);
            if (result.Any())
            {
                Assert.That(bindings, Is.EquivalentTo(expectedBindings));
            }
            else
            {
                Assert.That(bindings.Count() == 0);
            }
        }
Exemplo n.º 15
0
        public void TestUnifier()
        {
            Assert.Equal("{ a -> 9 }", Unifier.Unify(V("a"), 9).ToRepr());
            Assert.Equal("{ a -> [9] }", Unifier.Unify(V("a"), new Stack(new [] { 9 })).ToRepr());
            Assert.Equal("{ a -> E(9) }", Unifier.Unify(V("a"), new Stack(new object[] { 9 }).Cast <object>().CastBack()).ToRepr());
            Assert.Equal("{ }", Unifier.Unify(9, 9).ToRepr());
            // Assert.Equal(new Stack(new object[] { V("x"), 2, 1 }), @"[1 2 ""x""]".ToStack());
            Assert.Equal("{ x -> 1 }", Unifier.Unify(new Stack(new [] { V("x") }), @"[1]".ToStack()).ToRepr());
            Assert.Equal("{ x -> 1 }", Unifier.Unify(@"[1]".ToStack(), new Stack(new [] { V("x") })).ToRepr());
            Assert.Equal("{ x -> 1 }", Unifier.Unify(@"[1]".ToStack(), ToVarStack(@"[x]")).ToRepr());
            Assert.Equal("{ x -> 1 }", Unifier.Unify(@"[1]".ToStack(), ToVarStack("[x]")).ToRepr());
            Assert.Equal("{ x -> 1 }", Unifier.Unify(@"[1 2]".ToStack(), ToVarStack("[x 2]")).ToRepr());
            Assert.Equal("{ x -> [1] }", Unifier.Unify(@"[[1] 2]".ToStack(), ToVarStack("[x 2]")).ToRepr());
            Assert.Equal("{ x -> 1 }", Unifier.Unify(@"[0 1 2]".ToStack(), ToVarStack("[0 x 2]")).ToRepr());
            Assert.Equal("{ x -> 1, y -> 2 }", Unifier.Unify(ToVarStack("[0 1 y]"), ToVarStack("[0 x 2]")).ToRepr());
            Assert.Equal("{ x -> 1, y -> 1 }", Unifier.Unify(ToVarStack("[0 1 y]"), ToVarStack("[0 x x]")).ToRepr());

            // No inconsistent values.
            Assert.Throws <Exception>(() => Unifier.Unify(@"[1 2]".ToStack(), ToVarStack("[x x]")).ToRepr());
            // No cyclic bindings.
            Assert.Throws <Exception>(() => Unifier.Unify(ToVarStack("[[1 x] 2]"), ToVarStack("[x 2]")).ToRepr());
            // Assert.Equal("{ x -> 1 }", Unifier.Unify(ToVarStack("[[1 x] 2]"), ToVarStack("[x 2]")).ToRepr());
        }
Exemplo n.º 16
0
        public Expression Transform()
        {
            ctx.RemoveIdentifierUse(idDst);
            if (!cSrc.IsValid)
            {
                return(cSrc);
            }
            DataType dt = unifier.Unify(cSrc.DataType, idDst.DataType);
            var      pt = dt.ResolveAs <PrimitiveType>();

            if (pt != null)
            {
                return(Constant.Create(pt, cSrc.ToInt64()));
            }
            var ptr = dt.ResolveAs <Pointer>();

            if (ptr != null)
            {
                var addr = Address.Create(ptr, cSrc.ToUInt64());
                addr.DataType = ptr;
                return(addr);
            }
            throw new NotSupportedException(string.Format("Resulting type is {0}, which isn't supported yet.", dt));
        }
Exemplo n.º 17
0
        public Chain AttemptReduction(Chain nearParent, int farParentIndex)
        {
            Chain nnpc = null;

            Literal nearLiteral = nearParent.GetHead();

            IDictionary <string, IList <Chain> > candidateHeads = null;

            if (nearLiteral.IsPositiveLiteral())
            {
                candidateHeads = negHeads;
            }
            else
            {
                candidateHeads = posHeads;
            }

            IAtomicSentence nearAtom   = nearLiteral.AtomicSentence;
            string          nearestKey = nearAtom.GetSymbolicName();
            IList <Chain>   farParents = candidateHeads[nearestKey];

            if (null != farParents)
            {
                Chain farParent = farParents[farParentIndex];
                StandardizeApart(farParent);
                Literal         farLiteral          = farParent.GetHead();
                IAtomicSentence farAtom             = farLiteral.AtomicSentence;
                IDictionary <Variable, ITerm> subst = unifier.Unify(nearAtom, farAtom);

                // If I was able to Unify with one
                // of the far heads
                if (null != subst)
                {
                    // Want to always apply reduction uniformly
                    Chain   topChain = farParent;
                    Literal botLit   = nearLiteral;
                    Chain   botChain = nearParent;

                    // Need to apply subst to all of the
                    // literals in the reduction
                    IList <Literal> reduction = new List <Literal>();
                    foreach (Literal l in topChain.GetTail())
                    {
                        IAtomicSentence atom = (IAtomicSentence)substVisitor.Subst(
                            subst, l.AtomicSentence);
                        reduction.Add(l.NewInstance(atom));
                    }
                    reduction.Add(new ReducedLiteral((IAtomicSentence)substVisitor
                                                     .Subst(subst, botLit.AtomicSentence), botLit
                                                     .IsNegativeLiteral()));
                    foreach (Literal l in botChain.GetTail())
                    {
                        IAtomicSentence atom = (IAtomicSentence)substVisitor.Subst(
                            subst, l.AtomicSentence);
                        reduction.Add(l.NewInstance(atom));
                    }

                    nnpc = new Chain(reduction);
                    nnpc.SetProofStep(new ProofStepChainReduction(nnpc, nearParent,
                                                                  farParent, subst));
                }
            }

            return(nnpc);
        }
Exemplo n.º 18
0
        // Note: Applies binary resolution rule and factoring
        // Note: returns a set with an empty clause if both clauses
        // are empty, otherwise returns a set of binary resolvents.
        public ISet <Clause> BinaryResolvents(Clause othC)
        {
            ISet <Clause> resolvents = new HashedSet <Clause>();

            // Resolving two empty clauses
            // gives you an empty clause
            if (IsEmpty() && othC.IsEmpty())
            {
                resolvents.Add(new Clause());
                return(resolvents);
            }

            // Ensure Standardized Apart
            // Before attempting binary resolution
            othC = this.SaIfRequired(othC);

            var allPosLits = new List <Literal>();
            var allNegLits = new List <Literal>();

            allPosLits.AddRange(this.positiveLiterals);
            allPosLits.AddRange(othC.positiveLiterals);
            allNegLits.AddRange(this.negativeLiterals);
            allNegLits.AddRange(othC.negativeLiterals);

            var trPosLits    = new List <Literal>();
            var trNegLits    = new List <Literal>();
            var copyRPosLits = new List <Literal>();
            var copyRNegLits = new List <Literal>();

            for (int i = 0; i < 2; i++)
            {
                trPosLits.Clear();
                trNegLits.Clear();

                if (i == 0)
                {
                    // See if this clauses positives
                    // unify with the other clauses
                    // negatives
                    trPosLits.AddRange(this.positiveLiterals);
                    trNegLits.AddRange(othC.negativeLiterals);
                }
                else
                {
                    // Try the other way round now
                    trPosLits.AddRange(othC.positiveLiterals);
                    trNegLits.AddRange(this.negativeLiterals);
                }

                // Now check to see if they resolve
                IDictionary <Variable, ITerm> copyRBindings = new Dictionary <Variable, ITerm>();
                foreach (var pl in trPosLits)
                {
                    foreach (var nl in trNegLits)
                    {
                        copyRBindings.Clear();
                        if (null != _unifier.Unify(pl.AtomicSentence, nl.AtomicSentence, copyRBindings))
                        {
                            copyRPosLits.Clear();
                            copyRNegLits.Clear();
                            var found = false;
                            foreach (var l in allPosLits)
                            {
                                if (!found && pl.Equals(l))
                                {
                                    found = true;
                                    continue;
                                }
                                copyRPosLits.Add(_substVisitor.Subst(copyRBindings, l));
                            }
                            found = false;
                            foreach (Literal l in allNegLits)
                            {
                                if (!found && nl.Equals(l))
                                {
                                    found = true;
                                    continue;
                                }
                                copyRNegLits.Add(_substVisitor.Subst(copyRBindings, l));
                            }
                            // Ensure the resolvents are standardized apart
                            var renameSubstitituon = _standardizeApart
                                                     .GetStandardizeApartResult(copyRPosLits, copyRNegLits, _saIndexical);
                            var c = new Clause(copyRPosLits, copyRNegLits);
                            c.SetProofStep(new ProofStepClauseBinaryResolvent(c, this, othC, copyRBindings, renameSubstitituon));
                            if (this.Immutable)
                            {
                                c.Immutable = true;
                            }
                            if (!this.IsStandardizedApartCheckRequired())
                            {
                                c.SetStandardizedApartCheckNotRequired();
                            }
                            resolvents.Add(c);
                        }
                    }
                }
            }

            return(resolvents);
        }
Exemplo n.º 19
0
 private DataType RecordDataType(DataType dt, Expression exp)
 {
     exp.TypeVariable.DataType         = unifier.Unify(exp.TypeVariable.DataType, dt);
     exp.TypeVariable.OriginalDataType = unifier.Unify(exp.TypeVariable.OriginalDataType, dt);
     return(exp.TypeVariable.DataType);
 }
Exemplo n.º 20
0
        public void UnifyInt32()
        {
            DataType      d = un.Unify(PrimitiveType.Word32, PrimitiveType.Word32);
            PrimitiveType p = (PrimitiveType)d;

            Assert.AreEqual(PrimitiveType.Word32, p);
        }