ExtendedParser.java
ExtendedParser.java · 14.7 KB
From the archive cmextparser.zip
Download the archive « Back to the archive contents
package com.planet_ink.coffee_mud.utils;
import com.planet_ink.coffee_mud.interfaces.*;
import com.planet_ink.coffee_mud.common.*;
import java.io.*;
import java.util.regex.*;
import java.util.*;
/*
Copyright (c) 2006, Bo Zimmerman
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Extended Parser
* This class loads and maintains a set of regular expression/replacement expression pairings.
* It also contains methods to process player-entered commands against the regular expressions
* to produce one or more changed commands.
*/
public class ExtendedParser extends Scriptable
{
private ExtendedParser(){};
/**
* The named sections in the extended_parser.properties file.
*/
private static Hashtable parserSections=null;
/**
* This is the "hook" method that exposes the functionality of the
* extended parser to the rest of the system. It accepts the player
* who has entered a command, along with a vector of strings representing
* the command they entered along with its parameters, in order. It
* is expected to utilize the internal extended parser to modify the
* command the player entered into one or more changed commands, and then,
* when completed, que those commands with the player MOB class for
* processing by the system.
* This method is hooked by searching for
* mob.enqueCommand(CMDS,0);
* in the TelnetSession.java file, and replacing it with:
* ExtendedParser.queExtendedCommands(mob, CMDS);
*/
public static void queExtendedCommands(MOB mob, Vector CMDS)
{
Vector MORE_CMDS=preCommandParser(CMDS);
for(int m=0;m<MORE_CMDS.size();m++)
mob.enqueCommand((Vector)MORE_CMDS.elementAt(m),0);
}
/**
* Vector string combiner whose purpose is to take a vector of strings,
* starting at a given index, and return a single string with all the
* member strings concatenated, in order, and separated by tab
* characters. Since player commands are always represented as a
* vector or strings, while our regular expressions assume tab-separated
* commands and parameter strings, this method is a necessary converter.
*/
private static String combineWithTabs(Vector commands, int startAt)
{
StringBuffer Combined=new StringBuffer("");
if(commands!=null)
for(int commandIndex=startAt;commandIndex<commands.size();commandIndex++)
{
String s=(String)commands.elementAt(commandIndex);
Combined.append(s+"\t");
}
return Combined.toString().trim();
}
/**
* String parser whose purpose is to take a string containing 0 or more characters
* of the given delimeter string, separate the string into sections according to
* those delimeters, and add them, in order, to a vector. The vector of parsed
* strings is then returned. The ignoreNulls boolean tells the method whether
* empty strings, such as those found when two delimeters appear next to each
* other, should be added to the resulting vector.
* Since player commands are always represented as a vector or strings, while
* our regular expressions assume tab-separated commands and parameter strings,
* this method is a necessary converter
*/
private static Vector parseAny(String s, String delimeter, boolean ignoreNulls)
{
Vector V=new Vector();
if((s==null)||(s.length()==0)) return V;
int x=s.indexOf(delimeter);
while(x>=0)
{
String s2=s.substring(0,x).trim();
s=s.substring(x+delimeter.length()).trim();
if((!ignoreNulls)||(s2.length()>0))
V.addElement(s2);
x=s.indexOf(delimeter);
}
if((!ignoreNulls)||(s.trim().length()>0))
V.addElement(s.trim());
return V;
}
/**
* Calls parseAny with a tab-delimeter
*/
private static Vector parseTabs(String s, boolean ignoreNulls)
{ return parseAny(s,"\t",ignoreNulls);}
/**
* Parses, stores, and returns the list of regular expression and replacement
* expression pairings for use by the extended parser. This method expects
* only the name of a section of the extended_parser.properties file, and returns
* an n-dimensional vector reflective of the data in that section of the file.
* Since there is only one section at the moment, we can point out that this method
* will return a 3-dimensional vector where each row represents an expression pair,
* with the first column being the parser command (usually REPLACE), the second
* column being the compiled expression object, and the last being the replacement
* expression as a string.
*/
private static DVector getLanguageParser(String parser)
{
// If the sections of the file have not been read in and parsed, then do so...
if(parserSections==null)
{
parserSections=new Hashtable();
// Read in the file as a stringbuffer
StringBuffer alldata=Resources.getFileResource("extended_parser.properties",false);
if(alldata==null){ Log.errOut("Parser text not found! This mud is in deep doo-doo!"); return null;}
// parse the stringbuffer by carriage returns into a vector representing all the lines
// of the file.
Vector V=Resources.getFileLineVector(alldata);
String s=null; // stores the current line of the file
DVector currentSection=null; // the current file section being parsed
// now parse each line
for(int v=0;v<V.size();v++)
{
s=((String)V.elementAt(v)).trim();
if(s.startsWith("#")) continue; // comments are skipped
if(s.startsWith("[")) // an open bracket represents a new section!
{
int x=s.lastIndexOf("]");
currentSection=new DVector(3);
parserSections.put(s.substring(1,x).toUpperCase(),currentSection);
}
else
if(s.toUpperCase().startsWith("REPLACE")) // otherwise, the only supported command is replace
{
String cmd="REPLACE";
// expects the expression in double quotes
int regstart=s.indexOf('"');
if(regstart<0){ Log.errOut("Scripts","Malformed parser, line "+v); continue;}
int regend=s.indexOf('"',regstart+1);
// make sure the closing quote is not escaped.
while((regend>regstart)&&(s.charAt(regend-1)=='\\'))
regend=s.indexOf('"',regend+1);
if(regend<0){ Log.errOut("Scripts","Malformed parser, line "+v); continue;}
// now we actually have our expression for this line.
String expression=s.substring(regstart+1,regend);
// the expression must be followed by the key word WITH
s=s.substring(regend+1).trim();
if(!s.toUpperCase().startsWith("WITH")){ Log.errOut("Scripts","Malformed parser, line "+v); continue;}
// the replacement expression is also in double quotes
regstart=s.indexOf('"');
if(regstart<0){ Log.errOut("Scripts","Malformed parser, line "+v); continue;}
regend=s.indexOf('"',regstart+1);
while((regend>regstart)&&(s.charAt(regend-1)=='\\'))
regend=s.indexOf('"',regend+1);
if(regend<0){ Log.errOut("Scripts","Malformed parser, line "+v); continue;}
// and now we have our replacement string too!
String replacement=s.substring(regstart+1,regend);
// we have everything we need to add our expression to the vector, so we
// compile the expression and add the row.
try
{
Pattern expPattern=Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
currentSection.addElement(cmd,expPattern,replacement);
}
catch(Exception e){Log.errOut("Scripts",e);}
}
}
}
// since we definitely have a populated parserSections hashtable, we can look up the requested
// section, and return the n-dimensional vector that represents it.
return (DVector)parserSections.get(parser);
}
/**
* The main command parser. It expects a vector of strings representing
* the command and parameters entered by the user. It returns a vector
* of vectors representing one or more commands which should be applied.
* In between, it will utilize the regular expression parser to implement
* the nifty english-word rules.
*/
private static Vector preCommandParser(Vector CMDS)
{
// this will be our vector or vectors
Vector MORE_CMDS=new Vector();
// change the players command from a vector of strings into a single
// string where each parsed word is separated by a tab.
MORE_CMDS.addElement(combineWithTabs(CMDS,0));
// retreive our 3 dimensional vector of compiled regular expressions
// from the "command-pre-processor" section of our data file.
DVector parser=getLanguageParser("COMMAND-PRE-PROCESSOR");
// if an error has occurred, make sure we don't crash the system.
// just return what we were given.
if((parser==null)||(CMDS==null)){ MORE_CMDS.setElementAt(CMDS,0); return MORE_CMDS;}
// declare some working variables for use in our parsing loop.
Pattern pattern=null; // the regular expression being applied
Matcher matcher=null; // a matcher for a particular string against a particular expression
String str=null; // the current replacement string being applied
Vector expansion=null;// post-parsed replacement command strings, broken into several command strings
String expStr=null; // an individual replacement command after parsing, from the expansion vector
int strLen=-1; // the stored length of the original command string, for comparison later.
// iterate through the regular expressions
for(int p=0;p<parser.size();p++)
{
// we only care about rows that define a replacement
if(((String)parser.elementAt(p,1)).equals("REPLACE"))
{
// get our compiled regular expression pattern,
// and prepare to apply it 1 or more times.
pattern=(Pattern)parser.elementAt(p,2);
boolean nothingDone=false;
while(!nothingDone)
{
nothingDone=true;
// now iterate through our vector of command strings.
// at first, it will only have 1 string in it, but
// replacements may add others, so a-iterating we go.
for(int m=0;m<MORE_CMDS.size();m++)
{
str=(String)MORE_CMDS.elementAt(m);
strLen=str.length();
// build a matcher object for this expression against this command string
matcher=pattern.matcher(str);
if(matcher.find())
{
// we have a match, so fetch the replacement string, and use the
// matcher object to change any \1, \2, etc expressions into their
// proper parsed values from the original command string.
str=(String)parser.elementAt(p,3);
for(int i=0;i<=matcher.groupCount();i++)
str=Util.replaceAll(str,"\\"+i,matcher.group(i));
// if the resulting replacement string is NOT the same
// as our original string, we can safely proceed.
if(!((String)MORE_CMDS.elementAt(m)).equals(str))
{
// change any escaped tab characters into real tabs
str=Util.replaceAll(str,"\\t","\t");
// create a vector of commands by changing any CRs in our replacement
// command string into several different command strings, each of which
// will be in the resulting expansion vector.
expansion=parseAny(str,"\\n",false);
// replace our old command string with the first replacement command string.
MORE_CMDS.setElementAt(expansion.elementAt(0),m);
expStr=(String)expansion.elementAt(0);
// if the length of the first replacement is less than the original, we can
// safely proceed.
if(expStr.length()<=strLen) nothingDone=false;
// vectors don't like inserting at the end, so set a boolean to let us know
// whether we need to add any other replacement string commands to the end,
// or insert them immediately after the first one. The above and this whole
// thing could have been done as a single loop if vectors supported inserting
// at the end.
boolean insert=m<MORE_CMDS.size()-1;
// iterate through the rest of the replacement command strings, if any
// this loop is only executed when multiple commands result from one line.
for(int e=1;e<expansion.size();e++)
{
expStr=(String)expansion.elementAt(e);
if(expStr.length()<=strLen) nothingDone=false;
// check the length to set our "do it again" flag, and then
// add the new string to our final results vector
if(insert)
MORE_CMDS.insertElementAt(expStr,m+e);
else
MORE_CMDS.addElement(expStr);
}
}
}
}
}
}
}
// finally, since we need to return a vector of vectors, and we were working with a vector of
// tab-delimited command strings, our final step is to convert all the command strings back
// into vectors.
for(int m=0;m<MORE_CMDS.size();m++)
MORE_CMDS.setElementAt(parseTabs((String)MORE_CMDS.elementAt(m),false),m);
return MORE_CMDS;
}
}