Пример #1
0
        public void ProcessInstance <M>(ISemanticType obj, bool processOnCallerThread = false)
            where M : IMembrane, new()
        {
            IMembrane m = RegisterMembrane <M>();

            ProcessInstance(m, null, obj, processOnCallerThread);
        }
Пример #2
0
        public ISemanticType InstantiateSemanticType(string typeName)
        {
            Type          st   = Assembly.GetExecutingAssembly().GetTypes().SingleOrDefault(t => t.IsClass && t.IsPublic && t.GetInterfaces().Any(i => i.Name == nameof(ISemanticType)));
            ISemanticType inst = (ISemanticType)Activator.CreateInstance(st);

            return(inst);
        }
Пример #3
0
    public FType(ISemanticType basetype, LogicalForm formula)
    {
        if (!formula.IsFormula() || formula.IsClosed())
        {
            System.Console.WriteLine("FType failed: not a formula, or not free");
            return;
            // error
        }
        HashSet <Variable> .Enumerator vars = formula.GetFreeVariables().GetEnumerator();
        vars.MoveNext();
        Variable first = vars.Current;

        if (vars.MoveNext())
        {
            System.Console.WriteLine("FType failed: more than one free variable");
            return;
            // error (more than one free variable)
        }

        if (!first.GetSemanticType().Equals(basetype))
        {
            System.Console.WriteLine(first.GetSemanticType());
            System.Console.WriteLine(basetype);

            System.Console.WriteLine("FType failed: types aren't equal");
            return;
            // error
        }
        this.basetype = basetype;
        this.formula  = formula;
    }
Пример #4
0
        /// <summary>
        /// Given this membrane's outbound list, what membranes are inbound permeabe to the ST as well?
        /// </summary>
        public List <IMembrane> PermeateTo(ISemanticType st)
        {
            List <IMembrane> ret    = new List <IMembrane>();
            Type             sttype = st.GetType();

            if (outboundPermeableTo.Contains(sttype))
            {
                // Can we traverse to the parent?
                if ((parent != null) && (parent.inboundPermeableTo.Contains(sttype)))
                {
                    ret.Add(parent);
                }

                // Can we traverse to children?
                foreach (Membrane child in childMembranes)
                {
                    if (child.inboundPermeableTo.Contains(sttype))
                    {
                        ret.Add(child);
                    }
                }
            }

            return(ret);
        }
Пример #5
0
 public Field(VisibilityType visibilityType, ISemanticType type, string name, IExpression expression)
 {
     VisibilityType = visibilityType;
     Type           = type;
     Name           = name;
     Expression     = expression;
 }
Пример #6
0
 public void Process(ISemanticProcessor semProc, IMembrane membrane, ISemanticType t)
 {
     if ( (!(t is ST_Log)) && (!(t is ST_Exception)) )
     {
         Console.WriteLine("Publishing type: " + t.GetType().Name);
     }
 }
Пример #7
0
 public void Process(ISemanticProcessor semProc, IMembrane membrane, ISemanticType t)
 {
     if ((!(t is ST_Log)) && (!(t is ST_Exception)))
     {
         Console.WriteLine("Publishing type: " + t.GetType().Name);
     }
 }
Пример #8
0
 public VisualSemanticType(ISemanticType t, string stName)
 {
     SemanticType   = t;
     Name           = stName;
     Location       = new Point(0, 0);
     TargetLocation = new Point(0, 0);
 }
Пример #9
0
    public App(LogicalForm f, LogicalForm x) : base(null)
    {
        ISemanticType fType = f.GetSemanticType();
        ISemanticType xType = x.GetSemanticType();

        if (fType.GetType() != typeof(Arrow))
        {
            System.Console.WriteLine(
                "App failed: function argument not function type");
            return;
        }
        Arrow aType = (Arrow)fType;

        if (!aType.GetInputType().Equals(xType))
        {
            // error
            System.Console.WriteLine("App failed: type mismatch");
            // throw new InvalidTypeException();
            return;
        }

        this.type = aType.GetOutputType();

        this.isFormula = this.type.GetType() == typeof(T);

        this.freeVariables = f.MergeVariables(x);

        this.f = f;
        this.x = x;
    }
Пример #10
0
 public Variable(ISemanticType type, string name, string id, IExpression expression)
 {
     Type       = type;
     Name       = name;
     Id         = id;
     Expression = expression;
 }
Пример #11
0
    public Variable(ISemanticType type, int id) : base(type)
    {
        this.id        = id;
        this.isFormula = LogicalForm.IsFormulaType(type);

        this.freeVariables = new HashSet <Variable>();
        this.freeVariables.Add(this);
    }
Пример #12
0
        public void Publish(string typeName, string json)
        {
            Type          t  = assy.GetTypes().Single(at => at.Name == typeName);
            ISemanticType st = (ISemanticType)JsonConvert.DeserializeObject(json, t);

            // sp.ProcessInstance(membrane, st, true);
            sp.ProcessInstance <App.HopeMembrane>(st, true);
        }
Пример #13
0
 public ProcessEventArgs(IMembrane fromMembrane, IReceptor fromReceptor, IMembrane toMembrane, IReceptor toReceptor, ISemanticType st)
 {
     FromMembrane = fromMembrane;
     FromReceptor = fromReceptor;
     ToMembrane   = toMembrane;
     ToReceptor   = toReceptor;
     SemanticType = st;
 }
Пример #14
0
        internal override void Scan(bool scanNext)
        {
            for (var i = 0; i < _items.Count; ++i)
            {
                SemanticFind find = _errors[i];
                if (find.Operator == this)
                {
                    _errors.Remove(find);
                    --i;
                }
            }

            _initializedNames.Push(new List <string>());
            ISemanticType rightType = Expression.GetSemanticType();
            ISemanticType leftType  = SimpleType.Boolean;

            if (!rightType.CanCastTo(leftType, false))
            {
                GenerateFind(new InCorrectExpressionType(Operator, Expression.Words, leftType.FullType, rightType.FullType));
            }

            if (Child != null)
            {
                Child.Scan(true);
            }

            var ifNames = new HashSet <string>();

            ifNames.UnionWith(_initializedNames.Pop());

            foreach (var elseIf in ElseIfList)
            {
                _initializedNames.Push(new List <string>());
                elseIf.Scan(true);
                ifNames.IntersectWith(_initializedNames.Pop());
            }

            if (Else != null)
            {
                _initializedNames.Push(new List <string>());
                Else.Scan(true);
                ifNames.IntersectWith(_initializedNames.Pop());
            }
            else
            {
                ifNames.Clear();
            }

            if (_initializedNames.Count > 0)
            {
                _initializedNames.First().AddRange(ifNames);
            }

            if (Next != null && scanNext)
            {
                Next.Scan(true);
            }
        }
Пример #15
0
        protected void PublishSemanticMessage(Dictionary <string, string> data)
        {
            Type          st = Type.GetType("FlowSharpServiceInterfaces." + data["cmd"] + ",FlowSharpServiceInterfaces");
            ISemanticType t  = Activator.CreateInstance(st) as ISemanticType;

            PopulateType(t, data);
            // Synchronous, because however we're processing the commands in order, otherwise we lose the point of a web socket,
            // which keeps the messages in order.
            ServiceManager.Instance.Get <ISemanticProcessor>().ProcessInstance <FlowSharpMembrane>(t, true);
        }
Пример #16
0
        /// <summary>
        /// Any public properties that are of ISemanticType type and not null are also emitted into the membrane.
        /// </summary>
        protected void ProcessInnerTypes(IMembrane membrane, IMembrane caller, ISemanticType obj, bool processOnCallerThread)
        {
            var properties = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(pi => pi.PropertyType.GetInterfaces().Contains(typeof(ISemanticType)));

            properties.ForEach(pi =>
            {
                ISemanticType prop = (ISemanticType)pi.GetValue(obj);
                prop.IfNotNull((p) => ProcessInstance(membrane, caller, p, processOnCallerThread));
            });
        }
Пример #17
0
        protected void PopulateSTChildren(ISemanticType st, object parent)
        {
            TreeView.AddNode(parent, "decl", st.Decl);
            TreeView.AddNode(parent, "struct", st.Struct);

            st.Struct.SemanticElements.ForEach(elem =>
            {
                object tn = TreeView.AddNode(parent, elem.Name, elem);
                PopulateSTChildren(elem.Element, tn);
            });
        }
Пример #18
0
        public void Process(ISemanticProcessor proc, IMembrane membrane, ISemanticType type)
        {
            // Don't log our log message, otherwise we get an infinite loop!
            if (!(type is ST_Log))
            {
                // One way, with instances:
                // proc.ProcessInstance(proc.Logger, new ST_Log() { Message = type.GetType().ToString() });

                // Another way, strictly with types:
                proc.ProcessInstance <LoggerMembrane, ST_Log>(log => log.Message = type.GetType().ToString());
            }
        }
Пример #19
0
        public void Process(ISemanticProcessor proc, IMembrane membrane, ISemanticType type)
        {
            // Don't log our log message, otherwise we get an infinite loop!
            if (!(type is ST_Log))
            {
                // One way, with instances:
                // proc.ProcessInstance(proc.Logger, new ST_Log() { Message = type.GetType().ToString() });

                // Another way, strictly with types:
                proc.ProcessInstance<LoggerMembrane, ST_Log>(log => log.Message = type.GetType().ToString());
            }
        }
Пример #20
0
        protected void PublishSemanticMessage(HttpListenerContext context, string data)
        {
            NameValueCollection nvc = context.Request.QueryString;
            string        stname    = nvc["cmd"];
            Type          st        = Type.GetType("FlowSharpServiceInterfaces." + stname + ",FlowSharpServiceInterfaces");
            ISemanticType t         = Activator.CreateInstance(st) as ISemanticType;

            PopulateType(t, nvc);
            // Synchronous, because however we're processing the command doesn't know (or need to know) that it's
            // coming from an HTTP GET, but we don't want to issue the response until the action has been performed.
            serviceManager.Get <ISemanticProcessor>().ProcessInstance <FlowSharpMembrane>(t, true);
            Response(context);
        }
Пример #21
0
        protected void PopulateType(ISemanticType packet, Dictionary <string, string> data)
        {
            foreach (string key in data.Keys)
            {
                PropertyInfo pi = packet.GetType().GetProperty(key, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);

                if (pi != null)
                {
                    object valOfType = Convert.ChangeType(data[key], pi.PropertyType);
                    pi.SetValue(packet, valOfType);
                }
            }
        }
Пример #22
0
        protected void PopulateType(ISemanticType packet, NameValueCollection nvc)
        {
            foreach (string key in nvc.AllKeys)
            {
                PropertyInfo pi = packet.GetType().GetProperty(key, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);

                if (pi != null)
                {
                    object valOfType = Convert.ChangeType(Uri.UnescapeDataString(nvc[key].Replace('+', ' ')), pi.PropertyType);
                    pi.SetValue(packet, valOfType);
                }
            }
        }
Пример #23
0
    // Super compatible
    private HashSet <int> GetDomain(ISemanticType t)
    {
        Model currentModel = super;

        if (t.GetType() == typeof(FType))
        {
            FType       fType   = (FType)t;
            LogicalForm formula = fType.GetFormula();
            int         varID   = formula.GetFreeVariables().Single <Variable>().GetID();

            ISemanticType baseType = fType.GetBaseType();

            // populating the set with all semantic values
            // (including those in super models)
            // possible error: basetype is undefined in M
            Dictionary <int, ISemanticValue> .KeyCollection baseSet = model[baseType].Keys;

            while (currentModel != null)
            {
                // possible error: basetype is undefined in M
                baseSet.Union <int>(currentModel.model[baseType].Keys);
            }

            HashSet <int> finalSet = new HashSet <int>();

            foreach (int i in baseSet)
            {
                if (Satisfies(formula.Bind(varID, new Constant(baseType, i))))
                {
                    finalSet.Add(i);
                }
            }
            return(finalSet);
        }

        HashSet <int> theSet = new HashSet <int>();

        foreach (int i in model[t].Keys)
        {
            theSet.Add(i);
        }

        while (currentModel != null)
        {
            // possible error: t is undefined in M
            theSet.UnionWith(currentModel.model[t].Keys);
        }

        return(theSet);
    }
Пример #24
0
        /// <summary>
        /// Any public properties that are of ISemanticType type and not null are also emitted into the membrane.
        /// </summary>
        protected void ProcessInnerTypes(IMembrane membrane, IMembrane caller, ISemanticType obj, bool processOnCallerThread, IMembrane fromMembrane, IReceptor fromReceptor)
        {
            // TODO: Setup like we do for main ProcessInstance above so exceptions are caught and we get a ProcStates return.
            // ProcStates ps = ProcStates.NotProcessed;
            var properties = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(pi => pi.PropertyType.GetInterfaces().Contains(typeof(ISemanticType)));

            properties.ForEach(pi =>
            {
                ISemanticType prop = (ISemanticType)pi.GetValue(obj);

                if (prop != null)
                {
                    // TODO: Setup like we do for main ProcessInstance above so exceptions are caught and we get a ProcStates return.
                    ProcessInstanceWithInvoke(membrane, caller, prop, processOnCallerThread);
                }
            });
        }
Пример #25
0
        protected void ProcessTypeCollection()
        {
            foreach (SemanticTypeInstance typeInstance in Program.SemanticTypeSystem.Instances.Values)
            {
                ISemanticType instance = typeInstance.Instance;
                string        name     = typeInstance.Name;

                if (!ignoreNames.Contains(name))
                {
                    // A distinct type name, used for coloration logic.
                    distinctTypes.AddIfUnique(name);

                    // Also, for each type, we have a specific location to group all instances of that type.
                    if (!typeGroups.ContainsKey(name))
                    {
                        typeGroups[name] = new TypeGroup();
                        AdjustGroupLocations();
                        ResetAllTargets();
                    }

                    VisualSemanticType vst = new VisualSemanticType(instance, name);
                    vtypes.Add(vst);                                    // Only the collections go in this space.

                    // Add all the collection elements.
                    if (name == "PopulationByStateByYear")
                    {
                        // This is a collection.
                        List <ISemanticType> stList = (List <ISemanticType>)((dynamic)vst.SemanticType).Collection.Items;
                        int items = stList.Count;

                        stList.ForEachWithIndex((st, idx2) =>
                        {
                            // Create the collection types.  This is for every item in the collection, so many will be repeated (like year and state)
                            string subname = Program.SemanticTypeSystem.GetSemanticTypeName(st);
                            distinctTypes.AddIfUnique(subname);
                            VisualSemanticType vst2  = new VisualSemanticType(st, subname);
                            CollectionSubtype cs     = new CollectionSubtype(instance, st);
                            typeVisualizationMap[cs] = vst2;
                            // vtypes.Add(vst2);
                        });
                    }
                }
            }
        }
Пример #26
0
        internal override void Scan(bool scanNext)
        {
            for (var i = 0; i < _errors.Count; ++i)
            {
                SemanticFind find = _errors[i];
                if (find.Operator == this)
                {
                    _errors.Remove(find);
                    --i;
                }
            }

            ISemanticType rightType = Expression.GetSemanticType();
            ISemanticType leftType  = SimpleType.Boolean;

            if (rightType.CanCastTo(leftType, false))
            {
                GenerateFind(new InCorrectExpressionType(Operator, Expression.Words, leftType.FullType, rightType.FullType));
            }

            Child?.Scan(true);
        }
Пример #27
0
        protected void PopulateType(ISemanticType packet, Dictionary <string, string> data)
        {
            foreach (string key in data.Keys)
            {
                PropertyInfo pi = packet.GetType().GetProperty(key, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);

                if (pi != null)
                {
                    object valOfType = null;
                    Type   ptype     = pi.PropertyType;

                    if (ptype.IsGenericType)
                    {
                        // We assume it's a nullable type
                        ptype = ptype.GenericTypeArguments[0];
                    }

                    valOfType = Convert.ChangeType(Uri.UnescapeDataString(data[key].Replace('+', ' ')), ptype);
                    pi.SetValue(packet, valOfType);
                }
            }
        }
Пример #28
0
    // Adds a semantic value to the model, associating both
    // a semantic type and an ID number to it.
    public UpdateInfo Add(ISemanticType t, int id, ISemanticValue v)
    {
        // if the semantic type isn't currently in the model,
        // add an entry for it.
        if (!model.ContainsKey(t))
        {
            model[t] = new Dictionary <int, ISemanticValue>();
        }
        // get all the semantic values in the model with the
        // semantic type, t.
        Dictionary <int, ISemanticValue> modelByType = model[t];

        // if the ID is already defined for the semantic type t,
        // then don't change the model at all!
        if (modelByType.ContainsKey(id))
        {
            return(UpdateInfo.NoChange);
        }
        // otherwise, set the ID to the semantic value.
        modelByType[id] = v;

        // if there are formula rules with the given semantic type,
        // then we want to generate a sentence rule that refers
        // to the new semantic value.
        if (formulaRules.ContainsKey(t))
        {
            foreach (Rule fr in formulaRules[t])
            {
                HashSet <Rule> srs = GetSentenceRules(fr);
                foreach (Rule sr in srs)
                {
                    sentenceRules.Add(sr);
                }
            }
        }
        // if we're here, then we've updated the model!
        return(UpdateInfo.Updated);
    }
        protected ResponsePacket ProcessInboundSemanticType(Session session, Dictionary <string, object> parms)
        {
            string  json = parms["Data"].ToString();
            JObject jobj = JObject.Parse(json);
            string  type = jobj["_type_"].ToString();

            // strip off the _type_ so we can then instantiate the semantic type.
            json = "{" + json.RightOf(',');

            // Requires that the namespace also matches the remote's namespace.
            Type          ttarget = Type.GetType(type);
            ISemanticType target  = (ISemanticType)Activator.CreateInstance(ttarget);

            JsonConvert.PopulateObject(json, target);
            sp.ProcessInstance <DistributedProcessMembrane>(target);

            ResponsePacket ret = new ResponsePacket()
            {
                Data = Encoding.UTF8.GetBytes("OK"), ContentType = "text"
            };

            return(ret);
        }
Пример #30
0
		/// <summary>
		/// Returns the name as the semantic type given the instance.
		/// This is not very efficient as it is walking through the symbol table.
		/// </summary>
		public string GetSemanticTypeName(ISemanticType instance)
		{
			return SymbolTable.Single(s => s.Instance == instance).Name;
		}
Пример #31
0
        protected void PopulateSTChildren(ISemanticType st, object parent)
        {
            TreeView.AddNode(parent, "decl", st.Decl);
            TreeView.AddNode(parent, "struct", st.Struct);

            st.Struct.SemanticElements.ForEach(elem =>
                {
                    object tn = TreeView.AddNode(parent, elem.Name, elem);
                    PopulateSTChildren(elem.Element, tn);
                });
        }
Пример #32
0
 protected LogicalForm(ISemanticType type)
 {
     this.type = type;
 }
Пример #33
0
        /// <summary>
        /// Traverse permeable membranes without calling back into the caller.  While membranes should not be bidirectionally
        /// permeable, this does stop infinite recursion if the user accidentally (or intentionally) configured the membranes thusly.
        /// </summary>
        protected void PermeateOut(IMembrane membrane, IMembrane caller, ISemanticType obj, bool processOnCallerThread)
        {
            List <IMembrane> pmembranes = ((Membrane)membrane).PermeateTo(obj);

            pmembranes.Where(m => m != caller).ForEach((m) => ProcessInstance(m, membrane, obj, processOnCallerThread));
        }
Пример #34
0
 public CollectionSubtype(ISemanticType coll, ISemanticType subinst)
 {
     collection = coll;
     subinstance = subinst;
 }
Пример #35
0
 public void Process(ISemanticProcessor proc, IMembrane membrane, ISemanticType t)
 {
     stLogged = t is TestSemanticType;
 }
Пример #36
0
        /// <summary>
        /// Process an instance where we only know that it implements ISemanticType as opposed the the concrete type in the generic method above.
        /// We cannot use "dynamic" in this case, therefore we have to use Method.Invoke.
        /// </summary>
        protected void ProcessInstance(IMembrane membrane, IMembrane caller, ISemanticType obj, bool processOnCallerThread = false)
        {
            // We get the source object type.
            Type tsource = obj.GetType();

            // Stateless receptors:

            List <Type> receptors = GetReceptors(membrane, tsource);

            Log(membrane, obj);

            foreach (Type ttarget in receptors)
            {
                // We can use dynamic here because we have a <T> generic to resolve the call parameter.
                // If we instead only have the interface ISemanticType, dynamic does not downcast to the concrete type --
                // therefore it can't locate the call point because it implements the concrete type.
                IReceptor target = (IReceptor)Activator.CreateInstance(ttarget);

                ReceptorInitializer receptorInitializer;

                if (receptorInitializers.TryGetValue(new MembraneReceptor()
                {
                    Membrane = membrane, ReceptorType = ttarget
                }, out receptorInitializer))
                {
                    receptorInitializer.Initializer(target);
                }

                // Call immediately?
                MethodInfo method = GetProcessMethod(target, tsource);

                if (processOnCallerThread)
                {
                    method.Invoke(target, new object[] { this, membrane, obj });
                }
                else
                {
                    // Pick a thread that has the least work to do.
                    threadPool.MinBy(tp => tp.Count).Enqueue(new MethodInvokeCall()
                    {
                        Method = method, SemanticInstance = obj, Receptor = target, Parameters = new object[] { this, membrane, obj }
                    });
                }
            }

            // Also check stateful receptors
            List <IReceptor> sreceptors = GetStatefulReceptors(membrane, tsource);

            foreach (IReceptor receptor in sreceptors)
            {
                MethodInfo method = GetProcessMethod(receptor, tsource);

                // Call immediately?
                if (processOnCallerThread)
                {
                    method.Invoke(receptor, new object[] { this, membrane, obj });
                }
                else
                {
                    threadPool.MinBy(tp => tp.Count).Enqueue(new MethodInvokeCall()
                    {
                        Method = method, SemanticInstance = obj, Receptor = receptor, Parameters = new object[] { this, membrane, obj }, AutoDispose = false
                    });
                }
            }

            ProcessInnerTypes(membrane, caller, obj, processOnCallerThread);
            PermeateOut(membrane, caller, obj, processOnCallerThread);
        }
Пример #37
0
 public VisualSemanticType(ISemanticType t, string stName)
 {
     SemanticType = t;
     Name = stName;
     Location = new Point(0, 0);
     TargetLocation = new Point(0, 0);
 }