Mantis#1931. Thank you kindly, Kinoc for a patch that:

* Yield Prolog 1.0.1 Released : it passes all but 9 of the 
421 tests in the ISO Prolog test suite (97.8%) .
* support dynamic predicates and rules.
* support 'import' to use external static functions 
improves connection to C# functions
* Matches Yield Prolog r831
0.6.0-stable
Charles Krinke 2008-08-13 14:13:49 +00:00
parent e46248ab17
commit 323ada012d
23 changed files with 2060 additions and 584 deletions

View File

@ -98,6 +98,14 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
return make(Atom.a(name), args); return make(Atom.a(name), args);
} }
/// <summary>
/// If arg is another Functor, then succeed (yield once) if this and arg have the
/// same name and all functor args unify, otherwise fail (don't yield).
/// If arg is a Variable, then call its unify to unify with this.
/// Otherwise fail (don't yield).
/// </summary>
/// <param name="arg"></param>
/// <returns></returns>
public IEnumerable<bool> unify(object arg) public IEnumerable<bool> unify(object arg)
{ {
arg = YP.getValue(arg); arg = YP.getValue(arg);

View File

@ -52,6 +52,14 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
// disable warning on l1, don't see how we can // disable warning on l1, don't see how we can
// code this differently // code this differently
#pragma warning disable 0168 #pragma warning disable 0168
/// <summary>
/// If arg is another Functor1, then succeed (yield once) if this and arg have the
/// same name and the functor args unify, otherwise fail (don't yield).
/// If arg is a Variable, then call its unify to unify with this.
/// Otherwise fail (don't yield).
/// </summary>
/// <param name="arg"></param>
/// <returns></returns>
public IEnumerable<bool> unify(object arg) public IEnumerable<bool> unify(object arg)
{ {
arg = YP.getValue(arg); arg = YP.getValue(arg);

View File

@ -54,6 +54,10 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
// disable warning on l1, don't see how we can // disable warning on l1, don't see how we can
// code this differently // code this differently
#pragma warning disable 0168 #pragma warning disable 0168
/// If arg is another Functor2, then succeed (yield once) if this and arg have the
/// same name and all functor args unify, otherwise fail (don't yield).
/// If arg is a Variable, then call its unify to unify with this.
/// Otherwise fail (don't yield).
public IEnumerable<bool> unify(object arg) public IEnumerable<bool> unify(object arg)
{ {
arg = YP.getValue(arg); arg = YP.getValue(arg);

View File

@ -56,6 +56,10 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
// disable warning on l1, don't see how we can // disable warning on l1, don't see how we can
// code this differently // code this differently
#pragma warning disable 0168 #pragma warning disable 0168
/// If arg is another Functor3, then succeed (yield once) if this and arg have the
/// same name and all functor args unify, otherwise fail (don't yield).
/// If arg is a Variable, then call its unify to unify with this.
/// Otherwise fail (don't yield).
public IEnumerable<bool> unify(object arg) public IEnumerable<bool> unify(object arg)
{ {
arg = YP.getValue(arg); arg = YP.getValue(arg);

View File

@ -270,8 +270,7 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
throw new PrologException("instantiation_error", "Head is an unbound variable"); throw new PrologException("instantiation_error", "Head is an unbound variable");
object[] arguments = YP.getFunctorArgs(Head); object[] arguments = YP.getFunctorArgs(Head);
// We always match Head from _allAnswers, and the Body is // We always match Head from _allAnswers, and the Body is Atom.a("true").
// Atom.a("true").
#pragma warning disable 0168 #pragma warning disable 0168
foreach (bool l1 in YP.unify(Body, Atom.a("true"))) foreach (bool l1 in YP.unify(Body, Atom.a("true")))
{ {

View File

@ -132,6 +132,7 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
/// <summary> /// <summary>
/// Return an array of the elements in list or null if it is not /// Return an array of the elements in list or null if it is not
/// a proper list. If list is Atom.NIL, return an array of zero elements. /// a proper list. If list is Atom.NIL, return an array of zero elements.
/// If the list or one of the tails of the list is Variable, raise an instantiation_error.
/// This does not call YP.getValue on each element. /// This does not call YP.getValue on each element.
/// </summary> /// </summary>
/// <param name="list"></param> /// <param name="list"></param>
@ -143,10 +144,19 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
return new object[0]; return new object[0];
List<object> result = new List<object>(); List<object> result = new List<object>();
for (object element = list; object element = list;
element is Functor2 && ((Functor2)element)._name == Atom.DOT; while (true) {
element = YP.getValue(((Functor2)element)._arg2)) if (element == Atom.NIL)
break;
if (element is Variable)
throw new PrologException(Atom.a("instantiation_error"),
"List tail is an unbound variable");
if (!(element is Functor2 && ((Functor2)element)._name == Atom.DOT))
// Not a proper list.
return null;
result.Add(((Functor2)element)._arg1); result.Add(((Functor2)element)._arg1);
element = YP.getValue(((Functor2)element)._arg2);
}
if (result.Count <= 0) if (result.Count <= 0)
return null; return null;

View File

@ -29,6 +29,7 @@ FEATURES
* Compiler is generated by compiling the Prolog descrition of itself into C# * Compiler is generated by compiling the Prolog descrition of itself into C#
* Same script entry interface as LSL * Same script entry interface as LSL
* Yield Prolog 1.0.1 Released : it passes all but 9 of the 421 tests in the ISO Prolog test suite (97.8%).
TODO TODO
* Utilize ability to generate Javascript and Python code * Utilize ability to generate Javascript and Python code
@ -117,6 +118,113 @@ void retractdb2(string predicate, string arg1, string arg2)
YP.retractFact(name, new object[] { arg1, arg2 }); YP.retractFact(name, new object[] { arg1, arg2 });
} }
----------- IMPORT EXTERNAL FUNCTIONS ----------
Using 'import' to call a static function
Taken mostly from http://yieldprolog.sourceforge.net/tutorial4.html
If we want to call a static function but it is not defined in the Prolog code, we can simply add an import directive.
(In Prolog, if you start a line with :- it is a directive to the compiler. Don't forget to end with a period.):
:- import('', [parent/2]).
uncle(Person, Uncle):- parent(Person, Parent), brother(Parent, Uncle).
The import directive has two arguments.
The first argument is the module where the imported function is found, which is always ''.
For C#, this means the imported function is in the same class as the calling function.
For Javascript and Python, this means the imported function is in the global scope.
The second argument to import is the comma-separated list of imported functions, where each member of the list is 'name/n', where 'name' is the name of the function and 'n' is the number of arguments.
In this example, parent has two arguments, so we use parent/2.
Note: you can use an imported function in a dynamically defined goal, or a function in another class.
:- import('', [parent/2]).
uncle(Person, Uncle) :- Goal = parent(Person, Parent), Goal, brother(Parent, Uncle).
:- import('', ['OtherClass.parent'/2]).
uncle(Person, Uncle) :- 'OtherClass.parent'(Person, Parent), brother(Parent, Uncle).
--------- Round-about Hello Wonderful world ----------
//yp
:-import('',[sayit/1]).
sayhello(X):-sayit(X).
//cs
public void default_event_state_entry()
{
llSay(0,"prolog hello.");
foreach( bool ans in sayhello(Atom.a(@"wonderful world") )){};
}
PrologCallback sayit(object ans)
{
llSay(0,"sayit1");
string msg = "one answer is :"+((Variable)ans).getValue();
llSay(0,msg);
yield return false;
}
------------------ UPDATES -----------------
Yield Prolog 1.0 Released : It passes all but 15 of the 421 tests in the ISO Prolog test suite.
New Features:
* Added support for Prolog predicates read and read_term.
* In see, Added support for a char code list as the input.
Using this as the input for "fred" makes
set_prolog_flag(double_quotes, atom) and
set_prolog_flag(double_quotes, chars) pass the ISO test suite.
Fixed Bugs:
* In atom_chars, check for unbound tail in the char list.
This makes atom_chars pass the ISO test suite.
* In current_predicate, also check for static functions.
This makes current_predicate pass the ISO test suite.
Known Issues:
Here are the 9 errors of the 421 tests in the ISO test suite in
YieldProlog\source\prolog\isoTestSuite.P .
Some of these have a good excuse for why Yield Prolog produces the error. The rest will be addressed in a future maintenance release.
Goal: call((fail, 1))
Expected: type_error(callable, (fail, 1))
Extra Solutions found: failure
Goal: call((write(3), 1))
Expected: type_error(callable, (write(3), 1))
Extra Solutions found: type_error(callable, 1)
Goal: call((1; true))
Expected: type_error(callable, (1 ; true))
Extra Solutions found: type_error(callable, 1)
Goal: (catch(true, C, write('something')), throw(blabla))
Expected: system_error
Extra Solutions found: unexpected_ball(blabla)
Goal: catch(number_chars(A,L), error(instantiation_error, _), fail)
Expected: failure
Extra Solutions found: instantiation_error
Goal: Goal: (X = 1 + 2, 'is'(Y, X * 3))
Expected: [[X <-- (1 + 2), Y <-- 9]]
Extra Solutions found: type_error(evaluable, /(+, 2))
Goal: 'is'(77, N)
Expected: instantiation_error
Extra Solutions found: N <-- 77)
Goal: \+(!, fail)
Expected: success
Extra Solutions found: failure
((X=1;X=2), \+((!,fail)))
Expected: [[X <-- 1],[X <-- 2]]
Extra Solutions found: failure
========================= APPENDIX A: touch test ================================ ========================= APPENDIX A: touch test ================================
@ -403,3 +511,4 @@ public IEnumerable<bool> prolog_notify(object X) {
} } } }

View File

@ -43,6 +43,10 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
bool ground(); bool ground();
} }
/// <summary>
/// A Variable is passed to a function so that it can be unified with
/// value or another Variable. See getValue and unify for details.
/// </summary>
public class Variable : IUnifiable public class Variable : IUnifiable
{ {
// Use _isBound separate from _value so that it can be bound to any value, // Use _isBound separate from _value so that it can be bound to any value,
@ -50,6 +54,14 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
private bool _isBound = false; private bool _isBound = false;
private object _value; private object _value;
/// <summary>
/// If this Variable is unbound, then just return this Variable.
/// Otherwise, if this has been bound to a value with unify, return the value.
/// If the bound value is another Variable, this follows the "variable chain"
/// to the end and returns the final value, or the final Variable if it is unbound.
/// For more details, see http://yieldprolog.sourceforge.net/tutorial1.html
/// </summary>
/// <returns></returns>
public object getValue() public object getValue()
{ {
if (!_isBound) if (!_isBound)
@ -68,6 +80,16 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
return result; return result;
} }
/// <summary>
/// If this Variable is bound, then just call YP.unify to unify this with arg.
/// (Note that if arg is an unbound Variable, then YP.unify will bind it to
/// this Variable's value.)
/// Otherwise, bind this Variable to YP.getValue(arg) and yield once. After the
/// yield, return this Variable to the unbound state.
/// For more details, see http://yieldprolog.sourceforge.net/tutorial1.html
/// </summary>
/// <param name="arg"></param>
/// <returns></returns>
public IEnumerable<bool> unify(object arg) public IEnumerable<bool> unify(object arg)
{ {
if (!_isBound) if (!_isBound)
@ -105,7 +127,7 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
{ {
object value = getValue(); object value = getValue();
if (value == this) if (value == this)
return "Variable"; return "_Variable";
else else
return getValue().ToString(); return getValue().ToString();
} }

View File

@ -52,6 +52,8 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
private static TextWriter _outputStream = System.Console.Out; private static TextWriter _outputStream = System.Console.Out;
private static TextReader _inputStream = System.Console.In; private static TextReader _inputStream = System.Console.In;
private static IndexedAnswers _operatorTable = null; private static IndexedAnswers _operatorTable = null;
private static Dictionary<string, object> _prologFlags = new Dictionary<string, object>();
public const int MAX_ARITY = 255;
/// <summary> /// <summary>
/// An IClause is used so that dynamic predicates can call match. /// An IClause is used so that dynamic predicates can call match.
@ -62,6 +64,16 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
IEnumerable<bool> clause(object Head, object Body); IEnumerable<bool> clause(object Head, object Body);
} }
/// <summary>
/// If value is a Variable, then return its getValue. Otherwise, just
/// return value. You should call YP.getValue on any object that
/// may be a Variable to get the value to pass to other functions in
/// your system that are not part of Yield Prolog, such as math functions
/// or file I/O.
/// For more details, see http://yieldprolog.sourceforge.net/tutorial1.html
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static object getValue(object value) public static object getValue(object value)
{ {
if (value is Variable) if (value is Variable)
@ -70,6 +82,17 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
return value; return value;
} }
/// <summary>
/// If arg1 or arg2 is an object with a unify method (such as Variable or
/// Functor) then just call its unify with the other argument. The object's
/// unify method will bind the values or check for equals as needed.
/// Otherwise, both arguments are "normal" (atomic) values so if they
/// are equal then succeed (yield once), else fail (don't yield).
/// For more details, see http://yieldprolog.sourceforge.net/tutorial1.html
/// </summary>
/// <param name="arg1"></param>
/// <param name="arg2"></param>
/// <returns></returns>
public static IEnumerable<bool> unify(object arg1, object arg2) public static IEnumerable<bool> unify(object arg1, object arg2)
{ {
arg1 = getValue(arg1); arg1 = getValue(arg1);
@ -622,6 +645,10 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
if (args.Length == 0) if (args.Length == 0)
// Return the Name, even if it is not an Atom. // Return the Name, even if it is not an Atom.
return YP.unify(Term, Name); return YP.unify(Term, Name);
if (args.Length > MAX_ARITY)
throw new PrologException
(new Functor1("representation_error", Atom.a("max_arity")),
"Functor arity " + args.Length + " may not be greater than " + MAX_ARITY);
if (!atom(Name)) if (!atom(Name))
throw new PrologException throw new PrologException
(new Functor2("type_error", Atom.a("atom"), Name), (new Functor2("type_error", Atom.a("atom"), Name),
@ -666,6 +693,10 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
} }
else else
{ {
if ((int)Arity > MAX_ARITY)
throw new PrologException
(new Functor1("representation_error", Atom.a("max_arity")),
"Functor arity " + Arity + " may not be greater than " + MAX_ARITY);
if (!(FunctorName is Atom)) if (!(FunctorName is Atom))
throw new PrologException throw new PrologException
(new Functor2("type_error", Atom.a("atom"), FunctorName), "FunctorName is not an atom"); (new Functor2("type_error", Atom.a("atom"), FunctorName), "FunctorName is not an atom");
@ -903,8 +934,7 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
_operatorTable.addAnswer(new object[] { 20, Atom.a("xfx"), Atom.a("<--") }); _operatorTable.addAnswer(new object[] { 20, Atom.a("xfx"), Atom.a("<--") });
} }
foreach (bool l1 in _operatorTable.match(new object[] { Priority, Specifier, Operator })) return _operatorTable.match(new object[] { Priority, Specifier, Operator });
yield return false;
} }
public static IEnumerable<bool> atom_length(object atom, object Length) public static IEnumerable<bool> atom_length(object atom, object Length)
@ -1491,9 +1521,22 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
return Term is Functor1 || Term is Functor2 || Term is Functor3 || Term is Functor; return Term is Functor1 || Term is Functor2 || Term is Functor3 || Term is Functor;
} }
/// <summary>
/// If input is a TextReader, use it. If input is an Atom or String, create a StreamReader with the
/// input as the filename. If input is a Prolog list, then read character codes from it.
/// </summary>
/// <param name="input"></param>
public static void see(object input) public static void see(object input)
{ {
input = YP.getValue(input); input = YP.getValue(input);
if (input is Variable)
throw new PrologException(Atom.a("instantiation_error"), "Arg is an unbound variable");
if (input == null)
{
_inputStream = null;
return;
}
if (input is TextReader) if (input is TextReader)
{ {
_inputStream = (TextReader)input; _inputStream = (TextReader)input;
@ -1509,21 +1552,48 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
_inputStream = new StreamReader((String)input); _inputStream = new StreamReader((String)input);
return; return;
} }
else if (input is Functor2 && ((Functor2)input)._name == Atom.DOT)
{
_inputStream = new CodeListReader(input);
return;
}
else else
throw new InvalidOperationException("Can't open stream for " + input); throw new PrologException
(new Functor2("domain_error", Atom.a("stream_or_alias"), input),
"Input stream specifier not recognized");
} }
public static void seen() public static void seen()
{ {
if (_inputStream == null)
return;
if (_inputStream == Console.In) if (_inputStream == Console.In)
return; return;
_inputStream.Close(); _inputStream.Close();
_inputStream = Console.In; _inputStream = Console.In;
} }
public static IEnumerable<bool> current_input(object Stream)
{
return YP.unify(Stream, _inputStream);
}
/// <summary>
/// If output is a TextWriter, use it. If output is an Atom or a String, create a StreamWriter
/// with the input as the filename.
/// </summary>
/// <param name="output"></param>
public static void tell(object output) public static void tell(object output)
{ {
output = YP.getValue(output); output = YP.getValue(output);
if (output is Variable)
throw new PrologException(Atom.a("instantiation_error"), "Arg is an unbound variable");
if (output == null)
{
_outputStream = null;
return;
}
if (output is TextWriter) if (output is TextWriter)
{ {
_outputStream = (TextWriter)output; _outputStream = (TextWriter)output;
@ -1540,11 +1610,15 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
return; return;
} }
else else
throw new InvalidOperationException("Can't open stream for " + output); throw new PrologException
(new Functor2("domain_error", Atom.a("stream_or_alias"), output),
"Can't open stream for " + output);
} }
public static void told() public static void told()
{ {
if (_outputStream == null)
return;
if (_outputStream == Console.Out) if (_outputStream == Console.Out)
return; return;
_outputStream.Close(); _outputStream.Close();
@ -1558,6 +1632,8 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
public static void write(object x) public static void write(object x)
{ {
if (_outputStream == null)
return;
x = YP.getValue(x); x = YP.getValue(x);
if (x is double) if (x is double)
_outputStream.Write(doubleToString((double)x)); _outputStream.Write(doubleToString((double)x));
@ -1591,6 +1667,8 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
public static void put_code(object x) public static void put_code(object x)
{ {
if (_outputStream == null)
return;
if (var(x)) if (var(x))
throw new PrologException(Atom.a("instantiation_error"), "Arg 1 is an unbound variable"); throw new PrologException(Atom.a("instantiation_error"), "Arg 1 is an unbound variable");
int xInt; int xInt;
@ -1602,11 +1680,16 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
public static void nl() public static void nl()
{ {
if (_outputStream == null)
return;
_outputStream.WriteLine(); _outputStream.WriteLine();
} }
public static IEnumerable<bool> get_code(object code) public static IEnumerable<bool> get_code(object code)
{ {
if (_inputStream == null)
return YP.unify(code, -1);
else
return YP.unify(code, _inputStream.Read()); return YP.unify(code, _inputStream.Read());
} }
@ -1763,7 +1846,7 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
/// <summary> /// <summary>
/// Match all clauses of the dynamic predicate with the name and with arity /// Match all clauses of the dynamic predicate with the name and with arity
/// arguments.Length. /// arguments.Length.
/// It is an error if the predicate is not defined. /// If the predicate is not defined, return the result of YP.unknownPredicate.
/// </summary> /// </summary>
/// <param name="name">must be an Atom</param> /// <param name="name">must be an Atom</param>
/// <param name="arguments">an array of arity number of arguments</param> /// <param name="arguments">an array of arity number of arguments</param>
@ -1772,11 +1855,8 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
{ {
List<IClause> clauses; List<IClause> clauses;
if (!_predicatesStore.TryGetValue(new NameArity(name, arguments.Length), out clauses)) if (!_predicatesStore.TryGetValue(new NameArity(name, arguments.Length), out clauses))
throw new PrologException return unknownPredicate(name, arguments.Length,
(new Functor2 "Undefined dynamic predicate: " + name + "/" + arguments.Length);
(Atom.a("existence_error"), Atom.a("procedure"),
new Functor2(Atom.SLASH, name, arguments.Length)),
"Undefined predicate: " + name + "/" + arguments.Length);
if (clauses.Count == 1) if (clauses.Count == 1)
// Usually there is only one clause, so return it without needing to wrap it in an iterator. // Usually there is only one clause, so return it without needing to wrap it in an iterator.
@ -1808,6 +1888,34 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
} }
} }
/// <summary>
/// If _prologFlags["unknown"] is fail then return fail(), else if
/// _prologFlags["unknown"] is warning then write the message to YP.write and
/// return fail(), else throw a PrologException for existence_error. .
/// </summary>
/// <param name="name"></param>
/// <param name="arity"></param>
/// <param name="message"></param>
/// <returns></returns>
public static IEnumerable<bool> unknownPredicate(Atom name, int arity, string message)
{
establishPrologFlags();
if (_prologFlags["unknown"] == Atom.a("fail"))
return fail();
else if (_prologFlags["unknown"] == Atom.a("warning"))
{
write(message);
nl();
return fail();
}
else
throw new PrologException
(new Functor2
(Atom.a("existence_error"), Atom.a("procedure"),
new Functor2(Atom.SLASH, name, arity)), message);
}
/// <summary> /// <summary>
/// This is deprecated and just calls matchDynamic. This matches all clauses, /// This is deprecated and just calls matchDynamic. This matches all clauses,
/// not just the ones defined with assertFact. /// not just the ones defined with assertFact.
@ -1951,7 +2059,17 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
_predicatesStore[nameArity] = new List<IClause>(); _predicatesStore[nameArity] = new List<IClause>();
} }
public static IEnumerable<bool> current_predicate(object NameSlashArity) /// <summary>
/// If NameSlashArity is var, match with all the dynamic predicates using the
/// Name/Artity form.
/// If NameSlashArity is not var, check if the Name/Arity exists as a static or
/// dynamic predicate.
/// </summary>
/// <param name="NameSlashArity"></param>
/// <param name="declaringClass">if not null, used to resolve references to the default
/// module Atom.a("")</param>
/// <returns></returns>
public static IEnumerable<bool> current_predicate(object NameSlashArity, Type declaringClass)
{ {
NameSlashArity = YP.getValue(NameSlashArity); NameSlashArity = YP.getValue(NameSlashArity);
// First check if Name and Arity are nonvar so we can do a direct lookup. // First check if Name and Arity are nonvar so we can do a direct lookup.
@ -1976,7 +2094,7 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
(new Functor2("domain_error", Atom.a("not_less_than_zero"), arity), (new Functor2("domain_error", Atom.a("not_less_than_zero"), arity),
"Arity may not be less than zero"); "Arity may not be less than zero");
if (_predicatesStore.ContainsKey(new NameArity((Atom)name, (int)arity))) if (YPCompiler.isCurrentPredicate((Atom)name, (int)arity, declaringClass))
// The predicate is defined. // The predicate is defined.
yield return false; yield return false;
} }
@ -1991,6 +2109,18 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
} }
} }
/// <summary>
/// Return true if the dynamic predicate store has an entry for the predicate
/// with name and arity.
/// </summary>
/// <param name="name"></param>
/// <param name="arity"></param>
/// <returns></returns>
public static bool isDynamicCurrentPredicate(Atom name, int arity)
{
return _predicatesStore.ContainsKey(new NameArity(name, arity));
}
public static void abolish(object NameSlashArity) public static void abolish(object NameSlashArity)
{ {
NameSlashArity = YP.getValue(NameSlashArity); NameSlashArity = YP.getValue(NameSlashArity);
@ -2019,6 +2149,10 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
throw new PrologException throw new PrologException
(new Functor2("domain_error", Atom.a("not_less_than_zero"), arity), (new Functor2("domain_error", Atom.a("not_less_than_zero"), arity),
"Arity may not be less than zero"); "Arity may not be less than zero");
if ((int)arity > MAX_ARITY)
throw new PrologException
(new Functor1("representation_error", Atom.a("max_arity")),
"Arity may not be greater than " + MAX_ARITY);
if (isSystemPredicate((Atom)name, (int)arity)) if (isSystemPredicate((Atom)name, (int)arity))
throw new PrologException throw new PrologException
@ -2077,7 +2211,108 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
{ {
throw new PrologException(Term); throw new PrologException(Term);
} }
/// <summary>
/// This must be called by any function that uses YP._prologFlags to make sure
/// the initial defaults are loaded.
/// </summary>
private static void establishPrologFlags()
{
if (_prologFlags.Count > 0)
// Already established.
return;
// List these in the order they appear in the ISO standard.
_prologFlags["bounded"] = Atom.a("true");
_prologFlags["max_integer"] = Int32.MaxValue;
_prologFlags["min_integer"] = Int32.MinValue;
_prologFlags["integer_rounding_function"] = Atom.a("toward_zero");
_prologFlags["char_conversion"] = Atom.a("off");
_prologFlags["debug"] = Atom.a("off");
_prologFlags["max_arity"] = MAX_ARITY;
_prologFlags["unknown"] = Atom.a("error");
_prologFlags["double_quotes"] = Atom.a("codes");
}
public static IEnumerable<bool> current_prolog_flag(object Key, object Value)
{
establishPrologFlags();
Key = YP.getValue(Key);
Value = YP.getValue(Value);
if (Key is Variable)
{
// Bind all key values.
foreach (string key in _prologFlags.Keys)
{
foreach (bool l1 in YP.unify(Key, Atom.a(key)))
{
foreach (bool l2 in YP.unify(Value, _prologFlags[key]))
yield return false;
}
}
}
else
{
if (!(Key is Atom))
throw new PrologException
(new Functor2("type_error", Atom.a("atom"), Key), "Arg 1 Key is not an atom");
if (!_prologFlags.ContainsKey(((Atom)Key)._name))
throw new PrologException
(new Functor2("domain_error", Atom.a("prolog_flag"), Key),
"Arg 1 Key is not a recognized flag");
foreach (bool l1 in YP.unify(Value, _prologFlags[((Atom)Key)._name]))
yield return false;
}
}
public static void set_prolog_flag(object Key, object Value)
{
establishPrologFlags();
Key = YP.getValue(Key);
Value = YP.getValue(Value);
if (Key is Variable)
throw new PrologException(Atom.a("instantiation_error"),
"Arg 1 Key is an unbound variable");
if (Value is Variable)
throw new PrologException(Atom.a("instantiation_error"),
"Arg 1 Key is an unbound variable");
if (!(Key is Atom))
throw new PrologException
(new Functor2("type_error", Atom.a("atom"), Key), "Arg 1 Key is not an atom");
string keyName = ((Atom)Key)._name;
if (!_prologFlags.ContainsKey(keyName))
throw new PrologException
(new Functor2("domain_error", Atom.a("prolog_flag"), Key),
"Arg 1 Key " + Key + " is not a recognized flag");
bool valueIsOK = false;
if (keyName == "char_conversion")
valueIsOK = (Value == _prologFlags[keyName]);
else if (keyName == "debug")
valueIsOK = (Value == _prologFlags[keyName]);
else if (keyName == "unknown")
valueIsOK = (Value == Atom.a("fail") || Value == Atom.a("warning") ||
Value == Atom.a("error"));
else if (keyName == "double_quotes")
valueIsOK = (Value == Atom.a("codes") || Value == Atom.a("chars") ||
Value == Atom.a("atom"));
else
throw new PrologException
(new Functor3("permission_error", Atom.a("modify"), Atom.a("flag"), Key),
"May not modify Prolog flag " + Key);
if (!valueIsOK)
throw new PrologException
(new Functor2("domain_error", Atom.a("flag_value"), new Functor2("+", Key, Value)),
"May not set arg 1 Key " + Key + " to arg 2 Value " + Value);
_prologFlags[keyName] = Value;
}
/// <summary> /// <summary>
/// script_event calls hosting script with events as a callback method. /// script_event calls hosting script with events as a callback method.
/// </summary> /// </summary>
@ -2303,19 +2538,35 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
private IEnumerator<bool> _enumerator; private IEnumerator<bool> _enumerator;
private PrologException _exception = null; private PrologException _exception = null;
public Catch(IEnumerable<bool> iterator) /// <summary>
/// Call YP.getIterator(Goal, declaringClass) and save the returned iterator.
/// If getIterator throws an exception, save it the same as MoveNext().
/// </summary>
/// <param name="Goal"></param>
/// <param name="declaringClass"></param>
public Catch(object Goal, Type declaringClass)
{ {
_enumerator = iterator.GetEnumerator(); try
{
_enumerator = getIterator(Goal, declaringClass).GetEnumerator();
}
catch (PrologException exception)
{
// MoveNext() will check this.
_exception = exception;
}
} }
/// <summary> /// <summary>
/// Call _enumerator.MoveNext(). If it throws a PrologException, set _exception /// Call _enumerator.MoveNext(). If it throws a PrologException, set _exception
/// and return false. After this returns false, call unifyExceptionOrThrow. /// and return false. After this returns false, call unifyExceptionOrThrow.
/// Assume that, after this returns false, it will not be called again.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public bool MoveNext() public bool MoveNext()
{ {
if (_exception != null)
return false;
try try
{ {
return _enumerator.MoveNext(); return _enumerator.MoveNext();
@ -2372,6 +2623,7 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
public void Dispose() public void Dispose()
{ {
if (_enumerator != null)
_enumerator.Dispose(); _enumerator.Dispose();
} }
@ -2410,5 +2662,40 @@ namespace OpenSim.Region.ScriptEngine.DotNetEngine.Compiler.YieldProlog
#pragma warning restore 0168 #pragma warning restore 0168
} }
} }
/// <summary>
/// CodeListReader extends TextReader and overrides Read to read the next code from
/// the CodeList which is a Prolog list of integer character codes.
/// </summary>
public class CodeListReader : TextReader
{
private object _CodeList;
public CodeListReader(object CodeList)
{
_CodeList = YP.getValue(CodeList);
}
/// <summary>
/// If the head of _CodeList is an integer, return it and advance the list. Otherwise,
/// return -1 for end of file.
/// </summary>
/// <returns></returns>
public override int Read()
{
Functor2 CodeListPair = _CodeList as Functor2;
int code;
if (!(CodeListPair != null && CodeListPair._name == Atom.DOT &&
getInt(CodeListPair._arg1, out code)))
{
_CodeList = Atom.NIL;
return -1;
}
// Advance.
_CodeList = YP.getValue(CodeListPair._arg2);
return code;
}
}
} }
} }

View File

@ -405,8 +405,8 @@ namespace Temporary {
/// <summary> /// <summary>
/// If the functor with name and args can be called directly as determined by /// If the functor with name and args can be called directly as determined by
/// functorCallFunctionName, then call it and return its iterator. If the predicate is /// functorCallFunctionName, then call it and return its iterator. If the predicate is
/// dynamic and undefined, or if static and the method cannot be found, throw /// dynamic and undefined, or if static and the method cannot be found, return
/// a PrologException for existence_error. /// the result of YP.unknownPredicate.
/// This returns null if the functor has a special form than needs to be compiled /// This returns null if the functor has a special form than needs to be compiled
/// (including ,/2 and ;/2). /// (including ,/2 and ;/2).
/// </summary> /// </summary>
@ -424,13 +424,11 @@ namespace Temporary {
{ {
Atom functionNameAtom = ((Atom)FunctionName.getValue()); Atom functionNameAtom = ((Atom)FunctionName.getValue());
if (functionNameAtom == Atom.NIL) if (functionNameAtom == Atom.NIL)
{
// name is for a dynamic predicate. // name is for a dynamic predicate.
return YP.matchDynamic(name, args); return YP.matchDynamic(name, args);
}
// Set the default for the method to call.
string methodName = functionNameAtom._name; string methodName = functionNameAtom._name;
// Set the default for the method to call.
Type methodClass = declaringClass; Type methodClass = declaringClass;
bool checkMode = false; bool checkMode = false;
@ -448,10 +446,8 @@ namespace Temporary {
return null; return null;
if (methodClass == null) if (methodClass == null)
throw new PrologException return YP.unknownPredicate
(new Functor2 (name, args.Length,
(Atom.a("existence_error"), Atom.a("procedure"),
new Functor2(Atom.a("/"), name, args.Length)),
"Cannot find predicate function for: " + name + "/" + args.Length + "Cannot find predicate function for: " + name + "/" + args.Length +
" because declaringClass is null. Set declaringClass to the class containing " + " because declaringClass is null. Set declaringClass to the class containing " +
methodName); methodName);
@ -486,10 +482,8 @@ namespace Temporary {
} }
catch (MissingMethodException) catch (MissingMethodException)
{ {
throw new PrologException return YP.unknownPredicate
(new Functor2 (name, args.Length,
(Atom.a("existence_error"), Atom.a("procedure"),
new Functor2(Atom.a("/"), name, args.Length)),
"Cannot find predicate function " + methodName + " for " + name + "/" + args.Length + "Cannot find predicate function " + methodName + " for " + name + "/" + args.Length +
" in " + methodClass.FullName); " in " + methodClass.FullName);
} }
@ -498,6 +492,54 @@ namespace Temporary {
return null; return null;
} }
/// <summary>
/// Return true if there is a dynamic or static predicate with name and arity.
/// This returns false for built-in predicates.
/// </summary>
/// <param name="name"></param>
/// <param name="arity"></param>
/// <param name="declaringClass">used to resolve references to the default
/// module Atom.a(""). If a declaringClass is needed to resolve the reference but it is
/// null, return false</param>
/// <returns></returns>
public static bool isCurrentPredicate(Atom name, int arity, Type declaringClass)
{
CompilerState state = new CompilerState();
Variable FunctionName = new Variable();
foreach (bool l1 in functorCallFunctionName(state, name, arity, FunctionName))
{
Atom functionNameAtom = ((Atom)FunctionName.getValue());
if (functionNameAtom == Atom.NIL)
// name is for a dynamic predicate.
return YP.isDynamicCurrentPredicate(name, arity);
string methodName = functionNameAtom._name;
if (methodName.StartsWith("YP."))
// current_predicate/1 should fail for built-ins.
return false;
if (methodName.Contains("."))
// We don't support calling inner classes, etc.
return false;
if (declaringClass == null)
return false;
foreach (MemberInfo member in declaringClass.GetMember(methodName))
{
MethodInfo method = member as MethodInfo;
if (method == null)
continue;
if ((method.Attributes | MethodAttributes.Static) == 0)
// Not a static method.
continue;
if (method.GetParameters().Length == arity)
return true;
}
}
return false;
}
// Compiler output follows. // Compiler output follows.
public class YPInnerClass { } public class YPInnerClass { }
@ -567,9 +609,14 @@ namespace Temporary {
CompilerState.assertPred(State, Atom.a("nl"), Atom.a("det")); CompilerState.assertPred(State, Atom.a("nl"), Atom.a("det"));
CompilerState.assertPred(State, new Functor1("write", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det")); CompilerState.assertPred(State, new Functor1("write", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det"));
CompilerState.assertPred(State, new Functor1("put_code", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det")); CompilerState.assertPred(State, new Functor1("put_code", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det"));
CompilerState.assertPred(State, new Functor1("see", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det"));
CompilerState.assertPred(State, Atom.a("seen"), Atom.a("det"));
CompilerState.assertPred(State, new Functor1("tell", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det"));
CompilerState.assertPred(State, Atom.a("told"), Atom.a("det"));
CompilerState.assertPred(State, new Functor1("throw", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det")); CompilerState.assertPred(State, new Functor1("throw", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det"));
CompilerState.assertPred(State, new Functor1("abolish", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det")); CompilerState.assertPred(State, new Functor1("abolish", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det"));
CompilerState.assertPred(State, new Functor1("retractall", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det")); CompilerState.assertPred(State, new Functor1("retractall", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det"));
CompilerState.assertPred(State, new Functor2("set_prolog_flag", new Functor2("::", Atom.a("univ"), Atom.a("in")), new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det"));
CompilerState.assertPred(State, new Functor1("var", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("semidet")); CompilerState.assertPred(State, new Functor1("var", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("semidet"));
CompilerState.assertPred(State, new Functor1("nonvar", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("semidet")); CompilerState.assertPred(State, new Functor1("nonvar", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("semidet"));
CompilerState.assertPred(State, new Functor1("atom", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("semidet")); CompilerState.assertPred(State, new Functor1("atom", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("semidet"));
@ -2121,7 +2168,7 @@ namespace Temporary {
{ {
foreach (bool l3 in YP.unify(arg3, new ListPair(new Functor2("if", new Functor2("call", FunctionName, new ListPair(X1Code, new ListPair(X2Code, Atom.NIL))), BCode), Atom.NIL))) foreach (bool l3 in YP.unify(arg3, new ListPair(new Functor2("if", new Functor2("call", FunctionName, new ListPair(X1Code, new ListPair(X2Code, Atom.NIL))), BCode), Atom.NIL)))
{ {
foreach (bool l4 in YP.univ(A, new ListPair(Name, new ListPair(X1, new ListPair(X2, Atom.NIL))))) foreach (bool l4 in YP.univ(A, ListPair.make(new object[] { Name, X1, X2 })))
{ {
foreach (bool l5 in binaryExpressionConditional(Name, FunctionName)) foreach (bool l5 in binaryExpressionConditional(Name, FunctionName))
{ {
@ -2230,6 +2277,27 @@ namespace Temporary {
} }
} }
} }
{
object State = arg2;
Variable A = new Variable();
Variable B = new Variable();
Variable ATermCode = new Variable();
Variable BCode = new Variable();
foreach (bool l2 in YP.unify(arg1, new Functor2(",", new Functor1("current_predicate", A), B)))
{
foreach (bool l3 in YP.unify(arg3, new ListPair(new Functor2("foreach", new Functor2("call", Atom.a("YP.current_predicate"), new ListPair(ATermCode, new ListPair(new Functor2("call", Atom.a("getDeclaringClass"), Atom.NIL), Atom.NIL))), BCode), Atom.NIL)))
{
foreach (bool l4 in compileTerm(A, State, ATermCode))
{
foreach (bool l5 in compileRuleBody(B, State, BCode))
{
yield return true;
yield break;
}
}
}
}
}
{ {
object State = arg2; object State = arg2;
Variable A = new Variable(); Variable A = new Variable();
@ -2299,7 +2367,7 @@ namespace Temporary {
Variable HandlerAndBCode = new Variable(); Variable HandlerAndBCode = new Variable();
foreach (bool l2 in YP.unify(arg1, new Functor2(",", new Functor3("catch", Goal, Catcher, Handler), B))) foreach (bool l2 in YP.unify(arg1, new Functor2(",", new Functor3("catch", Goal, Catcher, Handler), B)))
{ {
foreach (bool l3 in YP.unify(arg3, new ListPair(new Functor3("declare", Atom.a("YP.Catch"), CatchGoal, new Functor2("new", Atom.a("YP.Catch"), new ListPair(new Functor2("call", Atom.a("YP.getIterator"), new ListPair(GoalTermCode, new ListPair(new Functor2("call", Atom.a("getDeclaringClass"), Atom.NIL), Atom.NIL))), Atom.NIL))), new ListPair(new Functor2("foreach", new Functor1("var", CatchGoal), BCode), new ListPair(new Functor2("foreach", new Functor3("callMember", new Functor1("var", CatchGoal), Atom.a("unifyExceptionOrThrow"), new ListPair(CatcherTermCode, Atom.NIL)), HandlerAndBCode), Atom.NIL))))) foreach (bool l3 in YP.unify(arg3, ListPair.make(new object[] { new Functor3("declare", Atom.a("YP.Catch"), CatchGoal, new Functor2("new", Atom.a("YP.Catch"), new ListPair(GoalTermCode, new ListPair(new Functor2("call", Atom.a("getDeclaringClass"), Atom.NIL), Atom.NIL)))), new Functor2("foreach", new Functor1("var", CatchGoal), BCode), new Functor2("foreach", new Functor3("callMember", new Functor1("var", CatchGoal), Atom.a("unifyExceptionOrThrow"), new ListPair(CatcherTermCode, Atom.NIL)), HandlerAndBCode) })))
{ {
foreach (bool l4 in CompilerState.gensym(State, Atom.a("catchGoal"), CatchGoal)) foreach (bool l4 in CompilerState.gensym(State, Atom.a("catchGoal"), CatchGoal))
{ {
@ -2833,6 +2901,10 @@ namespace Temporary {
{ {
return true; return true;
} }
if (YP.termEqual(Name, Atom.a("current_predicate")))
{
return true;
}
if (YP.termEqual(Name, Atom.a("asserta"))) if (YP.termEqual(Name, Atom.a("asserta")))
{ {
return true; return true;
@ -3015,19 +3087,6 @@ namespace Temporary {
} }
} }
} }
{
foreach (bool l2 in YP.unify(arg1, Atom.a("current_predicate")))
{
foreach (bool l3 in YP.unify(arg2, 1))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("YP.current_predicate")))
{
yield return true;
yield break;
}
}
}
}
{ {
foreach (bool l2 in YP.unify(arg1, Atom.a("atom_length"))) foreach (bool l2 in YP.unify(arg1, Atom.a("atom_length")))
{ {
@ -3213,6 +3272,58 @@ namespace Temporary {
} }
} }
} }
{
foreach (bool l2 in YP.unify(arg1, Atom.a("see")))
{
foreach (bool l3 in YP.unify(arg2, 1))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("YP.see")))
{
yield return true;
yield break;
}
}
}
}
{
foreach (bool l2 in YP.unify(arg1, Atom.a("seen")))
{
foreach (bool l3 in YP.unify(arg2, 0))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("YP.seen")))
{
yield return true;
yield break;
}
}
}
}
{
foreach (bool l2 in YP.unify(arg1, Atom.a("tell")))
{
foreach (bool l3 in YP.unify(arg2, 1))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("YP.tell")))
{
yield return true;
yield break;
}
}
}
}
{
foreach (bool l2 in YP.unify(arg1, Atom.a("told")))
{
foreach (bool l3 in YP.unify(arg2, 0))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("YP.told")))
{
yield return true;
yield break;
}
}
}
}
{ {
foreach (bool l2 in YP.unify(arg1, Atom.a("clause"))) foreach (bool l2 in YP.unify(arg1, Atom.a("clause")))
{ {
@ -3434,6 +3545,110 @@ namespace Temporary {
} }
} }
} }
{
foreach (bool l2 in YP.unify(arg1, Atom.a("current_prolog_flag")))
{
foreach (bool l3 in YP.unify(arg2, 2))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("YP.current_prolog_flag")))
{
yield return true;
yield break;
}
}
}
}
{
foreach (bool l2 in YP.unify(arg1, Atom.a("set_prolog_flag")))
{
foreach (bool l3 in YP.unify(arg2, 2))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("YP.set_prolog_flag")))
{
yield return true;
yield break;
}
}
}
}
{
foreach (bool l2 in YP.unify(arg1, Atom.a("current_input")))
{
foreach (bool l3 in YP.unify(arg2, 1))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("YP.current_input")))
{
yield return true;
yield break;
}
}
}
}
{
foreach (bool l2 in YP.unify(arg1, Atom.a("current_output")))
{
foreach (bool l3 in YP.unify(arg2, 1))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("YP.current_output")))
{
yield return true;
yield break;
}
}
}
}
{
foreach (bool l2 in YP.unify(arg1, Atom.a("read_term")))
{
foreach (bool l3 in YP.unify(arg2, 2))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("Parser.read_term2")))
{
yield return true;
yield break;
}
}
}
}
{
foreach (bool l2 in YP.unify(arg1, Atom.a("read_term")))
{
foreach (bool l3 in YP.unify(arg2, 3))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("Parser.read_term3")))
{
yield return true;
yield break;
}
}
}
}
{
foreach (bool l2 in YP.unify(arg1, Atom.a("read")))
{
foreach (bool l3 in YP.unify(arg2, 1))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("Parser.read1")))
{
yield return true;
yield break;
}
}
}
}
{
foreach (bool l2 in YP.unify(arg1, Atom.a("read")))
{
foreach (bool l3 in YP.unify(arg2, 2))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("Parser.read2")))
{
yield return true;
yield break;
}
}
}
}
} }
public static IEnumerable<bool> compileTerm(object arg1, object arg2, object arg3) public static IEnumerable<bool> compileTerm(object arg1, object arg2, object arg3)
@ -3490,6 +3705,34 @@ namespace Temporary {
{ } { }
} }
} }
{
object State = arg2;
Variable First = new Variable();
Variable Rest = new Variable();
Variable CompiledList = new Variable();
Variable x5 = new Variable();
Variable Rest2 = new Variable();
foreach (bool l2 in YP.unify(arg1, new ListPair(First, Rest)))
{
foreach (bool l3 in YP.unify(arg3, new Functor2("call", Atom.a("ListPair.make"), new ListPair(new Functor1("objectArray", CompiledList), Atom.NIL))))
{
if (YP.nonvar(Rest))
{
foreach (bool l5 in YP.unify(Rest, new ListPair(x5, Rest2)))
{
if (YP.termNotEqual(Rest2, Atom.NIL))
{
foreach (bool l7 in maplist_compileTerm(new ListPair(First, Rest), State, CompiledList))
{
yield return true;
yield break;
}
}
}
}
}
}
}
{ {
object State = arg2; object State = arg2;
Variable First = new Variable(); Variable First = new Variable();
@ -3563,7 +3806,7 @@ namespace Temporary {
{ {
foreach (bool l8 in compileTerm(X2, State, Arg2)) foreach (bool l8 in compileTerm(X2, State, Arg2))
{ {
foreach (bool l9 in YP.unify(Result, new Functor2("new", Atom.a("Functor2"), new ListPair(NameCode, new ListPair(Arg1, new ListPair(Arg2, Atom.NIL)))))) foreach (bool l9 in YP.unify(Result, new Functor2("new", Atom.a("Functor2"), ListPair.make(new object[] { NameCode, Arg1, Arg2 }))))
{ {
yield return true; yield return true;
yield break; yield break;
@ -3572,7 +3815,7 @@ namespace Temporary {
} }
goto cutIf5; goto cutIf5;
} }
foreach (bool l6 in YP.unify(TermArgs, new ListPair(X1, new ListPair(X2, new ListPair(X3, Atom.NIL))))) foreach (bool l6 in YP.unify(TermArgs, ListPair.make(new object[] { X1, X2, X3 })))
{ {
foreach (bool l7 in compileTerm(X1, State, Arg1)) foreach (bool l7 in compileTerm(X1, State, Arg1))
{ {
@ -3580,7 +3823,7 @@ namespace Temporary {
{ {
foreach (bool l9 in compileTerm(X3, State, Arg3)) foreach (bool l9 in compileTerm(X3, State, Arg3))
{ {
foreach (bool l10 in YP.unify(Result, new Functor2("new", Atom.a("Functor3"), new ListPair(NameCode, new ListPair(Arg1, new ListPair(Arg2, new ListPair(Arg3, Atom.NIL))))))) foreach (bool l10 in YP.unify(Result, new Functor2("new", Atom.a("Functor3"), ListPair.make(new object[] { NameCode, Arg1, Arg2, Arg3 }))))
{ {
yield return true; yield return true;
yield break; yield break;
@ -3623,7 +3866,7 @@ namespace Temporary {
{ {
foreach (bool l7 in compileTerm(X2, State, Arg2)) foreach (bool l7 in compileTerm(X2, State, Arg2))
{ {
foreach (bool l8 in YP.unify(Result, new Functor2("new", Atom.a("Functor2"), new ListPair(NameCode, new ListPair(Arg1, new ListPair(Arg2, Atom.NIL)))))) foreach (bool l8 in YP.unify(Result, new Functor2("new", Atom.a("Functor2"), ListPair.make(new object[] { NameCode, Arg1, Arg2 }))))
{ {
yield return true; yield return true;
yield break; yield break;
@ -3632,7 +3875,7 @@ namespace Temporary {
} }
goto cutIf7; goto cutIf7;
} }
foreach (bool l5 in YP.unify(TermArgs, new ListPair(X1, new ListPair(X2, new ListPair(X3, Atom.NIL))))) foreach (bool l5 in YP.unify(TermArgs, ListPair.make(new object[] { X1, X2, X3 })))
{ {
foreach (bool l6 in compileTerm(X1, State, Arg1)) foreach (bool l6 in compileTerm(X1, State, Arg1))
{ {
@ -3640,7 +3883,7 @@ namespace Temporary {
{ {
foreach (bool l8 in compileTerm(X3, State, Arg3)) foreach (bool l8 in compileTerm(X3, State, Arg3))
{ {
foreach (bool l9 in YP.unify(Result, new Functor2("new", Atom.a("Functor3"), new ListPair(NameCode, new ListPair(Arg1, new ListPair(Arg2, new ListPair(Arg3, Atom.NIL))))))) foreach (bool l9 in YP.unify(Result, new Functor2("new", Atom.a("Functor3"), ListPair.make(new object[] { NameCode, Arg1, Arg2, Arg3 }))))
{ {
yield return true; yield return true;
yield break; yield break;
@ -3725,9 +3968,11 @@ namespace Temporary {
{ {
foreach (bool l3 in YP.unify(arg3, new ListPair(FirstResult, RestResults))) foreach (bool l3 in YP.unify(arg3, new ListPair(FirstResult, RestResults)))
{ {
foreach (bool l4 in compileTerm(First, State, FirstResult)) if (YP.nonvar(Rest))
{ {
foreach (bool l5 in maplist_compileTerm(Rest, State, RestResults)) foreach (bool l5 in compileTerm(First, State, FirstResult))
{
foreach (bool l6 in maplist_compileTerm(Rest, State, RestResults))
{ {
yield return true; yield return true;
yield break; yield break;
@ -3737,6 +3982,7 @@ namespace Temporary {
} }
} }
} }
}
public static IEnumerable<bool> compileExpression(object Term, object State, object Result) public static IEnumerable<bool> compileExpression(object Term, object State, object Result)
{ {

View File

@ -113,6 +113,10 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
} }
} }
// disable warning on l1, don't see how we can
// code this differently
#pragma warning disable 0168
/// <summary> /// <summary>
/// For each result, unify the _freeVariables and unify bagArrayVariable with the associated bag. /// For each result, unify the _freeVariables and unify bagArrayVariable with the associated bag.
/// </summary> /// </summary>
@ -127,27 +131,19 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
// No unbound free variables, so we only filled one bag. If empty, bagof fails. // No unbound free variables, so we only filled one bag. If empty, bagof fails.
if (_findallBagArray.Count > 0) if (_findallBagArray.Count > 0)
{ {
// disable warning: don't see how we can code this differently short
// of rewriting the whole thing
#pragma warning disable 0168
foreach (bool l1 in bagArrayVariable.unify(_findallBagArray)) foreach (bool l1 in bagArrayVariable.unify(_findallBagArray))
yield return false; yield return false;
#pragma warning restore 0168
} }
} }
else else
{ {
foreach (KeyValuePair<object[], List<object>> valuesAndBag in _bagForFreeVariables) foreach (KeyValuePair<object[], List<object>> valuesAndBag in _bagForFreeVariables)
{ {
// disable warning: don't see how we can code this differently short
// of rewriting the whole thing
#pragma warning disable 0168
foreach (bool l1 in YP.unifyArrays(_freeVariables, valuesAndBag.Key)) foreach (bool l1 in YP.unifyArrays(_freeVariables, valuesAndBag.Key))
{ {
foreach (bool l2 in bagArrayVariable.unify(valuesAndBag.Value)) foreach (bool l2 in bagArrayVariable.unify(valuesAndBag.Value))
yield return false; yield return false;
} }
#pragma warning restore 0168
// Debug: Should we free memory of the answers already returned? // Debug: Should we free memory of the answers already returned?
} }
} }
@ -161,15 +157,11 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
public IEnumerable<bool> result(object Bag) public IEnumerable<bool> result(object Bag)
{ {
Variable bagArrayVariable = new Variable(); Variable bagArrayVariable = new Variable();
// disable warning: don't see how we can code this differently short
// of rewriting the whole thing
#pragma warning disable 0168
foreach (bool l1 in resultArray(bagArrayVariable)) foreach (bool l1 in resultArray(bagArrayVariable))
{ {
foreach (bool l2 in YP.unify(Bag, ListPair.make((List<object>)bagArrayVariable.getValue()))) foreach (bool l2 in YP.unify(Bag, ListPair.make((List<object>)bagArrayVariable.getValue())))
yield return false; yield return false;
} }
#pragma warning restore 0168
} }
/// <summary> /// <summary>
@ -181,9 +173,6 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
public IEnumerable<bool> resultSet(object Bag) public IEnumerable<bool> resultSet(object Bag)
{ {
Variable bagArrayVariable = new Variable(); Variable bagArrayVariable = new Variable();
// disable warning: don't see how we can code this differently short
// of rewriting the whole thing
#pragma warning disable 0168
foreach (bool l1 in resultArray(bagArrayVariable)) foreach (bool l1 in resultArray(bagArrayVariable))
{ {
List<object> bagArray = (List<object>)bagArrayVariable.getValue(); List<object> bagArray = (List<object>)bagArrayVariable.getValue();
@ -191,19 +180,14 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
foreach (bool l2 in YP.unify(Bag, ListPair.makeWithoutRepeatedTerms(bagArray))) foreach (bool l2 in YP.unify(Bag, ListPair.makeWithoutRepeatedTerms(bagArray)))
yield return false; yield return false;
} }
#pragma warning restore 0168
} }
public static IEnumerable<bool> bagofArray public static IEnumerable<bool> bagofArray
(object Template, object Goal, IEnumerable<bool> goalIterator, Variable bagArrayVariable) (object Template, object Goal, IEnumerable<bool> goalIterator, Variable bagArrayVariable)
{ {
BagofAnswers bagOfAnswers = new BagofAnswers(Template, Goal); BagofAnswers bagOfAnswers = new BagofAnswers(Template, Goal);
// disable warning: don't see how we can code this differently short
// of rewriting the whole thing
#pragma warning disable 0168
foreach (bool l1 in goalIterator) foreach (bool l1 in goalIterator)
bagOfAnswers.add(); bagOfAnswers.add();
#pragma warning restore 0168
return bagOfAnswers.resultArray(bagArrayVariable); return bagOfAnswers.resultArray(bagArrayVariable);
} }
@ -211,12 +195,8 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
(object Template, object Goal, IEnumerable<bool> goalIterator, object Bag) (object Template, object Goal, IEnumerable<bool> goalIterator, object Bag)
{ {
BagofAnswers bagOfAnswers = new BagofAnswers(Template, Goal); BagofAnswers bagOfAnswers = new BagofAnswers(Template, Goal);
// disable warning: don't see how we can code this differently short
// of rewriting the whole thing
#pragma warning disable 0168
foreach (bool l1 in goalIterator) foreach (bool l1 in goalIterator)
bagOfAnswers.add(); bagOfAnswers.add();
#pragma warning restore 0168
return bagOfAnswers.result(Bag); return bagOfAnswers.result(Bag);
} }
@ -224,14 +204,11 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
(object Template, object Goal, IEnumerable<bool> goalIterator, object Bag) (object Template, object Goal, IEnumerable<bool> goalIterator, object Bag)
{ {
BagofAnswers bagOfAnswers = new BagofAnswers(Template, Goal); BagofAnswers bagOfAnswers = new BagofAnswers(Template, Goal);
// disable warning: don't see how we can code this differently short
// of rewriting the whole thing
#pragma warning disable 0168
foreach (bool l1 in goalIterator) foreach (bool l1 in goalIterator)
bagOfAnswers.add(); bagOfAnswers.add();
#pragma warning restore 0168
return bagOfAnswers.resultSet(Bag); return bagOfAnswers.resultSet(Bag);
} }
#pragma warning restore 0168
/// <summary> /// <summary>
/// A TermArrayEqualityComparer implements IEqualityComparer to compare two object arrays using YP.termEqual. /// A TermArrayEqualityComparer implements IEqualityComparer to compare two object arrays using YP.termEqual.

View File

@ -71,6 +71,10 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
return YP.unify(Bag, result); return YP.unify(Bag, result);
} }
// disable warning on l1, don't see how we can
// code this differently
#pragma warning disable 0168
/// <summary> /// <summary>
/// This is a simplified findall when the goal is a single call. /// This is a simplified findall when the goal is a single call.
/// </summary> /// </summary>
@ -81,12 +85,8 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
public static IEnumerable<bool> findall(object Template, IEnumerable<bool> goal, object Bag) public static IEnumerable<bool> findall(object Template, IEnumerable<bool> goal, object Bag)
{ {
FindallAnswers findallAnswers = new FindallAnswers(Template); FindallAnswers findallAnswers = new FindallAnswers(Template);
// disable warning on l1, don't see how we can
// code this differently
#pragma warning disable 0168
foreach (bool l1 in goal) foreach (bool l1 in goal)
findallAnswers.add(); findallAnswers.add();
#pragma warning restore 0168
return findallAnswers.result(Bag); return findallAnswers.result(Bag);
} }
@ -99,13 +99,10 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
public static List<object> findallArray(object Template, IEnumerable<bool> goal) public static List<object> findallArray(object Template, IEnumerable<bool> goal)
{ {
FindallAnswers findallAnswers = new FindallAnswers(Template); FindallAnswers findallAnswers = new FindallAnswers(Template);
// disable warning on l1, don't see how we can
// code this differently
#pragma warning disable 0168
foreach (bool l1 in goal) foreach (bool l1 in goal)
findallAnswers.add(); findallAnswers.add();
#pragma warning restore 0168
return findallAnswers.resultArray(); return findallAnswers.resultArray();
} }
#pragma warning restore 0168
} }
} }

View File

@ -98,6 +98,14 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
return make(Atom.a(name), args); return make(Atom.a(name), args);
} }
/// <summary>
/// If arg is another Functor, then succeed (yield once) if this and arg have the
/// same name and all functor args unify, otherwise fail (don't yield).
/// If arg is a Variable, then call its unify to unify with this.
/// Otherwise fail (don't yield).
/// </summary>
/// <param name="arg"></param>
/// <returns></returns>
public IEnumerable<bool> unify(object arg) public IEnumerable<bool> unify(object arg)
{ {
arg = YP.getValue(arg); arg = YP.getValue(arg);

View File

@ -49,6 +49,17 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
{ {
} }
// disable warning on l1, don't see how we can
// code this differently
#pragma warning disable 0168
/// <summary>
/// If arg is another Functor1, then succeed (yield once) if this and arg have the
/// same name and the functor args unify, otherwise fail (don't yield).
/// If arg is a Variable, then call its unify to unify with this.
/// Otherwise fail (don't yield).
/// </summary>
/// <param name="arg"></param>
/// <returns></returns>
public IEnumerable<bool> unify(object arg) public IEnumerable<bool> unify(object arg)
{ {
arg = YP.getValue(arg); arg = YP.getValue(arg);
@ -57,25 +68,18 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
Functor1 argFunctor = (Functor1)arg; Functor1 argFunctor = (Functor1)arg;
if (_name.Equals(argFunctor._name)) if (_name.Equals(argFunctor._name))
{ {
// disable warning on l1, don't see how we can
// code this differently
#pragma warning disable 0168
foreach (bool l1 in YP.unify(_arg1, argFunctor._arg1)) foreach (bool l1 in YP.unify(_arg1, argFunctor._arg1))
yield return false; yield return false;
#pragma warning restore 0168
} }
} }
else if (arg is Variable) else if (arg is Variable)
{ {
// disable warning on l1, don't see how we can
// code this differently
#pragma warning disable 0168
foreach (bool l1 in ((Variable)arg).unify(this)) foreach (bool l1 in ((Variable)arg).unify(this))
yield return false; yield return false;
#pragma warning restore 0168
} }
} }
#pragma warning restore 0168
public override string ToString() public override string ToString()
{ {

View File

@ -51,6 +51,13 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
{ {
} }
// disable warning on l1, don't see how we can
// code this differently
#pragma warning disable 0168
/// If arg is another Functor2, then succeed (yield once) if this and arg have the
/// same name and all functor args unify, otherwise fail (don't yield).
/// If arg is a Variable, then call its unify to unify with this.
/// Otherwise fail (don't yield).
public IEnumerable<bool> unify(object arg) public IEnumerable<bool> unify(object arg)
{ {
arg = YP.getValue(arg); arg = YP.getValue(arg);
@ -59,27 +66,21 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
Functor2 argFunctor = (Functor2)arg; Functor2 argFunctor = (Functor2)arg;
if (_name.Equals(argFunctor._name)) if (_name.Equals(argFunctor._name))
{ {
// disable warning: don't see how we can code this differently short
// of rewriting the whole thing
#pragma warning disable 0168
foreach (bool l1 in YP.unify(_arg1, argFunctor._arg1)) foreach (bool l1 in YP.unify(_arg1, argFunctor._arg1))
{ {
foreach (bool l2 in YP.unify(_arg2, argFunctor._arg2)) foreach (bool l2 in YP.unify(_arg2, argFunctor._arg2))
yield return false; yield return false;
} }
#pragma warning restore 0168
} }
} }
else if (arg is Variable) else if (arg is Variable)
{ {
// disable warning: don't see how we can code this differently short
// of rewriting the whole thing
#pragma warning disable 0168
foreach (bool l1 in ((Variable)arg).unify(this)) foreach (bool l1 in ((Variable)arg).unify(this))
yield return false; yield return false;
#pragma warning restore 0168
} }
} }
#pragma warning restore 0168
public override string ToString() public override string ToString()
{ {

View File

@ -53,6 +53,13 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
{ {
} }
// disable warning on l1, don't see how we can
// code this differently
#pragma warning disable 0168
/// If arg is another Functor3, then succeed (yield once) if this and arg have the
/// same name and all functor args unify, otherwise fail (don't yield).
/// If arg is a Variable, then call its unify to unify with this.
/// Otherwise fail (don't yield).
public IEnumerable<bool> unify(object arg) public IEnumerable<bool> unify(object arg)
{ {
arg = YP.getValue(arg); arg = YP.getValue(arg);
@ -61,9 +68,6 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
Functor3 argFunctor = (Functor3)arg; Functor3 argFunctor = (Functor3)arg;
if (_name.Equals(argFunctor._name)) if (_name.Equals(argFunctor._name))
{ {
// disable warning: don't see how we can code this differently short
// of rewriting the whole thing
#pragma warning disable 0168
foreach (bool l1 in YP.unify(_arg1, argFunctor._arg1)) foreach (bool l1 in YP.unify(_arg1, argFunctor._arg1))
{ {
foreach (bool l2 in YP.unify(_arg2, argFunctor._arg2)) foreach (bool l2 in YP.unify(_arg2, argFunctor._arg2))
@ -72,19 +76,15 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
yield return false; yield return false;
} }
} }
#pragma warning restore 0168
} }
} }
else if (arg is Variable) else if (arg is Variable)
{ {
// disable warning: don't see how we can code this differently short
// of rewriting the whole thing
#pragma warning disable 0168
foreach (bool l1 in ((Variable)arg).unify(this)) foreach (bool l1 in ((Variable)arg).unify(this))
yield return false; yield return false;
#pragma warning restore 0168
} }
} }
#pragma warning restore 0168
public override string ToString() public override string ToString()
{ {

View File

@ -270,8 +270,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
throw new PrologException("instantiation_error", "Head is an unbound variable"); throw new PrologException("instantiation_error", "Head is an unbound variable");
object[] arguments = YP.getFunctorArgs(Head); object[] arguments = YP.getFunctorArgs(Head);
// We always match Head from _allAnswers, and the Body is // We always match Head from _allAnswers, and the Body is Atom.a("true").
// Atom.a("true").
#pragma warning disable 0168 #pragma warning disable 0168
foreach (bool l1 in YP.unify(Body, Atom.a("true"))) foreach (bool l1 in YP.unify(Body, Atom.a("true")))
{ {

View File

@ -132,6 +132,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
/// <summary> /// <summary>
/// Return an array of the elements in list or null if it is not /// Return an array of the elements in list or null if it is not
/// a proper list. If list is Atom.NIL, return an array of zero elements. /// a proper list. If list is Atom.NIL, return an array of zero elements.
/// If the list or one of the tails of the list is Variable, raise an instantiation_error.
/// This does not call YP.getValue on each element. /// This does not call YP.getValue on each element.
/// </summary> /// </summary>
/// <param name="list"></param> /// <param name="list"></param>
@ -143,10 +144,19 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
return new object[0]; return new object[0];
List<object> result = new List<object>(); List<object> result = new List<object>();
for (object element = list; object element = list;
element is Functor2 && ((Functor2)element)._name == Atom.DOT; while (true) {
element = YP.getValue(((Functor2)element)._arg2)) if (element == Atom.NIL)
break;
if (element is Variable)
throw new PrologException(Atom.a("instantiation_error"),
"List tail is an unbound variable");
if (!(element is Functor2 && ((Functor2)element)._name == Atom.DOT))
// Not a proper list.
return null;
result.Add(((Functor2)element)._arg1); result.Add(((Functor2)element)._arg1);
element = YP.getValue(((Functor2)element)._arg2);
}
if (result.Count <= 0) if (result.Count <= 0)
return null; return null;

View File

@ -43,6 +43,10 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
bool ground(); bool ground();
} }
/// <summary>
/// A Variable is passed to a function so that it can be unified with
/// value or another Variable. See getValue and unify for details.
/// </summary>
public class Variable : IUnifiable public class Variable : IUnifiable
{ {
// Use _isBound separate from _value so that it can be bound to any value, // Use _isBound separate from _value so that it can be bound to any value,
@ -50,6 +54,14 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
private bool _isBound = false; private bool _isBound = false;
private object _value; private object _value;
/// <summary>
/// If this Variable is unbound, then just return this Variable.
/// Otherwise, if this has been bound to a value with unify, return the value.
/// If the bound value is another Variable, this follows the "variable chain"
/// to the end and returns the final value, or the final Variable if it is unbound.
/// For more details, see http://yieldprolog.sourceforge.net/tutorial1.html
/// </summary>
/// <returns></returns>
public object getValue() public object getValue()
{ {
if (!_isBound) if (!_isBound)
@ -68,6 +80,16 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
return result; return result;
} }
/// <summary>
/// If this Variable is bound, then just call YP.unify to unify this with arg.
/// (Note that if arg is an unbound Variable, then YP.unify will bind it to
/// this Variable's value.)
/// Otherwise, bind this Variable to YP.getValue(arg) and yield once. After the
/// yield, return this Variable to the unbound state.
/// For more details, see http://yieldprolog.sourceforge.net/tutorial1.html
/// </summary>
/// <param name="arg"></param>
/// <returns></returns>
public IEnumerable<bool> unify(object arg) public IEnumerable<bool> unify(object arg)
{ {
if (!_isBound) if (!_isBound)
@ -92,12 +114,12 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
} }
else else
{ {
// disable warning: don't see how we can code this differently short // disable warning on l1, don't see how we can
// of rewriting the whole thing // code this differently
#pragma warning disable 0168 #pragma warning disable 0168
foreach (bool l1 in YP.unify(this, arg)) foreach (bool l1 in YP.unify(this, arg))
yield return false; yield return false;
#pragma warning restore 0168 #pragma warning restore 0168
} }
} }
@ -105,7 +127,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
{ {
object value = getValue(); object value = getValue();
if (value == this) if (value == this)
return "Variable"; return "_Variable";
else else
return getValue().ToString(); return getValue().ToString();
} }

View File

@ -52,6 +52,8 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
private static TextWriter _outputStream = System.Console.Out; private static TextWriter _outputStream = System.Console.Out;
private static TextReader _inputStream = System.Console.In; private static TextReader _inputStream = System.Console.In;
private static IndexedAnswers _operatorTable = null; private static IndexedAnswers _operatorTable = null;
private static Dictionary<string, object> _prologFlags = new Dictionary<string, object>();
public const int MAX_ARITY = 255;
/// <summary> /// <summary>
/// An IClause is used so that dynamic predicates can call match. /// An IClause is used so that dynamic predicates can call match.
@ -62,6 +64,16 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
IEnumerable<bool> clause(object Head, object Body); IEnumerable<bool> clause(object Head, object Body);
} }
/// <summary>
/// If value is a Variable, then return its getValue. Otherwise, just
/// return value. You should call YP.getValue on any object that
/// may be a Variable to get the value to pass to other functions in
/// your system that are not part of Yield Prolog, such as math functions
/// or file I/O.
/// For more details, see http://yieldprolog.sourceforge.net/tutorial1.html
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static object getValue(object value) public static object getValue(object value)
{ {
if (value is Variable) if (value is Variable)
@ -70,6 +82,17 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
return value; return value;
} }
/// <summary>
/// If arg1 or arg2 is an object with a unify method (such as Variable or
/// Functor) then just call its unify with the other argument. The object's
/// unify method will bind the values or check for equals as needed.
/// Otherwise, both arguments are "normal" (atomic) values so if they
/// are equal then succeed (yield once), else fail (don't yield).
/// For more details, see http://yieldprolog.sourceforge.net/tutorial1.html
/// </summary>
/// <param name="arg1"></param>
/// <param name="arg2"></param>
/// <returns></returns>
public static IEnumerable<bool> unify(object arg1, object arg2) public static IEnumerable<bool> unify(object arg1, object arg2)
{ {
arg1 = getValue(arg1); arg1 = getValue(arg1);
@ -622,6 +645,10 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
if (args.Length == 0) if (args.Length == 0)
// Return the Name, even if it is not an Atom. // Return the Name, even if it is not an Atom.
return YP.unify(Term, Name); return YP.unify(Term, Name);
if (args.Length > MAX_ARITY)
throw new PrologException
(new Functor1("representation_error", Atom.a("max_arity")),
"Functor arity " + args.Length + " may not be greater than " + MAX_ARITY);
if (!atom(Name)) if (!atom(Name))
throw new PrologException throw new PrologException
(new Functor2("type_error", Atom.a("atom"), Name), (new Functor2("type_error", Atom.a("atom"), Name),
@ -666,6 +693,10 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
} }
else else
{ {
if ((int)Arity > MAX_ARITY)
throw new PrologException
(new Functor1("representation_error", Atom.a("max_arity")),
"Functor arity " + Arity + " may not be greater than " + MAX_ARITY);
if (!(FunctorName is Atom)) if (!(FunctorName is Atom))
throw new PrologException throw new PrologException
(new Functor2("type_error", Atom.a("atom"), FunctorName), "FunctorName is not an atom"); (new Functor2("type_error", Atom.a("atom"), FunctorName), "FunctorName is not an atom");
@ -903,8 +934,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
_operatorTable.addAnswer(new object[] { 20, Atom.a("xfx"), Atom.a("<--") }); _operatorTable.addAnswer(new object[] { 20, Atom.a("xfx"), Atom.a("<--") });
} }
foreach (bool l1 in _operatorTable.match(new object[] { Priority, Specifier, Operator })) return _operatorTable.match(new object[] { Priority, Specifier, Operator });
yield return false;
} }
public static IEnumerable<bool> atom_length(object atom, object Length) public static IEnumerable<bool> atom_length(object atom, object Length)
@ -1491,9 +1521,22 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
return Term is Functor1 || Term is Functor2 || Term is Functor3 || Term is Functor; return Term is Functor1 || Term is Functor2 || Term is Functor3 || Term is Functor;
} }
/// <summary>
/// If input is a TextReader, use it. If input is an Atom or String, create a StreamReader with the
/// input as the filename. If input is a Prolog list, then read character codes from it.
/// </summary>
/// <param name="input"></param>
public static void see(object input) public static void see(object input)
{ {
input = YP.getValue(input); input = YP.getValue(input);
if (input is Variable)
throw new PrologException(Atom.a("instantiation_error"), "Arg is an unbound variable");
if (input == null)
{
_inputStream = null;
return;
}
if (input is TextReader) if (input is TextReader)
{ {
_inputStream = (TextReader)input; _inputStream = (TextReader)input;
@ -1509,21 +1552,48 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
_inputStream = new StreamReader((String)input); _inputStream = new StreamReader((String)input);
return; return;
} }
else if (input is Functor2 && ((Functor2)input)._name == Atom.DOT)
{
_inputStream = new CodeListReader(input);
return;
}
else else
throw new InvalidOperationException("Can't open stream for " + input); throw new PrologException
(new Functor2("domain_error", Atom.a("stream_or_alias"), input),
"Input stream specifier not recognized");
} }
public static void seen() public static void seen()
{ {
if (_inputStream == null)
return;
if (_inputStream == Console.In) if (_inputStream == Console.In)
return; return;
_inputStream.Close(); _inputStream.Close();
_inputStream = Console.In; _inputStream = Console.In;
} }
public static IEnumerable<bool> current_input(object Stream)
{
return YP.unify(Stream, _inputStream);
}
/// <summary>
/// If output is a TextWriter, use it. If output is an Atom or a String, create a StreamWriter
/// with the input as the filename.
/// </summary>
/// <param name="output"></param>
public static void tell(object output) public static void tell(object output)
{ {
output = YP.getValue(output); output = YP.getValue(output);
if (output is Variable)
throw new PrologException(Atom.a("instantiation_error"), "Arg is an unbound variable");
if (output == null)
{
_outputStream = null;
return;
}
if (output is TextWriter) if (output is TextWriter)
{ {
_outputStream = (TextWriter)output; _outputStream = (TextWriter)output;
@ -1540,11 +1610,15 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
return; return;
} }
else else
throw new InvalidOperationException("Can't open stream for " + output); throw new PrologException
(new Functor2("domain_error", Atom.a("stream_or_alias"), output),
"Can't open stream for " + output);
} }
public static void told() public static void told()
{ {
if (_outputStream == null)
return;
if (_outputStream == Console.Out) if (_outputStream == Console.Out)
return; return;
_outputStream.Close(); _outputStream.Close();
@ -1558,6 +1632,8 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
public static void write(object x) public static void write(object x)
{ {
if (_outputStream == null)
return;
x = YP.getValue(x); x = YP.getValue(x);
if (x is double) if (x is double)
_outputStream.Write(doubleToString((double)x)); _outputStream.Write(doubleToString((double)x));
@ -1591,6 +1667,8 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
public static void put_code(object x) public static void put_code(object x)
{ {
if (_outputStream == null)
return;
if (var(x)) if (var(x))
throw new PrologException(Atom.a("instantiation_error"), "Arg 1 is an unbound variable"); throw new PrologException(Atom.a("instantiation_error"), "Arg 1 is an unbound variable");
int xInt; int xInt;
@ -1602,11 +1680,16 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
public static void nl() public static void nl()
{ {
if (_outputStream == null)
return;
_outputStream.WriteLine(); _outputStream.WriteLine();
} }
public static IEnumerable<bool> get_code(object code) public static IEnumerable<bool> get_code(object code)
{ {
if (_inputStream == null)
return YP.unify(code, -1);
else
return YP.unify(code, _inputStream.Read()); return YP.unify(code, _inputStream.Read());
} }
@ -1763,7 +1846,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
/// <summary> /// <summary>
/// Match all clauses of the dynamic predicate with the name and with arity /// Match all clauses of the dynamic predicate with the name and with arity
/// arguments.Length. /// arguments.Length.
/// It is an error if the predicate is not defined. /// If the predicate is not defined, return the result of YP.unknownPredicate.
/// </summary> /// </summary>
/// <param name="name">must be an Atom</param> /// <param name="name">must be an Atom</param>
/// <param name="arguments">an array of arity number of arguments</param> /// <param name="arguments">an array of arity number of arguments</param>
@ -1772,11 +1855,8 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
{ {
List<IClause> clauses; List<IClause> clauses;
if (!_predicatesStore.TryGetValue(new NameArity(name, arguments.Length), out clauses)) if (!_predicatesStore.TryGetValue(new NameArity(name, arguments.Length), out clauses))
throw new PrologException return unknownPredicate(name, arguments.Length,
(new Functor2 "Undefined dynamic predicate: " + name + "/" + arguments.Length);
(Atom.a("existence_error"), Atom.a("procedure"),
new Functor2(Atom.SLASH, name, arguments.Length)),
"Undefined predicate: " + name + "/" + arguments.Length);
if (clauses.Count == 1) if (clauses.Count == 1)
// Usually there is only one clause, so return it without needing to wrap it in an iterator. // Usually there is only one clause, so return it without needing to wrap it in an iterator.
@ -1808,6 +1888,34 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
} }
} }
/// <summary>
/// If _prologFlags["unknown"] is fail then return fail(), else if
/// _prologFlags["unknown"] is warning then write the message to YP.write and
/// return fail(), else throw a PrologException for existence_error. .
/// </summary>
/// <param name="name"></param>
/// <param name="arity"></param>
/// <param name="message"></param>
/// <returns></returns>
public static IEnumerable<bool> unknownPredicate(Atom name, int arity, string message)
{
establishPrologFlags();
if (_prologFlags["unknown"] == Atom.a("fail"))
return fail();
else if (_prologFlags["unknown"] == Atom.a("warning"))
{
write(message);
nl();
return fail();
}
else
throw new PrologException
(new Functor2
(Atom.a("existence_error"), Atom.a("procedure"),
new Functor2(Atom.SLASH, name, arity)), message);
}
/// <summary> /// <summary>
/// This is deprecated and just calls matchDynamic. This matches all clauses, /// This is deprecated and just calls matchDynamic. This matches all clauses,
/// not just the ones defined with assertFact. /// not just the ones defined with assertFact.
@ -1951,7 +2059,17 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
_predicatesStore[nameArity] = new List<IClause>(); _predicatesStore[nameArity] = new List<IClause>();
} }
public static IEnumerable<bool> current_predicate(object NameSlashArity) /// <summary>
/// If NameSlashArity is var, match with all the dynamic predicates using the
/// Name/Artity form.
/// If NameSlashArity is not var, check if the Name/Arity exists as a static or
/// dynamic predicate.
/// </summary>
/// <param name="NameSlashArity"></param>
/// <param name="declaringClass">if not null, used to resolve references to the default
/// module Atom.a("")</param>
/// <returns></returns>
public static IEnumerable<bool> current_predicate(object NameSlashArity, Type declaringClass)
{ {
NameSlashArity = YP.getValue(NameSlashArity); NameSlashArity = YP.getValue(NameSlashArity);
// First check if Name and Arity are nonvar so we can do a direct lookup. // First check if Name and Arity are nonvar so we can do a direct lookup.
@ -1976,7 +2094,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
(new Functor2("domain_error", Atom.a("not_less_than_zero"), arity), (new Functor2("domain_error", Atom.a("not_less_than_zero"), arity),
"Arity may not be less than zero"); "Arity may not be less than zero");
if (_predicatesStore.ContainsKey(new NameArity((Atom)name, (int)arity))) if (YPCompiler.isCurrentPredicate((Atom)name, (int)arity, declaringClass))
// The predicate is defined. // The predicate is defined.
yield return false; yield return false;
} }
@ -1991,6 +2109,18 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
} }
} }
/// <summary>
/// Return true if the dynamic predicate store has an entry for the predicate
/// with name and arity.
/// </summary>
/// <param name="name"></param>
/// <param name="arity"></param>
/// <returns></returns>
public static bool isDynamicCurrentPredicate(Atom name, int arity)
{
return _predicatesStore.ContainsKey(new NameArity(name, arity));
}
public static void abolish(object NameSlashArity) public static void abolish(object NameSlashArity)
{ {
NameSlashArity = YP.getValue(NameSlashArity); NameSlashArity = YP.getValue(NameSlashArity);
@ -2019,6 +2149,10 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
throw new PrologException throw new PrologException
(new Functor2("domain_error", Atom.a("not_less_than_zero"), arity), (new Functor2("domain_error", Atom.a("not_less_than_zero"), arity),
"Arity may not be less than zero"); "Arity may not be less than zero");
if ((int)arity > MAX_ARITY)
throw new PrologException
(new Functor1("representation_error", Atom.a("max_arity")),
"Arity may not be greater than " + MAX_ARITY);
if (isSystemPredicate((Atom)name, (int)arity)) if (isSystemPredicate((Atom)name, (int)arity))
throw new PrologException throw new PrologException
@ -2077,7 +2211,108 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
{ {
throw new PrologException(Term); throw new PrologException(Term);
} }
/// <summary>
/// This must be called by any function that uses YP._prologFlags to make sure
/// the initial defaults are loaded.
/// </summary>
private static void establishPrologFlags()
{
if (_prologFlags.Count > 0)
// Already established.
return;
// List these in the order they appear in the ISO standard.
_prologFlags["bounded"] = Atom.a("true");
_prologFlags["max_integer"] = Int32.MaxValue;
_prologFlags["min_integer"] = Int32.MinValue;
_prologFlags["integer_rounding_function"] = Atom.a("toward_zero");
_prologFlags["char_conversion"] = Atom.a("off");
_prologFlags["debug"] = Atom.a("off");
_prologFlags["max_arity"] = MAX_ARITY;
_prologFlags["unknown"] = Atom.a("error");
_prologFlags["double_quotes"] = Atom.a("codes");
}
public static IEnumerable<bool> current_prolog_flag(object Key, object Value)
{
establishPrologFlags();
Key = YP.getValue(Key);
Value = YP.getValue(Value);
if (Key is Variable)
{
// Bind all key values.
foreach (string key in _prologFlags.Keys)
{
foreach (bool l1 in YP.unify(Key, Atom.a(key)))
{
foreach (bool l2 in YP.unify(Value, _prologFlags[key]))
yield return false;
}
}
}
else
{
if (!(Key is Atom))
throw new PrologException
(new Functor2("type_error", Atom.a("atom"), Key), "Arg 1 Key is not an atom");
if (!_prologFlags.ContainsKey(((Atom)Key)._name))
throw new PrologException
(new Functor2("domain_error", Atom.a("prolog_flag"), Key),
"Arg 1 Key is not a recognized flag");
foreach (bool l1 in YP.unify(Value, _prologFlags[((Atom)Key)._name]))
yield return false;
}
}
public static void set_prolog_flag(object Key, object Value)
{
establishPrologFlags();
Key = YP.getValue(Key);
Value = YP.getValue(Value);
if (Key is Variable)
throw new PrologException(Atom.a("instantiation_error"),
"Arg 1 Key is an unbound variable");
if (Value is Variable)
throw new PrologException(Atom.a("instantiation_error"),
"Arg 1 Key is an unbound variable");
if (!(Key is Atom))
throw new PrologException
(new Functor2("type_error", Atom.a("atom"), Key), "Arg 1 Key is not an atom");
string keyName = ((Atom)Key)._name;
if (!_prologFlags.ContainsKey(keyName))
throw new PrologException
(new Functor2("domain_error", Atom.a("prolog_flag"), Key),
"Arg 1 Key " + Key + " is not a recognized flag");
bool valueIsOK = false;
if (keyName == "char_conversion")
valueIsOK = (Value == _prologFlags[keyName]);
else if (keyName == "debug")
valueIsOK = (Value == _prologFlags[keyName]);
else if (keyName == "unknown")
valueIsOK = (Value == Atom.a("fail") || Value == Atom.a("warning") ||
Value == Atom.a("error"));
else if (keyName == "double_quotes")
valueIsOK = (Value == Atom.a("codes") || Value == Atom.a("chars") ||
Value == Atom.a("atom"));
else
throw new PrologException
(new Functor3("permission_error", Atom.a("modify"), Atom.a("flag"), Key),
"May not modify Prolog flag " + Key);
if (!valueIsOK)
throw new PrologException
(new Functor2("domain_error", Atom.a("flag_value"), new Functor2("+", Key, Value)),
"May not set arg 1 Key " + Key + " to arg 2 Value " + Value);
_prologFlags[keyName] = Value;
}
/// <summary> /// <summary>
/// script_event calls hosting script with events as a callback method. /// script_event calls hosting script with events as a callback method.
/// </summary> /// </summary>
@ -2303,19 +2538,35 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
private IEnumerator<bool> _enumerator; private IEnumerator<bool> _enumerator;
private PrologException _exception = null; private PrologException _exception = null;
public Catch(IEnumerable<bool> iterator) /// <summary>
/// Call YP.getIterator(Goal, declaringClass) and save the returned iterator.
/// If getIterator throws an exception, save it the same as MoveNext().
/// </summary>
/// <param name="Goal"></param>
/// <param name="declaringClass"></param>
public Catch(object Goal, Type declaringClass)
{ {
_enumerator = iterator.GetEnumerator(); try
{
_enumerator = getIterator(Goal, declaringClass).GetEnumerator();
}
catch (PrologException exception)
{
// MoveNext() will check this.
_exception = exception;
}
} }
/// <summary> /// <summary>
/// Call _enumerator.MoveNext(). If it throws a PrologException, set _exception /// Call _enumerator.MoveNext(). If it throws a PrologException, set _exception
/// and return false. After this returns false, call unifyExceptionOrThrow. /// and return false. After this returns false, call unifyExceptionOrThrow.
/// Assume that, after this returns false, it will not be called again.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public bool MoveNext() public bool MoveNext()
{ {
if (_exception != null)
return false;
try try
{ {
return _enumerator.MoveNext(); return _enumerator.MoveNext();
@ -2372,6 +2623,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
public void Dispose() public void Dispose()
{ {
if (_enumerator != null)
_enumerator.Dispose(); _enumerator.Dispose();
} }
@ -2407,7 +2659,42 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
foreach (bool l2 in YP.unify(Body, _Body)) foreach (bool l2 in YP.unify(Body, _Body))
yield return false; yield return false;
} }
#pragma warning disable 0168 #pragma warning restore 0168
}
}
/// <summary>
/// CodeListReader extends TextReader and overrides Read to read the next code from
/// the CodeList which is a Prolog list of integer character codes.
/// </summary>
public class CodeListReader : TextReader
{
private object _CodeList;
public CodeListReader(object CodeList)
{
_CodeList = YP.getValue(CodeList);
}
/// <summary>
/// If the head of _CodeList is an integer, return it and advance the list. Otherwise,
/// return -1 for end of file.
/// </summary>
/// <returns></returns>
public override int Read()
{
Functor2 CodeListPair = _CodeList as Functor2;
int code;
if (!(CodeListPair != null && CodeListPair._name == Atom.DOT &&
getInt(CodeListPair._arg1, out code)))
{
_CodeList = Atom.NIL;
return -1;
}
// Advance.
_CodeList = YP.getValue(CodeListPair._arg2);
return code;
} }
} }
} }

View File

@ -203,7 +203,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
// disable warning on l1, don't see how we can // disable warning on l1, don't see how we can
// code this differently // code this differently
#pragma warning disable 0168, 0164, 0162 #pragma warning disable 0168,0164,0162
public static bool isDetNoneOut(object State, object Term) public static bool isDetNoneOut(object State, object Term)
{ {
State = YP.getValue(State); State = YP.getValue(State);
@ -241,7 +241,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
return false; return false;
} }
#pragma warning restore 0168, 0164, 0162 #pragma warning restore 0168,0164,0162
/// <summary> /// <summary>
/// Return false if any of args is out, otherwise true. /// Return false if any of args is out, otherwise true.
@ -280,7 +280,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.YieldProlog
// disable warning on l1, don't see how we can // disable warning on l1, don't see how we can
// code this differently // code this differently
#pragma warning disable 0168, 0219, 0164, 0162 #pragma warning disable 0168, 0219,0164,0162
/// <summary> /// <summary>
/// Use makeFunctionPseudoCode, convertFunctionCSharp and compileAnonymousFunction /// Use makeFunctionPseudoCode, convertFunctionCSharp and compileAnonymousFunction
@ -405,8 +405,8 @@ namespace Temporary {
/// <summary> /// <summary>
/// If the functor with name and args can be called directly as determined by /// If the functor with name and args can be called directly as determined by
/// functorCallFunctionName, then call it and return its iterator. If the predicate is /// functorCallFunctionName, then call it and return its iterator. If the predicate is
/// dynamic and undefined, or if static and the method cannot be found, throw /// dynamic and undefined, or if static and the method cannot be found, return
/// a PrologException for existence_error. /// the result of YP.unknownPredicate.
/// This returns null if the functor has a special form than needs to be compiled /// This returns null if the functor has a special form than needs to be compiled
/// (including ,/2 and ;/2). /// (including ,/2 and ;/2).
/// </summary> /// </summary>
@ -424,13 +424,11 @@ namespace Temporary {
{ {
Atom functionNameAtom = ((Atom)FunctionName.getValue()); Atom functionNameAtom = ((Atom)FunctionName.getValue());
if (functionNameAtom == Atom.NIL) if (functionNameAtom == Atom.NIL)
{
// name is for a dynamic predicate. // name is for a dynamic predicate.
return YP.matchDynamic(name, args); return YP.matchDynamic(name, args);
}
// Set the default for the method to call.
string methodName = functionNameAtom._name; string methodName = functionNameAtom._name;
// Set the default for the method to call.
Type methodClass = declaringClass; Type methodClass = declaringClass;
bool checkMode = false; bool checkMode = false;
@ -448,10 +446,8 @@ namespace Temporary {
return null; return null;
if (methodClass == null) if (methodClass == null)
throw new PrologException return YP.unknownPredicate
(new Functor2 (name, args.Length,
(Atom.a("existence_error"), Atom.a("procedure"),
new Functor2(Atom.a("/"), name, args.Length)),
"Cannot find predicate function for: " + name + "/" + args.Length + "Cannot find predicate function for: " + name + "/" + args.Length +
" because declaringClass is null. Set declaringClass to the class containing " + " because declaringClass is null. Set declaringClass to the class containing " +
methodName); methodName);
@ -486,10 +482,8 @@ namespace Temporary {
} }
catch (MissingMethodException) catch (MissingMethodException)
{ {
throw new PrologException return YP.unknownPredicate
(new Functor2 (name, args.Length,
(Atom.a("existence_error"), Atom.a("procedure"),
new Functor2(Atom.a("/"), name, args.Length)),
"Cannot find predicate function " + methodName + " for " + name + "/" + args.Length + "Cannot find predicate function " + methodName + " for " + name + "/" + args.Length +
" in " + methodClass.FullName); " in " + methodClass.FullName);
} }
@ -498,6 +492,54 @@ namespace Temporary {
return null; return null;
} }
/// <summary>
/// Return true if there is a dynamic or static predicate with name and arity.
/// This returns false for built-in predicates.
/// </summary>
/// <param name="name"></param>
/// <param name="arity"></param>
/// <param name="declaringClass">used to resolve references to the default
/// module Atom.a(""). If a declaringClass is needed to resolve the reference but it is
/// null, return false</param>
/// <returns></returns>
public static bool isCurrentPredicate(Atom name, int arity, Type declaringClass)
{
CompilerState state = new CompilerState();
Variable FunctionName = new Variable();
foreach (bool l1 in functorCallFunctionName(state, name, arity, FunctionName))
{
Atom functionNameAtom = ((Atom)FunctionName.getValue());
if (functionNameAtom == Atom.NIL)
// name is for a dynamic predicate.
return YP.isDynamicCurrentPredicate(name, arity);
string methodName = functionNameAtom._name;
if (methodName.StartsWith("YP."))
// current_predicate/1 should fail for built-ins.
return false;
if (methodName.Contains("."))
// We don't support calling inner classes, etc.
return false;
if (declaringClass == null)
return false;
foreach (MemberInfo member in declaringClass.GetMember(methodName))
{
MethodInfo method = member as MethodInfo;
if (method == null)
continue;
if ((method.Attributes | MethodAttributes.Static) == 0)
// Not a static method.
continue;
if (method.GetParameters().Length == arity)
return true;
}
}
return false;
}
// Compiler output follows. // Compiler output follows.
public class YPInnerClass { } public class YPInnerClass { }
@ -567,9 +609,14 @@ namespace Temporary {
CompilerState.assertPred(State, Atom.a("nl"), Atom.a("det")); CompilerState.assertPred(State, Atom.a("nl"), Atom.a("det"));
CompilerState.assertPred(State, new Functor1("write", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det")); CompilerState.assertPred(State, new Functor1("write", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det"));
CompilerState.assertPred(State, new Functor1("put_code", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det")); CompilerState.assertPred(State, new Functor1("put_code", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det"));
CompilerState.assertPred(State, new Functor1("see", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det"));
CompilerState.assertPred(State, Atom.a("seen"), Atom.a("det"));
CompilerState.assertPred(State, new Functor1("tell", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det"));
CompilerState.assertPred(State, Atom.a("told"), Atom.a("det"));
CompilerState.assertPred(State, new Functor1("throw", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det")); CompilerState.assertPred(State, new Functor1("throw", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det"));
CompilerState.assertPred(State, new Functor1("abolish", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det")); CompilerState.assertPred(State, new Functor1("abolish", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det"));
CompilerState.assertPred(State, new Functor1("retractall", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det")); CompilerState.assertPred(State, new Functor1("retractall", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det"));
CompilerState.assertPred(State, new Functor2("set_prolog_flag", new Functor2("::", Atom.a("univ"), Atom.a("in")), new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("det"));
CompilerState.assertPred(State, new Functor1("var", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("semidet")); CompilerState.assertPred(State, new Functor1("var", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("semidet"));
CompilerState.assertPred(State, new Functor1("nonvar", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("semidet")); CompilerState.assertPred(State, new Functor1("nonvar", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("semidet"));
CompilerState.assertPred(State, new Functor1("atom", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("semidet")); CompilerState.assertPred(State, new Functor1("atom", new Functor2("::", Atom.a("univ"), Atom.a("in"))), Atom.a("semidet"));
@ -2121,7 +2168,7 @@ namespace Temporary {
{ {
foreach (bool l3 in YP.unify(arg3, new ListPair(new Functor2("if", new Functor2("call", FunctionName, new ListPair(X1Code, new ListPair(X2Code, Atom.NIL))), BCode), Atom.NIL))) foreach (bool l3 in YP.unify(arg3, new ListPair(new Functor2("if", new Functor2("call", FunctionName, new ListPair(X1Code, new ListPair(X2Code, Atom.NIL))), BCode), Atom.NIL)))
{ {
foreach (bool l4 in YP.univ(A, new ListPair(Name, new ListPair(X1, new ListPair(X2, Atom.NIL))))) foreach (bool l4 in YP.univ(A, ListPair.make(new object[] { Name, X1, X2 })))
{ {
foreach (bool l5 in binaryExpressionConditional(Name, FunctionName)) foreach (bool l5 in binaryExpressionConditional(Name, FunctionName))
{ {
@ -2230,6 +2277,27 @@ namespace Temporary {
} }
} }
} }
{
object State = arg2;
Variable A = new Variable();
Variable B = new Variable();
Variable ATermCode = new Variable();
Variable BCode = new Variable();
foreach (bool l2 in YP.unify(arg1, new Functor2(",", new Functor1("current_predicate", A), B)))
{
foreach (bool l3 in YP.unify(arg3, new ListPair(new Functor2("foreach", new Functor2("call", Atom.a("YP.current_predicate"), new ListPair(ATermCode, new ListPair(new Functor2("call", Atom.a("getDeclaringClass"), Atom.NIL), Atom.NIL))), BCode), Atom.NIL)))
{
foreach (bool l4 in compileTerm(A, State, ATermCode))
{
foreach (bool l5 in compileRuleBody(B, State, BCode))
{
yield return true;
yield break;
}
}
}
}
}
{ {
object State = arg2; object State = arg2;
Variable A = new Variable(); Variable A = new Variable();
@ -2299,7 +2367,7 @@ namespace Temporary {
Variable HandlerAndBCode = new Variable(); Variable HandlerAndBCode = new Variable();
foreach (bool l2 in YP.unify(arg1, new Functor2(",", new Functor3("catch", Goal, Catcher, Handler), B))) foreach (bool l2 in YP.unify(arg1, new Functor2(",", new Functor3("catch", Goal, Catcher, Handler), B)))
{ {
foreach (bool l3 in YP.unify(arg3, new ListPair(new Functor3("declare", Atom.a("YP.Catch"), CatchGoal, new Functor2("new", Atom.a("YP.Catch"), new ListPair(new Functor2("call", Atom.a("YP.getIterator"), new ListPair(GoalTermCode, new ListPair(new Functor2("call", Atom.a("getDeclaringClass"), Atom.NIL), Atom.NIL))), Atom.NIL))), new ListPair(new Functor2("foreach", new Functor1("var", CatchGoal), BCode), new ListPair(new Functor2("foreach", new Functor3("callMember", new Functor1("var", CatchGoal), Atom.a("unifyExceptionOrThrow"), new ListPair(CatcherTermCode, Atom.NIL)), HandlerAndBCode), Atom.NIL))))) foreach (bool l3 in YP.unify(arg3, ListPair.make(new object[] { new Functor3("declare", Atom.a("YP.Catch"), CatchGoal, new Functor2("new", Atom.a("YP.Catch"), new ListPair(GoalTermCode, new ListPair(new Functor2("call", Atom.a("getDeclaringClass"), Atom.NIL), Atom.NIL)))), new Functor2("foreach", new Functor1("var", CatchGoal), BCode), new Functor2("foreach", new Functor3("callMember", new Functor1("var", CatchGoal), Atom.a("unifyExceptionOrThrow"), new ListPair(CatcherTermCode, Atom.NIL)), HandlerAndBCode) })))
{ {
foreach (bool l4 in CompilerState.gensym(State, Atom.a("catchGoal"), CatchGoal)) foreach (bool l4 in CompilerState.gensym(State, Atom.a("catchGoal"), CatchGoal))
{ {
@ -2833,6 +2901,10 @@ namespace Temporary {
{ {
return true; return true;
} }
if (YP.termEqual(Name, Atom.a("current_predicate")))
{
return true;
}
if (YP.termEqual(Name, Atom.a("asserta"))) if (YP.termEqual(Name, Atom.a("asserta")))
{ {
return true; return true;
@ -3015,19 +3087,6 @@ namespace Temporary {
} }
} }
} }
{
foreach (bool l2 in YP.unify(arg1, Atom.a("current_predicate")))
{
foreach (bool l3 in YP.unify(arg2, 1))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("YP.current_predicate")))
{
yield return true;
yield break;
}
}
}
}
{ {
foreach (bool l2 in YP.unify(arg1, Atom.a("atom_length"))) foreach (bool l2 in YP.unify(arg1, Atom.a("atom_length")))
{ {
@ -3213,6 +3272,58 @@ namespace Temporary {
} }
} }
} }
{
foreach (bool l2 in YP.unify(arg1, Atom.a("see")))
{
foreach (bool l3 in YP.unify(arg2, 1))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("YP.see")))
{
yield return true;
yield break;
}
}
}
}
{
foreach (bool l2 in YP.unify(arg1, Atom.a("seen")))
{
foreach (bool l3 in YP.unify(arg2, 0))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("YP.seen")))
{
yield return true;
yield break;
}
}
}
}
{
foreach (bool l2 in YP.unify(arg1, Atom.a("tell")))
{
foreach (bool l3 in YP.unify(arg2, 1))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("YP.tell")))
{
yield return true;
yield break;
}
}
}
}
{
foreach (bool l2 in YP.unify(arg1, Atom.a("told")))
{
foreach (bool l3 in YP.unify(arg2, 0))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("YP.told")))
{
yield return true;
yield break;
}
}
}
}
{ {
foreach (bool l2 in YP.unify(arg1, Atom.a("clause"))) foreach (bool l2 in YP.unify(arg1, Atom.a("clause")))
{ {
@ -3434,6 +3545,110 @@ namespace Temporary {
} }
} }
} }
{
foreach (bool l2 in YP.unify(arg1, Atom.a("current_prolog_flag")))
{
foreach (bool l3 in YP.unify(arg2, 2))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("YP.current_prolog_flag")))
{
yield return true;
yield break;
}
}
}
}
{
foreach (bool l2 in YP.unify(arg1, Atom.a("set_prolog_flag")))
{
foreach (bool l3 in YP.unify(arg2, 2))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("YP.set_prolog_flag")))
{
yield return true;
yield break;
}
}
}
}
{
foreach (bool l2 in YP.unify(arg1, Atom.a("current_input")))
{
foreach (bool l3 in YP.unify(arg2, 1))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("YP.current_input")))
{
yield return true;
yield break;
}
}
}
}
{
foreach (bool l2 in YP.unify(arg1, Atom.a("current_output")))
{
foreach (bool l3 in YP.unify(arg2, 1))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("YP.current_output")))
{
yield return true;
yield break;
}
}
}
}
{
foreach (bool l2 in YP.unify(arg1, Atom.a("read_term")))
{
foreach (bool l3 in YP.unify(arg2, 2))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("Parser.read_term2")))
{
yield return true;
yield break;
}
}
}
}
{
foreach (bool l2 in YP.unify(arg1, Atom.a("read_term")))
{
foreach (bool l3 in YP.unify(arg2, 3))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("Parser.read_term3")))
{
yield return true;
yield break;
}
}
}
}
{
foreach (bool l2 in YP.unify(arg1, Atom.a("read")))
{
foreach (bool l3 in YP.unify(arg2, 1))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("Parser.read1")))
{
yield return true;
yield break;
}
}
}
}
{
foreach (bool l2 in YP.unify(arg1, Atom.a("read")))
{
foreach (bool l3 in YP.unify(arg2, 2))
{
foreach (bool l4 in YP.unify(arg3, Atom.a("Parser.read2")))
{
yield return true;
yield break;
}
}
}
}
} }
public static IEnumerable<bool> compileTerm(object arg1, object arg2, object arg3) public static IEnumerable<bool> compileTerm(object arg1, object arg2, object arg3)
@ -3490,6 +3705,34 @@ namespace Temporary {
{ } { }
} }
} }
{
object State = arg2;
Variable First = new Variable();
Variable Rest = new Variable();
Variable CompiledList = new Variable();
Variable x5 = new Variable();
Variable Rest2 = new Variable();
foreach (bool l2 in YP.unify(arg1, new ListPair(First, Rest)))
{
foreach (bool l3 in YP.unify(arg3, new Functor2("call", Atom.a("ListPair.make"), new ListPair(new Functor1("objectArray", CompiledList), Atom.NIL))))
{
if (YP.nonvar(Rest))
{
foreach (bool l5 in YP.unify(Rest, new ListPair(x5, Rest2)))
{
if (YP.termNotEqual(Rest2, Atom.NIL))
{
foreach (bool l7 in maplist_compileTerm(new ListPair(First, Rest), State, CompiledList))
{
yield return true;
yield break;
}
}
}
}
}
}
}
{ {
object State = arg2; object State = arg2;
Variable First = new Variable(); Variable First = new Variable();
@ -3563,7 +3806,7 @@ namespace Temporary {
{ {
foreach (bool l8 in compileTerm(X2, State, Arg2)) foreach (bool l8 in compileTerm(X2, State, Arg2))
{ {
foreach (bool l9 in YP.unify(Result, new Functor2("new", Atom.a("Functor2"), new ListPair(NameCode, new ListPair(Arg1, new ListPair(Arg2, Atom.NIL)))))) foreach (bool l9 in YP.unify(Result, new Functor2("new", Atom.a("Functor2"), ListPair.make(new object[] { NameCode, Arg1, Arg2 }))))
{ {
yield return true; yield return true;
yield break; yield break;
@ -3572,7 +3815,7 @@ namespace Temporary {
} }
goto cutIf5; goto cutIf5;
} }
foreach (bool l6 in YP.unify(TermArgs, new ListPair(X1, new ListPair(X2, new ListPair(X3, Atom.NIL))))) foreach (bool l6 in YP.unify(TermArgs, ListPair.make(new object[] { X1, X2, X3 })))
{ {
foreach (bool l7 in compileTerm(X1, State, Arg1)) foreach (bool l7 in compileTerm(X1, State, Arg1))
{ {
@ -3580,7 +3823,7 @@ namespace Temporary {
{ {
foreach (bool l9 in compileTerm(X3, State, Arg3)) foreach (bool l9 in compileTerm(X3, State, Arg3))
{ {
foreach (bool l10 in YP.unify(Result, new Functor2("new", Atom.a("Functor3"), new ListPair(NameCode, new ListPair(Arg1, new ListPair(Arg2, new ListPair(Arg3, Atom.NIL))))))) foreach (bool l10 in YP.unify(Result, new Functor2("new", Atom.a("Functor3"), ListPair.make(new object[] { NameCode, Arg1, Arg2, Arg3 }))))
{ {
yield return true; yield return true;
yield break; yield break;
@ -3623,7 +3866,7 @@ namespace Temporary {
{ {
foreach (bool l7 in compileTerm(X2, State, Arg2)) foreach (bool l7 in compileTerm(X2, State, Arg2))
{ {
foreach (bool l8 in YP.unify(Result, new Functor2("new", Atom.a("Functor2"), new ListPair(NameCode, new ListPair(Arg1, new ListPair(Arg2, Atom.NIL)))))) foreach (bool l8 in YP.unify(Result, new Functor2("new", Atom.a("Functor2"), ListPair.make(new object[] { NameCode, Arg1, Arg2 }))))
{ {
yield return true; yield return true;
yield break; yield break;
@ -3632,7 +3875,7 @@ namespace Temporary {
} }
goto cutIf7; goto cutIf7;
} }
foreach (bool l5 in YP.unify(TermArgs, new ListPair(X1, new ListPair(X2, new ListPair(X3, Atom.NIL))))) foreach (bool l5 in YP.unify(TermArgs, ListPair.make(new object[] { X1, X2, X3 })))
{ {
foreach (bool l6 in compileTerm(X1, State, Arg1)) foreach (bool l6 in compileTerm(X1, State, Arg1))
{ {
@ -3640,7 +3883,7 @@ namespace Temporary {
{ {
foreach (bool l8 in compileTerm(X3, State, Arg3)) foreach (bool l8 in compileTerm(X3, State, Arg3))
{ {
foreach (bool l9 in YP.unify(Result, new Functor2("new", Atom.a("Functor3"), new ListPair(NameCode, new ListPair(Arg1, new ListPair(Arg2, new ListPair(Arg3, Atom.NIL))))))) foreach (bool l9 in YP.unify(Result, new Functor2("new", Atom.a("Functor3"), ListPair.make(new object[] { NameCode, Arg1, Arg2, Arg3 }))))
{ {
yield return true; yield return true;
yield break; yield break;
@ -3725,9 +3968,11 @@ namespace Temporary {
{ {
foreach (bool l3 in YP.unify(arg3, new ListPair(FirstResult, RestResults))) foreach (bool l3 in YP.unify(arg3, new ListPair(FirstResult, RestResults)))
{ {
foreach (bool l4 in compileTerm(First, State, FirstResult)) if (YP.nonvar(Rest))
{ {
foreach (bool l5 in maplist_compileTerm(Rest, State, RestResults)) foreach (bool l5 in compileTerm(First, State, FirstResult))
{
foreach (bool l6 in maplist_compileTerm(Rest, State, RestResults))
{ {
yield return true; yield return true;
yield break; yield break;
@ -3737,6 +3982,7 @@ namespace Temporary {
} }
} }
} }
}
public static IEnumerable<bool> compileExpression(object Term, object State, object Result) public static IEnumerable<bool> compileExpression(object Term, object State, object Result)
{ {
@ -6131,6 +6377,6 @@ namespace Temporary {
} }
} }
} }
#pragma warning restore 0168, 0219, 0164, 0162 #pragma warning restore 0168, 0219, 0164,0162
} }
} }