protected override void BeginVisit(IConstant cn)
 {
     if (cn is INodeGenSettings)
     {
         _act(cn as INodeGenSettings);
     }
 }
        // PF TODO: This API and ConstantEditorBuilder is badly designed.

        /// <summary>
        /// Creates an editor for a constant.
        /// </summary>
        /// <param name="uiContext">The view in which the editor constant will be displayed.</param>
        /// <param name="portModel">The port that owns the constant, if any.</param>
        /// <param name="constant">The constant.</param>
        /// <param name="onValueChanged">An action to call when the user has finished editing the value.</param>
        /// <param name="modelIsLocked">Whether the node owning the constant, if any, is locked.</param>
        /// <returns>A VisualElement that contains an editor for the constant.</returns>
        public static VisualElement CreateEditorForConstant(
            IModelView uiContext, IPortModel portModel, IConstant constant,
            Action <IChangeEvent, object> onValueChanged, bool modelIsLocked)
        {
            Action <IChangeEvent> myValueChanged = evt =>
            {
                if (evt != null) // Enum editor sends null
                {
                    var p        = evt.GetType().GetProperty("newValue");
                    var newValue = p.GetValue(evt);
                    if (constant is IStringWrapperConstantModel stringWrapperConstantModel)
                    {
                        stringWrapperConstantModel.StringValue = (string)newValue;
                    }
                    else
                    {
                        onValueChanged(evt, newValue);
                    }
                }
            };

            var ext = ExtensionMethodCache <IConstantEditorBuilder> .GetExtensionMethod(
                uiContext.GetType(), constant.GetType(),
                ConstantEditorBuilder.FilterMethods, ConstantEditorBuilder.KeySelector);

            if (ext != null)
            {
                var constantBuilder = new ConstantEditorBuilder(myValueChanged, uiContext.CommandDispatcher, modelIsLocked, portModel);
                return((VisualElement)ext.Invoke(null, new object[] { constantBuilder, constant }));
            }

            Debug.Log($"Could not draw Editor GUI for node of type {constant.Type}");
            return(new Label("<Unknown>"));
        }
    protected override void ButtonClickedListener()
    {
        if (_instance != null)
        {
            IConstant targetInstanceWithConstant = null;
            if (((Field)_instance).HasPredicateInstance())
            {
                targetInstanceWithConstant = TryDeleteConstant();
            }

            if (targetInstanceWithConstant == null)
            {
                _instance.AddConstant(_constant);
            }
            else if (targetInstanceWithConstant != null && targetInstanceWithConstant != _instance)
            {
                _instance.AddConstant(_constant);
            }

            ValidateOverlay();
        }
        else
        {
            Debug.LogWarning("Instance is null");
        }
    }
Exemple #4
0
        public static string Comment(IConstant t, string indent = "")
        {
            var sb = new StringBuilder();

            sb.Append(indent);
            sb.Append(commentBegSummary);
            sb.AppendLine();

            sb.Append(indent);
            sb.Append(comment);
            sb.Append("UI name: ");
            sb.Append(t.NameUi);
            sb.AppendLine();

            if (!string.IsNullOrWhiteSpace(t.Description))
            {
                sb.Append(indent);
                sb.Append(comment);
                //sb.Append("Description: ");
                sb.Append(t.Description);
                sb.AppendLine();
            }

            sb.Append(indent);
            sb.Append(commentEndSummary);
            return(sb.ToString());
        }
 //大于
 private static IConstant GreaterThan(IConstant arg1, IConstant arg2)
 {
     if (Convert.ToDouble(arg1.Value) > Convert.ToDouble(arg2.Value))
     {
         return new IntConstant(1);
     }
     return new IntConstant(0);
 }
 //小于等于
 private static IConstant LessEquals(IConstant arg1, IConstant arg2)
 {
     if (Convert.ToDouble(arg1.Value) <= Convert.ToDouble(arg2.Value))
     {
         return new IntConstant(1);
     }
     return new IntConstant(0);
 }
 //非
 private static IConstant Not(IConstant arg)
 {
     if (Convert.ToDouble(arg.Value) == 0)
     {
         return new IntConstant(1);
     }
     return new IntConstant(0);
 }
 //或
 private static IConstant Or(IConstant arg1, IConstant arg2)
 {
     if (Convert.ToDouble(arg1.Value) != 0 || Convert.ToDouble(arg2.Value) != 0)
     {
         return new IntConstant(1);
     }
     return new IntConstant(0);
 }
Exemple #9
0
 public virtual bool IsFileGroup(IConstant ccc)
 {
     if (ccc is efx.Environment.Scheme.ConstFileGroup)
     {
         return(true);
     }
     return(false);
 }
Exemple #10
0
 public virtual bool IsFileGroup(IConstant ccc)
 {
     Globe.cstat(ConsoleColor.Green, "IsFileGroup?\r\t{0}: {1}", ccc.GetType(), ConsoleColor.Red, ccc.Value);
     if (ccc is efx.Environment.Scheme.ConstFileGroup)
     {
         return(true);
     }
     return(false);
 }
Exemple #11
0
 public bool GetValue(String varName, out IConstant value)
 {
     if (varDict.ContainsKey(varName))
     {
         value = varDict[varName];
         return(true);
     }
     value = null;
     return(false);
 }
        /// <summary>
        ///     Creates a new <see cref="IConstant" /> for the given <c>name</c> or fail with an
        ///     <see cref="ArgumentException" /> if a <see cref="IConstant" /> for the given <c>name</c> exists.
        /// </summary>
        public IConstant NewInstance <T>(string name)
        {
            if (this.Exists(name))
            {
                throw new ArgumentException($"'{name}' is already in use");
            }
            IConstant c = this.NewInstance0 <T>(name);

            return(c);
        }
Exemple #13
0
        //获取函数地址
        public int GetFunction(String funName)
        {
            IConstant constant = variableTableStack.GetValue(funName);

            if (constant.Type == NumericType.INT && ((IntConstant)constant).Usage == IntUsage.INSADDR)
            {
                return((int)constant.Value);
            }
            throw new Exception("cmm_vm::VMCore::getFunction: 变量名不指向函数");
        }
Exemple #14
0
        //实数出栈
        public RealConstant PopRealConst()
        {
            IConstant constant = operandStack.Pop();

            if (constant.Type != NumericType.REAL)
            {
                throw reporter.Throw("值类型错误", VMExceptionType.WRONG_TYPE);
            }
            return((RealConstant)constant);
        }
 //除法
 private static IConstant Div(IConstant arg1, IConstant arg2)
 {
     //只要一个参数为实数,则按照两个函数都为实数计算
     if (arg1.Type == NumericType.REAL || arg2.Type == NumericType.REAL)
     {
         return new RealConstant(Convert.ToDouble(arg1.Value) / Convert.ToDouble(arg2.Value));
     }
     //否则两个都是整数
     return new IntConstant((int)arg1.Value / (int)arg2.Value);
 }
 //取反
 private static IConstant Neg(IConstant arg)
 {
     //实数
     if (arg.Type == NumericType.REAL)
     {
         return new RealConstant(-Convert.ToDouble(arg.Value));
     }
     //整数
     return new IntConstant(-(int)arg.Value);
 }
Exemple #17
0
 // Be careful that this dose not check whether the argument is null or empty.
 IConstant NewInstance0 <T>(string name)
 {
     lock (this.constants)
     {
         IConstant c = this.NewConstant <T>(this.nextId, name);
         this.constants[name] = c;
         this.nextId++;
         return(c);
     }
 }
        private void AddReferenceToNode(ModelNode md, IConstant constant, IDataType d)
        {
            if (!md.DicReferenceToNodes.ContainsKey(d.ObjectGuid))
            {
                md.DicReferenceToNodes[d.ObjectGuid] = new ReferenceTo();
            }
            var tn = md.DicReferenceToNodes[d.ObjectGuid];

            tn.DicByFields[constant.Guid] = constant;
            tn.ToObject = this.currCfg.DicNodes[d.ObjectGuid];
        }
Exemple #19
0
 public static IncludeConstant Parse(IConstant arg)
 {
     return(new IncludeConstant
     {
         Name = arg.Name,
         Namespace = arg.Namespace,
         AccessibleNamespaces = arg.AccessibleNamespaces,
         Value = arg.Value,
         FullName = arg.FullName
     });
 }
 public ArticlesController(RoleManager <IdentityRole> roleManager, UserManager <ApplicationUser> userManager,
                           IArticles allArticles, IArticlesCategory allCategories, IArticlesAccess allArticlesAccess,
                           IConstant constants)
 {
     _allArticles       = allArticles;
     _allCategories     = allCategories;
     _allArticlesAccess = allArticlesAccess;
     _constants         = constants;
     _roleManager       = roleManager;
     _userManager       = userManager;
 }
Exemple #21
0
        /// <summary>
        ///     Creates a new <see cref="IConstant" /> for the given <c>name</c> or fail with an
        ///     <see cref="ArgumentException" /> if a <see cref="IConstant" /> for the given <c>name</c> exists.
        /// </summary>
        public IConstant NewInstance <T>(string name)
        {
            if (this.Exists(name))
            {
                ThrowHelper.ThrowArgumentException(name);
            }

            IConstant c = this.NewInstance0 <T>(name);

            return(c);
        }
Exemple #22
0
        //声明实型数组
        public void DeclareRealArray(String varName)
        {
            variableTableStack.DeclareIntVar(varName, IntUsage.ARRAYADDR);
            IConstant size = PopOperand();

            if (size.Type == NumericType.REAL)
            {
                //todo:数组的大小不为整数时报错
                //不确定语法分析时做没做
                return;
            }
            variableTableStack.SetIntValue(varName, (int)heap.AllocRealArray((int)size.Value).Value);
        }
Exemple #23
0
        public ValueType GetVariable(String name)
        {
            IConstant constant = variableTableStack.GetValue(name);

            if (constant.Type == NumericType.INT)
            {
                return((int)constant.Value);
            }
            else
            {
                return((double)constant.Value);
            }
        }
Exemple #24
0
 // XML generator constant nodes
 public void xg(int indnt, StreamWriter writer, IConstant node, string msg)
 {
     indent(indnt, writer);
     if (msg != "")
     {
         writer.WriteLine(msg);
     }
     writer.Write("<IConstant NodeId=\"" + node.UniqueId + "\" ParentId=\"" + node.ParentNode.UniqueId + "\">\n");
     indent(indnt + 1, writer); writer.Write("<Value>" + node.Value + "</Value>\n");
     PrintDataType(indnt + 1, writer, node.DataType);
     PrintTerminals(indnt + 1, writer, node.Terminals);
     indent(indnt, writer); writer.Write("</IConstant>\n");
 }
Exemple #25
0
        //存储变量到变量表
        public void StoreVariable(String varName)
        {
            IConstant val = operandStack.Pop();

            if (val.Type == NumericType.INT)
            {
                variableTableStack.SetIntValue(varName, (int)val.Value);
            }
            else
            {
                variableTableStack.SetRealValue(varName, (double)val.Value);
            }
        }
    private void SelectionClickedListener(SelectionManager.EventArgs arg0)
    {
        if (arg0.CurrentSelectedElement != null)
        {
            var element = arg0.CurrentSelectedElement.GetRootObj().GetComponent <IConstant>();
            if (element != null)
            {
                _instance = element;
            }
        }

        ValidateOverlay();
    }
Exemple #27
0
        protected override IVariableDeclarationModel InstantiateVariableDeclaration(Type variableTypeToCreate,
                                                                                    TypeHandle variableDataType, string variableName, ModifierFlags modifierFlags, bool isExposed,
                                                                                    IConstant initializationModel, SerializableGUID guid, Action <IVariableDeclarationModel, IConstant> initializationCallback = null)
        {
            var vdm = base.InstantiateVariableDeclaration(variableTypeToCreate, variableDataType, variableName, modifierFlags, isExposed, initializationModel, guid, initializationCallback);

            if (vdm is VariableDeclarationModel testVdm)
            {
                testVdm.SetGraphModel(this);
            }

            return(vdm);
        }
        private static PXSetPropertyException VerifyingAndGetError(PXUIVerifyAttribute attr, PXCache sender, object row)
        {
            if (row == null)
            {
                return(null);
            }

            if (attr == null)
            {
                throw new PXException(ErrorMessages.AttributeNotDefined, typeof(PXUIVerifyAttribute).Name);
            }

            if (attr.Condition != null && !GetConditionResult(sender, row, attr.Condition))
            {
                List <object> messageParams = new List <object>();

                foreach (Type arg in attr._args)
                {
                    if (typeof(IConstant).IsAssignableFrom(arg))
                    {
                        IConstant constantInstance = Activator.CreateInstance(arg) as IConstant;
                        messageParams.Add(constantInstance?.Value);
                    }
                    else if (attr.MessageArgumentsAreFieldNames)
                    {
                        messageParams.Add(PXUIFieldAttribute.GetDisplayName(sender, arg.Name));
                    }
                    else if (arg.IsGenericType && arg.GetGenericTypeDefinition() == typeof(Current <>))
                    {
                        Type    field = arg.GetGenericArguments()[0];
                        PXCache cache = sender.Graph.Caches[BqlCommand.GetItemType(field)];
                        messageParams.Add(cache.GetValue(cache.Current, field.Name));
                    }
                    else
                    {
                        var value = sender.GetValueExt(row, arg.Name);

                        if (value is PXFieldState)
                        {
                            messageParams.Add(((PXFieldState)value).Value);
                        }
                        else
                        {
                            messageParams.Add(value);
                        }
                    }
                }
                return(new PXSetPropertyException(attr._Message, attr._ErrorLevel, messageParams.ToArray()));
            }
            return(null);
        }
Exemple #29
0
 public virtual bool IsFile(IConstant ccc)
 {
     Globe.cstat(ConsoleColor.Green, "IsFile?\r\t{0}: {1}", ccc.GetType(), ConsoleColor.Red, ccc.Value);
     if (ccc is efx.Environment.Scheme.ConstFile)
     {
         return(true);
     }
     if (ccc is efx.Environment.Scheme.FileCommand)
     {
         return(true);
     }
     //if (ccc is efx.Environment.Scheme.FileFilter) return true;
     return(false);
 }
    private IConstant TryDeleteConstant()
    {
        var instance = GameManager.Instance;

        if (instance)
        {
            IConstant fieldobj = instance.GetCurrentBoard().GetBoardWithTargetConstant(_constant);
            if (fieldobj != null)
            {
                fieldobj.RemoveConstant(_constant);
            }
            return(fieldobj);
        }
        return(null);
    }
Exemple #31
0
 public StoredProcedureParameter(string name, DataTypeBase dataType, IConstant defaultValue, bool isOut, bool isReadonly)
     : this(name, dataType, defaultValue, isOut)
 {
     IsReadonly = isReadonly;
 }
Exemple #32
0
        private void Andify(List<IComponent> inputs, IComponent output, IConstant trueProp)
        {
            //Special case: If the inputs include false, connect false to thisComponent
            IEnumerable<IComponent> falseConstants = inputs.Where(c => c is IConstant && !c.Value);
            foreach (IComponent c in falseConstants)
            {
                //Connect false (c) to the output
                output.AddInput(c);
                c.AddOutput(output);
                return;
            }

            //For reals... just skip over any true constants
            var and = _componentFactory.CreateAnd();
            IEnumerable<IComponent> nonConstants = inputs.Where(input => !(input is IConstant));
            foreach (IComponent input in nonConstants)
            {
                input.AddOutput(and);
                and.AddInput(input);
            }

            //What if they're all true? (Or inputs is empty?) Then no inputs at this point...
            if (!and.Inputs.Any())
            {
                //Hook up to "true"
                trueProp.AddOutput(output);
                output.AddInput(trueProp);
                return;
            }
            //If there's just one, on the other hand, don't use the and gate
            if (and.Inputs.Count == 1)
            {
                IComponent input = and.GetSingleInput();
                input.RemoveOutput(and);
                and.RemoveInput(input);
                input.AddOutput(output);
                output.AddInput(input);
                return;
            }
            and.AddOutput(output);
            output.AddInput(and);
        }
Exemple #33
0
 public StoredProcedureParameter(string name, DataTypeBase dataType, IConstant defaultValue, bool isOut)
     : this(name, dataType, defaultValue)
 {
     IsOut = isOut;
 }
Exemple #34
0
 public StoredProcedureParameter(string name, DataTypeBase dataType, IConstant defaultValue)
     : this(name, dataType)
 {
     DefaultValue = defaultValue;
 }
Exemple #35
0
        public void AddSentenceForm(ISentenceForm form, ISentenceDomainModel model,
            IDictionary<Fact, IComponent> components,
            IDictionary<Fact, IComponent> negations, IConstant trueComponent, IConstant falseComponent,
            bool usingBase, bool usingInput, ISet<ISentenceForm> recursionForms,
            IDictionary<Fact, IComponent> temporaryComponents, IDictionary<Fact, IComponent> temporaryNegations,
            Dictionary<ISentenceForm, FunctionInfo> functionInfoMap, IConstantChecker constantChecker,
            Dictionary<ISentenceForm, ICollection<Fact>> completedSentenceFormValues)
        {
            //This is the meat of it (along with the entire Assignments class).
            //We need to enumerate the possible propositions in the sentence form...
            //We also need to hook up the sentence form to the inputs that can make it true.
            //We also try to optimize as we go, which means possibly removing the
            //proposition if it isn't actually possible, or replacing it with
            //true/false if it's a constant.

            ISet<Fact> alwaysTrueSentences = model.GetSentencesListedAsTrue(form);
            ISet<Implication> rules = model.GetRules(form);

            foreach (Fact alwaysTrueSentence in alwaysTrueSentences)
            {
                //We add the sentence as a constant
                if (alwaysTrueSentence.RelationName == GameContainer.Parser.TokLegal
                    || alwaysTrueSentence.RelationName == GameContainer.Parser.TokNext
                    || alwaysTrueSentence.RelationName == GameContainer.Parser.TokGoal)
                {
                    var prop = _componentFactory.CreateProposition(alwaysTrueSentence);
                    //Attach to true
                    trueComponent.AddOutput(prop);
                    prop.AddInput(trueComponent);
                    //Still want the same components;
                    //we just don't want this to be anonymized
                }
                //Assign as true
                components[alwaysTrueSentence] = trueComponent;
                negations[alwaysTrueSentence] = falseComponent;
            }

            //For does/true, make nodes based on input/base, if available
            if (usingInput && form.Name.Equals(GameContainer.Parser.TokDoes))
            {
                //Add only those propositions for which there is a corresponding INPUT
                ISentenceForm inputForm = form.WithName(GameContainer.SymbolTable["input"]);
                foreach (Fact inputSentence in constantChecker.GetTrueSentences(inputForm))
                {
                    Fact doesSentence = _doesProcessor.ProcessBaseFact(inputSentence);
                    var prop = _componentFactory.CreateProposition(doesSentence);
                    components[doesSentence] = prop;
                }
                return;
            }
            if (usingBase && form.Name.Equals(GameContainer.Parser.TokTrue))
            {
                ISentenceForm baseForm = form.WithName(GameContainer.SymbolTable["base"]);
                foreach (Fact baseSentence in constantChecker.GetTrueSentences(baseForm))
                {
                    Fact trueSentence = _trueProcessor.ProcessBaseFact(baseSentence);
                    IProposition prop = _componentFactory.CreateProposition(trueSentence);
                    components[trueSentence] = prop;
                }
                return;
            }

            //var recursiveFormCache = new RecursionFormsCache(recursionForms);

            var inputsToOr = new Dictionary<Fact, HashSet<IComponent>>();
            foreach (Implication rule in rules)
            {
                AssignmentsImpl assignments = AssignmentsFactory.GetAssignmentsForRule(rule, model, functionInfoMap,
                    completedSentenceFormValues);

                //Calculate vars in live (non-constant, non-distinct) conjuncts
                ISet<TermVariable> varsInLiveConjuncts = GetVarsInLiveConjuncts(rule,
                    constantChecker.ConstantSentenceForms);
                foreach (var head in rule.Consequent.VariablesOrEmpty)
                    varsInLiveConjuncts.Add(head);
                var varsInRule = new HashSet<TermVariable>(rule.VariablesOrEmpty);
                bool preventDuplicatesFromConstants = varsInRule.Count > varsInLiveConjuncts.Count;

                bool[] constantFormCheck = new bool[rule.Antecedents.Constituents.Length];
                for (int i = 0; i < rule.Antecedents.Constituents.Length; i++)
                {
                    Expression literal = rule.Antecedents.Constituents[i];
                    var fact = literal as Fact;
                    var negated = literal as Negation;
                    if (fact != null || negated != null)
                    {
                        if (negated != null)
                            fact = (Fact) negated.Negated;

                        ISentenceForm conjunctForm = model.GetSentenceForm(fact);
                        if (constantChecker.IsConstantForm(conjunctForm))
                            constantFormCheck[i] = true;
                    }
                }

                for (var asnItr = (AssignmentIteratorImpl) assignments.GetEnumerator(); asnItr.MoveNext();)
                {
                    TermObjectSubstitution assignment = asnItr.Current;
                    if (assignment == null)
                        continue; //Not sure if this will ever happen

                    //ConcurrencyUtils.checkForInterruption();

                    var sentence = (Fact) rule.Consequent.ApplySubstitution(assignment);

                    //Now we go through the conjuncts as before, but we wait to hook them up.
                    var componentsToConnect = new List<IComponent>(rule.Consequent.Arity);
                    for (int i = 0; i < rule.Antecedents.Constituents.Length; i++)
                    {
                        Expression literal = rule.Antecedents.Constituents[i];
                        var fact = literal as Fact;
                        if (fact != null)
                        {
                            if (fact.RelationName != GameContainer.Parser.TokDistinct)
                            {
                                //Get the sentence post-substitutions
                                var transformed = (Fact) literal.ApplySubstitution(assignment);

                                //Check for constant-ness
                                //ISentenceForm conjunctForm = model.GetSentenceForm(transformed);
                                //if (constantChecker.IsConstantForm(conjunctForm))
                                if (constantFormCheck[i])
                                {
                                    if (!constantChecker.IsTrueConstant(transformed))
                                    {
                                        List<TermVariable> varsToChange = GetVarsInConjunct(literal);
                                        asnItr.ChangeOneInNext(varsToChange, assignment);
                                        componentsToConnect.Add(null);
                                    }
                                    continue;
                                }

                                //If conj is null and this is a sentence form we're still handling, hook up to a temporary sentence form
                                IComponent conj;
                                if (!components.TryGetValue(transformed, out conj))
                                    temporaryComponents.TryGetValue(transformed, out conj);

                                if (conj == null && InSentenceFormGroup(transformed, recursionForms))
                                {
                                    //Set up a temporary component
                                    var tempProp = _componentFactory.CreateProposition(transformed);
                                    temporaryComponents[transformed] = tempProp;
                                    conj = tempProp;
                                }
                                //Let's say this is false; we want to backtrack and change the right variable
                                if (conj == null || IsThisConstant(conj, falseComponent))
                                {
                                    List<TermVariable> varsInConjunct = GetVarsInConjunct(literal);
                                    asnItr.ChangeOneInNext(varsInConjunct, assignment);
                                    //These last steps just speed up the process
                                    //telling the factory to ignore this rule
                                    componentsToConnect.Add(null);
                                    continue; //look at all the other restrictions we'll face
                                }

                                componentsToConnect.Add(conj);
                            }
                        }
                        else
                        {
                            var negation = literal as Negation;
                            if (negation != null)
                            {
                                //Add a "not" if necessary
                                //Look up the negation
                                var inner = (Fact) negation.Negated;
                                var transformed = (Fact) inner.ApplySubstitution(assignment);

                                //Add constant-checking here...
                                //ISentenceForm conjunctForm = model.GetSentenceForm(transformed);
                                //if (constantChecker.IsConstantForm(conjunctForm))
                                if (constantFormCheck[i])
                                {
                                    if (constantChecker.IsTrueConstant(transformed))
                                    {
                                        List<TermVariable> varsToChange = GetVarsInConjunct(negation);
                                        asnItr.ChangeOneInNext(varsToChange, assignment);
                                        componentsToConnect.Add(null);
                                    }
                                    continue;
                                }

                                IComponent conj;
                                negations.TryGetValue(transformed, out conj);
                                if (IsThisConstant(conj, falseComponent))
                                {
                                    //We need to change one of the variables inside
                                    List<TermVariable> varsInConjunct = GetVarsInConjunct(inner);
                                    asnItr.ChangeOneInNext(varsInConjunct, assignment);
                                    //ignore this rule
                                    componentsToConnect.Add(null);
                                    continue;
                                }
                                if (conj == null)
                                    temporaryNegations.TryGetValue(transformed, out conj);

                                //Check for the recursive case:
                                if (conj == null && InSentenceFormGroup(transformed, recursionForms))
                                {
                                    IComponent positive;
                                    if (!components.TryGetValue(transformed, out positive))
                                        temporaryComponents.TryGetValue(transformed, out positive);

                                    if (positive == null)
                                    {
                                        //Make the temporary proposition
                                        var tempProp = _componentFactory.CreateProposition(transformed);
                                        temporaryComponents[transformed] = tempProp;
                                        positive = tempProp;
                                    }
                                    //Positive is now set and in temporaryComponents
                                    //Evidently, wasn't in temporaryNegations
                                    //So we add the "not" gate and set it in temporaryNegations
                                    var not = _componentFactory.CreateNot();
                                    //Add positive as input
                                    not.AddInput(positive);
                                    positive.AddOutput(not);
                                    temporaryNegations[transformed] = not;
                                    conj = not;
                                }
                                if (conj == null)
                                {
                                    IComponent positive;
                                    components.TryGetValue(transformed, out positive);
                                    //No, because then that will be attached to "negations", which could be bad

                                    if (positive == null)
                                    {
                                        //So the positive can't possibly be true (unless we have recurstion)
                                        //and so this would be positive always
                                        //We want to just skip this conjunct, so we continue to the next

                                        continue; //to the next conjunct
                                    }

                                    //Check if we're sharing a component with another sentence with a negation
                                    //(i.e. look for "nots" in our outputs and use those instead)
                                    INot existingNotOutput = GetNotOutput(positive);
                                    if (existingNotOutput != null)
                                    {
                                        componentsToConnect.Add(existingNotOutput);
                                        negations[transformed] = existingNotOutput;
                                        continue; //to the next conjunct
                                    }

                                    var not = _componentFactory.CreateNot();
                                    not.AddInput(positive);
                                    positive.AddOutput(not);
                                    negations[transformed] = not;
                                    conj = not;
                                }
                                componentsToConnect.Add(conj);
                            }
                            else
                            {
                                throw new Exception("Unwanted Expression type");
                            }
                        }
                    }
                    if (!componentsToConnect.Contains(null))
                    {
                        //Connect all the components
                        IProposition andComponent = _componentFactory.CreateProposition(_tempFact);

                        Andify(componentsToConnect, andComponent, trueComponent);
                        if (!IsThisConstant(andComponent, falseComponent))
                        {
                            if (!inputsToOr.ContainsKey(sentence))
                                inputsToOr[sentence] = new HashSet<IComponent>();
                            inputsToOr[sentence].Add(andComponent);
                            //We'll want to make sure at least one of the non-constant
                            //components is changing
                            if (preventDuplicatesFromConstants)
                                asnItr.ChangeOneInNext(varsInLiveConjuncts, assignment);
                        }
                    }
                }
            }

            //At the end, we hook up the conjuncts
            foreach (var entry in inputsToOr)
            {
                //ConcurrencyUtils.checkForInterruption();

                Fact sentence = entry.Key;
                HashSet<IComponent> inputs = entry.Value;
                var realInputs = new HashSet<IComponent>();
                foreach (IComponent input in inputs)
                    if (input is IConstant || !input.Inputs.Any())
                        realInputs.Add(input);
                    else
                    {
                        realInputs.Add(input.GetSingleInput());
                        input.GetSingleInput().RemoveOutput(input);
                        input.RemoveAllInputs();
                    }

                var prop = _componentFactory.CreateProposition(sentence);
                Orify(realInputs, prop, falseComponent);
                components[sentence] = prop;
            }

            //True/does sentences will have none of these rules, but
            //still need to exist/"float"
            //We'll do this if we haven't used base/input as a basis
            if (form.Name.Equals(GameContainer.Parser.TokTrue) || form.Name.Equals(GameContainer.Parser.TokDoes))
                foreach (Fact sentence in model.GetDomain(form)) //ConcurrencyUtils.checkForInterruption();
                    components[sentence] = _componentFactory.CreateProposition(sentence);
        }
        private static void RemoveUselessBasePropositions(Dictionary<Fact, IComponent> components, Dictionary<Fact, IComponent> negations,
            IConstant trueComponent, IConstant falseComponent)
        {
            bool changedSomething = false;
            foreach (KeyValuePair<Fact, IComponent> entry in components)
            {
                if (entry.Key.RelationName == GameContainer.Parser.TokTrue)
                {
                    IComponent comp = entry.Value;
                    if (!comp.Inputs.Any())
                    {
                        comp.AddInput(falseComponent);
                        falseComponent.AddOutput(comp);
                        changedSomething = true;
                    }
                }
            }
            if (!changedSomething)
                return;

            OptimizeAwayTrueAndFalse(components, negations, trueComponent, falseComponent);
        }
        /// <summary>
        /// Adds an or gate connecting the inputs to produce the output.
        /// Handles special optimization cases like a true/false input.
        /// </summary>
        private static void Orify(ICollection<IComponent> inputs, IComponent output, IConstant falseProp)
        {
            //TODO: Look for already-existing ors with the same inputs?
            //Or can this be handled with a GDL transformation?

            //Special case: An input is the true constant
            IEnumerable<IComponent> trueConstants = inputs.Where(input => input is IConstant && input.Value);
            foreach (IComponent input in trueConstants)
            {
                //True constant: connect that to the component, done
                input.AddOutput(output);
                output.AddInput(input);
                return;
            }

            //Special case: An input is "or"
            //I'm honestly not sure how to handle special cases here...
            //What if that "or" gate has multiple outputs? Could that happen?

            //For reals... just skip over any false constants
            var or = _componentFactory.CreateOr();
            IEnumerable<IComponent> nonConstants = inputs.Where(input => !(input is IConstant));
            foreach (IComponent input in nonConstants)
            {
                input.AddOutput(or);
                or.AddInput(input);
            }

            //What if they're all false? (Or inputs is empty?) Then no inputs at this point...
            if (!or.Inputs.Any())
            {
                //Hook up to "false"
                falseProp.AddOutput(output);
                output.AddInput(falseProp);
                return;
            }
            //If there's just one, on the other hand, don't use the or gate
            if (or.Inputs.Count == 1)
            {
                IComponent input = or.GetSingleInput();
                input.RemoveOutput(or);
                or.RemoveInput(input);
                input.AddOutput(output);
                output.AddInput(input);
                return;
            }
            or.AddOutput(output);
            output.AddInput(or);
        }
 private void PrintConstant(IConstant constant)
 {
     builder.Append(constant.Value);
 }
        //TODO: Replace with version using constantChecker only
        //TODO: This can give problematic results if interpreted in
        //the standard way (see test_case_3d)
        private static void SetUpInit(IDictionary<Fact, IComponent> components, IConstant trueComponent, IConstant falseComponent)
        {
            var initProposition = _componentFactory.CreateProposition(new GroundFact(GameContainer.SymbolTable["INIT"]));
            IEnumerable<KeyValuePair<Fact, IComponent>> trueComponents = components.Where(entry => entry.Value == trueComponent);
            IEnumerable<KeyValuePair<Fact, IComponent>> trueInits = trueComponents.Where(entry => entry.Key.RelationName == GameContainer.Parser.TokInit);
            IEnumerable<Fact> trueInitFacts = trueInits.Select(entry => TrueProcessor.ProcessBaseFact(entry.Key));
            IEnumerable<IComponent> initTrueSentenceComponents = trueInitFacts.Select(trueSentence => components[trueSentence]);

            foreach (IComponent trueSentenceComponent in initTrueSentenceComponents)
            {
                if (!trueSentenceComponent.Inputs.Any())
                {
                    //Case where there is no transition input
                    //Add the transition input, connect to init, continue loop
                    var transition = _componentFactory.CreateTransition();
                    //init goes into transition
                    transition.AddInput(initProposition);
                    initProposition.AddOutput(transition);
                    //transition goes into component
                    trueSentenceComponent.AddInput(transition);
                    transition.AddOutput(trueSentenceComponent);
                }
                else
                {
                    //The transition already exists
                    IComponent transition = trueSentenceComponent.GetSingleInput();

                    //We want to add init as a thing that precedes the transition
                    //Disconnect existing input
                    IComponent input = transition.GetSingleInput();
                    //input and init go into or, or goes into transition
                    input.RemoveOutput(transition);
                    transition.RemoveInput(input);
                    var orInputs = new List<IComponent>(2) { input, initProposition };
                    Orify(orInputs, transition, falseComponent);
                }
            }
        }
Exemple #40
0
 private static bool IsThisConstant(IComponent conj, IConstant constantComponent)
 {
     if (conj == constantComponent)
         return true;
     return (conj is IProposition && conj.Inputs.Count == 1 && conj.GetSingleInput() == constantComponent);
 }