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 () }; }
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); }
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(); }
public List<object> ReadTerms() { List<object> terms = new List<object>(); object term; while ((term = ReadTerm()) != Symbol.EndOfFile) terms.Add(term); return terms; }
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); } }
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; }
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 bool FindAll(WamMachine machine, WamReferenceTarget[] arguments) { Debug.Assert(arguments.Length == 3); var arg0 = arguments[0].Dereference(); var arg1 = arguments[1].Dereference(); var arg2 = arguments[2].Dereference(); var variable = arg0 as WamVariable; if (variable == null) { return false; } var goal = arg1 as WamCompoundTerm; if (goal == null) { return false; } var result = arg2 as WamVariable; if (result == null) { return false; } var builder = new WamInstructionStreamBuilder(); builder.Write(new WamInstruction(WamInstructionOpCodes.Allocate)); for (var idx = 0; idx < goal.Functor.Arity; ++idx) { builder.Write(new WamInstruction( WamInstructionOpCodes.PutValue, goal.Children[idx], new WamInstructionRegister(WamInstructionRegisterTypes.Argument, (byte)idx))); } builder.Write(new WamInstruction(WamInstructionOpCodes.Call, goal.Functor)); builder.Write(new WamInstruction(WamInstructionOpCodes.Success)); machine.PushContext(builder.ToInstructionStream()); var values = new List<WamReferenceTarget>(); try { var results = machine.RunToSuccess(); while (results == ExecutionResults.Success) { var value = variable.Clone(); values.Add(value); results = machine.RunToSuccess(); } } finally { machine.PopContext(true); } // Unbind the variable from the last results found by the goal. // variable.Unbind(); // Unify the output variable with the list of values. // return machine.Unify(result, WamReferenceTarget.Create(values)); }
protected override CodeTerm GetCodeTermBase(WamDeferenceTypes dereferenceType, WamReferenceTargetMapping mapping) { if (Functor == Functor.ListFunctor) { var head = new List<CodeTerm>(); CodeTerm tail = null; var codeTermHead = Children[0].GetCodeTerm(dereferenceType, mapping); var codeTermTail = Children[1].GetCodeTerm(dereferenceType, mapping); head.Add(codeTermHead); if (codeTermTail.IsCodeList) { head.AddRange(codeTermTail.AsCodeList.Head); tail = codeTermTail.AsCodeList.Tail; } else { tail = codeTermTail; } return new CodeList(head, tail); } if (Functor.Arity == 0) { return new CodeCompoundTerm(new CodeFunctor(Functor.Name)); } var children = new List<CodeTerm>(); foreach (var child in Children) { children.Add(child.GetCodeTerm(dereferenceType, mapping)); } return new CodeCompoundTerm(new CodeFunctor(Functor.Name, Functor.Arity), children); }
public List<string> VariableWithName(string name) { List<string> returnValue = new List<string>(); foreach (Dictionary<string,string> result in vars) { returnValue.Add(result[name]); } return returnValue; }