[Mulgara-svn] r1563 - in trunk: . conf src/jar src/jar/content-rlog src/jar/content-rlog/java src/jar/content-rlog/java/org src/jar/content-rlog/java/org/mulgara src/jar/content-rlog/java/org/mulgara/content src/jar/content-rlog/java/org/mulgara/content/rlog src/jar/content-rlog/java/org/mulgara/krule src/jar/content-rlog/java/org/mulgara/krule/rlog src/jar/content-rlog/java/org/mulgara/krule/rlog/ast src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output src/jar/content-rlog/java/org/mulgara/krule/rlog/parser src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf src/jar/content-rlog/javacc src/jar/content-rlog/javacc/org src/jar/content-rlog/javacc/org/mulgara src/jar/content-rlog/javacc/org/mulgara/krule src/jar/content-rlog/javacc/org/mulgara/krule/rlog
pag at mulgara.org
pag at mulgara.org
Fri Feb 27 07:06:29 UTC 2009
Author: pag
Date: 2009-02-26 23:06:28 -0800 (Thu, 26 Feb 2009)
New Revision: 1563
Added:
trunk/src/jar/content-rlog/
trunk/src/jar/content-rlog/build.xml
trunk/src/jar/content-rlog/content-rlog-build.properties
trunk/src/jar/content-rlog/java/
trunk/src/jar/content-rlog/java/org/
trunk/src/jar/content-rlog/java/org/mulgara/
trunk/src/jar/content-rlog/java/org/mulgara/content/
trunk/src/jar/content-rlog/java/org/mulgara/content/rlog/
trunk/src/jar/content-rlog/java/org/mulgara/content/rlog/RlogContentHandler.java
trunk/src/jar/content-rlog/java/org/mulgara/content/rlog/RlogStatements.java
trunk/src/jar/content-rlog/java/org/mulgara/content/rlog/RlogStatementsUnitTest.java
trunk/src/jar/content-rlog/java/org/mulgara/content/rlog/package.html
trunk/src/jar/content-rlog/java/org/mulgara/krule/
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/Interpreter.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/Rlog.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/Axiom.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/BPredicate.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/BPredicateLabel.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/BPredicateLiteral.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/IntegerLiteral.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/InvertedPredicate.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/Node.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/NullPredicate.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/Predicate.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/PredicateLiteral.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/PredicateParam.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/PrintWalker.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/Rule.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/Statement.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/StringLiteral.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/TreeTransformer.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/TreeWalker.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/TypeLabel.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/TypeLiteral.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/TypeStatement.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/Variable.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/AxiomGenerator.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/AxiomWriter.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/KruleGenerator.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/KruleWriter.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/RDFXMLWriter.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/ReferenceGenerator.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/ReferenceWriter.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/RuleGenerator.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/RuleWriter.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/TripleGenerator.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/VariableWriter.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/XMLFragmentWriter.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/parser/
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/parser/NSUtils.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/parser/TypeException.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/parser/URIParseException.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/Literal.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/MulgaraGraphs.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/RDF.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/RDFNode.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/URIReference.java
trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/Var.java
trunk/src/jar/content-rlog/javacc/
trunk/src/jar/content-rlog/javacc/org/
trunk/src/jar/content-rlog/javacc/org/mulgara/
trunk/src/jar/content-rlog/javacc/org/mulgara/krule/
trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/
trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/ParseException.java
trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/RlogParser.java
trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/RlogParser.jj
trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/RlogParserConstants.java
trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/RlogParserTokenManager.java
trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/SimpleCharStream.java
trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/Token.java
trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/TokenMgrError.java
Modified:
trunk/.classpath
trunk/build.xml
trunk/conf/mulgara-config.xml
Log:
Integrated the RLog parser as a content handler
Modified: trunk/.classpath
===================================================================
--- trunk/.classpath 2009-02-27 06:53:53 UTC (rev 1562)
+++ trunk/.classpath 2009-02-27 07:06:28 UTC (rev 1563)
@@ -6,6 +6,8 @@
<classpathentry kind="src" path="src/jar/content-mp3/java"/>
<classpathentry kind="src" path="src/jar/content-n3/java"/>
<classpathentry kind="src" path="src/jar/content-rdfxml/java"/>
+ <classpathentry kind="src" path="src/jar/content-rlog/java"/>
+ <classpathentry kind="src" path="src/jar/content-rlog/javacc"/>
<classpathentry kind="src" path="src/jar/demo-mp3/java"/>
<classpathentry kind="src" path="src/jar/descriptor/src/java"/>
<classpathentry kind="src" path="src/jar/driver/java"/>
Modified: trunk/build.xml
===================================================================
--- trunk/build.xml 2009-02-27 06:53:53 UTC (rev 1562)
+++ trunk/build.xml 2009-02-27 07:06:28 UTC (rev 1563)
@@ -21,6 +21,7 @@
<property file="${jar.src.dir}/content-mp3/content-mp3-build.properties"/>
<property file="${jar.src.dir}/content-n3/content-n3-build.properties"/>
<property file="${jar.src.dir}/content-rdfxml/content-rdfxml-build.properties"/>
+ <property file="${jar.src.dir}/content-rlog/content-rlog-build.properties"/>
<property file="${jar.src.dir}/descriptor/descriptor-build.properties"/>
<property file="${jar.src.dir}/driver/driver-build.properties"/>
<property file="${jar.src.dir}/dtd/dtd-build.properties"/>
@@ -84,6 +85,7 @@
<import file="${jar.src.dir}/content-mp3/build.xml"/>
<import file="${jar.src.dir}/content-n3/build.xml"/>
<import file="${jar.src.dir}/content-rdfxml/build.xml"/>
+ <import file="${jar.src.dir}/content-rlog/build.xml"/>
<import file="${jar.src.dir}/descriptor/build.xml"/>
<import file="${jar.src.dir}/driver/build.xml"/>
<import file="${jar.src.dir}/dtd/build.xml"/>
@@ -470,7 +472,7 @@
resolver-store-dist, resolver-url-dist, resolver-jar-dist,
resolver-view-dist, resolver-xsd-dist,
content-mbox-dist, content-mp3-dist, content-n3-dist,
- content-rdfxml-dist,
+ content-rdfxml-dist, content-rlog-dist,
lite-create-manifest, javadoc-dist,
lite-dist-uptodate"
unless="dist.lite.uptodate"
@@ -536,6 +538,7 @@
<zipfileset src="${bin.dir}/${content-mp3.jar}" excludes="META-INF/**"/>
<zipfileset src="${bin.dir}/${content-n3.jar}" excludes="META-INF/**"/>
<zipfileset src="${bin.dir}/${content-rdfxml.jar}" excludes="META-INF/**"/>
+ <zipfileset src="${bin.dir}/${content-rlog.jar}" excludes="META-INF/**"/>
<zipfileset src="${bin.dir}/${descriptor.jar}" excludes="META-INF/**"/>
<zipfileset src="${bin.dir}/${driver.jar}" excludes="META-INF/**"/>
<zipfileset src="${bin.dir}/${dtd.jar}" excludes="META-INF/**"/>
@@ -732,7 +735,7 @@
ant-task-jar, client-jrdf-jar, config-jar,
content-mbox-jar, content-mp3-jar,
content-n3-jar, content-rdfxml-jar,
- querylang-jar,
+ content-rlog-jar, querylang-jar,
doclet.jar, jrdf-jar, store-jar,
store-xa-jar,
store-nodepool-jar, store-nodepool-memory-jar,
@@ -820,6 +823,7 @@
<sourcepath path="${content-mp3.src.dir}/java"/>
<sourcepath path="${content-n3.src.dir}/java"/>
<sourcepath path="${content-rdfxml.src.dir}/java"/>
+ <sourcepath path="${content-rlog.src.dir}/java"/>
<sourcepath path="${driver.src.dir}/java"/>
<sourcepath path="${dtd.src.dir}/java"/>
<sourcepath path="${querylang.src.dir}/java"/>
@@ -883,7 +887,7 @@
client-jrdf-javadoc,
content-mbox-javadoc,
content-mp3-javadoc, content-n3-javadoc,
- content-rdfxml-javadoc,
+ content-rdfxml-javadoc, content-rlog-javadoc,
descriptor-javadoc, driver-javadoc, dtd-javadoc,
querylang-javadoc,
store-javadoc, store-xa-javadoc,
@@ -1561,6 +1565,7 @@
content-mp3-jar,
content-n3-jar,
content-rdfxml-jar,
+ content-rlog-jar,
create-manifest,
demo-jar,
dtd-jar,
@@ -1709,6 +1714,7 @@
<zipfileset src="${bin.dir}/${content-n3.jar}" excludes="META-INF/**"/>
<zipfileset src="${bin.dir}/${content-mbox.jar}" excludes="META-INF/**"/>
<zipfileset src="${bin.dir}/${content-rdfxml.jar}" excludes="META-INF/**"/>
+ <zipfileset src="${bin.dir}/${content-rlog.jar}" excludes="META-INF/**"/>
<zipfileset src="${bin.dir}/${resolver-nodetype.jar}" excludes="META-INF/**"/>
<zipfileset src="${bin.dir}/${resolver-prefix.jar}" excludes="META-INF/**"/>
<zipfileset src="${bin.dir}/${resolver-relational.jar}" excludes="META-INF/**"/>
@@ -1754,6 +1760,7 @@
content-mp3-jar,
content-n3-jar,
content-rdfxml-jar,
+ content-rlog-jar,
create-manifest,
demo-jar,
dtd-jar,
@@ -1847,6 +1854,7 @@
<zipfileset src="${bin.dir}/${content-n3.jar}" excludes="META-INF/**"/>
<zipfileset src="${bin.dir}/${content-mbox.jar}" excludes="META-INF/**"/>
<zipfileset src="${bin.dir}/${content-rdfxml.jar}" excludes="META-INF/**"/>
+ <zipfileset src="${bin.dir}/${content-rlog.jar}" excludes="META-INF/**"/>
<zipfileset src="${bin.dir}/${resolver-nodetype.jar}" excludes="META-INF/**"/>
<zipfileset src="${bin.dir}/${resolver-prefix.jar}" excludes="META-INF/**"/>
<zipfileset src="${bin.dir}/${resolver-relational.jar}" excludes="META-INF/**"/>
@@ -1880,6 +1888,7 @@
config-jar,
content-n3-jar,
content-rdfxml-jar,
+ content-rlog-jar,
create-manifest,
demo-jar,
dtd-jar,
@@ -1964,6 +1973,7 @@
<zipfileset src="${bin.dir}/${tuples-hybrid.jar}" excludes="**/*.xml, META-INF/**"/>
<zipfileset src="${bin.dir}/${content-n3.jar}" excludes="**/*.xml, META-INF/**"/>
<zipfileset src="${bin.dir}/${content-rdfxml.jar}" excludes="**/*.xml, META-INF/**"/>
+ <zipfileset src="${bin.dir}/${content-rlog.jar}" excludes="**/*.xml, META-INF/**"/>
<zipfileset src="${bin.dir}/${resolver-nodetype.jar}" excludes="**/*.xml, META-INF/**"/>
<zipfileset src="${bin.dir}/${resolver-prefix.jar}" excludes="**/*.xml, META-INF/**"/>
<zipfileset src="${bin.dir}/${resolver-relational.jar}" excludes="**/*.xml, META-INF/**"/>
@@ -2046,7 +2056,7 @@
<target name="resolver-api-test"
depends="content-mbox-test, content-mp3-test, content-n3-test,
- content-rdfxml-test,
+ content-rdfxml-test, content-rlog-test,
resolver-test, resolver-null-test, resolver-file-test,
resolver-filesystem-test, resolver-jar-test, resolver-gis-test,
resolver-http-test, resolver-lucene-test,
Modified: trunk/conf/mulgara-config.xml
===================================================================
--- trunk/conf/mulgara-config.xml 2009-02-27 06:53:53 UTC (rev 1562)
+++ trunk/conf/mulgara-config.xml 2009-02-27 07:06:28 UTC (rev 1563)
@@ -117,6 +117,7 @@
<ContentHandler type="org.mulgara.content.mp3.MP3ContentHandler"/>
<ContentHandler type="org.mulgara.content.mbox.MBoxContentHandler"/>
<ContentHandler type="org.mulgara.content.n3.N3ContentHandler"/>
+ <ContentHandler type="org.mulgara.content.rlog.RlogContentHandler"/>
<!--
Additional resolvers
Added: trunk/src/jar/content-rlog/build.xml
===================================================================
--- trunk/src/jar/content-rlog/build.xml (rev 0)
+++ trunk/src/jar/content-rlog/build.xml 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,125 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!DOCTYPE project>
+
+<!-- =================================================================== -->
+<!-- Project definition -->
+<!-- =================================================================== -->
+<project name="content-rlog" default="content-rlog-jar" basedir="../../..">
+
+ <!-- =================================================================== -->
+ <!-- Property Definitions -->
+ <!-- =================================================================== -->
+
+ <!-- =================================================================== -->
+ <!-- Imports -->
+ <!-- =================================================================== -->
+
+ <!-- =================================================================== -->
+ <!-- Path Definitions -->
+ <!-- =================================================================== -->
+ <path id="content-rlog-classpath">
+ <path refid="common-classpath"/>
+ <fileset file="${query.dist.dir}/${query.jar}"/>
+ <fileset file="${resolver-spi.dist.dir}/${resolver-spi.jar}"/>
+ <fileset file="${resolver-file.dist.dir}/${resolver-file.jar}"/>
+ <fileset file="${tuples.dist.dir}/${tuples.jar}"/>
+ <fileset file="${util.dist.dir}/${util.jar}"/>
+ <fileset file="${rules.dist.dir}/${rules.jar}"/>
+ <fileset file="${krule.dist.dir}/${krule.jar}"/>
+ </path>
+
+ <path id="content-rlog-test-classpath">
+ <path refid="content-rlog-classpath"/>
+ <fileset file="${resolver-file.dist.dir}/${resolver-file.jar}"/>
+ <fileset file="${store-stringpool-memory.dist.dir}/${store-stringpool-memory.jar}"/>
+ <fileset file="${store-stringpool-xa.dist.dir}/${store-stringpool-xa.jar}"/>
+ <fileset file="${content-rlog.dist.dir}/${content-rlog.jar}"/>
+ </path>
+
+
+ <target name="content-rlog-clean" description="Removes all compile generated files for content-rlog">
+ <tstamp/>
+ <delete dir="${content-rlog.obj.dir}"/>
+ <delete dir="${content-rlog.test.dir}"/>
+ <delete dir="${content-rlog.dist.dir}"/>
+ </target>
+
+
+ <target name="-content-rlog-prepare"
+ description="Creates all directories associated with the content-rlog's compilation"
+ depends="-prepare-build">
+ <mkdir dir="${content-rlog.obj.dir}"/>
+ <mkdir dir="${content-rlog.test.dir}"/>
+ <mkdir dir="${content-rlog.dist.dir}"/>
+ <mkdir dir="${content-rlog.obj.dir}/classes"/>
+ </target>
+
+
+ <target name="gen-rlog-parser" description="Build the JavaCC generated files">
+ <javacc target="${content-rlog.src.dir}/javacc/org/mulgara/krule/rlog/RlogParser.jj" javacchome="${lib.dir}" />
+ </target>
+
+ <target name="content-rlog-compile"
+ depends="-content-rlog-prepare, gen-rlog-parser, resolver-spi-jar, resolver-file-jar, krule-jar"
+ description="Compiles all content-rlog related files included generated source code">
+ <javac destdir="${content-rlog.obj.dir}/classes" debug="on" deprecation="on" source="1.5" encoding="UTF-8">
+ <classpath refid="content-rlog-classpath"/>
+ <src path="${content-rlog.src.dir}/java"/>
+ <src path="${content-rlog.src.dir}/javacc"/>
+ </javac>
+ </target>
+
+
+ <target name="content-rlog-jar" depends="content-rlog-compile, -content-rlog-jar-uptodate"
+ unless="content-rlog.jar.uptodate" description="Builds the RLog content handler JAR">
+
+ <jar jarfile="${content-rlog.dist.dir}/${content-rlog.jar}">
+ <fileset dir="${content-rlog.obj.dir}/classes"/>
+ </jar>
+ </target>
+
+
+ <target name="-content-rlog-jar-uptodate">
+ <uptodate property="content-rlog.jar.uptodate" targetfile="${content-rlog.dist.dir}/${content-rlog.jar}">
+ <srcfiles dir="${content-rlog.obj.dir}/classes" includes="**/*"/>
+ </uptodate>
+ </target>
+
+
+ <target name="content-rlog-dist" depends="content-rlog-jar" unless="content-rlog.uptodate"
+ description="Performs all tasks related to finalising this content-rlog and readying it for distribution">
+ </target>
+
+
+ <target name="content-rlog-test"
+ depends="content-rlog-jar, resolver-file-jar, store-stringpool-memory-jar, store-stringpool-xa-jar">
+ <antcall target="component-test">
+ <param name="classpath.id" value="content-rlog-test-classpath"/>
+ <param name="dir" value="${content-rlog.src.dir}"/>
+ <param name="jar" value="${content-rlog.jar}"/>
+ </antcall>
+ </target>
+
+
+ <target name="content-rlog-javadoc" depends="content-rlog-jar" description="Creates the javadoc for this content-rlog">
+ <antcall target="javadoc">
+ <param name="javadoc.package" value="org.mulgara.content.rlog.*"/>
+ <param name="javadoc.classpath" value="content-rlog-classpath"/>
+ <param name="javadoc.sourcepath" value="${content-rlog.src.dir}/java"/>
+ </antcall>
+ </target>
+
+
+ <target name="content-rlog-help" description="Displays the help information for this content-rlog">
+ <echo message="Welcome to the build script for ${content-rlog.name}."/>
+ <echo message=""/>
+ <echo message="These targets can be invoked as follows:"/>
+ <echo message=" ./build.sh <target>"/>
+ <echo message=""/>
+ <java fork="false" classname="org.apache.tools.ant.Main" newenvironment="false">
+ <jvmarg value="${arch.bits}"/>
+ <arg line="-buildfile ${content-rlog.src.dir}/build.xml -projecthelp"/>
+ </java>
+ </target>
+
+</project>
Added: trunk/src/jar/content-rlog/content-rlog-build.properties
===================================================================
--- trunk/src/jar/content-rlog/content-rlog-build.properties (rev 0)
+++ trunk/src/jar/content-rlog/content-rlog-build.properties 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,14 @@
+#
+# Properties used by the RLog content handler module
+#
+
+# Module Name
+content-rlog.name = Content RLog
+
+# General module properties
+content-rlog.src.dir = ${jar.src.dir}/content-rlog
+content-rlog.obj.dir = ${jar.obj.dir}/content-rlog
+content-rlog.dist.dir = ${bin.dir}
+content-rlog.test.dir = ${test.dir}/content-rlog
+content-rlog.jxtest.dir = ${jxtest.dir}/content-rlog
+content-rlog.jar = content-rlog-base-${mulgara-version}.jar
Added: trunk/src/jar/content-rlog/java/org/mulgara/content/rlog/RlogContentHandler.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/content/rlog/RlogContentHandler.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/content/rlog/RlogContentHandler.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,99 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package org.mulgara.content.rlog;
+
+// Java 2 enterprise packages
+import javax.activation.MimeType;
+import javax.activation.MimeTypeParseException;
+
+// Third party packages
+import org.apache.log4j.Logger; // Apache Log4J
+
+// Local packages
+import org.mulgara.content.Content;
+import org.mulgara.content.ContentHandler;
+import org.mulgara.content.ContentHandlerException;
+import org.mulgara.content.ModifiedException;
+import org.mulgara.content.NotModifiedException;
+import org.mulgara.resolver.spi.ResolverSession;
+import org.mulgara.resolver.spi.Statements;
+
+/**
+ * Resolves constraints in models defined by RLog documents.
+ *
+ * @created Feb 24, 2009
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class RlogContentHandler implements ContentHandler {
+ /** Logger. */
+ @SuppressWarnings("unused")
+ private static Logger logger = Logger.getLogger(RlogContentHandler.class);
+
+ /** The MIME type of RLog. */
+ private static final MimeType TEXT_RLOG;
+
+ static {
+ try {
+ TEXT_RLOG = new MimeType("text", "rlog");
+ } catch (MimeTypeParseException e) {
+ throw new ExceptionInInitializerError(e);
+ }
+ }
+
+
+ public Statements parse(Content content, ResolverSession resolverSession) throws ContentHandlerException {
+ return new RlogStatements(content, resolverSession);
+ }
+
+
+ /**
+ * Tests if this content handler can handle the provided content.
+ * @return <code>true</code> if the file part of the URI has an
+ * <code>.rl</code>, or <code>.rlog</code> extension
+ * @throws NotModifiedException If the content has been accessed before
+ * and not modified in the meantime.
+ */
+ public boolean canParse(Content content) throws NotModifiedException {
+ // We definitely can parse anything of MIME type text/rlog
+ MimeType contentType = content.getContentType();
+ if (contentType != null && (TEXT_RLOG.match(contentType))) return true;
+
+ // Don't know about this MIME type, so sniff at the pathname extension
+ // We're breaking the WWW architectural principle of URI Opacity by doing
+ // so (see http://www.w3.org/TR/webarch/#uri-opacity).
+
+ if (content.getURI() == null) return false;
+
+ // Obtain the path part of the URI
+ String path = content.getURI().getPath();
+ if (path == null) return false;
+
+ // We recognize a fixed set of extensions
+ return path.endsWith(".dl") || path.endsWith(".rl") || path.endsWith(".rlog");
+ }
+
+
+ /**
+ * Writes out the statements in basic RLog format.
+ */
+ public void serialize(Statements statements, Content content, ResolverSession resolverSession)
+ throws ContentHandlerException, ModifiedException {
+ throw new UnsupportedOperationException();
+ }
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/content/rlog/RlogStatements.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/content/rlog/RlogStatements.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/content/rlog/RlogStatements.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,283 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package org.mulgara.content.rlog;
+
+// Java 2 standard packages
+
+// Third party packages
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+
+import org.apache.log4j.Logger; // Apache Log4J
+
+// Locally written packages
+import org.mulgara.content.Content;
+import org.mulgara.content.NotModifiedException;
+import org.mulgara.content.NotModifiedTuplesException;
+import org.mulgara.krule.rlog.Interpreter;
+import org.mulgara.krule.rlog.ParseException;
+import org.mulgara.query.Cursor;
+import org.mulgara.query.TuplesException;
+import org.mulgara.query.Variable;
+import org.mulgara.resolver.spi.LocalizeException;
+import org.mulgara.resolver.spi.ResolverSession;
+import org.mulgara.resolver.spi.Statements;
+import org.mulgara.resolver.spi.StatementsWrapperResolution;
+import org.mulgara.store.nodepool.NodePoolException;
+import org.mulgara.store.tuples.AbstractTuples;
+import org.mulgara.store.tuples.Tuples;
+
+import org.mulgara.krule.rlog.Rlog;
+import org.mulgara.krule.rlog.ast.output.KruleGenerator;
+import org.mulgara.krule.rlog.parser.TypeException;
+import org.mulgara.krule.rlog.parser.URIParseException;
+
+/**
+ * Parses an {@link InputStream} into {@link Statements}.
+ * This parser uses memory and does not stream.
+ *
+ * @created Feb 24, 2009
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class RlogStatements extends AbstractTuples implements Statements {
+ /** Logger. */
+ private static final Logger logger = Logger.getLogger(RlogStatements.class.getName());
+
+ /** The session used to globalize the RDF nodes from the stream. */
+ private ResolverSession resolverSession;
+
+ private Interpreter rlogParser = null;
+
+ private List<long[]> triples = null;
+
+ /** The current row iterator. If the cursor is not on a row, this will be <code>null</code> */
+ private Iterator<long[]> tripleIterator = null;
+
+ /** The current row. If the cursor is not on a row, this will be <code>null</code> */
+ private long[] triple;
+
+ /** If this exception is not null then it has yet to be thrown to the calling process */
+ TuplesException outstandingException = null;
+
+ /**
+ * Construct an RLog parser.
+ *
+ * @param content the RLog content
+ * @param resolverSession session against which to localize RDF nodes
+ * @throws IllegalArgumentException if <var>inputStream</var> or <var>resolverSession</var> are <code>null</code>
+ */
+ RlogStatements(Content content, ResolverSession resolverSession) {
+ if (content == null) throw new IllegalArgumentException( "Null \"content\" parameter");
+ if (resolverSession == null) throw new IllegalArgumentException("Null \"resolverSession\" parameter");
+
+ this.resolverSession = resolverSession;
+
+ // Fix the magical column names for RDF statements
+ setVariables(new Variable[] { SUBJECT, PREDICATE, OBJECT } );
+
+ try {
+ InputStreamReader input = new InputStreamReader(content.newInputStream());
+ try {
+ rlogParser = new Rlog(input);
+ } finally {
+ input.close();
+ }
+ } catch (IOException e) {
+ outstandingException = new TuplesException("Unable to access RLog data", e);
+ } catch (ParseException e) {
+ outstandingException = new TuplesException("Bad RLog structure", e);
+ } catch (TypeException e) {
+ outstandingException = new TuplesException("Head of rule has the wrong type", e);
+ } catch (URIParseException e) {
+ outstandingException = new TuplesException("Illegal URI in document", e);
+ } catch (NotModifiedException e) {
+ outstandingException = new TuplesException("Unexpected duplicate access to RLog file", e);
+ }
+ }
+
+
+ public long getSubject() throws TuplesException {
+ return getColumnValue(0);
+ }
+
+ public long getPredicate() throws TuplesException {
+ return getColumnValue(1);
+ }
+
+ public long getObject() throws TuplesException {
+ return getColumnValue(2);
+ }
+
+
+ /**
+ * {@inheritDoc}
+ *
+ * Non-zero length <var>prefix</var> values don't need to be supported by
+ * this class because prefix filtration is implemented by the
+ * {@link StatementsWrapperResolution} which the existing external resolvers
+ * always apply to their content before returning it.
+ *
+ * @param prefix {@inheritDoc}; for this particular implementation, non-zero
+ * length prefixes are not supported
+ * @throws NotModifiedTuplesException if the underlying tuples are cached
+ * @throws TuplesException {@inheritDoc}; also if <var>prefix</var> is non-zero length
+ */
+ public void beforeFirst(long[] prefix, int suffixTruncation) throws TuplesException {
+ if (logger.isDebugEnabled()) logger.debug("Before first");
+
+ // If the parser found an error, then throw it now
+ if (outstandingException != null) throw outstandingException;
+
+ // Validate "prefix" parameter
+ if (prefix == null) throw new IllegalArgumentException("Null \"prefix\" parameter");
+ if (prefix.length != 0) {
+ throw new TuplesException(getClass() + ".beforeFirst isn't implemented for non-zero length prefix");
+ }
+
+ // Validate "suffixTruncation" parameter
+ if (suffixTruncation != 0) throw new IllegalArgumentException("Null \"suffixTruncation\" parameter");
+
+ tripleIterator = getTriples().iterator();
+ }
+
+
+ /**
+ * The cursor position isn't cloned by this method.
+ */
+ public Object clone() {
+ RlogStatements cloned = (RlogStatements)super.clone();
+ cloned.triple = null;
+ return cloned;
+ }
+
+
+ /**
+ * Parsing is not streamed, so the data stream is already closed.
+ */
+ public void close() throws TuplesException {
+ // no op
+ }
+
+
+ /**
+ * Get the localized value for the column.
+ * @param column 0 for the subject, 1 for the predicate, 2 for the object
+ * @return the localized GNode for the column
+ */
+ public long getColumnValue(int column) throws TuplesException {
+ if (triple == null) throw new TuplesException("There is no current row");
+ if (column >= 3) throw new IllegalArgumentException("Index out of bounds for triple: " + column);
+ return triple[column];
+ }
+
+
+ /**
+ * Get the operands this Tuples represents. Since this object is atomic, there are not operands.
+ * @see org.mulgara.store.tuples.Tuples#getOperands()
+ */
+ public List<Tuples> getOperands() {
+ return Collections.emptyList();
+ }
+
+
+ /**
+ * @see org.mulgara.store.tuples.AbstractTuples#getRowCardinality()
+ */
+ public int getRowCardinality() throws TuplesException {
+ long statementCount = getTriples().size();
+
+ // Convert the statement count into a cardinality class
+ return statementCount == 0 ? Cursor.ZERO :
+ statementCount == 1 ? Cursor.ONE :
+ Cursor.MANY;
+ }
+
+
+ /**
+ * @see org.mulgara.store.tuples.AbstractTuples#getRowCount()
+ */
+ public long getRowCount() throws TuplesException {
+ return getTriples().size();
+ }
+
+ /**
+ * @see org.mulgara.store.tuples.AbstractTuples#getRowUpperBound()
+ */
+ public long getRowUpperBound() throws TuplesException {
+ return getTriples().size();
+ }
+
+ /**
+ * @see org.mulgara.store.tuples.Tuples#hasNoDuplicates()
+ */
+ public boolean hasNoDuplicates() throws TuplesException {
+ return false;
+ }
+
+ /**
+ * @see org.mulgara.store.tuples.AbstractTuples#isColumnEverUnbound(int)
+ */
+ public boolean isColumnEverUnbound(int column) throws TuplesException {
+ if (column > 2 || column < 0) throw new TuplesException("No such column " + column);
+ return false;
+ }
+
+
+ /**
+ * @see org.mulgara.store.tuples.AbstractTuples#next()
+ */
+ public boolean next() throws TuplesException {
+ if (!tripleIterator.hasNext()) {
+ tripleIterator = null;
+ triple = null;
+ return false;
+ }
+ triple = tripleIterator.next();
+ return true;
+ }
+
+
+ /**
+ * Retrieve the triples from the parser.
+ * @return A List of all the triples.
+ * @throws TuplesException if there was a Node pool or string pool persistence or access error,
+ * or if the RLog file contained bad data that wasn't caught in the initial parse.
+ */
+ private List<long[]> getTriples() throws TuplesException {
+ try {
+ if (triples == null) {
+ KruleGenerator generator;
+ generator = new KruleGenerator(rlogParser, resolverSession);
+ triples = new ArrayList<long[]>();
+ generator.emit(triples);
+ }
+ } catch (NodePoolException e) {
+ throw new TuplesException("Unable to create new nodes during RLog parsing.", e);
+ } catch (LocalizeException e) {
+ throw new TuplesException("Unable to localize data during RLog parsing.", e);
+ } catch (ParseException e) {
+ throw new TuplesException("Errors in RLog file.", e);
+ }
+ return triples;
+ }
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/content/rlog/RlogStatementsUnitTest.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/content/rlog/RlogStatementsUnitTest.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/content/rlog/RlogStatementsUnitTest.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.content.rlog;
+
+// Third party packages
+import junit.framework.*; // JUnit unit testing framework
+import org.apache.log4j.Logger; // Apache Log4J
+
+
+/**
+ * @created Feb 24, 2009
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class RlogStatementsUnitTest extends TestCase {
+ /** Logger. */
+ @SuppressWarnings("unused")
+ private static final Logger logger = Logger.getLogger(RlogStatementsUnitTest.class.getName());
+
+ //
+ // Constructors
+ //
+
+ /**
+ * Construct a test.
+ *
+ * @param name the name of the test to construct
+ */
+ public RlogStatementsUnitTest(String name) {
+ super(name);
+ }
+
+ //
+ // Methods implementing TestCase
+ //
+
+ public void setup() {
+ }
+
+ /**
+ * Hook from which the test runner can obtain a test suite.
+ *
+ * @return the test suite
+ */
+ public static Test suite() {
+ return new TestSuite(RlogStatementsUnitTest.class);
+ }
+
+
+ /**
+ * Test {@link N3Statements} parsing the file <tt>test0014.rdf</tt>..
+ *
+ * @throws Exception if there's an error running the test (note that if the
+ * test merely fails, this should <em>not</em> throw any exception
+ */
+ public void test1() throws Exception {
+ }
+
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/content/rlog/package.html
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/content/rlog/package.html (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/content/rlog/package.html 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,13 @@
+<html>
+<head>
+<title>RLog Content Handler</title>
+</head>
+<body>
+<abstract>
+RLog content handler.
+</abstract>
+<p>
+This package is a service provider for parsing RLog documents. It uses the JavaCC parser, and generates triples usable by the Krule engine.
+</p>
+</body>
+</html>
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/Interpreter.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/Interpreter.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/Interpreter.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,63 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog;
+
+import java.util.List;
+import java.util.Collection;
+import java.util.Set;
+
+import org.mulgara.krule.rlog.ast.*;
+import org.mulgara.krule.rlog.parser.URIParseException;
+import org.mulgara.krule.rlog.rdf.URIReference;
+import org.mulgara.krule.rlog.rdf.Var;
+
+/**
+ * This interface is used to interpret a string into an AST. The AST is then transformed into a krule encoding in XML.
+ *
+ * @created Feb 22, 2009
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public interface Interpreter {
+
+
+ /**
+ * Find all the variables in every rule.
+ * @return A complete collection of all the variables that were parsed.
+ */
+ public Collection<Var> getVariables();
+
+ /**
+ * Gets all the URIs referenced in the rules.
+ * @return All URIs in order of appearance within axioms, then rules.
+ * @throws URIParseException The referenced URIs had bad syntax.
+ */
+ public Set<URIReference> getReferences() throws URIParseException;
+
+ /**
+ * Get all the axioms appearing in the rule set.
+ * @return A list of axioms.
+ */
+ public List<Axiom> getAxioms();
+
+ /**
+ * Get all the rules appearing in the rule set.
+ * @return A list of rules.
+ */
+ public List<Rule> getRules();
+
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/Rlog.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/Rlog.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/Rlog.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,185 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog;
+
+import java.io.*;
+import java.util.Collections;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Set;
+
+import org.mulgara.krule.rlog.ast.*;
+import org.mulgara.krule.rlog.ast.output.KruleWriter;
+import org.mulgara.krule.rlog.parser.TypeException;
+import org.mulgara.krule.rlog.parser.URIParseException;
+import org.mulgara.krule.rlog.rdf.MulgaraGraphs;
+import org.mulgara.krule.rlog.rdf.URIReference;
+import org.mulgara.krule.rlog.rdf.Var;
+
+/**
+ * This class is used to interpret a string into an AST. The AST is then transformed into a krule encoding in XML.
+ *
+ * @created Feb 22, 2009
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class Rlog implements Interpreter {
+
+ /** The label used on all generated rules. */
+ private static String ruleLabel = "rule";
+
+ /** All the parsed statements to be processed. */
+ private List<Statement> statements;
+
+ /** All the parsed Axioms. */
+ private List<Axiom> axioms;
+
+ /** All the parsed Rules. */
+ private List<Rule> rules;
+
+ /**
+ * Parse input data into an AST and process.
+ * @param args May contain a filename with the code to be parsed. All other parameters ignored.
+ * @throws IOException If there was an error reading from the specified file, or standard in.
+ * @throws beaver.Parser.Exception If there was a parsing exception.
+ */
+ public static void main(String[] args) throws IOException, ParseException {
+ // get the input
+ Reader intReader;
+ if (args.length > 0) {
+ File inFile = new File(args[0]);
+ if (!inFile.exists() || !inFile.canRead()) {
+ System.err.println("Unable to open file: " + inFile);
+ return;
+ }
+ // borrow the filename for labelling rules
+ intReader = new FileReader(inFile);
+ String filename = inFile.getName();
+ ruleLabel = filename.substring(0, filename.lastIndexOf('.'));
+ } else {
+ intReader = new InputStreamReader(System.in);
+ }
+ Reader input = new BufferedReader(intReader);
+
+ try {
+ // parse the input
+ Rlog rlog = new Rlog(input);
+ // emit to output
+ new KruleWriter(rlog).emit(System.out);
+ } catch (TypeException te) {
+ System.err.println(te.getMessage());
+ return;
+ } catch (URIParseException e) {
+ System.err.println(e.getMessage());
+ return;
+ }
+
+ }
+
+ /**
+ * Sets the label to use for each rule. The rule names are made up of this label
+ * plus an incremening number.
+ * @param label The text label to use on rules.
+ */
+ public static void setRuleLabel(String label) {
+ ruleLabel = label;
+ }
+
+ /**
+ * Create an rlog interpreter for building an AST from a stream Reader object.
+ * @param input The stream Reader.
+ * @throws IOException There was an IO Exception on the input.
+ * @throws beaver.Parser.Exception There was a parser exception in the input data.
+ * @throws URIParseException If the rules contain illegal URIs.
+ */
+ public Rlog(Reader input) throws IOException, ParseException, TypeException, URIParseException {
+ // parse the rlog into statements
+ RlogParser parser = new RlogParser(input);
+
+ statements = parser.statements();
+
+ // separate out the rules from the axioms
+ int ruleCount = 0;
+ rules = new ArrayList<Rule>();
+ axioms = new ArrayList<Axiom>();
+ for (Statement s: statements) {
+ if (s instanceof Axiom) axioms.add((Axiom)s);
+ else if (s instanceof Rule) {
+ rules.add((Rule)s);
+ ((Rule)s).setName(ruleLabel + ++ruleCount);
+ } else throw new IllegalStateException("Unknown statement type found: " + s.getClass().getName());
+ }
+
+ // calculate dependencies between the rules
+ calculateRuleDependencies();
+ }
+
+ /**
+ * Find all the variables in every rule.
+ * @return A complete collection of all the variables that were parsed.
+ */
+ public Collection<Var> getVariables() {
+ LinkedHashSet<Var> vars = new LinkedHashSet<Var>();
+ for (Rule r: rules) vars.addAll(r.getVariables());
+ return vars;
+ }
+
+ /**
+ * Gets all the URIs referenced in the rules.
+ * @return All URIs in order of appearance within axioms, then rules.
+ * @throws URIParseException The referenced URIs had bad syntax.
+ */
+ public Set<URIReference> getReferences() throws URIParseException {
+ Set<URIReference> refs = new LinkedHashSet<URIReference>();
+ for (Axiom a: axioms) refs.addAll(a.getReferences());
+ for (Rule r: rules) refs.addAll(r.getReferences());
+ refs.addAll(MulgaraGraphs.getSpecialUriRefs());
+ return refs;
+ }
+
+ /**
+ * Get all the axioms appearing in the rule set.
+ * @return A list of axioms.
+ */
+ public List<Axiom> getAxioms() {
+ return Collections.unmodifiableList(axioms);
+ }
+
+ /**
+ * Get all the rules appearing in the rule set.
+ * @return A list of rules.
+ */
+ public List<Rule> getRules() {
+ return Collections.unmodifiableList(rules);
+ }
+
+ /**
+ * Determine which rules are dependent on the result of which other rules,
+ * and set the rule objects accordingly.
+ * @throws URIParseException If the rules contain illegal URIs.
+ */
+ private void calculateRuleDependencies() throws TypeException, URIParseException {
+ for (Rule trigger: rules) {
+ for (Rule potentialTarget: rules) {
+ if (potentialTarget.triggeredBy(trigger)) potentialTarget.addTrigger(trigger);
+ }
+ }
+ }
+
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/Axiom.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/Axiom.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/Axiom.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,105 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast;
+
+import java.util.Set;
+
+import org.mulgara.krule.rlog.parser.URIParseException;
+import org.mulgara.krule.rlog.rdf.RDFNode;
+import org.mulgara.krule.rlog.rdf.URIReference;
+
+/**
+ * Represents an axiom statement.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class Axiom extends Statement {
+
+ /** The predicate defined by this axiom */
+ public final Predicate predicate;
+
+ /**
+ * Takes a predicate for a statement and checks that there are not variables in it.
+ * @param p A Predicate containing no variables.
+ */
+ public Axiom(Predicate p) {
+ predicate = p;
+ if (predicate.containsVariables()) throw new IllegalArgumentException("Axioms may not contain variables.");
+ predicate.setParent(this);
+ }
+
+ /** {@inheritDoc} */
+ public void accept(TreeWalker walker) {
+ walker.visit(this);
+ }
+
+ /** {@inheritDoc} */
+ public void print(int indent) {
+ System.out.println(sp(indent) + "Axiom {");
+ predicate.print(indent + 1);
+ System.out.println(sp(indent) + "}");
+ }
+
+ /** {@inheritDoc} */
+ public boolean equals(Object o) {
+ return (o instanceof Axiom) && predicate.equals(((Axiom)o).predicate);
+ }
+
+ /** {@inheritDoc} */
+ public int hashCode() {
+ return 7 * predicate.hashCode();
+ }
+
+ /**
+ * Gets the references refered to by this axiom.
+ * @return An ordered set of URI references.
+ * @throws URIParseException The referenced URIs had poor syntax.
+ */
+ public Set<URIReference> getReferences() throws URIParseException {
+ return predicate.getReferences();
+ }
+
+ /**
+ * Get the subject of this axiom.
+ * @return The URIReference subject.
+ * @throws URIParseException The node is a malformed URIReference
+ */
+ public RDFNode getSubject() throws URIParseException {
+ return predicate.getSubject();
+ }
+
+ /**
+ * Get the predicate of this axiom.
+ * @return The URIReference predicate.
+ * @throws URIParseException The node is a malformed URIReference
+ */
+ public RDFNode getPredicate() throws URIParseException {
+ return predicate.getPredicate();
+ }
+
+ /**
+ * Get the object of this axiom.
+ * @return Either a URIReference, or a literal
+ * @throws URIParseException The node is a malformed URIReference
+ */
+ public RDFNode getObject() throws URIParseException {
+ return predicate.getObject();
+ }
+}
+
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/BPredicate.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/BPredicate.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/BPredicate.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,133 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast;
+
+import java.util.HashSet;
+import java.util.Collection;
+
+import org.mulgara.krule.rlog.parser.URIParseException;
+import org.mulgara.krule.rlog.rdf.MulgaraGraphs;
+import org.mulgara.krule.rlog.rdf.URIReference;
+import org.mulgara.krule.rlog.rdf.Var;
+
+/**
+ * Represents a binary predicate in the AST.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class BPredicate extends Predicate {
+
+ /** The predicate label. */
+ public final BPredicateLabel label;
+
+ /** The first parameter of the predicate. */
+ public final PredicateParam left;
+
+ /** The second parameter of the predicate. */
+ public final PredicateParam right;
+
+ /**
+ * Creates a binary predicate, connecting two resources.
+ * @param label The predicate name.
+ * @param left The first parameter of the predicate.
+ * @param right The second parameter of the predicate.
+ */
+ public BPredicate(BPredicateLabel label, PredicateParam left, PredicateParam right) {
+ this.label = label;
+ this.left = left;
+ this.right = right;
+ // get the referenced nodes, delaying any exceptions until later.
+ try {
+ subject = this.left.getRDFNode();
+ } catch (URIParseException e) {
+ delayedSubjectException = e;
+ }
+ try {
+ predicate = this.label.getRDFNode();
+ } catch (URIParseException e) {
+ delayedPredicateException = e;
+ }
+ try {
+ object = this.right.getRDFNode();
+ } catch (URIParseException e) {
+ delayedObjectException = e;
+ }
+ annotateGraph();
+ }
+
+ // inheritdoc
+ public void accept(TreeWalker walker) {
+ walker.visit(this);
+ }
+
+ // inheritdoc
+ public boolean containsVariables() {
+ return label instanceof Variable || left instanceof Variable || right instanceof Variable;
+ }
+
+ // inheritdoc
+ public Collection<Var> getVariables() {
+ Collection<Var> vars = new HashSet<Var>();
+ if (label instanceof Variable) vars.add(toVar(label));
+ if (left instanceof Variable) vars.add(toVar(left));
+ if (right instanceof Variable) vars.add(toVar(right));
+ return vars;
+ }
+
+ // inheritdoc
+ public void print(int indent) {
+ System.out.println(sp(indent) + "BPredicate {");
+ System.out.println(sp(indent + 1) + "label:");
+ label.print(indent + 2);
+ System.out.println(sp(indent + 1) + "left:");
+ left.print(indent + 2);
+ System.out.println(sp(indent + 1) + "right:");
+ right.print(indent + 2);
+ System.out.println(sp(indent) + "}");
+ }
+
+ //inheritdoc
+ public String toString() {
+ return "BPredicate: " + label + "(" + left + "," + right + ")";
+ }
+
+ //inheritdoc
+ public boolean equals(Object o) {
+ if (o instanceof BPredicate) {
+ BPredicate p = (BPredicate)o;
+ return label.equals(p.label) && left.equals(p.left) && right.equals(p.right);
+ } else return false;
+ }
+
+ // inheritdoc
+ public int hashCode() {
+ return label.hashCode() * 961 + left.hashCode() * 31 + right.hashCode();
+ }
+
+ /**
+ * Search for the predicate/object in the special graphs, and annotate this predicate
+ * to any detected graphs.
+ */
+ private void annotateGraph() {
+ if (predicate != null && predicate.isReference()) {
+ graphAnnotation = MulgaraGraphs.getPredicateGraph(((URIReference)predicate).getURI());
+ }
+ }
+}
+
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/BPredicateLabel.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/BPredicateLabel.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/BPredicateLabel.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast;
+
+import org.mulgara.krule.rlog.parser.URIParseException;
+import org.mulgara.krule.rlog.rdf.RDFNode;
+
+/**
+ * Represents binary predicate labels.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public interface BPredicateLabel {
+ public void accept(TreeWalker walker);
+ public void print(int indent);
+ public RDFNode getRDFNode() throws URIParseException;
+}
+
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/BPredicateLiteral.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/BPredicateLiteral.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/BPredicateLiteral.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast;
+
+/**
+ * Represents a value (not a variable) at any place in a predicate.
+ * Basic String and integer literals have a separate type.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class BPredicateLiteral extends PredicateLiteral implements BPredicateLabel, PredicateParam {
+
+ /**
+ * Creates a new literal, including a domain, for use in a binary predicate.
+ * @param domain The domain for the name (eg. rdfs or owl).
+ * @param name The name of the literal.
+ */
+ public BPredicateLiteral(String domain, String name) {
+ super(domain, name);
+ }
+
+ /** {@inheritDoc} */
+ public void accept(TreeWalker walker) {
+ walker.visit(this);
+ }
+
+ /** {@inheritDoc} */
+ public void print(int indent) {
+ System.out.println(sp(indent) + "BPredicateLiteral ('" + name + "')");
+ }
+
+ /** {@inheritDoc} */
+ public boolean equals(Object o) {
+ return o instanceof BPredicateLiteral && name.equals(((BPredicateLiteral)o).name);
+ }
+
+ /** {@inheritDoc} */
+ public int hashCode() {
+ return name.hashCode() * 13; // 13 for this type
+ }
+
+}
+
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/IntegerLiteral.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/IntegerLiteral.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/IntegerLiteral.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,76 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast;
+
+import org.mulgara.krule.rlog.rdf.Literal;
+import org.mulgara.krule.rlog.rdf.RDF;
+import org.mulgara.krule.rlog.rdf.RDFNode;
+
+/**
+ * A number in the AST.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class IntegerLiteral extends Node implements PredicateParam {
+
+ /** The value of the number. */
+ public final Long value;
+
+ /**
+ * A new numeric literal.
+ * @param value The value of the number.
+ */
+ public IntegerLiteral(String s) {
+ this.value = Long.valueOf(s);
+ }
+
+ /**
+ * A new numeric literal.
+ * @param value The value of the number.
+ */
+ public IntegerLiteral(Long value) {
+ this.value = value;
+ }
+
+ // inheritdoc
+ public void accept(TreeWalker walker) {
+ walker.visit(this);
+ }
+
+ // inheritdoc
+ public void print(int indent) {
+ System.out.println(sp(indent) + "IntegerLiteral (" + value + ")");
+ }
+
+ //inheritdoc
+ public boolean equals(Object o) {
+ return o instanceof IntegerLiteral && value.equals(((IntegerLiteral)o).value);
+ }
+
+ // inheritdoc
+ public int hashCode() {
+ return value.hashCode();
+ }
+
+ /** {@inheritDoc} */
+ public RDFNode getRDFNode() {
+ return new Literal(value.toString(), RDF.XSD_LONG);
+ }
+}
+
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/InvertedPredicate.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/InvertedPredicate.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/InvertedPredicate.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,90 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast;
+
+import java.util.Collection;
+
+import org.mulgara.krule.rlog.parser.URIParseException;
+import org.mulgara.krule.rlog.rdf.RDFNode;
+import org.mulgara.krule.rlog.rdf.Var;
+
+/**
+ * Represents the inversion of a standard predicate.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class InvertedPredicate extends Predicate {
+
+ public final Predicate invertPredicate;
+
+ public InvertedPredicate(Predicate typeStatement) {
+ super();
+ this.invertPredicate = typeStatement;
+ }
+
+ public void accept(TreeWalker walker) {
+ walker.visit(this);
+ }
+
+ public void print(int indent) {
+ System.out.println(sp(indent) + "InvertedType {");
+ invertPredicate.print(indent + 1);
+ System.out.println(sp(indent) + "}");
+ }
+
+ /**
+ * @return the wrapped Predicate
+ */
+ public Predicate getInvertPredicate() {
+ return invertPredicate;
+ }
+
+ @Override
+ public Collection<Var> getVariables() {
+ return invertPredicate.getVariables();
+ }
+
+ /**
+ * Get the subject of this predicate.
+ * @return Either a URIReference, or a variable
+ * @throws URIParseException The node is a malformed URIReference
+ */
+ public RDFNode getSubject() throws URIParseException {
+ return invertPredicate.getSubject();
+ }
+
+ /**
+ * Get the predicate value of this predicate.
+ * @return Either a URIReference, or a variable
+ */
+ public RDFNode getPredicate() throws URIParseException {
+ return invertPredicate.getPredicate();
+ }
+
+ /**
+ * Get the object of this predicate.
+ * @return Either a URIReference, a variable, or a literal
+ * @throws URIParseException The node is a malformed URIReference
+ */
+ public RDFNode getObject() throws URIParseException {
+ return invertPredicate.getObject();
+ }
+
+}
+
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/Node.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/Node.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/Node.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast;
+
+/**
+ * Base class for all nodes in the AST.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public abstract class Node {
+ /**
+ * Double binding return point for use with the visitor pattern.
+ * @param walker The Visitor object.
+ */
+ public abstract void accept(TreeWalker walker);
+
+ /**
+ * Print the details of this statement, over several lines. Some formatting through indenting, with a starting
+ * indent provided by the indent parameter.
+ * @param indent The number of spaces to indent the output.
+ */
+ public abstract void print(int indent);
+
+ /**
+ * Creates a string with the required number of spaces for indenting.
+ * @param nr The number of indent positions.
+ * @return a String continaing nr*2 spaces.
+ */
+ String sp(int nr) {
+ StringBuffer sb = new StringBuffer();
+ for (int n = 0; n < nr; n++) sb.append(" ");
+ return sb.toString();
+ }
+}
+
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/NullPredicate.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/NullPredicate.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/NullPredicate.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,94 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Set;
+
+import org.mulgara.krule.rlog.rdf.RDFNode;
+import org.mulgara.krule.rlog.rdf.URIReference;
+import org.mulgara.krule.rlog.rdf.Var;
+
+/**
+ * This class represents a predicate place holder that is not occupied.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class NullPredicate extends Predicate {
+
+ public static final NullPredicate NULL = new NullPredicate();
+
+ /**
+ * Creates a null predicate.
+ */
+ private NullPredicate() {
+ super();
+ }
+
+ /** {@inheritDoc} */
+ public void accept(TreeWalker walker) { }
+
+ /** {@inheritDoc} */
+ public boolean containsVariables() {
+ return false;
+ }
+
+ /** {@inheritDoc} */
+ @SuppressWarnings("unchecked")
+ public Collection<Var> getVariables() {
+ return (Collection<Var>)Collections.EMPTY_SET;
+ }
+
+ /** {@inheritDoc} */
+ @SuppressWarnings("unchecked")
+ public Set<URIReference> getReferences() {
+ return (Set<URIReference>)Collections.EMPTY_SET;
+ }
+
+ /**
+ * {@inheritDoc}
+ * Presumed to always match.
+ */
+ public boolean matches(RDFNode s, RDFNode p, RDFNode o) {
+ return true;
+ }
+
+ /** {@inheritDoc} */
+ public void print(int indent) {
+ System.out.println(sp(indent) + "<null>");
+ }
+
+ /** Get the subject of this predicate. */
+ public RDFNode getSubject() {
+ throw new UnsupportedOperationException();
+ }
+
+ /** Get the subject of this predicate. */
+ public RDFNode getPredicate() {
+ throw new UnsupportedOperationException();
+ }
+
+ /** Get the subject of this predicate. */
+ public RDFNode getObject() {
+ throw new UnsupportedOperationException();
+ }
+
+}
+
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/Predicate.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/Predicate.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/Predicate.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,176 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast;
+
+import java.util.Collection;
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+import org.mulgara.krule.rlog.parser.URIParseException;
+import org.mulgara.krule.rlog.rdf.RDFNode;
+import org.mulgara.krule.rlog.rdf.URIReference;
+import org.mulgara.krule.rlog.rdf.Var;
+
+/**
+ * A predicate in a statement appearing in the AST.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public abstract class Predicate extends Node {
+
+ /** The parent node in the AST. Always a statement. */
+ private Statement parent;
+
+ /** The predicate value of this predicate. */
+ protected RDFNode predicate = null;
+
+ /** The subject of this predicate. */
+ protected RDFNode subject = null;
+
+ /** The object of this predicate. */
+ protected RDFNode object = null;
+
+ /** The graph of this predicate. */
+ protected URIReference graphAnnotation = null;
+
+ /** The exception generated when trying to parse the predicate. Hopwefully null. */
+ protected URIParseException delayedPredicateException = null;
+
+ /** The exception generated when trying to parse the predicate. Hopwefully null. */
+ protected URIParseException delayedSubjectException = null;
+
+ /** The exception generated when trying to parse the predicate. Hopwefully null. */
+ protected URIParseException delayedObjectException = null;
+
+ /**
+ * Sets the parent AST node.
+ * @param parent The statement which contains this predicate.
+ */
+ public void setParent(Statement parent) { this.parent = parent; }
+
+ /**
+ * Gets the parent AST node. Always returns a statement.
+ * @return The Statement containing this node.
+ */
+ public Statement getParent() { return parent; }
+
+ /**
+ * Check if any variables are referenced by this predicate. More efficient implementation
+ * of !getVariables().isEmpty()
+ * @return <code>true</code> if there are any variables in this predicate.
+ */
+ public boolean containsVariables() { return !getVariables().isEmpty(); }
+
+ /**
+ * Get all variables referred to in this predicate.
+ * @return a collection with all the variable, or zero veriables if none are referenced.
+ */
+ public abstract Collection<Var> getVariables();
+
+ /**
+ * Get the subject of this predicate.
+ * @return Either a URIReference, or a variable
+ */
+ public RDFNode getSubject() throws URIParseException {
+ if (subject != null) return subject;
+ throw delayedSubjectException;
+ }
+
+ /**
+ * Get the predicate of this predicate.
+ * @return Either a URIReference, or a variable
+ */
+ public RDFNode getPredicate() throws URIParseException {
+ if (predicate != null) return predicate;
+ throw delayedPredicateException;
+ }
+
+ /**
+ * Get the object of this predicate.
+ * @return Either a URIReference, a variable, or a literal
+ */
+ public RDFNode getObject() throws URIParseException {
+ if (object != null) return object;
+ throw delayedObjectException;
+ }
+
+ /**
+ * Indicates that this predicate has an annotation on how it gets resolved.
+ * @return <code>true</code> if a resolution annotation exists.
+ */
+ public boolean hasGraphAnnotation() {
+ return graphAnnotation != null;
+ }
+
+ /**
+ * Retrieves the graph annotation for this predicate.
+ * @return The graph for resolving this predicate.
+ */
+ public URIReference getGraphAnnotation() throws URIParseException {
+ return graphAnnotation;
+ }
+
+ /**
+ * Gets the elements from this relationship that are references.
+ * @return An ordered set containing the references.
+ * @throws URIParseException The references had invalid syntax.
+ */
+ public Set<URIReference> getReferences() throws URIParseException {
+ Set<URIReference> refs = new LinkedHashSet<URIReference>();
+ RDFNode n = getSubject();
+ if (n.isReference()) refs.add((URIReference)n);
+ n = getPredicate();
+ if (n.isReference()) refs.add((URIReference)n);
+ n = getObject();
+ if (n.isReference()) refs.add((URIReference)n);
+ return refs;
+ }
+
+ /**
+ * Tests if this predicate possibly matches a pattern of subject/predicate/object
+ * @param s The subject from the pattern to test for match.
+ * @param p The predicate from the pattern to test for match.
+ * @param o The object from the pattern to test for match.
+ * @return <code>false</code> if this predicate cannote matches the subject/predicate/object,
+ * <code>true</code> otherwise.
+ */
+ public boolean matches(RDFNode s, RDFNode p, RDFNode o) throws URIParseException {
+ RDFNode localS = getSubject();
+ RDFNode localP = getPredicate();
+ RDFNode localO = getObject();
+ // can only fail if both are not variable and not equal
+ if (!s.isVariable() && !localS.isVariable() && !localS.equals(s)) return false;
+ if (!p.isVariable() && !localP.isVariable() && !localP.equals(p)) return false;
+ if (!o.isVariable() && !localO.isVariable() && !localO.equals(o)) return false;
+ // this rule has the potential to match the pattern
+ return true;
+ }
+
+ /**
+ * Converts a Variable to a Var. Accepts multiple types.
+ * @param v The Variable to convert. This must be a Variable.
+ * @return a new Var that is equivalent to the v.
+ * @throws ClassCastException If something other than a Variable is passed in.
+ */
+ protected Var toVar(Object v) {
+ return new Var(((Variable)v).name);
+ }
+
+}
+
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/PredicateLiteral.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/PredicateLiteral.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/PredicateLiteral.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,80 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast;
+
+import java.net.URISyntaxException;
+
+import org.mulgara.krule.rlog.parser.NSUtils;
+import org.mulgara.krule.rlog.parser.URIParseException;
+import org.mulgara.krule.rlog.rdf.RDFNode;
+import org.mulgara.krule.rlog.rdf.URIReference;
+
+/**
+ * Represents a value (not a variable) at any place in a predicate.
+ * Basic String and integer literals have a separate type.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public abstract class PredicateLiteral extends Node implements BPredicateLabel, PredicateParam {
+
+ /** The text found in this literal. */
+ public final String name;
+
+ /** The reference of this node. If null then the URI syntax is invalid. */
+ public final URIReference ref;
+
+ /**
+ * Creates a new literal, including a domain, for use in a binary predicate.
+ * @param domain The domain for the name (eg. rdfs or owl).
+ * @param name The name of the literal.
+ */
+ public PredicateLiteral(String domain, String name) {
+ // use some indirect references to let the compiler know we are really setting the final values
+ // storing null in ref means that the URI syntax is invalid
+ URIReference r = null;
+ String n = null;
+ try {
+ if (domain == null) {
+ n = NSUtils.newName(name);
+ r = new URIReference(name);
+ } else {
+ n = NSUtils.newName(domain, name);
+ r = new URIReference(domain, name);
+ }
+ } catch (URISyntaxException e) { /* r == null */ }
+ this.name = n;
+ this.ref = r;
+ }
+
+ /** {@inheritDoc} */
+ public abstract void accept(TreeWalker walker);
+
+ /** {@inheritDoc} */
+ public abstract void print(int indent);
+
+ /**
+ * {@inheritDoc}
+ * @throws URISyntaxException If the label is not a valid URI.
+ */
+ public RDFNode getRDFNode() throws URIParseException {
+ if (ref == null) throw new URIParseException(name);
+ return ref;
+ }
+}
+
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/PredicateParam.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/PredicateParam.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/PredicateParam.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2008 The Topaz PRoject
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast;
+
+import org.mulgara.krule.rlog.parser.URIParseException;
+import org.mulgara.krule.rlog.rdf.RDFNode;
+
+/**
+ * A parameter for a predicate.
+ *
+ * @created 2007
+ * @author Paul Gearon
+ * @copyright © 2007 <a href="mailto:pgearon at users.sourceforge.net">Topaz Project</a>
+ * @licence <a href="http://www.opensource.org/licenses/apache2.0.php">Apache License, Version 2.0</a>
+ */
+public interface PredicateParam {
+ public void accept(TreeWalker walker);
+ public void print(int indent);
+ public RDFNode getRDFNode() throws URIParseException;
+}
+
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/PrintWalker.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/PrintWalker.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/PrintWalker.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,79 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast;
+
+/**
+ * Visitor pattern class for traversing the AST and printing what it finds.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class PrintWalker implements TreeWalker {
+ // Axiom BPredicateLiteral Rule TypeLiteral Variable StringLiteral IntegerLiteral
+
+ public void visit(Axiom node) {
+ System.out.println("Local treewalker: Axiom");
+ node.predicate.accept(this);
+ }
+
+ public void visit(Rule node) {
+ System.out.println("Local treewalker: Rule");
+ node.head.accept(this);
+ for (Predicate p: node.body) p.accept(this);
+ }
+
+ public void visit(TypeStatement node) {
+ System.out.println("Local treewalker: TypeStatement");
+ node.typeLabel.accept(this);
+ node.param.accept(this);
+ }
+
+ public void visit(InvertedPredicate node) {
+ System.out.println("Local treewalker: InvertedPredicate");
+ node.invertPredicate.accept(this);
+ }
+
+ public void visit(BPredicate node) {
+ System.out.println("Local treewalker: BPredicate");
+ node.label.accept(this);
+ node.left.accept(this);
+ node.right.accept(this);
+ }
+
+ public void visit(BPredicateLiteral node) {
+ // leaf
+ }
+
+ public void visit(TypeLiteral node) {
+ // leaf
+ }
+
+ public void visit(Variable node) {
+ // leaf
+ }
+
+ public void visit(StringLiteral node) {
+ // leaf
+ }
+
+ public void visit(IntegerLiteral node) {
+ // leaf
+ }
+
+}
+
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/Rule.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/Rule.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/Rule.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,248 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+
+import org.mulgara.krule.rlog.parser.TypeException;
+import org.mulgara.krule.rlog.parser.URIParseException;
+import org.mulgara.krule.rlog.rdf.RDFNode;
+import org.mulgara.krule.rlog.rdf.URIReference;
+import org.mulgara.krule.rlog.rdf.Var;
+
+/**
+ * Represents a rule statement.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class Rule extends Statement {
+
+ /** The predicate found in the head of the rule. */
+ public final Predicate head;
+
+ /** The list of predicates found in the body of the rule. */
+ public final List<Predicate> body;
+
+ /** The list of predicates to be subtracted from the body of the rule. */
+ public final List<Predicate> bodySubtractions;
+
+ /** The collection of rules that this rule can trigger for execution. */
+ public final Collection<Rule> triggers;
+
+ /** The name of this rule. Used in RDF. */
+ private String name;
+
+ public Rule(List<Predicate> body) {
+ this(NullPredicate.NULL, body);
+ }
+
+ /**
+ * This constructor takes a head and body for a statement. It normalizes the structure,
+ * and checks for soundness.
+ * @param head A Predicate containing a subset of variables from the body.
+ * @param body A set of Predicates for the body.
+ */
+ public Rule(Predicate head, List<Predicate> body) {
+ this.head = head;
+ this.body = body;
+ this.bodySubtractions = new LinkedList<Predicate>();
+ this.head.setParent(this);
+ for (Predicate p: this.body) p.setParent(this);
+ // shuffle the inversions out of the body and into the body subtractions
+ normalizeBody(this.body, this.bodySubtractions);
+ triggers = new HashSet<Rule>();
+ try {
+ checkVariables();
+ } catch (IllegalArgumentException e) {
+ System.err.println("head = '" + head + "'");
+ System.err.println("body = '" + this.body + "'");
+ throw e;
+ }
+ }
+
+ /**
+ * Get all variables referred to by this rule.
+ * @return All variables from the body, since the variables in the head must be a subset.
+ */
+ public Collection<Var> getVariables() {
+ Collection<Var> vars = new HashSet<Var>();
+ for (Predicate p: body) vars.addAll(p.getVariables());
+ for (Predicate p: bodySubtractions) vars.addAll(p.getVariables());
+ return vars;
+ }
+
+ /**
+ * Adds a rule into the set of rules to be triggered by this rule.
+ * @param target The rule to be triggered.
+ */
+ public void addTrigger(Rule target) {
+ triggers.add(target);
+ }
+
+ /**
+ * Sets the name for this rule.
+ * @param name The new name for the rule.
+ */
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ /**
+ * @return The name of this rule.
+ */
+ public String getName() {
+ return name;
+ }
+
+ // inheritdoc
+ public void accept(TreeWalker walker) {
+ walker.visit(this);
+ }
+
+ // inheritdoc
+ public void print(int indent) {
+ System.out.println(sp(indent) + "Rule {");
+ System.out.println(sp(indent + 1) + "head:");
+ head.print(indent + 2);
+ System.out.println(sp(indent + 1) + "body [length=" + body.size() + "]:");
+ for (Predicate p: body) p.print(indent + 2);
+ if (!bodySubtractions.isEmpty()) {
+ System.out.print(sp(indent + 1) + "minus [length=" + bodySubtractions.size() + "]:");
+ for (Predicate p: bodySubtractions) p.print(indent + 2);
+ }
+ System.out.println(sp(indent) + "}");
+ }
+
+ /** {@inheritDoc} */
+ public boolean equals(Object o) {
+ if (!(o instanceof Rule)) return false;
+ Rule r = (Rule)o;
+ return head.equals(r.head) && body.equals(r.body);
+ }
+
+ /** {@inheritDoc} */
+ public int hashCode() {
+ return head.hashCode() * 31 + body.hashCode();
+ }
+
+ /**
+ * Tests if this rule is triggered by the given rule.
+ * @param trigger The potential triggering rule.
+ * @return <code>false</code> if this rule <em>cannot</em> be triggered by the trigger.
+ * @throws TypeException If the product of the rule is an illegal type.
+ * @throws URIParseException If the predicates in the rule result in illegal URIs.
+ */
+ public boolean triggeredBy(Rule trigger) throws TypeException, URIParseException {
+ Predicate triggerProduct = trigger.head;
+ if (triggerProduct instanceof InvertedPredicate) throw new TypeException("Unexpected inversion in a rule head.");
+ if (triggerProduct == NullPredicate.NULL) return false;
+ RDFNode subject = triggerProduct.getSubject();
+ RDFNode predicate = triggerProduct.getPredicate();
+ RDFNode object = triggerProduct.getObject();
+
+ for (Predicate p: body) if (p.matches(subject, predicate, object)) return true;
+ return false;
+ }
+
+ /**
+ * Get all the URI references used in this rule.
+ * @return All the references used in this rule.
+ */
+ public Set<URIReference> getReferences() throws URIParseException {
+ Set<URIReference> refs = new LinkedHashSet<URIReference>();
+ refs.addAll(head.getReferences());
+ for (Predicate p: body) refs.addAll(p.getReferences());
+ return refs;
+ }
+
+ /**
+ * @return the head
+ */
+ public Predicate getHead() {
+ return head;
+ }
+
+ /**
+ * @return the body
+ */
+ public List<Predicate> getBody() {
+ return Collections.unmodifiableList(body);
+ }
+
+ /**
+ * @return the bodySubtractions
+ */
+ public List<Predicate> getBodySubtractions() {
+ return Collections.unmodifiableList(bodySubtractions);
+ }
+
+ /**
+ * @return the triggers
+ */
+ public Collection<Rule> getTriggers() {
+ return triggers;
+ }
+
+ /**
+ * Checks that all variables in the head are found in the body, and that every subtracted predicate
+ * contains at least one variable that appears in the standard matching predicates.
+ * @throws IllegalArgumentException if there are any variables unaccounted for.
+ */
+ @SuppressWarnings("unchecked")
+ private void checkVariables() {
+ Collection<Var> headVars = head.getVariables();
+ HashSet<Var> bodyVars = new HashSet<Var>();
+ for (Predicate p: body) bodyVars.addAll(p.getVariables());
+ headVars.removeAll(bodyVars);
+ if (!headVars.isEmpty()) throw new IllegalArgumentException("Head of rule must contain variables from the body.");
+
+ for (Predicate p: bodySubtractions) {
+ HashSet<Var> vars = (HashSet<Var>)bodyVars.clone();
+ vars.retainAll(p.getVariables());
+ if (vars.isEmpty()) throw new IllegalArgumentException("Subtractions must match at least one variable in the original predicates.");
+ }
+ }
+
+ /**
+ * Remove all subtractions from the body, and place them in the bodySubtractions.
+ */
+ private void normalizeBody(List<Predicate> bdy, List<Predicate> subs) {
+ Iterator<Predicate> preds = bdy.iterator();
+ boolean changes = false;
+ while (preds.hasNext()) {
+ Predicate current = preds.next();
+ if (current instanceof InvertedPredicate) {
+ subs.add(((InvertedPredicate)current).getInvertPredicate());
+ preds.remove();
+ changes = true;
+ }
+ }
+ // normalize for any nested inversions
+ if (changes) normalizeBody(subs, bdy);
+ }
+
+}
+
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/Statement.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/Statement.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/Statement.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast;
+
+/**
+ * Marker class to represent top level nodes in the AST.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public abstract class Statement extends Node {
+}
+
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/StringLiteral.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/StringLiteral.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/StringLiteral.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast;
+
+import org.mulgara.krule.rlog.rdf.Literal;
+import org.mulgara.krule.rlog.rdf.RDFNode;
+
+/**
+ * A quoted string in the AST.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class StringLiteral extends Node implements PredicateParam {
+
+ /** The string value. */
+ public final String value;
+
+ /**
+ * A new string literal.
+ * @param value The contents of the quoted string.
+ */
+ public StringLiteral(String value) {
+ this.value = value;
+ }
+
+ // inheritdoc
+ public void accept(TreeWalker walker) {
+ walker.visit(this);
+ }
+
+ // inheritdoc
+ public void print(int indent) {
+ System.out.println(sp(indent) + "StringLiteral ('" + value + "')");
+ }
+
+ //inheritdoc
+ public boolean equals(Object o) {
+ return o instanceof StringLiteral && value.equals(((StringLiteral)o).value);
+ }
+
+ // inheritdoc
+ public int hashCode() {
+ return value.hashCode();
+ }
+
+ /** {@inheritDoc} */
+ public RDFNode getRDFNode() {
+ return new Literal(value.toString());
+ }
+}
+
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/TreeTransformer.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/TreeTransformer.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/TreeTransformer.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast;
+
+/**
+ * Visitor pattern class used to help convert a tree from a CST to an AST.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class TreeTransformer implements TreeWalker {
+ // Axiom BPredicateLiteral Rule TypeLiteral Variable StringLiteral IntegerLiteral
+
+ public void visit(Axiom node) {
+ System.out.println("Local treewalker: Axiom");
+ node.predicate.accept(this);
+ }
+
+ public void visit(Rule node) {
+ System.out.println("Local treewalker: Rule");
+ node.head.accept(this);
+ for (Predicate p: node.body) p.accept(this);
+ }
+
+ public void visit(TypeStatement node) {
+ System.out.println("Local treewalker: TypeStatement");
+ node.typeLabel.accept(this);
+ node.param.accept(this);
+ }
+
+ public void visit(InvertedPredicate node) {
+ System.out.println("Local treewalker: InvertedType");
+ node.invertPredicate.accept(this);
+ }
+
+ public void visit(BPredicate node) {
+ System.out.println("Local treewalker: BPredicate");
+ node.label.accept(this);
+ node.left.accept(this);
+ node.right.accept(this);
+ }
+
+ public void visit(BPredicateLiteral node) {
+ // leaf
+ }
+
+ public void visit(TypeLiteral node) {
+ // leaf
+ }
+
+ public void visit(Variable node) {
+ // leaf
+ }
+
+ public void visit(StringLiteral node) {
+ // leaf
+ }
+
+ public void visit(IntegerLiteral node) {
+ // leaf
+ }
+
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/TreeWalker.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/TreeWalker.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/TreeWalker.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast;
+
+/**
+ * Created by IntelliJ IDEA.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public interface TreeWalker {
+
+ void visit(Axiom node);
+
+ void visit(Rule node);
+
+ void visit(TypeStatement node);
+
+ void visit(InvertedPredicate node);
+
+ void visit(BPredicate node);
+
+ void visit(BPredicateLiteral node);
+
+ void visit(TypeLiteral node);
+
+ void visit(Variable node);
+
+ void visit(StringLiteral node);
+
+ void visit(IntegerLiteral node);
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/TypeLabel.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/TypeLabel.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/TypeLabel.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast;
+
+import org.mulgara.krule.rlog.parser.URIParseException;
+import org.mulgara.krule.rlog.rdf.RDFNode;
+
+/**
+ * Represents a label for a unary predicate.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public interface TypeLabel {
+ public void accept(TreeWalker walker);
+ public void print(int indent);
+ public RDFNode getRDFNode() throws URIParseException;
+}
+
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/TypeLiteral.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/TypeLiteral.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/TypeLiteral.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,58 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast;
+
+/**
+ * A literal for use in unary type predicates.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class TypeLiteral extends PredicateLiteral implements TypeLabel, PredicateParam {
+
+ /**
+ * Creates a new literal with a domain for a type predicate.
+ * @param domain The domain for the literal.
+ * @param name The text of the literal.
+ */
+ public TypeLiteral(String domain, String name) {
+ super(domain, name);
+ }
+
+ //inheritdoc
+ public void accept(TreeWalker walker) {
+ walker.visit(this);
+ }
+
+ //inheritdoc
+ public void print(int indent) {
+ System.out.println(sp(indent) + "TypeLiteral ('" + name + "')");
+ }
+
+ //inheritdoc
+ public boolean equals(Object o) {
+ return o instanceof TypeLiteral && name.equals(((TypeLiteral)o).name);
+ }
+
+ // inheritdoc
+ public int hashCode() {
+ return name.hashCode() * 17; // 17 for this type
+ }
+
+}
+
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/TypeStatement.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/TypeStatement.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/TypeStatement.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,124 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast;
+
+import java.util.Collection;
+import java.util.HashSet;
+
+import org.mulgara.krule.rlog.parser.URIParseException;
+import org.mulgara.krule.rlog.rdf.MulgaraGraphs;
+import org.mulgara.krule.rlog.rdf.RDF;
+import org.mulgara.krule.rlog.rdf.URIReference;
+import org.mulgara.krule.rlog.rdf.Var;
+
+/**
+ * This class represents a unary predicate in the AST. These are used as type specifiers
+ * for their parameter.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class TypeStatement extends Predicate {
+
+ /** The type of the object. */
+ public final TypeLabel typeLabel;
+
+ /** The object with the declared type/ */
+ public final PredicateParam param;
+
+ /**
+ * Creates a unary predicate indicating a type statement.
+ * @param typeLabel The declared type.
+ * @param param The object declared to be of the specified type.
+ */
+ public TypeStatement(TypeLabel typeLabel, PredicateParam param) {
+ super();
+ this.typeLabel = typeLabel;
+ this.param = param;
+ // get the referenced nodes, delaying any exceptions until later.
+ try {
+ subject = this.param.getRDFNode();
+ } catch (URIParseException e) {
+ delayedSubjectException = e;
+ }
+ predicate = RDF.TYPE;
+ try {
+ object = this.typeLabel.getRDFNode();
+ } catch (URIParseException e) {
+ delayedObjectException = e;
+ }
+ annotateGraph();
+ }
+
+ // inheritdoc
+ public void accept(TreeWalker walker) {
+ walker.visit(this);
+ }
+
+ // inheritdoc
+ public boolean containsVariables() {
+ return typeLabel instanceof Variable || param instanceof Variable;
+ }
+
+ // inheritdoc
+ public Collection<Var> getVariables() {
+ Collection<Var> vars = new HashSet<Var>();
+ if (typeLabel instanceof Variable) vars.add(toVar(typeLabel));
+ if (param instanceof Variable) vars.add(toVar(param));
+ return vars;
+ }
+
+ // inheritdoc
+ public void print(int indent) {
+ System.out.println(sp(indent) + "TypeStatement {");
+ System.out.println(sp(indent + 1) + "type:");
+ typeLabel.print(indent + 2);
+ System.out.println(sp(indent + 1) + "param:");
+ param.print(indent + 2);
+ System.out.println(sp(indent) + "}");
+ }
+
+ // inheritdoc
+ public String toString() {
+ return "TypeStatement: type(" + typeLabel + ") param(" + param + ")";
+ }
+
+ //inheritdoc
+ public boolean equals(Object o) {
+ if (o instanceof TypeStatement) {
+ TypeStatement ts = (TypeStatement)o;
+ return typeLabel.equals(ts.typeLabel) && param.equals(ts.param);
+ } else return false;
+ }
+
+ // inheritdoc
+ public int hashCode() {
+ return typeLabel.hashCode() * 37 + param.hashCode();
+ }
+
+ /**
+ * Search for the type in the special graphs, and annotate this predicate
+ * to any detected graphs.
+ */
+ private void annotateGraph() {
+ if (object != null && object.isReference()) {
+ graphAnnotation = MulgaraGraphs.getTypeGraph(((URIReference)object).getURI());
+ }
+ }
+}
+
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/Variable.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/Variable.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/Variable.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,66 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast;
+
+import org.mulgara.krule.rlog.rdf.RDFNode;
+import org.mulgara.krule.rlog.rdf.Var;
+
+/**
+ * Represents an RLog variable.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class Variable extends Node implements TypeLabel, BPredicateLabel, PredicateParam {
+
+ public final String name;
+
+ public Variable(String name) {
+ this.name = name;
+ }
+
+ public void accept(TreeWalker walker) {
+ walker.visit(this);
+ }
+
+ public void print(int indent) {
+ System.out.println(sp(indent) + "Variable (" + name + ")");
+ }
+
+ public String toString() {
+ return "var(" + name + ")";
+ }
+
+ /** {@inheritDoc} */
+ public RDFNode getRDFNode() {
+ return new Var(name);
+ }
+
+ /** {@inheritDoc} */
+ public boolean equals(Object o) {
+ if (!(o instanceof Variable)) return false;
+ return name.equals(((Variable)o).name);
+ }
+
+ /** {@inheritDoc} */
+ public int hashCode() {
+ return name.hashCode();
+ }
+
+}
+
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/AxiomGenerator.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/AxiomGenerator.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/AxiomGenerator.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,145 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast.output;
+
+import org.mulgara.krule.rlog.ParseException;
+import org.mulgara.krule.rlog.ast.Axiom;
+import org.mulgara.krule.rlog.parser.URIParseException;
+import org.mulgara.krule.rlog.rdf.Literal;
+import org.mulgara.krule.rlog.rdf.RDFNode;
+import org.mulgara.krule.rlog.rdf.URIReference;
+import org.mulgara.query.rdf.LiteralImpl;
+import org.mulgara.resolver.spi.LocalizeException;
+import org.mulgara.resolver.spi.ResolverSession;
+import org.mulgara.store.nodepool.NodePoolException;
+
+import java.net.URISyntaxException;
+import java.util.Collection;
+import java.util.List;
+
+import static org.mulgara.krule.KruleLoader.*;
+
+/**
+ * Writes variables to a list of triples.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class AxiomGenerator extends TripleGenerator {
+
+ /** The collection of axioms that this class emits. */
+ public Collection<Axiom> axioms;
+
+ /** The node for the krule:Axiom type */
+ private final long kruleAxiom;
+
+ /** The node for the krule:subject predicate */
+ private final long kruleSubject;
+
+ /** The node for the krule:predicate predicate */
+ private final long krulePredicate;
+
+ /** The node for the krule:object predicate */
+ private final long kruleObject;
+
+
+ /**
+ * Creates a new writer for a collection of variables.
+ * @param vars The variables to be written.
+ * @throws LocalizeException If localized nodes could not be accessed.
+ */
+ public AxiomGenerator(Collection<Axiom> axioms, ResolverSession resolverSession) throws LocalizeException {
+ super(resolverSession);
+ this.axioms = axioms;
+ kruleAxiom = resolverSession.localize(AXIOM);
+ kruleSubject = resolverSession.localize(AXIOM_SUBJECT);
+ krulePredicate = resolverSession.localize(AXIOM_PREDICATE);
+ kruleObject = resolverSession.localize(AXIOM_OBJECT);
+ }
+
+
+ /**
+ * {@inheritDoc}
+ * @throws URIParseException Constructing URIs for the output resulted in an invalid URI.
+ * @throws NodePoolException If blank nodes could not be created.
+ */
+ public List<long[]> emit(List<long[]> triples) throws ParseException, NodePoolException {
+ for (Axiom a: axioms) emitAxiom(triples, a);
+ return triples;
+ }
+
+
+ /**
+ * Create the the triple representation of an axiom and append it.
+ * @param triples the List to append the triples to
+ * @param a The axiom to emit.
+ * @throws NodePoolException If blank nodes could not be created.
+ * @throws ParseException If any bad URIs or non-object literals are encountered.
+ */
+ private List<long[]> emitAxiom(List<long[]> triples, Axiom a) throws NodePoolException, ParseException {
+ try {
+ long axiom = newBlankNode();
+
+ add(triples, axiom, rdfType, kruleAxiom);
+
+ addLocalTriples(triples, a.getSubject(), kruleSubject, axiom);
+ addLocalTriples(triples, a.getPredicate(), krulePredicate, axiom);
+ addLocalTriples(triples, a.getObject(), kruleObject, axiom);
+ } catch (LocalizeException e) {
+ throw new NodePoolException("Unable to localize data", e);
+ } catch (URISyntaxException e) {
+ throw new ParseException("Bad syntax in URI:" + e.getMessage());
+ } catch (URIParseException e) {
+ throw new ParseException("Bad syntax in URI:" + e.getMessage());
+ }
+
+ return triples;
+ }
+
+
+ protected void addLocalTriples(List<long[]> triples, RDFNode n, long pos, long axiom)
+ throws ParseException, NodePoolException, LocalizeException, URISyntaxException {
+ if (n.isReference()) {
+ long rl = toKruleNode(((URIReference)n).getRdfLabel());
+
+ // rl rdf:type URIReference
+ // axiom pos rl
+ add(triples, rl, rdfType, kruleUriReference);
+ add(triples, axiom, pos, rl);
+
+ } else if (n.isVariable()) {
+
+ long blank = newBlankNode();
+ add(triples, axiom, pos, blank);
+
+ } else {
+ Literal l = (Literal)n;
+ if (pos != kruleObject) throw new ParseException("Literal in unexpected position: " + l.getLexical());
+ long ll = resolverSession.localize(new LiteralImpl(l.getLexical()));
+ long blank = newBlankNode();
+
+ // axiom pos blank
+ // blank rdf:type krule:Literal
+ // blank rdf:value "....."
+ add(triples, axiom, pos, blank);
+ add(triples, blank, rdfType, getKruleLiteral());
+ add(triples, blank, getRdfValue(), ll);
+ }
+ }
+
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/AxiomWriter.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/AxiomWriter.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/AxiomWriter.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,74 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast.output;
+
+import org.mulgara.krule.rlog.ast.Axiom;
+import org.mulgara.krule.rlog.parser.URIParseException;
+
+import java.io.PrintStream;
+import java.util.Collection;
+
+/**
+ * Writes variables to an XML stream as a set of declarations.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class AxiomWriter extends XMLFragmentWriter {
+
+ /** The collection of axioms that this class emits. */
+ public Collection<Axiom> axioms;
+
+ /**
+ * Creates a new writer for a collection of variables.
+ * @param vars The variables to be written.
+ */
+ public AxiomWriter(Collection<Axiom> axioms) {
+ this.axioms = axioms;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @throws URIParseException Constructing URIs for the output resulted in an invalid URI.
+ */
+ public void emit(PrintStream out) throws URIParseException {
+ for (Axiom a: axioms) emitAxiom(out, a);
+ }
+
+ /**
+ * Write the the RDF/XML representation of an axiom to the print stream.
+ * @param out The print stream to send the axiom to.
+ * @param a The axiom to emit.
+ * @throws URIParseException If any references in the axiom are invalid URIs.
+ */
+ private void emitAxiom(PrintStream out, Axiom a) throws URIParseException {
+ StringBuilder sb = new StringBuilder(" <krule:Axiom>\n");
+ sb.append(" <subject>\n");
+ sb.append(" ").append(nodeString(a.getSubject())).append("\n");
+ sb.append(" </subject>\n");
+ sb.append(" <predicate>\n");
+ sb.append(" ").append(nodeString(a.getPredicate())).append("\n");
+ sb.append(" </predicate>\n");
+ sb.append(" <object>\n");
+ sb.append(" ").append(nodeString(a.getObject())).append("\n");
+ sb.append(" </object>\n");
+ sb.append(" </krule:Axiom>\n\n");
+ out.print(sb.toString());
+ }
+
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/KruleGenerator.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/KruleGenerator.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/KruleGenerator.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,74 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast.output;
+
+import java.util.List;
+
+import org.mulgara.krule.rlog.Interpreter;
+import org.mulgara.krule.rlog.ParseException;
+import org.mulgara.krule.rlog.parser.URIParseException;
+import org.mulgara.resolver.spi.LocalizeException;
+import org.mulgara.resolver.spi.ResolverSession;
+import org.mulgara.store.nodepool.NodePoolException;
+
+/**
+ * Converts a set of rules to triples.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class KruleGenerator {
+
+ /** The RLog interpreter that contains the data to be generated. */
+ private Interpreter interpreter;
+
+ /** The session for localizing data. */
+ private ResolverSession resolverSession;
+
+ /**
+ * Construct a generator for writing Krule triples files.
+ * @param interpreter The object that gets the data.
+ * @throws LocalizeException If the required graph nodes could not be found.
+ */
+ public KruleGenerator(Interpreter interpreter, ResolverSession resolverSession) throws LocalizeException {
+ this.interpreter = interpreter;
+ this.resolverSession = resolverSession;
+ }
+
+ // inheritdoc
+ public List<long[]> emit(List<long[]> triples) throws ParseException, NodePoolException {
+
+ // pull in all the elements, and give them to generators
+ TripleGenerator refWriter;
+ try {
+ refWriter = new ReferenceGenerator(interpreter.getReferences(), resolverSession);
+ TripleGenerator axiomWriter = new AxiomGenerator(interpreter.getAxioms(), resolverSession);
+ TripleGenerator ruleWriter = new RuleGenerator(interpreter.getRules(), resolverSession);
+
+ refWriter.emit(triples);
+ axiomWriter.emit(triples);
+ ruleWriter.emit(triples);
+ } catch (LocalizeException e) {
+ throw new NodePoolException("Unable to access local nodes", e);
+ } catch (URIParseException e) {
+ throw new ParseException("Invalid URI. " + e.getMessage());
+ }
+ return triples;
+ }
+
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/KruleWriter.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/KruleWriter.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/KruleWriter.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,61 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast.output;
+
+import java.io.PrintStream;
+
+import org.mulgara.krule.rlog.Interpreter;
+import org.mulgara.krule.rlog.parser.URIParseException;
+
+/**
+ * Writes a set of rules to an RDF/XML file in Krule format.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class KruleWriter extends RDFXMLWriter {
+
+ private Interpreter interpreter;
+
+ /**
+ * Construct a writer for writing Krule RDF/XML files.
+ * @param varWriter The object to write the variables.
+ * @param ruleWriter The object to write the rules.
+ */
+ public KruleWriter(Interpreter interpreter) {
+ this.interpreter = interpreter;
+ }
+
+ // inheritdoc
+ public void emit(PrintStream out) throws URIParseException {
+ // pull in all the elements, and give them to writers
+ // XMLFragmentWriter varWriter = new VariableWriter(interpreter.getVariables());
+ XMLFragmentWriter refWriter = new ReferenceWriter(interpreter.getReferences());
+ XMLFragmentWriter axiomWriter = new AxiomWriter(interpreter.getAxioms());
+ XMLFragmentWriter ruleWriter = new RuleWriter(interpreter.getRules());
+
+ // send to stdout
+ writeHeader(out);
+ // varWriter.emit(System.out);
+ refWriter.emit(System.out);
+ axiomWriter.emit(System.out);
+ ruleWriter.emit(System.out);
+ writeFooter(out);
+ }
+
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/RDFXMLWriter.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/RDFXMLWriter.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/RDFXMLWriter.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,65 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast.output;
+
+import java.io.PrintStream;
+
+/**
+ * Writes an RDF/XML file to a stream.
+ *
+ * @created May 3, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ * @licence <a href="http://www.opensource.org/licenses/apache2.0.php">Apache License, Version 2.0</a>
+ *
+ */
+public abstract class RDFXMLWriter {
+
+ /**
+ * Build the required XML headers.
+ * @param out The stream to write to.
+ */
+ protected void writeHeader(PrintStream out) {
+ StringBuilder sb = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
+ sb.append("<!DOCTYPE rdf:RDF [\n");
+ sb.append("<!ENTITY owl \"http://www.w3.org/2002/07/owl#\">\n");
+ sb.append("<!ENTITY rdf \"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n");
+ sb.append("<!ENTITY rdfs \"http://www.w3.org/2000/01/rdf-schema#\">\n");
+ sb.append("<!ENTITY xsd \"http://www.w3.org/2001/XMLSchema#\">\n");
+ sb.append("<!ENTITY mulgara \"http://mulgara.org/mulgara#\">\n");
+ sb.append("<!ENTITY krule \"http://mulgara.org/owl/krule/#\">\n");
+ sb.append("]>\n");
+ sb.append("\n");
+ sb.append("<rdf:RDF xmlns:rdf=\"&rdf;\"\n");
+ sb.append(" xmlns:rdfs=\"&rdfs;\"\n");
+ sb.append(" xmlns:owl=\"&owl;\"\n");
+ sb.append(" xmlns:xsd=\"&xsd;\"\n");
+ sb.append(" xmlns=\"&krule;\"\n");
+ sb.append(" xmlns:krule=\"&krule;\"\n");
+ sb.append(" xml:base=\"http://mulgara.org/owl/krule/\">\n");
+ out.println(sb.toString());
+ }
+
+ /**
+ * Build the required XML footers.
+ * @param out The stream to write to.
+ */
+ protected void writeFooter(PrintStream out) {
+ out.println("</rdf:RDF>");
+ }
+
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/ReferenceGenerator.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/ReferenceGenerator.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/ReferenceGenerator.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,92 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast.output;
+
+import org.mulgara.krule.rlog.ParseException;
+import org.mulgara.krule.rlog.parser.URIParseException;
+import org.mulgara.krule.rlog.rdf.URIReference;
+import org.mulgara.resolver.spi.LocalizeException;
+import org.mulgara.resolver.spi.ResolverSession;
+import org.mulgara.store.nodepool.NodePoolException;
+
+import java.net.URISyntaxException;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * Writes references to a list of triples.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class ReferenceGenerator extends TripleGenerator {
+
+ /** The collection of references that this class emits. */
+ public Collection<URIReference> refs;
+
+ /**
+ * Creates a new writer for a collection of references.
+ * @param vars The variables to be written.
+ * @throws LocalizeException If localized nodes could not be accessed.
+ */
+ public ReferenceGenerator(Collection<URIReference> refs, ResolverSession resolverSession) throws LocalizeException {
+ super(resolverSession);
+ this.refs = refs;
+ }
+
+
+ /**
+ * {@inheritDoc}
+ * @throws URIParseException Constructing URIs for the output resulted in an invalid URI.
+ * @throws NodePoolException If blank nodes could not be created.
+ */
+ public List<long[]> emit(List<long[]> triples) throws ParseException, NodePoolException {
+ for (URIReference r: refs) emitReference(triples, r);
+ return triples;
+ }
+
+
+ /**
+ * Create the the triple representation of a reference and append it.
+ * @param triples the List to append the triples to.
+ * @param ref The reference to emit.
+ * @throws NodePoolException If blank nodes could not be created.
+ * @throws ParseException If any bad URIs or non-object literals are encountered.
+ */
+ private List<long[]> emitReference(List<long[]> triples, URIReference ref) throws NodePoolException, ParseException {
+ // ref rdf:type kruleUriReference
+ // ref rdf:value ref.getURI
+
+ try {
+ long rl = toKruleNode(ref.getRdfLabel());
+ long val = toLocalNode(ref.getURI());
+
+ // rl rdf:type URIReference
+ // axiom pos val
+ add(triples, rl, rdfType, kruleUriReference);
+ add(triples, rl, getRdfValue(), val);
+ } catch (URISyntaxException e) {
+ throw new ParseException("Invalid URI:" + e.getMessage());
+ } catch (LocalizeException e) {
+ throw new NodePoolException("Unable to localize a URI", e);
+ }
+
+ return triples;
+ }
+
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/ReferenceWriter.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/ReferenceWriter.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/ReferenceWriter.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,54 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast.output;
+
+import org.mulgara.krule.rlog.rdf.URIReference;
+
+import java.io.PrintStream;
+import java.util.Collection;
+
+/**
+ * Writes variables to an XML stream as a set of declarations.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class ReferenceWriter extends XMLFragmentWriter {
+
+ /** The collection of variables that this class emits. */
+ public Collection<URIReference> refs;
+
+ /**
+ * Creates a new writer for a collection of variables.
+ * @param vars The variables to be written.
+ */
+ public ReferenceWriter(Collection<URIReference> refs) {
+ this.refs = refs;
+ }
+
+ /** {@inheritDoc} */
+ public void emit(PrintStream out) {
+ for (URIReference r: refs) emitRef(out, r);
+ }
+
+ private void emitRef(PrintStream out, URIReference r) {
+ out.println(" <krule:URIReference rdf:about=\"" + r.getRdfLabel() + "\">\n" +
+ " <rdf:value rdf:resource=\"" + r.getURI() + "\"/>\n" +
+ " </krule:URIReference>\n");
+ }
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/RuleGenerator.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/RuleGenerator.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/RuleGenerator.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,427 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast.output;
+
+import org.jrdf.vocabulary.RDF;
+import org.mulgara.krule.rlog.ParseException;
+import org.mulgara.krule.rlog.ast.Predicate;
+import org.mulgara.krule.rlog.ast.Rule;
+import org.mulgara.krule.rlog.parser.URIParseException;
+import org.mulgara.krule.rlog.rdf.Literal;
+import org.mulgara.krule.rlog.rdf.RDFNode;
+import org.mulgara.krule.rlog.rdf.Var;
+import org.mulgara.query.rdf.LiteralImpl;
+import org.mulgara.query.rdf.URIReferenceImpl;
+import org.mulgara.resolver.spi.LocalizeException;
+import org.mulgara.resolver.spi.ResolverSession;
+import org.mulgara.store.nodepool.NodePoolException;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import static org.mulgara.krule.KruleLoader.ARGUMENT;
+import static org.mulgara.krule.KruleLoader.CONSTRAINT_CONJUNCTION;
+import static org.mulgara.krule.KruleLoader.DIFFERENCE;
+import static org.mulgara.krule.KruleLoader.HAS_QUERY;
+import static org.mulgara.krule.KruleLoader.HAS_WHERE_CLAUSE;
+import static org.mulgara.krule.KruleLoader.HAS_SUBJECT;
+import static org.mulgara.krule.KruleLoader.HAS_PREDICATE;
+import static org.mulgara.krule.KruleLoader.HAS_OBJECT;
+import static org.mulgara.krule.KruleLoader.HAS_GRAPH;
+import static org.mulgara.krule.KruleLoader.NAME;
+import static org.mulgara.krule.KruleLoader.QUERY;
+import static org.mulgara.krule.KruleLoader.RULE;
+import static org.mulgara.krule.KruleLoader.SELECTION_VARS;
+import static org.mulgara.krule.KruleLoader.SIMPLE_CONSTRAINT;
+import static org.mulgara.krule.KruleLoader.TRIGGERS;
+import static org.mulgara.krule.KruleLoader.VARIABLE;
+
+/**
+ * Writes rules to a list of triples.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class RuleGenerator extends TripleGenerator {
+
+ /** The collection of rules that this class emits. */
+ public Collection<Rule> rules;
+
+ /** The node for the rdf:Sequence type */
+ private final long rdfSeq;
+
+ /** The node for the krule:Rule type */
+ private final long kruleRule;
+
+ /** The node for the krule:Query type */
+ private final long kruleQuery;
+
+ /** The node for the krule:Difference type */
+ private final long kruleDifference;
+
+ /** The node for the krule:ConstraintConjunction type */
+ private final long kruleConjunction;
+
+ /** The node for the krule:SimpleConstraint type */
+ private final long kruleSimple;
+
+ /** The node for the krule:Variable type */
+ private final long kruleVariable;
+
+ /** The node for the krule:hasQuery predicate */
+ private final long kruleHasQuery;
+
+ /** The node for the krule:triggers predicate */
+ private final long kruleTriggers;
+
+ /** The node for the krule:selectionVariables predicate */
+ private final long kruleSelVars;
+
+ /** The node for the krule:hasWhereClause predicate */
+ private final long kruleHasWhereClause;
+
+ /** The node for the krule:hasSubject predicate */
+ private final long kruleHasSubject;
+
+ /** The node for the krule:hasPredicate predicate */
+ private final long kruleHasPredicate;
+
+ /** The node for the krule:hasObject predicate */
+ private final long kruleHasObject;
+
+ /** The node for the krule:hasModel predicate */
+ private final long kruleHasGraph;
+
+ /** The node for the krule:argument predicate */
+ private final long kruleArgument;
+
+ /** The node for the krule:name predicate */
+ private final long kruleName;
+
+ /** The nodes for RDF sequence membership */
+ private final List<Long> cachedSeq = new ArrayList<Long>();
+
+ /**
+ * Creates a new writer for a collection of rules.
+ * @param rules The rules to be written.
+ * @throws LocalizeException If localized nodes could not be accessed.
+ */
+ public RuleGenerator(Collection<Rule> rules, ResolverSession resolverSession) throws LocalizeException {
+ super(resolverSession);
+ this.rules = rules;
+ rdfSeq = resolverSession.localize(new URIReferenceImpl(RDF.SEQ));
+ kruleRule = resolverSession.localize(RULE);
+ kruleQuery = resolverSession.localize(QUERY);
+ kruleDifference = resolverSession.localize(DIFFERENCE);
+ kruleConjunction = resolverSession.localize(CONSTRAINT_CONJUNCTION);
+ kruleSimple = resolverSession.localize(SIMPLE_CONSTRAINT);
+ kruleVariable = resolverSession.localize(VARIABLE);
+ kruleHasQuery = resolverSession.localize(HAS_QUERY);
+ kruleHasSubject = resolverSession.localize(HAS_SUBJECT);
+ kruleHasPredicate = resolverSession.localize(HAS_PREDICATE);
+ kruleHasObject = resolverSession.localize(HAS_OBJECT);
+ kruleHasGraph = resolverSession.localize(HAS_GRAPH);
+ kruleTriggers = resolverSession.localize(TRIGGERS);
+ kruleSelVars = resolverSession.localize(SELECTION_VARS);
+ kruleHasWhereClause = resolverSession.localize(HAS_WHERE_CLAUSE);
+ kruleArgument = resolverSession.localize(ARGUMENT);
+ kruleName = resolverSession.localize(NAME);
+ initSeqTo(3);
+ }
+
+
+ /**
+ * {@inheritDoc}
+ * @throws ParseException Constructing URIs for the output resulted in an invalid URI.
+ * @throws NodePoolException If blank nodes could not be created.
+ */
+ public List<long[]> emit(List<long[]> triples) throws ParseException, NodePoolException {
+ try {
+ for (Rule r: rules) emitRule(triples, r);
+ } catch (LocalizeException e) {
+ throw new NodePoolException("Unable to localize a node", e);
+ } catch (URISyntaxException e) {
+ throw new ParseException("Malformed URI in rules: " + e.getMessage());
+ } catch (URIParseException e) {
+ throw new ParseException("Malformed URI in rules: " + e.getMessage());
+ }
+ return triples;
+ }
+
+
+ /**
+ * Create the the triple representation of a rule and append it.
+ * @param triples the List to append the triples to.
+ * @param rule The rule to emit.
+ * @throws NodePoolException If blank nodes could not be created.
+ * @throws ParseException If any bad URIs or non-object literals are encountered.
+ * @throws URISyntaxException URIs in the rule are not formed correctly.
+ * @throws LocalizeException Due to an error localizing a URI.
+ * @throws URIParseException URIs in the rule are not formed correctly.
+ */
+ private List<long[]> emitRule(List<long[]> triples, Rule rule) throws NodePoolException, ParseException, LocalizeException, URISyntaxException, URIParseException {
+ long ruleNode = toKruleNode(rule.getName());
+
+ // rule rdf:type kruleRule
+ add(triples, ruleNode, rdfType, kruleRule);
+
+ emitTriggers(triples, ruleNode, rule.getTriggers());
+
+ // query rdf:type krule:Query
+ // rule krule:hasQuery query
+ long query = newBlankNode();
+ add(triples, query, rdfType, kruleQuery);
+ add(triples, ruleNode, kruleHasQuery, query);
+
+ emitSelection(triples, query, rule.getHead());
+ emitWhereClause(triples, query, rule.getBody(), rule.getBodySubtractions());
+
+ return triples;
+ }
+
+
+ /**
+ * Adds the triggers for a rule to the triples.
+ * @param triples The list of triples to append to.
+ * @param triggers The rules that get triggered by the current rule.
+ * @throws URISyntaxException IF a trigger rule has a malformed URI.
+ * @throws LocalizeException If the URI in a trigger rule cannot be localized.
+ */
+ private void emitTriggers(List<long[]> triples, long rule, Collection<Rule> triggers) throws LocalizeException, URISyntaxException {
+ for (Rule r: triggers) add(triples, rule, kruleTriggers, toKruleNode(r.getName()));
+ }
+
+
+ /**
+ * Adds the head of a rule to the triples.
+ * @param triples The list of triples to append to.
+ * @param selection The selection that makes up the head of a rule.
+ * @throws LocalizeException Unable to create a new blank node.
+ * @throws URISyntaxException If a selected URI is incorrectly formed.
+ */
+ private void emitSelection(List<long[]> triples, long query, Predicate selection) throws URIParseException, LocalizeException, URISyntaxException {
+ // seq rdf:type rdf:Seq
+ // query krule:selectionVariables seq
+ long seq = newBlankNode();
+ add(triples, seq, rdfType, rdfSeq);
+ add(triples, query, kruleSelVars, seq);
+
+ // seq rdf:_1 getSubject()
+ // seq rdf:_2 getPredicate()
+ // seq rdf:_3 getObject()
+ add(triples, seq, getSeq(1), toKruleNode(selection.getSubject().getRdfLabel()));
+ add(triples, seq, getSeq(2), toKruleNode(selection.getPredicate().getRdfLabel()));
+ add(triples, seq, getSeq(3), toKruleNode(selection.getObject().getRdfLabel()));
+ }
+
+
+ /**
+ * Prints the body for a rule to a PrintStream.
+ * @param out The PrintStream to send the where clause to.
+ * @param body The where clause that makes up the body of the rule.
+ * @param subs The part of a where clause to be removed from the body.
+ * @throws URIParseException If one of the URIs in the constraint expression has an invalid syntax.
+ * @throws LocalizeException Unable to localize some of the URIs in the constraints.
+ * @throws URISyntaxException If one of the URIs in the constraint has an invalid syntax.
+ */
+ private void emitWhereClause(List<long[]> triples, long query, List<Predicate> body, List<Predicate> subs) throws URIParseException, LocalizeException, URISyntaxException {
+ long constraintExpr = newBlankNode();
+ // query krule:hasWhereClause constraintExpr
+ add(triples, query, kruleHasWhereClause, constraintExpr);
+
+ if (subs.isEmpty()) emitConjunction(triples, constraintExpr, body);
+ else emitSubtractions(triples, constraintExpr, body, subs);
+ }
+
+
+ /**
+ * Emit the operation for the difference between the body and the subtractions as a set of triples.
+ * @param triples The
+ * @param body The main body to be selected (the minuend).
+ * @param subs The constraints to be subtracted from the body (the subtrahends).
+ * @throws URIParseException The constraints contain URIs that are invalid.
+ * @throws LocalizeException Unable to localize some of the URIs in the constraint.
+ * @throws URISyntaxException If one of the URIs in the constraint has an invalid syntax.
+ */
+ private void emitSubtractions(List<long[]> triples, long diff, List<Predicate> body, List<Predicate> subs) throws URIParseException, LocalizeException, URISyntaxException {
+ // constraintExpr rdf:type krule:Difference
+ add(triples, diff, rdfType, kruleDifference);
+
+ long argument = newBlankNode();
+ // diff krule:argument argument
+ add(triples, diff, kruleArgument, argument);
+
+ int lastElt = subs.size() - 1;
+ if (lastElt == 0) emitConjunction(triples, argument, body);
+ else emitSubtractions(triples, argument, body, subs.subList(0, lastElt));
+
+ // last argument in subtraction
+ // diff krule:argument argument
+ argument = newBlankNode();
+ add(triples, diff, kruleArgument, argument);
+
+ emitSimpleConstraint(triples, argument, subs.get(lastElt));
+ }
+
+
+ /**
+ * Adds a list of constraints as the arguments to a single ConstraintConjunction.
+ * @param triples The list of triples to add the statements to.
+ * @param conj The node representing the conjunction being emitted.
+ * @param conjunction The list of constraints that form the conjunction to be added.
+ * @throws URIParseException If one of the URIs in the constraint has an invalid syntax.
+ * @throws LocalizeException Unable to localize a URI in the expression.
+ * @throws URISyntaxException If one of the URIs in the constraint has an invalid syntax.
+ */
+ private void emitConjunction(List<long[]> triples, long conjNode, List<Predicate> conjunction) throws URIParseException, LocalizeException, URISyntaxException {
+ if (conjunction.size() == 1) emitSimpleConstraint(triples, conjNode, conjunction.get(0));
+ else {
+ // conj rdf:type krule:ConstraintConjunction
+ add(triples, conjNode, rdfType, kruleConjunction);
+
+ for (Predicate op: conjunction) {
+ long argument = newBlankNode();
+ // conj krule:argument argument
+ add(triples, conjNode, kruleArgument, argument);
+
+ emitSimpleConstraint(triples, argument, op);
+ }
+ }
+ }
+
+
+ /**
+ * Adds a single constraint to the generated triples.
+ * @param triples The triples to add to.
+ * @param constraintNode The local node representing the constraint.
+ * @param constraint The constraint to write.
+ * @throws URIParseException If one of the URIs in the constraint has an invalid syntax.
+ * @throws LocalizeException Unable to localize a URI in the expression.
+ * @throws URISyntaxException If one of the URIs in the constraint has an invalid syntax.
+ */
+ private void emitSimpleConstraint(List<long[]> triples, long constraintNode, Predicate constraint) throws URIParseException, LocalizeException, URISyntaxException {
+ // constraintNode rdf:type krule:SimpleConstraint
+ add(triples, constraintNode, rdfType, kruleSimple);
+
+ // constraintNode krule:hasSubject subjNode
+ // constraintNode krule:hasPredicate predNode
+ // constraintNode krule:hasObject objNode
+ // constraintNode krule:hasModel graphNode [OPTIONAL]
+
+ long node = emitNode(triples, constraint.getSubject());
+ add(triples, constraintNode, kruleHasSubject, node);
+
+ node = emitNode(triples, constraint.getPredicate());
+ add(triples, constraintNode, kruleHasPredicate, node);
+
+ node = emitNode(triples, constraint.getObject());
+ add(triples, constraintNode, kruleHasObject, node);
+
+ if (constraint.hasGraphAnnotation()) {
+ node = emitNode(triples, constraint.getGraphAnnotation());
+ add(triples, constraintNode, kruleHasGraph, node);
+ }
+ }
+
+
+ /**
+ * Add the details for a node to the list of triples.
+ * @param triples The triples to add the node for.
+ * @param node The structured data for the node being emitted.
+ * @return The localized node created for this node.
+ * @throws LocalizeException Unable to localize the URI for the node, or structure describing the node.
+ * @throws URISyntaxException The node URI, or a URI associated with this node is malformed.
+ */
+ private long emitNode(List<long[]> triples, RDFNode node) throws LocalizeException, URISyntaxException {
+ if (node.isReference()) {
+ // node rdf:type krule:URIReference
+ long r = toKruleNode(node.getRdfLabel());
+ add(triples, r, rdfType, kruleUriReference);
+ return r;
+ } else if (node.isVariable()) {
+ // node rdf:type krule:Variable
+ long r = toKruleNode(node.getRdfLabel());
+ add(triples, r, rdfType, kruleVariable);
+ add(triples, r, kruleName, localizeString(((Var)node).getName()));
+ return r;
+ } else {
+ // node rdf:type krule:Literal
+ // node rdf:value "......"
+ long r = newBlankNode();
+ add(triples, r, rdfType, getKruleLiteral());
+ add(triples, r, getRdfValue(), toLiteral(node));
+ return r;
+ }
+ }
+
+
+ /**
+ * Converts a node representing a literal to a localized literal.
+ * If krule Literals start to support data types, then so should this method.
+ * @param node The RDFNode that can be cast to a literal.
+ * @return A localized gNode for the literal.
+ * @throws LocalizeException The string could not be written to or accessed from the string pool.
+ */
+ private long toLiteral(RDFNode node) throws LocalizeException {
+ Literal l = (Literal)node;
+ return resolverSession.localize(new LiteralImpl(l.getLexical()));
+ }
+
+
+ /**
+ * Localizes a string.
+ * @param str The string to localize.
+ * @return The gNode which represents the string in local form.
+ * @throws LocalizeException The string could not be created in the string pool.
+ */
+ private long localizeString(String str) throws LocalizeException {
+ return resolverSession.localize(new LiteralImpl(str));
+ }
+
+
+ /**
+ * Get a cached sequence number. This will get more if they have not been cached yet.
+ * @param i The sequence number to retrieve. Starts at 1.
+ * @return The localized value of the URI rdf:_i
+ * @throws LocalizeException If an uncached URI could not be localized.
+ */
+ private long getSeq(int i) throws LocalizeException {
+ assert i >= 1;
+ if (i > cachedSeq.size()) initSeqTo(i);
+ // retrieving a 1-based sequence from a 0-based list
+ return cachedSeq.get(i - 1);
+ }
+
+
+ /**
+ * Fill the sequence array to the element given.
+ * @param largest The largest sequence element to initialize.
+ * @throws LocalizeException If a URI cannot be localized.
+ */
+ private void initSeqTo(int largest) throws LocalizeException {
+ String seqBase = RDF.BASE_URI.toString() + "_";
+ for (int i = cachedSeq.size() + 1; i <= largest; i++) {
+ URI s = URI.create(seqBase + i);
+ cachedSeq.add(resolverSession.lookup(new URIReferenceImpl(s)));
+ }
+ }
+
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/RuleWriter.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/RuleWriter.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/RuleWriter.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,177 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast.output;
+
+import org.mulgara.krule.rlog.ast.Predicate;
+import org.mulgara.krule.rlog.ast.Rule;
+import org.mulgara.krule.rlog.parser.URIParseException;
+
+import java.io.PrintStream;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * Writes variables to an XML stream as a set of declarations.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class RuleWriter extends XMLFragmentWriter {
+
+ /** The default starting point for indentation in the body of a statement. */
+ private static final int DEFAULT_BODY_INDENT = 5;
+
+ /** The collection of variables that this class emits. */
+ public Collection<Rule> rules;
+
+ /**
+ * Creates a new writer for a collection of variables.
+ * @param vars The variables to be written.
+ */
+ public RuleWriter(Collection<Rule> rules) {
+ this.rules = rules;
+ }
+
+ /** {@inheritDoc} */
+ public void emit(PrintStream out) throws URIParseException {
+ for (Rule r: rules) emitRule(out, r);
+ }
+
+ /**
+ * Prints an entire Rule to a PrintStream.
+ * @param out The PrintStream to send the rule to.
+ * @param r The rule to print.
+ */
+ private void emitRule(PrintStream out, Rule r) throws URIParseException {
+ out.println(" <krule:Rule rdf:about=\"#" + r.getName() + "\">");
+ emitTriggers(out, r.getTriggers());
+ out.println(" <hasQuery>\n" +
+ " <Query>");
+ emitSelection(out, r.getHead());
+ emitWhereClause(out, r.getBody(), r.getBodySubtractions());
+ out.println(" </Query>\n" +
+ " </hasQuery>\n" +
+ " </krule:Rule>\n");
+ }
+
+ /**
+ * Prints the triggers for a rule to a PrintStream.
+ * @param out The PrintStream to send the triggered rules to.
+ * @param triggers The rules that get triggered by the currently printing rule.
+ */
+ private void emitTriggers(PrintStream out, Collection<Rule> triggers) {
+ for (Rule r: triggers) {
+ out.println(" <triggers rdf:resource=\"#" + r.getName() + "\"/>");
+ }
+ }
+
+ /**
+ * Prints the head for a rule to a PrintStream.
+ * @param out The PrintStream to send the selection to.
+ * @param selection The selection that makes up the head of a rule.
+ */
+ private void emitSelection(PrintStream out, Predicate selection) throws URIParseException {
+ out.println(" <selectionVariables>\n" +
+ " <rdf:Seq>\n" +
+ " <rdf:li rdf:resource=\"" + selection.getSubject().getRdfLabel() + "\"/>\n" +
+ " <rdf:li rdf:resource=\"" + selection.getPredicate().getRdfLabel() + "\"/>\n" +
+ " <rdf:li rdf:resource=\"" + selection.getObject().getRdfLabel() + "\"/>\n" +
+ " </rdf:Seq>\n" +
+ " </selectionVariables>");
+ }
+
+ /**
+ * Prints the body for a rule to a PrintStream.
+ * @param out The PrintStream to send the where clause to.
+ * @param body The where clause that makes up the body of the rule.
+ * @param subs The part of a where clause to be removed from the body.
+ * @throws URIParseException If one of the URIs in the constraint expression has an invalid syntax.
+ */
+ private void emitWhereClause(PrintStream out, List<Predicate> body, List<Predicate> subs) throws URIParseException {
+ out.println(" <hasWhereClause>");
+ if (subs.isEmpty()) emitConjunction(out, body, DEFAULT_BODY_INDENT);
+ else emitSubtractions(out, body, subs, DEFAULT_BODY_INDENT);
+ out.println(" </hasWhereClause>");
+ }
+
+ private void emitSubtractions(PrintStream out, List<Predicate> body, List<Predicate> subs, int indent) throws URIParseException {
+ int lastElt = subs.size() - 1;
+ out.println(sp(indent) + "<Difference>\n" +
+ sp(indent + 1) + "<argument>");
+ if (lastElt == 0) emitConjunction(out, body, indent + 2);
+ else emitSubtractions(out, body, subs.subList(0, lastElt), indent + 2);
+ out.println(sp(indent + 1) + "</argument>\n" +
+ sp(indent + 1) + "<argument>");
+ emitSimpleConstraint(out, subs.get(lastElt), indent + 2);
+ out.println(sp(indent + 1) + "</argument>\n" +
+ sp(indent) + "</Difference>");
+ }
+
+ /**
+ * Prints a list of constraints as the arguments to a single ConstraintConjunction.
+ * @param out The PrintStream to send the constraint to.
+ * @param conjunction The list of constraints that form the conjunction to be written.
+ * @param indent The number of indentations needed for the expression to be written correctly.
+ * @throws URIParseException If one of the URIs in the constraint has an invalid syntax.
+ */
+ private void emitConjunction(PrintStream out, List<Predicate> conjunction, int indent) throws URIParseException {
+ if (conjunction.size() == 1) emitSimpleConstraint(out, conjunction.get(0), indent);
+ else {
+ out.println(sp(indent) + "<ConstraintConjunction>");
+ for (Predicate arg: conjunction) {
+ out.println(sp(indent + 1) + "<argument>");
+ emitSimpleConstraint(out, arg, indent + 2);
+ out.println(sp(indent + 1) + "</argument>");
+ }
+ out.println(sp(indent) + "</ConstraintConjunction>");
+ }
+ }
+
+ /**
+ * Prints a single constraint to a PrintStream.
+ * @param out The PrintStream to send the constraint to.
+ * @param constraint The constraint to write.
+ * @param indent The indentation needed for the constraint to be written correctly.
+ * @throws URIParseException If one of the URIs in the constraint has an invalid syntax.
+ */
+ private void emitSimpleConstraint(PrintStream out, Predicate constraint, int indent) throws URIParseException {
+ out.println(sp(indent) + "<SimpleConstraint>\n" +
+ sp(indent + 1) + "<hasSubject>\n" +
+ sp(indent + 2) + nodeString(constraint.getSubject()) + "\n" +
+ sp(indent + 1) + "</hasSubject>\n" +
+ sp(indent + 1) + "<hasPredicate>\n" +
+ sp(indent + 2) + nodeString(constraint.getPredicate()) + "\n" +
+ sp(indent + 1) + "</hasPredicate>\n" +
+ sp(indent + 1) + "<hasObject>\n" +
+ sp(indent + 2) + nodeString(constraint.getObject()) + "\n" +
+ sp(indent + 1) + "</hasObject>");
+ if (constraint.hasGraphAnnotation()) {
+ out.println(sp(indent + 1) + "<hasModel>\n" +
+ sp(indent + 2) + nodeString(constraint.getGraphAnnotation()) + "\n" +
+ sp(indent + 1) + "</hasModel>");
+ }
+ out.println(sp(indent) + "</SimpleConstraint>");
+ }
+
+ private String sp(int nr) {
+ StringBuffer sb = new StringBuffer();
+ for (int n = 0; n < nr; n++) sb.append(" ");
+ return sb.toString();
+ }
+
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/TripleGenerator.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/TripleGenerator.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/TripleGenerator.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,154 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast.output;
+
+import static org.mulgara.krule.KruleLoader.KRULE;
+import static org.mulgara.krule.KruleLoader.LITERAL;
+import static org.mulgara.krule.KruleLoader.URI_REF;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.List;
+
+import org.jrdf.vocabulary.RDF;
+import org.mulgara.krule.rlog.ParseException;
+import org.mulgara.query.rdf.BlankNodeImpl;
+import org.mulgara.query.rdf.URIReferenceImpl;
+import org.mulgara.resolver.spi.LocalizeException;
+import org.mulgara.resolver.spi.ResolverSession;
+import org.mulgara.store.nodepool.NodePoolException;
+
+/**
+ * Outputs a set of rules as triples.
+ *
+ * @created Feb 25, 2009
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ * @licence <a href="http://www.opensource.org/licenses/apache2.0.php">Apache License, Version 2.0</a>
+ */
+public abstract class TripleGenerator {
+
+ /** The domain for KRULE, sans the fragment tag */
+ private static final String KRULE_SHORT = KRULE.substring(0, KRULE.length() - 1);
+
+ /** The session for localizing strings and URIs */
+ ResolverSession resolverSession;
+
+ /** The node for rdf:type */
+ protected final long rdfType;
+
+ /** The node for kruleURIReference. This might not be used. */
+ protected final long kruleUriReference;
+
+ /** The node for rdf:value. This might not be used. */
+ private Long rdfValue;
+
+ /** The node for krule:Literal. This might not be used. */
+ private Long kruleLiteral;
+
+ /**
+ * Creates a triple generator and initializes it with shared nodes.
+ * @param resolverSession The session used for identifying nodes.
+ * @throws LocalizeException There was an error localizing nodes.
+ */
+ protected TripleGenerator(ResolverSession resolverSession) throws LocalizeException {
+ this.resolverSession = resolverSession;
+ rdfType = resolverSession.lookup(new URIReferenceImpl(RDF.TYPE));
+ kruleUriReference = resolverSession.localize(URI_REF);
+ }
+
+
+ /**
+ * Fill a list with the triples to be generated.
+ * @param triples The list to fill.
+ * @return The filled list.
+ * @throws NodePoolException If blank nodes could not be created.
+ */
+ abstract List<long[]> emit(List<long[]> triples) throws LocalizeException, ParseException, NodePoolException;
+
+
+ /**
+ * Convenience for adding a new triple to the list
+ * @param triples The list to add to.
+ * @param s The subject for the triple
+ * @param p The predicate for the triple
+ * @param o The object for the triple
+ */
+ static final protected void add(List<long[]> triples, long s, long p, long o) {
+ triples.add(new long[] { s, p, o });
+ }
+
+
+ /**
+ * Creates a localized URIReference for a name in the KRULE domain
+ * @param label the unqualified name
+ * @return A localized gNode for the URI
+ * @throws LocalizeException If the URI could not be localized
+ * @throws URISyntaxException If the URI was malformed
+ */
+ protected long toKruleNode(String label) throws LocalizeException, URISyntaxException {
+ String fullname;
+ fullname = (label.charAt(0) == '#') ? KRULE_SHORT + label : KRULE + label;
+ return resolverSession.localize(new URIReferenceImpl(new URI(fullname)));
+ }
+
+
+ /**
+ * Creates a localized URIReference for a general URI
+ * @param u The node to localize.
+ * @return A localized gNode for the URI
+ * @throws LocalizeException If the URI could not be localized
+ */
+ protected long toLocalNode(URI u) throws LocalizeException, URISyntaxException {
+ return resolverSession.localize(new URIReferenceImpl(u));
+ }
+
+
+ /**
+ * Creates a new blank node to use in this session.
+ * @return The ID for the new blank node.
+ * @throws LocalizeException If the blank node could not be created.
+ */
+ protected long newBlankNode() throws LocalizeException {
+ return resolverSession.localize(new BlankNodeImpl());
+ }
+
+
+ /**
+ * Retrive a cached value for rdf:Value
+ * @return The local node for rdf:Value
+ * @throws LocalizeException If a required lookup was unsuccessful
+ */
+ protected long getRdfValue() throws LocalizeException {
+ if (rdfValue == null) {
+ rdfValue = resolverSession.localize(new URIReferenceImpl(RDF.VALUE));
+ }
+ return rdfValue;
+ }
+
+
+ /**
+ * Retrive a cached value for krule:Literal
+ * @return The local node for krule:Literal
+ * @throws LocalizeException If a required lookup was unsuccessful
+ */
+ protected long getKruleLiteral() throws LocalizeException {
+ if (kruleLiteral == null) kruleLiteral = resolverSession.localize(LITERAL);
+ return kruleLiteral;
+ }
+
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/VariableWriter.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/VariableWriter.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/VariableWriter.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,57 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast.output;
+
+import org.mulgara.krule.rlog.rdf.Var;
+
+import java.io.PrintStream;
+import java.util.Collection;
+
+/**
+ * Writes variables to an XML stream as a set of declarations.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public class VariableWriter extends XMLFragmentWriter {
+
+ /** The collection of variables that this class emits. */
+ public Collection<Var> vars;
+
+ /**
+ * Creates a new writer for a collection of variables.
+ * @param vars The variables to be written.
+ */
+ public VariableWriter(Collection<Var> vars) {
+ this.vars = vars;
+ }
+
+ /** {@inheritDoc} */
+ public void emit(PrintStream out) {
+ for (Var v: vars) emitVar(out, v);
+ }
+
+ /**
+ * Prints a variable declaration to the stream
+ * @param out The print stream to print to.
+ * @param v The variable to emit.
+ */
+ private void emitVar(PrintStream out, Var v) {
+ out.println(" " + nodeString(v) + "\n");
+ }
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/XMLFragmentWriter.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/XMLFragmentWriter.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/ast/output/XMLFragmentWriter.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,65 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.ast.output;
+
+import java.io.PrintStream;
+
+import org.mulgara.krule.rlog.parser.URIParseException;
+import org.mulgara.krule.rlog.rdf.Literal;
+import org.mulgara.krule.rlog.rdf.RDFNode;
+import org.mulgara.krule.rlog.rdf.URIReference;
+import org.mulgara.krule.rlog.rdf.Var;
+
+/**
+ * Outputs an element of the AST into XML.
+ *
+ * @created May 16, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ */
+public abstract class XMLFragmentWriter {
+
+ /**
+ * Outputs the data for this object into a stream.
+ * @param out The stream to write to.
+ * @throws URIParseException Constructing URIs for the output resulted in an invalid URI.
+ */
+ public abstract void emit(PrintStream out) throws URIParseException;
+
+ /**
+ * Create a string representation of the RDF/XML needed for a node.
+ * @param n The node to write.
+ * @return An XML fragment string representing the node.
+ */
+ protected String nodeString(RDFNode n) {
+ StringBuilder sb;
+ if (n.isReference()) {
+ URIReference ref = (URIReference)n;
+ sb = new StringBuilder("<krule:URIReference rdf:about=\"");
+ sb.append(ref.getRdfLabel()).append("\"/>");
+ } else if (n.isVariable()) {
+ Var v = (Var)n;
+ sb = new StringBuilder("<krule:Variable rdf:about=\"");
+ sb.append(v.getRdfLabel()).append("\"><name>").append(v.getName()).append("</name></krule:Variable>");
+ } else {
+ sb = new StringBuilder("<krule:Literal><rdf:value rdf:parseType=\"Literal\">");
+ sb.append(((Literal)n).getLexical()).append("</rdf:value></krule:Literal>");
+ }
+ return sb.toString();
+ }
+
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/parser/NSUtils.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/parser/NSUtils.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/parser/NSUtils.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,123 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.parser;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.mulgara.krule.rlog.rdf.RDF;
+
+/**
+ * Records namespace information.
+ *
+ * @created May 2, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ * @licence <a href="http://www.opensource.org/licenses/apache2.0.php">Apache License, Version 2.0</a>
+ */
+public class NSUtils {
+
+ /** The default domain to use when no other is set. */
+ public static String defaultDomain = RDF.KRULE_NS;
+
+ public static String defaultPrefix = RDF.KRULE_PREFIX;
+
+ /** A mapping of prefixes to namespaces. */
+ private static Map<String,String> registeredDomains = new HashMap<String,String>();
+
+ static {
+ registeredDomains.put(RDF.PREFIX, RDF.NS);
+ registeredDomains.put(RDF.RDFS_PREFIX, RDF.RDFS_NS);
+ registeredDomains.put(RDF.OWL_PREFIX, RDF.OWL_NS);
+ registeredDomains.put(RDF.XSD_PREFIX, RDF.XSD_NS);
+ registeredDomains.put(RDF.MULGARA_PREFIX, RDF.MULGARA_NS);
+ registeredDomains.put(RDF.KRULE_PREFIX, RDF.KRULE_NS);
+ registeredDomains.put(RDF.FOAF_PREFIX, RDF.FOAF_NS);
+ registeredDomains.put(RDF.SKOS_PREFIX, RDF.SKOS_NS);
+ registeredDomains.put(RDF.DC_PREFIX, RDF.DC_NS);
+ }
+
+ /** Sets the default domain to use when no namespace is given. */
+ public static void setDefaultDomain(String prefix, String domain) {
+ defaultPrefix = prefix;
+ defaultDomain = domain;
+ registeredDomains.put(prefix, domain);
+ }
+
+ /** Gets the default domain used when no namespace is given. */
+ public static String getDefaultDomain() {
+ return defaultDomain;
+ }
+
+ /** Gets the default prefix used when no namespace is given. */
+ public static String getDefaultPrefix() {
+ return defaultPrefix;
+ }
+
+ /**
+ * Registers a new prefix to a namespace.
+ * @param prefix The prefix to map to the namespace.
+ * @param namespace The namespace for the domain.
+ */
+ public static void registerDomain(String prefix, String namespace) {
+ registeredDomains.put(prefix, namespace);
+ }
+
+ /**
+ * Creates a URI within the default domain.
+ * @param uriStr The name within the default domain.
+ * @return A new URI for the name in the default domain.
+ * @throws URISyntaxException The name within the domain doesn't form a valid URI.
+ */
+ public static URI newURI(String uriStr) throws URISyntaxException {
+ return new URI(newName(uriStr));
+ }
+
+ /**
+ * Creates a URI within the default domain.
+ * @param uriStr The name within the domain.
+ * @param domain The namespace for the URI.
+ * @return A new URI for the name in domain.
+ * @throws URISyntaxException The name within the domain doesn't form a valid URI.
+ */
+ public static URI newURI(String domain, String uriStr) throws URISyntaxException {
+ return new URI(newName(domain, uriStr));
+ }
+
+ /**
+ * Creates a new URI string within the default domain.
+ * @param name The name of the resource in the default domain.
+ * @return The complete name for the resource.
+ */
+ public static String newName(String name) {
+ return defaultDomain + ":" + name;
+ }
+
+ /**
+ * Creates a new URI string within a domain.
+ * @param domain The domain for the resource.
+ * @param uriStr The name of the resource in the domain.
+ * @return The complete name for the resource.
+ */
+ public static String newName(String domain, String uriStr) {
+ if (domain == null) return newName(uriStr);
+ String namespace = registeredDomains.get(domain);
+ return (namespace == null ? domain + ":" : namespace) + uriStr;
+ }
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/parser/TypeException.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/parser/TypeException.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/parser/TypeException.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.parser;
+
+/**
+ * Indicates the head of a rule has the wrong type.
+ *
+ * @created May 2, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ * @licence <a href="http://www.opensource.org/licenses/apache2.0.php">Apache License, Version 2.0</a>
+ */
+public class TypeException extends Exception {
+
+ /** For serializing */
+ private static final long serialVersionUID = 8935948978390444100L;
+
+ public TypeException(String message) {
+ super(message);
+ }
+
+ public TypeException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public TypeException(Throwable cause) {
+ super(cause);
+ }
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/parser/URIParseException.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/parser/URIParseException.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/parser/URIParseException.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.parser;
+
+/**
+ * Indicates an exception when parsing a URI.
+ *
+ * @created May 2, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ * @licence <a href="http://www.opensource.org/licenses/apache2.0.php">Apache License, Version 2.0</a>
+ */
+public class URIParseException extends Exception {
+
+ /** For serializing */
+ private static final long serialVersionUID = 8935948978390444100L;
+
+ public URIParseException(String message) {
+ super("URI not properly formed: " + message);
+ }
+
+ public URIParseException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public URIParseException(Throwable cause) {
+ super(cause);
+ }
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/Literal.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/Literal.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/Literal.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,93 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.rdf;
+
+import java.net.URI;
+
+/**
+ * An RDF literal.
+ *
+ * @created May 2, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ * @licence <a href="http://www.opensource.org/licenses/apache2.0.php">Apache License, Version 2.0</a>
+ */
+public class Literal implements RDFNode {
+
+ private final String lexical;
+
+ private final String language;
+
+ private final boolean isSimple;
+
+ private final URI type;
+
+ public Literal(String lexical) {
+ this.lexical = lexical;
+ language = "";
+ isSimple = true;
+ type = null;
+ }
+
+ public Literal(String lexical, String language) {
+ this.lexical = lexical;
+ this.language = language;
+ isSimple = true;
+ type = null;
+ }
+
+ public Literal(String lexical, URIReference type) {
+ this.lexical = lexical;
+ this.language = "";
+ isSimple = false;
+ this.type = type.getURI();
+ }
+
+ /** @see org.mulgara.krule.rlog.rdf.RDFNode#isVariable() */
+ public boolean isVariable() {
+ return false;
+ }
+
+ /** @see org.mulgara.krule.rlog.rdf.RDFNode#isReference() */
+ public boolean isReference() {
+ return false;
+ }
+
+ /** Get the lexical reference. */
+ public String getLexical() {
+ return lexical;
+ }
+
+ /** {@inheritDoc} */ // TODO: consider changing rule system to handle this in the head.
+ public String getRdfLabel() {
+ throw new UnsupportedOperationException();
+ }
+
+ /** {@inheritDoc} */
+ public boolean equals(Object o) {
+ if (o == this) return true;
+ if (!(o instanceof Literal)) return false;
+ Literal l = (Literal)o;
+ if (isSimple) return lexical.equals(l.lexical) && language.equals(l.language);
+ else return lexical.equals(l.lexical) && type.equals(l.type);
+ }
+
+ /** {@inheritDoc} */
+ public int hashCode() {
+ return lexical.hashCode() * 7 + language.hashCode() * 13 + type.hashCode() * 17 + (isSimple ? 1 : 0);
+ }
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/MulgaraGraphs.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/MulgaraGraphs.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/MulgaraGraphs.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,80 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.rdf;
+
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.mulgara.krule.rlog.rdf.RDF.MULGARA_PREFIX;
+import static org.mulgara.krule.rlog.rdf.RDF.RDFS_PREFIX;
+
+/**
+ * Contains information about specific Mulgara graphs that can be used in rlog.
+ *
+ * @created May 3, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ * @licence <a href="http://www.opensource.org/licenses/apache2.0.php">Apache License, Version 2.0</a>
+ */
+public class MulgaraGraphs {
+
+ public static final URIReference MULGARA_PRE = URIReference.create(MULGARA_PREFIX, "prefix");
+
+ public static final URIReference MULGARA_URI_REF = URIReference.create(MULGARA_PREFIX, "UriReference");
+
+ public static final URIReference MULGARA_LITERAL = URIReference.create(RDFS_PREFIX, "Literal");
+
+ public static final URIReference MULGARA_PRE_GRAPH = URIReference.create(MULGARA_PREFIX, "prefixGraph", "sys:prefix");
+
+ public static final URIReference MULGARA_TYPE_GRAPH = URIReference.create(MULGARA_PREFIX, "typeGraph", "sys:type");
+
+ /** Maps special predicates to graphs that can handle them. */
+ private static Map<URI,URIReference> specialPredicateGraphs = new HashMap<URI,URIReference>();
+
+ /** Maps special types to graphs that can handle them. */
+ private static Map<URI,URIReference> specialTypeGraphs = new HashMap<URI,URIReference>();
+
+ /** Holds a copy of all the special URIs. */
+ private static List<URIReference> specialUriRefs = new ArrayList<URIReference>();
+
+ static {
+ specialPredicateGraphs.put(MULGARA_PRE.getURI(), MULGARA_PRE_GRAPH);
+ specialTypeGraphs.put(MULGARA_URI_REF.getURI(), MULGARA_TYPE_GRAPH);
+ specialTypeGraphs.put(MULGARA_LITERAL.getURI(), MULGARA_TYPE_GRAPH);
+ specialUriRefs.add(MULGARA_PRE);
+ specialUriRefs.add(MULGARA_URI_REF);
+ specialUriRefs.add(MULGARA_LITERAL);
+ specialUriRefs.add(MULGARA_PRE_GRAPH);
+ specialUriRefs.add(MULGARA_TYPE_GRAPH);
+ }
+
+ public static URIReference getPredicateGraph(URI predicate) {
+ return specialPredicateGraphs.get(predicate);
+ }
+
+ public static URIReference getTypeGraph(URI type) {
+ return specialTypeGraphs.get(type);
+ }
+
+ public static List<URIReference> getSpecialUriRefs() {
+ return Collections.unmodifiableList(specialUriRefs);
+ }
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/RDF.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/RDF.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/RDF.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,72 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.rdf;
+
+/**
+ * Contains the RDF namespace details
+ *
+ * @created May 2, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ * @licence <a href="http://www.opensource.org/licenses/apache2.0.php">Apache License, Version 2.0</a>
+ */
+public class RDF {
+
+ /** The namespace for RDF */
+ public static final String NS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
+
+ public static final String PREFIX = "rdf";
+
+ public static final URIReference TYPE = URIReference.create(PREFIX, "type");
+
+ public static final String XSD_NS = "http://www.w3.org/2001/XMLSchema#";
+
+ public static final String XSD_PREFIX = "xsd";
+
+ public static final String OWL_NS = "http://www.w3.org/2002/07/owl#";
+
+ public static final String OWL_PREFIX = "owl";
+
+ public static final String RDFS_NS = "http://www.w3.org/2000/01/rdf-schema#";
+
+ public static final String RDFS_PREFIX = "rdfs";
+
+ public static final String MULGARA_NS = "http://mulgara.org/mulgara#";
+
+ public static final String MULGARA_PREFIX = "mulgara";
+
+ public static final String KRULE_NS = "http://mulgara.org/owl/krule/#";
+
+ public static final String KRULE_PREFIX = "krule";
+
+ public static final String FOAF_NS = "http://xmlns.com/foaf/0.1/";
+
+ public static final String FOAF_PREFIX = "foaf";
+
+ public static final String SKOS_NS = "http://www.w3.org/2004/02/skos/core#";
+
+ public static final String SKOS_PREFIX = "skos";
+
+ public static final String DC_NS = "http://purl.org/dc/elements/1.1/";
+
+ public static final String DC_PREFIX = "dc";
+
+ // Specific URIs used by the standard parser
+
+ public static final URIReference XSD_LONG = URIReference.create(XSD_PREFIX, "long");
+
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/RDFNode.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/RDFNode.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/RDFNode.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,37 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.rdf;
+
+/**
+ * Represents the RDF elements found in a rule.
+ *
+ * @created May 2, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ * @licence <a href="http://www.opensource.org/licenses/apache2.0.php">Apache License, Version 2.0</a>
+ */
+public interface RDFNode {
+
+ /** Indicates that this node can represent anything, depending on context. */
+ public boolean isVariable();
+
+ /** Indicates that this node is a URI reference. */
+ public boolean isReference();
+
+ /** Returns a label suitable for RDF. */
+ public String getRdfLabel();
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/URIReference.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/URIReference.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/URIReference.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,140 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.rdf;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import org.mulgara.krule.rlog.parser.NSUtils;
+
+/**
+ * A reference to a URI.
+ *
+ * @created May 2, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ * @licence <a href="http://www.opensource.org/licenses/apache2.0.php">Apache License, Version 2.0</a>
+ */
+public class URIReference implements RDFNode {
+
+ private final URI uri;
+
+ private final String prefix;
+
+ private final String value;
+
+ public URIReference(String prefix, String value) throws URISyntaxException {
+ this.prefix = prefix;
+ this.value = value;
+ this.uri = NSUtils.newURI(prefix, value);
+ }
+
+ public URIReference(String value) throws URISyntaxException {
+ this.prefix = NSUtils.getDefaultPrefix();
+ this.value = value;
+ this.uri = NSUtils.newURI(prefix, value);
+ }
+
+ /** Internal mechanism for setting each element manually from a factory. */
+ private URIReference(String prefix, String value, URI uri) {
+ this.prefix = prefix;
+ this.value = value;
+ this.uri = uri;
+ }
+
+ /**
+ * Creates a URIReference. This requires the URI to be clean. If it is possible that this
+ * can fail then use the constructor instead.
+ * @param prefix A namespace prefix.
+ * @param value The value within the namespace.
+ * @return A new URIReference.
+ */
+ public static URIReference create(String prefix, String value) {
+ try {
+ return new URIReference(prefix, value);
+ } catch (URISyntaxException e) {
+ throw new IllegalArgumentException("Unable to create a URI for: " + prefix + ":" + value);
+ }
+ }
+
+ /**
+ * Creates a URIReference. This requires the URI to be clean. If it is possible that this
+ * can fail then use the constructor instead.
+ * @param value The value within the namespace.
+ * @return A new URIReference.
+ */
+ public static URIReference create(String value) {
+ try {
+ return new URIReference(value);
+ } catch (URISyntaxException e) {
+ throw new IllegalArgumentException("Unable to create a URI for: " + NSUtils.getDefaultDomain() + ":" + value);
+ }
+ }
+
+ /**
+ * Creates a URIReference. This requires the URI to be pre-built.
+ * @param prefix A namespace prefix.
+ * @param value The value within the namespace.
+ * @param uri The string for the URI to wrap, and that is represented by prefix:value
+ * @return A new URIReference.
+ */
+ public static URIReference create(String prefix, String value, String uriStr) {
+ return new URIReference(prefix, value, URI.create(uriStr));
+ }
+
+ /** @see org.mulgara.krule.rlog.rdf.RDFNode#isVariable() */
+ public boolean isVariable() {
+ return false;
+ }
+
+ /** @see org.mulgara.krule.rlog.rdf.RDFNode#isReference() */
+ public boolean isReference() {
+ return true;
+ }
+
+ /** Get the URI this references. */
+ public URI getURI() {
+ return uri;
+ }
+
+ /** Get the prefix used for the URI. */
+ public String getPrefix() {
+ return prefix;
+ }
+
+ /** Get the value used for the URI. */
+ public String getValue() {
+ return value;
+ }
+
+ /** {@inheritDoc} */
+ public String getRdfLabel() {
+ return "#ref_" + prefix + value;
+ }
+
+ /** {@inheritDoc} */
+ public boolean equals(Object o) {
+ if (o == this) return true;
+ if (!(o instanceof URIReference)) return false;
+ return uri.equals(((URIReference)o).getURI());
+ }
+
+ /** {@inheritDoc} */
+ public int hashCode() {
+ return uri.hashCode();
+ }
+}
Added: trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/Var.java
===================================================================
--- trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/Var.java (rev 0)
+++ trunk/src/jar/content-rlog/java/org/mulgara/krule/rlog/rdf/Var.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2008 Fedora Commons, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.mulgara.krule.rlog.rdf;
+
+/**
+ * Represents a variable part of a rule.
+ *
+ * @created May 2, 2008
+ * @author Paul Gearon
+ * @copyright © 2008 <a href="http://www.fedora-commons.org/">Fedora Commons</a>
+ * @licence <a href="http://www.opensource.org/licenses/apache2.0.php">Apache License, Version 2.0</a>
+ */
+public class Var implements RDFNode {
+
+ private String name;
+
+ public Var(String name) {
+ this.name = name;
+ }
+
+ /** This node can represent anything, depending on context. */
+ public boolean isVariable() { return true; }
+
+ /** @see org.mulgara.krule.rlog.rdf.RDFNode#isReference() */
+ public boolean isReference() { return false; }
+
+ /** The name of the variable */
+ public String getName() { return name; }
+
+ /** {@inheritDoc} */
+ public String getRdfLabel() {
+ return "#var_" + name;
+ }
+
+ /** {@inheritDoc} */
+ public String toString() {
+ return "v(" + name + ")";
+ }
+
+ /** {@inheritDoc} */
+ public boolean equals(Object o) {
+ if (!(o instanceof Var)) return false;
+ return name.equals(((Var)o).name);
+ }
+
+ /** {@inheritDoc} */
+ public int hashCode() {
+ return name.hashCode() + 1;
+ }
+}
Added: trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/ParseException.java
===================================================================
--- trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/ParseException.java (rev 0)
+++ trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/ParseException.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,195 @@
+/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 3.0 */
+package org.mulgara.krule.rlog;
+
+/**
+ * This exception is thrown when parse errors are encountered.
+ * You can explicitly create objects of this exception type by
+ * calling the method generateParseException in the generated
+ * parser.
+ *
+ * You can modify this class to customize your error reporting
+ * mechanisms so long as you retain the public fields.
+ */
+public class ParseException extends Exception {
+
+ /** Generated serialization ID */
+ private static final long serialVersionUID = -136444386298670642L;
+
+ /**
+ * This constructor is used by the method "generateParseException"
+ * in the generated parser. Calling this constructor generates
+ * a new object of this type with the fields "currentToken",
+ * "expectedTokenSequences", and "tokenImage" set. The boolean
+ * flag "specialConstructor" is also set to true to indicate that
+ * this constructor was used to create this object.
+ * This constructor calls its super class with the empty string
+ * to force the "toString" method of parent class "Throwable" to
+ * print the error message in the form:
+ * ParseException: <result of getMessage>
+ */
+ public ParseException(Token currentTokenVal,
+ int[][] expectedTokenSequencesVal,
+ String[] tokenImageVal
+ )
+ {
+ super("");
+ specialConstructor = true;
+ currentToken = currentTokenVal;
+ expectedTokenSequences = expectedTokenSequencesVal;
+ tokenImage = tokenImageVal;
+ }
+
+ /**
+ * The following constructors are for use by you for whatever
+ * purpose you can think of. Constructing the exception in this
+ * manner makes the exception behave in the normal way - i.e., as
+ * documented in the class "Throwable". The fields "errorToken",
+ * "expectedTokenSequences", and "tokenImage" do not contain
+ * relevant information. The JavaCC generated code does not use
+ * these constructors.
+ */
+
+ public ParseException() {
+ super();
+ specialConstructor = false;
+ }
+
+ public ParseException(String message) {
+ super(message);
+ specialConstructor = false;
+ }
+
+ /**
+ * This variable determines which constructor was used to create
+ * this object and thereby affects the semantics of the
+ * "getMessage" method (see below).
+ */
+ protected boolean specialConstructor;
+
+ /**
+ * This is the last token that has been consumed successfully. If
+ * this object has been created due to a parse error, the token
+ * followng this token will (therefore) be the first error token.
+ */
+ public Token currentToken;
+
+ /**
+ * Each entry in this array is an array of integers. Each array
+ * of integers represents a sequence of tokens (by their ordinal
+ * values) that is expected at this point of the parse.
+ */
+ public int[][] expectedTokenSequences;
+
+ /**
+ * This is a reference to the "tokenImage" array of the generated
+ * parser within which the parse error occurred. This array is
+ * defined in the generated ...Constants interface.
+ */
+ public String[] tokenImage;
+
+ /**
+ * This method has the standard behavior when this object has been
+ * created using the standard constructors. Otherwise, it uses
+ * "currentToken" and "expectedTokenSequences" to generate a parse
+ * error message and returns it. If this object has been created
+ * due to a parse error, and you do not catch it (it gets thrown
+ * from the parser), then this method is called during the printing
+ * of the final stack trace, and hence the correct error message
+ * gets displayed.
+ */
+ public String getMessage() {
+ if (!specialConstructor) {
+ return super.getMessage();
+ }
+ StringBuffer expected = new StringBuffer();
+ int maxSize = 0;
+ for (int i = 0; i < expectedTokenSequences.length; i++) {
+ if (maxSize < expectedTokenSequences[i].length) {
+ maxSize = expectedTokenSequences[i].length;
+ }
+ for (int j = 0; j < expectedTokenSequences[i].length; j++) {
+ expected.append(tokenImage[expectedTokenSequences[i][j]]).append(" ");
+ }
+ if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
+ expected.append("...");
+ }
+ expected.append(eol).append(" ");
+ }
+ String retval = "Encountered \"";
+ Token tok = currentToken.next;
+ for (int i = 0; i < maxSize; i++) {
+ if (i != 0) retval += " ";
+ if (tok.kind == 0) {
+ retval += tokenImage[0];
+ break;
+ }
+ retval += add_escapes(tok.image);
+ tok = tok.next;
+ }
+ retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
+ retval += "." + eol;
+ if (expectedTokenSequences.length == 1) {
+ retval += "Was expecting:" + eol + " ";
+ } else {
+ retval += "Was expecting one of:" + eol + " ";
+ }
+ retval += expected.toString();
+ return retval;
+ }
+
+ /**
+ * The end of line string for this machine.
+ */
+ protected String eol = System.getProperty("line.separator", "\n");
+
+ /**
+ * Used to convert raw characters to their escaped version
+ * when these raw version cannot be used as part of an ASCII
+ * string literal.
+ */
+ protected String add_escapes(String str) {
+ StringBuffer retval = new StringBuffer();
+ char ch;
+ for (int i = 0; i < str.length(); i++) {
+ switch (str.charAt(i))
+ {
+ case 0 :
+ continue;
+ case '\b':
+ retval.append("\\b");
+ continue;
+ case '\t':
+ retval.append("\\t");
+ continue;
+ case '\n':
+ retval.append("\\n");
+ continue;
+ case '\f':
+ retval.append("\\f");
+ continue;
+ case '\r':
+ retval.append("\\r");
+ continue;
+ case '\"':
+ retval.append("\\\"");
+ continue;
+ case '\'':
+ retval.append("\\\'");
+ continue;
+ case '\\':
+ retval.append("\\\\");
+ continue;
+ default:
+ if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
+ String s = "0000" + Integer.toString(ch, 16);
+ retval.append("\\u" + s.substring(s.length() - 4, s.length()));
+ } else {
+ retval.append(ch);
+ }
+ continue;
+ }
+ }
+ return retval.toString();
+ }
+
+}
Added: trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/RlogParser.java
===================================================================
--- trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/RlogParser.java (rev 0)
+++ trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/RlogParser.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,844 @@
+/* Generated By:JavaCC: Do not edit this line. RlogParser.java */
+package org.mulgara.krule.rlog;
+
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.mulgara.krule.rlog.ast.Axiom;
+import org.mulgara.krule.rlog.ast.BPredicate;
+import org.mulgara.krule.rlog.ast.BPredicateLiteral;
+import org.mulgara.krule.rlog.ast.IntegerLiteral;
+import org.mulgara.krule.rlog.ast.InvertedPredicate;
+import org.mulgara.krule.rlog.ast.Predicate;
+import org.mulgara.krule.rlog.ast.PredicateParam;
+import org.mulgara.krule.rlog.ast.Rule;
+import org.mulgara.krule.rlog.ast.Statement;
+import org.mulgara.krule.rlog.ast.StringLiteral;
+import org.mulgara.krule.rlog.ast.TypeLiteral;
+import org.mulgara.krule.rlog.ast.TypeStatement;
+import org.mulgara.krule.rlog.ast.Variable;
+import org.mulgara.util.StringUtil;
+
+public class RlogParser implements RlogParserConstants {
+
+ public static List<Statement> parse(String query) throws ParseException {
+ RlogParser parser = new RlogParser(new StringReader(query));
+ return parser.statements();
+ }
+
+ private static final String unq(String str) {
+ return str.substring(1, str.length() - 1);
+ }
+
+/* statements ::= (statement)+ */
+ final public List<Statement> statements() throws ParseException {
+ List<Statement> sList = new ArrayList<Statement>();
+ Statement s;
+ label_1:
+ while (true) {
+ s = statement();
+ sList.add(s);
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case IMPLIED_BY:
+ case INVERT:
+ case IDENTIFIER:
+ case VARIABLE:
+ case TYPE:
+ case DOMAIN:
+ ;
+ break;
+ default:
+ jj_la1[0] = jj_gen;
+ break label_1;
+ }
+ }
+ {if (true) return sList;}
+ throw new Error("Missing return statement in function");
+ }
+
+/* statement ::= axiom | rule */
+ final public Statement statement() throws ParseException {
+ Statement s;
+ if (jj_2_1(10)) {
+ s = axiom();
+ } else {
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case IMPLIED_BY:
+ case INVERT:
+ case IDENTIFIER:
+ case VARIABLE:
+ case TYPE:
+ case DOMAIN:
+ s = rule();
+ break;
+ default:
+ jj_la1[1] = jj_gen;
+ jj_consume_token(-1);
+ throw new ParseException();
+ }
+ }
+ {if (true) return s;}
+ throw new Error("Missing return statement in function");
+ }
+
+/* axiom ::= predicate DOT */
+ final public Axiom axiom() throws ParseException {
+ Predicate p;
+ p = predicate();
+ jj_consume_token(DOT);
+ {if (true) return new Axiom(p);}
+ throw new Error("Missing return statement in function");
+ }
+
+/* rule ::= IMPLIED_BY predicate_list DOT | predicate IMPLIED_BY predicate_list DOT */
+ final public Rule rule() throws ParseException {
+ List<Predicate> body;
+ Predicate head;
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case IMPLIED_BY:
+ jj_consume_token(IMPLIED_BY);
+ body = predicateList();
+ jj_consume_token(DOT);
+ {if (true) return new Rule(body);}
+ break;
+ case INVERT:
+ case IDENTIFIER:
+ case VARIABLE:
+ case TYPE:
+ case DOMAIN:
+ head = predicate();
+ jj_consume_token(IMPLIED_BY);
+ body = predicateList();
+ jj_consume_token(DOT);
+ {if (true) return new Rule(head, body);}
+ break;
+ default:
+ jj_la1[2] = jj_gen;
+ jj_consume_token(-1);
+ throw new ParseException();
+ }
+ throw new Error("Missing return statement in function");
+ }
+
+/* predicate ::= type_decl | binary_predicate | INVERT predicate */
+ final public Predicate predicate() throws ParseException {
+ Predicate p;
+ if (jj_2_2(5)) {
+ p = typeDecl();
+ {if (true) return p;}
+ } else {
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case IDENTIFIER:
+ case VARIABLE:
+ case DOMAIN:
+ p = binaryPredicate();
+ {if (true) return p;}
+ break;
+ case INVERT:
+ jj_consume_token(INVERT);
+ p = predicate();
+ {if (true) return new InvertedPredicate(p);}
+ break;
+ default:
+ jj_la1[3] = jj_gen;
+ jj_consume_token(-1);
+ throw new ParseException();
+ }
+ }
+ throw new Error("Missing return statement in function");
+ }
+
+/* type_decl ::= dom? TYPE LPAR parameter_elt RPAR | VARIABLE LPAREN parameter_elt RPAREN */
+ final public TypeStatement typeDecl() throws ParseException {
+ Token t;
+ PredicateParam p;
+ String d = null;
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case TYPE:
+ case DOMAIN:
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case DOMAIN:
+ d = dom();
+ break;
+ default:
+ jj_la1[4] = jj_gen;
+ ;
+ }
+ t = jj_consume_token(TYPE);
+ jj_consume_token(LPAR);
+ p = parameterElt();
+ jj_consume_token(RPAR);
+ {if (true) return new TypeStatement(new TypeLiteral(d, t.image), p);}
+ break;
+ case VARIABLE:
+ t = jj_consume_token(VARIABLE);
+ jj_consume_token(LPAR);
+ p = parameterElt();
+ jj_consume_token(RPAR);
+ {if (true) return new TypeStatement(new Variable(t.image), p);}
+ break;
+ default:
+ jj_la1[5] = jj_gen;
+ jj_consume_token(-1);
+ throw new ParseException();
+ }
+ throw new Error("Missing return statement in function");
+ }
+
+/* binary_predicate ::= dom? IDENTIFIER LPAR parameter_elt COMMA parameter RPAR
+ | VARIABLE LPAR parameter_elt COMMA parameter RPAR */
+ final public BPredicate binaryPredicate() throws ParseException {
+ String d = null;
+ Token pred;
+ PredicateParam left, right;
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case IDENTIFIER:
+ case DOMAIN:
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case DOMAIN:
+ d = dom();
+ break;
+ default:
+ jj_la1[6] = jj_gen;
+ ;
+ }
+ pred = jj_consume_token(IDENTIFIER);
+ jj_consume_token(LPAR);
+ left = parameterElt();
+ jj_consume_token(COMMA);
+ right = parameter();
+ jj_consume_token(RPAR);
+ {if (true) return new BPredicate(new BPredicateLiteral(d, pred.image), left, right);}
+ break;
+ case VARIABLE:
+ pred = jj_consume_token(VARIABLE);
+ jj_consume_token(LPAR);
+ left = parameterElt();
+ jj_consume_token(COMMA);
+ right = parameter();
+ jj_consume_token(RPAR);
+ {if (true) return new BPredicate(new Variable(pred.image), left, right);}
+ break;
+ default:
+ jj_la1[7] = jj_gen;
+ jj_consume_token(-1);
+ throw new ParseException();
+ }
+ throw new Error("Missing return statement in function");
+ }
+
+/* parameter_elt ::= dom? IDENTIFIER | dom? TYPE | VARIABLE */
+ final public PredicateParam parameterElt() throws ParseException {
+ String d = null;
+ Token t;
+ PredicateParam p;
+ if (jj_2_3(2)) {
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case DOMAIN:
+ d = dom();
+ break;
+ default:
+ jj_la1[8] = jj_gen;
+ ;
+ }
+ t = jj_consume_token(IDENTIFIER);
+ {if (true) return new BPredicateLiteral(d, t.image);}
+ } else {
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case TYPE:
+ case DOMAIN:
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case DOMAIN:
+ d = dom();
+ break;
+ default:
+ jj_la1[9] = jj_gen;
+ ;
+ }
+ t = jj_consume_token(TYPE);
+ {if (true) return new TypeLiteral(d, t.image);}
+ break;
+ case VARIABLE:
+ t = jj_consume_token(VARIABLE);
+ {if (true) return new Variable(t.image);}
+ break;
+ default:
+ jj_la1[10] = jj_gen;
+ jj_consume_token(-1);
+ throw new ParseException();
+ }
+ }
+ throw new Error("Missing return statement in function");
+ }
+
+/* parameter ::= VARIABLE | dom? IDENTIFIER | dom? TYPE | literal */
+ final public PredicateParam parameter() throws ParseException {
+ PredicateParam p;
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case IDENTIFIER:
+ case VARIABLE:
+ case TYPE:
+ case DOMAIN:
+ p = parameterElt();
+ {if (true) return p;}
+ break;
+ case STRING_LITERAL:
+ case INTEGER_LITERAL:
+ p = literal();
+ {if (true) return p;}
+ break;
+ default:
+ jj_la1[11] = jj_gen;
+ jj_consume_token(-1);
+ throw new ParseException();
+ }
+ throw new Error("Missing return statement in function");
+ }
+
+/* literal ::= STRING_LITERAL | INTEGER_LITERAL */
+ final public PredicateParam literal() throws ParseException {
+ Token t;
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case INTEGER_LITERAL:
+ t = jj_consume_token(INTEGER_LITERAL);
+ {if (true) return new IntegerLiteral(t.image);}
+ break;
+ case STRING_LITERAL:
+ t = jj_consume_token(STRING_LITERAL);
+ {if (true) return new StringLiteral(StringUtil.unescapeJavaString(unq(t.image)));}
+ break;
+ default:
+ jj_la1[12] = jj_gen;
+ jj_consume_token(-1);
+ throw new ParseException();
+ }
+ throw new Error("Missing return statement in function");
+ }
+
+/* predicate_list ::= predicate (COMMA predicate)* */
+ final public List<Predicate> predicateList() throws ParseException {
+ List<Predicate> predicates = new ArrayList<Predicate>();
+ Predicate p;
+ p = predicate();
+ predicates.add(p);
+ label_2:
+ while (true) {
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case COMMA:
+ ;
+ break;
+ default:
+ jj_la1[13] = jj_gen;
+ break label_2;
+ }
+ jj_consume_token(COMMA);
+ p = predicate();
+ predicates.add(p);
+ }
+ {if (true) return predicates;}
+ throw new Error("Missing return statement in function");
+ }
+
+/* dom ::= DOMAIN */
+ final public String dom() throws ParseException {
+ Token d;
+ d = jj_consume_token(DOMAIN);
+ {if (true) return d.image.substring(0, d.image.length() - 1);}
+ throw new Error("Missing return statement in function");
+ }
+
+ final private boolean jj_2_1(int xla) {
+ jj_la = xla; jj_lastpos = jj_scanpos = token;
+ try { return !jj_3_1(); }
+ catch(LookaheadSuccess ls) { return true; }
+ finally { jj_save(0, xla); }
+ }
+
+ final private boolean jj_2_2(int xla) {
+ jj_la = xla; jj_lastpos = jj_scanpos = token;
+ try { return !jj_3_2(); }
+ catch(LookaheadSuccess ls) { return true; }
+ finally { jj_save(1, xla); }
+ }
+
+ final private boolean jj_2_3(int xla) {
+ jj_la = xla; jj_lastpos = jj_scanpos = token;
+ try { return !jj_3_3(); }
+ catch(LookaheadSuccess ls) { return true; }
+ finally { jj_save(2, xla); }
+ }
+
+ final private boolean jj_3R_6() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3_2()) {
+ jj_scanpos = xsp;
+ if (jj_3R_10()) {
+ jj_scanpos = xsp;
+ if (jj_3R_11()) return true;
+ }
+ }
+ return false;
+ }
+
+ final private boolean jj_3_2() {
+ if (jj_3R_4()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_19() {
+ if (jj_3R_9()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_16() {
+ if (jj_scan_token(VARIABLE)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_5() {
+ if (jj_3R_9()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_15() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_19()) jj_scanpos = xsp;
+ if (jj_scan_token(TYPE)) return true;
+ return false;
+ }
+
+ final private boolean jj_3_3() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_5()) jj_scanpos = xsp;
+ if (jj_scan_token(IDENTIFIER)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_13() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3_3()) {
+ jj_scanpos = xsp;
+ if (jj_3R_15()) {
+ jj_scanpos = xsp;
+ if (jj_3R_16()) return true;
+ }
+ }
+ return false;
+ }
+
+ final private boolean jj_3R_9() {
+ if (jj_scan_token(DOMAIN)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_3() {
+ if (jj_3R_6()) return true;
+ if (jj_scan_token(DOT)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_18() {
+ if (jj_scan_token(VARIABLE)) return true;
+ if (jj_scan_token(LPAR)) return true;
+ if (jj_3R_13()) return true;
+ if (jj_scan_token(COMMA)) return true;
+ if (jj_3R_21()) return true;
+ if (jj_scan_token(RPAR)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_20() {
+ if (jj_3R_9()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_17() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_20()) jj_scanpos = xsp;
+ if (jj_scan_token(IDENTIFIER)) return true;
+ if (jj_scan_token(LPAR)) return true;
+ if (jj_3R_13()) return true;
+ if (jj_scan_token(COMMA)) return true;
+ if (jj_3R_21()) return true;
+ if (jj_scan_token(RPAR)) return true;
+ return false;
+ }
+
+ final private boolean jj_3_1() {
+ if (jj_3R_3()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_14() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_17()) {
+ jj_scanpos = xsp;
+ if (jj_3R_18()) return true;
+ }
+ return false;
+ }
+
+ final private boolean jj_3R_8() {
+ if (jj_scan_token(VARIABLE)) return true;
+ if (jj_scan_token(LPAR)) return true;
+ if (jj_3R_13()) return true;
+ if (jj_scan_token(RPAR)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_26() {
+ if (jj_scan_token(STRING_LITERAL)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_25() {
+ if (jj_scan_token(INTEGER_LITERAL)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_24() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_25()) {
+ jj_scanpos = xsp;
+ if (jj_3R_26()) return true;
+ }
+ return false;
+ }
+
+ final private boolean jj_3R_12() {
+ if (jj_3R_9()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_7() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_12()) jj_scanpos = xsp;
+ if (jj_scan_token(TYPE)) return true;
+ if (jj_scan_token(LPAR)) return true;
+ if (jj_3R_13()) return true;
+ if (jj_scan_token(RPAR)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_4() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_7()) {
+ jj_scanpos = xsp;
+ if (jj_3R_8()) return true;
+ }
+ return false;
+ }
+
+ final private boolean jj_3R_23() {
+ if (jj_3R_24()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_22() {
+ if (jj_3R_13()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_21() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_22()) {
+ jj_scanpos = xsp;
+ if (jj_3R_23()) return true;
+ }
+ return false;
+ }
+
+ final private boolean jj_3R_11() {
+ if (jj_scan_token(INVERT)) return true;
+ if (jj_3R_6()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_10() {
+ if (jj_3R_14()) return true;
+ return false;
+ }
+
+ public RlogParserTokenManager token_source;
+ SimpleCharStream jj_input_stream;
+ public Token token, jj_nt;
+ private int jj_ntk;
+ private Token jj_scanpos, jj_lastpos;
+ private int jj_la;
+ public boolean lookingAhead = false;
+ private boolean jj_semLA;
+ private int jj_gen;
+ final private int[] jj_la1 = new int[14];
+ static private int[] jj_la1_0;
+ static {
+ jj_la1_0();
+ }
+ private static void jj_la1_0() {
+ jj_la1_0 = new int[] {0x1703000,0x1703000,0x1703000,0x1302000,0x1000000,0x1600000,0x1000000,0x1300000,0x1000000,0x1000000,0x1600000,0x1f80000,0x880000,0x10000,};
+ }
+ final private JJCalls[] jj_2_rtns = new JJCalls[3];
+ private boolean jj_rescan = false;
+ private int jj_gc = 0;
+
+ public RlogParser(java.io.InputStream stream) {
+ this(stream, null);
+ }
+ public RlogParser(java.io.InputStream stream, String encoding) {
+ try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
+ token_source = new RlogParserTokenManager(jj_input_stream);
+ token = new Token();
+ jj_ntk = -1;
+ jj_gen = 0;
+ for (int i = 0; i < 14; i++) jj_la1[i] = -1;
+ for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
+ }
+
+ public void ReInit(java.io.InputStream stream) {
+ ReInit(stream, null);
+ }
+ public void ReInit(java.io.InputStream stream, String encoding) {
+ try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
+ token_source.ReInit(jj_input_stream);
+ token = new Token();
+ jj_ntk = -1;
+ jj_gen = 0;
+ for (int i = 0; i < 14; i++) jj_la1[i] = -1;
+ for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
+ }
+
+ public RlogParser(java.io.Reader stream) {
+ jj_input_stream = new SimpleCharStream(stream, 1, 1);
+ token_source = new RlogParserTokenManager(jj_input_stream);
+ token = new Token();
+ jj_ntk = -1;
+ jj_gen = 0;
+ for (int i = 0; i < 14; i++) jj_la1[i] = -1;
+ for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
+ }
+
+ public void ReInit(java.io.Reader stream) {
+ jj_input_stream.ReInit(stream, 1, 1);
+ token_source.ReInit(jj_input_stream);
+ token = new Token();
+ jj_ntk = -1;
+ jj_gen = 0;
+ for (int i = 0; i < 14; i++) jj_la1[i] = -1;
+ for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
+ }
+
+ public RlogParser(RlogParserTokenManager tm) {
+ token_source = tm;
+ token = new Token();
+ jj_ntk = -1;
+ jj_gen = 0;
+ for (int i = 0; i < 14; i++) jj_la1[i] = -1;
+ for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
+ }
+
+ public void ReInit(RlogParserTokenManager tm) {
+ token_source = tm;
+ token = new Token();
+ jj_ntk = -1;
+ jj_gen = 0;
+ for (int i = 0; i < 14; i++) jj_la1[i] = -1;
+ for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
+ }
+
+ final private Token jj_consume_token(int kind) throws ParseException {
+ Token oldToken;
+ if ((oldToken = token).next != null) token = token.next;
+ else token = token.next = token_source.getNextToken();
+ jj_ntk = -1;
+ if (token.kind == kind) {
+ jj_gen++;
+ if (++jj_gc > 100) {
+ jj_gc = 0;
+ for (int i = 0; i < jj_2_rtns.length; i++) {
+ JJCalls c = jj_2_rtns[i];
+ while (c != null) {
+ if (c.gen < jj_gen) c.first = null;
+ c = c.next;
+ }
+ }
+ }
+ return token;
+ }
+ token = oldToken;
+ jj_kind = kind;
+ throw generateParseException();
+ }
+
+ static private final class LookaheadSuccess extends java.lang.Error { }
+ final private LookaheadSuccess jj_ls = new LookaheadSuccess();
+ final private boolean jj_scan_token(int kind) {
+ if (jj_scanpos == jj_lastpos) {
+ jj_la--;
+ if (jj_scanpos.next == null) {
+ jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken();
+ } else {
+ jj_lastpos = jj_scanpos = jj_scanpos.next;
+ }
+ } else {
+ jj_scanpos = jj_scanpos.next;
+ }
+ if (jj_rescan) {
+ int i = 0; Token tok = token;
+ while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; }
+ if (tok != null) jj_add_error_token(kind, i);
+ }
+ if (jj_scanpos.kind != kind) return true;
+ if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls;
+ return false;
+ }
+
+ final public Token getNextToken() {
+ if (token.next != null) token = token.next;
+ else token = token.next = token_source.getNextToken();
+ jj_ntk = -1;
+ jj_gen++;
+ return token;
+ }
+
+ final public Token getToken(int index) {
+ Token t = lookingAhead ? jj_scanpos : token;
+ for (int i = 0; i < index; i++) {
+ if (t.next != null) t = t.next;
+ else t = t.next = token_source.getNextToken();
+ }
+ return t;
+ }
+
+ final private int jj_ntk() {
+ if ((jj_nt=token.next) == null)
+ return (jj_ntk = (token.next=token_source.getNextToken()).kind);
+ else
+ return (jj_ntk = jj_nt.kind);
+ }
+
+ private java.util.Vector<int[]> jj_expentries = new java.util.Vector<int[]>();
+ private int[] jj_expentry;
+ private int jj_kind = -1;
+ private int[] jj_lasttokens = new int[100];
+ private int jj_endpos;
+
+ private void jj_add_error_token(int kind, int pos) {
+ if (pos >= 100) return;
+ if (pos == jj_endpos + 1) {
+ jj_lasttokens[jj_endpos++] = kind;
+ } else if (jj_endpos != 0) {
+ jj_expentry = new int[jj_endpos];
+ for (int i = 0; i < jj_endpos; i++) {
+ jj_expentry[i] = jj_lasttokens[i];
+ }
+ boolean exists = false;
+ for (java.util.Enumeration e = jj_expentries.elements(); e.hasMoreElements();) {
+ int[] oldentry = (int[])(e.nextElement());
+ if (oldentry.length == jj_expentry.length) {
+ exists = true;
+ for (int i = 0; i < jj_expentry.length; i++) {
+ if (oldentry[i] != jj_expentry[i]) {
+ exists = false;
+ break;
+ }
+ }
+ if (exists) break;
+ }
+ }
+ if (!exists) jj_expentries.addElement(jj_expentry);
+ if (pos != 0) jj_lasttokens[(jj_endpos = pos) - 1] = kind;
+ }
+ }
+
+ public ParseException generateParseException() {
+ jj_expentries.removeAllElements();
+ boolean[] la1tokens = new boolean[25];
+ for (int i = 0; i < 25; i++) {
+ la1tokens[i] = false;
+ }
+ if (jj_kind >= 0) {
+ la1tokens[jj_kind] = true;
+ jj_kind = -1;
+ }
+ for (int i = 0; i < 14; i++) {
+ if (jj_la1[i] == jj_gen) {
+ for (int j = 0; j < 32; j++) {
+ if ((jj_la1_0[i] & (1<<j)) != 0) {
+ la1tokens[j] = true;
+ }
+ }
+ }
+ }
+ for (int i = 0; i < 25; i++) {
+ if (la1tokens[i]) {
+ jj_expentry = new int[1];
+ jj_expentry[0] = i;
+ jj_expentries.addElement(jj_expentry);
+ }
+ }
+ jj_endpos = 0;
+ jj_rescan_token();
+ jj_add_error_token(0, 0);
+ int[][] exptokseq = new int[jj_expentries.size()][];
+ for (int i = 0; i < jj_expentries.size(); i++) {
+ exptokseq[i] = (int[])jj_expentries.elementAt(i);
+ }
+ return new ParseException(token, exptokseq, tokenImage);
+ }
+
+ final public void enable_tracing() {
+ }
+
+ final public void disable_tracing() {
+ }
+
+ final private void jj_rescan_token() {
+ jj_rescan = true;
+ for (int i = 0; i < 3; i++) {
+ try {
+ JJCalls p = jj_2_rtns[i];
+ do {
+ if (p.gen > jj_gen) {
+ jj_la = p.arg; jj_lastpos = jj_scanpos = p.first;
+ switch (i) {
+ case 0: jj_3_1(); break;
+ case 1: jj_3_2(); break;
+ case 2: jj_3_3(); break;
+ }
+ }
+ p = p.next;
+ } while (p != null);
+ } catch(LookaheadSuccess ls) { }
+ }
+ jj_rescan = false;
+ }
+
+ final private void jj_save(int index, int xla) {
+ JJCalls p = jj_2_rtns[index];
+ while (p.gen > jj_gen) {
+ if (p.next == null) { p = p.next = new JJCalls(); break; }
+ p = p.next;
+ }
+ p.gen = jj_gen + xla - jj_la; p.first = token; p.arg = xla;
+ }
+
+ static final class JJCalls {
+ int gen;
+ Token first;
+ int arg;
+ JJCalls next;
+ }
+
+}
Added: trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/RlogParser.jj
===================================================================
--- trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/RlogParser.jj (rev 0)
+++ trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/RlogParser.jj 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,217 @@
+options
+{
+ STATIC=false;
+ UNICODE_INPUT=true;
+ IGNORE_CASE=false;
+ JAVA_UNICODE_ESCAPE=false;
+ DEBUG_PARSER=false;
+ JDK_VERSION="1.5";
+}
+
+PARSER_BEGIN(RlogParser)
+package org.mulgara.krule.rlog;
+
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.mulgara.krule.rlog.ast.Axiom;
+import org.mulgara.krule.rlog.ast.BPredicate;
+import org.mulgara.krule.rlog.ast.BPredicateLiteral;
+import org.mulgara.krule.rlog.ast.IntegerLiteral;
+import org.mulgara.krule.rlog.ast.InvertedPredicate;
+import org.mulgara.krule.rlog.ast.Predicate;
+import org.mulgara.krule.rlog.ast.PredicateParam;
+import org.mulgara.krule.rlog.ast.Rule;
+import org.mulgara.krule.rlog.ast.Statement;
+import org.mulgara.krule.rlog.ast.StringLiteral;
+import org.mulgara.krule.rlog.ast.TypeLiteral;
+import org.mulgara.krule.rlog.ast.TypeStatement;
+import org.mulgara.krule.rlog.ast.Variable;
+import org.mulgara.util.StringUtil;
+
+public class RlogParser {
+
+ public static List<Statement> parse(String query) throws ParseException {
+ RlogParser parser = new RlogParser(new StringReader(query));
+ return parser.statements();
+ }
+
+ private static final String unq(String str) {
+ return str.substring(1, str.length() - 1);
+ }
+}
+
+PARSER_END(RlogParser)
+
+SKIP : { "\t" | "\n" | "\r" | "\f" | " " }
+
+MORE : { "--" : IN_COMMENT }
+
+<IN_COMMENT>
+SPECIAL_TOKEN : { < COMMENT: (~["\r","\n"])* > : DEFAULT }
+
+TOKEN :
+{
+ < #LOWER_CASE_LETTER: ["a"-"z"] >
+ | < #UPPER_CASE_LETTER: ["A"-"Z"] >
+ | < #DIGIT: ["0"-"9"] >
+ | < #J_LETTER_DIGIT: ["0"-"9", "a"-"z", "A"-"Z", "_"] >
+}
+
+TOKEN :
+{
+ < IMPLIED_BY: ":-" >
+ | < INVERT: "~" >
+ | < NEGATE: "-" >
+ | < DOT: "." >
+ | < COMMA: "," >
+ | < LPAR: "(" >
+ | < RPAR: ")" >
+}
+
+TOKEN :
+{
+ < STRING_LITERAL: "\""
+ ( (~["\"","\\","\n","\r"])
+ | ("\\"
+ ( ["n","t","b","r","f","\\","'","\""]
+ | ["0"-"7"] ( ["0"-"7"] )?
+ | ["0"-"3"] ["0"-"7"] ["0"-"7"]
+ )
+ )
+ )*
+ "\""
+ >
+}
+
+TOKEN :
+{
+ < IDENTIFIER : <LOWER_CASE_LETTER> (<J_LETTER_DIGIT>)* >
+ | < VARIABLE : <UPPER_CASE_LETTER> >
+ | < TYPE : <UPPER_CASE_LETTER> (<J_LETTER_DIGIT>)+ >
+ | < INTEGER_LITERAL : ("0" | ["1"-"9"] (<DIGIT>)*) >
+ | < DOMAIN : (<LOWER_CASE_LETTER>)+ ":" >
+}
+
+
+/* statements ::= (statement)+ */
+List<Statement> statements() : {
+ List<Statement> sList = new ArrayList<Statement>();
+ Statement s;
+} {
+ (s=statement() { sList.add(s); } )+ { return sList; }
+}
+
+
+/* statement ::= axiom | rule */
+Statement statement() : {
+ Statement s;
+} {
+ ( LOOKAHEAD(10) s=axiom() | s=rule() ) { return s; }
+}
+
+
+/* axiom ::= predicate DOT */
+Axiom axiom() : {
+ Predicate p;
+} {
+ p=predicate() <DOT> { return new Axiom(p); }
+}
+
+/* rule ::= IMPLIED_BY predicate_list DOT | predicate IMPLIED_BY predicate_list DOT */
+Rule rule() : {
+ List<Predicate> body;
+ Predicate head;
+} {
+ <IMPLIED_BY> body=predicateList() <DOT> { return new Rule(body); }
+| head=predicate() <IMPLIED_BY> body=predicateList() <DOT> { return new Rule(head, body); }
+}
+
+/* predicate ::= type_decl | binary_predicate | INVERT predicate */
+Predicate predicate() : {
+ Predicate p;
+} {
+ LOOKAHEAD(5)
+ p=typeDecl() { return p; }
+| p=binaryPredicate() { return p; }
+| <INVERT> p=predicate() { return new InvertedPredicate(p); }
+}
+
+/* type_decl ::= dom? TYPE LPAR parameter_elt RPAR | VARIABLE LPAREN parameter_elt RPAREN */
+TypeStatement typeDecl() : {
+ Token t;
+ PredicateParam p;
+ String d = null;
+} {
+ (d=dom())? t=<TYPE> <LPAR> p=parameterElt() <RPAR> {
+ return new TypeStatement(new TypeLiteral(d, t.image), p);
+ }
+| t=<VARIABLE> <LPAR> p=parameterElt() <RPAR> { return new TypeStatement(new Variable(t.image), p); }
+}
+
+/* binary_predicate ::= dom? IDENTIFIER LPAR parameter_elt COMMA parameter RPAR
+ | VARIABLE LPAR parameter_elt COMMA parameter RPAR */
+BPredicate binaryPredicate() : {
+ String d = null;
+ Token pred;
+ PredicateParam left, right;
+} {
+ (d=dom())? pred=<IDENTIFIER> <LPAR> left=parameterElt() <COMMA> right=parameter() <RPAR> {
+ return new BPredicate(new BPredicateLiteral(d, pred.image), left, right);
+ }
+| pred=<VARIABLE> <LPAR> left=parameterElt() <COMMA> right=parameter() <RPAR> {
+ return new BPredicate(new Variable(pred.image), left, right);
+ }
+}
+
+
+/* parameter_elt ::= dom? IDENTIFIER | dom? TYPE | VARIABLE */
+PredicateParam parameterElt() : {
+ String d = null;
+ Token t;
+ PredicateParam p;
+} {
+ LOOKAHEAD(2)
+ (d=dom())? t=<IDENTIFIER> { return new BPredicateLiteral(d, t.image); }
+| (d=dom())? t=<TYPE> { return new TypeLiteral(d, t.image); }
+| t=<VARIABLE> { return new Variable(t.image); }
+}
+
+
+/* parameter ::= VARIABLE | dom? IDENTIFIER | dom? TYPE | literal */
+PredicateParam parameter() : {
+ PredicateParam p;
+} {
+ p=parameterElt() { return p; }
+| p=literal() { return p; }
+}
+
+
+/* literal ::= STRING_LITERAL | INTEGER_LITERAL */
+PredicateParam literal() : {
+ Token t;
+} {
+ t=<INTEGER_LITERAL> { return new IntegerLiteral(t.image); }
+| t=<STRING_LITERAL> { return new StringLiteral(StringUtil.unescapeJavaString(unq(t.image))); }
+}
+
+
+/* predicate_list ::= predicate (COMMA predicate)* */
+List<Predicate> predicateList() : {
+ List<Predicate> predicates = new ArrayList<Predicate>();
+ Predicate p;
+} {
+ p=predicate() { predicates.add(p); }
+ (<COMMA> p=predicate() { predicates.add(p); })*
+ { return predicates; }
+}
+
+/* dom ::= DOMAIN */
+String dom() : {
+ Token d;
+} {
+ d=<DOMAIN> { return d.image.substring(0, d.image.length() - 1); }
+}
Added: trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/RlogParserConstants.java
===================================================================
--- trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/RlogParserConstants.java (rev 0)
+++ trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/RlogParserConstants.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,57 @@
+/* Generated By:JavaCC: Do not edit this line. RlogParserConstants.java */
+package org.mulgara.krule.rlog;
+
+public interface RlogParserConstants {
+
+ int EOF = 0;
+ int COMMENT = 7;
+ int LOWER_CASE_LETTER = 8;
+ int UPPER_CASE_LETTER = 9;
+ int DIGIT = 10;
+ int J_LETTER_DIGIT = 11;
+ int IMPLIED_BY = 12;
+ int INVERT = 13;
+ int NEGATE = 14;
+ int DOT = 15;
+ int COMMA = 16;
+ int LPAR = 17;
+ int RPAR = 18;
+ int STRING_LITERAL = 19;
+ int IDENTIFIER = 20;
+ int VARIABLE = 21;
+ int TYPE = 22;
+ int INTEGER_LITERAL = 23;
+ int DOMAIN = 24;
+
+ int DEFAULT = 0;
+ int IN_COMMENT = 1;
+
+ String[] tokenImage = {
+ "<EOF>",
+ "\"\\t\"",
+ "\"\\n\"",
+ "\"\\r\"",
+ "\"\\f\"",
+ "\" \"",
+ "\"--\"",
+ "<COMMENT>",
+ "<LOWER_CASE_LETTER>",
+ "<UPPER_CASE_LETTER>",
+ "<DIGIT>",
+ "<J_LETTER_DIGIT>",
+ "\":-\"",
+ "\"~\"",
+ "\"-\"",
+ "\".\"",
+ "\",\"",
+ "\"(\"",
+ "\")\"",
+ "<STRING_LITERAL>",
+ "<IDENTIFIER>",
+ "<VARIABLE>",
+ "<TYPE>",
+ "<INTEGER_LITERAL>",
+ "<DOMAIN>",
+ };
+
+}
Added: trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/RlogParserTokenManager.java
===================================================================
--- trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/RlogParserTokenManager.java (rev 0)
+++ trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/RlogParserTokenManager.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,650 @@
+/* Generated By:JavaCC: Do not edit this line. RlogParserTokenManager.java */
+package org.mulgara.krule.rlog;
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.mulgara.krule.rlog.ast.Axiom;
+import org.mulgara.krule.rlog.ast.BPredicate;
+import org.mulgara.krule.rlog.ast.BPredicateLiteral;
+import org.mulgara.krule.rlog.ast.IntegerLiteral;
+import org.mulgara.krule.rlog.ast.InvertedPredicate;
+import org.mulgara.krule.rlog.ast.Predicate;
+import org.mulgara.krule.rlog.ast.PredicateParam;
+import org.mulgara.krule.rlog.ast.Rule;
+import org.mulgara.krule.rlog.ast.Statement;
+import org.mulgara.krule.rlog.ast.StringLiteral;
+import org.mulgara.krule.rlog.ast.TypeLiteral;
+import org.mulgara.krule.rlog.ast.TypeStatement;
+import org.mulgara.krule.rlog.ast.Variable;
+import org.mulgara.util.StringUtil;
+
+public class RlogParserTokenManager implements RlogParserConstants
+{
+ public java.io.PrintStream debugStream = System.out;
+ public void setDebugStream(java.io.PrintStream ds) { debugStream = ds; }
+private final int jjStopStringLiteralDfa_0(int pos, long active0)
+{
+ switch (pos)
+ {
+ default :
+ return -1;
+ }
+}
+private final int jjStartNfa_0(int pos, long active0)
+{
+ return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0), pos + 1);
+}
+private final int jjStopAtPos(int pos, int kind)
+{
+ jjmatchedKind = kind;
+ jjmatchedPos = pos;
+ return pos + 1;
+}
+private final int jjStartNfaWithStates_0(int pos, int kind, int state)
+{
+ jjmatchedKind = kind;
+ jjmatchedPos = pos;
+ try { curChar = input_stream.readChar(); }
+ catch(java.io.IOException e) { return pos + 1; }
+ return jjMoveNfa_0(state, pos + 1);
+}
+private final int jjMoveStringLiteralDfa0_0()
+{
+ switch(curChar)
+ {
+ case 40:
+ return jjStopAtPos(0, 17);
+ case 41:
+ return jjStopAtPos(0, 18);
+ case 44:
+ return jjStopAtPos(0, 16);
+ case 45:
+ jjmatchedKind = 14;
+ return jjMoveStringLiteralDfa1_0(0x40L);
+ case 46:
+ return jjStopAtPos(0, 15);
+ case 58:
+ return jjMoveStringLiteralDfa1_0(0x1000L);
+ case 126:
+ return jjStopAtPos(0, 13);
+ default :
+ return jjMoveNfa_0(0, 0);
+ }
+}
+private final int jjMoveStringLiteralDfa1_0(long active0)
+{
+ try { curChar = input_stream.readChar(); }
+ catch(java.io.IOException e) {
+ jjStopStringLiteralDfa_0(0, active0);
+ return 1;
+ }
+ switch(curChar)
+ {
+ case 45:
+ if ((active0 & 0x40L) != 0L)
+ return jjStopAtPos(1, 6);
+ else if ((active0 & 0x1000L) != 0L)
+ return jjStopAtPos(1, 12);
+ break;
+ default :
+ break;
+ }
+ return jjStartNfa_0(0, active0);
+}
+private final void jjCheckNAdd(int state)
+{
+ if (jjrounds[state] != jjround)
+ {
+ jjstateSet[jjnewStateCnt++] = state;
+ jjrounds[state] = jjround;
+ }
+}
+private final void jjAddStates(int start, int end)
+{
+ do {
+ jjstateSet[jjnewStateCnt++] = jjnextStates[start];
+ } while (start++ != end);
+}
+private final void jjCheckNAddTwoStates(int state1, int state2)
+{
+ jjCheckNAdd(state1);
+ jjCheckNAdd(state2);
+}
+private final void jjCheckNAddStates(int start, int end)
+{
+ do {
+ jjCheckNAdd(jjnextStates[start]);
+ } while (start++ != end);
+}
+private final void jjCheckNAddStates(int start)
+{
+ jjCheckNAdd(jjnextStates[start]);
+ jjCheckNAdd(jjnextStates[start + 1]);
+}
+static final long[] jjbitVec0 = {
+ 0xfffffffffffffffeL, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL
+};
+static final long[] jjbitVec2 = {
+ 0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL
+};
+private final int jjMoveNfa_0(int startState, int curPos)
+{
+ int[] nextStates;
+ int startsAt = 0;
+ jjnewStateCnt = 18;
+ int i = 1;
+ jjstateSet[0] = startState;
+ int j, kind = 0x7fffffff;
+ for (;;)
+ {
+ if (++jjround == 0x7fffffff)
+ ReInitRounds();
+ if (curChar < 64)
+ {
+ long l = 1L << curChar;
+ MatchLoop: do
+ {
+ switch(jjstateSet[--i])
+ {
+ case 0:
+ if ((0x3fe000000000000L & l) != 0L)
+ {
+ if (kind > 23)
+ kind = 23;
+ jjCheckNAdd(11);
+ }
+ else if (curChar == 48)
+ {
+ if (kind > 23)
+ kind = 23;
+ }
+ else if (curChar == 34)
+ jjCheckNAddStates(0, 2);
+ break;
+ case 1:
+ if ((0xfffffffbffffdbffL & l) != 0L)
+ jjCheckNAddStates(0, 2);
+ break;
+ case 3:
+ if ((0x8400000000L & l) != 0L)
+ jjCheckNAddStates(0, 2);
+ break;
+ case 4:
+ if (curChar == 34 && kind > 19)
+ kind = 19;
+ break;
+ case 5:
+ if ((0xff000000000000L & l) != 0L)
+ jjCheckNAddStates(3, 6);
+ break;
+ case 6:
+ if ((0xff000000000000L & l) != 0L)
+ jjCheckNAddStates(0, 2);
+ break;
+ case 7:
+ if ((0xf000000000000L & l) != 0L)
+ jjstateSet[jjnewStateCnt++] = 8;
+ break;
+ case 8:
+ if ((0xff000000000000L & l) != 0L)
+ jjCheckNAdd(6);
+ break;
+ case 9:
+ if (curChar == 48 && kind > 23)
+ kind = 23;
+ break;
+ case 10:
+ if ((0x3fe000000000000L & l) == 0L)
+ break;
+ if (kind > 23)
+ kind = 23;
+ jjCheckNAdd(11);
+ break;
+ case 11:
+ if ((0x3ff000000000000L & l) == 0L)
+ break;
+ if (kind > 23)
+ kind = 23;
+ jjCheckNAdd(11);
+ break;
+ case 13:
+ if ((0x3ff000000000000L & l) == 0L)
+ break;
+ if (kind > 20)
+ kind = 20;
+ jjstateSet[jjnewStateCnt++] = 13;
+ break;
+ case 15:
+ if (curChar == 58 && kind > 24)
+ kind = 24;
+ break;
+ case 17:
+ if ((0x3ff000000000000L & l) == 0L)
+ break;
+ if (kind > 22)
+ kind = 22;
+ jjstateSet[jjnewStateCnt++] = 17;
+ break;
+ default : break;
+ }
+ } while(i != startsAt);
+ }
+ else if (curChar < 128)
+ {
+ long l = 1L << (curChar & 077);
+ MatchLoop: do
+ {
+ switch(jjstateSet[--i])
+ {
+ case 0:
+ if ((0x7fffffeL & l) != 0L)
+ {
+ if (kind > 21)
+ kind = 21;
+ jjCheckNAdd(17);
+ }
+ else if ((0x7fffffe00000000L & l) != 0L)
+ {
+ if (kind > 20)
+ kind = 20;
+ jjCheckNAddStates(7, 9);
+ }
+ break;
+ case 1:
+ if ((0xffffffffefffffffL & l) != 0L)
+ jjCheckNAddStates(0, 2);
+ break;
+ case 2:
+ if (curChar == 92)
+ jjAddStates(10, 12);
+ break;
+ case 3:
+ if ((0x14404410000000L & l) != 0L)
+ jjCheckNAddStates(0, 2);
+ break;
+ case 12:
+ if ((0x7fffffe00000000L & l) == 0L)
+ break;
+ if (kind > 20)
+ kind = 20;
+ jjCheckNAddStates(7, 9);
+ break;
+ case 13:
+ if ((0x7fffffe87fffffeL & l) == 0L)
+ break;
+ if (kind > 20)
+ kind = 20;
+ jjCheckNAdd(13);
+ break;
+ case 14:
+ if ((0x7fffffe00000000L & l) != 0L)
+ jjCheckNAddTwoStates(14, 15);
+ break;
+ case 16:
+ if ((0x7fffffeL & l) == 0L)
+ break;
+ if (kind > 21)
+ kind = 21;
+ jjCheckNAdd(17);
+ break;
+ case 17:
+ if ((0x7fffffe87fffffeL & l) == 0L)
+ break;
+ if (kind > 22)
+ kind = 22;
+ jjCheckNAdd(17);
+ break;
+ default : break;
+ }
+ } while(i != startsAt);
+ }
+ else
+ {
+ int hiByte = (int)(curChar >> 8);
+ int i1 = hiByte >> 6;
+ long l1 = 1L << (hiByte & 077);
+ int i2 = (curChar & 0xff) >> 6;
+ long l2 = 1L << (curChar & 077);
+ MatchLoop: do
+ {
+ switch(jjstateSet[--i])
+ {
+ case 1:
+ if (jjCanMove_0(hiByte, i1, i2, l1, l2))
+ jjAddStates(0, 2);
+ break;
+ default : break;
+ }
+ } while(i != startsAt);
+ }
+ if (kind != 0x7fffffff)
+ {
+ jjmatchedKind = kind;
+ jjmatchedPos = curPos;
+ kind = 0x7fffffff;
+ }
+ ++curPos;
+ if ((i = jjnewStateCnt) == (startsAt = 18 - (jjnewStateCnt = startsAt)))
+ return curPos;
+ try { curChar = input_stream.readChar(); }
+ catch(java.io.IOException e) { return curPos; }
+ }
+}
+private final int jjMoveStringLiteralDfa0_1()
+{
+ return jjMoveNfa_1(0, 0);
+}
+private final int jjMoveNfa_1(int startState, int curPos)
+{
+ int[] nextStates;
+ int startsAt = 0;
+ jjnewStateCnt = 1;
+ int i = 1;
+ jjstateSet[0] = startState;
+ int j, kind = 0x7fffffff;
+ for (;;)
+ {
+ if (++jjround == 0x7fffffff)
+ ReInitRounds();
+ if (curChar < 64)
+ {
+ long l = 1L << curChar;
+ MatchLoop: do
+ {
+ switch(jjstateSet[--i])
+ {
+ case 0:
+ if ((0xffffffffffffdbffL & l) == 0L)
+ break;
+ kind = 7;
+ jjstateSet[jjnewStateCnt++] = 0;
+ break;
+ default : break;
+ }
+ } while(i != startsAt);
+ }
+ else if (curChar < 128)
+ {
+ long l = 1L << (curChar & 077);
+ MatchLoop: do
+ {
+ switch(jjstateSet[--i])
+ {
+ case 0:
+ kind = 7;
+ jjstateSet[jjnewStateCnt++] = 0;
+ break;
+ default : break;
+ }
+ } while(i != startsAt);
+ }
+ else
+ {
+ int hiByte = (int)(curChar >> 8);
+ int i1 = hiByte >> 6;
+ long l1 = 1L << (hiByte & 077);
+ int i2 = (curChar & 0xff) >> 6;
+ long l2 = 1L << (curChar & 077);
+ MatchLoop: do
+ {
+ switch(jjstateSet[--i])
+ {
+ case 0:
+ if (!jjCanMove_0(hiByte, i1, i2, l1, l2))
+ break;
+ if (kind > 7)
+ kind = 7;
+ jjstateSet[jjnewStateCnt++] = 0;
+ break;
+ default : break;
+ }
+ } while(i != startsAt);
+ }
+ if (kind != 0x7fffffff)
+ {
+ jjmatchedKind = kind;
+ jjmatchedPos = curPos;
+ kind = 0x7fffffff;
+ }
+ ++curPos;
+ if ((i = jjnewStateCnt) == (startsAt = 1 - (jjnewStateCnt = startsAt)))
+ return curPos;
+ try { curChar = input_stream.readChar(); }
+ catch(java.io.IOException e) { return curPos; }
+ }
+}
+static final int[] jjnextStates = {
+ 1, 2, 4, 1, 2, 6, 4, 13, 14, 15, 3, 5, 7,
+};
+private static final boolean jjCanMove_0(int hiByte, int i1, int i2, long l1, long l2)
+{
+ switch(hiByte)
+ {
+ case 0:
+ return ((jjbitVec2[i2] & l2) != 0L);
+ default :
+ if ((jjbitVec0[i1] & l1) != 0L)
+ return true;
+ return false;
+ }
+}
+public static final String[] jjstrLiteralImages = {
+"", null, null, null, null, null, null, null, null, null, null, null,
+"\72\55", "\176", "\55", "\56", "\54", "\50", "\51", null, null, null, null, null, null, };
+public static final String[] lexStateNames = {
+ "DEFAULT",
+ "IN_COMMENT",
+};
+public static final int[] jjnewLexState = {
+ -1, -1, -1, -1, -1, -1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+};
+static final long[] jjtoToken = {
+ 0x1fff001L,
+};
+static final long[] jjtoSkip = {
+ 0xbeL,
+};
+static final long[] jjtoSpecial = {
+ 0x80L,
+};
+static final long[] jjtoMore = {
+ 0x40L,
+};
+protected SimpleCharStream input_stream;
+private final int[] jjrounds = new int[18];
+private final int[] jjstateSet = new int[36];
+StringBuffer image;
+int jjimageLen;
+int lengthOfMatch;
+protected char curChar;
+public RlogParserTokenManager(SimpleCharStream stream){
+ if (SimpleCharStream.staticFlag)
+ throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer.");
+ input_stream = stream;
+}
+public RlogParserTokenManager(SimpleCharStream stream, int lexState){
+ this(stream);
+ SwitchTo(lexState);
+}
+public void ReInit(SimpleCharStream stream)
+{
+ jjmatchedPos = jjnewStateCnt = 0;
+ curLexState = defaultLexState;
+ input_stream = stream;
+ ReInitRounds();
+}
+private final void ReInitRounds()
+{
+ int i;
+ jjround = 0x80000001;
+ for (i = 18; i-- > 0;)
+ jjrounds[i] = 0x80000000;
+}
+public void ReInit(SimpleCharStream stream, int lexState)
+{
+ ReInit(stream);
+ SwitchTo(lexState);
+}
+public void SwitchTo(int lexState)
+{
+ if (lexState >= 2 || lexState < 0)
+ throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE);
+ else
+ curLexState = lexState;
+}
+
+protected Token jjFillToken()
+{
+ Token t = Token.newToken(jjmatchedKind);
+ t.kind = jjmatchedKind;
+ if (jjmatchedPos < 0)
+ {
+ if (image == null)
+ t.image = "";
+ else
+ t.image = image.toString();
+ t.beginLine = t.endLine = input_stream.getBeginLine();
+ t.beginColumn = t.endColumn = input_stream.getBeginColumn();
+ }
+ else
+ {
+ String im = jjstrLiteralImages[jjmatchedKind];
+ t.image = (im == null) ? input_stream.GetImage() : im;
+ t.beginLine = input_stream.getBeginLine();
+ t.beginColumn = input_stream.getBeginColumn();
+ t.endLine = input_stream.getEndLine();
+ t.endColumn = input_stream.getEndColumn();
+ }
+ return t;
+}
+
+int curLexState = 0;
+int defaultLexState = 0;
+int jjnewStateCnt;
+int jjround;
+int jjmatchedPos;
+int jjmatchedKind;
+
+public Token getNextToken()
+{
+ int kind;
+ Token specialToken = null;
+ Token matchedToken;
+ int curPos = 0;
+
+ EOFLoop :
+ for (;;)
+ {
+ try
+ {
+ curChar = input_stream.BeginToken();
+ }
+ catch(java.io.IOException e)
+ {
+ jjmatchedKind = 0;
+ matchedToken = jjFillToken();
+ matchedToken.specialToken = specialToken;
+ return matchedToken;
+ }
+ image = null;
+ jjimageLen = 0;
+
+ for (;;)
+ {
+ switch(curLexState)
+ {
+ case 0:
+ try { input_stream.backup(0);
+ while (curChar <= 32 && (0x100003600L & (1L << curChar)) != 0L)
+ curChar = input_stream.BeginToken();
+ }
+ catch (java.io.IOException e1) { continue EOFLoop; }
+ jjmatchedKind = 0x7fffffff;
+ jjmatchedPos = 0;
+ curPos = jjMoveStringLiteralDfa0_0();
+ break;
+ case 1:
+ jjmatchedKind = 7;
+ jjmatchedPos = -1;
+ curPos = 0;
+ curPos = jjMoveStringLiteralDfa0_1();
+ break;
+ }
+ if (jjmatchedKind != 0x7fffffff)
+ {
+ if (jjmatchedPos + 1 < curPos)
+ input_stream.backup(curPos - jjmatchedPos - 1);
+ if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L)
+ {
+ matchedToken = jjFillToken();
+ matchedToken.specialToken = specialToken;
+ if (jjnewLexState[jjmatchedKind] != -1)
+ curLexState = jjnewLexState[jjmatchedKind];
+ return matchedToken;
+ }
+ else if ((jjtoSkip[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L)
+ {
+ if ((jjtoSpecial[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L)
+ {
+ matchedToken = jjFillToken();
+ if (specialToken == null)
+ specialToken = matchedToken;
+ else
+ {
+ matchedToken.specialToken = specialToken;
+ specialToken = (specialToken.next = matchedToken);
+ }
+ SkipLexicalActions(matchedToken);
+ }
+ else
+ SkipLexicalActions(null);
+ if (jjnewLexState[jjmatchedKind] != -1)
+ curLexState = jjnewLexState[jjmatchedKind];
+ continue EOFLoop;
+ }
+ jjimageLen += jjmatchedPos + 1;
+ if (jjnewLexState[jjmatchedKind] != -1)
+ curLexState = jjnewLexState[jjmatchedKind];
+ curPos = 0;
+ jjmatchedKind = 0x7fffffff;
+ try {
+ curChar = input_stream.readChar();
+ continue;
+ }
+ catch (java.io.IOException e1) { }
+ }
+ int error_line = input_stream.getEndLine();
+ int error_column = input_stream.getEndColumn();
+ String error_after = null;
+ boolean EOFSeen = false;
+ try { input_stream.readChar(); input_stream.backup(1); }
+ catch (java.io.IOException e1) {
+ EOFSeen = true;
+ error_after = curPos <= 1 ? "" : input_stream.GetImage();
+ if (curChar == '\n' || curChar == '\r') {
+ error_line++;
+ error_column = 0;
+ }
+ else
+ error_column++;
+ }
+ if (!EOFSeen) {
+ input_stream.backup(1);
+ error_after = curPos <= 1 ? "" : input_stream.GetImage();
+ }
+ throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR);
+ }
+ }
+}
+
+void SkipLexicalActions(Token matchedToken)
+{
+ switch(jjmatchedKind)
+ {
+ default :
+ break;
+ }
+}
+}
Added: trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/SimpleCharStream.java
===================================================================
--- trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/SimpleCharStream.java (rev 0)
+++ trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/SimpleCharStream.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,439 @@
+/* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 4.0 */
+package org.mulgara.krule.rlog;
+
+/**
+ * An implementation of interface CharStream, where the stream is assumed to
+ * contain only ASCII characters (without unicode processing).
+ */
+
+public class SimpleCharStream
+{
+ public static final boolean staticFlag = false;
+ int bufsize;
+ int available;
+ int tokenBegin;
+ public int bufpos = -1;
+ protected int bufline[];
+ protected int bufcolumn[];
+
+ protected int column = 0;
+ protected int line = 1;
+
+ protected boolean prevCharIsCR = false;
+ protected boolean prevCharIsLF = false;
+
+ protected java.io.Reader inputStream;
+
+ protected char[] buffer;
+ protected int maxNextCharInd = 0;
+ protected int inBuf = 0;
+ protected int tabSize = 8;
+
+ protected void setTabSize(int i) { tabSize = i; }
+ protected int getTabSize(int i) { return tabSize; }
+
+
+ protected void ExpandBuff(boolean wrapAround)
+ {
+ char[] newbuffer = new char[bufsize + 2048];
+ int newbufline[] = new int[bufsize + 2048];
+ int newbufcolumn[] = new int[bufsize + 2048];
+
+ try
+ {
+ if (wrapAround)
+ {
+ System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
+ System.arraycopy(buffer, 0, newbuffer,
+ bufsize - tokenBegin, bufpos);
+ buffer = newbuffer;
+
+ System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
+ System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);
+ bufline = newbufline;
+
+ System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
+ System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);
+ bufcolumn = newbufcolumn;
+
+ maxNextCharInd = (bufpos += (bufsize - tokenBegin));
+ }
+ else
+ {
+ System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
+ buffer = newbuffer;
+
+ System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
+ bufline = newbufline;
+
+ System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
+ bufcolumn = newbufcolumn;
+
+ maxNextCharInd = (bufpos -= tokenBegin);
+ }
+ }
+ catch (Throwable t)
+ {
+ throw new Error(t.getMessage());
+ }
+
+
+ bufsize += 2048;
+ available = bufsize;
+ tokenBegin = 0;
+ }
+
+ protected void FillBuff() throws java.io.IOException
+ {
+ if (maxNextCharInd == available)
+ {
+ if (available == bufsize)
+ {
+ if (tokenBegin > 2048)
+ {
+ bufpos = maxNextCharInd = 0;
+ available = tokenBegin;
+ }
+ else if (tokenBegin < 0)
+ bufpos = maxNextCharInd = 0;
+ else
+ ExpandBuff(false);
+ }
+ else if (available > tokenBegin)
+ available = bufsize;
+ else if ((tokenBegin - available) < 2048)
+ ExpandBuff(true);
+ else
+ available = tokenBegin;
+ }
+
+ int i;
+ try {
+ if ((i = inputStream.read(buffer, maxNextCharInd,
+ available - maxNextCharInd)) == -1)
+ {
+ inputStream.close();
+ throw new java.io.IOException();
+ }
+ else
+ maxNextCharInd += i;
+ return;
+ }
+ catch(java.io.IOException e) {
+ --bufpos;
+ backup(0);
+ if (tokenBegin == -1)
+ tokenBegin = bufpos;
+ throw e;
+ }
+ }
+
+ public char BeginToken() throws java.io.IOException
+ {
+ tokenBegin = -1;
+ char c = readChar();
+ tokenBegin = bufpos;
+
+ return c;
+ }
+
+ protected void UpdateLineColumn(char c)
+ {
+ column++;
+
+ if (prevCharIsLF)
+ {
+ prevCharIsLF = false;
+ line += (column = 1);
+ }
+ else if (prevCharIsCR)
+ {
+ prevCharIsCR = false;
+ if (c == '\n')
+ {
+ prevCharIsLF = true;
+ }
+ else
+ line += (column = 1);
+ }
+
+ switch (c)
+ {
+ case '\r' :
+ prevCharIsCR = true;
+ break;
+ case '\n' :
+ prevCharIsLF = true;
+ break;
+ case '\t' :
+ column--;
+ column += (tabSize - (column % tabSize));
+ break;
+ default :
+ break;
+ }
+
+ bufline[bufpos] = line;
+ bufcolumn[bufpos] = column;
+ }
+
+ public char readChar() throws java.io.IOException
+ {
+ if (inBuf > 0)
+ {
+ --inBuf;
+
+ if (++bufpos == bufsize)
+ bufpos = 0;
+
+ return buffer[bufpos];
+ }
+
+ if (++bufpos >= maxNextCharInd)
+ FillBuff();
+
+ char c = buffer[bufpos];
+
+ UpdateLineColumn(c);
+ return (c);
+ }
+
+ /**
+ * @deprecated
+ * @see #getEndColumn
+ */
+
+ public int getColumn() {
+ return bufcolumn[bufpos];
+ }
+
+ /**
+ * @deprecated
+ * @see #getEndLine
+ */
+
+ public int getLine() {
+ return bufline[bufpos];
+ }
+
+ public int getEndColumn() {
+ return bufcolumn[bufpos];
+ }
+
+ public int getEndLine() {
+ return bufline[bufpos];
+ }
+
+ public int getBeginColumn() {
+ return bufcolumn[tokenBegin];
+ }
+
+ public int getBeginLine() {
+ return bufline[tokenBegin];
+ }
+
+ public void backup(int amount) {
+
+ inBuf += amount;
+ if ((bufpos -= amount) < 0)
+ bufpos += bufsize;
+ }
+
+ public SimpleCharStream(java.io.Reader dstream, int startline,
+ int startcolumn, int buffersize)
+ {
+ inputStream = dstream;
+ line = startline;
+ column = startcolumn - 1;
+
+ available = bufsize = buffersize;
+ buffer = new char[buffersize];
+ bufline = new int[buffersize];
+ bufcolumn = new int[buffersize];
+ }
+
+ public SimpleCharStream(java.io.Reader dstream, int startline,
+ int startcolumn)
+ {
+ this(dstream, startline, startcolumn, 4096);
+ }
+
+ public SimpleCharStream(java.io.Reader dstream)
+ {
+ this(dstream, 1, 1, 4096);
+ }
+ public void ReInit(java.io.Reader dstream, int startline,
+ int startcolumn, int buffersize)
+ {
+ inputStream = dstream;
+ line = startline;
+ column = startcolumn - 1;
+
+ if (buffer == null || buffersize != buffer.length)
+ {
+ available = bufsize = buffersize;
+ buffer = new char[buffersize];
+ bufline = new int[buffersize];
+ bufcolumn = new int[buffersize];
+ }
+ prevCharIsLF = prevCharIsCR = false;
+ tokenBegin = inBuf = maxNextCharInd = 0;
+ bufpos = -1;
+ }
+
+ public void ReInit(java.io.Reader dstream, int startline,
+ int startcolumn)
+ {
+ ReInit(dstream, startline, startcolumn, 4096);
+ }
+
+ public void ReInit(java.io.Reader dstream)
+ {
+ ReInit(dstream, 1, 1, 4096);
+ }
+ public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
+ int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
+ {
+ this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
+ }
+
+ public SimpleCharStream(java.io.InputStream dstream, int startline,
+ int startcolumn, int buffersize)
+ {
+ this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
+ }
+
+ public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
+ int startcolumn) throws java.io.UnsupportedEncodingException
+ {
+ this(dstream, encoding, startline, startcolumn, 4096);
+ }
+
+ public SimpleCharStream(java.io.InputStream dstream, int startline,
+ int startcolumn)
+ {
+ this(dstream, startline, startcolumn, 4096);
+ }
+
+ public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
+ {
+ this(dstream, encoding, 1, 1, 4096);
+ }
+
+ public SimpleCharStream(java.io.InputStream dstream)
+ {
+ this(dstream, 1, 1, 4096);
+ }
+
+ public void ReInit(java.io.InputStream dstream, String encoding, int startline,
+ int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
+ {
+ ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
+ }
+
+ public void ReInit(java.io.InputStream dstream, int startline,
+ int startcolumn, int buffersize)
+ {
+ ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
+ }
+
+ public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
+ {
+ ReInit(dstream, encoding, 1, 1, 4096);
+ }
+
+ public void ReInit(java.io.InputStream dstream)
+ {
+ ReInit(dstream, 1, 1, 4096);
+ }
+ public void ReInit(java.io.InputStream dstream, String encoding, int startline,
+ int startcolumn) throws java.io.UnsupportedEncodingException
+ {
+ ReInit(dstream, encoding, startline, startcolumn, 4096);
+ }
+ public void ReInit(java.io.InputStream dstream, int startline,
+ int startcolumn)
+ {
+ ReInit(dstream, startline, startcolumn, 4096);
+ }
+ public String GetImage()
+ {
+ if (bufpos >= tokenBegin)
+ return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);
+ else
+ return new String(buffer, tokenBegin, bufsize - tokenBegin) +
+ new String(buffer, 0, bufpos + 1);
+ }
+
+ public char[] GetSuffix(int len)
+ {
+ char[] ret = new char[len];
+
+ if ((bufpos + 1) >= len)
+ System.arraycopy(buffer, bufpos - len + 1, ret, 0, len);
+ else
+ {
+ System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0,
+ len - bufpos - 1);
+ System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1);
+ }
+
+ return ret;
+ }
+
+ public void Done()
+ {
+ buffer = null;
+ bufline = null;
+ bufcolumn = null;
+ }
+
+ /**
+ * Method to adjust line and column numbers for the start of a token.
+ */
+ public void adjustBeginLineColumn(int newLine, int newCol)
+ {
+ int start = tokenBegin;
+ int len;
+
+ if (bufpos >= tokenBegin)
+ {
+ len = bufpos - tokenBegin + inBuf + 1;
+ }
+ else
+ {
+ len = bufsize - tokenBegin + bufpos + 1 + inBuf;
+ }
+
+ int i = 0, j = 0, k = 0;
+ int nextColDiff = 0, columnDiff = 0;
+
+ while (i < len &&
+ bufline[j = start % bufsize] == bufline[k = ++start % bufsize])
+ {
+ bufline[j] = newLine;
+ nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];
+ bufcolumn[j] = newCol + columnDiff;
+ columnDiff = nextColDiff;
+ i++;
+ }
+
+ if (i < len)
+ {
+ bufline[j] = newLine++;
+ bufcolumn[j] = newCol + columnDiff;
+
+ while (i++ < len)
+ {
+ if (bufline[j = start % bufsize] != bufline[++start % bufsize])
+ bufline[j] = newLine++;
+ else
+ bufline[j] = newLine;
+ }
+ }
+
+ line = bufline[j];
+ column = bufcolumn[j];
+ }
+
+}
Added: trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/Token.java
===================================================================
--- trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/Token.java (rev 0)
+++ trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/Token.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,81 @@
+/* Generated By:JavaCC: Do not edit this line. Token.java Version 3.0 */
+package org.mulgara.krule.rlog;
+
+/**
+ * Describes the input token stream.
+ */
+
+public class Token {
+
+ /**
+ * An integer that describes the kind of this token. This numbering
+ * system is determined by JavaCCParser, and a table of these numbers is
+ * stored in the file ...Constants.java.
+ */
+ public int kind;
+
+ /**
+ * beginLine and beginColumn describe the position of the first character
+ * of this token; endLine and endColumn describe the position of the
+ * last character of this token.
+ */
+ public int beginLine, beginColumn, endLine, endColumn;
+
+ /**
+ * The string image of the token.
+ */
+ public String image;
+
+ /**
+ * A reference to the next regular (non-special) token from the input
+ * stream. If this is the last token from the input stream, or if the
+ * token manager has not read tokens beyond this one, this field is
+ * set to null. This is true only if this token is also a regular
+ * token. Otherwise, see below for a description of the contents of
+ * this field.
+ */
+ public Token next;
+
+ /**
+ * This field is used to access special tokens that occur prior to this
+ * token, but after the immediately preceding regular (non-special) token.
+ * If there are no such special tokens, this field is set to null.
+ * When there are more than one such special token, this field refers
+ * to the last of these special tokens, which in turn refers to the next
+ * previous special token through its specialToken field, and so on
+ * until the first special token (whose specialToken field is null).
+ * The next fields of special tokens refer to other special tokens that
+ * immediately follow it (without an intervening regular token). If there
+ * is no such token, this field is null.
+ */
+ public Token specialToken;
+
+ /**
+ * Returns the image.
+ */
+ public String toString()
+ {
+ return image;
+ }
+
+ /**
+ * Returns a new Token object, by default. However, if you want, you
+ * can create and return subclass objects based on the value of ofKind.
+ * Simply add the cases to the switch for all those special cases.
+ * For example, if you have a subclass of Token called IDToken that
+ * you want to create if ofKind is ID, simlpy add something like :
+ *
+ * case MyParserConstants.ID : return new IDToken();
+ *
+ * to the following switch statement. Then you can cast matchedToken
+ * variable to the appropriate type and use it in your lexical actions.
+ */
+ public static final Token newToken(int ofKind)
+ {
+ switch(ofKind)
+ {
+ default : return new Token();
+ }
+ }
+
+}
Added: trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/TokenMgrError.java
===================================================================
--- trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/TokenMgrError.java (rev 0)
+++ trunk/src/jar/content-rlog/javacc/org/mulgara/krule/rlog/TokenMgrError.java 2009-02-27 07:06:28 UTC (rev 1563)
@@ -0,0 +1,136 @@
+/* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 3.0 */
+package org.mulgara.krule.rlog;
+
+public class TokenMgrError extends Error
+{
+ /*
+ * Ordinals for various reasons why an Error of this type can be thrown.
+ */
+
+ /** Generated serialization ID */
+ private static final long serialVersionUID = -7021183633912339051L;
+
+ /**
+ * Lexical error occured.
+ */
+ static final int LEXICAL_ERROR = 0;
+
+ /**
+ * An attempt wass made to create a second instance of a static token manager.
+ */
+ static final int STATIC_LEXER_ERROR = 1;
+
+ /**
+ * Tried to change to an invalid lexical state.
+ */
+ static final int INVALID_LEXICAL_STATE = 2;
+
+ /**
+ * Detected (and bailed out of) an infinite loop in the token manager.
+ */
+ static final int LOOP_DETECTED = 3;
+
+ /**
+ * Indicates the reason why the exception is thrown. It will have
+ * one of the above 4 values.
+ */
+ int errorCode;
+
+ /**
+ * Replaces unprintable characters by their espaced (or unicode escaped)
+ * equivalents in the given string
+ */
+ protected static final String addEscapes(String str) {
+ StringBuffer retval = new StringBuffer();
+ char ch;
+ for (int i = 0; i < str.length(); i++) {
+ switch (str.charAt(i))
+ {
+ case 0 :
+ continue;
+ case '\b':
+ retval.append("\\b");
+ continue;
+ case '\t':
+ retval.append("\\t");
+ continue;
+ case '\n':
+ retval.append("\\n");
+ continue;
+ case '\f':
+ retval.append("\\f");
+ continue;
+ case '\r':
+ retval.append("\\r");
+ continue;
+ case '\"':
+ retval.append("\\\"");
+ continue;
+ case '\'':
+ retval.append("\\\'");
+ continue;
+ case '\\':
+ retval.append("\\\\");
+ continue;
+ default:
+ if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
+ String s = "0000" + Integer.toString(ch, 16);
+ retval.append("\\u" + s.substring(s.length() - 4, s.length()));
+ } else {
+ retval.append(ch);
+ }
+ continue;
+ }
+ }
+ return retval.toString();
+ }
+
+ /**
+ * Returns a detailed message for the Error when it is thrown by the
+ * token manager to indicate a lexical error.
+ * Parameters :
+ * EOFSeen : indicates if EOF caused the lexicl error
+ * curLexState : lexical state in which this error occured
+ * errorLine : line number when the error occured
+ * errorColumn : column number when the error occured
+ * errorAfter : prefix that was seen before this error occured
+ * curchar : the offending character
+ * Note: You can customize the lexical error message by modifying this method.
+ */
+ protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) {
+ return("Lexical error at line " +
+ errorLine + ", column " +
+ errorColumn + ". Encountered: " +
+ (EOFSeen ? "<EOF> " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") +
+ "after : \"" + addEscapes(errorAfter) + "\"");
+ }
+
+ /**
+ * You can also modify the body of this method to customize your error messages.
+ * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not
+ * of end-users concern, so you can return something like :
+ *
+ * "Internal Error : Please file a bug report .... "
+ *
+ * from this method for such cases in the release version of your parser.
+ */
+ public String getMessage() {
+ return super.getMessage();
+ }
+
+ /*
+ * Constructors of various flavors follow.
+ */
+
+ public TokenMgrError() {
+ }
+
+ public TokenMgrError(String message, int reason) {
+ super(message);
+ errorCode = reason;
+ }
+
+ public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) {
+ this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason);
+ }
+}
More information about the Mulgara-svn
mailing list