public ContinueCodelet(double salience, Context context, IContinuation succ, IFailure fail)
     : base(context.Coderack, salience, 4 * 4, 5)
 {
     this.context = context;
     this.succ = succ;
     this.fail = fail;
 }
Пример #2
0
        void DoMatching(List <PatternTemplateSource> dicta, string input)
        {
            if (verbose > 0)
            {
                Console.WriteLine("Parsing input...");
            }
            IParsedPhrase phrase = parser.Parse(input);

            if (verbose > 0)
            {
                Console.WriteLine("Matching templates...");
            }

            // Add a codelet for each of these, to match the input
            if (!serialmode)
            {
                foreach (PatternTemplateSource dictum in dicta)
                {
                    IFailure fail = tryToRescueMatch.MakeFailure(phrase, dictum, this, new NopCallable(), coderack);
                    dictum.Generate(coderack, phrase, this, fail, 1.0);
                }
            }
            else
            {
                SerialTemplateMatcher matcher = new SerialTemplateMatcher(this, this, coderack, tryToRescueMatch, phrase, dicta, 1.0);
                matcher.MatchNextSentence();
            }

            RunToEnd();
        }
        public override bool Call(object value, IContinuation succ, IFailure fail)
        {
            Context context = (Context)value;

            double result = 0;

            foreach (IContent content in context.Contents)
            {
                double term = 0;
                if (content is Word && double.TryParse(content.Name, out term))
                {
                    result += term;
                }
                else
                {
                    fail.Fail("Argument isn't number", succ);
                    return(true);
                }
            }

            List <IContent> cntres = new List <IContent>();

            cntres.Add(new Word(result.ToString()));
            succ.Continue(new Context(context, cntres), fail);

            return(true);
        }
        public static ContinueToCallAgent Instantiate(CallAgent agent, Context context, IContinuation succ, IFailure fail)
        {
            ContinueToCallAgent continuer = new ContinueToCallAgent(agent, succ);
            continuer.SetResult(new TwoTuple<Context, IFailure>(context, fail), context.Weight, "ContinueToCallAgent: Instantiate");

            return continuer;
        }
Пример #5
0
 /// <summary>
 /// Add a rule that target Capability shall be failed in case of a NOK monitoring result
 /// </summary>
 /// <param name="degrader">Degrader being used to add the rule</param>
 /// <param name="failure"></param>
 /// <param name="targetCapability"></param>
 public static void AddRuleForFailure(
     this IDegrader degrader,
     IFailure failure,
     ICapability targetCapability)
 {
     degrader.AddRule(failure, MonitoringResult.NOK, targetCapability, Capabilities.Failed);
 }
Пример #6
0
        public PatternMatch Match(AmbiguousPhrase phrase, IContinuation succ, IFailure fail)
        {
            //IArena arena = new QueueArena();
            //arena.Call();

            return null;
        }
Пример #7
0
 public CallableAsEvaluable(ICallable callable, object value, IContinuation succ, IFailure fail)
 {
     this.callable = callable;
     this.value    = value;
     this.succ     = succ;
     this.fail     = fail;
 }
        public override bool Produce(Context context, IContinuation succ, IFailure fail)
        {
            string word = StarUtilities.ProducedCode(context, tagger, parser);
            Datum  datum;

            if (word == "past")
            {
                datum = new Datum(null, Relations.Relation.Tense, memory.past, context.Weight);
            }
            else if (word.Contains(" "))
            {
                datum = new Datum(null, Relations.Relation.Tense, memory.NewConcept(word, Concept.Kind.Entity), context.Weight);
            }
            else
            {
                bool isPast = verbs.GetInflection(word) == Verbs.Convert.ext_Ved;
                if (isPast)
                {
                    datum = new Datum(null, Relations.Relation.Tense, memory.past, context.Weight);
                }
                else
                {
                    datum = new Datum(null, Relations.Relation.Tense, memory.now, context.Weight);
                }
            }

            context.LookupAndAdd <List <Datum> >("$knowPartials", new List <Datum>()).Add(datum);

            succ.Continue(new Context(context, new List <IContent>()), fail);
            return(true);
        }
        public override bool Call(object value, IContinuation succ, IFailure fail)
        {
            Context context = (Context) value;
            if (principleSource == null || assertionSource == null) {
                fail.Fail("ConceptNet sources missing", succ);
                return true;
            }

            Notion concept;
            if (!principleSource.TryGetValue(StarUtilities.ContentsCode(context, tagger, parser), out concept))
            {
                fail.Fail("Could not find produced in ConceptNet", succ);
                return true;
            }

            List<Assertion> assertions;
            if (!assertionSource.TryGetValue(new KeyValuePair<Notion, string>(concept, relation), out assertions))
                assertions = new List<Assertion>();

            List<IContent> contents = new List<IContent>();

            foreach (Assertion assertion in assertions)
            {
                contents.Add(new Word(assertion.Sentence));
                contents.Add(new Word(" ."));
            }

            succ.Continue(new Context(context, contents), fail);
            return true;
        }
Пример #10
0
 public CallableAsEvaluable(ICallable callable, object value, IContinuation succ, IFailure fail)
 {
     this.callable = callable;
     this.value = value;
     this.succ = succ;
     this.fail = fail;
 }
        public override bool CallRescue(Coderack coderack, IParsedPhrase input, PatternTemplateSource patternTemplateSource, string reason, IContinuation skip, IContinuation succ, IFailure fail)
        {
            List <string> words = GroupPhrase.PhraseToTexts(input);

            bool          changed   = false;
            List <string> corrected = new List <string>();

            foreach (string word in words)
            {
                string correct = comparer.GetCorrects(word)[0];
                if (correct.ToLower() != word.ToLower())
                {
                    changed = true;
                }
                corrected.Add(correct);
            }

            if (changed)
            {
                IParsedPhrase correct  = parser.Parse(StringUtilities.JoinWords(corrected));
                IFailure      fallfail = fallback.MakeFailure(input, patternTemplateSource, succ, fail, coderack);
                patternTemplateSource.Generate(coderack, correct, succ, fallfail, weight);
                return(true);
            }
            else
            {
                return(fallback.CallRescue(coderack, input, patternTemplateSource, reason, skip, succ, fail));
            }
        }
 public ContinueCodelet(double salience, Context context, IContinuation succ, IFailure fail)
     : base(context.Coderack, salience, 4 * 4, 5)
 {
     this.context = context;
     this.succ    = succ;
     this.fail    = fail;
 }
Пример #13
0
        /// <summary>
        /// Updates the monitoring result of a failure, including all the degradation which will be updated
        /// </summary>
        /// <param name="failure">Failure which is changed</param>
        /// <param name="monitoringResult">Requests an update of the failure</param>
        public void UpdateMonitoringResult(IFailure failure, MonitoringResult monitoringResult)
        {
            // Checks, if the failure has changed
            MonitoringResult oldResult;

            if (_failureStatus.TryGetValue(failure, out oldResult))
            {
                if (oldResult == monitoringResult)
                {
                    // No change of failure... so just return
                    return;
                }
            }

            _failureStatus[failure] = monitoringResult;

            // Go through all rulesets where the capability is dependent on the failure
            var alreadyUpdated = new HashSet <ICapability>();

            foreach (var ruleSet in _rules.Values)
            {
                UpdateDegradation(ruleSet.Capability, alreadyUpdated);

                /*
                 * foreach (var rule in ruleSet.Rules
                 *  .OfType<FailureRule>()
                 *  .Where(x=> x.Failure.Equals(failure)))
                 * {
                 *  if (rule.Failure.Equals(failure))
                 *  {
                 *      UpdateDegradation(ruleSet.Capability, alreadyUpdated);
                 *  }
                 * }*/
            }
        }
        public override bool Call(object value, IContinuation succ, IFailure fail)
        {
            if (breakpointCall)
                Console.WriteLine("Breakpoint in MatchProduceAgent");
            Context context = (Context) value;
            bool production = context.LookupDefaulted<bool>("$production", false);
            if (!production)
            {
                object check = context.LookupDefaulted<object>("$check", null);

                if (check == null)
                {
                    // Matcher did not call us
                    List<IContent> contents = new List<IContent>();
                    Context child = new Context(context, contents);
                    // Put us into content stream, for matcher to find
                    contents.Add(new Value(this));
                    // Save this context-- we'll use it later!
                    child.Map["$argctx"] = context;

                    succ.Continue(child, fail);
                    return true;
                }

                Context argctx = context.LookupDefaulted<Context>("$argctx", context);
                // Add our context, shadowing variables in argctx
                Context argctxchild = argctx.ChildRange(0);
                argctxchild.AddMappings(context);

                return Match(check, argctxchild, succ, fail);
            }
            else
                return Produce(context, succ, fail);
        }
        public PatternMatch Match(AmbiguousPhrase phrase, IContinuation succ, IFailure fail)
        {
            //IArena arena = new QueueArena();
            //arena.Call();

            return(null);
        }
        public int Call(object value, IContinuation succ, IFailure fail)
        {
            if (aborter.IsAborted)
                return 1;   // abort!

            List<IAction> namedacts = plugenv.GetNamedActions(resultType.Name);
            // Remove all actions that have already been used
            int ii = 0;
            while (ii < namedacts.Count)
            {
                if (searched.ContainsKey(namedacts[ii]))
                    namedacts.RemoveAt(ii);
                else
                {
                    searched.Add(namedacts[ii], 1);
                    ii++;
                }
            }

            if (namedacts.Count == 0)
                return arena.Fail(fail, salience, "no matching acts", succ);

            IContinuation next = new ContinueletWrapper(CheckAction, value, succ);
            IFailure more = new FailletWrapper(RecurseConversionAttempt, value, namedacts, succ);

            if (namedacts.Count == 1)
                return arena.Continue(next, salience, namedacts[0], more) + 2;

            TryValues<IAction> tryeach = new TryValues<IAction>();
            return arena.Call(tryeach, salience * .9, namedacts, next, more) + 3;
        }
Пример #17
0
 /// <summary>
 /// Add a rule that target Capability shall be unknown in case of a unknown monitoring result
 /// </summary>
 /// <param name="degrader">Degrader being used to add the rule</param>
 /// <param name="failure"></param>
 /// <param name="targetCapability"></param>
 public static void AddRuleForUnknown(
     this IDegrader degrader,
     IFailure failure,
     ICapability targetCapability)
 {
     degrader.AddRule(failure, MonitoringResult.Unknown, targetCapability, Capabilities.Unknown);
 }
 public int Call(ICallable callable, double salience, object value, IContinuation succ, IFailure fail)
 {
     if (callable is IAgent)
         ((IAgent)callable).Initialize(this, salience);
     if (salience > 0)
         return callable.Call(value, succ, fail);
     return 1;
 }
Пример #19
0
 /// <summary>
 /// Adds a default rule to set the target capability to Failed or Unknown depending on the failure.
 /// NOK will be mapped to Failed, Unknown will be mapped to Unknown
 /// If additional relationships need to be established, further explicit calls are necessary
 /// </summary>
 /// <param name="degrader">Degrader to be used for the rule</param>
 /// <param name="failure">The falilue whose change will have an effect on the <c>targetCapability</c></param>
 /// <param name="targetCapability">The targetcapability being used</param>
 public static void AddDefaultRules(
     this IDegrader degrader,
     IFailure failure,
     ICapability targetCapability)
 {
     AddRuleForFailure(degrader, failure, targetCapability);
     AddRuleForUnknown(degrader, failure, targetCapability);
 }
Пример #20
0
        /// <summary>
        /// This method can be called by the inherited methods which define a specific failure
        /// </summary>
        /// <param name="failure">Failure, whose status shall be updated</param>
        /// <param name="result">The monitoring result of the failure</param>
        protected void ReportMonitoringResult(IFailure failure, MonitoringResult result)
        {
            if (Degrader == null)
            {
                throw new InvalidOperationException("Degrader is not set");
            }

            Degrader.UpdateMonitoringResult(failure, result);
        }
        public override bool Match(object check, Context context, IContinuation succ, IFailure fail)
        {
            List<Relations.Relation> kinds = new List<Relations.Relation>();
            kinds.Add(Relations.Relation.AtTime);

            Thinker.SearchForMatch(salience, memory, kinds, (Datum) check, context, succ, fail);

            return true;
        }
        public static bool PrintContents(Context context, IContinuation succ, IFailure fail, params object[] args)
        {
            PluginEnvironment plugenv = (PluginEnvironment) args[0];
            POSTagger tagger = new POSTagger(plugenv);
            GrammarParser parser = new GrammarParser(plugenv);

            Console.WriteLine(StarUtilities.ProducedCode(context, tagger, parser));
            succ.Continue(new Context(context, new List<IContent>()), fail);
            return true;
        }
 public int Fail(IFailure fail, double salience, string reason, IContinuation skip)
 {
     // Clone it!
     fail = (IFailure)fail.Clone();
     if (fail is IAgent)
         ((IAgent)fail).Initialize(this, salience);
     if (salience > 0)
         return fail.Fail(reason, skip);
     return 1;
 }
 public int Continue(IContinuation cont, double salience, object value, IFailure fail)
 {
     // Clone it!
     cont = (IContinuation)cont.Clone();
     if (cont is IAgent)
         ((IAgent)cont).Initialize(this, salience);
     if (salience > 0)
         return cont.Continue(value, fail);
     return 1;
 }
Пример #25
0
        public static bool PrintContents(Context context, IContinuation succ, IFailure fail, params object[] args)
        {
            PluginEnvironment plugenv = (PluginEnvironment)args[0];
            POSTagger         tagger  = new POSTagger(plugenv);
            GrammarParser     parser  = new GrammarParser(plugenv);

            Console.WriteLine(StarUtilities.ProducedCode(context, tagger, parser));
            succ.Continue(new Context(context, new List <IContent>()), fail);
            return(true);
        }
        public override bool Produce(Context context, IContinuation succ, IFailure fail)
        {
            object var = context.LookupDefaulted<object>("$p$" + name, null);

            if (var is IParsedPhrase)
                succ.Continue((IParsedPhrase)var, fail);

            succ.Continue(null, fail);

            return true;
        }
Пример #27
0
        bool FailToTryToRescue(IArena arena, double salience, string reason, IContinuation skip, params object[] args)
        {
            TryToRescueMatch      tryToRescueMatch      = (TryToRescueMatch)args[0];
            IParsedPhrase         input                 = (IParsedPhrase)args[1];
            PatternTemplateSource patternTemplateSource = (PatternTemplateSource)args[2];
            IContinuation         succ = (IContinuation)args[3];
            IFailure fail     = (IFailure)args[4];
            Coderack coderack = (Coderack)args[5];

            return(tryToRescueMatch.CallRescue(coderack, input, patternTemplateSource, reason, skip, succ, fail));
        }
Пример #28
0
        public static bool EvaluateDefinition(Context context, IContinuation succ, IFailure fail, params object[] args)
        {
            double  salience   = (double)args[0];
            Context definition = (Context)args[1];

            Evaluator eval = new Evaluator(salience, ArgumentMode.ManyArguments, succ, new NopCallable(), true);

            eval.Continue(definition, fail);

            return(true);
        }
            public bool Continue(object value, IFailure fail)
            {
                if (parent.salience <= salience)
                {
                    parent.salience = salience;
                    parent.value    = value;
                    parent.fail     = fail;
                }

                return(true);
            }
 public bool Call(object value, IContinuation succ, IFailure fail)
 {
     try
     {
         object results = method.Invoke(obj, new object[] { value });
         return(arena.Continue(succ, salience, results, fail));
     }
     catch (Exception ex)
     {
         return(arena.Fail(fail, salience, ex.Message, succ));
     }
 }
 public override int Call(object value, IContinuation succ, IFailure fail)
 {
     try
     {
         object results = Handle(value);
         return time + arena.Continue(succ, salience, results, fail);
     }
     catch (Exception ex)
     {
         return time + 2 + arena.Fail(fail, salience, ex.Message, succ);
     }
 }
 public override bool Call(object value, IContinuation succ, IFailure fail)
 {
     try
     {
         object results = Handle(value);
         return(arena.Continue(succ, salience, results, fail));
     }
     catch (Exception ex)
     {
         return(arena.Fail(fail, salience, ex.Message, succ));
     }
 }
        public override bool Produce(Context context, IContinuation succ, IFailure fail)
        {
            object var = context.LookupDefaulted <object>("$p$" + name, null);

            if (var is IParsedPhrase)
            {
                succ.Continue((IParsedPhrase)var, fail);
            }

            succ.Continue(null, fail);

            return(true);
        }
        public override bool Produce(Context context, IContinuation succ, IFailure fail)
        {
            // Evaluate all children
            ContinueToCallAgent cont = CallAgentWrapper.MakeContinuation(ConstructSentence, succ, 100.0, 10, 10);

            ContinuationAppender appender = new ContinuationAppender(context, cont);

            Evaluator eval = new Evaluator(salience, ArgumentMode.ManyArguments, appender.AsIndex(0), appender.AsIndex(1), true);

            eval.Continue(context, fail);

            return(true);
        }
        public override bool Produce(Context context, IContinuation succ, IFailure fail)
        {
            Concept concept = CompletePartials(context);

            if (concept == null)
            {
                fail.Fail("Nothing to complete partials", succ);
                return(true);
            }

            succ.Continue(new Context(context, new List <IContent>()), fail);
            return(true);
        }
Пример #36
0
        public void AggregateFailureConstructor_FailuresToAggregate_ShouldReturnAggregateFailureWithAggregatedFailure()
        {
            // ARRANGE
            var baseFailure        = new FailureWithMessage("Base failure");
            var failureToAggregate = new FailureWithMessage("Failure to aggregate");
            var expectedFailures   = new IFailure[] { baseFailure, failureToAggregate };

            // ACT
            var aggregatedFailure = new AggregateFailure(new[] { baseFailure, failureToAggregate });

            // ASSERT
            aggregatedFailure.Failures.Should().BeEquivalentTo(expectedFailures.AsEnumerable());
        }
        public override bool Produce(Context context, IContinuation succ, IFailure fail)
        {
            IParsedPhrase phrase = StarUtilities.ProducedPhrase(context, tagger, parser);
            if (phrase == null)
            {
                succ.Continue(new Context(context, new List<IContent>()), fail);
                return true; // cannot do!
            }

            KnowPhrase(phrase, context, memory);

            succ.Continue(new Context(context, new List<IContent>()), fail);
            return true;
        }
        public bool ConstructSentence(Context context, IContinuation succ, IFailure fail, params object[] args)
        {
            // Need to produce all my contents!
            IParsedPhrase phrase = StarUtilities.ProducedPhrase(context, tagger, parser);

            if (phrase == null)
            {
                // oops, we failed to produce
                fail.Fail("Context could not be produced", succ);
                return(true);
            }

            if (!(phrase.Part == "=P"))
            {
                if (phrase.Part == "FRAG" || phrase.Part == "S" || phrase.Part == "SBARQ")
                {
                    if (final != null)
                    {
                        GroupPhrase   groupPhrase = new GroupPhrase(phrase);
                        IParsedPhrase last        = groupPhrase.GetBranch(groupPhrase.Count - 1);
                        if (!(last.Part == "." || last.Part == "!" || last.Part == "?"))
                        {
                            List <IParsedPhrase> branches = new List <IParsedPhrase>();
                            branches.AddRange(phrase.Branches);
                            branches.Add((IParsedPhrase)final.Clone());
                            phrase = new GroupPhrase(phrase.Part, branches);
                        }
                    }
                }
                else
                {
                    List <IParsedPhrase> branches = new List <IParsedPhrase>();
                    branches.Add(phrase);
                    if (final != null)
                    {
                        branches.Add((IParsedPhrase)final.Clone());
                    }
                    phrase = new GroupPhrase("FRAG", branches);
                }
            }

            List <IContent> contents = new List <IContent>();

            contents.Add(new Word(phrase.Text));
            Context child = new Context(context, contents);

            succ.Continue(child, fail);

            return(true);
        }
Пример #39
0
        public bool Continue(object value, IFailure fail)
        {
            Context context = (Context)value;

            if (!context.IsEmpty)
            {
                Console.WriteLine(context.ContentsCode());
            }

            // update context
            basectx = context;

            return(true);
        }
 public bool Fail(IFailure fail, double salience, string reason, IContinuation skip)
 {
     // Clone it!
     fail = (IFailure)fail.Clone();
     if (fail is IAgent)
     {
         ((IAgent)fail).Initialize(this, salience);
     }
     if (salience > 0)
     {
         return(fail.Fail(reason, skip));
     }
     return(true);
 }
 public bool Continue(IContinuation cont, double salience, object value, IFailure fail)
 {
     // Clone it!
     cont = (IContinuation)cont.Clone();
     if (cont is IAgent)
     {
         ((IAgent)cont).Initialize(this, salience);
     }
     if (salience > 0)
     {
         return(cont.Continue(value, fail));
     }
     return(true);
 }
        public static bool DefineInNoArgRule(Context context, IContinuation succ, IFailure fail, params object[] args)
        {
            double salience = (double) args[0];

            List<IContent> contents = context.Contents;
            string name = contents[0].Name;

            Context definition = context.ChildRange(1);
            context.Map.Add(name, new CallAgentWrapper(EvaluateDefinition, ArgumentMode.NoArugments, salience, definition.Size, 10, salience, definition));

            Context empty = new Context(context, new List<IContent>());
            succ.Continue(empty, fail);

            return true;
        }
        public void NextSentence(Context context, IContinuation succ, IFailure fail, params object[] args)
        {
            int?sentenceStart = context.LookupDefaulted <int?>("$sentences.index", null);

            TwoTuple <List <IContent>, IContinuation> parts = SplitArguments(context, succ);
            List <IContent> chunk = parts.one;

            Context first = new Context(context, chunk);

            first.Map["$sentences.index"] = sentenceStart + 1;

            GroupPhrase groupPhrase = new GroupPhrase((IParsedPhrase)context.Lookup("$sentences.check"));

            Matcher.MatchAgainst(salience, first, groupPhrase.GetBranch(sentenceStart.Value), new List <IParsedPhrase>(), parts.two, fail);
        }
Пример #44
0
        // This will call success either way, but only propogate if context is empty
        public bool PropogateOnClear(Context context, IContinuation succ, IFailure fail, params object[] args)
        {
            if (context.IsEmpty || (context.Contents.Count == 1 && context.Contents[0].Name.StartsWith("*")))
            {
                string name  = (string)args[0];
                object check = args[1];

                Variable dummy = new Variable(name);
                dummy.Propogate(context, check, context.Weight);
            }

            succ.Continue(context, fail);

            return(true);
        }
        public override bool Produce(Context context, IContinuation succ, IFailure fail)
        {
            IParsedPhrase phrase = StarUtilities.ProducedPhrase(context, tagger, parser);

            if (phrase == null)
            {
                succ.Continue(new Context(context, new List <IContent>()), fail);
                return(true); // cannot do!
            }

            KnowPhrase(phrase, context, memory);

            succ.Continue(new Context(context, new List <IContent>()), fail);
            return(true);
        }
Пример #46
0
        public void Aggregate_AggregateFailureAndFailuretoAggregate_ShouldReturnAggregateFailureWithAggregatedFailures()
        {
            // ARRANGE
            var baseFailure          = new FailureWithMessage("Base failure");
            var baseAggregateFailure = new AggregateFailure(new [] { baseFailure });
            var failureToAggregate   = new FailureWithMessage("Failure to aggregate");
            var expectedFailures     = new IFailure[] { baseFailure, failureToAggregate };

            // ACT
            var aggregatedFailure = baseAggregateFailure.Aggregate(failureToAggregate);

            // ASSERT
            aggregatedFailure.Should().BeAssignableTo <IAggregateFailure>()
            .Which.Failures.Should().BeEquivalentTo(expectedFailures.AsEnumerable());
        }
Пример #47
0
        public override bool Call(object value, IContinuation succ, IFailure fail)
        {
            Context context = (Context) value;
            IContent content = context.Contents[0];
            double term = 0;
            if (content is Word && double.TryParse(content.Name, out term))
            {
                term = -term;
                Context result = new Context(context, context.Contents);
                result.Contents[0] = new Word(term.ToString());
                succ.Continue(result, fail);
            }
            else
                fail.Fail("Argument isn't number", succ);

            return true;
        }
        public override bool CallRescue(Coderack coderack, IParsedPhrase input, PatternTemplateSource patternTemplateSource, string reason, IContinuation skip, IContinuation succ, IFailure fail)
        {
            List<string> words = GroupPhrase.PhraseToTexts(input);

            bool changed = false;
            List<string> corrected = new List<string>();
            foreach (string word in words) {
                string correct = comparer.GetCorrects(word)[0];
                if (correct.ToLower() != word.ToLower())
                    changed = true;
                corrected.Add(correct);
            }

            if (changed) {
                IParsedPhrase correct = parser.Parse(StringUtilities.JoinWords(corrected));
                IFailure fallfail = fallback.MakeFailure(input, patternTemplateSource, succ, fail, coderack);
                patternTemplateSource.Generate(coderack, correct, succ, fallfail, weight);
                return true;
            } else
                return fallback.CallRescue(coderack, input, patternTemplateSource, reason, skip, succ, fail);
        }
        public int CheckAction(IArena arena, double salience, object value, IFailure fail, params object[] args)
        {
            // params: object oldval, IContinuation succ
            if (aborter.IsAborted)
                return 1;   // abort!

            ArgumentTree argtree = new ArgumentTree(args[0]);
            IContinuation succ = (IContinuation)args[1];
            IAction action = (IAction)value;

            ArgumentTree result = action.Input.IsValid(argtree);
            if (result == null)
            {
                // abort the search-- we found an appropriate action!
                aborter.Abort();

                return arena.Call(action, salience, args[0], succ, fail);
            }
            else
                return arena.Fail(fail, salience, "input type doesn't match", succ);
        }
        public static bool DefinePhraseChoiceVariable(Context context, IContinuation succ, IFailure fail, params object[] args)
        {
            List<IContent> contents = context.Contents;
            string name = contents[0].Name;
            PluginEnvironment plugenv = (PluginEnvironment) args[0];

            List<List<string>> options = new List<List<string>>();
            List<string> curropt = new List<string>();
            for (int ii = 1; ii < contents.Count; ii++) {
                if (contents[ii] == Special.ArgDelimSpecial) {
                    options.Add(curropt);
                    curropt = new List<string>();
                } else
                    curropt.Add(contents[ii].Name.ToLower());
            }
            options.Add(curropt);

            context.Map.Add(name, new PhraseChoiceVariable(name, options, plugenv, (WordComparer) context.LookupSimple("$Compare")));

            Context empty = new Context(context, new List<IContent>());
            succ.Continue(empty, fail);

            return true;
        }
        public override bool Match(object check, Context context, IContinuation succ, IFailure fail)
        {
            if (!(check is IParsedPhrase)) {
                fail.Fail("Cannot match a " + check.GetType(), succ);
                return true;
            }

            // Set up main check
            IParsedPhrase full = (IParsedPhrase) check;

            GroupPhrase sofar = context.LookupDefaulted<GroupPhrase>("$active$" + name, null);
            if (sofar != null)
                full = sofar.AddBranch(full);

            bool? isMatch = IsMatch(full);

            if (!isMatch.HasValue) {
                List<IContent> contents = new List<IContent>();
                contents.Add(new Value(this));
                Context tryagain = new Context(context, contents);
                tryagain.Map["$active$" + name] = new GroupPhrase(full);
                // Continue with same context
                succ.Continue(tryagain, fail);
            } else {
                if (isMatch.Value) {
                    Propogate(context, full, 1.0);
                    context.Map[StarUtilities.NextStarName(context, name)] = full.Text;

                    succ.Continue(context.ChildRange(1), fail);
                } else {
                    fail.Fail("Does not match " + full.Text, succ);
                }
            }

            return true;
        }
Пример #52
0
        public override bool Call(object value, IContinuation succ, IFailure fail)
        {
            Context context = (Context) value;

            double result = 0;

            foreach (IContent content in context.Contents)
            {
                double term = 0;
                if (content is Word && double.TryParse(content.Name, out term))
                    result += term;
                else
                {
                    fail.Fail("Argument isn't number", succ);
                    return true;
                }
            }

            List<IContent> cntres = new List<IContent>();
            cntres.Add(new Word(result.ToString()));
            succ.Continue(new Context(context, cntres), fail);

            return true;
        }
Пример #53
0
 public bool Fail(IFailure fail, double salience, string reason, IContinuation skip)
 {
     AddCodelet(new CodeletEvaluableWrapper(new FailureAsEvaluable(fail, reason, skip), this, salience, 1, 1), "Coderack Fail");
     return true;
 }
Пример #54
0
 public bool Continue(IContinuation cont, double salience, object value, IFailure fail)
 {
     AddCodelet(new CodeletEvaluableWrapper(new ContinuationAsEvaluable(cont, value, fail), this, salience, 1, 1), "Continue");
     return true;
 }
Пример #55
0
 public bool Call(ICallable callable, double salience, object value, IContinuation succ, IFailure fail)
 {
     AddCodelet(new CodeletEvaluableWrapper(new CallableAsEvaluable(callable, value, succ, fail), this, salience, 1, 1), "Call");
     return true;
 }
Пример #56
0
 public bool Continue(object value, IFailure fail)
 {
     return true;
 }
Пример #57
0
 public bool Call(object value, IContinuation succ, IFailure fail)
 {
     return true;
 }
Пример #58
0
 public FailureAsEvaluable(IFailure fail, string reason, IContinuation skip)
 {
     this.fail = fail;
     this.reason = reason;
     this.skip = skip;
 }
Пример #59
0
        public bool Continue(object value, IFailure fail)
        {
            Context context = (Context) value;
            if (!context.IsEmpty)
                Console.WriteLine(context.ContentsCode());

            // update context
            basectx = context;

            return true;
        }
 public int Call(object value, IContinuation succ, IFailure fail)
 {
     try
     {
         object results = method.Invoke(obj, new object[] { value });
         return time + arena.Continue(succ, salience, results, fail);
     }
     catch (Exception ex)
     {
         return time + 2 + arena.Fail(fail, salience, ex.Message, succ);
     }
 }