public static object CreateInstance(this Type type, List<object> constructorArguments) { if (type == null) throw new ArgumentNullException("type"); if (constructorArguments == null) throw new ArgumentNullException("constructorArguments"); return type.CreateInstance(constructorArguments.ToArray()); }
/// <summary> /// Creates a blank DB entry for the specified functor /// </summary> public PredicateInfo(Symbol functorName, int arity, KnowledgeBase kb) { Name = functorName; Arity = arity; Entries = new List<KnowledgeBaseEntry>(); KnowledgeBase = kb; }
public ArrayVariable(string name, TermArray ta, ListTerm subscripts) { this.ta = ta; this.name = ta.Name; this.subscripts = subscripts.ArgumentsToArrayList (); if (this.subscripts.Count != ta.Rank) IO.Error ("Wrong number of subscripts for '{0}': expected {1}, got {2}", name, ta.Rank, this.subscripts.Count); }
/// <summary> /// Creates a PrologContext that can for at most the specified number of steps. /// </summary> public PrologContext(KnowledgeBase kb, int stepLimit) { StepsRemaining = stepLimit; goalStack = new List<GoalStackFrame>(); goalStackCurrentRules = new List<KnowledgeBaseEntry>(); GoalStackDepth = 0; KnowledgeBase = kb; traceVariables = new LogicVariable[256]; traceValues = new object[256]; tracePointer = 0; IndexicalBindingStack = new List<KeyValuePair<Symbol, object>>(); }
private static AST.Program ConvertToAst(Runtime.ISolutionTreeNode unnamed_top_node) { var clause_nodes = ParsePossiblyEmptyList (unnamed_top_node ["run"] ["program"], "clause_list", "clause"); var dcgClauses = new List <AST.DcgClause> (); var prologClauses = new List <AST.Clause> (); foreach (var clause_node in clause_nodes) { var dgc_clause_node = clause_node ["dcg_clause"]; if (dgc_clause_node != null) { var head = GoalToAst (dgc_clause_node ["dcg_head"] ["goal"]); var dcgClause = new AST.DcgClause { Head = new AST.Goal { PredicateName = head.PredicateName, Arguments = head.Arguments }, Body = ParsePossiblyEmptyList (dgc_clause_node ["dcg_body"], "dcg_goal_list", "dcg_goal").Select (DcgGoalToAst).ToArray () }; dcgClauses.Add (dcgClause); } else { var prolog_clause_node = clause_node ["prolog_clause"]; if (prolog_clause_node != null) { var prologClause = new AST.Clause { Head = GoalToAst (prolog_clause_node ["head"] ["goal"]), Body = ParsePossiblyEmptyList (prolog_clause_node ["body"], "goal_list", "goal").Select (GoalToAst).ToArray () }; prologClauses.Add (prologClause); } else { throw new Exception ("A 'clause' is expected to be either a 'dcg_clause' or a 'prolog_clause'."); } } } return new AST.Program { Clauses = prologClauses.ToArray (), DcgClauses = dcgClauses.ToArray () }; }
public WamChoicePoint(WamChoicePoint predecessor, WamEnvironment environment, int stackIndex, WamInstructionPointer returnInstructionPointer, IEnumerable<WamReferenceTarget> argumentRegisters, WamChoicePoint cutChoicePoint) { m_generation = s_nextGeneration++; m_predecessor = predecessor; m_environment = environment; m_stackIndex = stackIndex; m_returnInstructionPointer = returnInstructionPointer; m_argumentRegisters = new WamReferenceTargetList(argumentRegisters); m_cutChoicePoint = cutChoicePoint; m_backtrackInstructionPointer = WamInstructionPointer.Undefined; m_predicateEnumerator = null; m_trail = new List<WamVariable>(); }
public WamChoicePoint(WamChoicePoint predecessor, WamEnvironment environment, int stackIndex, WamInstructionPointer returnInstructionPointer, IEnumerable<WamReferenceTarget> argumentRegisters, WamChoicePoint cutChoicePoint) { Generation = NextGeneration++; Predecessor = predecessor; Environment = environment; StackIndex = stackIndex; ReturnInstructionPointer = returnInstructionPointer; ArgumentRegisters = new WamReferenceTargetList(argumentRegisters); CutChoicePoint = cutChoicePoint; BacktrackInstructionPointer = WamInstructionPointer.Undefined; PredicateEnumerator = null; Trail = new List<WamVariable>(); }
/// <summary> /// Creates a KnowledgedBaseRule given a Term object for a :- expression. /// </summary> public static KnowledgeBaseRule FromTerm(Structure structure, bool checkSingletons, string source, int line) { if (structure == null) throw new ArgumentNullException("structure"); if (structure.IsFunctor(Symbol.Implication, 2)) { var body = new List<Structure>(); UnwindCommaExpression(structure.Argument(1), body); if (structure.Argument(0) == null) throw new ArgumentException("head of rule is null"); Structure head = Term.Structurify(structure.Argument(0), "Head of :- must be a valid proposition or predicate."); if (head == null) throw new ArgumentException("Head of rule is not a term."); return MakeRule(head, body, checkSingletons, source, line); } return MakeRule(structure, null, checkSingletons, source, line); }
internal static void UnwindCommaExpression(object subgoal, List<Structure> body) { if (subgoal == null) throw new ArgumentNullException("subgoal", "Subgoal of rule is null"); Structure structure; if (subgoal is LogicVariable) structure = new Structure(Symbol.Call, subgoal); else structure = Term.Structurify(subgoal, "Not a valid subgoal."); if (structure.IsFunctor(Symbol.Comma, 2)) { UnwindCommaExpression(structure.Argument(0), body); UnwindCommaExpression(structure.Argument(1), body); } else body.Add(structure); }
/// <summary> /// Fills in fields given head and body terms. /// </summary> protected KnowledgeBaseRule(Structure ruleHead, Structure[] ruleBody, bool checkSingletons, string source, int line) { SourceFile = source; SourceLineNumber = line; head = ruleHead; if (ruleHead == null) throw new ArgumentNullException("ruleHead"); HeadArgs = ruleHead.Arguments; headIndexers = PredicateArgumentIndexer.ArglistIndexers(HeadArgs); BodyGoals = ruleBody; FreeVariables = new List<LogicVariable>(); var singletons = new List<LogicVariable>(); foreach (var a in HeadArgs) FindVariables(a, singletons); foreach (var g in BodyGoals) FindVariables(g, singletons); if (checkSingletons && singletons.Count > 0) { foreach (var v in singletons) PrintWarning("singleton variable: {0}", v.Name); } Functor = ruleHead.Functor; }
static KnowledgeBaseRule MakeRule(Structure head, List<Structure> body, bool checkSingletons, string source, int line) { if (body == null) return new KnowledgeBaseRule0(head, new Structure[0], checkSingletons, source, line); switch (body.Count) { case 0: return new KnowledgeBaseRule0(head, body.ToArray(), checkSingletons, source, line); case 1: return new KnowledgeBaseRule1(head, body.ToArray(), checkSingletons, source, line); case 2: return new KnowledgeBaseRule2(head, body.ToArray(), checkSingletons, source, line); case 3: return new KnowledgeBaseRule3(head, body.ToArray(), checkSingletons, source, line); case 4: return new KnowledgeBaseRule4(head, body.ToArray(), checkSingletons, source, line); case 5: return new KnowledgeBaseRule5(head, body.ToArray(), checkSingletons, source, line); case 6: return new KnowledgeBaseRule6(head, body.ToArray(), checkSingletons, source, line); case 7: return new KnowledgeBaseRule7(head, body.ToArray(), checkSingletons, source, line); case 8: return new KnowledgeBaseRule8(head, body.ToArray(), checkSingletons, source, line); default: throw new ArgumentException(string.Format("Rules with {0} clauses are not supported.", body.Count)); } }
private List<string> MakeRow(object row) { //Debug.Log("Making row "+ISOPrologWriter.WriteToString(row)); var rowData = new List<string>(); int column = 0; foreach (var columnData in Prolog.PrologListItems(row)) { //Debug.Log("Making column " + ISOPrologWriter.WriteToString(columnData)); var data = MakeColumn(columnData); rowData.Add(data); ReserveColumnWidth(column, data); column++; } return rowData; }
private static IEnumerable<CutState> DeclareHigherOrderImplementation(object[] args, PrologContext context) { if (args.Length != 1) throw new ArgumentCountException("higher_order", args, "*predicate"); var predicate = Term.Deref(args[0]) as Structure; if (predicate == null) throw new ArgumentTypeException("higher_order", "predicate", args[0], typeof(Structure)); var higherOrderArguments = new List<int>(); for (int argumentIndex=0; argumentIndex<predicate.Arity; argumentIndex++) { int indicator = Convert.ToInt32(predicate.Argument(argumentIndex)); if (indicator > 0) higherOrderArguments.Add(argumentIndex); } context.KnowledgeBase.DeclareHigherOrderArguments(predicate.PredicateIndicator, higherOrderArguments.ToArray()); yield return CutState.Continue; }
private static List<object> SolutionList(PrologContext context, object template, object goal, int maxSolutions, bool deleteDuplicates) { var bag = new List<object>(); #pragma warning disable 414, 168, 219 // ReSharper disable UnusedVariable foreach (var ignore in context.Prove(goal, "goal argument to findall must be a valid Prolog goal.")) // ReSharper restore UnusedVariable #pragma warning restore 414, 168, 219 { object instance = Term.CopyInstantiation(template); bag.Add(instance); if (--maxSolutions <= 0) break; } if (deleteDuplicates) Term.Sort(bag, true); return bag; }
/// <summary> /// All we have to do here is check whether this is one of the variables we're looking for. /// </summary> public override object AlphaConvert(List<LogicVariable> oldVars, LogicVariable[] newVars, PrologContext context, bool evalIndexicals) { var index = oldVars.IndexOf(this); if (index < 0) return this; return newVars[index] ?? (newVars[index] = new LogicVariable(this.Name)); }
public static object CreateInstanceWithInitializerKeywords(this Type type, List<object> constructorArguments) { if (type == null) throw new ArgumentNullException("type"); if (constructorArguments == null) throw new ArgumentNullException("constructorArguments"); var constructorArgs = new List<object>(); // Everything up to the first keyword is a constructor arg int i; for (i = 0; i < constructorArguments.Count; i++) { var s = constructorArguments[i] as Symbol; if (s != null && s.IsKeyword) break; constructorArgs.Add(constructorArguments[i]); } if (((constructorArguments.Count - i) & 1) != 0) throw new ArgumentException("Odd number of initializer arguments provided"); object o = type.CreateInstance(constructorArgs); for (; i + 1 < constructorArguments.Count; i += 2) { var name = constructorArguments[i] as Symbol; if (name == null) throw new ArgumentException("Improper initializer name: " + constructorArguments[i]); o.SetPropertyOrField(name.KeywordName, constructorArguments[i + 1]); } return o; }
public static object CreateGenericInstance(this Type genericType, Type[] genericTypeParameters, List<object> constructorArguments) { if (genericType == null) throw new ArgumentNullException("genericType"); if (genericTypeParameters == null) throw new ArgumentNullException("genericTypeParameters"); if (constructorArguments == null) throw new ArgumentNullException("constructorArguments"); return genericType.CreateGenericInstance(genericTypeParameters, constructorArguments.ToArray()); }
/// <summary> /// Substitutes occurances of newVars for all occurances of oldVars in argList. /// Returns new array, if substitutions were made, the original array if not. /// Original array is not modified /// </summary> internal static object[] AlphaConvertArglist(object[] argList, List<LogicVariable> oldVars, LogicVariable[] newVars, PrologContext context, bool evalIndexicals) { object[] newArgs = null; for (int i = 0; i < argList.Length; i++) { var term = argList[i] as AlphaConvertibleTerm; if (term != null) { object converted = term.AlphaConvert(oldVars, newVars, context, evalIndexicals); if (converted != argList[i]) { if (newArgs == null) { newArgs = new object[argList.Length]; argList.CopyTo(newArgs, 0); } newArgs[i] = converted; } } } // Return newArgs unless it turns out it was never actually allocated // (in which case none of the args had renamed vars) return newArgs ?? argList; }
static void AddBinding(LogicVariable lv, object value, ref List<LogicVariable> vars, ref List<object> values) { if (vars == null) { vars = new List<LogicVariable> { lv }; values = new List<object> { value }; } else { vars.Add(lv); values.Add(value); } }
public List<object> ReadTerms() { List<object> terms = new List<object>(); object term; while ((term = ReadTerm()) != Symbol.EndOfFile) terms.Add(term); return terms; }
/// <summary> /// Recopy the term to replace variables. If term contains no variables, no recopying is done. /// </summary> /// <param name="oldVars">Variables to be replaced</param> /// <param name="newVars">The corresponding variables that are replacing the oldVars</param> /// <param name="context">PrologContext to evaluating indexicals</param> /// <param name="evalIndexicals">If true, any indexicals will be replaced with their values.</param> /// <returns>Converted term or original term if not conversion necessary</returns> public abstract object AlphaConvert( List<LogicVariable> oldVars, LogicVariable[] newVars, PrologContext context, bool evalIndexicals);
List<KnowledgeBaseEntry> GetEntriesListForUpdate() { List<KnowledgeBaseEntry> entries = Entries; if (entriesListUsed) { entriesListUsed = false; return Entries = new List<KnowledgeBaseEntry>(entries); } return this.Entries; }
/// <summary> /// Replace self with value if evalIndexicals is true, otherwise return self unchanged. /// </summary> public override object AlphaConvert(List<LogicVariable> oldVars, LogicVariable[] newVars, PrologContext context, bool evalIndexicals) { // Temporarily ignoring evalIndexicals to try out programming here rule bodies expand indexicals, not just rule heads. //return evalIndexicals ? this.GetValue(context) : this; return this.GetValue(context); }
public override bool Unify (BaseTerm t, VarStack varStack) { if ((t = t.ChainEnd ()) is Variable) // t not unified { ((Variable)t).Bind (this); varStack.Push (t); return true; } if (t is ListPatternTerm && arity == t.Arity) // two ListPatternTerms match if their rangeTerms match { for (int i = 0; i < arity; i++) if (!args [i].Unify (t.Args [i], varStack)) return false; return true; } if (t is ListTerm) { pattern = args; // pattern is searched ... target = ((ListTerm)t).ToList (); // ... in target int ip = 0; int it = 0; return UnifyTailEx (ip, it, varStack); } return false; }
void FindVariables(object obj, List<LogicVariable> singletons) { if (obj == null) return; var v = obj as LogicVariable; if (v != null) { bool inSingletons = singletons.Contains(v); if (FreeVariables.Contains(v)) { if (inSingletons) singletons.Remove(v); } else { FreeVariables.Add(v); if (!v.Name.Name.StartsWith("_")) singletons.Add(v); } } else { var t = obj as Structure; if (t != null) foreach (var a in t.Arguments) FindVariables(a, singletons); } }
/// <summary> /// Sorts arbitrary list of Prolog terms /// </summary> public static void KeySort(List<object> terms, bool deleteDuplicates) { if (terms.Count == 0) return; terms.Sort(CompareKeys); if (deleteDuplicates) { for (int i = terms.Count - 2; i > 0; i--) if (Compare(terms[i], terms[i + 1]) == 0) terms.RemoveAt(i + 1); if (terms.Count > 1 && Compare(terms[0], terms[1]) == 0) terms.RemoveAt(1); } }
public static Object ReadAndGetFreeVariables(string exp, List<LogicVariable> variables) { ISOPrologReader r = new ISOPrologReader(exp); var term = r.ReadTerm(); variables.Clear(); variables.AddRange(r.vars); return term; }
internal static bool Unifiable(object v1, object v2, ref List<LogicVariable> vars, ref List<object> values) { v1 = CanonicalizeWithExplicitBindingList(v1, vars, values); v2 = CanonicalizeWithExplicitBindingList(v2, vars, values); if (v1 == v2) // Fast path return true; var l1 = v1 as LogicVariable; if (l1 != null) { // v1 is an unbound variable; bind it. AddBinding(l1, v2, ref vars, ref values); return true; } var l2 = v2 as LogicVariable; if (l2 != null) { // v2 is an unbound variable; bind it AddBinding(l2, v1, ref vars, ref values); return true; } // Neither is an unbound variable var s1 = v1 as Structure; var s2 = v2 as Structure; if (s1 != null && s2 != null) { // They're both structures if (s1.Functor != s2.Functor || s1.Arguments.Length != s2.Arguments.Length) return false; for (int i = 0; i < s1.Arguments.Length; i++) if (!Unifiable(s1.Arguments[i], s2.Arguments[i], ref vars, ref values)) return false; return true; } // None of the above if (v1 == null) return v2 == null; return v1.Equals(v2); }
string CaptureStack() { List<object> result = new List<object>(); if (this.TokenString != "") result.Add(this.TokenString); StackFrame s = pStack; while (s != null) { object item; switch(s.tokentype) { case EOFFILE: item = "end_of_file"; break; case OPEN_TOKEN: case OPEN_CT_TOKEN: item = '('; break; case CLOSE_TOKEN: item = ')'; break; case OPEN_LIST_TOKEN: item = '['; break; case CLOSE_LIST_TOKEN: item = ']'; break; case OPEN_CURLY_TOKEN: item = '{'; break; case CLOSE_CURLY_TOKEN: item = '}'; break; case HEAD_TAIL_SEPARATOR_TOKEN: item = '|'; break; case COMMA_TOKEN: item = ','; break; case END_TOKEN: item = '.'; break; default: item = s.term; break; } result.Insert(0, item); // okay, so this is technically quadratic, but the stack shouldn't be deep, and this only runs when syntax errors are thrown s = s.down; } StringWriter sw = new StringWriter(); ISOPrologWriter w = new ISOPrologWriter(sw); bool first = true; foreach (var t in result) { if (first) first = false; else w.WriteString(" "); w.Write(t); } return sw.ToString(); }
static object CanonicalizeWithExplicitBindingList(object value, List<LogicVariable> vars, List<object> values) { value = Deref(value); if (vars == null) return value; var lv = value as LogicVariable; while (lv != null) { int bindingPosition; if ((bindingPosition = vars.IndexOf(lv)) >= 0) { // it's aliased by the binding list value = values[bindingPosition]; lv = value as LogicVariable; } else // It's not in the binding list, so we're done. return value; } return value; }