this should be in packages, not in LGPL!

This commit is contained in:
Vitor Santos Costa 2009-05-02 14:11:10 -05:00
parent 8385f4bea6
commit 7b993ca987
55 changed files with 0 additions and 17459 deletions

View File

@ -1,30 +0,0 @@
#
# default base directory for YAP installation
#
ROOTDIR = @prefix@
#
# where the binary should be
#
BINDIR = $(ROOTDIR)/bin
#
# where YAP should look for binary libraries
#
LIBDIR=$(ROOTDIR)/lib/Yap
#
# where YAP should look for architecture-independent Prolog libraries
#
SHAREDIR=$(ROOTDIR)/share
#
#
# You shouldn't need to change what follows.
#
INSTALL=@INSTALL@
INSTALL_DATA=@INSTALL_DATA@
INSTALL_PROGRAM=@INSTALL_PROGRAM@
srcdir=@srcdir@
PROGRAMS= $(srcdir)/jpl.yap jpl_paths.yap
install: $(PROGRAMS)
mkdir -p $(DESTDIR)$(SHAREDIR)/Yap
for p in $(PROGRAMS); do $(INSTALL_DATA) $$p $(DESTDIR)$(SHAREDIR)/Yap; done

View File

@ -1,119 +0,0 @@
################################################################
# Build jpl.jar
################################################################
.SUFFIXES: .java .class
#
# default base directory for YAP installation
#
ROOTDIR = @prefix@
#
# where the binary should be
#
BINDIR = $(ROOTDIR)/bin
#
# where YAP should look for binary libraries
#
LIBDIR=$(ROOTDIR)/lib/Yap
#
# where YAP should look for architecture-independent Prolog libraries
#
SHAREDIR=$(ROOTDIR)/share
#
#
# You shouldn't need to change what follows.
#
INSTALL=@INSTALL@
INSTALL_DATA=@INSTALL_DATA@
INSTALL_PROGRAM=@INSTALL_PROGRAM@
SHELL=/bin/sh
RANLIB=@RANLIB@
srcdir=@srcdir@
SHLIB_CFLAGS=@SHLIB_CFLAGS@
SHLIB_SUFFIX=@SHLIB_SUFFIX@
#4.1VPATH=@srcdir@:@srcdir@/OPTYap
CWD=$(PWD)
#
JAVAC=@JAVAC@
JAR=@JAR@
JPLJAR=jpl.jar
TESTJAR=jpltest.jar
CLS= jpl/Atom.java \
jpl/Compound.java \
jpl/Float.java \
jpl/Integer.java \
jpl/JRef.java \
jpl/JPLException.java \
jpl/JPL.java \
jpl/PrologException.java \
jpl/Query.java \
jpl/Term.java \
jpl/Util.java \
jpl/Variable.java \
jpl/Version.java
FLI= jpl/fli/atom_t.java \
jpl/fli/BooleanHolder.java \
jpl/fli/DoubleHolder.java \
jpl/fli/engine_t.java \
jpl/fli/fid_t.java \
jpl/fli/functor_t.java \
jpl/fli/IntHolder.java \
jpl/fli/Int64Holder.java \
jpl/fli/LongHolder.java \
jpl/fli/module_t.java \
jpl/fli/ObjectHolder.java \
jpl/fli/PointerHolder.java \
jpl/fli/predicate_t.java \
jpl/fli/Prolog.java \
jpl/fli/qid_t.java \
jpl/fli/StringHolder.java \
jpl/fli/term_t.java
TEST= jpl/test/Family.java \
jpl/test/FetchBigTree.java \
jpl/test/FetchLongList.java \
jpl/test/Ga2.java \
jpl/test/Ga.java \
jpl/test/Garbo.java \
jpl/test/Masstest.java \
jpl/test/MaxObjects.java \
jpl/test/ShadowA.java \
jpl/test/ShadowB.java \
jpl/test/SyntaxError.java \
jpl/test/Test.java \
jpl/test/TestJUnit.java \
jpl/test/TestOLD.java
JAVA=$(CLS) $(FLI)
CLASSES=$(JAVA:.java=.class)
TESTCLASSES=$(TEST:.java=.class)
all: $(JPLJAR)
$(JAVA):
for f in $(CLS); do cp $(srcdir)/$$f jpl ; done
for f in $(FLI); do cp $(srcdir)/$$f jpl/fli ; done
for f in $(TEST); do cp $(srcdir)/$$f jpl/test ; done
$(JPLJAR): $(JAVA)
$(JAVAC) $(JAVA)
$(JAR) cf $(JPLJAR) $(CLASSES)
$(TESTJAR): $(JAVA) $(TEST)
$(JAVAC) -classpath $(JPLJAR):$(JUNIT) $(TEST)
$(JAR) cf $(JPL) $(TESTCLASSES)
clean::
rm -f *~ $(CLASSES)
distclean: clean
rm -r $(JPL)
install: $(JPLJAR)
mkdir -p $(DESTDIR)$(SHAREDIR)/Yap
$(INSTALL_DATA) $(JPLJAR) $(DESTDIR)$(SHAREDIR)/Yap

View File

@ -1,165 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: Atom.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
// Author: Paul Singleton <paul@jbgb.com>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 2004 Paul Singleton
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl;
import java.util.Map;
import jpl.fli.Prolog;
import jpl.fli.StringHolder;
import jpl.fli.term_t;
//----------------------------------------------------------------------/
// Atom
/**
* Atom is a specialised Compound with zero arguments, representing a Prolog atom with the same name.
* An Atom is constructed with a String parameter (its name, unquoted), which cannot thereafter be changed.
* <pre>Atom a = new Atom("hello");</pre>
* An Atom can be used (and re-used) as an argument of Compound Terms.
* Two Atom instances are equal (by equals()) iff they have equal names.
*
* <hr><i>
* Copyright (C) 2004 Paul Singleton<p>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
* @see jpl.Term
* @see jpl.Compound
*/
public class Atom extends Compound {
//==================================================================/
// Attributes (none)
//==================================================================/
//==================================================================/
// Constructors
//==================================================================/
/**
* @param name the Atom's name (unquoted)
*/
public Atom(String name) {
super(name);
}
//==================================================================/
// Methods (common)
//==================================================================/
// these are all inherited from Compound
public final int type() {
return Prolog.ATOM;
}
/**
* returns the name of the type of this term, as "Atom"
*
* @return the name of the type of this term, as "Atom"
*/
public String typeName() { // overrides same in jpl.Term
return "Atom";
}
//==================================================================/
// Methods (deprecated)
//==================================================================/
/**
* Returns a debug-friendly String representation of an Atom.
*
* @return a debug-friendly String representation of an Atom
* @deprecated
*/
public String debugString() {
return "(Atom " + toString() + ")";
}
//==================================================================/
// Converting JPL Terms to Prolog terms
//==================================================================/
// (this is done with the put() method inherited from Compound)
//==================================================================/
// Converting Prolog terms to JPL Terms
//==================================================================/
/**
* Converts a Prolog term (as a term_t), which is known to be an atom, to a new jpl.Atom.
* This is only called from Term.getTerm(),
* and just creates a new Atom object initialised with the atom's name.
*
* @param vars_to_Vars A Map from Prolog variables to JPL Variables.
* @param term The Prolog term to be converted
* @return A new Atom instance
*/
protected static Term getTerm1(Map vars_to_Vars, term_t term) {
StringHolder holder = new StringHolder();
Prolog.get_atom_chars(term, holder); // ignore return val; assume success...
return new Atom(holder.value);
}
/**
* Converts a Prolog term (as a term_t), which is known to be a SWI-Prolog string, to a new jpl.Atom,
* by creating a new Atom object initialised with the string's value.
* JPL users should avoid SWI-Prolog's non-ISO strings, but in some obscure
* circumstances they are returned unavoidably, so we have to handle them
* (and this is how).
*
* @param vars_to_Vars A Map from Prolog variables to JPL Variables.
* @param term The term_t to convert
* @return A new Atom instance
*/
protected static Term getString(Map vars_to_Vars, term_t term) {
StringHolder holder = new StringHolder();
Prolog.get_string_chars(term, holder); // ignore return val; assume success...
return new Atom(holder.value);
}
//==================================================================/
// Computing substitutions
//==================================================================/
// (done with the inherited Compound.getSubst() method)
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,386 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: Compound.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 2004 Paul Singleton
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl;
import java.util.Map;
import jpl.fli.IntHolder;
import jpl.fli.ObjectHolder;
import jpl.fli.Prolog;
import jpl.fli.StringHolder;
import jpl.fli.term_t;
//----------------------------------------------------------------------/
// Compound
/**
* A Compound represents a structured term,
* comprising a functor and arguments (Terms).
* Atom is a subclass of Compound, whose instances have zero arguments.
* Direct instances of Compound must have one or more arguments
* (it is an error to attempt to construct a Compound with zero args;
* a JPLException will be thrown).
* For example, this Java expression yields
* a representation of the term f(a):
* <pre>
* new Compound( "f", new Term[] { new Atom("a") } )
* </pre>
* Note the use of the "anonymous array" notation to denote the arguments
* (an anonymous array of Term).
* <br>
* Alternatively, construct the Term from Prolog source syntax:
* <pre>
* Util.textToTerm("f(a)")
* </pre>
* The <i>arity</i> of a Compound is the quantity of its arguments.
* Once constructed, neither the name nor the arity of a Compound can be altered.
* An argument of a Compound can be replaced with the setArg() method.
* <hr><i>
* Copyright (C) 2004 Paul Singleton<p>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
* @see jpl.Term
* @see jpl.Atom
*/
public class Compound extends Term {
//==================================================================/
// Attributes
//==================================================================/
/**
* the name of this Compound
*/
protected final String name;
/**
* the arguments of this Compound
*/
protected final Term[] args;
//==================================================================/
// Constructors
//==================================================================/
/**
* Creates a Compound with name but no args (i.e. an Atom).
* This condsructor is protected (from illegal public use) and is used
* only by Atom, which inherits it.
*
* @param name the name of this Compound
* @param args the arguments of this Compound
*/
protected Compound(String name) {
if (name == null) {
throw new JPLException("jpl.Atom: cannot construct with null name");
}
this.name = name;
this.args = new Term[] {};
}
/**
* Creates a Compound with name and args.
*
* @param name the name of this Compound
* @param args the (one or more) arguments of this Compound
*/
public Compound(String name, Term[] args) {
if (name == null) {
throw new JPLException("jpl.Compound: cannot construct with null name");
}
if (args == null) {
throw new JPLException("jpl.Compound: cannot construct with null args");
}
if (args.length == 0) {
throw new JPLException("jpl.Compound: cannot construct with zero args");
}
this.name = name;
this.args = args;
}
/**
* Creates a Compound with name and arity.
* This constructor, along with the setArg method, serves the new, native Prolog-term-to-Java-term routine,
* and is public only so as to be accessible via JNI: it is not intended for general use.
*
* @param name the name of this Compound
* @param arity the arity of this Compound
*/
public Compound(String name, int arity) {
if (name == null) {
throw new JPLException("jpl.Compound: cannot construct with null name");
}
if (arity < 0) {
throw new JPLException("jpl.Compound: cannot construct with negative arity");
}
this.name = name;
this.args = new Term[arity];
}
//==================================================================/
// Methods (common)
//==================================================================/
/**
* Returns the ith argument (counting from 1) of this Compound;
* throws an ArrayIndexOutOfBoundsException if i is inappropriate.
*
* @return the ith argument (counting from 1) of this Compound
*/
public final Term arg(int i) {
return args[i - 1];
}
/**
* Tests whether this Compound's functor has (String) 'name' and 'arity'.
*
* @return whether this Compound's functor has (String) 'name' and 'arity'
*/
public final boolean hasFunctor(String name, int arity) {
return name.equals(this.name) && arity == args.length; // BUGFIX: was just name.equals(name)
}
/**
* whether this Term is a 'jboolean' structure denoting Java's false, i.e. @(false)
*
* @return whether this Term is a 'jboolean' structure denoting Java's false, i.e. @(false)
*/
public boolean isJFalse() {
return hasFunctor("@", 1) && arg(1).hasFunctor("false", 0);
}
/**
* whether this Term is a 'jboolean' structure denoting Java's true, i.e. @(fatruelse)
*
* @return whether this Term is a 'jboolean' structure denoting Java's true, i.e. @(fatruelse)
*/
public boolean isJTrue() {
return hasFunctor("@", 1) && arg(1).hasFunctor("true", 0);
}
/**
* whether this Term is a 'jnull' structure, i.e. @(null)
*
* @return whether this Term is a 'jnull' structure, i.e. @(null)
*/
public boolean isJNull() {
return hasFunctor("@", 1) && arg(1).hasFunctor("null", 0);
}
/**
* whether this Term is a 'jvoid' structure, i.e. @(void)
*
* @return whether this Term is a 'jvoid' structure, i.e. @(void)
*/
public boolean isJVoid() {
return hasFunctor("@", 1) && arg(1).hasFunctor("void", 0);
}
/**
* whether this Term is a 'jobject' structure, i.e. @(Tag)
*
* @return whether this Term is a 'jobject' structure, i.e. @(Tag)
*/
public boolean isJObject() {
return hasFunctor("@", 1) && arg(1).isAtom() && JPL.isTag(arg(1).name());
}
/**
* whether this Term is a 'jref' structure, i.e. @(Tag) or @(null)
*
* @return whether this Term is a 'jref' structure, i.e. @(Tag) or @(null)
*/
public boolean isJRef() {
return isJObject() || isJNull();
}
/**
* Returns the name (unquoted) of this Compound.
*
* @return the name (unquoted) of this Compound
*/
public final String name() {
return name;
}
/**
* Returns the arity (1+) of this Compound.
*
* @return the arity (1+) of this Compound
*/
public final int arity() {
return args.length;
}
/**
* Returns a prefix functional representation of a Compound of the form name(arg1,...),
* where 'name' is quoted iff necessary (to be valid Prolog soutce text)
* and each argument is represented according to its toString() method.
*
* @return string representation of an Compound
*/
public String toString() {
return quotedName() + (args.length > 0 ? "(" + Term.toString(args) + ")" : "");
}
/**
* Two Compounds are equal if they are identical (same object) or their names and arities are equal and their
* respective arguments are equal.
*
* @param obj the Object to compare (not necessarily another Compound)
* @return true if the Object satisfies the above condition
*/
public final boolean equals(Object obj) {
return (this == obj || (obj instanceof Compound && name.equals(((Compound) obj).name) && Term.terms_equals(args, ((Compound) obj).args)));
}
/**
* returns the type of this term, as jpl.fli.Prolog.COMPOUND
*
* @return the type of this term, as jpl.fli.Prolog.COMPOUND
*/
public int type() {
return Prolog.COMPOUND;
}
/**
* returns the name of the type of this term, as "Compound"
*
* @return the name of the type of this term, as "Compound"
*/
public String typeName(){
return "Compound";
}
/**
* Sets the i-th (from 1) arg of this Compound to the given Term instance.
* This method, along with the Compound(name,arity) constructor, serves the new, native Prolog-term-to-Java-term routine,
* and is public only so as to be accessible via JNI: it is not intended for general use.
*
* @param i the index (1+) of the arg to be set
* @param arg the Term which is to become the i-th (from 1) arg of this Compound
*/
public void setArg(int i, Term arg) {
if (i <= 0) {
throw new JPLException("jpl.Compound#setArg: bad (non-positive) argument index");
}
if (i > args.length) {
throw new JPLException("jpl.Compound#setArg: bad (out-of-range) argument index");
}
if (arg == null) {
throw new JPLException("jpl.Compound#setArg: bad (null) argument");
}
args[i - 1] = arg;
}
//==================================================================/
// Methods (protected)
//==================================================================/
/**
* Returns a quoted (iff necessary) form of the Atom's name, as understood by Prolog read/1
* (I suspect that there are more efficient ways of doing this)
*
* @return a quoted form of the Atom's name, as understood by Prolog read/1
*/
protected String quotedName() {
return ((Atom) (new Query(new Compound("sformat", new Term[] { new Variable("S"), new Atom("~q"), new Compound(".", new Term[] { new Atom(this.name), new Atom("[]") }) }))).oneSolution().get(
"S")).name;
}
//==================================================================/
// Methods (deprecated)
//==================================================================/
/**
* Returns the arguments of this Compound (1..arity) of this Compound as an array[0..arity-1] of Term.
*
* @return the arguments (1..arity) of this Compound as an array[0..arity-1] of Term
* @deprecated
*/
public final Term[] args() {
return args;
}
/**
* Returns the ith argument (counting from 0) of this Compound.
*
* @return the ith argument (counting from 0) of this Compound
* @deprecated
*/
public final Term arg0(int i) {
return args[i];
}
/**
* Returns a debug-friendly representation of a Compound.
*
* @return a debug-friendly representation of a Compound
* @deprecated
*/
public String debugString() {
return "(Compound " + name + " " + Term.debugString(args) + ")";
}
//==================================================================/
// Converting JPL Terms to Prolog terms
//==================================================================/
/**
* To put a Compound in a term, we create a sequence of term_t
* references from the Term.terms_to_term_ts() method, and then
* use the Prolog.cons_functor_v() method to create a Prolog compound
* term.
*
* @param varnames_to_vars A Map from variable names to Prolog variables
* @param term A (previously created) term_t which is to be
* set to a Prolog term corresponding to the Term subtype
* (Atom, Variable, Compound, etc.) on which the method is invoked.
*/
protected final void put(Map varnames_to_vars, term_t term) {
Prolog.cons_functor_v(term, Prolog.new_functor(Prolog.new_atom(name), args.length), Term.putTerms(varnames_to_vars, args));
}
//==================================================================/
// Converting Prolog terms to JPL Terms
//==================================================================/
/**
* Converts the Prolog term in term_t (known to be a compound) to a JPL Compound.
* In this case, we create a list of Terms by calling Term.getTerm for each
* term_t reference we get from Prolog.get_arg
* (Not sure why we couldn't get a sequence from there, but...).<p>
*
* @param varnames_to_vars A Map from variable names to Prolog variables
* @param term The Prolog term to convert
* @return A new Compound
*/
protected static Term getTerm1(Map varnames_to_vars, term_t term) {
ObjectHolder jthing_holder = new ObjectHolder();
StringHolder name_holder = new StringHolder();
IntHolder arity_holder = new IntHolder();
Prolog.get_name_arity(term, name_holder, arity_holder); // assume it succeeds
Term args[] = new Term[arity_holder.value];
for (int i = 1; i <= arity_holder.value; i++) {
term_t termi = Prolog.new_term_ref();
Prolog.get_arg(i, term, termi);
args[i - 1] = Term.getTerm(varnames_to_vars, termi);
}
return new Compound(name_holder.value, args);
}
//==================================================================/
// Computing Substitutions
//==================================================================/
/**
* Nothing needs to be done except to pass the buck to this Compound's args.
*
* @param varnames_to_Terms A Map from variable names to JPL Terms
* @param vars_to_Vars A Map from Prolog variables to JPL Variables
*/
protected final void getSubst(Map varnames_to_Terms, Map vars_to_Vars) {
Term.getSubsts(varnames_to_Terms, vars_to_Vars, args);
}
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,294 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: Float.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 2004 Paul Singleton
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl;
import java.util.Map;
import jpl.fli.DoubleHolder;
import jpl.fli.Prolog;
import jpl.fli.term_t;
//----------------------------------------------------------------------/
// Float
/**
* Float is a specialised Term with a double field, representing a Prolog 64-bit ISO/IEC floating point value.
* Once constructed, a Float's value cannot be altered.
* <pre>
* Float f = new Float( 3.14159265 );
* </pre>
* A Float can be used (and re-used) in Compound Terms.
* Two Float instances are equal (by .equals()) iff their (double) values are equal.
*
* <hr><i>
* Copyright (C) 2004 Paul Singleton<p>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
* @see jpl.Term
* @see jpl.Compound
*/
public class Float extends Term {
//==================================================================/
// Attributes
//==================================================================/
/**
* the Float's immutable value
*/
protected final double value;
//==================================================================/
// Constructors and Initialization
//==================================================================/
/**
* This constructor creates a Float with the supplied
* (double) value.
*
* @param value this Float's value
*/
public Float(double value) {
this.value = value;
}
//==================================================================/
// Methods (common)
//==================================================================/
/**
* throws a JPLException (arg(int) is defined only for Compound and Atom)
*
* @return the ith argument (counting from 1) of this Float (never)
*/
public final Term arg(int i) {
throw new JPLException("jpl.Float#arg(int) is undefined");
}
/**
* The (nonexistent) args of this Float
*
* @return the (nonexistent) args of this Float
*/
public Term[] args() {
return new Term[] {};
}
/**
* Tests whether this Float's functor has (String) 'name' and 'arity' (never)
*
* @return whether this Float's functor has (String) 'name' and 'arity' (never)
*/
public final boolean hasFunctor(String name, int arity) {
return false;
}
/**
* Tests whether this Float's functor has (int) 'name' and 'arity' (never)
*
* @return whether this Float's functor has (int) 'name' and 'arity' (never)
*/
public final boolean hasFunctor(int val, int arity) {
return false;
}
/**
* Tests whether this Float's functor has (double) 'name' and 'arity'
*
* @return whether this Float's functor has (double) 'name' and 'arity'
*/
public final boolean hasFunctor(double val, int arity) {
return val == this.value && arity == 0;
}
/**
* throws a JPLException (name() is defined only for Compound, Atom and Variable)
*
* @return the name of this Float (never)
*/
public final String name() {
throw new JPLException("jpl.Float#name() is undefined");
}
/**
* Returns the arity (0) of this Float
*
* @return the arity (0) of this Float
*/
public final int arity() {
return 0;
}
/**
* returns the (double) value of this Float, converted to an int
*
* @return the (double) value of this Float, converted to an int
*/
public final int intValue() {
return (new Double(value)).intValue();
}
/**
* returns the (double) value of this Float, converted to a long
*
* @return the (double) value of this Float, converted to a long
*/
public final long longValue() {
return (new Double(value)).longValue();
}
/**
* returns the (double) value of this Float, converted to a float
*
* @return the (double) value of this Float, converted to a float
*/
public final float floatValue() {
return (new Double(value)).floatValue();
}
/**
* returns the (double) value of this Float
*
* @return the (double) value of this Float
*/
public final double doubleValue() {
return this.value;
}
public final int type() {
return Prolog.FLOAT;
}
public String typeName(){
return "Float";
}
/**
* Returns a Prolog source text representation of this Float
*
* @return a Prolog source text representation of this Float
*/
public String toString() {
return "" + value + "";
}
/**
* Two Floats are equal if they are the same object, or their values are equal
*
* @param obj The Object to compare
* @return true if the Object satisfies the above condition
*/
public final boolean equals(Object obj) {
return this == obj || (obj instanceof Float && value == ((Float) obj).value);
}
//==================================================================/
// Methods (deprecated)
//==================================================================/
/**
* The immutable value of this jpl.Float object, as a Java double
*
* @return the Float's value
* @deprecated
*/
public double value() {
return value;
}
/**
* Returns a debug-friendly String representation of this Float
*
* @return a debug-friendly String representation of this Float
* @deprecated
*/
public String debugString() {
return "(Float " + toString() + ")";
}
//==================================================================/
// Converting JPL Terms to Prolog terms
//==================================================================/
/**
* To convert a JPL Float to a Prolog term, we put its value field into the
* term_t as a float.
*
* @param varnames_to_vars A Map from variable names to Prolog variables.
* @param term A (previously created) term_t which is to be
* set to a Prolog float corresponding to this Float's value
*/
protected final void put(Map varnames_to_vars, term_t term) {
Prolog.put_float(term, value);
}
//==================================================================/
// Converting Prolog terms to JPL Terms
//==================================================================/
/**
* Converts a Prolog term (known to be a float) to a JPL Float.
*
* @param vars_to_Vars A Map from Prolog variables to JPL Variables
* @param term The Prolog term (a float) to convert
* @return A new Float instance
*/
protected static Term getTerm1(Map vars_to_Vars, term_t term) {
DoubleHolder double_holder = new DoubleHolder();
Prolog.get_float(term, double_holder); // assume it succeeds...
return new jpl.Float(double_holder.value);
}
//==================================================================/
// Computing Substitutions
//==================================================================/
/**
* Nothing needs to be done if the Term is an Atom, Integer or (as in this case) a Float
*
* @param varnames_to_Terms A Map from variable names to JPL Terms
* @param vars_to_Vars A Map from Prolog variables to JPL Variables
*/
protected final void getSubst(Map varnames_to_Terms, Map vars_to_Vars) {
}
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,268 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: Integer.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 2004 Paul Singleton
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl;
import java.util.Map;
import jpl.fli.Int64Holder;
import jpl.fli.Prolog;
import jpl.fli.term_t;
//----------------------------------------------------------------------/
// Integer
/**
* Integer is a specialised Term with a long field, representing a Prolog integer value.
* <pre>
* Integer i = new Integer(1024);
* </pre>
* Once constructed, the value of an Integer instance cannot be altered.
* An Integer can be used (and re-used) as an argument of Compounds.
* Beware confusing jpl.Integer with java.lang.Integer.
*
* <hr><i>
* Copyright (C) 2004 Paul Singleton<p>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
* @see jpl.Term
* @see jpl.Compound
*/
public class Integer extends Term {
//==================================================================/
// Attributes
//==================================================================/
/**
* the Integer's immutable long value
*/
protected final long value;
//==================================================================/
// Constructors
//==================================================================/
/**
* @param value This Integer's (long) value
*/
public Integer(long value) {
this.value = value;
}
//==================================================================/
// Methods (common)
//==================================================================/
/**
* The (nonexistent) args of this Integer
*
* @return the (nonexistent) args of this Integer
*/
public Term[] args() {
return new Term[] {
};
}
/**
* Tests whether this Integer's functor has (int) 'name' and 'arity' (c.f. functor/3)
*
* @return whether this Integer's functor has (int) 'name' and 'arity'
*/
public final boolean hasFunctor(int val, int arity) {
return val == this.value && arity == 0;
}
/**
* throws a JPLException (name() is defined only for Compound, Atom and Variable)
*
* @return the name of this Integer (never)
*/
public final String name() {
throw new JPLException("jpl.Integer#name() is undefined");
}
/**
* Returns the arity (0) of this jpl.Integer (c.f. functor/3)
*
* @return the arity (0) of this jpl.Integer
*/
public final int arity() {
return 0;
}
/**
* Returns the value of this Integer as an int if possible, else throws a JPLException
*
* @throws JPLException if the value of this Integer is too great to be represented as a Java int
* @return the int value of this Integer
*/
public final int intValue() {
if (value < java.lang.Integer.MIN_VALUE || value > java.lang.Integer.MAX_VALUE) {
throw new JPLException("cannot represent Integer value as an int");
} else {
return (int) value;
}
}
/**
* Returns the value of this Integer as a long
*
* @return the value of this Integer as a long
*/
public final long longValue() {
return value;
}
/**
* Returns the value of this Integer converted to a float
*
* @return the value of this Integer converted to a float
*/
public final float floatValue() {
return (new java.lang.Long(value)).floatValue(); // safe but inefficient...
}
/**
* Returns the value of this Integer converted to a double
*
* @return the value of this Integer converted to a double
*/
public final double doubleValue() {
return (new java.lang.Long(value)).doubleValue(); // safe but inefficient...
}
public final int type() {
return Prolog.INTEGER;
}
public String typeName(){
return "Integer";
}
/**
* Returns a Prolog source text representation of this Integer's value
*
* @return a Prolog source text representation of this Integer's value
*/
public String toString() {
return "" + value; // hopefully invokes Integer.toString() or equivalent
}
/**
* Two Integer instances are equal if they are the same object, or if their values are equal
*
* @param obj The Object to compare (not necessarily an Integer)
* @return true if the Object satisfies the above condition
*/
public final boolean equals(Object obj) {
return this == obj || (obj instanceof Integer && value == ((Integer) obj).value);
}
//==================================================================/
// Methods (deprecated)
//==================================================================/
/**
* Returns the int value of this jpl.Integer
*
* @return the Integer's value
* @deprecated
*/
public final int value() {
return (int) value;
}
/**
* Returns a debug-friendly representation of this Integer's value
*
* @return a debug-friendly representation of this Integer's value
* @deprecated
*/
public String debugString() {
return "(Integer " + toString() + ")";
}
//==================================================================/
// Converting JPL Terms to Prolog terms
//==================================================================/
/**
* To convert an Integer into a Prolog term, we put its value into the term_t.
*
* @param varnames_to_vars A Map from variable names to Prolog variables.
* @param term A (previously created) term_t which is to be
* set to a Prolog integer
*/
protected final void put(Map varnames_to_vars, term_t term) {
Prolog.put_integer(term, value);
}
//==================================================================/
// Converting Prolog terms to JPL Terms
//==================================================================/
/**
* Converts a Prolog term (known to be an integer) to a new Integer instance.
*
* @param vars_to_Vars A Map from Prolog variables to JPL Variables
* @param term The Prolog term (an integer) which is to be converted
* @return A new Integer instance
*/
protected static Term getTerm1(Map vars_to_Vars, term_t term) {
Int64Holder int64_holder = new Int64Holder();
Prolog.get_integer(term, int64_holder); // assume it succeeds...
return new jpl.Integer(int64_holder.value);
}
//==================================================================/
// Computing Substitutions
//==================================================================/
/**
* Nothing needs to be done if the Term is an Atom, Integer or Float
*
* @param varnames_to_Terms A Map from variable names to Terms.
* @param vars_to_Vars A Map from Prolog variables to JPL Variables.
*/
protected final void getSubst(Map varnames_to_Terms, Map vars_to_Vars) {
}
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,217 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: JBoolean.java,v 1.1 2004-08-27 20:27:56 vsc Exp $
// Date: $Date: 2004-08-27 20:27:56 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 2004 Paul Singleton
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl;
import java.util.Map;
import jpl.fli.BooleanHolder;
import jpl.fli.Prolog;
import jpl.fli.term_t;
//----------------------------------------------------------------------/
// JBoolean
/**
* A jpl.JBoolean is a specialised Term with a boolean field, representing JPL's Prolog representation of a Java boolean value.
* <pre>
* JBoolean b = new JBoolean( true or false );
* </pre>
* A JBoolean can be used (and re-used) in Compound Terms.
*
* <hr><i>
* Copyright (C) 2004 Paul Singleton<p>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.1 $
* @see jpl.Term
* @see jpl.Compound
*/
public class JBoolean extends Term {
//==================================================================/
// Attributes
//==================================================================/
/**
* the JBoolean's value (a boolean)
*/
protected final boolean value;
//==================================================================/
// Constructors
//==================================================================/
/**
* Constructs a JBoolean with the supplied boolean value.
*
* @param b this JBoolean's value (a boolean)
*/
public JBoolean(boolean b) {
this.value = b;
}
//==================================================================/
// Methods (common)
//==================================================================/
/**
* Tests whether this JBoolean's functor has (String) 'name' and 'arity'
*
* @return whether this JBoolean's functor has (String) 'name' and 'arity'
*/
public final boolean hasFunctor(String name, int arity) {
return name.equals("@") && arity==1;
}
/**
* Returns a Prolog source text representation of this JBoolean
*
* @return a Prolog source text representation of this JBoolean
*/
public String toString() {
return (value ? "@(true)" : "@(false)");
}
/**
* Two JBooleans are equal if their values are equal
*
* @param obj The Object to compare (not necessarily a JBoolean)
* @return true if the Object satisfies the above condition
*/
public final boolean equals(Object obj) {
return this == obj || (obj instanceof JBoolean && value == ((JBoolean) obj).value);
}
//==================================================================/
// Methods (peculiar)
//==================================================================/
/**
* The boolean value which this jpl.JBoolean object represents
*
* @return the boolean value which this jpl.JBoolean object represents
*/
public boolean boolValue() {
return value;
}
public final int type() {
return Prolog.JBOOLEAN;
}
public String typeName(){
return "JBoolean";
}
//==================================================================/
// Methods (deprecated)
//==================================================================/
/**
* The (nonexistent) args of this JBoolean
*
* @return the (nonexistent) args of this JBoolean
* @deprecated
*/
public Term[] args() {
throw new JPLException("jpl.JBoolean.args() is undefined");
}
/**
* Returns a debug-friendly representation of this JBoolean
*
* @return a debug-friendly representation of this JBoolean
* @deprecated
*/
public String debugString() {
return "(JBoolean " + toString() + ")";
}
//==================================================================/
// Converting JPL Terms to Prolog terms
//==================================================================/
/**
* To convert a JBoolean to a term, we unify the (freshly created, hence unbound)
* term_t with either @(false) or @(true) as appropriate.
*
* @param varnames_to_vars A Map from variable names to Prolog variables.
* @param term A (newly created) term_t which is to be
* set to a Prolog @(false) or @(true) structure denoting the
* .value of this JBoolean instance
*/
protected final void put(Map varnames_to_vars, term_t term) {
Prolog.put_jboolean(term, value);
}
//==================================================================/
// Converting Prolog terms to JPL Terms
//==================================================================/
/**
* Converts a term_t to a JBoolean. If the Prolog term is either
* @(false) or @(true), we just create a new JBoolean with a corresponding value.
* NB This conversion is only invoked if "JPL-aware" term import is specified.
*
* @param vars_to_Vars A Map from Prolog variable to JPL Variables.
* @param term The term (either @(false) or @(true)) to convert
* @return A new JBoolean instance
*/
protected static Term getTerm(Map vars_to_Vars, term_t term) {
BooleanHolder b = new BooleanHolder();
Prolog.get_jboolean(term, b); // assume it succeeds...
return new jpl.JBoolean(b.value);
}
//==================================================================/
// Computing Substitutions
//==================================================================/
/**
* Nothing needs to be done if the Term denotes an Atom, Integer, Float, JRef or JBoolean
*
* @param varnames_to_Terms A Map from variable names to Terms.
* @param vars_to_Vars A Map from Prolog variables to JPL Variables.
*/
protected final void getSubst(Map varnames_to_Terms, Map vars_to_Vars) {
}
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,211 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: JPL.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 2004 Paul Singleton
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl;
import jpl.fli.Prolog;
//----------------------------------------------------------------------/
// JPL
/**
* The jpl.JPL class contains methods which allow (i) inspection and alteration
* of the "default" initialisation arguments (ii) explicit initialisation
* (iii) discovery of whether the Prolog engine is already initialised,
* and if so, with what arguments.
* The Prolog engine must be initialized
* before any queries are made, but this will happen automatically
* (upon the first call to a Prolog FLI routine) if it has not already
* been done explicitly.
*
* <hr><i>
* Copyright (C) 2004 Paul Singleton<p>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
*/
public class JPL {
protected static final boolean DEBUG = false;
//
public static final Term JFALSE = new Compound("@", new Term[] {new Atom("false")});
public static final Term JTRUE = new Compound("@", new Term[] {new Atom("true")});
public static final Term JNULL = new Compound("@", new Term[] {new Atom("null")});
public static final Term JVOID = new Compound("@", new Term[] {new Atom("void")});
protected static boolean modeDontTellMe = true;
// setDTMMode
/**
* Sets the global "dont-tell-me" mode (default value: true).
* When 'true', bindings will *not* be returned for any variable (in a Query's goal)
* whose name begins with an underscore character (except for "anonymous" variables,
* i.e. those whose name comprises just the underscore character, whose bindings are never returned).
* When 'false', bindings are returned for *all* variables except anonymous ones;
* this mode may be useful when traditional top-level interpreter behaviour is wanted,
* e.g. in a Java-based Prolog IDE or debugger.<p>
* This method should be regarded as experimental, and may subsequently be deprecated
* in favour of some more general mechanism for setting options, perhaps per-Query and
* per-call as well as globally.
*
* @param dtm new "dont-tell-me" mode value
*/
public static void setDTMMode( boolean dtm){
modeDontTellMe = dtm;
}
// getDefaultInitArgs
/**
* Returns, in an array of String, the sequence of command-line
* arguments that would be used if the Prolog engine were to be initialised now.
* Returns null if the Prolog VM has already been initialised (in which
* case the default init args are irrelevant and the actual init args are of interest)<p>
*
* @see jpl.JPL#getActualInitArgs
* @return current default initialisation arguments, or null if already initialised
*/
public static String[] getDefaultInitArgs() {
return Prolog.get_default_init_args();
}
// setDefaultInitArgs
/**
* Specifies, in an array of String, the sequence of command-line
* arguments that should be used if the Prolog engine is subsequently initialised.<p>
*
* @param args new default initialization arguments
*/
public static void setDefaultInitArgs(String[] args) {
Prolog.set_default_init_args(args);
}
// getActualInitArgs
/**
* Returns, in an array of String, the sequence of command-line
* arguments that were actually used when the Prolog engine was formerly initialised.
*
* This method returns null if the Prolog engine has not yet been initialised,
* and thus may be used to test this condition.
*
* @return actual initialization arguments
*/
public static String[] getActualInitArgs() {
return Prolog.get_actual_init_args();
}
// init
/**
* Initializes the Prolog engine, using the String argument
* parameters passed. This method need be called only if you want to both
* (i) initialise the Prolog engine with parameters other than the default ones
* and (ii) force initialisation to occur
* (rather than allow it to occur automatically at the first query).
* For parameter options, consult your local
* Prolog documentation. The parameter values are passed directly
* to initialization routines for the Prolog environment.<p>
*
* This method must be called before making any queries.
*
* @param args Initialization parameter list
*/
public static boolean init(String[] args) {
return Prolog.set_default_init_args(args) && init();
}
// init
/**
* Initialises the Prolog engine using the current default initialisation parameters,
* and returns 'true' (or 'false' if already initialised).
*/
public static boolean init() {
return Prolog.initialise();
}
// isTag(String)
/**
* whether the String arg is a plausible tag, e.g. "J#0123456789".
*/
public static boolean isTag(String s) {
return s.length()==12 && s.charAt(0)=='J' && s.charAt(1)=='#' && Character.isDigit(s.charAt(2)) && Character.isDigit(s.charAt(3)) && Character.isDigit(s.charAt(4)) && Character.isDigit(s.charAt(5)) && Character.isDigit(s.charAt(6)) && Character.isDigit(s.charAt(7)) && Character.isDigit(s.charAt(8)) && Character.isDigit(s.charAt(9)) && Character.isDigit(s.charAt(10)) && Character.isDigit(s.charAt(11));
}
// newJRef(Object)
/**
* returns a new Term instance which represents the given object
*/
public static Term newJRef(Object obj) {
return new Compound( "@", new Term[]{new Atom(Prolog.object_to_tag(obj))});
}
// halt
/**
* Terminates the Prolog session.<p>
*
* <b>Note.</b> This method calls the FLI halt() method with a
* status of 0, but the halt method currently is a no-op in SWI.
* @deprecated
*/
public static void halt() {
Prolog.halt(0);
}
// a static reference to the current Version
private static final Version version_ = new Version();
// version
/**
* Returns (as a Version) an identification of this version of JPL.
* @return the running version of JPL.
*/
public static Version version() {
return version_;
}
// version_string
/**
* Returns a String (eg "3.0.0-alpha") identifying this version of JPL.
* @return a String (eg "3.0.0-alpha") identifying this version of JPL.
*/
public static String version_string() {
return version_.major + "." + version_.minor + "." + version_.patch + "-" + version_.status;
}
public static void main(String[] args) {
System.out.println(version_string());
}
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,63 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: JPLException.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 2004 Paul Singleton
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl;
//----------------------------------------------------------------------/
// JPLException
/**
* This is the base class for exceptions thrown by JPL's Java-calls-Prolog interface.
* Such exceptions represent errors and exceptional conditions within the interface code itself;
* see jpl.PrologException for the way Prolog exceptions are returned to calling Java code.
* <hr><i>
* Copyright (C) 2004 Paul Singleton<p>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
*/
public class JPLException extends RuntimeException {
private static final long serialVersionUID = 1L;
public JPLException() {
super();
}
public JPLException(String s) {
super(s);
}
}

View File

@ -1,195 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: JRef.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 2004 Paul Singleton
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl;
import java.util.Map;
import jpl.fli.Prolog;
import jpl.fli.term_t;
//----------------------------------------------------------------------/
// JRef
/**
* JRef is a specialised Term with an Object field, representing JPL's Prolog references to Java objects (or to null).
* <pre>
* JRef r = new JRef( non_String_object_or_null );
* </pre>
* A JRef can be used (and re-used) in Compound Terms.
*
* <hr><i>
* Copyright (C) 2004 Paul Singleton<p>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
* @see jpl.Term
* @see jpl.Compound
*
* @deprecated
*/
public class JRef extends Term {
//==================================================================/
// Attributes
//==================================================================/
/**
* the JRef's value (a non-String Object or null)
*/
protected final Object ref;
//==================================================================/
// Constructors
//==================================================================/
/**
* This constructor creates a JRef, initialized with the supplied
* non-String object (or null).
*
* @param ref this JRef's value (a non-String object, or null)
*/
public JRef(Object ref) {
if (ref instanceof String) {
throw new JPLException("a JRef cannot have a String value (String maps to atom)");
} else {
this.ref = ref;
}
}
//==================================================================/
// Methods (common)
//==================================================================/
/**
* Returns a Prolog source text representation of this JRef
*
* @return a Prolog source text representation of this JRef
*/
public String toString() {
return "" + ref + ""; // WRONG
}
/**
* Two JRefs are equal if their references are identical (?)
*
* @param obj The Object to compare
* @return true if the Object satisfies the above condition
*/
public final boolean equals(Object obj) {
return this == obj || (obj instanceof JRef && ref == ((JRef) obj).ref);
}
public final int type() {
return Prolog.JREF;
}
public String typeName(){
return "JRef";
}
//==================================================================/
// Methods (peculiar)
//==================================================================/
/**
* The non-String object (or null) which this jpl.JRef represents
*
* @return the non-String object (or null) which this jpl.JRef represents
*/
public Object ref() {
return ref;
}
//==================================================================/
// Methods (deprecated)
//==================================================================/
/**
* The (nonexistent) args of this JRef
*
* @return the (nonexistent) args of this JRef
* @deprecated
*/
public Term[] args() {
return new Term[] {
};
}
/**
* Returns a debug-friendly representation of this JRef
*
* @return a debug-friendly representation of this JRef
* @deprecated
*/
public String debugString() {
return "(JRef " + toString() + ")";
}
//==================================================================/
// Converting JPL Terms to Prolog terms
//==================================================================/
/**
* To convert a JRef to a term, we put its Object field (.value) into the
* term_t as a JPL ref (i.e. @/1) structure.
*
* @param varnames_to_vars A Map from variable names to Prolog variables.
* @param term A (newly created) term_t which is to be
* set to a Prolog 'ref' (i.e. @/1) structure denoting the
* .value of this JRef instance
*/
protected final void put(Map varnames_to_vars, term_t term) {
Prolog.put_jref(term, ref);
}
//==================================================================/
// Computing Substitutions
//==================================================================/
/**
* Nothing needs to be done if the Term is an Atom, Integer, Float or JRef
*
* @param varnames_to_Terms A Map from variable names to Terms.
* @param vars_to_Vars A Map from Prolog variables to JPL Variables.
*/
protected final void getSubst(Map varnames_to_Terms, Map vars_to_Vars) {
}
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,185 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: JVoid.java,v 1.1 2004-08-27 20:27:56 vsc Exp $
// Date: $Date: 2004-08-27 20:27:56 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 2004 Paul Singleton
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl;
import java.util.Map;
import jpl.fli.Prolog;
import jpl.fli.term_t;
//----------------------------------------------------------------------/
// JVoid
/**
* A jpl.JVoid is a specialised Term. Instances of this class
* denote JPL 'jvoid' values in Prolog, i.e. @(void):
* <pre>
* JVoid b = new JVoid();
* </pre>
* A JVoid can be used (and re-used) in Compound Terms.
*
* <hr><i>
* Copyright (C) 2004 Paul Singleton<p>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.1 $
* @see jpl.Term
* @see jpl.Compound
*/
public class JVoid extends Term {
//==================================================================/
// Attributes (none)
//==================================================================/
//==================================================================/
// Constructors
//==================================================================/
/**
* This constructor creates a JVoid.
*
*/
public JVoid() {
}
//==================================================================/
// Methods (common)
//==================================================================/
/**
* Returns a Prolog source text representation of this JVoid
*
* @return a Prolog source text representation of this JVoid
*/
public String toString() {
return "@(void)";
}
/**
* Two JVoids are equal
*
* @param obj The Object to compare (not necessarily another JVoid)
* @return true if the Object satisfies the above condition
*/
public final boolean equals(Object obj) {
return this == obj || (obj instanceof JVoid);
}
public final int type() {
return Prolog.JVOID;
}
public String typeName(){
return "JVoid";
}
//==================================================================/
// Methods (deprecated)
//==================================================================/
/**
* The (nonexistent) args of this JVoid
*
* @return the (nonexistent) args of this JVoid
* @deprecated
*/
public Term[] args() {
return new Term[] {};
}
/**
* Returns a debug-friendly representation of this JVoid
*
* @return a debug-friendly representation of this JVoid
* @deprecated
*/
public String debugString() {
return "(JVoid)";
}
//==================================================================/
// Converting JPL Terms to Prolog terms
//==================================================================/
/**
* To convert a JVoid to a term, we unify the (freshly created, hence unbound)
* term_t with @(void).
*
* @param varnames_to_vars A Map from variable names to Prolog variables.
* @param term A (previously created and unbound) term_t which is to be
* assigned a Prolog @(void) structure
*/
protected final void put(Map varnames_to_vars, term_t term) {
Prolog.put_jvoid(term);
}
//==================================================================/
// Converting Prolog terms to JPL Terms
//==================================================================/
/**
* Converts a term_t to a JVoid. Assuming the Prolog term to be
* @(void), we just create a new JVoid instance.
* NB This conversion is only invoked if "JPL-aware" term import is specified.
*
* @param vars_to_Vars A Map from Prolog variables to JPL Variables.
* @param term The term_t to convert
* @return A new JVoid instance
*/
protected static Term getTerm(Map vars_to_Vars, term_t term) {
return new jpl.JVoid();
}
//==================================================================/
// Computing Substitutions
//==================================================================/
/**
* Nothing needs to be done if the Term denotes an Atom, Integer, Float, JRef, JBoolean or JVoid
*
* @param varnames_to_Terms A Map from variable names to Terms.
* @param vars_to_Vars A Map from Prolog variables to JPL Variables.
* Variables.
*/
protected final void getSubst(Map varnames_to_Terms, Map vars_to_Vars) {
}
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,75 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: PrologException.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 2004 Paul Singleton
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl;
//----------------------------------------------------------------------/
// PrologException
/**
* PrologException instances wrap Prolog exceptions thrown (either by a Prolog engine or by user code)
* in the course of finding a solution to a Query. See JPLException for the handling of errors within the JPL Java-calls-Prolog interface.
* <p>
* This class allows Java code which uses JPL's Java-calls-Prolog API to handle
* Prolog exceptions, which is in general necessary for hybrid Java+Prolog programming.
* <p>
* Use the term() accessor to obtain a Term representation of the term that was
* thrown from within Prolog.
*
* <hr><i>
* Copyright (C) 2004 Paul Singleton<p>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
*/
public final class PrologException extends JPLException {
private static final long serialVersionUID = 1L;
private Term term_ = null;
protected PrologException(Term term) {
super("PrologException: " + term.toString());
this.term_ = term;
}
/**
* @return a reference to the Term thrown by the call to throw/1
*/
public Term term() {
return this.term_;
}
}

View File

@ -1,869 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: Query.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 2004 Paul Singleton
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map;
import java.util.Vector;
import jpl.fli.*;
//----------------------------------------------------------------------/
// Query
/**
* A Query instance is created by an application in order to query the Prolog database
* (or to invoke a built-in predicate).
* It is initialised with a
* Compound (or Atom) denoting the goal which is to be called, and also contains assorted private state
* relating to solutions. In some future version, it may contain details of the module
* in which the goal is to be called.<p>
* A Query is either open or closed: when closed, it has no connection to the Prolog system;
* when open, it is linked to an active goal within a Prolog engine.<p>
* The Query class implements the Enumeration interface,
* through which one can obtain successive solutions. The Enumeration
* hasMoreElements() method returns true if the call or redo succeeded (otherwise
* false), and if the call or redo did succeed, the nextElement() method returns
* a Hashtable representing variable bindings; the elements in the
* Hashtable are Terms, indexed by the (String) names of the Variables with which they are associated.
* For example, if <i>p(a)</i> and <i>p(b)</i> are facts in the Prolog
* database, then the following is equivalent to printing all
* the solutions to the Prolog query <i>p(X)</i>:
* <pre>
* Variable X = new Variable("X");
* Term arg[] = { X };
* Query q = new Query("p", arg);
*
* while (q.hasMoreElements()){
* Term bound_to_x = ((Hashtable) q.nextElement()).get("X");
* System.out.println(bound_to_x);
* }
* </pre>
* Make sure to close the Query (using the close() method) if you do not need
* any further solutions which it may have.
* It is safe (although redundant) to close a Query whose solutions are already exhausted,
* or which is already closed.
*
* To obtain just one solution from a Query, use the oneSolution() method.
*
* To obtain all solutions, use the allSolutions() method.
*
* To obtain at most N solutions, use the nSolutions() method.
*
* To determine merely whether the Query is provable,
* use the hasSolution() method
* (i.e. has at least one solution).
* <hr>
* <i>
* Copyright (C) 2007 Paul Singleton<p>
* Copyright (C) 1998 Fred Dushin
* <p>
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* <p>
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i>
* <hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
*/
// Implementation notes:
//
//----------------------------------------------------------------------/
public class Query implements Enumeration {
//==================================================================/
// Attributes
//==================================================================/
private static Map m = new Hashtable(); // maps (engine_t) engine handle to (Query) topmost query
/**
* the Compound (hence perhaps an Atom, but not Integer, Float or Variable) corresponding to the goal of this Query
*/
protected final Compound goal_; // set by all initialisers
protected final String hostModule = "user"; // until revised constructors allow this to be specified
protected final String contextModule = "user"; // until revised constructors allow this to be specified
/**
* @deprecated Use .goal().name() instead.
* @return the name of this Query's goal (redundant, deprecated)
*/
public final String name() {
return goal_.name(); // it can only be a Compound or Atom
}
/**
* @deprecated Use .goal().args() instead.
* @return the arguments of this Query's goal (redundant, deprecated)
*/
public final Term[] args() {
return goal_.args();
}
/**
* Returns the Compound (hence perhaps an Atom) which is the goal of this Query
* @return a Term representing the goal of this Query
*/
public final Compound goal() {
return goal_;
}
//==================================================================/
// Constructors and Initialization
//==================================================================/
//------------------------------------------------------------------/
// Query
/**
* This constructor creates a Query whose goal is the specified Term.
* The Query is initially closed.
* <b>NB</b> Creating an instance of the Query class does not
* result in a call to a Prolog engine.
* <b>NB</b> The goal can be a Compound or an Atom (Atom extends Compound), but cannot be an instance
* of jpl.Float, jpl.Integer or jpl.Variable.
* @param t the goal of this Query
*/
public Query(Term t) { // formerly insisted (confusingly) on a Compound (or Atom)
this.goal_ = Query1(t);
}
private Compound Query1(Term t) {
if (t instanceof Compound) {
return (Compound) t;
} else if (t instanceof Integer) {
throw new JPLException("a Query's goal must be an Atom or Compound (not an Integer)");
} else if (t instanceof Float) {
throw new JPLException("a Query's goal must be an Atom or Compound (not a Float)");
} else if (t instanceof Variable) {
throw new JPLException("a Query's goal must be an Atom or Compound (not a Variable)");
} else {
throw new JPLException("a Query's goal must be an Atom or Compound");
}
}
// Query
/**
* If text denotes an atom, this constructor is shorthand for
* <font face="monospace">new Query(new Compound(name,args))</font>,
* but if text denotes a term containing N query (?) symbols
* and there are N args, each query is replaced by its corresponding arg
* to provide the new Query's goal.
*
* @param text the name of the principal functor of this Query's goal
* @param args the arguments of this Query's goal
*/
public Query(String text, Term[] args) {
this(Query1(text, args));
}
// convenience case for a single arg
public Query(String text, Term arg) {
this(Query1(text, new Term[] { arg }));
}
private static Term Query1(String text, Term[] args) {
Term t = Util.textToTerm(text);
if (t instanceof Atom) {
return new Compound(text, args);
} else {
return t.putParams(args);
}
}
// Query
/**
* This constructor builds a Query from the given Prolog source text.
* Throws PrologException containing error(syntax_error(_),_) if text is invalid.
*
* @param text the Prolog source text of this Query
*/
public Query(String text) {
this(Util.textToTerm(text));
}
//==================================================================/
// Making Prolog Queries
//==================================================================/
/**
* These variables are used and set across the hasMoreElements
* and nextElement Enumeration interface implementation
*/
private boolean open = false;
// the following state variables are used and defined only if this query is open:
// private boolean called = false; // open/get/close vs. hasMoreSolutions/nextSolution
private engine_t engine = null; // handle of attached Prolog engine iff open, else null
private Query subQuery = null; // the open Query (if any) on top of which this open Query is stacked, else null
private predicate_t predicate = null; // handle of this Query's predicate iff open, else undefined
// private fid_t fid = null; // id of current Prolog foreign frame iff open, else null
// private fid_t fid2 = null; // id of experimental inner frame
private term_t term0 = null; // term refs of this Query's args iff open, else undefined
private qid_t qid = null; // id of current Prolog query iff open, else null
//------------------------------------------------------------------/
// hasMoreSolutions
/**
* This method returns true if JPL was able to initiate a "call" of this
* Query within a Prolog engine. It is designed to be used
* with the nextSolution() method to retrieve one or
* more substitutions in the form of Hashtables. To iterate through
* all the solutions to a Query, for example, one might write
* <pre>
* Query q = // obtain Query reference
* while (q.hasMoreSolutions()) {
* Hashtable solution = q.nextSolution();
* // process solution...
* }
* </pre>
* To ensure thread-safety, you should wrap sequential calls to
* this method in a synchronized block, using the static
* lock method to obtain the monitor.
* <pre>
* Query q = // obtain Query reference
* synchronized ( jpl.Query.lock() ){
* while ( q.hasMoreElements() ){
* Hashtable solution = q.nextSolution();
* // process solution...
* }
* }
* </pre>
*
* @return true if the Prolog query succeeds; otherwise false.
*/
public synchronized final boolean hasMoreSolutions() {
if (!open) {
open();
}
return get1();
}
//------------------------------------------------------------------/
// open
/**
* This method returns true if JPL was able to initiate a "call" of this
* Query within the Prolog engine. It is designed to be used
* with the getSolution() and close() methods to retrieve one or
* more substitutions in the form of Hashtables.
* To ensure thread-safety, you should wrap sequential calls to
* this method in a synchronized block, using the static
* lock method to obtain the monitor.
* <pre>
* Query q = // obtain Query reference
* synchronized ( jpl.Query.lock() ){
* while ( q.hasMoreElements() ){
* Hashtable solution = q.nextSolution();
* // process solution...
* }
* }
* </pre>
* <p>
* If this method is called on an already-open Query,
* or if the query cannot be set up for whatever reason,
* then a JPLException will be thrown.
*/
public synchronized final void open() {
if (open) {
throw new JPLException("Query is already open");
}
// int self = Prolog.thread_self();
// System.out.println("JPL thread_self()=" + self);
if (Prolog.thread_self() == -1) { // this Java thread has no attached Prolog engine?
engine = Prolog.attach_pool_engine(); // may block for a while, or fail
// System.out.println("JPL attaching engine[" + engine.value + "] for " + this.hashCode() + ":" + this.toString());
} else { // this Java thread has an attached engine
engine = Prolog.current_engine();
// System.out.println("JPL reusing engine[" + engine.value + "] for " + this.hashCode() + ":" + this.toString());
}
if (m.containsKey(new Long(engine.value))) {
subQuery = (Query) m.get(new Long(engine.value)); // get this engine's previous topmost query
// System.out.println("JPL reusing engine[" + engine.value + "] pushing " + subQuery.hashCode() + ":" + subQuery.toString());
} else {
subQuery = null;
}
m.put(new Long(engine.value), this); // update this engine's topmost query
//
// here, we must check for a module prefis, e.g. jpl:jpl_modifier_bit(volatile,T)
String module;
Term goal;
if (goal_.hasFunctor(":", 2)) {
if (goal_.arg(1).isAtom()) {
module = goal_.arg(1).name();
} else if (goal_.arg(1).isVariable()) {
throw new PrologException(Util.textParamsToTerm("error(instantiation_error,?)", new Term[] { goal_ }));
} else {
throw new PrologException(Util.textParamsToTerm("error(type_error(atom,?),?)", new Term[] { goal_.arg(1), goal_ }));
}
goal = goal_.arg(2);
} else {
module = contextModule;
goal = goal_;
}
predicate = Prolog.predicate(goal.name(), goal.arity(), module); // was hostModule
// fid = Prolog.open_foreign_frame(); // always succeeds?
Map varnames_to_vars = new Hashtable();
term0 = Term.putTerms(varnames_to_vars, goal.args());
// THINKS: invert varnames_to_Vars and use it when getting substitutions?
qid = Prolog.open_query(Prolog.new_module(Prolog.new_atom(contextModule)), Prolog.Q_CATCH_EXCEPTION, predicate, term0);
open = true;
// called = false;
}
private final boolean get1() { // try to get the next solution; if none, close the query;
// if (fid2 != null) { // PS 23/Mar/2007 ensure inner frame is closed
// Prolog.close_foreign_frame(fid2);
// fid2 = null;
// }
if (Prolog.next_solution(qid)) {
// fid2 = Prolog.open_foreign_frame(); // PS 23/Mar/2007 open an inner frame
// called = true; // OK to call get2()
return true;
} else {
// if failure was due to throw/1, build exception term and throw it
term_t exception_term_t = Prolog.exception(qid);
if (exception_term_t.value != 0L) {
Term exception_term = Term.getTerm(new Hashtable(), exception_term_t);
close();
throw new PrologException(exception_term);
} else {
close();
return false;
}
}
}
//------------------------------------------------------------------/
// getSolution
/**
* This method returns a java.util.Hashtable, which represents
* a set of bindings from the names of query variables to terms within the solution.
* <p>
* For example, if a Query has an occurrence of a jpl.Variable,
* say, named "X", one can obtain the Term bound to "X" in the solution
* by looking up "X" in the Hashtable.
* <pre>
* Variable x = new Variable("X");
* Query q = // obtain Query reference (with x in the Term array)
* while (q.hasMoreSolutions()) {
* Hashtable solution = q.nextSolution();
* // make t the Term bound to "X" in the solution
* Term t = (Term) solution.get("X");
* // ...
* }
* </pre>
* Programmers should obey the following rules when using this method.
* <menu>
* <li> The nextSolution() method should only be called after the
* hasMoreSolutions() method returns true; otherwise a JPLException
* will be raised, indicating that the Query is no longer open.
* <li> The nextSolution() and hasMoreSolutions() should be called
* in the same thread of execution, for a given Query
* instance.
* </menu>
*
* This method will throw a JPLException if Query is not open.
*
* @return A Hashtable representing a substitution, or null
*/
public synchronized final Hashtable getSolution() {
// oughta check: Query is open and thread has its engine
if (get1()) {
return get2();
} else {
return null;
}
}
public synchronized final Hashtable getSubstWithNameVars() {
// oughta check: Query is open and thread has its engine
if (get1()) {
return get2WithNameVars();
} else {
return null;
}
}
//------------------------------------------------------------------/
// nextSolution
/**
* This method returns a java.util.Hashtable, which represents
* a binding from the names of query variables to terms within the solution.
* <p>
* For example, if a Query has an occurrence of a jpl.Variable,
* say, named "X", one can obtain the Term bound to "X" in the solution
* by looking up "X" in the Hashtable.
* <pre>
* Variable x = new Variable("X");
* Query q = // obtain Query reference (with x in the Term array)
* while (q.hasMoreSolutions()) {
* Hashtable solution = q.nextSolution();
* // make t the Term bound to "X" in the solution
* Term t = (Term) solution.get("X");
* // ...
* }
* </pre>
* Programmers should obey the following rules when using this method.
* <menu>
* <li> The nextSolution() method should only be called after the
* hasMoreSolutions() method returns true; otherwise a JPLException
* will be raised, indicating that the Query is no longer open.
* <li> The nextSolution() and hasMoreSolutions() should be called
* in the same thread of execution, for a given Query
* instance.
* </menu>
*
* This method will throw a JPLException if Query is not open.
*
* @return A Hashtable representing a substitution.
*/
public synchronized final Hashtable nextSolution() {
return get2();
}
private final Hashtable get2() {
if (!open) {
throw new JPLException("Query is not open");
} else {
Hashtable substitution = new Hashtable();
// NB I reckon computeSubstitutions needn't be in Term (but where else?)
Term.getSubsts(substitution, new Hashtable(), goal_.args);
return substitution;
}
}
// assumes that Query's last arg is a Variable which will be bound to a [Name=Var,..] dict
private final Hashtable get2WithNameVars() {
if (!open) {
throw new JPLException("Query is not open");
} else {
Term[] args = goal_.args; // for slight convenience below
Term argNV = args[args.length - 1]; // the Query's last arg
String nameNV = ((Variable) argNV).name; // its name
// get the [Name=Var,..] dict from the last arg
Map varnames_to_Terms1 = new Hashtable();
Map vars_to_Vars1 = new Hashtable();
args[args.length - 1].getSubst(varnames_to_Terms1, vars_to_Vars1);
Hashtable varnames_to_Terms2 = new Hashtable();
Term nvs = (Term) varnames_to_Terms1.get(nameNV);
Map vars_to_Vars2 = Util.namevarsToMap(nvs);
for (int i = 0; i < args.length - 1; ++i) {
args[i].getSubst(varnames_to_Terms2, vars_to_Vars2);
}
return varnames_to_Terms2;
}
}
//------------------------------------------------------------------/
// hasMoreElements
/**
* This method implements part of the java.util.Enumeration
* interface. It is a wrapper for hasMoreSolutions.
*
* @return true if the Prolog query yields a (or another) solution, else false.
*/
public synchronized final boolean hasMoreElements() {
return hasMoreSolutions();
}
//------------------------------------------------------------------/
// nextElement
/**
* This method implements part of the java.util.Enumeration
* interface. It is a wrapper for nextSolution.
* <p>
*
* @return A Hashtable representing a substitution.
*/
public synchronized final Object nextElement() {
return nextSolution();
}
public synchronized final void rewind() {
close();
}
/**
* This method can be used to close an open query before its solutions are exhausted.
* It is called automatically when solutions are exhausted, i.e. when hasMoreSolutions() fails.
* Calling close() on an already closed Query is harmless (has no effect).<p>
*
* Here is one way to get the first three solutions to a Query:
* <pre>
* Query q = new Query(predicate, args);
* Hashtable sub1 = (Hashtable) q.nextSolution();
* Hashtable sub2 = (Hashtable) q.nextSolution();
* Hashtable sub3 = (Hashtable) q.nextSolution();
* q.close();
* </pre><p>
*/
public synchronized final void close() {
if (!open) {
return; // it is not an error to attempt to close a closed Query
}
if (Prolog.thread_self() == -1) {
throw new JPLException("no engine is attached to this thread");
}
if (Prolog.current_engine().value != engine.value) {
throw new JPLException("this Query's engine is not that which is attached to this thread");
}
Query topmost = (Query) m.get(new Long(engine.value));
if (topmost != this) {
throw new JPLException("this Query (" + this.hashCode() + ":" + this.toString() + ") is not topmost (" + topmost.hashCode() + ":" + topmost.toString() + ") within its engine["
+ engine.value + "]");
}
Prolog.close_query(qid);
qid = null; // for tidiness
m.remove(new Long(engine.value));
if (subQuery == null) { // only Query open in this engine?
if (Prolog.current_engine_is_pool()) { // this (Query's) engine is from the pool?
Prolog.release_pool_engine();
// System.out.println("JPL releasing engine[" + engine.value + "]");
} else {
// System.out.println("JPL leaving engine[" + engine.value + "]");
}
} else {
m.put(new Long(engine.value), subQuery);
// System.out.println("JPL retaining engine[" + engine.value + "] popping subQuery(" + subQuery.hashCode() + ":" + subQuery.toString() + ")");
}
open = false; // this Query is now closed
engine = null; // this Query, being closed, is no longer associated with any Prolog engine
subQuery = null; // this Query, being closed, is not stacked upon any other Query
}
/**
* calls the Query's goal to exhaustion
* and returns an array of zero or more Hashtables of zero or more variablename-to-term bindings (each Hashtable represents a solution, in the order in which they were found).
* @return an array of zero or more Hashtables of zero or more variablename-to-term bindings (each Hashtable represents a solution, in the order in which they were found)
* <b>NB</b> in JPL 1.0.1, this method (inconsistently) returned null when a Query had no solutions;
* in JPL 2.x onwards it returns an empty array (thus the length of the array is, in every case,
* the quantity of solutions).<p>
* <b>NB</b> in JPL 1.0.1, bindings were keyed (awkwardly) by Variable instances;
* in JPL 2.x onwards they are keyed by the (String) names of variables,
* which is consistent with the Term type being just a concrete syntax for terms (and hence queries).<p>
*/
public synchronized final Hashtable[] allSolutions() {
if (open) {
throw new JPLException("Query is already open");
} else {
// get a vector of solutions:
Vector v = new Vector();
while (hasMoreSolutions()) {
v.addElement(nextSolution());
}
// turn the vector into an array:
Hashtable solutions[] = new Hashtable[v.size()]; // 0 solutions -> Hashtable[0]
v.copyInto(solutions);
return solutions;
}
}
/**
* This static method creates a Query whose goal is the given Term,
* calls it to exhaustion,
* and returns an array of zero or more Hashtables of zero or more variablename-to-term bindings (each Hashtable represents a solution, in the order in which they were found).
* Throws JPLException if goal is neither a jpl.Atom nor a jpl.Compound.
*
* @return an array of zero or more Hashtables of zero or more variablename-to-term bindings (each Hashtable represents a solution, in the order in which they were found)
*
* @param goal the goal of this Query
*/
public static final Hashtable[] allSolutions(Term goal) {
return (new Query(goal)).allSolutions();
}
/**
* This static method creates a Query from the given Prolog source text fragment,
* calls it to exhaustion,
* and returns an array of zero or more Hashtables of zero or more variablename-to-term bindings (each Hashtable represents a solution, in the order in which they were found).
* Throws PrologException containing error(syntax_error(_),_) if text is invalid.
*
* @return an array of zero or more Hashtables of zero or more variablename-to-term bindings (each Hashtable represents a solution, in the order in which they were found)
*
* @param text a Prolog source text fragment denoting a goal
*/
public static final Hashtable[] allSolutions(String text) {
return (new Query(text)).allSolutions();
}
/**
* If text denotes (in traditional Prolog source syntax) a term containing N questionmark (?) symbols and there are N accompanying Term params,
* this static method replaces each questionmark symbol by its respective param,
* calls the resulting goal to exhaustion,
* and returns an array of zero or more Hashtables of zero or more variablename-to-term bindings (each Hashtable represents a solution, in the order in which they were found).
*
* Otherwise, if text denotes an atom, this static method creates a Query
* where text is the name of the goal and params are the args;
* the resulting goal is then called as above.
* This letter mode is redundant, deprecated (informally), and retained only for backward compatibility.
*
* @return an array of zero or more Hashtables of zero or more variablename-to-term bindings (each Hashtable represents a solution, in the order in which they were found)
*
* @param text the Prolog source text of a goal, in which questionmarks are regarded as substitutible parameters
* @param params terms to be substituted for the respective questionmarks in the query text
*/
public static final Hashtable[] allSolutions(String text, Term[] params) {
return (new Query(text, params)).allSolutions();
}
/**
* calls the Query's goal to exhaustion or until N solutions are found, whichever is sooner,
* and returns an array containing (as possibly empty Hashtables of variablename-to-term bindings) every found solution (in the order in which they were found).
* @return an array of Hashtables (possibly none), each of which is a solution
* (in the order in which they were found) of the Query; at most 'n' solutions will be found and returned.
* <b>NB</b> in JPL 1.0.1, this method (inconsistently) returned null when a Query had no solutions;
* in JPL 2.x onwards it returns an empty array (thus the length of the array is, in every case,
* the quantity of solutions).<p>
* <b>NB</b> in JPL 1.0.1, bindings were keyed (awkwardly) by Variable instances;
* in JPL 2.x onwards they are keyed by the (String) names of variables,
* which is consistent with the Term type being just a concrete syntax for terms (and hence queries).<p>
*/
public synchronized final Hashtable[] nSolutions(long n) {
if (open) {
throw new JPLException("Query is already open");
} else {
// get a vector of solutions:
Vector v = new Vector();
for (long i = 0; i++ < n && hasMoreSolutions();) {
v.addElement(nextSolution());
}
// turn the vector into an array:
Hashtable solutions[] = new Hashtable[v.size()]; // 0 solutions -> Hashtable[0]
v.copyInto(solutions);
return solutions;
}
}
/**
* This static method creates a Query whose goal is the given Term,
* calls it to exhaustion or until N solutions are found, whichever is sooner,
* and returns an array containing (as possibly empty Hashtables of variablename-to-term bindings) every found solution (in the order in which they were found).
* Throws JPLException if goal is neither a jpl.Atom nor a jpl.Compound.
*
* @param goal the goal of this Query
*/
public static final Hashtable[] nSolutions(Term goal, long n) {
return (new Query(goal)).nSolutions(n);
}
/**
* This static method creates a Query from the given Prolog source text fragment,
* calls it to exhaustion or until N solutions are found, whichever is sooner,
* and returns an array containing (as possibly empty Hashtables of variablename-to-term bindings) every found solution (in the order in which they were found).
* Throws PrologException containing error(syntax_error(_),_) if text is invalid.
*
* @param text a Prolog source text fragment denoting a goal
*/
public static final Hashtable[] nSolutions(String text, long n) {
return (new Query(text)).nSolutions(n);
}
/**
* If text denotes (in traditional Prolog source syntax) a term containing N questionmark (?) symbols and there are N accompanying params,
* this static method replaces each questionmark symbol by its respective param,
* calls the resulting goal to exhaustion or until N solutions are found, whichever is sooner,
* and returns an array containing (as possibly empty Hashtables of variablename-to-term bindings) every found solution (in the order in which they were found).
*
* Otherwise, if text denotes an atom, this static method creates a Query
* where text is the name of the goal and params are the args;
* the resulting goal is then called as above.
* This latter mode is redundant, deprecated (informally), and retained only for backward compatibility.
*
* @param text the Prolog source text of a goal, in which questionmarks are regarded as substitutible parameters
* @param params terms to be substituted for the respective questionmarks in the query text
*/
public static final Hashtable[] nSolutions(String text, Term[] params, long n) {
return (new Query(text, params)).nSolutions(n);
}
/**
* Returns the first solution, if any, as a (possibly empty) Hashtable of variablename-to-term bindings, else null.
*
* This method will throw a JPLException if this Query is already open (and the Query will remain open as before).
* Otherwise, upon return, the Query will be closed.
* @return the first solution, if the query has one, as a (possibly empty) Hashtable.
* If the return value is null, this means that the Query has no solutions.<p>
*/
public synchronized final Hashtable oneSolution() {
if (open) {
throw new JPLException("Query is already open");
} else {
Hashtable solution;
if (hasMoreSolutions()) {
solution = nextSolution();
close(); // safe, whether or not this is the only solution
} else {
solution = null;
}
return solution;
}
}
/**
* This static method creates a Query (whose goal is the specified Term)
* and calls it at most once, returning the first solution, if there is one, as a (possibly empty) Hashtable, else null.
* The goal can be a jpl.Atom or a jpl.Compound, but cannot be an instance
* of jpl.Float, jpl.Integer or jpl.Variable.
*
* @param goal the goal of this Query
*/
public static final Hashtable oneSolution(Term goal) {
return (new Query(goal)).oneSolution();
}
/**
* This static method creates a Query from the given Prolog source text fragment,
* and calls it at most once, returning the first solution, if there is one, as a (possibly empty) Hashtable, else null.
* Throws PrologException containing error(syntax_error(_),_) if text is invalid.
*
* @param text a Prolog source text fragment denoting a goal
*/
public static final Hashtable oneSolution(String text) {
return (new Query(text)).oneSolution();
}
/**
* If text denotes (in traditional Prolog source syntax) a term containing N questionmark (?) symbols
* and there are N params, each questionmark symbol is replaced by its respective param
* to provide the goal of this query:
* the resulting goal is then called (at most once) and the first solution, if there is one, is returned as a (possibly empty) Hashtable, else null.
*
* Otherwise, if text denotes an atom, this static method creates a Query
* where text is the name of the goal and params are the args;
* the resulting goal is then called as above.
* This latter mode is redundant, deprecated (informally), and retained only for backward compatibility.
*
* @param text the Prolog source text of a goal, in which questionmarks are regarded as substitutible parameters
* @param params terms to be substituted for the respective questionmarks in the query text
*/
public static final Hashtable oneSolution(String text, Term[] params) {
return (new Query(text, params)).oneSolution();
}
/**
* This method will attempt to call this Query's goal within an available Prolog engine.
* @return the provability of the Query, i.e. 'true' if it has at least
* one solution, 'false' if the call fails without finding a solution.<p>
*
* Only the first solution (if there is one) will be found;
* any bindings will be discarded, and the Query will be closed.<p>
* This method will throw a JPLException if this Query is already open.
*
* @deprecated Use .hasSolution() instead.
*/
public synchronized final boolean query() {
return oneSolution() != null;
}
/**
* This method will attempt to call this Query's goal within an available Prolog engine.
* @return the provability of the Query, i.e. 'true' if it has at least
* one solution, 'false' if the call fails without finding a solution.<p>
*
* Only the first solution (if there is one) will be found;
* any bindings will be discarded, and the Query will be closed.<p>
* This method will throw a JPLException if this Query is already open.
*/
public synchronized final boolean hasSolution() {
return oneSolution() != null;
}
/**
* This static method creates a Query (whose goal is the specified Term)
* and calls it at most once, returning true if a solution was found, else false.
* The goal can be a jpl.Atom or a jpl.Compound, but cannot be an instance
* of jpl.Float, jpl.Integer or jpl.Variable.
*
* @param goal the goal of this Query
*/
public static final boolean hasSolution(Term goal) {
return (new Query(goal)).hasSolution();
}
/**
* This static method creates a Query from the given Prolog source text
* and calls it at most once, returning true if a solution was found, else false.
* Throws PrologException containing error(syntax_error(_),_) if text is invalid.
*
* @param text the goal of this Query, as Prolog source text
*/
public static final boolean hasSolution(String text) {
return (new Query(text)).hasSolution();
}
/**
* If text denotes (in traditional Prolog source syntax) a term containing N questionmark (?) symbols
* and there are N params, each questionmark symbol is replaced by its corresponding arg
* to provide the new Query's goal: the resulting Query is called as described above.
*
* Otherwise, if text denotes an atom, this static method creates a Query
* where text is the name of its goal and args are its args;
* it then calls this goal (at most once) and returns true if a solution was found, else false.
* This latter mode is redundant, deprecated (informally), and retained only for backward compatibility.
*
* @param text the Prolog source text of a goal, in which questionmarks are regarded as substitutible parameters
* @param params terms to be substituted for the respective questionmarks in the query text
*/
public static final boolean hasSolution(String text, Term[] params) {
return (new Query(text, params)).hasSolution();
}
//
// this method doesn't work, but is intended to be called from another thread,
// to abort a Query which is open and possibly currently executing nextSolution() or similar
public final int abort() {
if (open) {
(new Thread(new Runnable() {
public void run() {
try {
int rc1 = Prolog.attach_engine(engine);
System.out.println("q.abort(): attach_engine() returns " + rc1);
int rc2 = Prolog.action_abort();
System.out.println("q.abort(): action_abort() returns " + rc2);
// int rc3 = Prolog.release_pool_engine();
// System.out.println("q.abort(): release_pool_engine() returns " + rc3);
} catch (Exception e) {
}
}
})).start(); // call the query in a separate thread
/*
int rc0a = Prolog.pool_engine_id(this.engine);
System.out.println("q.abort(): this.engine has id=" + rc0a);
engine_t e = Prolog.current_engine();
System.out.println("q.abort(): " + (e == null ? "no current engine" : "current engine id=" + Prolog.pool_engine_id(e)));
int rc0b = Prolog.release_pool_engine();
System.err.println("q.abort(): release_pool_engine() returns " + rc0b);
engine_t e2 = Prolog.current_engine();
System.out.println("q.abort(): " + (e == null ? "no current engine" : "current engine id=" + Prolog.pool_engine_id(e2)));
int rc1 = Prolog.attach_engine(this.engine);
System.out.println("q.abort(): attach_engine() returns " + rc1);
engine_t e3 = Prolog.current_engine();
System.out.println("q.abort(): " + (e == null ? "no current engine" : "current engine id=" + Prolog.pool_engine_id(e3)));
int rc2 = Prolog.action_abort();
System.out.println("q.abort(): action_abort() returns " + rc2);
int rc3 = Prolog.release_pool_engine();
System.out.println("q.abort(): release_pool_engine() returns " + rc3);
int rc4 = Prolog.attach_engine(e);
System.out.println("q.abort(): attach_engine() returns " + rc4);
*/
return 0;
} else {
System.out.println("q.abort(): query is not open");
return -1;
}
}
//==================================================================/
// misc
//==================================================================/
/**
* Returns a crude String representation of a Query.
*
* @return a crude String representation of a Query
*/
public String toString() {
return goal_.name + "( " + Term.toString(goal_.args) + " )";
}
//==================================================================/
// Methods (deprecated)
//==================================================================/
/**
* Returns a debug-friendly representation of a Query
*
* @return a debug-friendly representation of a Query
* @deprecated
*/
public String debugString() {
return "(Query " + goal_.name + " " + Term.debugString(goal_.args) + ")";
}
}

View File

@ -1,783 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: Term.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 2004 Paul Singleton
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import jpl.fli.DoubleHolder;
import jpl.fli.Int64Holder;
import jpl.fli.IntHolder;
import jpl.fli.Prolog;
import jpl.fli.StringHolder;
import jpl.fli.term_t;
//----------------------------------------------------------------------/
// Term
/**
* Term is the abstract base class for
* Compound, Atom, Variable, Integer and Float, which comprise a Java-oriented concrete syntax for Prolog.
* You cannot create instances of Term directly; rather, you should create
* instances of Term's concrete subclasses.
* Alternatively, use textToTerm() to construct a Term from its conventional
* Prolog source text representation.
*
* <hr><i>
* Copyright (C) 2004 Paul Singleton<p>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
*/
public abstract class Term {
//==================================================================/
// Attributes
//==================================================================/
//==================================================================/
// Constructors
//==================================================================/
/**
* This default constructor is provided in order for subclasses
* to be able to define their own default constructors.
*/
protected Term() {
}
//==================================================================/
// Methods (abstract, common)
//==================================================================/
/**
* returns the ano-th (1+) argument of a (Compound) Term
* throws a JPLException for any other subclass
*
* @return the ano-th argument of a (Compound) Term
*/
public Term arg(int ano) {
throw new JPLException("jpl." + this.typeName() + ".arg() is undefined");
};
/**
* returns, as a Term[], the arguments of a Compound
* returns an empty Term[] from an Atom, Integer or Float
* throws a JPLException from a Variable
*
* @return the arguments of a Compound as a Term[
*/
public abstract Term[] args();
/**
* Tests whether this Term's functor has (String) 'name' and 'arity'
* Returns false if called inappropriately
*
* @return whether this Term's functor has (String) 'name' and 'arity'
*/
public boolean hasFunctor(String name, int arity) {
return false;
}
/**
* Tests whether this Term's functor has (int) 'name' and 'arity'
* Returns false if called inappropriately
*
* @return whether this Term's functor has (int) 'name' and 'arity'
*/
public boolean hasFunctor(int value, int arity) {
return false;
}
/**
* Tests whether this Term's functor has (double) 'name' and 'arity'
* Returns false if called inappropriately
*
* @return whether this Term's functor has (double) 'name' and 'arity'
*/
public boolean hasFunctor(double value, int arity) {
return false;
}
/**
* returns, as a String, the name of a Compound, Atom or Variable
* throws a JPLException from an Integer or Float
*
* @return the name of a Compound, Atom or Variable
*/
public String name() {
throw new JPLException("jpl." + this.typeName() + ".name() is undefined");
};
/**
* returns, as an int, the arity of a Compound, Atom, Integer or Float
* throws a JPLException from a Variable
*
* @return the arity of a Compound, Atom, Integer or Float
*/
public int arity() {
throw new JPLException("jpl." + this.typeName() + ".arity() is undefined");
};
/**
* returns the value (as an int) of an Integer or Float
* throws a JPLException from a Compound, Atom or Variable
*
* @return the value (as an int) of an Integer or Float
*/
public int intValue() {
throw new JPLException("jpl." + this.typeName() + ".intValue() is undefined");
}
/**
* returns the value (as a long) of an Integer or Float
* throws a JPLException from a Compound, Atom or Variable
*
* @return the value (as a long) of an Integer or Float
*/
public long longValue() {
throw new JPLException("jpl." + this.typeName() + ".longValue() is undefined");
}
/**
* returns the value (as a float) of an Integer or Float
* throws a JPLException from a Compound, Atom or Variable
*
* @return the value (as a float) of an Integer or Float
*/
public float floatValue() {
throw new JPLException("jpl." + this.typeName() + ".floatValue() is undefined");
}
/**
* returns the value (as a double) of an Integer or Float
* throws a JPLException from any other subclass
*
* @return the value (as an double) of an Integer or Float
*/
public double doubleValue() {
throw new JPLException("jpl." + this.typeName() + ".doubleValue() is undefined");
}
//==================================================================/
// Methods (common)
//==================================================================/
/**
* returns the type of this term, as one of jpl.fli.Prolog.COMPOUND, .ATOM, .VARIABLE, .INTEGER, .FLOAT etc
*
* @return the type of this term, as one of jpl.fli.Prolog.COMPOUND, .ATOM, .VARIABLE, .INTEGER, .FLOAT etc
*/
public abstract int type();
/**
* returns the name of the type of this term, as one of "Compound", "Atom", "Variable", "Integer", "Float" etc
*
* @return the name of the type of this term, as one of "Compound", "Atom", "Variable", "Integer", "Float" etc
*/
public abstract String typeName();
/**
* whether this Term represents an atom
*
* @return whether this Term represents an atom
*/
public boolean isAtom() {
return this instanceof Atom;
}
/**
* whether this Term represents a compound term
*
* @return whether this Term represents a compound atom
*/
public boolean isCompound() {
return this instanceof Compound;
}
/**
* whether this Term represents an atom
*
* @return whether this Term represents an atom
*/
public boolean isFloat() {
return this instanceof Float;
}
/**
* whether this Term represents an atom
*
* @return whether this Term represents an atom
*/
public boolean isInteger() {
return this instanceof Integer;
}
/**
* whether this Term is a variable
*
* @return whether this Term is a variable
*/
public boolean isVariable() {
return this instanceof Variable;
}
/**
* whether this Term is a 'jfalse' structure, i.e. @(false)
*
* @return whether this Term is a 'jfalse' structure, i.e. @(false)
*/
public boolean isJFalse() {
return false; // overridden in Compound, where it might sometimes be true
}
/**
* whether this Term is a 'jtrue' structure, i.e. @(true)
*
* @return whether this Term is a 'jtrue' structure, i.e. @(true)
*/
public boolean isJTrue() {
return false; // overridden in Compound, where it might sometimes be true
}
/**
* whether this Term is a 'jnull' structure, i.e. @(null)
*
* @return whether this Term is a 'jnull' structure, i.e. @(null)
*/
public boolean isJNull() {
return false; // overridden in Compound, where it might sometimes be true
}
/**
* whether this Term is a 'jvoid' structure, i.e. @(void)
*
* @return whether this Term is a 'jvoid' structure, i.e. @(void)
*/
public boolean isJVoid() {
return false; // overridden in Compound, where it might sometimes be true
}
/**
* whether this Term is a 'jobject' structure, i.e. @(Tag)
*
* @return whether this Term is a 'jobject' structure, i.e. @(Tag)
*/
public boolean isJObject() {
return false; // overridden in Compound, where it might sometimes be true
}
/**
* whether this Term is a 'jref' structure, i.e. @(Tag) or @(null)
*
* @return whether this Term is a 'jref' structure, i.e. @(Tag) or @(null)
*/
public boolean isJRef() {
return false; // overridden in Compound, where it might sometimes be true
}
public Term putParams(Term[] ps) {
IntHolder next = new IntHolder();
next.value = 0;
Term t2 = this.putParams1(next, ps);
if (next.value != ps.length) {
throw new JPLException("Term.putParams: more actual params than formal");
}
return t2;
}
public Term putParams(Term plist) {
Term[] ps = plist.toTermArray();
return putParams(ps);
}
protected Term putParams1(IntHolder next, Term[] ps) {
switch (this.type()) {
case Prolog.COMPOUND :
return new Compound(this.name(), putParams2(this.args(), next, ps));
case Prolog.ATOM :
if (this.name().equals("?")) {
if (next.value >= ps.length) {
throw new JPLException("Term.putParams: fewer actual params than formal params");
}
return ps[next.value++];
} // else drop through to default
default :
return this;
}
}
static protected Term[] putParams2(Term[] ts, IntHolder next, Term[] ps) {
int n = ts.length;
Term[] ts2 = new Term[n];
for (int i = 0; i < n; i++) {
ts2[i] = ts[i].putParams1(next, ps);
}
return ts2;
}
/**
* the length of this list, iff it is one, else an exception is thrown
*
* @throws JPLException
* @return the length (as an int) of this list, iff it is one
*/
public int listLength() {
int len = 0;
if (this.hasFunctor(".", 2)) {
return 1 + this.arg(2).listLength();
} else if (this.hasFunctor("[]", 0)) {
return 0;
} else {
throw new JPLException("Term.listLength: term is not a list");
}
}
/** returns an array of terms which are the successive members of this list, if it is a list, else throws an exception
*
* @throws JPLException
* @return an array of terms which are the successive members of this list, if it is a list
*/
public Term[] toTermArray() {
try {
int len = this.listLength();
Term[] ts = new Term[len];
Term t = this;
for (int i = 0; i < len; i++) {
ts[i] = t.arg(1);
t = t.arg(2);
}
return ts;
} catch (JPLException e) {
throw new JPLException("Term.toTermArray: term is not a proper list");
}
}
//==================================================================/
// Methods (deprecated)
//==================================================================/
/**
* Returns a debug-friendly representation of a Term
*
* @return a debug-friendly representation of a Term
* @deprecated
*/
public abstract String debugString();
/**
* Returns a debug-friendly representation of a list of Terms
*
* @return a debug-friendly representation of a list of Terms
* @deprecated
*/
public static String debugString(Term arg[]) {
String s = "[";
for (int i = 0; i < arg.length; ++i) {
s += arg[i].debugString();
if (i != arg.length - 1) {
s += ", ";
}
}
return s + "]";
}
//==================================================================/
// Converting JPL Terms to Prolog terms
//
// To convert a Term to a term_t, we need to traverse the Term
// structure and build a corresponding Prolog term_t object.
// There are some issues:
//
// - Prolog term_ts rely on the *consecutive* nature of term_t
// references. In particular, to build a compound structure
// in the Prolog FLI, one must *first* determine the arity of the
// compound, create a *sequence* of term_t references, and then
// put atoms, functors, etc. into those term references. We
// do this in these methods by first determining the arity of the
// Compound, and then by "put"-ing a type into a term_t.
// The "put" method is implemented differently in each of Term's
// five subclasses.
//
// - What if we are trying to make a term_t from a Term, but the
// Term has multiple instances of the same Variable? We want
// to ensure that _one_ Prolog variable will be created, or else
// queries will give incorrect answers. We thus pass a Hashtable
// (var_table) through these methods. The table contains term_t
// instances, keyed on Variable instances.
//==================================================================/
public void put( term_t term){
put( new Hashtable(), term);
}
/**
* Cache the reference to the Prolog term_t here.
*
* @param varnames_to_vars A Map from variable names to JPL Variables.
* @param term A (previously created) term_t which is to be
* put with a Prolog term-type appropriate to the Term type
* (e.g., Atom, Variable, Compound, etc.) on which the method is
* invoked.)
*/
protected abstract void put(Map varnames_to_vars, term_t term);
/**
* This static method converts an array of Terms to a *consecutive*
* sequence of term_t objects. Note that the first term_t object
* returned is a term_t class (structure); the succeeding term_t
* objects are consecutive references obtained by incrementing the
* *value* field of the term_t.
*
* @param varnames_to_vars Map from variable names to JPL Variables.
* @param args An array of jpl.Term references.
* @return consecutive term_t references (first of which is
* a structure)
*/
protected static term_t putTerms(Map varnames_to_vars, Term[] args) {
// first create a sequence of term_ts. The 0th term_t
// will be a jpl.fli.term_t. Successive Prolog term_t
// references will reside in the Prolog engine, and
// can be obtained by term0.value+i.
//
term_t term0 = Prolog.new_term_refs(args.length);
// for each new term reference, construct a Prolog term
// by putting an appropriate Prolog type into the reference.
//
long ith_term_t = term0.value;
for (int i = 0; i < args.length; ++i, ++ith_term_t) {
term_t term = new term_t();
term.value = ith_term_t;
args[i].put(varnames_to_vars, term); // each subclass defines its own put()
}
return term0;
}
// experiment: for jni_jobject_to_term_byval/2 in jpl.c
public static void putTerm( Object obj, term_t termref){
if (obj instanceof Term){
((Term)obj).put(termref);
} else {
throw new JPLException("not a Term");
}
}
//==================================================================/
// Converting Prolog terms to JPL Terms
//
// Converting back from term_ts to Terms is simple, since
// the (simplified) Term representation is canonical (there is only one
// correct structure for any given Prolog term).
//
// One problem concerns variable bindings. We illustrate
// with several examples. First, consider the Prolog fact
//
// p( f(X,X)).
//
// And the query
//
// ?- p( Y).
//
// A solution should be
//
// y = f(X,X)
//
// and indeed, if this query is run, the term_t to which Y will
// be unified is a compound, f(X,X). The problem is, how do
// we know, in converting the term_ts to Terms in the compound f/2
// whether we should create one Variable or two? This begs the
// question, how do we _identify_ Variables in JPL? The answer
// to the latter question is, by reference; two Variable (Java)
// references refer to the same variable iff they are, in memory,
// the same Variable object. That is, they satisfy the Java == relation.
// (Note that this condition is _not_ true of the other Term types.)
//
// Given this design decision, therefore, we should create a
// single Variable instance and a Compound instance whose two arg
// values refer to the same Variable object. We therefore need to keep
// track, in converting a term_t to a Term (in particular, in
// converting a term_t whose type is variable to a Variable), of
// which Variables have been created. We do this by using the vars
// Hashtable, which gets passed recursively though the from_term_t
// methods; this table holds the Variable instances that have been
// created, keyed by the unique and internal-to-Prolog string
// representation of the variable (I'm not sure about this...).
//==================================================================/
/**
* This method calls from_term_t on each term in the n consecutive term_ts.
* A temporary jpl.term_t "holder" (byref) structure must be created
* in order to extract type information from the Prolog engine.
*
* @param vars_to_Vars A Map from Prolog variables to jpl.Variable instances
* @param n The number of consecutive term_ts
* @param term0 The 0th term_t (structure); subsequent
* term_ts are not structures.
* @return An array of converted Terms
*/
/*
protected static Term[] from_term_ts(Map vars_to_Vars, int n, term_t term0) {
// create an (uninitialised) array of n Term references
Term[] terms = new Term[n];
// for each term_t (from 0...n-1), create a term_t
// (temporary) structure and dispatch the translation
// to a Term to the static from_term_t method of the Term
// class. This will perform (Prolog) type analysis on the
// term_t and call the appropriate static method to create
// a Term of the right type (e.g., Atom, Variable, List, etc.)
//
long ith_term_t = term0.value;
for (int i = 0; i < n; ++i, ++ith_term_t) {
term_t term = new term_t();
term.value = ith_term_t;
terms[i] = Term.from_term_t(vars_to_Vars, term);
}
return terms;
}
*/
/**
* We discover the Prolog type of the term, then forward the
* call to the appropriate subclass
*
* @param vars A Map from Prolog variables to jpl.Variable instances
* @param term The Prolog term (in a term_t holder) to convert
* @return The converted Term subtype instance.
*/
protected static Term getTerm1(Map vars_to_Vars, term_t term) {
int type = Prolog.term_type(term);
switch (type) {
case Prolog.VARIABLE :
return Variable.getTerm(vars_to_Vars, term);
case Prolog.ATOM :
return Atom.getTerm(vars_to_Vars, term);
case Prolog.STRING :
return Atom.getString(vars_to_Vars, term);
case Prolog.INTEGER :
return Integer.getTerm(vars_to_Vars, term);
case Prolog.FLOAT :
return Float.getTerm(vars_to_Vars, term);
case Prolog.COMPOUND :
return Compound.getTerm(vars_to_Vars, term);
default :
// should never happen...
throw new JPLException("Term.from_term_t: unknown term type=" + type);
}
}
protected static Term getTerm(Map vars_to_Vars, term_t term) {
StringHolder hString;
IntHolder hInt;
Int64Holder hInt64;
// int type = Prolog.term_type(term);
switch (Prolog.term_type(term)) {
case Prolog.VARIABLE:
for (Iterator i = vars_to_Vars.keySet().iterator(); i.hasNext();) {
term_t varX = (term_t) i.next(); // a previously seen Prolog variable
if (Prolog.compare(varX, term) == 0) { // identical Prolog variables?
return (Term) vars_to_Vars.get(varX); // return the associated JPL Variable
}
}
// otherwise, the Prolog variable in term has not been seen before
Variable Var = new Variable(); // allocate a new (sequentially named) Variable to represent it
Var.term_ = term; // this should become redundant...
vars_to_Vars.put(term, Var); // use Hashtable(var,null), but only need set(var)
return Var;
case Prolog.ATOM: // return Atom.getTerm(vars_to_Vars, term);
hString = new StringHolder();
Prolog.get_atom_chars(term, hString); // ignore return val; assume success...
return new Atom(hString.value);
case Prolog.STRING: // return Atom.getString(vars_to_Vars, term);
hString = new StringHolder();
Prolog.get_string_chars(term, hString); // ignore return val; assume success...
return new Atom(hString.value);
case Prolog.INTEGER: // return Integer.getTerm(vars_to_Vars, term);
hInt64 = new Int64Holder();
Prolog.get_integer(term, hInt64); // assume it succeeds...
return new jpl.Integer(hInt64.value);
case Prolog.FLOAT: // return Float.getTerm(vars_to_Vars, term);
DoubleHolder hFloatValue = new DoubleHolder();
Prolog.get_float(term, hFloatValue); // assume it succeeds...
return new jpl.Float(hFloatValue.value);
case Prolog.COMPOUND: // return Compound.getTerm(vars_to_Vars, term);
hString = new StringHolder();
hInt = new IntHolder();
Prolog.get_name_arity(term, hString, hInt); // assume it succeeds
Term args[] = new Term[hInt.value];
// term_t term1 = Prolog.new_term_refs(hArity.value);
for (int i = 1; i <= hInt.value; i++) {
term_t termi = Prolog.new_term_ref();
Prolog.get_arg(i, term, termi);
args[i - 1] = Term.getTerm(vars_to_Vars, termi);
}
return new Compound(hString.value, args);
default:
// should never happen...
throw new JPLException("Term.from_term_t: unknown term type=" + Prolog.term_type(term));
}
}
protected static Term getTerm( term_t term){
return getTerm( new Hashtable(), term);
}
//==================================================================/
// Computing Substitutions
//
// Once a solution has been found, the Prolog term_t references
// will have been instantiated and will refer to new terms. To compute
// a substitution, we traverse the (original) Term structure, looking
// at the term_t reference in the Term. The only case we really care
// about is if the (original) Term is a Variable; if so, the term_t
// back in the Prolog engine may be instantiated (non Variable parts
// of the original Term cannot change or become uninstantiated). In
// this case, we can store this term in a Hashtable, keyed by the
// Variable with which the term was unified.
//==================================================================/
//------------------------------------------------------------------/
// getSubst
/**
* This method computes a substitution from a Term. The bindings
* Hashtable stores Terms, keyed by Variables. Thus, a
* substitution is as it is in mathematical logic, a sequence
* of the form \sigma = {t_0/x_0, ..., t_n/x_n}. Once the
* substitution is computed, the substitution should satisfy
*
* \sigma T = t
*
* where T is the Term from which the substitution is computed,
* and t is the term_t which results from the Prolog query.<p>
*
* A second Hashtable, vars, is required; this table holds
* the Variables that occur (thus far) in the unified term.
* The Variable instances in this table are guaranteed to be
* unique and are keyed on Strings which are Prolog internal
* representations of the variables.
*
* @param bindings table holding Term substitutions, keyed on
* Variables.
* @param vars A Hashtable holding the Variables that occur
* thus far in the term; keyed by internal (Prolog) string rep.
*/
protected abstract void getSubst(Map varnames_to_Terms, Map vars_to_Vars);
//------------------------------------------------------------------/
// getSubsts
/**
* Just calls computeSubstitution for each Term in the array.
*
* @param varnames_to_Terms a Map from variable names to Terms
* @param vars_to_Vars a Map from Prolog variables to JPL Variables
* @param arg a list of Terms
*/
protected static void getSubsts(Map varnames_to_Terms, Map vars_to_Vars, Term[] args) {
for (int i = 0; i < args.length; ++i) {
args[i].getSubst(varnames_to_Terms, vars_to_Vars);
}
}
//------------------------------------------------------------------/
// terms_equals
/**
* This method is used (by Compound.equals) to determine the Terms in two Term arrays
* are pairwise equal, where two Terms are equal if they satisfy
* the equals predicate (defined differently in each Term subclass).
*
* @param t1 an array of Terms
* @param t2 another array of Terms
* @return true if all of the Terms in the (same-length) arrays are pairwise equal
*/
protected static boolean terms_equals(Term[] t1, Term[] t2) {
if (t1.length != t2.length) {
return false;
}
for (int i = 0; i < t1.length; ++i) {
if (!t1[i].equals(t2[i])) {
return false;
}
}
return true;
}
// newJRef
/**
* This method is used (by Compound.equals) to determine the Terms in two Term arrays
* are pairwise equal, where two Terms are equal if they satisfy
* the equals predicate (defined differently in each Term subclass).
*
* @param t1 an array of Terms
* @param t2 another array of Terms
* @return true if all of the Terms in the (same-length) arrays are pairwise equal
*/
protected static Term newJRef(Object obj) {
return JPL.JNULL; // not yet implemented
}
//------------------------------------------------------------------/
// toString
/**
* Converts a list of Terms to a String.
*
* @param args An array of Terms to convert
* @return String representation of a list of Terms
*/
public static String toString(Term[] args) {
String s = "";
for (int i = 0; i < args.length; ++i) {
s += args[i].toString();
if (i != args.length - 1) {
s += ", ";
}
}
return s;
}
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,281 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: Util.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 2004 Paul Singleton
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl;
import java.util.Hashtable;
import java.util.Map;
//----------------------------------------------------------------------/
// Util
/**
* This class provides a bunch of static utility methods for the JPL
* High-Level Interface.
*
* <hr><i>
* Copyright (C) 2004 Paul Singleton<p>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
*/
public final class Util {
//------------------------------------------------------------------/
// termArrayToList
/**
* Converts an array of Terms to a JPL representation of a Prolog list of terms
* whose members correspond to the respective array elements.
*
* @param terms An array of Term
* @return Term a list of the array elements
*/
public static Term termArrayToList(Term[] terms) {
Term list = new Atom("[]");
for (int i = terms.length - 1; i >= 0; --i) {
list = new Compound(".", new Term[] { terms[i], list });
}
return list;
}
/**
* Converts a solution hashtable to an array of Terms.
*
* @param varnames_to_Terms A Map from variable names to Terms
* @return Term[] An array of the Terms to which successive variables are bound
*/
public static Term[] bindingsToTermArray(Map varnames_to_Terms) {
Term[] ts = new Term[varnames_to_Terms.size()];
for (java.util.Iterator i = varnames_to_Terms.keySet().iterator(); i.hasNext();) {
Variable k = (Variable) i.next();
ts[k.index] = (Term) (varnames_to_Terms.get(k));
}
return ts;
}
//------------------------------------------------------------------/
// toString
/**
* Converts a substitution, in the form of a Map from variable names to Terms, to a String.
*
* @param varnames_to_Terms A Map from variable names to Terms.
* @return String A String representation of the variable bindings
*/
public static String toString(Map varnames_to_Terms) {
if (varnames_to_Terms == null) {
return "[no solution]";
}
java.util.Iterator varnames = varnames_to_Terms.keySet().iterator();
String s = "Bindings: ";
while (varnames.hasNext()) {
String varname = (String) varnames.next();
s += varname + "=" + varnames_to_Terms.get(varname).toString() + "; ";
}
return s;
}
//------------------------------------------------------------------/
// namevarsToMap
/**
* Converts a (JPL) list of Name=Var pairs (as yielded by atom_to_term/3)
* to a Map from Prolog variables (necessarily in term_t holders) to named JPL Variables
*
* @param nvs A JPL list of Name=Var pairs (as yielded by atom_to_term/3)
* @return Map A Map from Prolog variables (necessarily in term_t holders) to named JPL Variables
*/
public static Map namevarsToMap(Term nvs) {
try {
Map vars_to_Vars = new Hashtable();
/*
while (nvs.hasFunctor(".", 2) && ((Compound) nvs).arg(1).hasFunctor("=", 2)) {
Atom name = (Atom) ((Compound) ((Compound) nvs).arg(1)).arg(1); // get the Name of the =/2 pair
Variable var = (Variable) ((Compound) ((Compound) nvs).arg(1)).arg(2); // get the Var of the =/2 pair
vars_to_Vars.put(var.term_, new Variable(name.name())); // map the Prolog variable to a new, named Variable
nvs = ((Compound) nvs).arg(2); // advance to next list cell
}
*/
while (nvs.hasFunctor(".", 2) && nvs.arg(1).hasFunctor("=", 2)) {
// the cast to Variable is necessary to access the (protected) .term_ field
vars_to_Vars.put(((Variable)nvs.arg(1).arg(2)).term_, new Variable(nvs.arg(1).arg(1).name())); // map the Prolog variable to a new, named Variable
nvs = nvs.arg(2); // advance to next list cell
}
// maybe oughta check that nvs is [] ?
return vars_to_Vars;
} catch (java.lang.ClassCastException e) { // nvs is not of the expected structure
return null;
}
}
//------------------------------------------------------------------/
// textToTerm
/**
* Converts a Prolog source text to a corresponding JPL Term
* (in which each Variable has the appropriate name from the source text).
* Throws PrologException containing error(syntax_error(_),_) if text is invalid.
*
* @param text A Prolog source text denoting a term
* @return Term a JPL Term equivalent to the given source text
*/
public static Term textToTerm(String text) {
// it might be better to use PL_chars_to_term()
Query q = new Query(new Compound("atom_to_term", new Term[] { new Atom(text), new Variable("Term"), new Variable("NVdict")}));
q.open();
Map s = q.getSubstWithNameVars();
if (s != null) {
q.close();
return (Term) s.get("Term");
} else {
return null;
}
}
//
// textParamsToTerm
/**
* Converts a Prolog source text to a corresponding JPL Term (in which each Variable has the appropriate name from the source text), replacing successive occurrences of ? in the text by the
* corresponding element of Term[] params. (New in JPL 3.0.4)
*
* Throws PrologException containing error(syntax_error(_),_) if text is invalid.
*
* @param text
* A Prolog source text denoting a term
* @return Term a JPL Term equivalent to the given source text
*/
public static Term textParamsToTerm(String text, Term[] params) {
return Util.textToTerm(text).putParams(params);
}
//
/**
* Converts an array of String to a corresponding JPL list
*
* @param a
* An array of String objects
* @return Term a JPL list corresponding to the given String array
*/
public static Term stringArrayToList(String[] a) {
Term list = new Atom("[]");
for (int i = a.length - 1; i >= 0; i--) {
list = new Compound(".", new Term[]{new Atom(a[i]), list});
}
return list;
}
//
/**
* Converts an array of int to a corresponding JPL list
*
* @param a
* An array of int values
* @return Term a JPL list corresponding to the given int array
*/
public static Term intArrayToList(int[] a) {
Term list = new Atom("[]");
for (int i = a.length - 1; i >= 0; i--) {
list = new Compound(".", new Term[]{new jpl.Integer(a[i]), list});
}
return list;
}
//
/**
* Converts an array of arrays of int to a corresponding JPL list of lists
*
* @param a
* An array of arrays of int values
* @return Term a JPL list of lists corresponding to the given int array of arrays
*/
public static Term intArrayArrayToList(int[][] a) {
Term list = new Atom("[]");
for (int i = a.length - 1; i >= 0; i--) {
list = new Compound(".", new Term[]{intArrayToList(a[i]), list});
}
return list;
}
public static int listToLength(Term t) {
int length = 0;
Term head = t;
while (head.hasFunctor(".", 2)) {
length++;
head = head.arg(2);
}
return (head.hasFunctor("[]", 0) ? length : -1);
}
/** converts a proper list to an array of terms, else throws an exception
*
* @throws JPLException
* @return an array of terms whose successive elements are the corresponding members of the list (if it is a list)
*/
public static Term[] listToTermArray(Term t) {
try {
int len = t.listLength();
Term[] ts = new Term[len];
for (int i = 0; i < len; i++) {
ts[i] = t.arg(1);
t = t.arg(2);
}
return ts;
} catch (JPLException e) {
throw new JPLException("Util.listToTermArray: term is not a proper list");
}
}
public static String[] atomListToStringArray( Term t){
int n = listToLength(t);
String[] a;
if ( n<0){
return null;
} else {
a = new String[n];
}
int i = 0;
Term head = t;
while ( head.hasFunctor(".", 2)){
Term x = head.arg(1);
if ( x.isAtom()){
a[i++]=x.name();
} else {
return null;
}
head = head.arg(2);
}
return (head.hasFunctor("[]", 0) ? a : null );
}
}

View File

@ -1,277 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: Variable.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 2004 Paul Singleton
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl;
import java.util.Iterator;
import java.util.Map;
import jpl.fli.Prolog;
import jpl.fli.term_t;
//----------------------------------------------------------------------/
// Variable
/**
* This class supports Java representations of Prolog variables.<p>
*
* A jpl.Variable instance is equivalent to a variable in a fragment of Prolog source text:
* it is *not* a "live" variable within a Prolog stack or heap.
* A corresponding Prolog variable is created only upon opening
* a Query whose goal refers to a Variable (and then only temporarily).
*
* <hr><i>
* Copyright (C) 2004 Paul Singleton<p>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
*/
// Implementation notes:
//
//----------------------------------------------------------------------/
public class Variable extends Term {
//==================================================================/
// Attributes
//==================================================================/
private static long n = 0; // the integral part of the next automatic variable name to be allocated
public final String name; // the name of this Variable
protected transient term_t term_ = null; // defined between Query.open() and Query.get2()
protected transient int index; // only used by (redundant?)
//==================================================================/
// Constructors
//==================================================================/
/**
* Create a new Variable with 'name' (which must not be null or ""),
* and may one day be constrained to comply with traditional Prolog syntax.
*
* @param name the source name of this Variable
*/
public Variable(String name) {
if (name == null) {
throw new JPLException("constructor jpl.Variable(name): name cannot be null");
}
if (!isValidName(name)) {
throw new JPLException("constructor jpl.Variable(name): name cannot be empty String");
}
this.name = name;
}
/**
* Create a new Variable with new sequential name of the form "_261".
*
*/
public Variable() {
this.name = "_" + Long.toString(n++); // e.g. _0, _1 etc.
}
//==================================================================/
// Methods (common)
//==================================================================/
/**
* The (nonexistent) args of this Variable
* @throws JPLException
*
* @return the (nonexistent) args of this Variable (never)
*/
public Term[] args() {
throw new JPLException("jpl.Variable#args(): call is improper");
}
/**
* returns the lexical name of this Variable
*
* @return the lexical name of this Variable
*/
public final String name() {
return this.name;
}
/**
* returns the type of this subclass of Term, i.e. Prolog.VARIABLE
*
* @return the type of this subclass of Term, i.e. Prolog.VARIABLE
*/
public final int type() {
return Prolog.VARIABLE;
}
/**
* returns the typeName of this subclass of Term, i.e. "Variable"
*
* @return the typeName of this subclass of Term, i.e. "Variable"
*/
public String typeName() {
return "Variable";
}
/**
* Returns a Prolog source text representation of this Variable
*
* @return a Prolog source text representation of this Variable
*/
public String toString() {
return this.name;
}
/**
* A Variable is equal to another if their names are the same and they are not anonymous.
*
* @param obj The Object to compare.
* @return true if the Object is a Variable and the above condition apply.
*/
public final boolean equals(Object obj) {
return obj instanceof Variable && !this.name.equals("_") && this.name.equals(((Variable) obj).name);
}
//==================================================================/
// Methods (private)
//==================================================================/
/**
* Tests the lexical validity of s as a variable's name
*
* @return the lexical validity of s as a variable's name
* @deprecated
*/
private boolean isValidName(String s) {
if (s == null) {
throw new java.lang.NullPointerException(); // JPL won't call it this way
}
int len = s.length();
if (len == 0) {
throw new JPLException("invalid variable name");
}
char c = s.charAt(0);
if (!(c == '_' || c >= 'A' && c <= 'Z')) {
return false;
}
for (int i = 1; i < len; i++) {
c = s.charAt(i);
if (!(c == '_' || c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9')) {
return false;
}
}
return true;
}
//==================================================================/
// Methods (deprecated)
//==================================================================/
/**
* Returns a debug-friendly String representation of an Atom.
*
* @return a debug-friendly String representation of an Atom
* @deprecated
*/
public String debugString() {
return "(Variable " + toString() + ")";
}
//==================================================================/
// Converting JPL Terms to Prolog terms
//==================================================================/
/**
* To put a Variable, we must check whether a (non-anonymous) variable with the same name
* has already been put in the Term. If one has, then the corresponding Prolog variable has
* been stashed in the varnames_to_vars Map, keyed by the Variable name, so we can look
* it up and reuse it (this way, the sharing of variables in the Prolog term
* reflects the sharing of Variable names in the Term.
* Otherwise, if this Variable name has not
* already been seen in the Term, then we put a new Prolog variable and add it into the Map
* (keyed by this Variable name).
*
* @param varnames_to_vars A Map from variable names to Prolog variables.
* @param term A (previously created) term_t which is to be
* set to a (new or reused) Prolog variable.
*/
protected final void put(Map varnames_to_vars, term_t term) {
term_t var;
// if this var is anonymous or as yet unseen, put a new Prolog variable
if (this.name.equals("_") || (var = (term_t) varnames_to_vars.get(this.name)) == null) {
this.term_ = term;
this.index = varnames_to_vars.size(); // i.e. first var in is #0 etc.
Prolog.put_variable(term);
if (!this.name.equals("_")) {
varnames_to_vars.put(this.name, term);
}
} else {
this.term_ = var;
Prolog.put_term(term, var);
}
}
//==================================================================/
// Converting Prolog terms to JPL Terms
//==================================================================/
/**
* Converts a term_t (known to refer to a Prolog variable) to a Variable.
* If the variable has already been seen (and hence converted),
* return its corresponding Variable from the map,
* else create a new Variable, stash it in the map (keyed by the Prolog variable),
* and return it.
*
* @param vars_to_Vars a map from Prolog to JPL variables
* @param var The term_t (known to be a variable) to convert
* @return A new or reused Variable
*/
protected static Term getTerm1(Map vars_to_Vars, term_t var) {
for (Iterator i = vars_to_Vars.keySet().iterator(); i.hasNext();) {
term_t varX = (term_t) i.next(); // a previously seen Prolog variable
if (Prolog.compare(varX, var) == 0) { // identical Prolog variables?
return (Term) vars_to_Vars.get(varX); // return the associated JPL Variable
}
}
// otherwise, the Prolog variable in term has not been seen before
Variable Var = new Variable(); // allocate a new (sequentially named) Variable to represent it
Var.term_ = var; // this should become redundant...
vars_to_Vars.put(var, Var); // use Hashtable(var,null), but only need set(var)
return Var;
}
//==================================================================/
// Computing Substitutions
//==================================================================/
/**
* If this Variable instance is not an anonymous or (in dont-tell-me mode) a dont-tell-me variable, and its binding is not already in the varnames_to_Terms Map,
* put the result of converting the term_t to which this variable
* has been unified to a Term in the Map, keyed on this Variable's name.
*
* @param varnames_to_Terms A Map of bindings from variable names to JPL Terms.
* @param vars_to_Vars A Map from Prolog variables to JPL Variables.
*/
protected final void getSubst(Map varnames_to_Terms, Map vars_to_Vars) {
// NB a Variable.name cannot be "" i.e. of 0 length
// if (!(this.name.charAt(0) == '_') && varnames_to_Terms.get(this.name) == null) {
if (tellThem() && varnames_to_Terms.get(this.name) == null) {
varnames_to_Terms.put(this.name, Term.getTerm(vars_to_Vars, this.term_));
}
}
// whether, according to prevailing policy and theis Variable's name,
// any binding should be returned
// (yes, unless it's anonymous or we're in dont-tell-me mode and its a dont-tell-me variable)
private final boolean tellThem() {
return !(this.name.equals("_") || jpl.JPL.modeDontTellMe && this.name.charAt(0) == '_');
// return !this.name.equals("_");
}
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,9 +0,0 @@
// $Id: Version.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
package jpl;
class Version {
public final int major = 3;
public final int minor = 1;
public final int patch = 3;
public final String status = "alpha";
}

View File

@ -1,60 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: BooleanHolder.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl.fli;
//----------------------------------------------------------------------/
// BooleanHolder
/**
* A BooleanHolder is merely a Holder class for a boolean value.
*
* <hr><i>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
*/
// Implementation notes:
//
//----------------------------------------------------------------------/
public class BooleanHolder
{
public boolean value;
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,60 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: DoubleHolder.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl.fli;
//----------------------------------------------------------------------/
// DoubleHolder
/**
* A DoubleHolder is merely a Holder class for a double value.
*
* <hr><i>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
*/
// Implementation notes:
//
//----------------------------------------------------------------------/
public class DoubleHolder
{
public double value;
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,34 +0,0 @@
package jpl.fli;
//----------------------------------------------------------------------/
//Int64Holder
/**
* An Int64Holder is merely a Holder class for an int64 value.
*
* <hr><i>
* Copyright (C) 2005 Paul Singleton<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Paul Singleton <paul@jbgb.com>
* @version $Revision: 1.1 $
*/
//Implementation notes:
//
//----------------------------------------------------------------------/
public class Int64Holder
{
public long value;
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,60 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: IntHolder.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl.fli;
//----------------------------------------------------------------------/
// IntHolder
/**
* An IntHolder is merely a Holder class for an Int value.
*
* <hr><i>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
*/
// Implementation notes:
//
//----------------------------------------------------------------------/
public class IntHolder
{
public int value;
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,61 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: LongHolder.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl.fli;
//----------------------------------------------------------------------/
// LongHolder
/**
* A Long Holder merely holds a long value.
*
* <hr><i>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
*/
// Implementation notes:
//
//----------------------------------------------------------------------/
public class LongHolder {
public long value = 0L;
public boolean equals(LongHolder lh) {
return lh.value == this.value;
}
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,60 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: ObjectHolder.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl.fli;
//----------------------------------------------------------------------/
// ObjectHolder
/**
* A ObjectHolder is merely a Holder class for an Object reference (or null).
*
* <hr><i>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
*/
// Implementation notes:
//
//----------------------------------------------------------------------/
public class ObjectHolder
{
public Object value;
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,63 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: PointerHolder.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl.fli;
//----------------------------------------------------------------------/
// PointerHolder
/**
* A PointerHolder is a trivial extension of a LongHolder. This is sort of
* a no-no in Java, as the long value stored herein is sometimes a
* machine address. (Don't tell Sun.)
*
* <hr><i>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
*/
// Implementation notes:
// There could be issues in the future with signedness, since Java
// does not have an unsigned type; make sure not to do any arithmetic
// with the stored value.
//----------------------------------------------------------------------/
public class PointerHolder extends LongHolder
{
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,237 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: Prolog.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl.fli;
//----------------------------------------------------------------------/
// Prolog
/**
* This class consists only of constants (static finals) and static
* native methods. The constants and methods defined herein are in
* (almost) strict 1-1 correspondence with the functions in the Prolog
* FLI by the same name (except without the PL_, SQ_, etc. prefixes).<p>
*
* See the file jpl.c for the native (ANSI C) implementations of these
* methods. Refer to your local Prolog FLI documentations for the meanings
* of these methods, and observe the following:<p>
*
* <menu>
* <li> The types and signatures of the following methods are almost
* in 1-1 correspondence with the Prolog FLI. The Prolog types
* term_t, atom_t, functor_t, etc. are mirrored in this package with
* classes by the same name, making the C and Java uses of these
* interfaces similar.</li>
* <li> As term_t, functor_t, etc. types are Java classes, they are
* passed to these methods <b>by value</b>; however, calling these
* methods on such class instances does have side effects. In general,
* the value fields of these instances will be modified, in much the
* same way the term_t, functor_t, etc. Prolog instances would be
* modified.</li>
* <li> The exceptions to this rule occur when maintaining the same
* signature would be impossible, e.g., when the Prolog FLI functions
* require <i>pointers</i>; in this case, the signatures have been
* modified to take *Holder classes (Int, Double, String, etc.),
* to indicate a call by reference parameter.
* <li> Functions which take variable-length argument lists in C
* take arrays in Java; from Java 1.1 onwards, anonymous arrays
* can be used e.g. Term[] { new Atom("a"), new Atom ("b") }
* </menu>
*
* <hr><i>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
*/
public final class Prolog {
static {
System.loadLibrary("jpl");
}
/* term types */
public static final int VARIABLE = 1;
public static final int ATOM = 2;
public static final int INTEGER = 3;
public static final int FLOAT = 4;
public static final int STRING = 5;
public static final int COMPOUND = 6;
public static final int JBOOLEAN = 101;
public static final int JREF = 102;
public static final int JVOID = 103;
/**
* @deprecated use Prolog.COMPOUND
*/
public static final int TERM = 6;
public static final int succeed = 1;
public static final int fail = 0;
/* query flags */
public static final int Q_NORMAL = 0x02;
public static final int Q_NODEBUG = 0x04;
public static final int Q_CATCH_EXCEPTION = 0x08;
public static final int Q_PASS_EXCEPTION = 0x10;
/* conversion flags */
public static final int CVT_ATOM = 0x0001;
public static final int CVT_STRING = 0x0002;
public static final int CVT_LIST = 0x0004;
public static final int CVT_INTEGER = 0x0008;
public static final int CVT_FLOAT = 0x0010;
public static final int CVT_VARIABLE = 0x0020;
public static final int CVT_NUMBER = (CVT_INTEGER | CVT_FLOAT);
public static final int CVT_ATOMIC = (CVT_NUMBER | CVT_ATOM | CVT_STRING);
public static final int CVT_ALL = 0x00ff;
public static final int BUF_DISCARDABLE = 0x0000;
public static final int BUF_RING = 0x0100;
public static final int BUF_MALLOC = 0x0200;
/* new, for revised term_t-to-Variable stuff */
public static native int compare(term_t t1, term_t t2); // returns -1, 0 or 1
/* Creating and destroying term-refs */
public static native term_t new_term_ref();
public static native term_t new_term_refs(int n);
public static native term_t copy_term_ref(term_t from); // NOT USED
/* Constants */
public static native atom_t new_atom(String s);
public static native String atom_chars(atom_t a);
public static native functor_t new_functor(atom_t f, int a);
public static native void unregister_atom(atom_t a); // called from atom_t's finalize()
/* Get Java-values from Prolog terms */
public static native boolean get_atom_chars(term_t t, StringHolder a);
public static native boolean get_string_chars(term_t t, StringHolder s);
public static native boolean get_integer(term_t t, Int64Holder i);
public static native boolean get_float(term_t t, DoubleHolder d);
public static native boolean get_name_arity(term_t t, StringHolder name, IntHolder arity);
public static native boolean get_arg(int index, term_t t, term_t a);
public static native String object_to_tag(Object obj);
/* Verify types */
public static native int term_type(term_t t);
/* Assign to term-references */
public static native void put_variable(term_t t);
public static native void put_integer(term_t t, long i);
public static native void put_float(term_t t, double f);
public static native void put_term(term_t t1, term_t t2);
public static native void put_jref(term_t t, Object ref);
/* ... */
public static native void cons_functor_v(term_t h, functor_t fd, term_t a0);
// predicates:
public static native predicate_t predicate(String name, int arity, String module);
// querying (general):
public static native qid_t open_query(module_t m, int flags, predicate_t pred, term_t t0);
public static native boolean next_solution(qid_t qid);
public static native void close_query(qid_t qid);
// modules:
public static native module_t new_module(atom_t name);
// exceptions:
public static native term_t exception(qid_t qid);
// initialisation:
public static native String[] get_default_init_args();
public static native boolean set_default_init_args(String argv[]);
public static native boolean initialise();
public static native String[] get_actual_init_args();
public static native void halt(int status);
// thread & engine management:
public static native int thread_self();
public static native engine_t attach_pool_engine();
public static native int release_pool_engine();
public static native engine_t current_engine();
public static native boolean current_engine_is_pool();
public static native int attach_engine(engine_t e);
// misc.
public static native String get_c_lib_version();
public static native int action_abort();
// not used:
// public static native void reset_term_refs(term_t r);
// public static native atom_t functor_name(functor_t f);
// public static native int functor_arity(functor_t f);
// public static native boolean get_atom(term_t t, atom_t a);
// public static native boolean get_pointer(term_t t, PointerHolder ptr);
// public static native boolean get_functor(term_t t, functor_t f);
// public static native boolean get_module(term_t t, module_t module);
// public static native boolean get_jref(term_t t, ObjectHolder obj);
// public static native boolean get_jboolean(term_t t, BooleanHolder b);
// public static native boolean get_jpl_term(term_t t, ObjectHolder obj); // withdrawn 17/Oct/2004
// public static native boolean is_variable(term_t t);
// public static native boolean is_atom(term_t t);
// public static native boolean is_integer(term_t t);
// public static native boolean is_float(term_t t);
// public static native boolean is_compound(term_t t);
// public static native boolean is_functor(term_t t, functor_t f);
// public static native boolean is_atomic(term_t t);
// public static native boolean is_number(term_t t);
// public static native void put_atom(term_t t, atom_t a);
// public static native void put_pointer(term_t t, PointerHolder ptr);
// public static native void put_functor(term_t t, functor_t functor);
// public static native void put_jboolean(term_t t, boolean b);
// public static native void put_jvoid(term_t t);
// public static native void cons_list(term_t l, term_t h, term_t t);
// public static native int unify(term_t t1, term_t t2);
// public static native predicate_t pred(functor_t f, module_t m);
// public static native int predicate_info(predicate_t pred, atom_t name, IntHolder arity, module_t module);
// public static native void cut_query(qid_t qid);
// public static native boolean call(term_t t, module_t m);
// public static native boolean call_predicate(module_t m, int debug, predicate_t pred, term_t t0);
// public static native fid_t open_foreign_frame(); // NOT USED
// public static native void close_foreign_frame(fid_t cid); // NOT USED
// public static native void discard_foreign_frame(fid_t cid); // NOT USED
// public static native module_t context();
// public static native atom_t module_name(module_t module);
// public static native int strip_module(term_t in, module_t m, term_t out);
// public static native int pool_engine_id(engine_t e);
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,60 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: StringHolder.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl.fli;
//----------------------------------------------------------------------/
// StringHolder
/**
* A StringHolder is merely a Holder class for a String value.
*
* <hr><i>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
*/
// Implementation notes:
//
//----------------------------------------------------------------------/
public class StringHolder
{
public String value;
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,82 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: atom_t.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl.fli;
//----------------------------------------------------------------------/
// atom_t
/**
* An atom_t is a specialised LongHolder which decrements its atom's
* reference count when garbage-collected (finalized).
*
* <hr><i>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
*/
// Implementation notes:
//
//----------------------------------------------------------------------/
public class atom_t
extends LongHolder
{
//------------------------------------------------------------------/
// toString
/**
* The String representation of an atom_t is just the atom's name.
*
* @return atom's name
*/
// Implementation notes:
//
//------------------------------------------------------------------/
public String
toString()
{
return Prolog.atom_chars( this );
}
protected void finalize() throws Throwable {
super.finalize();
Prolog.unregister_atom( this);
}
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,56 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: engine_t.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl.fli;
//----------------------------------------------------------------------/
// engine_t
/**
* A engine_t holds a reference to a Prolog engine.
*
* <hr><i>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
*/
// Implementation notes: Note that a engine_t is not a term,
// consistent with the treatment in the Prolog FLI.
//----------------------------------------------------------------------/
public class engine_t extends LongHolder {
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,60 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: fid_t.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl.fli;
//----------------------------------------------------------------------/
// fid_t
/**
* An fid_t holds the value of a frame id in the Prolog Engine.
*
* <hr><i>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
*/
// Implementation notes:
//
//----------------------------------------------------------------------/
public class fid_t
extends LongHolder
{
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,61 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: functor_t.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl.fli;
//----------------------------------------------------------------------/
// functor_t
/**
* A functor_t holds a reference to a Prolog functor_t in the
* Prolog engine.
*
* <hr><i>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
*/
// Implementation notes: Note that a functor_t is not a term,
// consistent with the treatment in the Prolog FLI.
//----------------------------------------------------------------------/
public class functor_t
extends LongHolder
{
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,61 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: module_t.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl.fli;
//----------------------------------------------------------------------/
// module_t
/**
* A module_t is a PointerHolder type which holds a reference to a Prolog
* module_t reference.
*
* <hr><i>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
*/
// Implementation notes:
//
//----------------------------------------------------------------------/
public class module_t
extends PointerHolder
{
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,61 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: predicate_t.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl.fli;
//----------------------------------------------------------------------/
// predicate_t
/**
* A predicate_t is a PointerHolder class whose value is a reference to a
* Prolog predicate_t.
*
* <hr><i>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
*/
// Implementation notes:
//
//----------------------------------------------------------------------/
public class predicate_t
extends PointerHolder
{
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,60 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: qid_t.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl.fli;
//----------------------------------------------------------------------/
// qid_t
/**
* A qid_t holds a reference to a Prolog qid_t.
*
* <hr><i>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
*/
// Implementation notes:
//
//----------------------------------------------------------------------/
public class qid_t
extends LongHolder
{
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,133 +0,0 @@
//tabstop=4
//*****************************************************************************/
// Project: jpl
//
// File: $Id: term_t.java,v 1.2 2007-09-27 15:25:32 vsc Exp $
// Date: $Date: 2007-09-27 15:25:32 $
// Author: Fred Dushin <fadushin@syr.edu>
//
//
// Description:
//
//
// -------------------------------------------------------------------------
// Copyright (c) 1998 Fred Dushin
// All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library Public License for more details.
//*****************************************************************************/
package jpl.fli;
//----------------------------------------------------------------------/
// term_t
/**
* A term_t is a simple class which mirrors the term_t type in
* the Prolog FLI. All it really does is hold a term reference,
* which is an internal representation of a term in the Prolog
* Engine.
*
* <hr><i>
* Copyright (C) 1998 Fred Dushin<p>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.<p>
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library Public License for more details.<p>
* </i><hr>
* @author Fred Dushin <fadushin@syr.edu>
* @version $Revision: 1.2 $
*/
// Implementation notes:
//
//----------------------------------------------------------------------/
public class term_t
extends LongHolder
{
public static final long UNASSIGNED = -1L;
public
term_t()
{
value = UNASSIGNED;
}
//------------------------------------------------------------------/
// toString
/**
* This static method converts a term_t, which is assumed to contain
* a reference to a *consecutive* list of term_t references to a
* String representation of a list of terms, in this case, a comma
* separated list.
*
* @param n the number of consecutive term_ts
* @param term0 a term_t whose value is the 0th term_t.
*/
// Implementation notes:
//
//------------------------------------------------------------------/
public static String
toString( int n, term_t term0 )
{
String s = "";
int i;
long ith_term_t;
for ( i = 0, ith_term_t = term0.value; i < n; ++i, ++ith_term_t ){
term_t term = new term_t();
term.value = ith_term_t;
s += term.toString();
if ( i != n - 1 ){
s += ", ";
}
}
return s;
}
//------------------------------------------------------------------/
// equals
/**
* Instances of term_ts are stored in Term objects (see jpl.Term),
* and these term_ts are in some cases stored in Hashtables.
* Supplying this predicate provides the right behavior in Hashtable
* lookup (see the rules for Hashtable lookup in java.util).<p>
*
* Note. Two term_ts are *not* equal if their values have not
* been assigned. (Since Prolog FLI term_ts are unsigned values and
* the UNASSIGNED value is -1, this should work).
*
* @param obj the Object to comapre.
* @return true if the supplied object is a term_t instances
* and the long values are the same
*/
// Implementation notes:
//
//------------------------------------------------------------------/
public boolean
equals( Object obj )
{
return
(obj instanceof term_t) &&
this.value == ((term_t)obj).value &&
this.value != UNASSIGNED;
}
}
//345678901234567890123456789012346578901234567890123456789012345678901234567890

View File

@ -1,78 +0,0 @@
package jpl.test;
/**
* CelsiusConverter.java is a 1.4 application that
* demonstrates the use of JButton, JTextField and
* JLabel. It requires no other files.
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CelsiusConverter implements ActionListener {
JFrame converterFrame;
JPanel converterPanel;
JTextField tempCelsius;
JLabel celsiusLabel, fahrenheitLabel;
JButton convertTemp;
public CelsiusConverter() { // initially locate the window at top-left of desktop
this(0, 0);
}
public CelsiusConverter(int left, int top) { // initially locate the window at top-left of desktop
// create and set up the window
converterFrame = new JFrame("Convert Celsius to Fahrenheit");
converterFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
converterFrame.setSize(new Dimension(120, 40));
converterFrame.setLocation(left, top);
// create and set up the panel
converterPanel = new JPanel(new GridLayout(2, 2));
// create widgets
tempCelsius = new JTextField(2);
celsiusLabel = new JLabel("Celsius", SwingConstants.LEFT);
celsiusLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
//
convertTemp = new JButton("Convert");
fahrenheitLabel = new JLabel("Fahrenheit", SwingConstants.LEFT);
// listen to events from the Convert button
convertTemp.addActionListener(this);
// add the widgets to the container
converterPanel.add(tempCelsius);
converterPanel.add(celsiusLabel);
converterPanel.add(convertTemp);
converterPanel.add(fahrenheitLabel);
fahrenheitLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
converterFrame.getRootPane().setDefaultButton(convertTemp); // make "convert" the window's default button
// add the panel to the window
converterFrame.getContentPane().add(converterPanel, BorderLayout.CENTER);
// display the window
converterFrame.pack();
converterFrame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
// parse degrees Celsius as a double
double tC = (Double.parseDouble(tempCelsius.getText()));
//
// convert to Fahrenheit (in Java)
// int tempFahr = (int) (tC * 1.8 + 32);
//
// convert to Fahrenheit (in Prolog, via JPL)
int tempFahr = ((jpl.Float) jpl.Query.oneSolution("TF is ? * 1.8 + 32", new jpl.Term[] {new jpl.Float(tC)}).get("TF")).intValue();
//
// display the result
fahrenheitLabel.setText(tempFahr + " Fahrenheit");
}
public static void spawnGUI(final int left, final int top) {
// schedule a job for the event-dispatching thread: create and show an instance of this application at (left,top)
javax.swing.SwingUtilities.invokeLater(new Runnable() {
int x = left;
int y = top;
public void run() {
new CelsiusConverter(x, y); // can we be sure this won't be garbage collected?
}
});
}
public static void main(String[] args) {
// just for fun, we ask Prolog to start five instances of this class (at stepped offsets from top-left of display)
jpl.Query.allSolutions("between(1, 5, N), X is 10*N, Y is 20*N, jpl_call('jpl.test.CelsiusConverter', spawnGUI, [X,Y], _)");
}
}

View File

@ -1,96 +0,0 @@
package jpl.test;
import jpl.Atom;
import jpl.Query;
import jpl.Term;
import jpl.Variable;
public class Family extends Thread {
int id; // client thread id
private static final int delay = 0;
Family(int i) {
this.id = i;
}
public static void main(String argv[]) {
Query q1 = new Query("consult", new Term[] { new Atom("jpl/test/family.pl")});
System.err.println("consult " + (q1.hasSolution() ? "succeeded" : "failed"));
for (int i = 0; i < 20; i++) {
System.out.println("spawning client[" + i + "]");
new Family(i).start();
}
}
public void run() {
java.util.Hashtable solution;
Variable X = new Variable("X");
//--------------------------------------------------
Query q2 = new Query("child_of", new Term[] { new Atom("joe"), new Atom("ralf")});
System.err.println("child_of(joe,ralf) is " + (q2.hasSolution() ? "provable" : "not provable"));
new Query("sleep", new Term[] { new jpl.Integer(delay)}).hasSolution();
//--------------------------------------------------
Query q3 = new Query("descendent_of", new Term[] { new Atom("steve"), new Atom("ralf")});
System.err.println("descendent_of(steve,ralf) is " + (q3.hasSolution() ? "provable" : "not provable"));
new Query("sleep", new Term[] { new jpl.Integer(delay)}).hasSolution();
//--------------------------------------------------
Query q4 = new Query("descendent_of", new Term[] { X, new Atom("ralf")});
solution = q4.oneSolution();
System.err.println("first solution of descendent_of(X, ralf)");
System.err.println("X = " + solution.get(X.name));
new Query("sleep", new Term[] { new jpl.Integer(delay)}).hasSolution();
//--------------------------------------------------
java.util.Hashtable[] solutions = q4.allSolutions();
System.err.println("all solutions of descendent_of(X, ralf)");
for (int i = 0; i < solutions.length; i++) {
System.err.println("X = " + solutions[i].get(X.name));
}
new Query("sleep", new Term[] { new jpl.Integer(delay)}).hasSolution();
//--------------------------------------------------
System.err.println("each solution of descendent_of(X, ralf)");
while (q4.hasMoreSolutions()) {
solution = q4.nextSolution();
System.err.println("X = " + solution.get(X.name));
}
new Query("sleep", new Term[] { new jpl.Integer(delay)}).hasSolution();
//--------------------------------------------------
Variable Y = new Variable("Y");
Query q5 = new Query("descendent_of", new Term[] { X, Y });
System.err.println(id + ": each solution of descendent_of(X, Y)");
while (q5.hasMoreSolutions()) {
solution = q5.nextSolution();
System.err.println(id + ": X = " + solution.get(X.name) + ", Y = " + solution.get(Y.name));
new Query("sleep", new Term[] { new jpl.Integer(delay)}).hasSolution();
}
}
}

View File

@ -1,18 +0,0 @@
package jpl.test;
import jpl.Query;
import jpl.Term;
public class FetchBigTree {
public static void main(String[] args) {
// Prolog.set_default_init_args(new String[] { "libpl.dll", "-f", "D:/pcm/bin/pcm.ini", "-g", "pcm_2000" });
(new Query("consult('jpl/test/test.pl')")).oneSolution();
Term t = (Term)((new Query("p(18,T)")).oneSolution().get("T"));
int i = 1;
while ( t.hasFunctor("a", 2)){
t = t.arg(2);
i = i+1;
}
System.err.println("got a tree of " + i+" generations");
}
}

View File

@ -1,17 +0,0 @@
package jpl.test;
import jpl.Query;
import jpl.Term;
public class FetchLongList {
public static void main(String[] args) {
// Prolog.set_default_init_args(new String[] { "libpl.dll", "-f", "D:/pcm/bin/pcm.ini", "-g", "pcm_2000" });
Term t = (Term)((new Query("findall(foo(N,bar),between(1,2308,N),L)")).oneSolution().get("L"));
int i = 0;
while ( t.hasFunctor(".", 2)){
t = t.arg(2);
i = i+1;
}
System.err.println("got a list of " + i+" members");
}
}

View File

@ -1,23 +0,0 @@
package jpl.test;
import jpl.Query;
public class Ga {
public static void main(String argv[]) {
// Prolog.set_default_init_args(new String[] { "libpl.dll", "-f", "D:/pcm/bin/pcm.ini", "-g", "pcm_2000" });
// (new Query("loadall(jpl_test:jr)")).hasSolution();
// System.err.println("jr " + ((new Query("jr")).hasSolution() ? "succeeded" : "failed"));
// System.err.println( "something " + (new Query("statistics(atoms,X)")).oneSolution().get("X"));
// Query.hasSolution("statistics");
// (new Query("x")).hasSolution();
// (new Query("statistics,x")).hasSolution();
// (new Query(new Atom("statistics"))).hasSolution();
// Query.hasSolution("write(hello),nl");
// Query.hasSolution("write(hello),nl");
// (new Query("nl")).hasSolution();
(new Query("nl,nl")).hasSolution();
// (new Query("user:nl")).hasSolution();
}
}

View File

@ -1,10 +0,0 @@
package jpl.test;
import jpl.Query;
public class Ga2 {
public static void main(String argv[]) {
// Prolog.set_default_init_args(new String[] { "libpl.dll", "-f", "D:/pcm/bin/pcm.ini", "-g", "pcm_2000" });
(new Query("current_prolog_flag(K,V),write(K-V),nl,fail")).oneSolution();
}
}

View File

@ -1,19 +0,0 @@
package jpl.test;
public class Garbo {
public static int created = 0;
public static int destroyed = 0;
//
public final int i;
public Garbo( ) {
this.i = created++;
}
protected void finalize() throws Throwable {
try {
destroyed++;
// System.out.println("gced["+i+"]");
} finally {
super.finalize();
}
}
}

View File

@ -1,93 +0,0 @@
/*
* JPLTest.java
* JUnit based test
*
* Created on 13 February 2006, 11:31
*/
package jpl.test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import junit.framework.*;
import jpl.*;
/**
*
* @author rick
*/
public class JPLTest extends TestCase {
// private static final Logger logger = Logger.getLogger(JPLTest.class.getName());
private CountDownLatch latch;
public JPLTest(String testName) {
super(testName);
}
protected void setUp() throws Exception {
/*
* Prolog file can be an empty file. The JVM seems to crash with a
* SIGSEGV if you don't consult a file prior to interacting with JPL.
final String prologFile = "jpl/test/test.pl"; // was "/home/rick/temp/test.pl";
System.out.println("prolog file is: " + prologFile);
String qString = "consult('" + prologFile + "')";
System.out.println("about to: " + qString);
Query query = new Query(qString);
System.out.println("Generated Query: " + query);
if (!query.hasSolution()) {
System.out.println(qString + " failed");
fail("Failed to consult prolog file.");
}
(new Query("true")).hasSolution();
*/
}
public void testThreadedAdds() {
latch = new CountDownLatch(4);
final AddWithThreads[] addTasks = { new AddWithThreads("a", latch), new AddWithThreads("b", latch), new AddWithThreads("c", latch), new AddWithThreads("d", latch) };
// System.out.println("Starting threads...");
for (int i = 0; i < addTasks.length; i++) {
addTasks[i].start();
}
try {
// System.out.println("Latch is waiting");
assertTrue("Timed out waiting for action to execute", latch.await(20, TimeUnit.SECONDS));
// System.out.println("Latch has been flipped");
} catch (final InterruptedException e) {
fail("Waiting thread was interrupted: " + e);
}
for (int i = 0; i < AddWithThreads.REPS; i++) {
for (int j = 0; j < addTasks.length; j++) {
Query query = new Query(addTasks[j].getNamespace() + "(test('" + i + "'))");
// System.out.println("query: " + query);
boolean ret = query.hasMoreElements();
query.close();
}
}
}
}
class AddWithThreads extends Thread {
private final CountDownLatch latch;
private final String namespace;
private static final Logger logger = Logger.getLogger(JPLTest.class.getName());
public static final int REPS = 2000; // was 200
public AddWithThreads(final String namespace, final CountDownLatch latch) {
this.latch = latch;
this.namespace = namespace;
setName("namespace" + namespace); //set thread name for debugging
}
public String getNamespace() {
return namespace;
}
public void run() {
for (int i = 0; i < REPS; i++) {
// System.out.println("Asserting test('" + i + "')");
Query queryA = new Query("assert(" + namespace + "(test('" + i + "')))");
Thread.yield();
// System.out.println("adding query: " + queryA);
boolean retA = queryA.hasMoreElements();
queryA.close();
}
latch.countDown();
}
}

View File

@ -1,42 +0,0 @@
package jpl.test;
import jpl.Query;
import jpl.fli.Prolog;
public class Masstest extends Thread {
public static void main(String[] args) {
// String[] dia = Prolog.get_default_init_args();
// String s = "default init args: ";
// for (int i = 0; i < dia.length; i++) {
// s += " " + dia[i];
// }
// System.out.println(s);
//
// Prolog.set_default_init_args(new String[] { "libpl.dll", "-f", "none", "-g", "true", "-q" });
// empirically, needs this at least:
// Prolog.set_default_init_args(new String[] { "libpl.dll" });
// Prolog.set_default_init_args(new String[] { "pl" });
//
// (new Query("assert(diagnose_declaration(_,_,_,[not,a,real,error]))")).hasSolution();
//
int STUDENTSNUMBER = 5;
Masstest[] threads = new Masstest[STUDENTSNUMBER];
for (int i = 0; i < STUDENTSNUMBER; i++) {
threads[i] = new Masstest();
threads[i].start();
}
}
public void predQuery() {
String st = "diagnose_declaration(1,[(sp, 'prefix', [('arg1', '+', 'list', 'Liste1'), ('arg2', '+', 'list', 'Liste2')])], DecMap, ErrorList)";
Query stQuery = new Query(st);
String errString = stQuery.oneSolution().get("ErrorList").toString();
System.out.println("errString=" + errString);
}
public void run() {
try {
predQuery();
} catch (Exception e) {
System.err.println("ERROR: " + e);
}
}
}

View File

@ -1,4 +0,0 @@
package jpl.test;
public class MaxObjects {
}

View File

@ -1,13 +0,0 @@
/*
* Created on 22-Nov-2004
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package jpl.test;
public class ShadowA {
public int shadow = -1;
public static int fieldStaticInt;
}

View File

@ -1,16 +0,0 @@
/*
* Created on 22-Nov-2004
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package jpl.test;
public class ShadowB extends ShadowA {
public String shadow;
public ShadowB(String s) {
shadow = s;
}
public static int fieldStaticInt;
}

View File

@ -1,10 +0,0 @@
package jpl.test;
import jpl.Query;
public class SyntaxError {
public static void main(String argv[]) {
Query q = new Query("syntax)error");
System.err.println(q.hasSolution() ? "yes" : "no");
}
}

View File

@ -1,283 +0,0 @@
package jpl.test;
import jpl.Query;
import jpl.Term;
// This class contains members which support those tests which are performed from Prolog.
// See also TestJUnit
public class Test {
public Test() {
}
public Test(Term t) {
this.termFromConstructor = t;
}
public Term termFromConstructor;
//
public static boolean fieldStaticBoolean;
public static final boolean fieldStaticBoolean1 = false;
public static final boolean fieldStaticBoolean2 = true;
//
public static char fieldStaticChar;
public static final char fieldStaticChar1 = '\u0000';
public static final char fieldStaticChar2 = '\uFFFF';
//
public static byte fieldStaticByte;
public static final byte fieldStaticByte1 = -(1 << 7);
public static final byte fieldStaticByte2 = -1;
public static final byte fieldStaticByte3 = 0;
public static final byte fieldStaticByte4 = 1;
public static final byte fieldStaticByte5 = (1 << 7) - 1;
//
public static short fieldStaticShort;
public static final short fieldStaticShort1 = -(1 << 15);
public static final short fieldStaticShort2 = -(1 << 7);
public static final short fieldStaticShort3 = -1;
public static final short fieldStaticShort4 = 0;
public static final short fieldStaticShort5 = 1;
public static final short fieldStaticShort6 = (1 << 7) - 1;
public static final short fieldStaticShort7 = (1 << 15) - 1;
//
public static int fieldStaticInt;
public static final int fieldStaticInt1 = -(1 << 31);
public static final int fieldStaticInt2 = -(1 << 15);
public static final int fieldStaticInt3 = -(1 << 7);
public static final int fieldStaticInt4 = -1;
public static final int fieldStaticInt5 = 0;
public static final int fieldStaticInt6 = 1;
public static final int fieldStaticInt7 = (1 << 7) - 1;
public static final int fieldStaticInt8 = (1 << 15) - 1;
public static final int fieldStaticInt9 = (1 << 31) - 1;
//
public static long fieldStaticLong;
public static final long fieldStaticLong1 = -(1 << 63);
public static final long fieldStaticLong2 = -(1 << 31);
public static final long fieldStaticLong3 = -(1 << 15);
public static final long fieldStaticLong4 = -(1 << 7);
public static final long fieldStaticLong5 = -1;
public static final long fieldStaticLong6 = 0;
public static final long fieldStaticLong7 = 1;
public static final long fieldStaticLong8 = (1 << 7) - 1;
public static final long fieldStaticLong9 = (1 << 15) - 1;
public static final long fieldStaticLong10 = (1 << 31) - 1;
public static final long fieldStaticLong11 = (1 << 63) - 1;
//
public static float fieldStaticFloat;
public static final float fieldStaticFloat1 = 12345.6789F;
public static final float fieldStaticFloat2 = 3.4e+38F; // nearly MAX_VALUE
public static final float fieldStaticFloat3 = 1.4e-45F; // nearly MIN_VALUE
public static final float fieldStaticFloat4 = 0.0F;
public static final float fieldStaticFloat5 = java.lang.Float.MIN_VALUE;
public static final float fieldStaticFloat6 = java.lang.Float.MAX_VALUE;
public static final float fieldStaticFloat7 = java.lang.Float.NEGATIVE_INFINITY;
public static final float fieldStaticFloat8 = java.lang.Float.POSITIVE_INFINITY;
public static final float fieldStaticFloat9 = java.lang.Float.NaN;
//
public static double fieldStaticDouble;
public static final double fieldStaticDouble1 = 12345.6789D;
public static final double fieldStaticDouble2 = 2.3456789e+100D;
public static final double fieldStaticDouble3 = 3.456789e-100D;
public static final double fieldStaticDouble4 = 0.0D;
public static final double fieldStaticDouble5 = Double.MIN_VALUE;
public static final double fieldStaticDouble6 = Double.MAX_VALUE;
public static final double fieldStaticDouble7 = Double.NEGATIVE_INFINITY;
public static final double fieldStaticDouble8 = Double.POSITIVE_INFINITY;
public static final double fieldStaticDouble9 = Double.NaN;
//
public static Object[] fieldStaticObjectArray; // can assign e.g. String[]
public static long[] fieldStaticLongArray; // cannot assign e.g. int[]
//
public static long fac(long n) { // complements jpl:jpl_test_fac(+integer,-integer)
if (n == 1) {
return 1;
} else if (n > 1) {
// return n * ((Integer) new Query(new Compound("jpl_test_fac", new Term[] { new Integer(n - 1), new Variable("F") })).oneSolution().get("F")).intValue();
return n * ((jpl.Integer) Query.oneSolution("jpl_test_fac(?,F)", new Term[] {new jpl.Integer(n-1)}).get("F")).longValue();
} else {
return 0;
}
}
static void packageMethod() { // not callable via JPL
return;
}
public static void publicMethod() {
return;
}
protected static void protectedMethod() { // not callable via JPL
return;
}
private static void privateMethod() { // not callable via JPL
return;
}
public boolean fieldInstanceBoolean;
public final boolean fieldInstanceBoolean1 = false;
public final boolean fieldInstanceBoolean2 = true;
public byte fieldInstanceByte;
public final byte fieldInstanceByte1 = -(1 << 7);
public final byte fieldInstanceByte2 = -1;
public final byte fieldInstanceByte3 = 0;
public final byte fieldInstanceByte4 = 1;
public final byte fieldInstanceByte5 = (1 << 7) - 1;
public char fieldInstanceChar;
public final char fieldInstanceChar1 = '\u0000';
public final char fieldInstanceChar2 = '\uFFFF';
public double fieldInstanceDouble;
public final double fieldInstanceDouble1 = 12345.6789D;
public final double fieldInstanceDouble2 = 2.3456789e+100D;
public final double fieldInstanceDouble3 = 3.456789e-100D;
public final double fieldInstanceDouble4 = 0.0D;
public final double fieldInstanceDouble5 = Double.MIN_VALUE;
public final double fieldInstanceDouble6 = Double.MAX_VALUE;
public final double fieldInstanceDouble7 = Double.NEGATIVE_INFINITY;
public final double fieldInstanceDouble8 = Double.POSITIVE_INFINITY;
public final double fieldInstanceDouble9 = Double.NaN;
public float fieldInstanceFloat;
public final float fieldInstanceFloat1 = 12345.6789F;
public final float fieldInstanceFloat2 = 3.4e+38F;
public final float fieldInstanceFloat3 = 1.4e-45F;
public final float fieldInstanceFloat4 = 0.0F;
public final float fieldInstanceFloat5 = java.lang.Float.MIN_VALUE;
public final float fieldInstanceFloat6 = java.lang.Float.MAX_VALUE;
public final float fieldInstanceFloat7 = java.lang.Float.NEGATIVE_INFINITY;
public final float fieldInstanceFloat8 = java.lang.Float.POSITIVE_INFINITY;
public final float fieldInstanceFloat9 = java.lang.Float.NaN;
public int fieldInstanceInt;
public final int fieldInstanceInt1 = -(1 << 31);
public final int fieldInstanceInt2 = -(1 << 15);
public final int fieldInstanceInt3 = -(1 << 7);
public final int fieldInstanceInt4 = -1;
public final int fieldInstanceInt5 = 0;
public final int fieldInstanceInt6 = 1;
public final int fieldInstanceInt7 = (1 << 7) - 1;
public final int fieldInstanceInt8 = (1 << 15) - 1;
public final int fieldInstanceInt9 = (1 << 31) - 1;
public long fieldInstanceLong;
public final long fieldInstanceLong1 = -(1 << 63);
public final long fieldInstanceLong10 = (1 << 31) - 1;
public final long fieldInstanceLong11 = (1 << 63) - 1;
public final long fieldInstanceLong2 = -(1 << 31);
public final long fieldInstanceLong3 = -(1 << 15);
public final long fieldInstanceLong4 = -(1 << 7);
public final long fieldInstanceLong5 = -1;
public final long fieldInstanceLong6 = 0;
public final long fieldInstanceLong7 = 1;
public final long fieldInstanceLong8 = (1 << 7) - 1;
public final long fieldInstanceLong9 = (1 << 15) - 1;
public short fieldInstanceShort;
public final short fieldInstanceShort1 = -(1 << 15);
public final short fieldInstanceShort2 = -(1 << 7);
public final short fieldInstanceShort3 = -1;
public final short fieldInstanceShort4 = 0;
public final short fieldInstanceShort5 = 1;
public final short fieldInstanceShort6 = (1 << 7) - 1;
public final short fieldInstanceShort7 = (1 << 15) - 1;
//
public Term term; // obsolete
public static Term staticTerm;
public Term instanceTerm;
//
// for testing accessibility of non-public fields:
static boolean fieldPackageStaticBoolean;
protected static boolean fieldProtectedStaticBoolean;
private static boolean fieldPrivateStaticBoolean;
//
// for testing update of final field:
public static final int fieldStaticFinalInt = 7;
//
// for testing passing general terms in from Prolog:
public static Term fieldStaticTerm;
public Term fieldInstanceTerm;
public static boolean methodStaticTerm(Term t) {
return t != null;
}
public boolean methodInstanceTerm(Term t) {
return t != null;
}
public static Term methodStaticEchoTerm(Term t) {
return t;
}
public static boolean methodStaticEchoBoolean(boolean v) {
return v;
}
public static char methodStaticEchoChar(char v) {
return v;
}
public static byte methodStaticEchoByte(byte v) {
return v;
}
public static short methodStaticEchoShort(short v) {
return v;
}
public static int methodStaticEchoInt(int v) {
return v;
}
public static long methodStaticEchoLong(long v) {
return v;
}
public static float methodStaticEchoFloat(float v) {
return v;
}
public static double methodStaticEchoDouble(double v) {
return v;
}
public Term methodInstanceTermEcho(Term t) {
return t;
}
public static boolean methodStaticTermIsJNull(Term t) {
return t.hasFunctor("@", 1) && t.arg(1).hasFunctor("null", 0);
}
public boolean methodInstanceTermIsJNull(Term t) {
return t.hasFunctor("@", 1) && t.arg(1).hasFunctor("null", 0);
}
public static void hello() {
System.out.println("hello");
}
public static boolean[] newArrayBooleanFromValue(boolean v) {
boolean[] a = new boolean[1];
a[0] = v;
return a;
}
public static byte[] newArrayByteFromValue(byte v) {
byte[] a = new byte[1];
a[0] = v;
return a;
}
public static char[] newArrayCharFromValue(char v) {
char[] a = new char[1];
a[0] = v;
return a;
}
public static short[] newArrayShortFromValue(short v) {
short[] a = new short[1];
a[0] = v;
return a;
}
public static int[] newArrayIntFromValue(int v) {
int[] a = new int[1];
a[0] = v;
return a;
}
public static long[] newArrayLongFromValue(long v) {
long[] a = new long[1];
a[0] = v;
return a;
}
public static float[] newArrayFloatFromValue(float v) {
float[] a = new float[1];
a[0] = v;
return a;
}
public static double[] newArrayDoubleFromValue(double v) {
double[] a = new double[1];
a[0] = v;
return a;
}
public static String methodStaticArray(long[] a) {
return "long[]";
}
public static String methodStaticArray(int[] a) {
return "int[]";
}
public static String methodStaticArray(short[] a) {
return "short[]";
}
}

View File

@ -1,532 +0,0 @@
// Created on 25-Jul-2004
package jpl.test;
import java.util.Map;
import jpl.Atom;
import jpl.Compound;
import jpl.Integer;
import jpl.JPL;
import jpl.JRef;
import jpl.PrologException;
import jpl.Query;
import jpl.Term;
import jpl.Util;
import jpl.Variable;
import jpl.fli.Prolog;
import junit.framework.TestCase;
import junit.framework.TestSuite;
// This class defines all the tests which are run from Java.
// It needs junit.framework.TestCase and junit.framework.TestSuite, which are not supplied with JPL.
public class TestJUnit extends TestCase {
//
public static long fac(long n) { // complements jpl:jpl_test_fac(+integer,-integer)
if (n == 1) {
return 1;
} else if (n > 1) {
return n * ((jpl.Integer) Query.oneSolution("jpl_test_fac(?,F)", new Term[] { new jpl.Integer(n - 1) }).get("F")).longValue();
} else {
return 0;
}
}
public TestJUnit(String name) {
super(name);
}
public static junit.framework.Test suite() {
return new TestSuite(TestJUnit.class);
}
public static void main(String args[]) {
junit.textui.TestRunner.run(suite());
}
protected void setUp() {
// initialization code
// Prolog.set_default_init_args(new String[] { "libpl.dll", "-f", "none", "-g", "set_prolog_flag(debug_on_error,false)", "-q" });
Prolog.set_default_init_args(new String[] { "libpl.dll", "-f", "none", "-g", "true", "-q" });
assertTrue((new Query("consult(test_jpl)")).hasSolution());
}
protected void tearDown() {
// cleanup code
}
//
public void testMasstest() {
assertTrue((new Query("assert(diagnose_declaration(_,_,_,[not,a,real,error]))")).hasSolution());
}
public void testSameLibVersions1() {
String java_lib_version = JPL.version_string();
String c_lib_version = jpl.fli.Prolog.get_c_lib_version();
assertTrue("java_lib_version(" + java_lib_version + ") is same as c_lib_version(" + c_lib_version + ")", java_lib_version.equals(c_lib_version));
}
public void testSameLibVersions2() {
String java_lib_version = JPL.version_string();
String pl_lib_version = ((Term) (new Query(new Compound("jpl_pl_lib_version", new Term[] { new Variable("V") })).oneSolution().get("V"))).name();
assertTrue("java_lib_version(" + java_lib_version + ") is same as pl_lib_version(" + pl_lib_version + ")", java_lib_version.equals(pl_lib_version));
}
public void testAtomName1() {
String name = "fred";
Atom a = new Atom(name);
assertEquals("an Atom's name is that with which it was created", a.name(), name);
}
public void testAtomName2() {
String name = "ha ha";
Atom a = new Atom(name);
assertEquals("an Atom's name is that with which it was created", a.name(), name);
}
public void testAtomName3() {
String name = "3";
Atom a = new Atom(name);
assertEquals("an Atom's name is that with which it was created", a.name(), name);
}
public void testAtomToString1() {
String name = "fred";
String toString = "fred";
Atom a = new Atom(name);
assertEquals("an Atom's .toString() value is quoted iff appropriate", a.toString(), toString);
}
public void testAtomToString2() {
String name = "ha ha";
String toString = "'ha ha'";
Atom a = new Atom(name);
assertEquals("an Atom's .toString() value is quoted iff appropriate", a.toString(), toString);
}
public void testAtomToString3() {
String name = "3";
String toString = "'3'";
Atom a = new Atom(name);
assertEquals("an Atom's .toString() value is quoted iff appropriate", a.toString(), toString);
}
public void testAtomArity() {
Atom a = new Atom("willy");
assertEquals("an Atom has arity zero", a.arity(), 0);
}
public void testAtomEquality1() {
String name = "fred";
Atom a1 = new Atom(name);
Atom a2 = new Atom(name);
assertEquals("two Atoms created with the same name are equal", a1, a2);
}
public void testAtomIdentity() { // how could this fail?!
String name = "fred";
Atom a1 = new Atom(name);
Atom a2 = new Atom(name);
assertNotSame("two Atoms created with the same name are not identical", a1, a2);
}
public void testAtomHasFunctorNameZero() {
String name = "sam";
Atom a = new Atom(name);
assertTrue(a.hasFunctor(name, 0));
}
public void testAtomHasFunctorWrongName() {
assertFalse("an Atom does not have a functor whose name is other than that with which the Atom was created", new Atom("wally").hasFunctor("poo", 0));
}
public void testAtomHasFunctorWrongArity() {
String name = "ted";
assertFalse("an Atom does not have a functor whose arity is other than zero", new Atom(name).hasFunctor(name, 1));
}
public void testVariableBinding1() {
Term lhs = new Compound("p", new Term[] { new Variable("X"), new Variable("Y") });
Term rhs = new Compound("p", new Term[] { new Atom("a"), new Atom("b") });
Term goal = new Compound("=", new Term[] { lhs, rhs });
Map soln = new Query(goal).oneSolution();
assertTrue("two variables with different names can bind to distinct atoms", soln != null && ((Term) soln.get("X")).name().equals("a") && ((Term) soln.get("Y")).name().equals("b"));
}
public void testVariableBinding2() {
Term lhs = new Compound("p", new Term[] { new Variable("X"), new Variable("X") });
Term rhs = new Compound("p", new Term[] { new Atom("a"), new Atom("b") });
Term goal = new Compound("=", new Term[] { lhs, rhs });
assertFalse("two distinct Variables with same name cannot unify with distinct atoms", new Query(goal).hasSolution());
}
public void testVariableBinding3() {
Variable X = new Variable("X");
Term lhs = new Compound("p", new Term[] { X, X });
Term rhs = new Compound("p", new Term[] { new Atom("a"), new Atom("b") });
Term goal = new Compound("=", new Term[] { lhs, rhs });
assertFalse("two occurrences of same named Variable cannot unify with distinct atoms", new Query(goal).hasSolution());
}
public void testVariableBinding4() {
Term lhs = new Compound("p", new Term[] { new Variable("_"), new Variable("_") });
Term rhs = new Compound("p", new Term[] { new Atom("a"), new Atom("b") });
Term goal = new Compound("=", new Term[] { lhs, rhs });
assertTrue("two distinct anonymous Variables can unify with distinct atoms", new Query(goal).hasSolution());
}
public void testVariableBinding5() {
Variable Anon = new Variable("_");
Term lhs = new Compound("p", new Term[] { Anon, Anon });
Term rhs = new Compound("p", new Term[] { new Atom("a"), new Atom("b") });
Term goal = new Compound("=", new Term[] { lhs, rhs });
assertTrue("two occurrences of same anonymous Variable can unify with distinct atoms", new Query(goal).hasSolution());
}
public void testAtomEquality2() {
Atom a = new Atom("a");
assertTrue("two occurrences of same Atom are equal by .equals()", a.equals(a));
}
public void testAtomEquality3() {
assertTrue("two distinct Atoms with same names are equal by .equals()", (new Atom("a")).equals(new Atom("a")));
}
public void testTextToTerm1() {
String text = "fred(B,p(A),[A,B,C])";
Term t = Util.textToTerm(text);
assertTrue("Util.textToTerm() converts \"fred(B,p(A),[A,B,C])\" to a corresponding Term", t.hasFunctor("fred", 3) && t.arg(1).isVariable() && t.arg(1).name().equals("B")
&& t.arg(2).hasFunctor("p", 1) && t.arg(2).arg(1).isVariable() && t.arg(2).arg(1).name().equals("A"));
}
public void testArrayToList1() {
Term l2 = Util.termArrayToList(new Term[] { new Atom("a"), new Atom("b"), new Atom("c"), new Atom("d"), new Atom("e") });
Query q9 = new Query(new Compound("append", new Term[] { new Variable("Xs"), new Variable("Ys"), l2 }));
assertTrue("append(Xs,Ys,[a,b,c,d,e]) has 6 solutions", q9.allSolutions().length == 6);
}
public void testArrayToList2() {
String goal = "append(Xs,Ys,[a,b,c,d,e])";
assertTrue(goal + " has 6 solutions", Query.allSolutions(goal).length == 6);
}
public void testLength1() {
Query q5 = new Query(new Compound("length", new Term[] { new Variable("Zs"), new jpl.Integer(2) }));
Term zs = (Term) (q5.oneSolution().get("Zs"));
assertTrue("length(Zs,2) binds Zs to a list of two distinct variables " + zs.toString(), zs.hasFunctor(".", 2) && zs.arg(1).isVariable() && zs.arg(2).hasFunctor(".", 2)
&& zs.arg(2).arg(1).isVariable() && zs.arg(2).arg(2).hasFunctor("[]", 0) && !zs.arg(1).name().equals(zs.arg(2).arg(1).name()));
}
public void testGenerate1() { // we chickened out of verifying each solution :-)
String goal = "append(Xs,Ys,[_,_,_,_,_])";
assertTrue(goal + " has 6 solutions", Query.allSolutions(goal).length == 6);
}
public void testPrologException1() {
try {
new Query("p(]"); // writes junk to stderr and enters debugger unless flag debug_on_error = false
} catch (PrologException e) {
assertTrue("new Query(\"p(]\") throws a PrologException " + e.toString(), true);
return;
}
fail("new Query(\"p(]\") oughta throw a PrologException");
}
public void testAtom1() {
assertTrue("new Atom(\"3 3\")" + (new Atom("3 3")).toString(), true);
}
public void testTextToTerm2() {
String text1 = "fred(?,2,?)";
String text2 = "[first(x,y),A]";
Term plist = Util.textToTerm(text2);
Term[] ps = plist.toTermArray();
Term t = Util.textToTerm(text1).putParams(ps);
assertTrue("fred(?,2,?) .putParams( [first(x,y),A] )", t.hasFunctor("fred", 3) && t.arg(1).hasFunctor("first", 2) && t.arg(1).arg(1).hasFunctor("x", 0) && t.arg(1).arg(2).hasFunctor("y", 0)
&& t.arg(2).hasFunctor(2, 0) && t.arg(3).isVariable() && t.arg(3).name().equals("A"));
}
public void testDontTellMeMode1() {
final Query q = new Query("setof(_M,current_module(_M),_Ms),length(_Ms,N)");
JPL.setDTMMode(true);
assertTrue("in dont-tell-me mode, setof(_M,current_module(_M),_Ms),length(_Ms,N) returns binding for just one variable", q.oneSolution().keySet().size() == 1);
}
public void testDontTellMeMode2() {
final Query q = new Query("setof(_M,current_module(_M),_Ms),length(_Ms,N)");
JPL.setDTMMode(false);
assertTrue("not in dont-tell-me mode, setof(_M,current_module(_M),_Ms),length(_Ms,N) returns binding for three variables", q.oneSolution().keySet().size() == 3);
}
public void testModulePrefix1() {
assertTrue(Query.hasSolution("call(user:true)"));
}
private void testMutualRecursion(int n, long f) { // f is the expected result for fac(n)
try {
assertEquals("mutual recursive Java<->Prolog factorial: fac(" + n + ") = " + f, fac(n), f);
} catch (Exception e) {
fail("fac(" + n + ") threw " + e);
}
}
public void testMutualRecursion1() {
testMutualRecursion(1, 1);
}
public void testMutualRecursion2() {
testMutualRecursion(2, 2);
}
public void testMutualRecursion3() {
testMutualRecursion(3, 6);
}
public void testMutualRecursion10() {
testMutualRecursion(10, 3628800);
}
public void testIsJNull1() {
Term t = (Term) (new Query("X = @(null)")).oneSolution().get("X");
assertTrue("@(null) . isJNull() succeeds", t.isJNull());
}
public void testIsJNull2() {
Term t = (Term) (new Query("X = @(3)")).oneSolution().get("X");
assertFalse("@(3) . isJNull() fails", t.isJNull());
}
public void testIsJNull3() {
Term t = (Term) (new Query("X = _")).oneSolution().get("X");
assertFalse("_ . isJNull() fails", t.isJNull());
}
public void testIsJNull4() {
Term t = (Term) (new Query("X = @(true)")).oneSolution().get("X");
assertFalse("@(true) . isJNull() fails", t.isJNull());
}
public void testIsJNull5() {
Term t = (Term) (new Query("X = @(false)")).oneSolution().get("X");
assertFalse("@(false) . isJNull() fails", t.isJNull());
}
public void testIsJTrue1() {
Term t = (Term) (new Query("X = @(true)")).oneSolution().get("X");
assertTrue("@(true) . isJTrue() succeeds", t.isJTrue());
}
public void testIsJTrue2() {
Term t = (Term) (new Query("X = @(3)")).oneSolution().get("X");
assertFalse("@(3) . isJTrue() fails", t.isJTrue());
}
public void testIsJTrue3() {
Term t = (Term) (new Query("X = _")).oneSolution().get("X");
assertFalse("_ . isJTrue() fails", t.isJTrue());
}
public void testIsJTrue4() {
Term t = (Term) (new Query("X = @(false)")).oneSolution().get("X");
assertFalse("@(false) . isJTrue() fails", t.isJTrue());
}
public void testIsJVoid1() {
Term t = (Term) (new Query("X = @(void)")).oneSolution().get("X");
assertTrue("@(void) . isJVoid() succeeds", t.isJVoid());
}
public void testIsJVoid2() {
Term t = (Term) (new Query("X = @(3)")).oneSolution().get("X");
assertFalse("@(3) . isJVoid() fails", t.isJVoid());
}
public void testIsJVoid3() {
Term t = (Term) (new Query("X = _")).oneSolution().get("X");
assertFalse("_ . isJVoid() fails", t.isJVoid());
}
public void testTypeName1() {
assertEquals("Y = foo binds Y to an Atom", ((Term) Query.oneSolution("Y = foo").get("Y")).typeName(), "Atom");
}
public void testTypeName2() {
assertEquals("Y = 3.14159 binds Y to a Float", ((Term) Query.oneSolution("Y = 3.14159").get("Y")).typeName(), "Float");
}
public void testTypeName4() {
assertEquals("Y = 6 binds Y to an Integer", ((Term) Query.oneSolution("Y = 6").get("Y")).typeName(), "Integer");
}
public void testTypeName5() {
assertEquals("Y = _ binds Y to a Variable", ((Term) Query.oneSolution("Y = _").get("Y")).typeName(), "Variable");
}
public void testTypeName3() {
assertEquals("Y = f(x) binds Y to a Compound", ((Term) Query.oneSolution("Y = f(x)").get("Y")).typeName(), "Compound");
}
public void testGoalWithModulePrefix1() {
String goal = "jpl:jpl_modifier_bit(volatile,I)";
assertTrue(goal + " binds I to an integer", ((Term) Query.oneSolution(goal).get("I")).isInteger());
}
public void testGoalWithModulePrefix2() {
String goal = "user:length([],0)";
assertTrue(goal + " succeeds", Query.hasSolution(goal));
}
public void testGoalWithModulePrefix3() {
try {
(new Query("3:length([],0)")).hasSolution();
// shouldn't get to here
fail("(new Query(\"3:length([],0)\")).hasSolution() didn't throw exception");
} catch (jpl.PrologException e) {
// correct exception class, but is it correct in detail?
if (e.term().hasFunctor("error", 2) && e.term().arg(1).hasFunctor("type_error", 2) && e.term().arg(1).arg(1).hasFunctor("atom", 0)) {
// OK: an appropriate exception was thrown
} else {
fail("(new Query(\"3:length([],0)\")).hasSolution() threw incorrect PrologException: " + e);
}
} catch (Exception e) {
fail("(new Query(\"3:length([],0)\")).hasSolution() threw wrong class of exception: " + e);
}
}
public void testGoalWithModulePrefix4() {
try {
(new Query("_:length([],0)")).hasSolution();
// shouldn't get to here
fail("bad (unbound) module prefix");
} catch (jpl.PrologException e) {
// correct exception class, but is it correct in detail?
if (e.term().hasFunctor("error", 2) && e.term().arg(1).hasFunctor("instantiation_error", 0)) {
// OK: an appropriate exception was thrown
} else {
fail("(new Query(\"_:length([],0)\")).hasSolution() threw incorrect PrologException: " + e);
}
} catch (Exception e) {
fail("(new Query(\"_:length([],0)\")).hasSolution() threw wrong class of exception: " + e);
}
}
public void testGoalWithModulePrefix5() {
try {
(new Query("f(x):length([],0)")).hasSolution();
// shouldn't get to here
fail("bad (compound) module prefix");
} catch (jpl.PrologException e) {
// correct exception class, but is it correct in detail?
if (e.term().hasFunctor("error", 2) && e.term().arg(1).hasFunctor("type_error", 2) && e.term().arg(1).arg(1).hasFunctor("atom", 0)) {
// OK: an appropriate exception was thrown
} else {
fail("(new Query(\"f(x):length([],0)\")).hasSolution() threw incorrect PrologException: " + e);
}
} catch (Exception e) {
fail("(new Query(\"f(x):length([],0)\")).hasSolution() threw wrong class of exception: " + e);
}
}
public void testGoalWithModulePrefix6() {
try {
(new Query("no_such_module:no_such_predicate(0)")).hasSolution();
// shouldn't get to here
fail("bad (nonexistent) module prefix");
} catch (jpl.PrologException e) {
// correct exception class, but is it correct in detail?
if (e.term().hasFunctor("error", 2) && e.term().arg(1).hasFunctor("existence_error", 2) && e.term().arg(1).arg(1).hasFunctor("procedure", 0)) {
// OK: an appropriate exception was thrown
} else {
fail("(new Query(\"f(x):length([],0)\")).hasSolution() threw incorrect PrologException: " + e);
}
} catch (Exception e) {
fail("(new Query(\"f(x):length([],0)\")).hasSolution() threw wrong class of exception: " + e);
}
}
// public void testFetchCyclicTerm(){
// assertTrue((new Query("X=f(X)")).hasSolution());
// }
public void testFetchLongList0() {
assertTrue((new Query("findall(foo(N),between(0,10,N),L)")).hasSolution());
}
public void testFetchLongList1() {
assertTrue((new Query("findall(foo(N),between(0,100,N),L)")).hasSolution());
}
public void testFetchLongList2() {
assertTrue((new Query("findall(foo(N),between(0,1000,N),L)")).hasSolution());
}
public void testFetchLongList2c() {
assertTrue((new Query("findall(foo(N),between(0,1023,N),L)")).hasSolution());
}
public void testFetchLongList2a() {
assertTrue((new Query("findall(foo(N),between(0,2000,N),L)")).hasSolution());
}
// public void testFetchLongList2b() {
// assertTrue((new Query("findall(foo(N),between(0,3000,N),L)")).hasSolution());
// }
// public void testFetchLongList3() {
// assertTrue((new Query("findall(foo(N),between(0,10000,N),L)")).hasSolution());
// }
public void testUnicode0() {
assertTrue(Query.hasSolution("atom_codes(?,[32])", new Term[] { new Atom(" ") }));
}
public void testUnicode0a() {
assertTrue(Query.hasSolution("atom_codes(?,[32])", new Term[] { new Atom("\u0020") }));
}
public void testUnicode0b() {
assertTrue(Query.hasSolution("atom_codes(?,[0])", new Term[] { new Atom("\u0000") }));
}
public void testUnicode0c() {
assertTrue(Query.hasSolution("atom_codes(?,[1])", new Term[] { new Atom("\u0001") }));
}
public void testUnicode0d() {
assertTrue(Query.hasSolution("atom_codes(?,[127])", new Term[] { new Atom("\u007F") }));
}
public void testUnicode0e() {
assertTrue(Query.hasSolution("atom_codes(?,[128])", new Term[] { new Atom("\u0080") }));
}
public void testUnicode0f() {
assertTrue(Query.hasSolution("atom_codes(?,[255])", new Term[] { new Atom("\u00FF") }));
}
public void testUnicode0g() {
assertTrue(Query.hasSolution("atom_codes(?,[256])", new Term[] { new Atom("\u0100") }));
}
public void testUnicode1() {
assertTrue(Query.hasSolution("atom_codes(?,[0,127,128,255])", new Term[] { new Atom("\u0000\u007F\u0080\u00FF") }));
}
public void testUnicode2() {
assertTrue(Query.hasSolution("atom_codes(?,[256,32767,32768,65535])", new Term[] { new Atom("\u0100\u7FFF\u8000\uFFFF") }));
}
public void testStringXput1() {
Term a = (Term) (Query.oneSolution("string_concat(foo,bar,S)").get("S"));
assertTrue(a.name().equals("foobar"));
}
public void testStringXput2() {
String s1 = "\u0000\u007F\u0080\u00FF";
String s2 = "\u0100\u7FFF\u8000\uFFFF";
String s = s1 + s2;
Term a1 = new Atom(s1);
Term a2 = new Atom(s2);
Term a = (Term) (Query.oneSolution("string_concat(?,?,S)", new Term[] { a1, a2 }).get("S"));
assertEquals(a.name(), s);
}
// public void testMaxInteger1(){
// assertEquals(((Term)(Query.oneSolution("current_prolog_flag(max_integer,I)").get("I"))).longValue(), java.lang.Long.MAX_VALUE); // i.e. 9223372036854775807L
// }
// public void testSingleton1() {
// assertTrue(Query.hasSolution("style_check(-singleton),consult('test_singleton.pl')"));
// }
public void testStaticQueryInvalidSourceText2() {
String goal = "p(]";
try {
Query.hasSolution(goal);
} catch (jpl.PrologException e) {
if (e.term().hasFunctor("error", 2) && e.term().arg(1).hasFunctor("syntax_error", 1) && e.term().arg(1).arg(1).hasFunctor("cannot_start_term", 0)) {
// OK: an appropriate exception was thrown
} else {
fail("Query.hasSolution(" + goal + ") threw incorrect PrologException: " + e);
}
} catch (Exception e) {
fail("Query.hasSolution(" + goal + ") threw wrong class of exception: " + e);
}
}
public void testStaticQueryInvalidSourceText1() {
String goal = "bad goal";
try {
Query.hasSolution(goal);
} catch (jpl.PrologException e) {
if (e.term().hasFunctor("error", 2) && e.term().arg(1).hasFunctor("syntax_error", 1) && e.term().arg(1).arg(1).hasFunctor("operator_expected", 0)) {
// OK: an appropriate exception was thrown
} else {
fail("Query.hasSolution(" + goal + ") threw incorrect PrologException: " + e);
}
} catch (Exception e) {
fail("Query.hasSolution(" + goal + ") threw wrong class of exception: " + e);
}
}
public void testStaticQueryNSolutions1() {
String goal = "member(X, [0,1,2,3,4,5,6,7,8,9])";
int n = 5;
assertTrue("Query.nSolutions(" + goal + ", " + n + ") returns " + n + " solutions", Query.nSolutions(goal, n).length == n);
}
public void testStaticQueryNSolutions2() {
String goal = "member(X, [0,1,2,3,4,5,6,7,8,9])";
int n = 0;
assertTrue("Query.nSolutions(" + goal + ", " + n + ") returns " + n + " solutions", Query.nSolutions(goal, n).length == n);
}
public void testStaticQueryNSolutions3() {
String goal = "member(X, [0,1,2,3,4,5,6,7,8,9])";
int n = 20;
assertTrue("Query.nSolutions(" + goal + ", " + n + ") returns 10 solutions", Query.nSolutions(goal, n).length == 10);
}
public void testStaticQueryAllSolutions1() {
String goal = "member(X, [0,1,2,3,4,5,6,7,8,9])";
assertTrue("Query.allSolutions(" + goal + ") returns 10 solutions", Query.allSolutions(goal).length == 10);
}
public void testStaticQueryHasSolution1() {
String goal = "memberchk(13, [?,?,?])";
Term[] params = new Term[] { new Integer(12), new Integer(13), new Integer(14) };
assertTrue(Query.hasSolution(goal, params));
}
public void testStaticQueryHasSolution2() {
String goal = "memberchk(23, [?,?,?])";
Term[] params = new Term[] { new Integer(12), new Integer(13), new Integer(14) };
assertFalse(Query.hasSolution(goal, params));
}
public void testUtilListToTermArray1() {
String goal = "T = [a,b,c]";
Term list = (Term) Query.oneSolution(goal).get("T");
Term[] array = Util.listToTermArray(list);
assertTrue(array[2].isAtom() && array[2].name().equals("c"));
}
public void testTermToTermArray1() {
String goal = "T = [a,b,c]";
Term list = (Term) Query.oneSolution(goal).get("T");
Term[] array = list.toTermArray();
assertTrue(array[2].isAtom() && array[2].name().equals("c"));
}
public void testJRef1() {
// System.out.println("java.library.path=" + System.getProperties().get("java.library.path"));
// System.out.println("jpl.c version = " + jpl.fli.Prolog.get_c_lib_version());
int i = 76543;
Integer I = new Integer(i);
Query q = new Query("jpl_call(?,intValue,[],I2)", new Term[] { new JRef(I) });
Term I2 = (Term) q.oneSolution().get("I2");
assertTrue(I2.isInteger() && I2.intValue() == i);
}
public void testBerhhard1() {
assertTrue(Query.allSolutions( "consult(library('lists'))" ).length == 1);
}
}

View File

@ -1,142 +0,0 @@
package jpl.test;
import java.util.Map;
import jpl.Atom;
import jpl.Compound;
import jpl.Integer;
import jpl.JPL;
import jpl.PrologException;
import jpl.Query;
import jpl.Term;
import jpl.Util;
import jpl.Variable;
import jpl.fli.Prolog;
// This class is nearly obsolete; most of its tests have been migrated to TestJUnit.
public class TestOLD {
private static void test10() {
System.err.println("test10:");
System.err.println(" java_lib_version = " + JPL.version_string());
System.err.println(" c_lib_version = " + jpl.fli.Prolog.get_c_lib_version());
System.err.println(" pl_lib_version = " + new Query(new Compound("jpl_pl_lib_version", new Term[] { new Variable("V") })).oneSolution().get("V"));
System.err.println(" java.version = " + System.getProperty("java.version"));
System.err.println(" os.name = " + System.getProperty("os.name"));
System.err.println(" os.arch = " + System.getProperty("os.arch"));
System.err.println(" os.version = " + System.getProperty("os.version"));
System.err.println();
}
private static void test10j() {
Term l2 = Util.termArrayToList(new Term[] { new Atom("a"), new Atom("b"), new Atom("c"), new Atom("d"), new Atom("e") });
Query q9 = new Query(new Compound("append", new Term[] { new Variable("Xs"), new Variable("Ys"), l2 }));
Map[] s9s = q9.allSolutions();
System.err.println("test10j:");
for (int i = 0; i < s9s.length; i++) {
System.err.println(" append(Xs,Ys,[a,b,c,d,e]) -> " + Util.toString(s9s[i]));
}
System.err.println();
}
private static void test10k() {
String[] args = jpl.fli.Prolog.get_default_init_args();
String which;
String s = "";
System.err.println("test10k:");
if (args == null) {
args = jpl.fli.Prolog.get_actual_init_args();
which = "actual";
} else {
which = "default";
}
for (int i = 0; i < args.length; i++) {
s = s + args[i] + " ";
}
System.err.println(" " + which + "_init_args = " + s + '\n');
}
private static void test10l() {
Query q5 = new Query(new Compound("length", new Term[] { new Variable("Zs"), new jpl.Integer(5) }));
Map s5 = q5.oneSolution();
System.err.println("test10l:");
System.err.println(" length(Zs,5)");
System.err.println(" " + Util.toString(s5));
System.err.println(" Zs = " + (Term) s5.get("Zs"));
System.err.println();
}
private static void test10m() {
String text = "append(Xs,Ys,[_,_,_,_,_])";
Query q = new Query(text);
Map[] ss = q.allSolutions();
System.err.println("test10m:");
System.err.println(" all solutions of " + text);
for (int i = 0; i < ss.length; i++) {
System.err.println(" " + Util.toString(ss[i]));
}
System.err.println();
}
private static void test10o() {
System.err.println("test10o:");
Term l2b = Util.termArrayToList(new Term[] { new Variable("A"), new Variable("B"), new Variable("C"), new Variable("D"), new Variable("E") });
Query q9b = new Query(new Compound("append", new Term[] { new Variable("Xs"), new Variable("Ys"), l2b }));
Map[] s9bs = q9b.allSolutions();
for (int i = 0; i < s9bs.length; i++) {
System.err.println(" append(Xs,Ys,[A,B,C,D,E]) -> " + Util.toString(s9bs[i]));
}
System.err.println();
}
private static void test10q() {
System.err.println("test10q:");
System.err.println((new Compound("Bad Name", new Term[] { new Atom("3 3") })).toString());
System.err.println();
}
private static void test10s() {
final Query q = new Query("jpl_slow_goal"); // 10 successive sleep(1)
System.err.println("test10s:");
Thread t = new Thread(new Runnable() {
public void run() {
try {
System.err.println("q.hasSolution() ... ");
System.err.println(q.hasSolution() ? "finished" : "failed");
} catch (Exception e) {
System.err.println("q.hasSolution() threw " + e);
}
}
});
t.start(); // call the query in a separate thread
System.err.println("pausing for 2 secs...");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
;
} // wait a coupla seconds for it to get started
// (new Query("set_prolog_flag(abort_with_exception, true)")).hasSolution();
System.err.println("calling q.abort()...");
q.abort();
System.err.println();
}
public static void main(String argv[]) {
Prolog.set_default_init_args(new String[] { "libpl.dll", "-f", "none", "-g", "set_prolog_flag(debug_on_error,false)", "-q" });
System.err.println("tag = " + Prolog.object_to_tag(new Query("hello")));
test10k();
test10();
// test10h();
// test10i();
test10j();
test10k();
test10l();
test10m();
// test10n();
test10o();
//test10p();
test10q();
// test10r();
// test10s();
// test10t();
// test10u();
// test10v();
String s = new String("" + '\0' + '\377');
System.err.println("s.length = " + s.length());
for (int i = 0; i < s.length(); i++) {
System.err.print((new Integer(s.charAt(i))).toString() + " ");
}
System.err.println();
System.err.println(new Query("atom_codes(A,[127,128,255,0])").oneSolution().toString());
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,43 +0,0 @@
:- ensure_loaded(library(swi)).
jpl_java_home('@JAVA_HOME@').
yap.
load_jpl_lib :-
jpl_java_home(JavaHome),
fetch_arch(Arch),
gen_jvm_lib(JavaHome,Arch,JPL,JLibs),
load_foreign_files(JPL, JLibs, install), !.
fetch_arch(Arch) :-
current_prolog_flag(host_type,Name),
atom_codes(Name,Codes),
gen_arch(Codes,Arch).
gen_arch(L,mac) :-
append(_,[0'd,0'a,0'r,0'w,0'i,0'n|_],L), !.
% handle compilation in 64 bit machine of 32 bit binary.
gen_arch([0'x,0'8,0'6,0'_,0'6,0'4|_],i386) :- yap_flag(max_tagged_integer, 67108863).
gen_arch([0'x,0'8,0'6,0'_,0'6,0'4|_],amd64).
gen_arch([0'i,_,0'8,0'6|_],i386). % take all versions of X86
gen_arch([0's,0'p,0'a,0'r,0'c|_],sparc).
gen_arch([0'/,0'u,0's,0'r|_],mac).
gen_jvm_lib(_,mac,[jpl],[]) :- !.
gen_jvm_lib(JavaHome,Arch,[jpl], [JLib]) :-
atom_concat([JavaHome,'/jre/lib/',Arch,'/client/libjvm.so'],JLib),
exists(JLib), !.
gen_jvm_lib(JavaHome,Arch,[jpl], [JLib]) :-
atom_concat([JavaHome,'/jre/lib/',Arch,'/server/libjvm.so'],JLib),
exists(JLib), !.
gen_jvm_lib(JavaHome,Arch,[jpl], [JLib]) :-
atom_concat([JavaHome,'/jre/lib/',Arch,'/classic/libjvm.so'],JLib),
exists(JLib), !.
gen_jvm_lib(JavaHome,Arch,[jpl], [JLib]) :-
atom_concat([JavaHome,'/jre/lib/',Arch,'/libjvm.so'],JLib),
exists(JLib), !.

View File

@ -1,63 +0,0 @@
#
#
JAVA_HOME=@JAVA_HOME@
JVM_INC = @JAVAINCPATH@
JVM_LIB = @JAVALIBPATH@ -ljava -lverify -ljvm
#
#
#
# default base directory for YAP installation
# (EROOT for architecture-dependent files)
#
prefix = @prefix@
ROOTDIR = $(prefix)
EROOTDIR = @exec_prefix@
#
# where the binary should be
#
BINDIR = $(EROOTDIR)/bin
#
# where YAP should look for libraries
#
LIBDIR=$(EROOTDIR)/lib/Yap
#
#
CC=@CC@
CFLAGS= @CFLAGS@ $(YAP_EXTRAS) $(DEFS) -I$(srcdir) -I../../.. -I$(srcdir)/../../../include $(JVM_INC) -DJAVA_HOME=\"$(JAVA_HOME)\"
#
#
# You shouldn't need to change what follows.
#
INSTALL=@INSTALL@
INSTALL_DATA=@INSTALL_DATA@
INSTALL_PROGRAM=@INSTALL_PROGRAM@
SHELL=/bin/sh
RANLIB=@RANLIB@
srcdir=@srcdir@
SHLIB_CFLAGS=@SHLIB_CFLAGS@
SHLIB_SUFFIX=@SHLIB_SUFFIX@
#4.1VPATH=@srcdir@:@srcdir@/OPTYap
CWD=$(PWD)
#
OBJS=jpl.o
SOBJS=jpl@SHLIB_SUFFIX@
all: $(SOBJS)
jpl.o: $(srcdir)/jpl.c $(srcdir)/hacks.c
$(CC) -c $(CFLAGS) $(SHLIB_CFLAGS) $(srcdir)/jpl.c -o jpl.o
@DO_SECOND_LD@%@SHLIB_SUFFIX@: %.o
@DO_SECOND_LD@ @SHLIB_LD@ -o $@ $<
@DO_SECOND_LD@jpl_jni@SHLIB_SUFFIX@: jpl_jni.o jvm.o
@DO_SECOND_LD@ @SHLIB_LD@ -o jpl_jni@SHLIB_SUFFIX@ jpl.o $(JVM_LIB)
install: all
$(INSTALL_PROGRAM) $(SOBJS) $(DESTDIR)$(LIBDIR)
clean:
rm -f *.o *~ $(OBJS) $(SOBJS) *.BAK

View File

@ -1,73 +0,0 @@
/*
%T jni_SetByteArrayElement(+term, +term, +term)
*/
static foreign_t
jni_SetByteArrayElement(
term_t ta1, // +Arg1
term_t ta2, // +Arg2
term_t ta3 // +Arg3
)
{
jboolean r; // Prolog exit/fail outcome
jbyteArray p1;
int i2;
jbyte p4;
JNIEnv *env;
atom_t a; /* " */
functor_t fn; /* temp for conversion macros */
term_t a1; /* " */
int i; /* " */
if ( !jni_ensure_jvm() )
{
return FALSE;
}
r =
JNI_term_to_byte_jarray(ta1,p1)
&& JNI_term_to_jint(ta2,i2)
&& JNI_term_to_jbyte(ta3,p4)
&& ( (*env)->SetByteArrayRegion(env,p1,(jsize)i2,1,&p4) , TRUE );
return jni_check_exception(env) && r;
}
/*
%T jni_SetByteArrayElement(+term, +term, +term)
*/
static foreign_t
jni_SetDoubleArrayElement(
term_t ta1, // +Arg1
term_t ta2, // +Arg2
term_t ta3 // +Arg3
)
{
jboolean r; // Prolog exit/fail outcome
void *p1;
jint i2;
jdouble p4;
JNIEnv *env;
atom_t a; /* " */
functor_t fn; /* temp for conversion macros */
term_t a1; /* " */
int i; /* " */
int64_t i64;
if ( !jni_ensure_jvm() )
{
return FALSE;
}
r =
JNI_term_to_double_jarray(ta1,p1)
&& JNI_term_to_jint(ta2,i2)
&& JNI_term_to_jdouble(ta3,p4)
&& ( (*env)->SetDoubleArrayRegion(env,(jdoubleArray)p1,(jsize)i2,1,&p4) , TRUE );
return jni_check_exception(env) && r;
}

File diff suppressed because it is too large Load Diff