📄 rule.java
字号:
* Returns false for rules which can affect other rules non-monotonically (remove builtin
* or similar) or are affected non-monotonically (involve negation-as-failure).
*/
public boolean isMonotonic() {
return isMonotonic;
}
/**
* Returns true if the rule does not depend on any data, and so should
* be treated as an axiom.
*/
public boolean isAxiom() {
if (isBackward() && body.length > 0) return false;
for (int i = 0; i < body.length; i++) {
if (body[i] instanceof TriplePattern) {
return false;
}
}
return true;
}
/**
* Printable string describing the rule
*/
public String toString() {
StringBuffer buff = new StringBuffer();
buff.append("[ ");
if (name != null) {
buff.append(name);
buff.append(": ");
}
if (isBackward) {
for (int i = 0; i < head.length; i++) {
buff.append(PrintUtil.print(head[i]));
buff.append(" ");
}
buff.append("<- ");
for (int i = 0; i < body.length; i++) {
buff.append(PrintUtil.print(body[i]));
buff.append(" ");
}
} else {
for (int i = 0; i < body.length; i++) {
buff.append(PrintUtil.print(body[i]));
buff.append(" ");
}
buff.append("-> ");
for (int i = 0; i < head.length; i++) {
buff.append(PrintUtil.print(head[i]));
buff.append(" ");
}
}
buff.append("]");
return buff.toString();
}
/**
* Print a short description of the rule, just its name if it
* has one, otherwise the whole rule description.
*/
public String toShortString() {
if (name != null) {
return name;
} else {
return toString();
}
}
//=======================================================================
// parser access
/**
* Parse a string as a rule.
* @throws ParserException if there is a problem
*/
public static Rule parseRule(String source) throws ParserException {
Parser parser = new Parser(source);
return parser.parseRule();
}
/**
* Answer the list of rules parsed from the given URL.
* @throws RulesetNotFoundException
*/
public static List rulesFromURL( String uri ) {
try {
BufferedReader br = FileUtils.readerFromURL( uri );
return parseRules( Rule.rulesParserFromReader( br ) );
}
catch (WrappedIOException e)
{ throw new RulesetNotFoundException( uri ); }
}
/**
Answer a String which is the concatenation (with newline glue) of all the
non-comment lines readable from <code>src</code>. A comment line is
one starting "#" or "//".
@deprecated Use rulesParserFromReader
*/
public static String rulesStringFromReader( BufferedReader src ) {
try {
StringBuffer result = new StringBuffer();
String line;
while ((line = src.readLine()) != null) {
if (line.startsWith( "#" ) || line.startsWith( "//" )) continue; // Skip comment lines
result.append( line );
result.append( "\n" );
}
return result.toString();
}
catch (IOException e)
{ throw new WrappedIOException( e ); }
}
/**
* Processes the source reader stripping off comment lines and noting prefix
* definitions (@prefix) and rule inclusion commands (@include).
* Returns a parser which is bound to the stripped source text with
* associated prefix and rule inclusion definitions.
*/
public static Parser rulesParserFromReader( BufferedReader src ) {
try {
StringBuffer result = new StringBuffer();
String line;
Map prefixes = new HashMap();
List preloadedRules = new ArrayList();
while ((line = src.readLine()) != null) {
if (line.startsWith("#")) continue; // Skip comment lines
line = line.trim();
if (line.startsWith("//")) continue; // Skip comment lines
if (line.startsWith("@prefix")) {
line = line.substring("@prefix".length());
String prefix = nextArg(line);
String rest = nextAfterArg(line);
if (prefix.endsWith(":")) prefix = prefix.substring(0, prefix.length() - 1);
String url = extractURI(rest);
prefixes.put(prefix, url);
} else if (line.startsWith("@include")) {
// Include referenced rule file, either URL or local special case
line = line.substring("@include".length());
String url = extractURI(line);
// Check for predefined cases
if (url.equalsIgnoreCase("rdfs")) {
preloadedRules.addAll( RDFSFBRuleReasoner.loadRules() );
} else if (url.equalsIgnoreCase("owl")) {
preloadedRules.addAll( OWLFBRuleReasoner.loadRules() ) ;
} else if (url.equalsIgnoreCase("owlmicro")) {
preloadedRules.addAll( OWLMicroReasoner.loadRules() ) ;
} else if (url.equalsIgnoreCase("owlmini")) {
preloadedRules.addAll( OWLMiniReasoner.loadRules() ) ;
} else {
// Just try loading as a URL
preloadedRules.addAll( rulesFromURL(url) );
}
} else {
result.append(line);
result.append("\n");
}
}
Parser parser = new Parser(result.toString());
parser.registerPrefixMap(prefixes);
parser.addRulesPreload(preloadedRules);
return parser;
}
catch (IOException e)
{ throw new WrappedIOException( e ); }
}
/**
* Helper function find a URI argument in the current string,
* optionally surrounded by matching <>.
*/
private static String extractURI(String lineSoFar) {
String token = lineSoFar.trim();
if (token.startsWith("<")) {
int split = token.indexOf('>');
token = token.substring(1, split);
}
return token;
}
/**
* Helper function to return the next whitespace delimited argument
* from the string
*/
private static String nextArg(String token) {
int start = nextSplit(0, false, token);
int stop = nextSplit(start, true, token);
return token.substring(start, stop);
}
/**
* Helper function to return the remainder of the line after
* stripping off the next whitespace delimited argument
* from the string
*/
private static String nextAfterArg(String token) {
int start = nextSplit(0, false, token);
int stop = nextSplit(start, true, token);
int rest = nextSplit(stop, false, token);
return token.substring(rest);
}
/**
* Helper function - find index of next whitespace or non white
* after the start index.
*/
private static int nextSplit(int start, boolean white, String line) {
int i = start;
while (i < line.length()) {
boolean isWhite = Character.isWhitespace(line.charAt(i));
if ((white & isWhite) || (!white & !isWhite)) {
return i;
}
i++;
}
return i;
}
public static void main(String[] args) {
String test = " <http://myuri/fool>.";
String arg = nextArg(test);
String rest = nextAfterArg(test);
String uri = extractURI(rest);
System.out.println("ARG = [" + arg + "], URI = [" + uri + "]");
}
/**
* Run a pre-bound rule parser to extract it's rules
* @return a list of rules
* @throws ParserException if there is a problem
*/
public static List parseRules(Parser parser) throws ParserException {
boolean finished = false;
List ruleset = new ArrayList();
ruleset.addAll(parser.getRulesPreload());
while (!finished) {
try {
parser.peekToken();
} catch (NoSuchElementException e) {
finished = true;
break;
}
Rule rule = parser.parseRule();
ruleset.add(rule);
}
return ruleset;
}
/**
* Parse a string as a list a rules.
* @return a list of rules
* @throws ParserException if there is a problem
*/
public static List parseRules(String source) throws ParserException {
return parseRules(new Parser(source));
}
//=======================================================================
// parser support
/**
* Inner class which provides minimalist parsing support based on
* tokenisation with depth 1 lookahead. No sensible error reporting on offer.
* No embedded spaces supported.
*/
public static class Parser {
/** Tokenizer */
private Tokenizer stream;
/** Look ahead, null if none */
private String lookahead;
// Literal parse state flags
private static final int NORMAL = 0;
private static final int STARTED_LITERAL = 1;
/** Literal parse state */
private int literalState = NORMAL;;
/** Trace back of recent tokens for error reporting */
protected List priorTokens = new ArrayList();
/** Maximum number of recent tokens to remember */
private static final int maxPriors = 20;
/** Variable table */
private Map varMap;
/** Local prefix map */
private PrefixMapping prefixMapping = PrefixMapping.Factory.create();
/** Pre-included rules */
private List preloadedRules = new ArrayList();
/**
* Constructor
* @param source the string to be parsed
*/
Parser(String source) {
stream = new Tokenizer(source, "()[], \t\n\r", "'\"", true);
lookahead = null;
}
/**
* Register a new namespace prefix with the parser
*/
public void registerPrefix(String prefix, String namespace ) {
prefixMapping.setNsPrefix(prefix, namespace);
}
/**
* Register a set of prefix to namespace mappings with the parser
*/
public void registerPrefixMap(Map map) {
prefixMapping.setNsPrefixes(map);
}
/**
* Return a map of all the discovered prefixes
*/
public Map getPrefixMap() {
return prefixMapping.getNsPrefixMap();
}
/**
* Add a new set of preloaded rules.
*/
void addRulesPreload(List rules) {
preloadedRules.addAll(rules);
}
/**
* Return the complete set of preloaded rules;
*/
public List getRulesPreload() {
return preloadedRules;
}
/**
* Return the next token
*/
String nextToken() {
if (lookahead != null) {
String temp = lookahead;
lookahead = null;
return temp;
} else {
String token = stream.nextToken();
if (literalState == NORMAL) {
// Skip separators unless within a literal
while (isSeparator(token)) {
token = stream.nextToken();
}
}
if (token.equals("'")) {
if (literalState == NORMAL) {
literalState = STARTED_LITERAL;
} else {
literalState = NORMAL;
}
}
priorTokens.add(0, token);
if (priorTokens.size() > maxPriors) {
priorTokens.remove(priorTokens.size()-1);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -