public TermSet(Term list) { while (list.Arity == 2) { Add(list.Arg(0)); list = list.Arg(1); } }
public Term ToList() { Term t; t = Term.NULLLIST; // [] for (int i = Count - 1; i >= 0; i--) t = new Term(Parser.DOT, (Term)this[i], t, FType.comp, OType.xfy, 100); // [a1, a2, ...] return t; }
public void Insert(Term termToInsert) { int i = BinarySearch(termToInsert); if (i >= 0) // found { if (dupMode == DupMode.dupAccept) Insert(i, termToInsert); } else Insert(~i, termToInsert); }
private void ClauseSequence(TerminalSet _TS) { Monitor.Enter(PrologEngine.TermMonitor); do { ClauseNode(_TS.Union(LeftParen, Identifier, IntLiteral, RealLiteral, StringLiteral, Operator, Atom, Anonymous, CutSym, ImpliesSym, PromptSym, LSqBracket, LCuBracket, PrologString)); Monitor.Pulse(PrologEngine.TermMonitor); Monitor.Wait(PrologEngine.TermMonitor); GetSymbol(_TS.Union(LeftParen, Identifier, IntLiteral, RealLiteral, StringLiteral, Operator, Atom, Anonymous, CutSym, ImpliesSym, PromptSym, LSqBracket, LCuBracket, PrologString), false, true); } while (!(_TS.Contains(symbol.Terminal))); readTerm = new Term(EOF); Monitor.Pulse(PrologEngine.TermMonitor); Monitor.Exit(PrologEngine.TermMonitor); }
internal abstract IEnumerable<bool> UnifyWithTerm(Term term);
public bool RetractAll(Term t, VarStack varStack) // should *always* return true ????? { // remark: first-argument indexing is not affected by deleting clauses string key = t.KbKey; if (predefineds.Contains(key)) PrologIO.Error("retract of predefined predicate {0} not allowed", key); PredicateDescr pd = this[key]; if (pd == null) return true; #if persistent if (pd is PersistentPredDescr) { ((PersistentPredDescr)pd).Retract (t, varStack, null); return true; /////////////JPO persistent retract always to succeed ???? } #endif ClauseNode c = pd.GetClauseList(null, null); ClauseNode prevc = null; bool match = false; while (c != null) { Term cleanTerm = c.Term.CleanCopy(); if (cleanTerm.Unifiable(t, varStack)) // match found -- remove this term from the chain { match = true; // to indicate that at least one term was found if (prevc == null) // remove first clause { if (c.NextClause == null) // we are about to remove the last remaining clause for this predicate { predTable.Remove(key); // ... so remove its PredicateDescr as well break; } else pd.SetClauseListHead(c.NextClause); } else // not the first { prevc.NextClause = c.NextClause; prevc = c; } } else prevc = c; c = c.NextClause; } if (match) { #if arg1index pd.DestroyFirstArgIndex (); // rebuild by ResolveIndices() #endif pd.AdjustClauseListEnd(); ResolveIndices(); } return true; }
public void Assert(Term assertion, bool asserta) { assertion = assertion.CleanCopy(); // make a fresh copy Term head; TermNode body = null; if (assertion.Functor == Parser.IMPLIES) { head = assertion.Arg(0); body = assertion.Arg(1).ToGoalList(); } else head = assertion; if (head.IsVar) PrologIO.Error("Cannot assert a variable as predicate head"); string key = head.KbKey; // A predefined predicate (which may also be defined as operator) may not be redefined. // Operators ':-', ',', ';', '-->', '->' (precedence >= 1000) may also not be redefined. if (predefineds.Contains(key) || (head.Precedence >= 1000)) PrologIO.Error("assert cannot be applied to predefined predicate or system operator {0}", assertion.Index); PredicateDescr pd = (PredicateDescr)predTable[key]; #if persistent if (pd != null && pd is PersistentPredDescr) { ((PersistentPredDescr)pd).Assert (head); return; } #endif ClauseNode newC = new ClauseNode(head, body); if (pd == null) // first head { SetClauseList(PredEnum.session, head.Functor, head.Arity, newC); ResolveIndices(); } else if (asserta) // at beginning { newC.NextClause = pd.ClauseNode; // pd.ClauseNode may be null SetClauseList(PredEnum.session, head.Functor, head.Arity, newC); #if arg1index pd.CreateFirstArgIndex (); // re-create #endif } else // at end { pd.AppendToClauseList(newC); #if arg1index pd.CreateFirstArgIndex (); // re-create #endif } }
internal override IEnumerable<bool> UnifyWithTerm(Term value) { return value.UnifyWithAtomicConstant(this); }
public void Clear() { term = null; nextNode = null; nextClause = null; level = 0; }
internal override IEnumerable <bool> UnifyWithTerm(Term term) { return(UnifyWithCanonicalValue(term)); }
internal override bool UnifyWithTerm(Term term, PrologContext context) { return(UnifyWithCanonicalValue(term, context)); }
private void Render(object renderingOperation) { renderingOperation = Term.Deref(renderingOperation); if (renderingOperation == null) { return; } var op = renderingOperation as Structure; if (op != null) { switch (op.Functor.Name) { case "cons": Render(op.Argument(0)); Render(op.Argument(1)); break; case "line": foreach (var arg in op.Arguments) { Render(arg); } textBuilder.AppendLine(); break; case "color": textBuilder.AppendFormat("<color={0}>", op.Argument(0)); for (int i = 1; i < op.Arity; i++) { Render(op.Argument(i)); } textBuilder.Append("</color>"); break; case "size": textBuilder.AppendFormat("<size={0}>", op.Argument(0)); for (int i = 1; i < op.Arity; i++) { Render(op.Argument(i)); } textBuilder.Append("</size>"); break; case "bold": textBuilder.AppendFormat("<b>"); for (int i = 0; i < op.Arity; i++) { Render(op.Argument(i)); } textBuilder.Append("</b>"); break; case "italic": textBuilder.AppendFormat("<i>"); for (int i = 0; i < op.Arity; i++) { Render(op.Argument(i)); } textBuilder.Append("</i>"); break; case "term": textBuilder.Append(ISOPrologWriter.WriteToString(op.Argument(0))); break; case "table": MakeTable(op.Argument(0)); break; default: textBuilder.Append(ISOPrologWriter.WriteToString(op)); break; } } else { var str = renderingOperation as string; textBuilder.Append(str ?? ISOPrologWriter.WriteToString(renderingOperation)); } }
public void Consult(TextReader inStream) { sourceFiles.NoteFile(Prolog.CurrentSourceFile); var reader = new ISOPrologReader(inStream); reader.SkipLayout(); int lastLine = reader.LineNumber; using (var context = PrologContext.Allocate(this, this)) { try { object unexpanded; Prolog.CurrentSourceLineNumber = lastLine; while ((unexpanded = reader.ReadTerm()) != Symbol.EndOfFile) { // Perform user-level macroexpansion. object assertion = TermExpansion(unexpanded); if (ELProlog.IsELTerm(assertion)) // It's an EL term. ELProlog.Update(assertion, this); else { // It's a normal Prolog term var t = Term.Structurify( assertion, "Assertions in prolog files must be valid propositions or predicates."); // Perform built-in macroexpansion. t = t.Expand(); if (t.IsFunctor(Symbol.Implication, 1)) { context.Reset(); var goal = Term.Structurify( t.Argument(0), "Argument to a :- directive must be an atom or structure."); // Run t once, but don't backtrack for a second solution (since it's presumably an imperative anyway). Prove(goal.Functor, goal.Arguments, context, 0).GetEnumerator().MoveNext(); } else Assert(t, true, true); } reader.SkipLayout(); lastLine = reader.LineNumber; Prolog.CurrentSourceLineNumber = lastLine; } } catch (InferenceStepsExceededException e) { Repl.RecordExceptionSourceLocation(e, lastLine); throw; } catch (Exception e) { Debug.LogException(e); Repl.RecordExceptionSourceLocation(e, lastLine); throw new PrologError( e, context.StackTrace(Prolog.CurrentSourceFile, Prolog.CurrentSourceLineNumber, "consult/1", false)); } } }
// ReSharper disable once InconsistentNaming void LoadCSVRow(int rowNumber, Structure row) { if (!this.IsTrue(new Structure("load_csv_row", rowNumber, row))) throw new Exception(string.Format("Failed to load CSV row number {0} : {1}", rowNumber, Term.ToStringInPrologFormat(row))); }
private void List(TerminalSet _TS, out Term term) { Term beforeBar; Term afterBar = null; ArrayList elements = null; terminalTable[DOT] = Atom; terminalTable[OP] = Atom; GetSymbol(new TerminalSet(LSqBracket), true, true); GetSymbol(new TerminalSet(LeftParen, Identifier, IntLiteral, RealLiteral, StringLiteral, Operator, Atom, Anonymous, CutSym, LSqBracket, RSqBracket, LCuBracket, PrologString), false, true); if (symbol.IsMemberOf(LeftParen, Identifier, IntLiteral, RealLiteral, StringLiteral, Operator, Atom, Anonymous, CutSym, LSqBracket, LCuBracket, PrologString)) { PrologTerm(new TerminalSet(RSqBracket, VBar), out beforeBar); elements = beforeBar.ArgumentsToArrayList(false); GetSymbol(new TerminalSet(RSqBracket, VBar), false, true); if (symbol.Terminal == VBar) { symbol.SetProcessed(); PrologTerm(new TerminalSet(RSqBracket), out afterBar); } } terminalTable[DOT] = Dot; terminalTable[OP] = OpSym; GetSymbol(new TerminalSet(RSqBracket), true, true); if (afterBar == null) term = Term.NULLLIST; else term = afterBar; if (elements != null) for (int i = elements.Count - 1; i >= 0; i--) term = new ListTerm((Term)elements[i], term); }
internal override bool UnifyWithTerm(Term term, PrologContext context) { return UnifyWithCanonicalValue(term, context); }
// whereTerm != null : for persistent predicates only // put the predicate definition (if found) into the TermNode if it is not already there public bool FindPredicateDefinition(PredicateStorage predicateStorage, Term whereTerm) { if (predDescr == null) predDescr = predicateStorage[term.KbKey]; if (predDescr == null) return false; #if arg1index Term arg; if (predDescr.IsFirstArgIndexed) { if ((arg = term.Arg (0)).IsVar) nextClause = predDescr.FirstArgVarClause (); else // not a variable { nextClause = predDescr.FirstArgNonvarClause (arg.Functor); // check whether there is an indexed var clause if (nextClause == null) nextClause = predDescr.FirstArgVarClause (); // if the above failed, the entire predicate fails (no unification possible) if (nextClause == null) nextClause = ClauseNode.FAIL; // "fail." } if (nextClause == null) nextClause = predDescr.GetClauseList (term, whereTerm); // GetClauseList: in PredicateStorage } else // not indexed #endif nextClause = predDescr.GetClauseList(term, whereTerm); // GetClauseList: in PredicateStorage return true; }
/// <summary> /// Remove a term from the KB. /// </summary> public void RetractAll(object term) { if (term == null) throw new ArgumentNullException("term", "Term to retract cannot be null."); RetractAll(Term.Structurify(term, "Fact is not a valid proposition or predicate.")); }
public ClauseNode(Term t, TermNode body, double p) : this(t, body) { timestamp = DateTime.Now.Ticks; prob = p; }
public bool Retract(Term t, VarStack varStack, Term where) { string key = t.KbKey; if (predefineds.Contains(key)) PrologIO.Error("retract of predefined predicate {0} not allowed", key); PredicateDescr pd = this[key]; if (pd == null) return false; #if persistent if (pd is PersistentPredDescr) { ((PersistentPredDescr)pd).Retract (t, varStack, where); return true; } #endif ClauseNode c = pd.GetClauseList(null, null); ClauseNode prevc = null; Term cleanTerm; int top; while (c != null) { cleanTerm = c.Term.CleanCopy(); top = varStack.Count; if (cleanTerm.Unify(t, varStack)) // match found -- remove this term from the chain { if (prevc == null) // remove first clause { if (c.NextClause == null) // we are about to remove the last remaining clause for this predicate { predTable.Remove(key); // ... so remove its PredicateDescr as well #if arg1index pd.CreateFirstArgIndex (); // re-create #endif ResolveIndices(); } else pd.SetClauseListHead(c.NextClause); } else // not the first { prevc.NextClause = c.NextClause; prevc = c; pd.AdjustClauseListEnd(); #if arg1index pd.CreateFirstArgIndex (); // re-create #endif } return true; // possible bindings must stay intact (e.g. if p(a) then retract(p(X)) yields X=a) } Term s; for (int i = varStack.Count - top; i > 0; i--) // unbind all vars that got bound by the above Unification { s = (Term)varStack.Pop(); s.Unbind(); } prevc = c; c = c.NextClause; } ResolveIndices(); return false; }
private Term DataRowAsTerm(int rowNo) { DataRow row = dataRowCollection [rowNo]; // caching does not work !!!!!!!!!!!!!!!!! (Conversion to Term fails for unknown reason) //if (row [0] != DBNull.Value) return (Term)row [0.Value]; // return cached value, else construct value into row[0] PersistentPredDescr ppd = (PersistentPredDescr)predDescr; DbMetaDataCollection mdc = ppd.MetaDataCollection; // construct the term, by inspecting each argument of the input term. // If it is a Var: take the corresponding value from the result set row, otherwise: simply copy the argument int colNo = 0; int nCols = ppd.Query.Arity; Term[] args = new Term [nCols]; for (int i = 0; i < nCols; i++) { Term a = ppd.Query.Args [i]; if (a.IsVar) args [i] = DbAccess.DbScalarToTerm (row[1+colNo++], mdc [i].DbType, a.FType, ppd.DbEntity); else args [i] = a; } Term rowTerm = new Term (ppd.Name, args); row [0] = rowTerm; // cache /// BUT DOES NOT WORK return rowTerm; }
public bool IsPersistent (Term t) { PredicateDescr pd = (PredicateDescr)predTable [t.KbKey]; return (pd == null) ? false : pd is PersistentPredDescr; }
public ClauseNode(Term t, TermNode body, double p, long ts) : this(t, body) { timestamp = ts; prob = p; }
public ClauseNode(Term t, TermNode body) : base(t, body) { }
public bool SetSpy(bool enabled, string functor, int arity, Term list) { SpyPort ports; if (list == null) ports = SpyPort.full; else { ports = SpyPort.none; string s; while (list.Arity == 2) { s = list.Arg(0).Functor; try { ports |= (SpyPort)Enum.Parse(typeof(SpyPort), s); } catch { PrologIO.Error("Illegal value '{0}'", s); } list = list.Arg(1); } } PredicateDescr pd; if (arity == -1) { bool found = false; foreach (DictionaryEntry de in predTable) if ((pd = (PredicateDescr)de.Value).Name == functor) { found = true; pd.SetSpy(enabled, pd.Name, pd.Arity, ports, !enabled); } if (!found) PrologIO.Error("Predicate does not exist: {0}", functor); return found; } else { if ((pd = (PredicateDescr)predTable[Term.Key(functor, arity)]) == null) { PrologIO.Error("Predicate does not exist: {0}/{1}", functor, arity); return false; } pd.SetSpy(enabled, functor, arity, ports, !enabled); } return true; }
internal abstract bool UnifyWithTerm(Term term, PrologContext context);
public void SetDiscontiguous(Term t) { if (t == null || t.Functor != SLASH || !t.Arg(0).IsAtom || !t.Arg(1).IsInteger) PrologIO.Error("Illegal or missing argument '{0}' for discontiguous/1", t); // The predicate descriptor does not yet exist (and may even not come at all!) string key = Term.Key(t.Arg(0).Functor, t.Arg(1).Functor); //Console.WriteLine ("--- Setting discontiguous for {0} in definingFile {1}", key, Globals.ConsultFileName); isDiscontiguous[key] = "true"; }
private void ClauseNode(TerminalSet _TS) { Term head; TermNode body = null; ClauseNode c; if (parseMode != ParseMode.Reading) Globals.EraseVariables(); GetSymbol(new TerminalSet(LeftParen, Identifier, IntLiteral, RealLiteral, StringLiteral, Operator, Atom, Anonymous, CutSym, ImpliesSym, PromptSym, LSqBracket, LCuBracket, PrologString), false, true); if (symbol.IsMemberOf(LeftParen, Identifier, IntLiteral, RealLiteral, StringLiteral, Operator, Atom, Anonymous, CutSym, LSqBracket, LCuBracket, PrologString)) { PrologTerm(new TerminalSet(Dot, ImpliesSym, DCGArrowSym), out head); if (!head.IsGoal) PrologIO.Error("Illegal predicate head: {0}", head.ToString()); GetSymbol(new TerminalSet(Dot, ImpliesSym, DCGArrowSym), false, true); if (symbol.IsMemberOf(ImpliesSym, DCGArrowSym)) { GetSymbol(new TerminalSet(ImpliesSym, DCGArrowSym), false, true); if (symbol.Terminal == ImpliesSym) { symbol.SetProcessed(); Query(new TerminalSet(Dot), out body); } else { symbol.SetProcessed(); Term t; PrologTerm(new TerminalSet(Dot), out t); body = t.ToDCG(ref head); } } c = new ClauseNode(head, body); if (parseMode == ParseMode.Reading) readTerm = new Term(c).CleanUp(); else ps.AddClause(c); } else if (symbol.Terminal == PromptSym) { symbol.SetProcessed(); bool m = inQueryMode; bool o = is1000OperatorSetting; int k = terminalTable[DOT]; try { parseMode = ParseMode.Query; inQueryMode = true; terminalTable[DOT] = Dot; Set1000Operators(true); Query(new TerminalSet(Dot), out queryNode); PrologIO.Error("'?-' querymode in file not yet supported"); } finally { inQueryMode = m; terminalTable[DOT] = k; Set1000Operators(o); } } else { symbol.SetProcessed(); terminalTable.Add(Persistent, "Persistent", "persistent"); terminalTable.Add(Module, "Module", "module"); terminalTable.Add(UndefPredAction, "UndefPredAction", "undef_pred_action"); try { GetSymbol(new TerminalSet(LSqBracket, OpSym, EnsureLoaded, Discontiguous, AllDiscontiguous, Dynamic, Persistent, Module, UndefPredAction), false, true); if (symbol.Terminal == OpSym) { OperatorDefinition(new TerminalSet(Dot), true); } else if (symbol.Terminal == EnsureLoaded) { symbol.SetProcessed(); GetSymbol(new TerminalSet(LeftParen), true, true); GetSymbol(new TerminalSet(StringLiteral, Atom), false, true); if (symbol.Terminal == Atom) { symbol.SetProcessed(); } else { symbol.SetProcessed(); } string fileName = Utils.ExtendedFileName(symbol.ToString().ToLower(), ".pl"); if (Globals.ConsultedFiles[fileName] == null) { ps.Consult(fileName); Globals.ConsultedFiles[fileName] = true; } GetSymbol(new TerminalSet(RightParen), true, true); } else if (symbol.Terminal == Discontiguous) { symbol.SetProcessed(); Term t; PrologTerm(new TerminalSet(Dot), out t); ps.SetDiscontiguous(t); } else if (symbol.Terminal == AllDiscontiguous) { symbol.SetProcessed(); ps.SetDiscontiguous(true); } else if (symbol.Terminal == UndefPredAction) { symbol.SetProcessed(); Term t; PrologTerm(new TerminalSet(Dot), out t); ps.SetUndefPredAction(t, true); } else if (symbol.Terminal == Dynamic) { symbol.SetProcessed(); Term t; PrologTerm(new TerminalSet(Dot), out t); } else if (symbol.Terminal == Persistent) { PersistentDeclaration(new TerminalSet(Dot)); } else if (symbol.Terminal == Module) { symbol.SetProcessed(); GetSymbol(new TerminalSet(LeftParen), true, true); try { terminalTable[COMMA] = Comma; GetSymbol(new TerminalSet(StringLiteral, Atom), false, true); if (symbol.Terminal == Atom) { symbol.SetProcessed(); } else { symbol.SetProcessed(); } ps.SetModuleName(symbol.ToString()); GetSymbol(new TerminalSet(Comma), true, true); } finally { terminalTable[COMMA] = Operator; } Term t; PrologTerm(new TerminalSet(RightParen), out t); GetSymbol(new TerminalSet(RightParen), true, true); } else { symbol.SetProcessed(); int lines = 0; int files = 0; try { while (true) { GetSymbol(new TerminalSet(StringLiteral, Atom), false, true); if (symbol.Terminal == Atom) { symbol.SetProcessed(); } else { symbol.SetProcessed(); } string fileName = Utils.FileNameFromSymbol(symbol.ToString(), ".pl"); terminalTable[COMMA] = Operator; lines += ps.Consult(fileName); files++; terminalTable[COMMA] = Comma; GetSymbol(new TerminalSet(Comma, RSqBracket), false, true); if (symbol.Terminal == Comma) { symbol.SetProcessed(); } else break; } if (files > 1) PrologIO.Message("Grand total is {0} lines", lines); } finally { terminalTable[COMMA] = Operator; } GetSymbol(new TerminalSet(RSqBracket), true, true); } } finally { terminalTable.Remove("module"); terminalTable.Remove("persistent"); terminalTable.Remove("undef_pred_action"); } } GetSymbol(new TerminalSet(Dot), true, true); }
public bool SetUndefPredAction(Term t, bool err) { Term pred = null; Term action = null; ArrayList args = null; string msg; bool result = true; t.IsPacked = false; if (t != null) args = t.ArgumentsToArrayList(false); bool OK = t != null && (args.Count == 2) && (pred = (Term)args[0]).Arity == 2 && pred.Functor == SLASH && pred.Arg(0).IsAtom && pred.Arg(1).IsInteger; if (!OK) { result = false; msg = string.Format("Bad first argument '{0}' for undef_pred_action( <predicate>/<arity>, ...)", t.Arg(0)); if (err) PrologIO.Error(msg); else PrologIO.Warning(msg); } OK = (action = (Term)args[1]) != null && (action.Functor == "fail" || // action.Functor == "succeed" || action.Functor == "error" || action.Functor == "warning"); if (!OK) { result = false; msg = string.Format("Bad second argument '{0}' for undef_pred_action( ..., fail/succeed/warning)", action); if (err) PrologIO.Error(msg); else PrologIO.Warning(msg); } if (result) { string key = Term.Key(pred.Arg(0).Functor, pred.Arg(1).Functor); actionWhenUndefined[key] = (UndefAction)Enum.Parse(typeof(UndefAction), action.Functor, false); } return result; }
private void DCGBracketList(TerminalSet _TS, out Term term) { Term head; ArrayList elements = null; GetSymbol(new TerminalSet(LCuBracket), true, true); GetSymbol(new TerminalSet(LeftParen, Identifier, IntLiteral, RealLiteral, StringLiteral, Operator, Atom, Anonymous, CutSym, LSqBracket, LCuBracket, RCuBracket, PrologString), false, true); if (symbol.IsMemberOf(LeftParen, Identifier, IntLiteral, RealLiteral, StringLiteral, Operator, Atom, Anonymous, CutSym, LSqBracket, LCuBracket, PrologString)) { PrologTerm(new TerminalSet(RCuBracket), out head); elements = head.ArgumentsToArrayList(true); } GetSymbol(new TerminalSet(RCuBracket), true, true); term = new DCGTerm(); if (elements != null) for (int i = elements.Count - 1; i >= 0; i--) term = new DCGTerm((Term)elements[i], term); }
private enum PredEnum { session, table, execproc, selproc } // table and view are treated identically #if persistent public void SetPersistent (Term t) { Term pred = null; Term db_info = null; // table( <name>) or procedure( <name>, <executable/selectable>) bool isTable = false; bool isExec = false; // executable stored procedure (as opposed to selectable) Term dbEntity = null; DbLogin dbLogin = null; ArrayList args = null; PredEnum predType; t.IsPacked = false; if (t != null) args = t.ArgumentsToArrayList (false); //for (int i = 0; i < args.Count; i++) Console.WriteLine ("args [{0}] = {1}", i, args [i]); bool OK = t != null && (args.Count == 2 || args.Count == 5) && (pred = (Term)args [0]).Arity == 2 && pred.Functor == SLASH && pred.Arg (0).IsAtom && pred.Arg (1).IsInteger; if (!OK) IO.Error ("Bad first argument '{0}' for persistent( <predicate>/<arity>, ...)", t.Arg (0)); OK = (db_info = (Term)args [1]) != null && ( (isTable = (db_info.Functor == "table" || db_info.Functor == "view")) || db_info.Functor == "procedure" || db_info.Functor == "proc") && db_info.Arity > 0 && ( (dbEntity = db_info.Arg (0)).IsAtom || dbEntity.IsString ); if (!OK) IO.Error ("Bad second argument '{0}' for persistent( ..., table/view/procedure(...))", db_info); if (isTable) { if (db_info.Arity != 1) IO.Error ("Bad second argument '{0}' for persistent( ..., table/view( <db_entity_name>))", db_info); predType = PredEnum.table; } else { string invocation; OK = (db_info.Arity == 2) && // procedure( <name>, <executable/selectable>) ( (isExec = ((invocation = db_info.Arg (1).Functor) == "executable" || invocation == "exec")) || invocation == "selectable" || invocation == "select" ); if (!OK) IO.Error ("Bad second argument '{0}' for persistent( ..., procedure( <db_entity_name>, [selectable|executable]))", t.Arg (1)); predType = isExec ? PredEnum.execproc : PredEnum.selproc; } string functor = pred.Arg (0).Functor; int arity = Convert.ToInt32 (pred.Arg (1).Functor); string index = Term.Key (functor, arity); if (predefineds [index] != null) IO.Error ("Predefined predicate '{0}/{1}' cannot be declared as persistent", functor, arity); if (args.Count == 5) { for (int i = 2; i <= 4; i++) if (!(((Term)args [i]).IsAtom || ((Term)args [i]).IsString)) IO.Error ("Argument '{0}' not an atom or string", (Term)args [i]); dbLogin = new DbLogin (((Term)args [2]).Functor, ((Term)args [3]).Functor, ((Term)args [4]).Functor); } PredicateDescr pd = this [index]; if (pd != null) // apparently already defined { string definingFile = (pd.DefiningFile == Globals.ConsultFileName) ? "this file" : pd.DefiningFile; if (!(pd is PersistentPredDescr)) IO.Error ("Predicate '{0}/{1}' cannot be declared as persistent (predicate defined in {2})", functor, arity, definingFile); } pd = SetClauseList (predType, functor, arity, null); ((PersistentPredDescr)pd).DbEntity = dbEntity.Functor; ((PersistentPredDescr)pd).DbLogin = dbLogin; }
private void PrologTerm(TerminalSet _TS, out Term t) { Term lastInfix = null; string s; ArrayList termInfixArr = new ArrayList(); termInfixArr.Add(null); do { GetSymbol(new TerminalSet(LeftParen, Identifier, IntLiteral, RealLiteral, StringLiteral, Operator, Atom, Anonymous, CutSym, LSqBracket, LCuBracket, PrologString), false, true); if (symbol.Terminal == Operator) { symbol.SetProcessed(); t = new Term((OperatorDescr)symbol.OValue); } else if (symbol.IsMemberOf(StringLiteral, Atom)) { GetSymbol(new TerminalSet(StringLiteral, Atom), false, true); if (symbol.Terminal == Atom) { symbol.SetProcessed(); s = symbol.ToString(); } else { symbol.SetProcessed(); s = Utils.UnquoteIfUnnecessary(symbol.ToString()); } Term[] terms = null; bool b = is1000OperatorSetting; GetSymbol(_TS.Union(LeftParen, Identifier, IntLiteral, RealLiteral, StringLiteral, Operator, Atom, Anonymous, CutSym, LSqBracket, LCuBracket, PrologString), false, true); if (symbol.Terminal == LeftParen) { symbol.SetProcessed(); Set1000Operators(true); terminalTable[DOT] = Atom; terminalTable[OP] = Atom; PrologTerm(new TerminalSet(RightParen), out t); terminalTable[DOT] = Dot; terminalTable[OP] = OpSym; terms = t.ArgumentsToTermArray(); Set1000Operators(b); GetSymbol(new TerminalSet(RightParen), true, true); } if (terms == null) t = new Term(s); else t = new Term(s, terms); } else if (symbol.Terminal == Identifier) { symbol.SetProcessed(); s = symbol.ToString(); t = Globals.GetVariable(s); if (t == null) { t = new NamedVar(s); Globals.SetVariable(t, s); } } else if (symbol.Terminal == Anonymous) { symbol.SetProcessed(); t = new Term(); } else if (symbol.IsMemberOf(IntLiteral, RealLiteral)) { GetSymbol(new TerminalSet(IntLiteral, RealLiteral), false, true); if (symbol.Terminal == IntLiteral) { symbol.SetProcessed(); } else { symbol.SetProcessed(); } t = new Term(symbol.ToString(), FType.number); } else if (symbol.Terminal == LSqBracket) { List(_TS.Union(LeftParen, Identifier, IntLiteral, RealLiteral, StringLiteral, Operator, Atom, Anonymous, CutSym, LSqBracket, LCuBracket, PrologString), out t); } else if (symbol.Terminal == LCuBracket) { DCGBracketList(_TS.Union(LeftParen, Identifier, IntLiteral, RealLiteral, StringLiteral, Operator, Atom, Anonymous, CutSym, LSqBracket, LCuBracket, PrologString), out t); } else if (symbol.Terminal == PrologString) { symbol.SetProcessed(); t = new Term(symbol.ToUnquoted(), FType.text); } else if (symbol.Terminal == CutSym) { symbol.SetProcessed(); t = new Cut(0); } else { symbol.SetProcessed(); PrologTerm(new TerminalSet(RightParen), out t); GetSymbol(new TerminalSet(RightParen), true, true); t.IsPacked = true; } termInfixArr.Add(t); Term.AnalyzeInput(ref termInfixArr, ref lastInfix); GetSymbol(_TS.Union(LeftParen, Identifier, IntLiteral, RealLiteral, StringLiteral, Operator, Atom, Anonymous, CutSym, LSqBracket, LCuBracket, PrologString), false, true); } while (!(_TS.Contains(symbol.Terminal))); termInfixArr.Add(null); Term.AnalyzeInput(ref termInfixArr, ref lastInfix); t = Term.InfixToPrefix(termInfixArr); }
public void SetUnpersistent (Term t) { Term s; if ( t == null || t.Arity != 1 || (s = t.Arg (0)).Arity != 2 || s.Functor != SLASH || !s.Arg (0).IsAtom || !s.Arg (1).IsInteger ) IO.Error ("Bad argument(s) {0} for unpersistent( <predicate>/<arity>)", t); string functor = t.Arg (0).Arg (0).Functor; // do not touch case int arity = Convert.ToInt32 (t.Arg (0).Arg (1).Functor); string key = Term.Key (functor, arity); if (predefineds [key] != null) IO.Error ("Predefined predicate '{0}/{1}' cannot be declared as unpersistent", functor, arity); PredicateDescr pd = this [key]; if (pd == null || !(pd is PersistentPredDescr)) IO.Error ("Predicate '{0}/{1}' was not declared as persistent", functor, arity); else this [key] = null; }
internal override IEnumerable<bool> UnifyWithTerm(Term term) { return UnifyWithCanonicalValue(term); }
public void SetUnpersistent(Term t) { PrologIO.Error("Persistent predicates are not available in this version"); }
internal override bool UnifyWithTerm(Term value, PrologContext context) { return value.UnifyWithAtomicConstant(this, context); }
/// <summary> /// Add a term (fact or rule) to the KB. /// </summary> public void Assert(Structure structure, bool atEnd, bool checkSingletons) { if (structure == null) throw new ArgumentNullException("structure", "Term to add to KB may not be null."); //structure = structure.Expand(); if (structure == null) throw new ArgumentNullException("structure"); Structure head = structure.IsFunctor(Symbol.Implication, 2) ? Term.Structurify(structure.Argument(0), "Head of :- must be a valid proposition or predicate.") : structure; if (head.IsFunctor(Symbol.ColonColon, 2)) { var argument = head.Argument(0); var kb = argument as KnowledgeBase; if (kb == null) { var o = argument as GameObject; if (o != null) kb = o.KnowledgeBase(); else { var c = argument as Component; if (c != null) kb = c.KnowledgeBase(); else throw new ArgumentTypeException( "assert", "knowledgebase", argument, typeof(KnowledgeBase)); } } if (structure.IsFunctor(Symbol.Implication, 2)) kb.Assert( new Structure(Symbol.Implication, head.Argument(1), structure.Argument(1)), atEnd, checkSingletons); else { kb.Assert(structure.Argument(1), atEnd, checkSingletons); } } else { if (PrologPrimitives.Implementations.ContainsKey(head.Functor)) throw new PrologException( new Structure( "error", new Structure( "permission_error", Symbol.Intern("modify"), Symbol.Intern("static_procedure"), Term.PredicateIndicatorExpression(head)))); KnowledgeBaseRule assertion = KnowledgeBaseRule.FromTerm( structure, checkSingletons, Prolog.CurrentSourceFile, Prolog.CurrentSourceLineNumber); PredicateInfo info = EntryForStoring(head.PredicateIndicator); PredicateInfo parentInfo; if (!info.Shadow && this.Parent != null && (parentInfo = this.Parent.CheckForPredicateInfoInThisKB(head.PredicateIndicator)) != null && !parentInfo.External) throw new PrologException( new Structure( "error", new Structure( "permission_error", Symbol.Intern("shadow"), Term.PredicateIndicatorExpression(head)))); info.Assert(assertion, atEnd); } }