diff options
author | wizard23 <wizard23@cb376a5e-1013-0410-a455-b6b1f9ac8223> | 2009-02-19 17:15:58 +0000 |
---|---|---|
committer | wizard23 <wizard23@cb376a5e-1013-0410-a455-b6b1f9ac8223> | 2009-02-19 17:15:58 +0000 |
commit | b3fe39d92b90e153b7bdd570381d30b7918db007 (patch) | |
tree | 777c39714825ce9f264cd7c8337562a46c820ec3 | |
parent | 7b5df3d7dc22cdfc5509d3a6ef12f31987e0a791 (diff) | |
download | reprap-backup-b3fe39d92b90e153b7bdd570381d30b7918db007.tar.gz reprap-backup-b3fe39d92b90e153b7bdd570381d30b7918db007.zip |
experimental version of AoI object evaluator does not work yet
git-svn-id: https://reprap.svn.sourceforge.net/svnroot/reprap@2560 cb376a5e-1013-0410-a455-b6b1f9ac8223
29 files changed, 5014 insertions, 0 deletions
diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator.xml b/trunk/users/metalab/AoI/plugins/CSGEvaluator.xml new file mode 100755 index 00000000..f6f5559f --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator.xml @@ -0,0 +1,60 @@ +<?xml version="1.0"?> + +<project name="CSGEvaluator" default="dist" basedir="."> + + <!-- set global properties for this build --> + <property name="aoidir" value="/home/wizard23/software/ArtOfIllusion261" /> + <property name="src" value="CSGEvaluator/src" /> + <property name="build" value="CSGEvaluator/build" /> + <property name="docs" value="CSGEvaluator/docs" /> + <property name="dist" value="Plugins" /> + <property name="aoijar" value="${aoidir}/ArtOfIllusion.jar" /> + <property name="buoyjar" value="Buoy.jar" /> + + + <target name="init"> + <!-- Create the time stamp --> + <tstamp/> + <!-- Create the build directory structure used by compile --> + <mkdir dir="${build}" /> + <!-- Create the docs directory structure used by documentation --> + <mkdir dir="${docs}" /> + </target> + + <target name="compile" depends="init"> + <!-- Compile the java code from ${src} into ${build} --> + <javac source="1.5" target="1.5" srcdir="${src}" destdir="${build}" classpath="${aoijar}:${buoyjar}" debug="on" extdirs="" /> + </target> + + <target name="dist" depends="compile"> + <!-- Copy all necessary files into ${build}, then create the jar file --> + <copy file="${src}/extensions.xml" todir="${build}" /> + <copy todir="${build}"> + <fileset dir="${src}" includes="*.properties" /> + </copy> + <jar jarfile="${dist}/CSGEvaluator.jar" basedir="${build}" /> + </target> + + <target name="docs" depends="init"> + <javadoc packagenames="artofillusion.*" + sourcepath="${src}" + classpath="${buoyjar};${aoijar}" + defaultexcludes="yes" + destdir="${docs}" + author="true" + version="true" + use="true" + windowtitle="CSGEvaluator Documentation" + public="true"> + <doctitle><![CDATA[<h1>CSGEvaluator</h1>]]></doctitle> + <bottom><![CDATA[<i>Copyright © 2009 by Marius Kintel.</i>]]></bottom> + </javadoc> + </target> + + <target name="clean"> + <!-- Delete the ${build} and ${docs} directory trees --> + <delete dir="${build}" /> + <delete dir="${docs}" /> + </target> +</project> + diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/extensions.xml b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/extensions.xml new file mode 100755 index 00000000..759cd4f7 --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/extensions.xml @@ -0,0 +1,15 @@ +<?xml version='1.0'?> + +<extension name="CSGEvaluator" version="1.0"> + <plugin class="org.reprap.artofillusion.CSGEvaluatorTool"/> + + <author>Marius Kintel, Philipp Tiefenbacher, Stefan Farthofer (Metalab)</author> + <date>2009/1/14</date> + <description>CSG Evaluator plugin. Simplifies building objects based on boolean operations.</description> + <history> + <log version="0.2" date="11 january 2009" author="all">initial release</log> + <log version="1.0" date="14 january 2009" author="all">minor tweaks</log> + </history> + <comments> + </comments> +</extension> diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ASCII_CharStream.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ASCII_CharStream.java new file mode 100644 index 00000000..9bf185f5 --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ASCII_CharStream.java @@ -0,0 +1,192 @@ +package org.cheffo.jeplite;
+/**
+ * An implementation of interface CharStream, where the stream is assumed to
+ * contain only ASCII characters (without unicode processing).
+ */
+public final class ASCII_CharStream
+{
+ public static final boolean staticFlag = false;
+ int bufsize;
+ int available;
+ int tokenBegin;
+ public int bufpos = -1;
+ private boolean prevCharIsCR = false;
+ private boolean prevCharIsLF = false;
+ private java.io.Reader inputStream;
+ private char[] buffer;
+ private int maxNextCharInd = 0;
+ private int inBuf = 0;
+
+ private final void ExpandBuff(boolean wrapAround)
+ {
+ char[] newbuffer = new char[bufsize + 2048];
+ try
+ {
+ if (wrapAround)
+ {
+ System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
+ System.arraycopy(buffer, 0, newbuffer,
+ bufsize - tokenBegin, bufpos);
+ buffer = newbuffer;
+ maxNextCharInd = (bufpos += (bufsize - tokenBegin));
+ }
+ else
+ {
+ System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
+ buffer = newbuffer;
+ maxNextCharInd = (bufpos -= tokenBegin);
+ }
+ }
+ catch (Throwable t)
+ {
+ throw new Error(t.getMessage());
+ }
+ bufsize += 2048;
+ available = bufsize;
+ tokenBegin = 0;
+ }
+
+ private final 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 final char BeginToken() throws java.io.IOException
+ {
+ tokenBegin = -1;
+ char c = readChar();
+ tokenBegin = bufpos;
+ return c;
+ }
+
+ public final char readChar() throws java.io.IOException
+ {
+ if (inBuf > 0)
+ {
+ --inBuf;
+ return (char)((char)0xff & buffer[(bufpos == bufsize - 1) ? (bufpos = 0) : ++bufpos]);
+ }
+ if (++bufpos >= maxNextCharInd)
+ FillBuff();
+ char c = (char)((char)0xff & buffer[bufpos]);
+ return (c);
+ }
+
+ public final void backup(int amount) {
+ inBuf += amount;
+ if ((bufpos -= amount) < 0)
+ bufpos += bufsize;
+ }
+
+ public ASCII_CharStream(java.io.Reader dstream, int startline,
+ int startcolumn, int buffersize)
+ {
+ inputStream = dstream;
+ available = bufsize = buffersize;
+ buffer = new char[buffersize];
+ }
+
+ public ASCII_CharStream(java.io.Reader dstream, int startline,
+ int startcolumn)
+ {
+ this(dstream, startline, startcolumn, 4096);
+ }
+
+ public void ReInit(java.io.Reader dstream, int startline,
+ int startcolumn, int buffersize)
+ {
+ inputStream = dstream;
+ if (buffer == null || buffersize != buffer.length)
+ {
+ available = bufsize = buffersize;
+ buffer = new char[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 ASCII_CharStream(java.io.InputStream dstream, int startline,
+ int startcolumn, int buffersize)
+ {
+ this(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096);
+ }
+
+ public ASCII_CharStream(java.io.InputStream dstream, int startline,
+ int startcolumn)
+ {
+ this(dstream, startline, startcolumn, 4096);
+ }
+
+ public void ReInit(java.io.InputStream dstream, int startline,
+ int startcolumn, int buffersize)
+ {
+ ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096);
+ }
+
+ public void ReInit(java.io.InputStream dstream, int startline,
+ int startcolumn)
+ {
+ ReInit(dstream, startline, startcolumn, 4096);
+ }
+
+ public final 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 void Done()
+ {
+ buffer = null;
+ }
+}
+
diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ASTConstant.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ASTConstant.java new file mode 100644 index 00000000..04aa6f0f --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ASTConstant.java @@ -0,0 +1,55 @@ +/*****************************************************************************
+JEP - Java Expression Parser
+ JEP is a Java package for parsing and evaluating mathematical
+ expressions. It currently supports user defined variables,
+ constant, and functions. A number of common mathematical
+ functions and constants are included.
+ JEPLite is a simplified version of JEP.
+JEP Author: Nathan Funk
+JEPLite Author: Stephen "Cheffo" Kolaroff
+JEP Copyright (C) 2001 Nathan Funk
+JEPLite Copyright (C) 2002 Stefan Kolarov
+ JEPLite is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ JEPLite is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with JEPLite; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+*****************************************************************************/
+package org.cheffo.jeplite;
+import org.cheffo.jeplite.util.*;
+public final class ASTConstant extends SimpleNode {
+ private double value;
+ public ASTConstant(int id) {
+ super(id);
+ }
+
+ public ASTConstant(Parser p, int id) {
+ super(p, id);
+ }
+
+ public final void setValue(double val) {
+ value = val;
+ }
+
+ public String toString() {
+ return "Constant: " + value;
+ }
+
+ /*Return the Value of the node*/
+ public final double getValue()
+ {
+ return value;
+ }
+
+ public final void getValue(DoubleStack stack) {
+ stack.push(value);
+ }
+}
\ No newline at end of file diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ASTFunNode.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ASTFunNode.java new file mode 100644 index 00000000..a14f6421 --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ASTFunNode.java @@ -0,0 +1,95 @@ +/*****************************************************************************
+JEP - Java Expression Parser
+ JEP is a Java package for parsing and evaluating mathematical
+ expressions. It currently supports user defined variables,
+ constant, and functions. A number of common mathematical
+ functions and constants are included.
+ JEPLite is a simplified version of JEP.
+JEP Author: Nathan Funk
+JEPLite Author: Stephen "Cheffo" Kolaroff
+JEP Copyright (C) 2001 Nathan Funk
+JEPLite Copyright (C) 2002 Stefan Kolarov
+ JEPLite is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ JEPLite is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with JEPLite; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+*****************************************************************************/
+package org.cheffo.jeplite;
+
+import org.cheffo.jeplite.function.*;
+import org.cheffo.jeplite.util.*;
+import java.util.*;
+
+public class ASTFunNode extends SimpleNode {
+ private PostfixMathCommand pfmc;
+
+ public ASTFunNode(int id) {
+ super(id);
+ }
+
+ public ASTFunNode(Parser p, int id) {
+ super(p, id);
+ }
+
+ public Object jjtAccept(ParserVisitor visitor, Object data) {
+ return visitor.visit(this, data);
+ }
+
+ public void setFunction(String name_in, PostfixMathCommand pfmc_in)
+ {
+ name = name_in;
+ pfmc = pfmc_in;
+ }
+
+ public String toString()
+ {
+ if (name!=null)
+ {
+ try {
+ return "Function \"" + name + "\" = " + getValue();
+ } catch (Exception e) {
+ return "Function \"" + name + "\"";
+ }
+ }
+ else
+ {
+ return "Function: no function class set";
+ }
+ }
+
+ public double getValue() throws ParseException
+ {
+ double value = 0;
+ DoubleStack tempStack = new DoubleStack();
+ getValue(tempStack);
+ return tempStack.pop();
+ }
+
+ public final void getValue(DoubleStack tempStack) throws ParseException {
+ double value = 0;
+ for (int i=0; i < jjtGetNumChildren(); i++)
+ {
+ children[i].getValue(tempStack);
+ }
+ if (pfmc!=null)
+ {
+ try {
+ pfmc.run(tempStack);
+ } catch (ParseException e)
+ {
+ String errorStr = "Error in \"" + name + "\" function: ";
+ errorStr += e.getErrorInfo();
+ throw new ParseException(errorStr);
+ }
+ }
+ }
+}
\ No newline at end of file diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ASTVarNode.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ASTVarNode.java new file mode 100644 index 00000000..308aecc0 --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ASTVarNode.java @@ -0,0 +1,64 @@ +/*****************************************************************************
+JEP - Java Expression Parser
+ JEP is a Java package for parsing and evaluating mathematical
+ expressions. It currently supports user defined variables,
+ constant, and functions. A number of common mathematical
+ functions and constants are included.
+ JEPLite is a simplified version of JEP.
+JEP Author: Nathan Funk
+JEPLite Author: Stephen "Cheffo" Kolaroff
+JEP Copyright (C) 2001 Nathan Funk
+JEPLite Copyright (C) 2002 Stefan Kolarov
+ JEPLite is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ JEPLite is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with JEPLite; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+*****************************************************************************/
+package org.cheffo.jeplite;
+
+import java.util.*;
+import org.cheffo.jeplite.util.*;
+
+public class ASTVarNode extends SimpleNode {
+ private HashMap symTab;
+ private double value;
+ public ASTVarNode(int id) {
+ super(id);
+ name = "";
+ }
+
+ public ASTVarNode(Parser p, int id) {
+ super(p, id);
+ }
+
+ public void setValue(double value) {
+ this.value = value;
+ }
+
+ public double getValue() {
+ return value;
+ }
+
+ public void getValue(DoubleStack stack) {
+ stack.push(value);
+ }
+
+ public String toString()
+ {
+ return "Variable: \"" + getName() + "\"" + " = " + getValue();
+ }
+
+ public Object jjtAccept(ParserVisitor visitor, Object data) {
+ return visitor.visit(this, data);
+ }
+}
+
diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/Doc/LICENSE.txt b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/Doc/LICENSE.txt new file mode 100644 index 00000000..7d1f8605 --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/Doc/LICENSE.txt @@ -0,0 +1,342 @@ + GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+ 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Library General
+Public License instead of this License.
+
+
diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/Doc/Notes.txt b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/Doc/Notes.txt new file mode 100644 index 00000000..8d429ef4 --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/Doc/Notes.txt @@ -0,0 +1,38 @@ +This is a simplified and overoptimized version of the Natan Funk's java expression parser JEP. If you intent to use the parser for fast numeric evaluations, based on double values only, the optimized version is may be your better choice.
+
+The inspiration for this optimized version came from the Dustyscripty (a COL - Children Orineted Language) project. Since the children are rarely tempted to use complex number arithmetics, but instead are less willing to accept longer response times, we had to strip some irrelevant features. The result appeared to be quite successful and so we decided to share it with the public.
+
+Any questions, bug reports and so on for the lite version should be sent to xcheffo at users.sourceforge.net, or to the corresponding forum.
+
+This FAQ tries to exply the fetures and issues of the optimized version, compared to those in JEP.
+
+Q: What version of JEP is used as a base for enlitement?
+A: Actually, we don't know, and will never understand. In the light version we may have features unique for the most recent JEP release, while some older and useful are omitted in sake of simplicity.
+
+Q: What is the typical use of the opted version?
+A: Create-Parse-Evaluate. The original JEP is not very open to dirty magic, this optimized version - even less.
+
+Q: What is optimized at all? Do I need the optimized version?
+A: The initial intention was to reduce both source and compiled code size through removal of complex numbed and string arithmetics. So if you _don't_ need those features, the opt version is for you. Later, the use of single numeric type led into a great (about 5-7 times in some test examples) relaxation of the evaluation times, and moderate (20%-30%) relaxation of the parsing times. If complex numbers or string concatenations are crucial for your project, you should consider using the original JEP.
+
+Q: Is JEP outward interface changed? Is my existing code compatible with the optimized version?
+A: Yes, there are some changes in the least frequently used features. More precisely, if your code relies on API entries from the org.funk.jep.function package, it will not compile any more. But if you are merely passing expressions string to be, chancess are that you will have no porting problems. Besides, there is a entirely new package: org.nfunk.jep.utils, where are placed light weighted implementation of stacks with different element types.
+
+Q: But I have some TreeVisitors implemented! Can I use them with the light version?
+A: Most probably yes. If not - concider it as a bug in the lite version and report.
+
+Q: But I have some functions implemented! Can I use them with the light version?
+A: Most probably no. For jeplite, you must extend org.cheffo.jep.PostfixMathCommand (PostfixMathCommandI was removed) and rewrite your function to conforma with the new interface.
+
+Q: But I am using JEP in multiple threads.
+A: There is no heavy tests of the multithreaded stability of the optimized version. But we have a common rule instead: different threads - different JEPs.
+
+Q: So, the lite version is faster, leaner and meaner than the original one. And therefore better?
+A: Absolutely not better. While strippin, some sets of features rendered obsolate their time consuming support. That's all. But JEPLite is to be concidered _worse_ right now, since it has not passed even moderate tests.
+
+Feature comparison
+String evaluations: JEP
+Array evaluations: JEP
+Complex numbers: JEP
+Standart numbers evaluation: JEP, JEPLite
+Row/col error report: JEP
\ No newline at end of file diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/JEP.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/JEP.java new file mode 100644 index 00000000..2a403bc6 --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/JEP.java @@ -0,0 +1,209 @@ +/*****************************************************************************
+JEP - Java Expression Parser
+ JEP is a Java package for parsing and evaluating mathematical
+ expressions. It currently supports user defined variables,
+ constant, and functions. A number of common mathematical
+ functions and constants are included.
+ JEPLite is a simplified version of JEP.
+JEP Author: Nathan Funk
+JEPLite Author: Stephen "Cheffo" Kolaroff
+JEP Copyright (C) 2001 Nathan Funk
+JEPLite Copyright (C) 2002 Stefan Kolarov
+ JEPLite is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ JEPLite is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with JEPLite; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+*****************************************************************************/
+package org.cheffo.jeplite;
+import java.io.*;
+import java.util.*;
+import org.cheffo.jeplite.*;
+import org.cheffo.jeplite.function.*;
+import org.cheffo.jeplite.util.*;
+
+public class JEP {
+ private HashMap symTab;
+ private HashMap funTab;
+ private SimpleNode topNode;
+ private boolean debug=false;
+ private Parser parser;
+ private boolean hasError;
+ private ParseException parseException;
+ public JEP()
+ {
+ topNode = null;
+ hasError = true;
+ parseException = null;
+ initSymTab();
+ initFunTab();
+ parser = new Parser(new StringReader(""));
+ parseExpression("");
+ }
+
+ /**
+ * Initializes the symbol table
+ */
+ public void initSymTab() {
+ symTab = new HashMap();
+ }
+
+ /**
+ * Initializes the function table
+ */
+ public void initFunTab() {
+ funTab = new HashMap();
+ }
+
+ /**
+ * Adds the standard functions to the parser. If this function is not called
+ * before parsing an expression, functions such as sin() or cos() would
+ * produce an "Unrecognized function..." error.
+ * In most cases, this method should be called immediately after the JEP
+ * object is created.
+ */
+ public void addStandardFunctions()
+ {
+ PostfixMathCommand.fillFunctionTable(funTab);
+ }
+
+ /**
+ * Adds the constants pi and e to the parser. As addStandardFunctions(), this
+ * method should be called immediatly after the JEP object is created.
+ */
+ public void addStandardConstants(){
+ addVariable("pi", Math.PI);
+ addVariable("e", Math.E);
+ }
+
+ /**
+ * Adds a new function to the parser. This must be done before parsing
+ * an expression so the parser is aware that the new function may be
+ * contained in the expression.
+ */
+ public void addFunction(String functionName, Object function)
+ {
+ funTab.put(functionName, function);
+ }
+
+ /**
+ * Adds a new variable to the parser, or updates the value of an
+ * existing variable. This must be done before parsing
+ * an expression so the parser is aware that the new variable may be
+ * contained in the expression.
+ * @param name Name of the variable to be added
+ * @param value Initial value or new value for the variable
+ * @return Double object of the variable
+ */
+ public Double addVariable(String name, double value)
+ {
+ ASTVarNode toAdd = (ASTVarNode)symTab.get(name);
+ if(toAdd!=null)
+ toAdd.setValue(value);
+ else {
+ toAdd = new ASTVarNode(ParserTreeConstants.JJTVARNODE);
+ toAdd.setName(name);
+ toAdd.setValue(value);
+ symTab.put(name, toAdd);
+ }
+ return new Double(value);
+ }
+
+ public ASTVarNode getVarNode(String var) {
+ return (ASTVarNode)symTab.get(var);
+ }
+
+ public void setVarNode(String var, ASTVarNode node) {
+ symTab.put(var, node);
+ }
+
+ /**
+ * Parses the expression
+ * @param expression_in The input expression string
+ */
+ public void parseExpression(String expression_in)
+ {
+ Reader reader = new StringReader(expression_in);
+ hasError = false;
+ parseException = null;
+ try
+ {
+ topNode = parser.parseStream(reader, symTab, funTab);
+ } catch (Throwable e)
+ {
+ if (debug && !(e instanceof ParseException))
+ {
+ System.out.println(e.getMessage());
+ e.printStackTrace();
+ }
+ topNode = null;
+ hasError = true;
+ if (e instanceof ParseException)
+ parseException = (ParseException)e;
+ else
+ parseException = null;
+ }
+ Vector errorList = parser.getErrorList();
+ if (!errorList.isEmpty()) hasError = true;
+ }
+
+ /**
+ * Evaluates and returns the value of the expression. If the value is
+ * complex, the real component of the complex number is returned. To
+ * get the complex value, use getComplexValue().
+ * @return The calculated value of the expression. If the value is
+ * complex, the real component is returned. If an error occurs during
+ * evaluation, 0 is returned.
+ */
+ public double getValue() throws ParseException
+ {
+ return getValue(new DoubleStack());
+ }
+
+ public SimpleNode getTopNode() {
+ return topNode;
+ }
+
+ public double getValue(DoubleStack evalStack) throws ParseException {
+ topNode.getValue(evalStack);
+ return(evalStack.pop());
+ }
+
+ /**
+ * Reports whether there is an error in the expression
+ * @return Returns true if the expression has an error
+ */
+ public boolean hasError()
+ {
+ return hasError;
+ }
+
+ /**
+ * Reports information on the error in the expression
+ * @return Returns a string containing information on the error;
+ * null if no error has occured
+ */
+ public String getErrorInfo()
+ {
+ if (hasError)
+ {
+ Vector el = parser.getErrorList();
+ String str = "";
+ if (parseException == null && el.size()==0) str = "Syntax error\n";
+ if (parseException != null) str = parseException.getErrorInfo() + "\n";
+ for (int i=0; i<el.size(); i++)
+ str += el.elementAt(i) + "\n";
+ return str;
+ }
+ else
+ return null;
+ }
+}
\ No newline at end of file diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/JJTParserState.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/JJTParserState.java new file mode 100644 index 00000000..703c426a --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/JJTParserState.java @@ -0,0 +1,134 @@ +/*****************************************************************************
+JEP - Java Expression Parser
+ JEP is a Java package for parsing and evaluating mathematical
+ expressions. It currently supports user defined variables,
+ constant, and functions. A number of common mathematical
+ functions and constants are included.
+ JEPLite is a simplified version of JEP.
+JEP Author: Nathan Funk
+JEPLite Author: Stephen "Cheffo" Kolaroff
+JEP Copyright (C) 2001 Nathan Funk
+JEPLite Copyright (C) 2002 Stefan Kolarov
+ JEPLite is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ JEPLite is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with JEPLite; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+*****************************************************************************/
+package org.cheffo.jeplite;
+import org.cheffo.jeplite.util.*;
+class JJTParserState {
+ private SimpleNodeStack nodes;
+ private IntegerStack marks;
+ private int sp; // number of nodes on stack
+ private int mk; // current mark
+ private boolean node_created;
+ JJTParserState() {
+ nodes = new SimpleNodeStack(100);
+ marks = new IntegerStack(100);
+ sp = 0;
+ mk = 0;
+ }
+
+ /* Determines whether the current node was actually closed and
+ pushed. This should only be called in the final user action of a
+ node scope. */
+ final boolean nodeCreated() {
+ return node_created;
+ }
+
+ /* Call this to reinitialize the node stack. It is called
+ automatically by the parser's ReInit() method. */
+ void reset() {
+ nodes.removeAllElements();
+ marks.removeAllElements();
+ sp = 0;
+ mk = 0;
+ }
+
+ /* Returns the root node of the AST. It only makes sense to call
+ this after a successful parse. */
+ final SimpleNode rootNode() {
+ return nodes.elementAt(0);
+ }
+
+ final void pushNode(SimpleNode n) {
+ nodes.push(n);
+ ++sp;
+ }
+
+ /* Returns the node on the top of the stack, and remove it from the
+ stack. */
+ final SimpleNode popNode() {
+ if (--sp < mk) {
+ mk = marks.pop();
+ }
+ return nodes.pop();
+ }
+
+ final SimpleNode peekNode() {
+ return nodes.peek();
+ }
+
+ /* Returns the number of children on the stack in the current node
+ scope. */
+ final int nodeArity() {
+ return sp - mk;
+ }
+
+ final void clearNodeScope(SimpleNode n) {
+ while (sp > mk) {
+ popNode();
+ }
+ mk = marks.pop();
+ }
+
+ final void openNodeScope(SimpleNode n) {
+ marks.push(mk);
+ mk = sp;
+ n.jjtOpen();
+ }
+
+ final void closeNodeScope(SimpleNode n, int num) {
+ mk = marks.pop();
+ while (num-- > 0) {
+ SimpleNode c = popNode();
+ c.jjtSetParent(n);
+ n.jjtAddChild(c, num);
+ }
+ n.jjtClose();
+ pushNode(n);
+ node_created = true;
+ }
+
+ /* A conditional node is constructed if its condition is true. All
+ the nodes that have been pushed since the node was opened are
+ made children of the the conditional node, which is then pushed
+ on to the stack. If the condition is false the node is not
+ constructed and they are left on the stack. */
+ final void closeNodeScope(SimpleNode n, boolean condition) {
+ if (condition) {
+ int a = nodeArity();
+ mk = marks.pop();
+ while (a-- > 0) {
+ SimpleNode c = popNode();
+ c.jjtSetParent(n);
+ n.jjtAddChild(c, a);
+ }
+ n.jjtClose();
+ pushNode(n);
+ node_created = true;
+ } else {
+ mk = marks.pop();
+ node_created = false;
+ }
+ }
+}
\ No newline at end of file diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ParseException.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ParseException.java new file mode 100644 index 00000000..bd0a4872 --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ParseException.java @@ -0,0 +1,205 @@ +/*****************************************************************************
+JEP - Java Expression Parser
+ JEP is a Java package for parsing and evaluating mathematical
+ expressions. It currently supports user defined variables,
+ constant, and functions. A number of common mathematical
+ functions and constants are included.
+ JEPLite is a simplified version of JEP.
+JEP Author: Nathan Funk
+JEPLite Author: Stephen "Cheffo" Kolaroff
+JEP Copyright (C) 2001 Nathan Funk
+JEPLite Copyright (C) 2002 Stefan Kolarov
+ JEPLite is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ JEPLite is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with JEPLite; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+*****************************************************************************/
+/**
+ * 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.
+ */
+package org.cheffo.jeplite;
+public class ParseException extends Exception {
+ /**
+ * 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;
+ }
+
+ public ParseException(Token currentTokenVal, String message) {
+ super(message);
+ specialConstructor = false;
+ currentToken = currentTokenVal;
+ }
+
+ /**
+ * 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;
+
+ /**
+ * The end of line string for this machine.
+ */
+ protected static final String eol = System.getProperty("line.separator", "\n");
+
+ /**
+ * 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();
+ }
+ String expected = "";
+ 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 += tokenImage[expectedTokenSequences[i][j]] + " ";
+ }
+ if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
+ expected += "...";
+ }
+ expected += eol + " ";
+ }
+ 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 += TokenMgrError.addEscapes(tok.image);
+ tok = tok.next;
+ }
+ if (expectedTokenSequences.length == 1) {
+ retval += "Was expecting:" + eol + " ";
+ } else {
+ retval += "Was expecting one of:" + eol + " ";
+ }
+ retval += expected;
+ return retval;
+ }
+
+ /**
+ * getErrorInfo() was added to the parser generated code to provide clean
+ * output instead of the standard format of Exception.toString(). It returns
+ * a short description of the error that occured as well as the position of
+ * next token as part of the string.
+ */
+ public String getErrorInfo()
+ {
+ if (!specialConstructor) {
+ return super.getMessage();
+ }
+ String expected = "";
+ 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 += tokenImage[expectedTokenSequences[i][j]] + " ";
+ }
+ if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
+ expected += "...";
+ }
+ expected += eol + " ";
+ }
+ String retval = "Unexpected \"";
+ Token tok = currentToken.next;
+ for (int i = 0; i < maxSize; i++) {
+ if (i != 0) retval += " ";
+ if (tok.kind == 0) {
+ retval += tokenImage[0];
+ break;
+ }
+ retval += TokenMgrError.addEscapes(tok.image);
+ tok = tok.next;
+ }
+ return retval;
+ }
+}
\ No newline at end of file diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/Parser.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/Parser.java new file mode 100644 index 00000000..ba8a0e3c --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/Parser.java @@ -0,0 +1,1263 @@ +/* Generated By:JJTree&JavaCC: Do not edit this line. Parser.java */
+package org.cheffo.jeplite;
+import java.util.*;
+import org.cheffo.jeplite.function.*;
+import org.cheffo.jeplite.function.PostfixMathCommand.*;
+
+class Parser/*@bgen(jjtree)*/implements ParserTreeConstants, ParserConstants {/*@bgen(jjtree)*/
+ protected JJTParserState jjtree = new JJTParserState();
+ private HashMap symTab;
+ private HashMap funTab;
+ private Vector errorList;
+ public SimpleNode parseStream(java.io.Reader stream, HashMap symTab_in, HashMap funTab_in) throws ParseException
+ {
+ ReInit(stream);
+ symTab = symTab_in;
+ funTab = funTab_in;
+ errorList = new Vector();
+ SimpleNode n = Start();
+ return n.jjtGetChild(0);
+ }
+
+ private void addToErrorList(String errorStr)
+ {
+ errorList.addElement(errorStr);
+ }
+
+ public Vector getErrorList()
+ {
+ return errorList;
+ }
+
+ final public SimpleNode Start() throws ParseException {
+ SimpleNode jjtn000 = new SimpleNode(JJTSTART);
+ boolean jjtc000 = true;
+ jjtree.openNodeScope(jjtn000);
+ try {
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case INTEGER_LITERAL:
+ case FLOATING_POINT_LITERAL:
+ case STRING_LITERAL:
+ case IDENTIFIER:
+ case 12:
+ case 19:
+ case 20:
+ case 25:
+ case 28:
+ Expression();
+ jj_consume_token(0);
+ jjtree.closeNodeScope(jjtn000, true);
+ jjtc000 = false;
+ return jjtn000;
+ case 0:
+ jj_consume_token(0);
+ jjtree.closeNodeScope(jjtn000, true);
+ jjtc000 = false;
+ throw new ParseException(token, "No expression entered");
+ default:
+ jj_la1[0] = jj_gen;
+ jj_consume_token(-1);
+ throw new ParseException();
+ }
+ } catch (Throwable jjte000) {
+ if (jjtc000) {
+ jjtree.clearNodeScope(jjtn000);
+ jjtc000 = false;
+ } else {
+ jjtree.popNode();
+ }
+ if (jjte000 instanceof RuntimeException) {
+ {throw (RuntimeException)jjte000;}
+ }
+ if (jjte000 instanceof ParseException) {
+ throw (ParseException)jjte000;
+ }
+ throw (Error)jjte000;
+ } finally {
+ if (jjtc000) {
+ jjtree.closeNodeScope(jjtn000, true);
+ }
+ }
+ }
+
+ final public void Expression() throws ParseException {
+ LogicalExpression();
+ }
+
+ final public void LogicalExpression() throws ParseException {
+ NotExpression();
+ label_1:
+ while (true) {
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case 10:
+ case 11:
+ ;
+ break;
+ default:
+ jj_la1[1] = jj_gen;
+ break label_1;
+ }
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case 10:
+ ASTFunNode jjtn001 = new ASTFunNode(JJTFUNNODE);
+ boolean jjtc001 = true;
+ jjtree.openNodeScope(jjtn001);
+ try {
+ jj_consume_token(10);
+ NotExpression();
+ jjtree.closeNodeScope(jjtn001, 2);
+ jjtc001 = false;
+ jjtn001.setFunction("&&", new Logical(0));
+ } catch (Throwable jjte001) {
+ if (jjtc001) {
+ jjtree.clearNodeScope(jjtn001);
+ jjtc001 = false;
+ } else {
+ jjtree.popNode();
+ }
+ if (jjte001 instanceof RuntimeException) {
+ throw (RuntimeException)jjte001;
+ }
+ if (jjte001 instanceof ParseException) {
+ throw (ParseException)jjte001;
+ }
+ throw (Error)jjte001;
+ } finally {
+ if (jjtc001) {
+ jjtree.closeNodeScope(jjtn001, 2);
+ }
+ }
+ break;
+ case 11:
+ ASTFunNode jjtn002 = new ASTFunNode(JJTFUNNODE);
+ boolean jjtc002 = true;
+ jjtree.openNodeScope(jjtn002);
+ try {
+ jj_consume_token(11);
+ NotExpression();
+ jjtree.closeNodeScope(jjtn002, 2);
+ jjtc002 = false;
+ jjtn002.setFunction("||", new Logical(1));
+ } catch (Throwable jjte002) {
+ if (jjtc002) {
+ jjtree.clearNodeScope(jjtn002);
+ jjtc002 = false;
+ } else {
+ jjtree.popNode();
+ }
+ if (jjte002 instanceof RuntimeException) {
+ throw (RuntimeException)jjte002;
+ }
+ if (jjte002 instanceof ParseException) {
+ {if (true) throw (ParseException)jjte002;}
+ }
+ {if (true) throw (Error)jjte002;}
+ } finally {
+ if (jjtc002) {
+ jjtree.closeNodeScope(jjtn002, 2);
+ }
+ }
+ break;
+ default:
+ jj_la1[2] = jj_gen;
+ jj_consume_token(-1);
+ throw new ParseException();
+ }
+ }
+ }
+
+ final public void NotExpression() throws ParseException {
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case INTEGER_LITERAL:
+ case FLOATING_POINT_LITERAL:
+ case STRING_LITERAL:
+ case IDENTIFIER:
+ case 19:
+ case 20:
+ case 25:
+ case 28:
+ RelationalExpression();
+ break;
+ case 12:
+ ASTFunNode jjtn001 = new ASTFunNode(JJTFUNNODE);
+ boolean jjtc001 = true;
+ jjtree.openNodeScope(jjtn001);
+ try {
+ jj_consume_token(12);
+ RelationalExpression();
+ jjtree.closeNodeScope(jjtn001, 1);
+ jjtc001 = false;
+ jjtn001.setFunction("!", new Not());
+ } catch (Throwable jjte001) {
+ if (jjtc001) {
+ jjtree.clearNodeScope(jjtn001);
+ jjtc001 = false;
+ } else {
+ jjtree.popNode();
+ }
+ if (jjte001 instanceof RuntimeException) {
+ throw (RuntimeException)jjte001;
+ }
+ if (jjte001 instanceof ParseException) {
+ throw (ParseException)jjte001;
+ }
+ throw (Error)jjte001;
+ } finally {
+ if (jjtc001) {
+ jjtree.closeNodeScope(jjtn001, 1);
+ }
+ }
+ break;
+ default:
+ jj_la1[3] = jj_gen;
+ jj_consume_token(-1);
+ throw new ParseException();
+ }
+ }
+
+ final public void RelationalExpression() throws ParseException {
+ OrEqualExpression();
+ label_2:
+ while (true) {
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case 13:
+ case 14:
+ ;
+ break;
+ default:
+ jj_la1[4] = jj_gen;
+ break label_2;
+ }
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case 13:
+ ASTFunNode jjtn001 = new ASTFunNode(JJTFUNNODE);
+ boolean jjtc001 = true;
+ jjtree.openNodeScope(jjtn001);
+ try {
+ jj_consume_token(13);
+ OrEqualExpression();
+ jjtree.closeNodeScope(jjtn001, 2);
+ jjtc001 = false;
+ jjtn001.setFunction("<", new Comparative(0));
+ } catch (Throwable jjte001) {
+ if (jjtc001) {
+ jjtree.clearNodeScope(jjtn001);
+ jjtc001 = false;
+ } else {
+ jjtree.popNode();
+ }
+ if (jjte001 instanceof RuntimeException) {
+ throw (RuntimeException)jjte001;
+ }
+ if (jjte001 instanceof ParseException) {
+ throw (ParseException)jjte001;
+ }
+ throw (Error)jjte001;
+ } finally {
+ if (jjtc001) {
+ jjtree.closeNodeScope(jjtn001, 2);
+ }
+ }
+ break;
+ case 14:
+ ASTFunNode jjtn002 = new ASTFunNode(JJTFUNNODE);
+ boolean jjtc002 = true;
+ jjtree.openNodeScope(jjtn002);
+ try {
+ jj_consume_token(14);
+ OrEqualExpression();
+ jjtree.closeNodeScope(jjtn002, 2);
+ jjtc002 = false;
+ jjtn002.setFunction(">", new Comparative(1));
+ } catch (Throwable jjte002) {
+ if (jjtc002) {
+ jjtree.clearNodeScope(jjtn002);
+ jjtc002 = false;
+ } else {
+ jjtree.popNode();
+ }
+ if (jjte002 instanceof RuntimeException) {
+ throw (RuntimeException)jjte002;
+ }
+ if (jjte002 instanceof ParseException) {
+ throw (ParseException)jjte002;
+ }
+ throw (Error)jjte002;
+ } finally {
+ if (jjtc002) {
+ jjtree.closeNodeScope(jjtn002, 2);
+ }
+ }
+ break;
+ default:
+ jj_la1[5] = jj_gen;
+ jj_consume_token(-1);
+ throw new ParseException();
+ }
+ }
+ }
+
+ final public void OrEqualExpression() throws ParseException {
+ EqualExpression();
+ label_3:
+ while (true) {
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case 15:
+ case 16:
+ ;
+ break;
+ default:
+ jj_la1[6] = jj_gen;
+
+ break label_3;
+
+ }
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case 15:
+ ASTFunNode jjtn001 = new ASTFunNode(JJTFUNNODE);
+ boolean jjtc001 = true;
+ jjtree.openNodeScope(jjtn001);
+ try {
+ jj_consume_token(15);
+ EqualExpression();
+ jjtree.closeNodeScope(jjtn001, 2);
+ jjtc001 = false;
+ jjtn001.setFunction("<=", new Comparative(2));
+ } catch (Throwable jjte001) {
+ if (jjtc001) {
+ jjtree.clearNodeScope(jjtn001);
+ jjtc001 = false;
+ } else {
+ jjtree.popNode();
+ }
+ if (jjte001 instanceof RuntimeException) {
+ throw (RuntimeException)jjte001;
+ }
+ if (jjte001 instanceof ParseException) {
+ throw (ParseException)jjte001;
+ }
+ throw (Error)jjte001;
+ } finally {
+ if (jjtc001) {
+ jjtree.closeNodeScope(jjtn001, 2);
+ }
+ }
+ break;
+ case 16:
+ ASTFunNode jjtn002 = new ASTFunNode(JJTFUNNODE);
+ boolean jjtc002 = true;
+ jjtree.openNodeScope(jjtn002);
+ try {
+ jj_consume_token(16);
+ EqualExpression();
+ jjtree.closeNodeScope(jjtn002, 2);
+ jjtc002 = false;
+ jjtn002.setFunction(">=", new Comparative(3));
+ } catch (Throwable jjte002) {
+ if (jjtc002) {
+ jjtree.clearNodeScope(jjtn002);
+ jjtc002 = false;
+ } else {
+ jjtree.popNode();
+ }
+ if (jjte002 instanceof RuntimeException) {
+ throw (RuntimeException)jjte002;
+ }
+ if (jjte002 instanceof ParseException) {
+ {if (true) throw (ParseException)jjte002;}
+ }
+ {if (true) throw (Error)jjte002;}
+ } finally {
+ if (jjtc002) {
+ jjtree.closeNodeScope(jjtn002, 2);
+ }
+ }
+ break;
+ default:
+ jj_la1[7] = jj_gen;
+ jj_consume_token(-1);
+ throw new ParseException();
+ }
+ }
+ }
+
+ final public void EqualExpression() throws ParseException {
+ AdditiveExpression();
+ label_4:
+ while (true) {
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case 17:
+ case 18:
+ ;
+ break;
+ default:
+ jj_la1[8] = jj_gen;
+ break label_4;
+ }
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case 17:
+ ASTFunNode jjtn001 = new ASTFunNode(JJTFUNNODE);
+ boolean jjtc001 = true;
+ jjtree.openNodeScope(jjtn001);
+ try {
+ jj_consume_token(17);
+ AdditiveExpression();
+ jjtree.closeNodeScope(jjtn001, 2);
+ jjtc001 = false;
+ jjtn001.setFunction("!=", new Comparative(4));
+ } catch (Throwable jjte001) {
+ if (jjtc001) {
+ jjtree.clearNodeScope(jjtn001);
+ jjtc001 = false;
+ } else {
+ jjtree.popNode();
+ }
+ if (jjte001 instanceof RuntimeException) {
+ throw (RuntimeException)jjte001;
+ }
+ if (jjte001 instanceof ParseException) {
+ throw (ParseException)jjte001;
+ }
+ throw (Error)jjte001;
+ } finally {
+ if (jjtc001) {
+ jjtree.closeNodeScope(jjtn001, 2);
+ }
+ }
+ break;
+ case 18:
+ ASTFunNode jjtn002 = new ASTFunNode(JJTFUNNODE);
+ boolean jjtc002 = true;
+ jjtree.openNodeScope(jjtn002);
+ try {
+ jj_consume_token(18);
+ AdditiveExpression();
+ jjtree.closeNodeScope(jjtn002, 2);
+ jjtc002 = false;
+ jjtn002.setFunction("==", new Comparative(5));
+ } catch (Throwable jjte002) {
+ if (jjtc002) {
+ jjtree.clearNodeScope(jjtn002);
+ jjtc002 = false;
+ } else {
+ jjtree.popNode();
+ }
+ if (jjte002 instanceof RuntimeException) {
+ {if (true) throw (RuntimeException)jjte002;}
+ }
+ if (jjte002 instanceof ParseException) {
+ throw (ParseException)jjte002;
+ }
+ throw (Error)jjte002;
+ } finally {
+ if (jjtc002) {
+ jjtree.closeNodeScope(jjtn002, 2);
+ }
+ }
+ break;
+ default:
+ jj_la1[9] = jj_gen;
+ jj_consume_token(-1);
+ throw new ParseException();
+ }
+ }
+ }
+
+ final public void AdditiveExpression() throws ParseException {
+ MultiplicativeExpression();
+ label_5:
+ while (true) {
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case 19:
+ case 20:
+ ;
+ break;
+ default:
+ jj_la1[10] = jj_gen;
+ break label_5;
+ }
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case 19:
+ ASTFunNode jjtn001 = new ASTFunNode(JJTFUNNODE);
+ boolean jjtc001 = true;
+ jjtree.openNodeScope(jjtn001);
+ try {
+ jj_consume_token(19);
+ MultiplicativeExpression();
+ jjtree.closeNodeScope(jjtn001, 2);
+ jjtc001 = false;
+ jjtn001.setFunction("+", PostfixMathCommand.ADD);
+ } catch (Throwable jjte001) {
+ if (jjtc001) {
+ jjtree.clearNodeScope(jjtn001);
+ jjtc001 = false;
+ } else {
+ jjtree.popNode();
+ }
+ if (jjte001 instanceof RuntimeException) {
+ throw (RuntimeException)jjte001;
+ }
+ if (jjte001 instanceof ParseException) {
+ throw (ParseException)jjte001;
+ }
+ throw (Error)jjte001;
+ } finally {
+ if (jjtc001) {
+ jjtree.closeNodeScope(jjtn001, 2);
+ }
+ }
+ break;
+ case 20:
+ ASTFunNode jjtn002 = new ASTFunNode(JJTFUNNODE);
+ boolean jjtc002 = true;
+ jjtree.openNodeScope(jjtn002);
+ try {
+ jj_consume_token(20);
+ MultiplicativeExpression();
+ jjtree.closeNodeScope(jjtn002, 2);
+ jjtc002 = false;
+ jjtn002.setFunction("-", new Subtract());
+ } catch (Throwable jjte002) {
+ if (jjtc002) {
+ jjtree.clearNodeScope(jjtn002);
+ jjtc002 = false;
+ } else {
+ jjtree.popNode();
+ }
+ if (jjte002 instanceof RuntimeException) {
+ throw (RuntimeException)jjte002;
+ }
+ if (jjte002 instanceof ParseException) {
+ throw (ParseException)jjte002;
+ }
+ throw (Error)jjte002;
+ } finally {
+ if (jjtc002) {
+ jjtree.closeNodeScope(jjtn002, 2);
+ }
+ }
+ break;
+ default:
+ jj_la1[11] = jj_gen;
+ jj_consume_token(-1);
+ throw new ParseException();
+ }
+ }
+ }
+
+ final public void MultiplicativeExpression() throws ParseException {
+ DivisionExpression();
+ label_6:
+ while (true) {
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case 21:
+ ;
+ break;
+ default:
+ jj_la1[12] = jj_gen;
+ break label_6;
+ }
+ ASTFunNode jjtn001 = new ASTFunNode(JJTFUNNODE);
+ boolean jjtc001 = true;
+ jjtree.openNodeScope(jjtn001);
+ try {
+ jj_consume_token(21);
+ DivisionExpression();
+ jjtree.closeNodeScope(jjtn001, 2);
+ jjtc001 = false;
+ jjtn001.setFunction("*", PostfixMathCommand.MULTIPLY);
+ } catch (Throwable jjte001) {
+ if (jjtc001) {
+ jjtree.clearNodeScope(jjtn001);
+ jjtc001 = false;
+ } else {
+ jjtree.popNode();
+ }
+ if (jjte001 instanceof RuntimeException) {
+ throw (RuntimeException)jjte001;
+ }
+ if (jjte001 instanceof ParseException) {
+ throw (ParseException)jjte001;
+ }
+ {if (true) throw (Error)jjte001;}
+ } finally {
+ if (jjtc001) {
+ jjtree.closeNodeScope(jjtn001, 2);
+ }
+ }
+ }
+ }
+
+ final public void DivisionExpression() throws ParseException {
+ ModulusExpression();
+ label_7:
+ while (true) {
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case 22:
+ ;
+ break;
+ default:
+ jj_la1[13] = jj_gen;
+ break label_7;
+ }
+ ASTFunNode jjtn001 = new ASTFunNode(JJTFUNNODE);
+ boolean jjtc001 = true;
+ jjtree.openNodeScope(jjtn001);
+ try {
+ jj_consume_token(22);
+ ModulusExpression();
+ jjtree.closeNodeScope(jjtn001, 2);
+ jjtc001 = false;
+ jjtn001.setFunction("/", PostfixMathCommand.DIVIDE);
+ } catch (Throwable jjte001) {
+ if (jjtc001) {
+ jjtree.clearNodeScope(jjtn001);
+ jjtc001 = false;
+ } else {
+ jjtree.popNode();
+ }
+ if (jjte001 instanceof RuntimeException) {
+ throw (RuntimeException)jjte001;
+ }
+ if (jjte001 instanceof ParseException) {
+ {if (true) throw (ParseException)jjte001;}
+ }
+ {if (true) throw (Error)jjte001;}
+ } finally {
+ if (jjtc001) {
+ jjtree.closeNodeScope(jjtn001, 2);
+ }
+ }
+ }
+ }
+
+ final public void ModulusExpression() throws ParseException {
+ UnaryExpression();
+ label_8:
+ while (true) {
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case 23:
+ ;
+ break;
+ default:
+ jj_la1[14] = jj_gen;
+ break label_8;
+ }
+ ASTFunNode jjtn001 = new ASTFunNode(JJTFUNNODE);
+ boolean jjtc001 = true;
+ jjtree.openNodeScope(jjtn001);
+ try {
+ jj_consume_token(23);
+ UnaryExpression();
+ jjtree.closeNodeScope(jjtn001, 2);
+ jjtc001 = false;
+ jjtn001.setFunction("%", new Modulus());
+ } catch (Throwable jjte001) {
+ if (jjtc001) {
+ jjtree.clearNodeScope(jjtn001);
+ jjtc001 = false;
+ } else {
+ jjtree.popNode();
+ }
+ if (jjte001 instanceof RuntimeException) {
+ throw (RuntimeException)jjte001;
+ }
+ if (jjte001 instanceof ParseException) {
+ throw (ParseException)jjte001;
+ }
+ throw (Error)jjte001;
+ } finally {
+ if (jjtc001) {
+ jjtree.closeNodeScope(jjtn001, 2);
+ }
+ }
+ }
+ }
+
+ final public void UnaryExpression() throws ParseException {
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case 19:
+ jj_consume_token(19);
+ UnaryExpression();
+ break;
+ case 20:
+ ASTFunNode jjtn001 = new ASTFunNode(JJTFUNNODE);
+ boolean jjtc001 = true;
+ jjtree.openNodeScope(jjtn001);
+ try {
+ jj_consume_token(20);
+ UnaryExpression();
+ jjtree.closeNodeScope(jjtn001, 1);
+ jjtc001 = false;
+ jjtn001.setFunction("-", PostfixMathCommand.UMINUS);
+ } catch (Throwable jjte001) {
+ if (jjtc001) {
+ jjtree.clearNodeScope(jjtn001);
+ jjtc001 = false;
+ } else {
+ jjtree.popNode();
+ }
+ if (jjte001 instanceof RuntimeException) {
+ throw (RuntimeException)jjte001;
+ }
+ if (jjte001 instanceof ParseException) {
+ throw (ParseException)jjte001;
+ }
+ throw (Error)jjte001;
+ } finally {
+ if (jjtc001) {
+ jjtree.closeNodeScope(jjtn001, 1);
+ }
+ }
+ break;
+ case INTEGER_LITERAL:
+ case FLOATING_POINT_LITERAL:
+ case STRING_LITERAL:
+ case IDENTIFIER:
+ case 25:
+ case 28:
+ PowerExpression();
+ break;
+ default:
+ jj_la1[15] = jj_gen;
+ jj_consume_token(-1);
+ throw new ParseException();
+ }
+ }
+
+ final public void PowerExpression() throws ParseException {
+ UnaryExpressionNotPlusMinus();
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case 24:
+ ASTFunNode jjtn001 = new ASTFunNode(JJTFUNNODE);
+ boolean jjtc001 = true;
+ jjtree.openNodeScope(jjtn001);
+ try {
+ jj_consume_token(24);
+ UnaryExpression();
+ jjtree.closeNodeScope(jjtn001, 2);
+ jjtc001 = false;
+ jjtn001.setFunction("^", new Power());
+ } catch (Throwable jjte001) {
+ if (jjtc001) {
+ jjtree.clearNodeScope(jjtn001);
+ jjtc001 = false;
+ } else {
+ jjtree.popNode();
+ }
+ if (jjte001 instanceof RuntimeException) {
+ throw (RuntimeException)jjte001;
+ }
+ if (jjte001 instanceof ParseException) {
+ throw (ParseException)jjte001;
+ }
+ throw (Error)jjte001;
+ } finally {
+ if (jjtc001) {
+ jjtree.closeNodeScope(jjtn001, 2);
+ }
+ }
+ break;
+ default:
+ jj_la1[16] = jj_gen;
+ ;
+ }
+ }
+
+ final public void UnaryExpressionNotPlusMinus() throws ParseException {
+ int reqArguments = 0;
+ boolean isSymbol = false;
+ boolean isFunction = false;
+ String identString = "";
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case INTEGER_LITERAL:
+ case FLOATING_POINT_LITERAL:
+ case STRING_LITERAL:
+ case 28:
+ AnyConstant();
+ break;
+ case 25:
+ jj_consume_token(25);
+ Expression();
+ jj_consume_token(26);
+ break;
+ case IDENTIFIER:
+ if (jj_2_1(2)) {
+ ASTFunNode jjtn001 = new ASTFunNode(JJTFUNNODE);
+ boolean jjtc001 = true;
+ jjtree.openNodeScope(jjtn001);
+ try {
+ identString = Identifier();
+ if (funTab.containsKey(identString))
+ {
+ reqArguments = ((PostfixMathCommand)funTab.get(identString)).getNumberOfParameters();
+ jjtn001.setFunction(identString, (PostfixMathCommand)funTab.get(identString));
+ }
+ else
+ {
+ addToErrorList("Unrecognized function \"" + identString + "\"");
+ }
+ jj_consume_token(25);
+ ArgumentList(reqArguments, identString);
+ jj_consume_token(26);
+ jjtree.closeNodeScope(jjtn001, true);
+ jjtc001 = false;
+ } catch (Throwable jjte001) {
+ if (jjtc001) {
+ jjtree.clearNodeScope(jjtn001);
+ jjtc001 = false;
+ } else {
+ jjtree.popNode();
+ }
+ if (jjte001 instanceof RuntimeException) {
+ throw (RuntimeException)jjte001;
+ }
+ if (jjte001 instanceof ParseException) {
+ throw (ParseException)jjte001;
+ }
+ throw (Error)jjte001;
+ } finally {
+ if (jjtc001) {
+ jjtree.closeNodeScope(jjtn001, true);
+ }
+ }
+ } else {
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case IDENTIFIER:
+ boolean jjtc002 = true;
+ identString = Identifier();
+ ASTVarNode jjtn002 = (ASTVarNode)symTab.get(identString);
+ if(jjtn002==null) {
+ addToErrorList("Unrecognized symbol \"" + identString +"\"");
+ jjtn002 = new ASTVarNode(JJTVARNODE);
+ return;
+ }
+ try {
+ jjtree.openNodeScope(jjtn002);
+ jjtree.closeNodeScope(jjtn002, true);
+ jjtc002 = false;
+ if (symTab.containsKey(identString))
+ {
+ jjtn002.setName(identString);
+ }
+ else
+ {
+ addToErrorList("Unrecognized symbol \"" + identString +"\"");
+ }
+ } catch (Throwable jjte002) {
+ if (jjtc002) {
+ jjtree.clearNodeScope(jjtn002);
+ jjtc002 = false;
+ } else {
+ jjtree.popNode();
+ }
+ if (jjte002 instanceof RuntimeException) {
+ throw (RuntimeException)jjte002;
+ }
+ if (jjte002 instanceof ParseException) {
+ throw (ParseException)jjte002;
+ }
+ throw (Error)jjte002;
+ } finally {
+ if (jjtc002) {
+ jjtree.closeNodeScope(jjtn002, true);
+ }
+ }
+ break;
+ default:
+ jj_la1[17] = jj_gen;
+ jj_consume_token(-1);
+ throw new ParseException();
+ }
+ }
+ break;
+ default:
+ jj_la1[18] = jj_gen;
+ jj_consume_token(-1);
+ throw new ParseException();
+ }
+ }
+
+ final public void ArgumentList(int reqArguments, String functionName) throws ParseException {
+ int count = 0;
+ String errorStr = "";
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case INTEGER_LITERAL:
+ case FLOATING_POINT_LITERAL:
+ case STRING_LITERAL:
+ case IDENTIFIER:
+ case 12:
+ case 19:
+ case 20:
+ case 25:
+ case 28:
+ Expression();
+ count++;
+ label_9:
+ while (true) {
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case 27:
+ ;
+ break;
+ default:
+ jj_la1[19] = jj_gen;
+ break label_9;
+ }
+ jj_consume_token(27);
+ Expression();
+ count++;
+ }
+ break;
+ default:
+ jj_la1[20] = jj_gen;
+ ;
+ }
+ if (reqArguments != count && reqArguments != -1)
+ {
+ errorStr = "Function \"" + functionName +"\" requires " + reqArguments + " parameter";
+ if (reqArguments!=1) errorStr += "s";
+ addToErrorList(errorStr);
+ }
+ }
+
+ final public String Identifier() throws ParseException {
+ Token t;
+ t = jj_consume_token(IDENTIFIER);
+ return t.image;
+ }
+
+ final public void AnyConstant() throws ParseException {
+ ASTConstant jjtn000 = new ASTConstant(JJTCONSTANT);
+ boolean jjtc000 = true;
+ jjtree.openNodeScope(jjtn000);Token t;
+ double value;
+ Vector array;
+ try {
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case INTEGER_LITERAL:
+ case FLOATING_POINT_LITERAL:
+ value = RealConstant();
+ jjtree.closeNodeScope(jjtn000, true);
+ jjtc000 = false;
+ jjtn000.setValue(value);
+ break;
+ default:
+ jj_la1[21] = jj_gen;
+ jj_consume_token(-1);
+ throw new ParseException();
+ }
+ } catch (Throwable jjte000) {
+ if (jjtc000) {
+ jjtree.clearNodeScope(jjtn000);
+ jjtc000 = false;
+ } else {
+ jjtree.popNode();
+ }
+ if (jjte000 instanceof RuntimeException) {
+ throw (RuntimeException)jjte000;
+ }
+ if (jjte000 instanceof ParseException) {
+ throw (ParseException)jjte000;
+ }
+ throw (Error)jjte000;
+ } finally {
+ if (jjtc000) {
+ jjtree.closeNodeScope(jjtn000, true);
+ }
+ }
+ }
+
+
+ final public double RealConstant() throws ParseException {
+ Token t;
+ double value;
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case INTEGER_LITERAL:
+ t = jj_consume_token(INTEGER_LITERAL);
+ break;
+ case FLOATING_POINT_LITERAL:
+ t = jj_consume_token(FLOATING_POINT_LITERAL);
+ break;
+ default:
+ jj_la1[23] = jj_gen;
+ jj_consume_token(-1);
+ throw new ParseException();
+ }
+ try
+ {
+ Double number = new Double(t.image);
+ value = number.doubleValue();
+ } catch (Exception e)
+ {
+ value = 0;
+ addToErrorList("Can't parse \"" + t.image + "\"");
+ }
+ return value;
+ }
+
+ final private boolean jj_2_1(int xla) {
+ jj_la = xla; jj_lastpos = jj_scanpos = token;
+ boolean retval = !jj_3_1();
+ jj_save(0, xla);
+ return retval;
+ }
+
+ final private boolean jj_3_1() {
+ if (jj_3R_11()) return true;
+ if (jj_la == 0 && jj_scanpos == jj_lastpos) return false;
+ if (jj_scan_token(25)) return true;
+ if (jj_la == 0 && jj_scanpos == jj_lastpos) return false;
+ return false;
+ }
+
+ final private boolean jj_3R_11() {
+ if (jj_scan_token(IDENTIFIER)) return true;
+ if (jj_la == 0 && jj_scanpos == jj_lastpos) return false;
+ return false;
+ }
+
+ public ParserTokenManager token_source;
+ ASCII_CharStream 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[24];
+ final private int[] jj_la1_0 = {0x121810d5,0xc00,0xc00,0x121810d4,0x6000,0x6000,0x18000,0x18000,0x60000,0x60000,0x180000,0x180000,0x200000,0x400000,0x800000,0x121800d4,0x1000000,0x80,0x120000d4,0x8000000,0x121810d4,0x10000054,0x8000000,0x14,};
+ final private JJCalls[] jj_2_rtns = new JJCalls[1];
+ private boolean jj_rescan = false;
+ private int jj_gc = 0;
+ public Parser(java.io.InputStream stream) {
+ jj_input_stream = new ASCII_CharStream(stream, 1, 1);
+ token_source = new ParserTokenManager(jj_input_stream);
+ token = new Token();
+ jj_ntk = -1;
+ jj_gen = 0;
+ for (int i = 0; i < 24; 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) {
+ jj_input_stream.ReInit(stream, 1, 1);
+ token_source.ReInit(jj_input_stream);
+ token = new Token();
+ jj_ntk = -1;
+ jjtree.reset();
+ jj_gen = 0;
+ for (int i = 0; i < 24; i++) jj_la1[i] = -1;
+ for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
+ }
+
+ public Parser(java.io.Reader stream) {
+ jj_input_stream = new ASCII_CharStream(stream, 1, 1);
+ token_source = new ParserTokenManager(jj_input_stream);
+ token = new Token();
+ jj_ntk = -1;
+ jj_gen = 0;
+ for (int i = 0; i < 24; 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;
+ jjtree.reset();
+ jj_gen = 0;
+ for (int i = 0; i < 24; i++) jj_la1[i] = -1;
+ for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
+ }
+
+ public Parser(ParserTokenManager tm) {
+ token_source = tm;
+ token = new Token();
+ jj_ntk = -1;
+ jj_gen = 0;
+ for (int i = 0; i < 24; i++) jj_la1[i] = -1;
+ for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
+ }
+
+ public void ReInit(ParserTokenManager tm) {
+ token_source = tm;
+ token = new Token();
+ jj_ntk = -1;
+ jjtree.reset();
+ jj_gen = 0;
+ for (int i = 0; i < 24; 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();
+ }
+
+ 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);
+ }
+ return (jj_scanpos.kind != kind);
+ }
+
+ 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 jj_expentries = new java.util.Vector();
+ 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 (Enumeration enum_ = jj_expentries.elements(); enum_.hasMoreElements();) {
+ int[] oldentry = (int[])(enum_.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;
+ }
+ }
+
+ final public ParseException generateParseException() {
+ jj_expentries.removeAllElements();
+ boolean[] la1tokens = new boolean[30];
+ for (int i = 0; i < 30; i++) {
+ la1tokens[i] = false;
+ }
+ if (jj_kind >= 0) {
+ la1tokens[jj_kind] = true;
+ jj_kind = -1;
+ }
+ for (int i = 0; i < 24; 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 < 30; 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 private void jj_rescan_token() {
+ jj_rescan = true;
+ for (int i = 0; i < 1; i++) {
+ 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;
+ }
+ }
+ p = p.next;
+ } while (p != null);
+ }
+ 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;
+ }
+} diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ParserConstants.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ParserConstants.java new file mode 100644 index 00000000..ec778f1f --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ParserConstants.java @@ -0,0 +1,45 @@ +package org.cheffo.jeplite;
+public interface ParserConstants {
+ int EOF = 0;
+ int INTEGER_LITERAL = 2;
+ int DECIMAL_LITERAL = 3;
+ int FLOATING_POINT_LITERAL = 4;
+ int EXPONENT = 5;
+ int STRING_LITERAL = 6;
+ int IDENTIFIER = 7;
+ int LETTER = 8;
+ int DIGIT = 9;
+ int DEFAULT = 0;
+ String[] tokenImage = {
+ "<EOF>",
+ "\" \"",
+ "<INTEGER_LITERAL>",
+ "<DECIMAL_LITERAL>",
+ "<FLOATING_POINT_LITERAL>",
+ "<EXPONENT>",
+ "<STRING_LITERAL>",
+ "<IDENTIFIER>",
+ "<LETTER>",
+ "<DIGIT>",
+ "\"&&\"",
+ "\"||\"",
+ "\"!\"",
+ "\"<\"",
+ "\">\"",
+ "\"<=\"",
+ "\">=\"",
+ "\"!=\"",
+ "\"==\"",
+ "\"+\"",
+ "\"-\"",
+ "\"*\"",
+ "\"/\"",
+ "\"%\"",
+ "\"^\"",
+ "\"(\"",
+ "\")\"",
+ "\",\"",
+ "\"[\"",
+ "\"]\"",
+ };
+}
\ No newline at end of file diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ParserTokenManager.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ParserTokenManager.java new file mode 100644 index 00000000..52b7ceb8 --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ParserTokenManager.java @@ -0,0 +1,502 @@ +package org.cheffo.jeplite;
+import java.util.Vector;
+import org.cheffo.jeplite.function.*;
+import java.io.*;
+
+public class ParserTokenManager implements ParserConstants
+{
+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(IOException e) { return pos + 1; }
+ return jjMoveNfa_0(state, pos + 1);
+}
+private final int jjMoveStringLiteralDfa0_0()
+{
+ switch(curChar)
+ {
+ case 33:
+ jjmatchedKind = 12;
+ return jjMoveStringLiteralDfa1_0(0x20000L);
+ case 37:
+ return jjStopAtPos(0, 23);
+ case 38:
+ return jjMoveStringLiteralDfa1_0(0x400L);
+ case 40:
+ return jjStopAtPos(0, 25);
+ case 41:
+ return jjStopAtPos(0, 26);
+ case 42:
+ return jjStopAtPos(0, 21);
+ case 43:
+ return jjStopAtPos(0, 19);
+ case 44:
+ return jjStopAtPos(0, 27);
+ case 45:
+ return jjStopAtPos(0, 20);
+ case 47:
+ return jjStopAtPos(0, 22);
+ case 60:
+ jjmatchedKind = 13;
+ return jjMoveStringLiteralDfa1_0(0x8000L);
+ case 61:
+ return jjMoveStringLiteralDfa1_0(0x40000L);
+ case 62:
+ jjmatchedKind = 14;
+ return jjMoveStringLiteralDfa1_0(0x10000L);
+ case 91:
+ return jjStopAtPos(0, 28);
+ case 93:
+ return jjStopAtPos(0, 29);
+ case 94:
+ return jjStopAtPos(0, 24);
+ case 124:
+ return jjMoveStringLiteralDfa1_0(0x800L);
+ default :
+ return jjMoveNfa_0(0, 0);
+ }
+}
+
+private final int jjMoveStringLiteralDfa1_0(long active0)
+{
+ try {curChar = input_stream.readChar();}
+ catch(IOException e) {
+ jjStopStringLiteralDfa_0(0, active0);
+ return 1;
+ }
+ switch(curChar)
+ {
+ case 38:
+ if ((active0 & 0x400L) != 0L)
+ return jjStopAtPos(1, 10);
+ break;
+ case 61:
+ if ((active0 & 0x8000L) != 0L)
+ return jjStopAtPos(1, 15);
+ else if ((active0 & 0x10000L) != 0L)
+ return jjStopAtPos(1, 16);
+ else if ((active0 & 0x20000L) != 0L)
+ return jjStopAtPos(1, 17);
+ else if ((active0 & 0x40000L) != 0L)
+ return jjStopAtPos(1, 18);
+ break;
+ case 124:
+ if ((active0 & 0x800L) != 0L)
+ return jjStopAtPos(1, 11);
+ 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 = {
+ 0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL
+};
+
+private final int jjMoveNfa_0(int startState, int curPos)
+{
+ int[] nextStates;
+ int startsAt = 0;
+ jjnewStateCnt = 28;
+ 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 ((0x3ff000000000000L & l) != 0L)
+ {
+ if (kind > 2)
+ kind = 2;
+ jjCheckNAddStates(0, 4);
+ }
+ else if (curChar == 34)
+ jjCheckNAddStates(5, 7);
+ else if (curChar == 46)
+ jjCheckNAdd(1);
+ break;
+ case 1:
+ if ((0x3ff000000000000L & l) == 0L)
+ break;
+ if (kind > 4)
+ kind = 4;
+ jjCheckNAddTwoStates(1, 2);
+ break;
+ case 3:
+ if ((0x280000000000L & l) != 0L)
+ jjCheckNAdd(4);
+ break;
+ case 4:
+ if ((0x3ff000000000000L & l) == 0L)
+ break;
+ if (kind > 4)
+ kind = 4;
+ jjCheckNAdd(4);
+ break;
+ case 5:
+ if (curChar == 34)
+ jjCheckNAddStates(5, 7);
+ break;
+ case 6:
+ if ((0xfffffffbffffdbffL & l) != 0L)
+ jjCheckNAddStates(5, 7);
+ break;
+ case 8:
+ if ((0x8400000000L & l) != 0L)
+ jjCheckNAddStates(5, 7);
+ break;
+ case 9:
+ if (curChar == 34 && kind > 6)
+ kind = 6;
+ break;
+ case 10:
+ if ((0xff000000000000L & l) != 0L)
+ jjCheckNAddStates(8, 11);
+ break;
+ case 11:
+ if ((0xff000000000000L & l) != 0L)
+ jjCheckNAddStates(5, 7);
+ break;
+ case 12:
+ if ((0xf000000000000L & l) != 0L)
+ jjstateSet[jjnewStateCnt++] = 13;
+ break;
+ case 13:
+ if ((0xff000000000000L & l) != 0L)
+ jjCheckNAdd(11);
+ break;
+ case 15:
+ if ((0x3ff000000000000L & l) == 0L)
+ break;
+ if (kind > 7)
+ kind = 7;
+ jjstateSet[jjnewStateCnt++] = 15;
+ break;
+ case 16:
+ if ((0x3ff000000000000L & l) == 0L)
+ break;
+ if (kind > 2)
+ kind = 2;
+ jjCheckNAddStates(0, 4);
+ break;
+ case 17:
+ if ((0x3ff000000000000L & l) == 0L)
+ break;
+ if (kind > 2)
+ kind = 2;
+ jjCheckNAdd(17);
+ break;
+ case 18:
+ if ((0x3ff000000000000L & l) != 0L)
+ jjCheckNAddTwoStates(18, 19);
+ break;
+ case 19:
+ if (curChar != 46)
+ break;
+ if (kind > 4)
+ kind = 4;
+ jjCheckNAddTwoStates(20, 21);
+ break;
+ case 20:
+ if ((0x3ff000000000000L & l) == 0L)
+ break;
+ if (kind > 4)
+ kind = 4;
+ jjCheckNAddTwoStates(20, 21);
+ break;
+ case 22:
+ if ((0x280000000000L & l) != 0L)
+ jjCheckNAdd(23);
+ break;
+ case 23:
+ if ((0x3ff000000000000L & l) == 0L)
+ break;
+ if (kind > 4)
+ kind = 4;
+ jjCheckNAdd(23);
+ break;
+ case 24:
+ if ((0x3ff000000000000L & l) != 0L)
+ jjCheckNAddTwoStates(24, 25);
+ break;
+ case 26:
+ if ((0x280000000000L & l) != 0L)
+ jjCheckNAdd(27);
+ break;
+ case 27:
+ if ((0x3ff000000000000L & l) == 0L)
+ break;
+ if (kind > 4)
+ kind = 4;
+ jjCheckNAdd(27);
+ break;
+ default : break;
+ }
+ } while(i != startsAt);
+ }
+ else if (curChar < 128)
+ {
+ long l = 1L << (curChar & 077);
+ MatchLoop: do
+ {
+ switch(jjstateSet[--i])
+ {
+ case 0:
+ case 15:
+ if ((0x7fffffe87fffffeL & l) == 0L)
+ break;
+ if (kind > 7)
+ kind = 7;
+ jjCheckNAdd(15);
+ break;
+ case 2:
+ if ((0x2000000020L & l) != 0L)
+ jjAddStates(12, 13);
+ break;
+ case 6:
+ if ((0xffffffffefffffffL & l) != 0L)
+ jjCheckNAddStates(5, 7);
+ break;
+ case 7:
+ if (curChar == 92)
+ jjAddStates(14, 16);
+ break;
+ case 8:
+ if ((0x14404410000000L & l) != 0L)
+ jjCheckNAddStates(5, 7);
+ break;
+ case 21:
+ if ((0x2000000020L & l) != 0L)
+ jjAddStates(17, 18);
+ break;
+ case 25:
+ if ((0x2000000020L & l) != 0L)
+ jjAddStates(19, 20);
+ break;
+ default : break;
+ }
+ } while(i != startsAt);
+ }
+ else
+ {
+ int i2 = (curChar & 0xff) >> 6;
+ long l2 = 1L << (curChar & 077);
+ MatchLoop: do
+ {
+ switch(jjstateSet[--i])
+ {
+ case 6:
+ if ((jjbitVec0[i2] & l2) != 0L)
+ jjAddStates(5, 7);
+ break;
+ default : break;
+ }
+ } while(i != startsAt);
+ }
+ if (kind != 0x7fffffff)
+ {
+ jjmatchedKind = kind;
+ jjmatchedPos = curPos;
+ kind = 0x7fffffff;
+ }
+ ++curPos;
+ if ((i = jjnewStateCnt) == (startsAt = 28 - (jjnewStateCnt = startsAt)))
+ return curPos;
+ try { curChar = input_stream.readChar(); }
+ catch(IOException e) { return curPos; }
+ }
+}
+
+static final int[] jjnextStates = {
+ 17, 18, 19, 24, 25, 6, 7, 9, 6, 7, 11, 9, 3, 4, 8, 10,
+ 12, 22, 23, 26, 27,
+};
+public static final String[] jjstrLiteralImages = {
+"", null, null, null, null, null, null, null, null, null, "\46\46",
+"\174\174", "\41", "\74", "\76", "\74\75", "\76\75", "\41\75", "\75\75", "\53", "\55",
+"\52", "\57", "\45", "\136", "\50", "\51", "\54", "\133", "\135", };
+public static final String[] lexStateNames = {
+ "DEFAULT",
+};
+static final long[] jjtoToken = {
+ 0x3ffffcd5L,
+};
+static final long[] jjtoSkip = {
+ 0x2L,
+};
+private ASCII_CharStream input_stream;
+private final int[] jjrounds = new int[28];
+private final int[] jjstateSet = new int[56];
+protected char curChar;
+public ParserTokenManager(ASCII_CharStream stream)
+{
+ if (ASCII_CharStream.staticFlag)
+ throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer.");
+ input_stream = stream;
+}
+public ParserTokenManager(ASCII_CharStream stream, int lexState)
+{
+ this(stream);
+ SwitchTo(lexState);
+}
+public void ReInit(ASCII_CharStream stream)
+{
+ jjmatchedPos = jjnewStateCnt = 0;
+ curLexState = defaultLexState;
+ input_stream = stream;
+ ReInitRounds();
+}
+
+private final void ReInitRounds()
+{
+ int i;
+ jjround = 0x80000001;
+ for (i = 28; i-- > 0;)
+ jjrounds[i] = 0x80000000;
+}
+public void ReInit(ASCII_CharStream stream, int lexState)
+{
+ ReInit(stream);
+ SwitchTo(lexState);
+}
+public void SwitchTo(int lexState)
+{
+ if (lexState >= 1 || lexState < 0)
+ throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE);
+ else
+ curLexState = lexState;
+}
+
+private final Token jjFillToken()
+{
+ Token t = Token.newToken(jjmatchedKind);
+ t.kind = jjmatchedKind;
+ String im = jjstrLiteralImages[jjmatchedKind];
+ t.image = (im == null) ? input_stream.GetImage() : im;
+ return t;
+}
+
+int curLexState = 0;
+int defaultLexState = 0;
+int jjnewStateCnt;
+int jjround;
+int jjmatchedPos;
+int jjmatchedKind;
+
+public final Token getNextToken()
+{
+ int kind;
+ Token specialToken = null;
+ Token matchedToken;
+ int curPos = 0;
+ EOFLoop :
+ for (;;)
+ {
+ try
+ {
+ curChar = input_stream.BeginToken();
+ }
+ catch(IOException e)
+ {
+ jjmatchedKind = 0;
+ matchedToken = jjFillToken();
+ return matchedToken;
+ }
+
+ try { input_stream.backup(0);
+ while (curChar <= 32 && (0x100000000L & (1L << curChar)) != 0L)
+ curChar = input_stream.BeginToken();
+ }
+ catch (IOException e1) { continue EOFLoop; }
+ jjmatchedKind = 0x7fffffff;
+ jjmatchedPos = 0;
+ curPos = jjMoveStringLiteralDfa0_0();
+ if (jjmatchedKind != 0x7fffffff)
+ {
+ if (jjmatchedPos + 1 < curPos)
+ input_stream.backup(curPos - jjmatchedPos - 1);
+ if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L)
+ {
+ matchedToken = jjFillToken();
+ return matchedToken;
+ }
+ else
+ {
+ continue EOFLoop;
+ }
+ }
+ String error_after = null;
+ boolean EOFSeen = false;
+ try { input_stream.readChar(); input_stream.backup(1); }
+ catch (IOException e1) {
+ EOFSeen = true;
+ error_after = curPos <= 1 ? "" : input_stream.GetImage();
+ }
+ if (!EOFSeen) {
+ input_stream.backup(1);
+ error_after = curPos <= 1 ? "" : input_stream.GetImage();
+ }
+ throw new TokenMgrError(EOFSeen, curLexState, error_after, curChar, TokenMgrError.LEXICAL_ERROR);
+ }
+}
+}
\ No newline at end of file diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ParserTreeConstants.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ParserTreeConstants.java new file mode 100644 index 00000000..ac9b3901 --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ParserTreeConstants.java @@ -0,0 +1,17 @@ +package org.cheffo.jeplite;
+public interface ParserTreeConstants
+{
+ public int JJTSTART = 0;
+ public int JJTVOID = 1;
+ public int JJTFUNNODE = 2;
+ public int JJTVARNODE = 3;
+ public int JJTCONSTANT = 4;
+
+ public String[] jjtNodeName = {
+ "Start",
+ "void",
+ "FunNode",
+ "VarNode",
+ "Constant",
+ };
+}
\ No newline at end of file diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ParserVisitor.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ParserVisitor.java new file mode 100644 index 00000000..39c63eec --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/ParserVisitor.java @@ -0,0 +1,8 @@ +package org.cheffo.jeplite;
+public interface ParserVisitor
+{
+ public Object visit(SimpleNode node, Object data);
+ public Object visit(ASTFunNode node, Object data);
+ public Object visit(ASTVarNode node, Object data);
+ public Object visit(ASTConstant node, Object data);
+}
\ No newline at end of file diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/SimpleNode.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/SimpleNode.java new file mode 100644 index 00000000..c47d533f --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/SimpleNode.java @@ -0,0 +1,78 @@ +package org.cheffo.jeplite;
+import org.cheffo.jeplite.util.*;
+public class SimpleNode {
+ protected SimpleNode parent;
+ protected SimpleNode[] children;
+ protected int id;
+ protected Parser parser;
+ protected String name;
+
+ public SimpleNode(int i) {
+ id = i;
+ }
+
+ public SimpleNode(Parser p, int i) {
+ this(i);
+ parser = p;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void jjtOpen() {
+ }
+
+ public void jjtClose() {
+ }
+
+ public final void jjtSetParent(SimpleNode n) { parent = n; }
+ public final SimpleNode jjtGetParent() { return parent; }
+
+ public void jjtAddChild(SimpleNode n, int i) {
+ if (children == null) {
+ children = new SimpleNode[i + 1];
+ } else if (i >= children.length) {
+ SimpleNode c[] = new SimpleNode[i + 1];
+ System.arraycopy(children, 0, c, 0, children.length);
+ children = c;
+ }
+ children[i] = n;
+ }
+
+ public final SimpleNode jjtGetChild(int i) {
+ return children[i];
+ }
+
+ public final int jjtGetNumChildren() {
+ return (children == null) ? 0 : children.length;
+ }
+
+ public Object jjtAccept(ParserVisitor visitor, Object data) {
+ return visitor.visit(this, data);
+ }
+
+ public Object childrenAccept(ParserVisitor visitor, Object data) {
+ if (children != null) {
+ for (int i = 0; i < children.length; ++i) {
+ children[i].jjtAccept(visitor, data);
+ }
+ }
+ return data;
+ }
+
+ public String toString() { return ParserTreeConstants.jjtNodeName[id]; }
+
+ public double getValue() throws ParseException
+ {
+ return 0;
+ }
+
+ public void getValue(DoubleStack stack) throws ParseException {
+ stack.push(getValue());
+ }
+}
\ No newline at end of file diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/Token.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/Token.java new file mode 100644 index 00000000..d2c77fe9 --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/Token.java @@ -0,0 +1,68 @@ +/**
+ * Describes the input token stream.
+ */
+package org.cheffo.jeplite;
+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;
+ /**
+ * 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 final 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();
+ }
+ }
+}
\ No newline at end of file diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/TokenMgrError.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/TokenMgrError.java new file mode 100644 index 00000000..4c2249c8 --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/TokenMgrError.java @@ -0,0 +1,123 @@ +package org.cheffo.jeplite;
+public class TokenMgrError extends Error
+{
+ /**
+ * 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
+ */
+ 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.
+ */
+ private static final String LexicalError(boolean EOFSeen, int lexState, String errorAfter, char curChar) {
+ return("Lexical error 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, String errorAfter, char curChar, int reason) {
+ this(LexicalError(EOFSeen, lexState, errorAfter, curChar), reason);
+ }
+}
\ No newline at end of file diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/function/PostfixMathCommand.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/function/PostfixMathCommand.java new file mode 100644 index 00000000..17a6dbb6 --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/function/PostfixMathCommand.java @@ -0,0 +1,486 @@ +/*****************************************************************************
+
+JEP - Java Expression Parser
+ JEP is a Java package for parsing and evaluating mathematical
+ expressions. It currently supports user defined variables,
+ constant, and functions. A number of common mathematical
+ functions and constants are included.
+ JEPLite is a simplified version of JEP.
+
+JEP Author: Nathan Funk
+JEPLite Author: Stephen "Cheffo" Kolaroff
+JEP Copyright (C) 2001 Nathan Funk
+JEPLite Copyright (C) 2002 Stefan Kolarov
+
+ JEPLite is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ JEPLite is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with JEPLite; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+*****************************************************************************/
+package org.cheffo.jeplite.function;
+import org.cheffo.jeplite.util.*;
+import org.cheffo.jeplite.*;
+import java.util.HashMap;
+
+public abstract class PostfixMathCommand
+{
+ public static final PostfixMathCommand ADD = new Add();
+ public static final PostfixMathCommand DIVIDE = new Divide();
+ public static final PostfixMathCommand MULTIPLY = new Multiply();
+ public static final PostfixMathCommand UMINUS = new UMinus();
+ public static final PostfixMathCommand AND = new Logical(0);
+ public static final PostfixMathCommand OR = new Logical(1);
+
+ protected int numberOfParameters;
+ public final int getNumberOfParameters()
+ {
+ return numberOfParameters;
+ }
+
+ public double operation(double[] params) throws ParseException{throw new ParseException("Not implemented");}
+
+ public void run(DoubleStack inStack)
+ throws ParseException
+ {
+ double[] params = new double[numberOfParameters];
+ for(int i=numberOfParameters-1; i>-1; i--)
+ params[i] = inStack.pop();
+ inStack.push(operation(params));
+ return;
+ }
+
+ public static void fillFunctionTable(HashMap funTab) {
+ funTab.put("sin", new Sine());
+ funTab.put("cos", new Cosine());
+ funTab.put("tan", new Tangent());
+ funTab.put("asin", new ArcSine());
+ funTab.put("acos", new ArcCosine());
+ funTab.put("atan", new ArcTangent());
+ funTab.put("sqrt", new Sqrt());
+
+ funTab.put("log", new Logarithm());
+ funTab.put("ln", new NaturalLogarithm());
+
+ funTab.put("angle", new Angle());
+ funTab.put("abs", new Abs());
+ funTab.put("mod", new Modulus());
+ funTab.put("sum", new Sum());
+
+ funTab.put("rand", new Random());
+
+ funTab.put("umin", new UMinus());
+ funTab.put("add", new Add());
+ }
+
+ static class Abs extends PostfixMathCommand
+ {
+ public Abs() {
+ numberOfParameters = 1;
+ }
+
+ public final void run(DoubleStack stack) {
+ stack.push(Math.abs(stack.pop()));
+ }
+ }
+
+ static class Add extends PostfixMathCommand
+ {
+ public Add()
+ {
+ numberOfParameters = 2;
+ }
+
+ public final void run(DoubleStack stack) {
+ stack.push(stack.pop()+stack.pop());
+ }
+ }
+
+ static class Angle extends PostfixMathCommand
+ {
+ public Angle()
+ {
+ numberOfParameters = 2;
+ }
+
+ public final void run(DoubleStack inStack)
+ throws ParseException
+ {
+ double param2 = inStack.pop();
+ double param1 = inStack.pop();
+ inStack.push(Math.atan2(param1, param2));
+ }
+ }
+
+ static class ArcCosine extends PostfixMathCommand {
+ public ArcCosine()
+ {
+ numberOfParameters = 1;
+ }
+
+ public final void run(DoubleStack stack)
+ throws ParseException
+ {
+ stack.push(Math.acos(stack.pop()));
+ }
+ }
+
+ static class ArcSine extends PostfixMathCommand
+ {
+ public ArcSine()
+ {
+ numberOfParameters = 1;
+ }
+
+ public final double operation(double[] params)
+ throws ParseException
+ {
+ return Math.asin(params[0]);
+ }
+ }
+
+ static class ArcTangent extends PostfixMathCommand {
+ public ArcTangent()
+ {
+ numberOfParameters = 1;
+ }
+
+ public final double operation(double[] params)
+ throws ParseException
+ {
+ return Math.atan(params[0]);
+ }
+ }
+
+ static class Cosine extends PostfixMathCommand
+ {
+ public Cosine()
+ {
+ numberOfParameters = 1;
+ }
+
+ public final double operation(double[] params)
+ throws ParseException
+ {
+ return Math.cos(params[0]);
+ }
+ }
+
+ static class Logarithm extends PostfixMathCommand
+ {
+ public Logarithm()
+ {
+ numberOfParameters = 1;
+ }
+ private static final double LOG_10 = Math.log(10);
+
+ public final double operation(double[] params)
+ throws ParseException
+ {
+ return Math.log(params[0])/LOG_10;
+ }
+ }
+
+ static class NaturalLogarithm extends PostfixMathCommand
+ {
+ public NaturalLogarithm()
+ {
+ numberOfParameters = 1;
+ }
+
+ public final double operation(double[] params)
+ throws ParseException
+ {
+ return Math.log(params[0]);
+ }
+ }
+
+ static class Sine extends PostfixMathCommand
+ {
+ public Sine()
+ {
+ numberOfParameters = 1;
+ }
+
+ public final double operation(double[] params)
+ throws ParseException
+ {
+ return Math.sin(params[0]);
+ }
+ }
+
+ static class Tangent extends PostfixMathCommand
+ {
+ public Tangent()
+ {
+ numberOfParameters = 1;
+ }
+
+ public final double operation(double[] params)
+ throws ParseException
+ {
+ return Math.tan(params[0]);
+ }
+ }
+
+ static class UMinus extends PostfixMathCommand
+ {
+ public UMinus()
+ {
+ numberOfParameters = 1;
+ }
+
+ public final void run(DoubleStack stack)
+ throws ParseException
+ {
+ stack.push(-stack.pop());
+ }
+ }
+
+ static class Sqrt extends PostfixMathCommand
+ {
+ public Sqrt()
+ {
+ numberOfParameters = 1;
+ }
+
+ public final void run(DoubleStack stack)
+ throws ParseException
+ {
+ stack.push(Math.sqrt(stack.pop()));
+ }
+ }
+
+ public static class Divide extends PostfixMathCommand
+ {
+ public Divide()
+ {
+ numberOfParameters = 2;
+ }
+
+ public final void run(DoubleStack stack) {
+ double p2 = stack.pop();
+ stack.push(stack.pop()/p2);
+ }
+
+ public final double operation(double[] params)
+ throws ParseException
+ {
+ return params[0]/params[1];
+ }
+ }
+
+ public static class Subtract extends PostfixMathCommand
+ {
+ public Subtract()
+ {
+ numberOfParameters = 2;
+ }
+
+ public final double operation(double[] params){return params[0]-params[1];}
+ }
+
+ public static class Comparative extends PostfixMathCommand
+ {
+ int id;
+ double tolerance;
+
+ public double operation(double[] params) {return 0;}
+ public Comparative(int id_in)
+ {
+ id = id_in;
+ numberOfParameters = 2;
+ tolerance = 1e-6;
+ }
+
+ public final void run(DoubleStack inStack)
+ throws ParseException
+ {
+ double y = inStack.pop();
+ double x = inStack.pop();
+ int r;
+ switch (id)
+ {
+ case 0:
+ r = (x<y) ? 1 : 0;
+ break;
+ case 1:
+ r = (x>y) ? 1 : 0;
+ break;
+ case 2:
+ r = (x<=y) ? 1 : 0;
+ break;
+ case 3:
+ r = (x>=y) ? 1 : 0;
+ break;
+ case 4:
+ r = (x!=y) ? 1 : 0;
+ break;
+ case 5:
+ r = (x==y) ? 1 : 0;
+ break;
+ default:
+ throw new ParseException("Unknown relational operator");
+ }
+ inStack.push(r);
+ }
+ }
+
+ public static class Power extends PostfixMathCommand
+ {
+ public Power()
+ {
+ numberOfParameters = 2;
+ }
+
+ public final double operation(double[] params) {return 0;}
+ public final void run(DoubleStack inStack)
+ throws ParseException
+ {
+ double param2 = inStack.pop();
+ double param1 = inStack.pop();
+
+ inStack.push(Math.pow(param1, param2));
+ }
+ }
+
+ static class Random extends PostfixMathCommand
+ {
+ public Random()
+ {
+ numberOfParameters = 0;
+
+ }
+
+ public double operation(double[] params){return 0;}
+
+ public final void run(DoubleStack inStack)
+ throws ParseException
+ {
+ inStack.push(Math.random());
+ }
+ }
+
+ public static class Logical extends PostfixMathCommand
+ {
+ int id;
+
+ public Logical(int id_in)
+ {
+ id = id_in;
+ numberOfParameters = 2;
+ }
+
+ public final double operation(double[] params) {return 0;}
+ public final void run(DoubleStack inStack)
+ throws ParseException
+ {
+ double y = inStack.pop();
+ double x = inStack.pop();
+ int r;
+
+ switch (id)
+ {
+ case 0:
+ // AND
+ r = ((x!=0d) && (y!=0d)) ? 1 : 0;
+ break;
+ case 1:
+ // OR
+ r = ((x!=0d) || (y!=0d)) ? 1 : 0;
+ break;
+ default:
+ r = 0;
+ }
+
+ inStack.push(r);
+ return;
+ }
+ }
+
+ public static class Multiply extends PostfixMathCommand
+ {
+ public Multiply()
+ {
+ numberOfParameters = 2;
+ }
+
+ public final double operation(double[] params) {return 0;}
+ public final void run(DoubleStack inStack)
+ throws ParseException
+ {
+ inStack.push(inStack.pop()*inStack.pop());
+ return;
+ }
+ }
+
+ public static class Not extends PostfixMathCommand
+ {
+ public Not()
+ {
+ numberOfParameters = 1;
+
+ }
+
+ public double operation(double[] params) {return 0;}
+ public void run(DoubleStack inStack)
+ throws ParseException
+ {
+ double param = inStack.pop();
+ int r = (param==0) ? 1 : 0;
+ inStack.push(r);
+ return;
+ }
+
+ }
+
+ public static class Modulus extends PostfixMathCommand
+ {
+ public Modulus()
+ {
+ numberOfParameters = 2;
+ }
+
+ public double operation(double[] params){return 0;}
+ public final void run(DoubleStack inStack)
+ throws ParseException
+ {
+ double param2 = inStack.pop();
+ double param1 = inStack.pop();
+ double result = param1 % param2;
+ inStack.push(result);
+ return;
+ }
+ }
+
+ static class Sum extends PostfixMathCommand
+ {
+ public Sum()
+ {
+ numberOfParameters = -1;
+ }
+
+ public final double operation(double[] params){return 0;}
+ public void run(DoubleStack inStack)
+ throws ParseException
+ {
+ if (null == inStack)
+ {
+ throw new ParseException("Stack argument null");
+ }
+ double r = 0;
+ while(!inStack.isEmpty())
+ r += inStack.pop();
+ inStack.push(r);
+ }
+ }
+}
diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/optimizer/ExpressionOptimizer.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/optimizer/ExpressionOptimizer.java new file mode 100644 index 00000000..1c8f777c --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/optimizer/ExpressionOptimizer.java @@ -0,0 +1,162 @@ +package org.cheffo.jeplite.optimizer; + +/** + * Title: + * Description: + * Copyright: Copyright (c) 2002 + * Company: + * @author + * @version 1.0 + */ +import org.cheffo.jeplite.*; +import org.cheffo.jeplite.util.*; +import org.cheffo.jeplite.function.*; + +import java.util.*; +public class ExpressionOptimizer implements ParserVisitor { + + SimpleNode node; + final HashMap constTab = new HashMap(); + public ExpressionOptimizer(SimpleNode node) { + this.node = node; + } + + /** + * Marks a variable name to be a constant name. + */ + public void addConst(String constName) { + constTab.put(constName, constName); + } + + /** + * Unmarks a variable name to be a constant name. + */ + public void removeConst(String constName) { + constTab.remove(constName); + } + + public void clearConstants() { + constTab.clear(); + } + + public SimpleNode optimize() { + return (SimpleNode)node.jjtAccept(this, null); + } + + public Object visit(ASTFunNode node, Object data) { + SimpleNode res = node; + try{ + boolean allConstNode = true; + int numChildren = node.jjtGetNumChildren(); + SimpleNode[] nodes = new SimpleNode[numChildren]; + for(int i=0; i<numChildren; i++) { + nodes[i] = (SimpleNode)node.jjtGetChild(i).jjtAccept(this, data); + allConstNode &= (nodes[i] instanceof ASTConstant); + // well, let wind the whole loop + } + + if(res.getName().equals("+")||res.getName().equals("*")) + res = (ASTFunNode)visitAdditive(node, data); + + if(allConstNode) { + ASTConstant constRes = new ASTConstant(-1); + constRes.jjtSetParent(node.jjtGetParent()); + constRes.setValue(node.getValue()); + res = constRes; + } + + } catch(Exception ex) {ex.printStackTrace();} + return res; + } + + /** + * Now we are sure that we had visited/preevaluated all possible children. + */ + private Object visitAdditive(ASTFunNode node, Object data) { + ArrayList nodes = new ArrayList(); + int numChildren = node.jjtGetNumChildren(); + String nodeName = node.getName(); + boolean toOptimize = false; + for(int i=0; i<numChildren; i++) { + SimpleNode curChild = node.jjtGetChild(i); + String curChildName = curChild.getName(); + if(curChildName!=null&&curChildName.equals(nodeName)) { + toOptimize = true; + int grandChildrenNum = curChild.jjtGetNumChildren(); + for(int j=0; j<grandChildrenNum; j++) + nodes.add(curChild.jjtGetChild(j)); + } else { + nodes.add(curChild); + } + } + ASTFunNode res = node; + if(toOptimize) { + res = new ASTFunNode(ParserTreeConstants.JJTFUNNODE); + res.setName(node.getName()); + res.jjtSetParent(node.jjtGetParent()); + int pos = nodes.size()-1; + for(Iterator i=nodes.iterator(); i.hasNext();) + node.jjtAddChild((SimpleNode)i.next(), pos--); + if(nodeName.equals("+")) + res.setFunction("+", new Madd(nodes.size())); + else + res.setFunction("*", new Mmul(nodes.size())); + } + return res; + } + + /** + * If a var node is defined in the const table, make it to be a real constant. + */ + public Object visit(ASTVarNode node, Object data) { + boolean isConst = (constTab.get(node.getName())!=null); + SimpleNode res = node; + if(isConst) { + try { + ASTConstant res1 = new ASTConstant(ParserTreeConstants.JJTCONSTANT); + res1.setValue(res.getValue()); + res1.jjtSetParent(res.jjtGetParent()); + res = res1; + } catch(ParseException ex) {ex.printStackTrace();} + } + return res; + } + + public Object visit(ASTConstant node, Object data) { + return node; + } + + public Object visit(SimpleNode node, Object data) { + return node; + } + + static class Madd extends PostfixMathCommand { + Madd(int numberOfParameters) { + this.numberOfParameters = numberOfParameters; + } + + public double operation(double[] params) {return 0;}; + + public void run(DoubleStack stack) { + double res = 0; + for(int i=0; i<numberOfParameters; i++) + res += stack.pop(); + stack.push(res); + } + } + + static class Mmul extends PostfixMathCommand { + Mmul(int numberOfParameters) { + this.numberOfParameters = numberOfParameters; + } + + public double operation(double[] params) {return 0;}; + + public void run(DoubleStack stack) { + double res = 1; + for(int i=0; i<numberOfParameters; i++) + res *= stack.pop(); + stack.push(res); + } + } +}
\ No newline at end of file diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/test/Tests.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/test/Tests.java new file mode 100644 index 00000000..c14ad33f --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/test/Tests.java @@ -0,0 +1,128 @@ +package org.cheffo.jeplite.test; + +import java.util.*; +import java.io.*; + +import org.cheffo.jeplite.*; +import org.cheffo.jeplite.util.*; +import org.cheffo.jeplite.optimizer.*; + +/** + * Title: + * Description: + * Copyright: Copyright (c) 2002 + * Company: + * @author + * @version 1.0 + */ + +/** + * Provided to check for backward compability and performance. + */ +public class Tests { + + public Tests() { + } + + static void parseParams(String[] args) { + for(int i=0; i<args.length; i+=2) { + params.put(args[i].toLowerCase().trim(), args[i+1]); + } + } + + static JEP jep = new JEP(); + static HashMap params = new HashMap(); + + static void doIt(String toParse, BufferedWriter fw, SimpleNode optNode) throws Exception { + long[] testArray = new long[10]; + double d = 0; + DoubleStack stack = new DoubleStack(); + for(int j=0; j<10; j++) { + Thread.yield(); + long start = System.currentTimeMillis(); + for(int i=0; i<100000; i++){ + d = optNode.getValue(); + } + testArray[j] = System.currentTimeMillis()-start; + } + fw.write("100000 evaluations: "); + for(int j=0; j<10; j++) { + fw.write(testArray[j]+", "); + } + fw.write("\n"); + } + + public static void main(String[] args) throws Exception { + Date startTime = new Date(); + parseParams(args); + File inFile = new File((String)params.get("-file")); + File logFile = new File((String)params.get("-logfile")); + + BufferedReader fr = new BufferedReader(new FileReader(inFile)); + BufferedWriter fw = new BufferedWriter(new FileWriter(logFile)); + + + jep.addStandardConstants(); + jep.addStandardFunctions(); + + String curLine = null; + int lines = 0; + while(null!=(curLine=fr.readLine())) { + if(curLine.startsWith("#")) + continue; + String description = curLine; + String toParse = fr.readLine(); + double result = Double.parseDouble(fr.readLine().trim()); + + fw.write("Processing:"+toParse+",\n"); + fw.write("Expected: "+result+"\n"); + fw.flush(); + + // Give enought time to the jit compiler. + double d = 0; + DoubleStack stack = new DoubleStack(); + for(int i=0; i<1000; i++) { + jep.parseExpression(toParse); + d = jep.getValue(stack); + } + SimpleNode optNode = jep.getTopNode(); + //if(Boolean.getBoolean("noopt")) { + fw.write("Not Optimized: "); + doIt(toParse, fw, optNode); + //} + + //if(Boolean.getBoolean("opt")) { + ExpressionOptimizer optimizer = new ExpressionOptimizer(jep.getTopNode()); + //optimizer.addConst("pi"); + //optimizer.addConst("e"); + optNode = optimizer.optimize(); + + fw.write("Optimized : "); + + doIt(toParse, fw, optNode); + + long[] testArray = new long[10]; + for(int j=0; j<10; j++) { + Thread.yield(); + long start = System.currentTimeMillis(); + for(int i=0; i<1000; i++){ + jep.parseExpression(toParse); + } + testArray[j] = System.currentTimeMillis()-start; + } + fw.write("1000 parses: "); + for(int j=0; j<10; j++) { + fw.write(testArray[j]+", "); + } + fw.write("\n"); + fw.write(d+"\n_____________________________________________________\n"); + fw.flush(); + //} + } + Date endTime = new Date(); + fw.write("Start time: "+startTime+"\n"); + fw.write("End time: "+endTime+"\n"); + fw.write("Total time: "+(endTime.getTime()-startTime.getTime())+ " ms"); + fw.close(); + } +}
\ No newline at end of file diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/util/DoubleStack.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/util/DoubleStack.java new file mode 100644 index 00000000..a6407ad0 --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/util/DoubleStack.java @@ -0,0 +1,57 @@ +package org.cheffo.jeplite.util; + +public class DoubleStack { + private static final int DEFAULT_STACK_DEPTH = 10; + private static final int DEFAULT_STACK_INCREMENT = DEFAULT_STACK_DEPTH; + private double[] theStack; + private int stackPtr; + private int stackDepth; + private int stackIncrement; + public static int instances; + + public DoubleStack() { + this(DEFAULT_STACK_DEPTH); + } + + public DoubleStack(int stackDepth) { + theStack = new double[this.stackDepth=stackDepth]; + instances++; + } + + public final double peek() { + return theStack[stackPtr-1]; + } + + public final double pop() { + return theStack[--stackPtr]; + } + + public final void push(double what) { + if(stackPtr==stackDepth) + enlarge(); + theStack[stackPtr++] = what; + } + + public final boolean isEmpty() { + return stackPtr==0; + } + + public final int size() { + return stackPtr; + } + + private final void enlarge() { + stackDepth += stackIncrement; + double[] newStack = new double[stackDepth]; + System.arraycopy(theStack, 0, newStack, 0, stackDepth); + theStack = newStack; + } + + public final double elementAt(int index) { + return theStack[0]; + } + + public final void removeAllElements() { + stackPtr = 0; + } +}
\ No newline at end of file diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/util/IntegerStack.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/util/IntegerStack.java new file mode 100644 index 00000000..2abeba99 --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/util/IntegerStack.java @@ -0,0 +1,57 @@ +package org.cheffo.jeplite.util; + +public class IntegerStack { + private static final int DEFAULT_STACK_DEPTH = 10; + private static final int DEFAULT_STACK_INCREMENT = DEFAULT_STACK_DEPTH; + private int[] theStack; + private int stackPtr; + private int stackDepth; + private int stackIncrement; + public static int instances; + + public IntegerStack() { + this(DEFAULT_STACK_DEPTH); + } + + public IntegerStack(int stackDepth) { + theStack = new int[this.stackDepth=stackDepth]; + instances++; + } + + public final int peek() { + return theStack[stackPtr-1]; + } + + public final int pop() { + return theStack[--stackPtr]; + } + + public final void push(int what) { + if(stackPtr==stackDepth) + enlarge(); + theStack[stackPtr++] = what; + } + + public final boolean isEmpty() { + return stackPtr==0; + } + + public final int size() { + return stackPtr; + } + + private final void enlarge() { + stackDepth += stackIncrement; + int[] newStack = new int[stackDepth]; + System.arraycopy(theStack, 0, newStack, 0, stackDepth); + theStack = newStack; + } + + public final int elementAt(int index) { + return theStack[0]; + } + + public final void removeAllElements() { + stackPtr = 0; + } +}
\ No newline at end of file diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/util/SimpleNodeStack.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/util/SimpleNodeStack.java new file mode 100644 index 00000000..f19198b6 --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/cheffo/jeplite/util/SimpleNodeStack.java @@ -0,0 +1,58 @@ +package org.cheffo.jeplite.util;
+import org.cheffo.jeplite.*;
+
+public class SimpleNodeStack {
+ private static final int DEFAULT_STACK_DEPTH = 10;
+ private static final int DEFAULT_STACK_INCREMENT = DEFAULT_STACK_DEPTH;
+ private SimpleNode[] theStack;
+ private int stackPtr;
+ private int stackDepth;
+ private int stackIncrement;
+ public static int instances;
+
+ public SimpleNodeStack() {
+ this(DEFAULT_STACK_DEPTH);
+ }
+
+ public SimpleNodeStack(int stackDepth) {
+ theStack = new SimpleNode[this.stackDepth=stackDepth];
+ instances++;
+ }
+
+ public final SimpleNode peek() {
+ return theStack[stackPtr-1];
+ }
+
+ public final SimpleNode pop() {
+ return theStack[--stackPtr];
+ }
+
+ public final void push(SimpleNode what) {
+ if(stackPtr==stackDepth)
+ enlarge();
+ theStack[stackPtr++] = what;
+ }
+
+ public final boolean isEmpty() {
+ return stackPtr==0;
+ }
+
+ public final int size() {
+ return stackPtr;
+ }
+
+ private final void enlarge() {
+ stackDepth += stackIncrement;
+ SimpleNode[] newStack = new SimpleNode[stackDepth];
+ System.arraycopy(theStack, 0, newStack, 0, stackDepth);
+ theStack = newStack;
+ }
+
+ public final SimpleNode elementAt(int index) {
+ return theStack[0];
+ }
+
+ public final void removeAllElements() {
+ stackPtr = 0;
+ }
+}
\ No newline at end of file diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/reprap/artofillusion/CSGEvaluatorDialog.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/reprap/artofillusion/CSGEvaluatorDialog.java new file mode 100644 index 00000000..8b88b961 --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/reprap/artofillusion/CSGEvaluatorDialog.java @@ -0,0 +1,146 @@ +/* + * This program is free software; you can redistribute it and/or modify it under the + * terms of the GNU General Public License as published by the Free Software + * Foundation; either version 2 of the License, or (at your option) any later version. + * This program is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A + * PARTICULAR PURPOSE. See the GNU General Public License for more details. + */ +package org.reprap.artofillusion; + +import java.awt.Insets; +import java.awt.Rectangle; + +import artofillusion.LayoutWindow; +import buoy.event.CommandEvent; +import buoy.event.KeyPressedEvent; +import buoy.event.WindowClosingEvent; +import buoy.widget.BButton; +import buoy.widget.BDialog; +import buoy.widget.BLabel; +import buoy.widget.BorderContainer; +import buoy.widget.FormContainer; +import buoy.widget.LayoutInfo; + + + + +import java.util.*; +import java.io.*; + +import org.cheffo.jeplite.*; +import org.cheffo.jeplite.util.*; +import org.cheffo.jeplite.optimizer.*; + + +/** + * CSGEvaluator dialog + */ +class CSGEvaluatorDialog extends BDialog +{ + LayoutWindow window; + JEP jep = new JEP(); + + public CSGEvaluatorDialog(LayoutWindow window) + { + super(window, "CSG Evaluator ", false); // Modeless + + jep.addVariable("x", 22.5); + jep.parseExpression("x*2-3"); + + this.window = window; + this.setResizable(false); + + CSGEvaluatorEngine engine = new CSGEvaluatorEngine(window); + + BorderContainer bc = new BorderContainer(); + this.setContent(bc); + + bc.setDefaultLayout(new LayoutInfo()); + + String versionstr = "1.0"; + // FIXME: This was an attempt to pick up the version from the extensions.xml file, + // but it didn't work out since the classloader found the wrong file. + /* + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder; + try { + builder = factory.newDocumentBuilder(); + Document doc = builder.parse(CSGEvaluatorDialog.class.getResourceAsStream("/extensions.xml")); + Element extensions = doc.getDocumentElement(); + versionstr = extensions.getAttribute("version"); + } catch (Exception e) { + e.printStackTrace(); + } + */ + + try { + + + bc.add(new BLabel("<html>CSG Evaluator Control Panel <font size=1>V"+versionstr+"</font>" + jep.getValue() + "</html>"), BorderContainer.NORTH); + } + catch (Exception ex) + {} + + String[] buttons = new String [] {"evaluate", "devaluate", "union", "intersection", "difference"}; + String[] labels = new String [] {"Actions", null, "Boolean Op", null, null}; + + FormContainer fc = new FormContainer(2, buttons.length+1); + bc.add(fc, BorderContainer.CENTER); + + for (int i = 0; i < buttons.length; i++) { + if (labels[i] != null) { + fc.add(new BLabel(labels[i]), 0, i, new LayoutInfo(LayoutInfo.EAST, LayoutInfo.NONE, new Insets(2, 0, 2, 5), null)); + } + BButton button = new BButton(buttons[i]); + fc.add(button, 1, i, new LayoutInfo(LayoutInfo.WEST, LayoutInfo.HORIZONTAL, new Insets(2, 0, 2, 0), null)); + button.addEventLink(KeyPressedEvent.class, this, "keyPressed"); // For Esc support + button.addEventLink(CommandEvent.class, engine, buttons[i]); + } +// BButton button = new BButton("test"); +// fc.add(button, 1, buttons.length); +// button.addEventLink(CommandEvent.class, this, "test"); + + // Close button + BButton closeButton; + bc.add(closeButton = new BButton("close"), BorderContainer.SOUTH); + closeButton.addEventLink(CommandEvent.class, this, "closeWindow"); + closeButton.addEventLink(KeyPressedEvent.class, this, "keyPressed"); // For Esc support + // FIXME: Other events (most noticeably Cmd-Z (undo)) are consumed and won't reach our + // parent window. + setDefaultButton(closeButton); + + addEventLink(WindowClosingEvent.class, this, "closeWindow"); + pack(); + + // Move dialog to lower left corner + Rectangle r1 = window.getBounds(), r2 = this.getBounds(); + int x = r1.x; + int y = r1.y+r1.height-r2.height; + if (x < 0) x = 0; + if (y < 0) y = 0; + this.setBounds(new Rectangle(x, y, r2.width, r2.height)); + + setVisible(true); + } + + /** Pressing Escape are equivalent to clicking close */ + public void keyPressed(KeyPressedEvent ev) + { + if (ev.getKeyCode() == KeyPressedEvent.VK_ESCAPE || + ev.getKeyCode() == KeyPressedEvent.VK_C) closeWindow(); + } + + public void closeWindow() + { + dispose(); + } + + public void test() + { + int[] selidx = this.window.getSelectedIndices(); + for (int i : selidx) { + System.out.println("sel: " + i); + } + } +} diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/reprap/artofillusion/CSGEvaluatorEngine.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/reprap/artofillusion/CSGEvaluatorEngine.java new file mode 100644 index 00000000..0744bb76 --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/reprap/artofillusion/CSGEvaluatorEngine.java @@ -0,0 +1,321 @@ +package org.reprap.artofillusion; + +import java.util.Collection; +import java.util.Iterator; + +import artofillusion.LayoutWindow; +import artofillusion.UndoRecord; +import artofillusion.math.CoordinateSystem; +import artofillusion.object.CSGObject; +import artofillusion.object.Object3D; +import artofillusion.object.ObjectInfo; +import artofillusion.texture.Texture; +import artofillusion.ui.MessageDialog; + + + +class CSGEvaluatorEngine +{ + LayoutWindow window; + + + + public CSGEvaluatorEngine(LayoutWindow window) + { + this.window = window; + } + + /** + Returns a normalized selection, meaning children of a selected parent + are removed. + */ + public ObjectInfo[] getSelection() + { + Collection<ObjectInfo> sel = this.window.getSelectedObjects(); + ObjectInfo[] objects = new ObjectInfo[sel.size()]; + Iterator<ObjectInfo> it = sel.iterator(); + int i = 0; + while (it.hasNext()) { + ObjectInfo objinfo = it.next(); + ObjectInfo p = objinfo.getParent(); + while (p != null) { // Check if any parent is selected + if (this.window.isObjectSelected(p)) break; + p = p.getParent(); + } + if (p == null) objects[i++] = objinfo; + } + ObjectInfo[] cleanedobjects = new ObjectInfo[i]; + System.arraycopy(objects, 0, cleanedobjects, 0, i); + return cleanedobjects; + } + + /** + * Evaluates the currently selected subtree + */ + public void evaluate() + { + try { + UndoRecord undo = new UndoRecord(this.window, false); + ObjectInfo[] objects = getSelection(); + if (objects != null) { + for (int i=0;i<objects.length;i++) { + this.evaluateNode(objects[i], undo); + } + + this.window.setUndoRecord(undo); + this.window.rebuildItemList(); + this.window.updateImage(); + this.window.setModified(); + } + } + catch (Exception ex) { + // this.debug("exception in evaluate: " + ex.toString()); + } + } + + /** + * Devaluates the currently selected subtree + */ + public void devaluate() + { + UndoRecord undo = new UndoRecord(this.window, false); + ObjectInfo[] objects = getSelection(); + if (objects != null) { + for (int i=0;i<objects.length;i++) { + this.devaluateNode(objects[i], undo); + } + + this.window.setUndoRecord(undo); + this.window.rebuildItemList(); + this.window.updateImage(); + this.window.setModified(); + } + } + + /** + * Performs the given operation on the currently selected objects + */ + public void execute(int operation) + { + UndoRecord undo = new UndoRecord(this.window, false); + ObjectInfo[] objects = getSelection(); + if (objects == null || objects.length < 2) { + new MessageDialog(this.window, "Minimum two objects must be selected."); + return; + } + + // Selection undo + int[] oldSelection = this.window.getSelectedIndices(); + undo.addCommand(UndoRecord.SET_SCENE_SELECTION, new Object[] {oldSelection}); + + ObjectInfo newobjinfo = this.createNewObject(objects, operation, undo); + // Must rebuild before updating the selection to rebuild indices. + this.window.rebuildItemList(); + this.window.setSelection(this.window.getScene().indexOf(newobjinfo)); + + this.window.setUndoRecord(undo); + + // FIXME: Not sure if these are needed.. + this.window.updateImage(); + this.window.setModified(); + } + + /** + * Performs the union operation on the currently selected objects + */ + public void union() + { + execute(CSGObject.UNION); + } + + /** + * Performs the intersect operation on the currently selected objects + */ + public void intersection() + { + execute(CSGObject.INTERSECTION); + } + + /** + * Performs the subtract operation on the currently selected objects + */ + public void difference() + { + execute(CSGObject.DIFFERENCE12); + } + + /** + * Converts from operation to String (CSGObject.op) + */ + public String opToString(int operation) { + switch (operation) { + case CSGObject.UNION: + return "union"; + case CSGObject.INTERSECTION: + return "intersection"; + case CSGObject.DIFFERENCE12: + return "difference"; + default: + return null; + } + } + + /** + * Converts from string to operation (CSGObject.op). + */ + public int stringToOp(String opstr) { + String lower = opstr.toLowerCase(); + if (lower.startsWith("union") || lower.startsWith("+")) { + return CSGObject.UNION; + } + else if (lower.startsWith("intersection") || lower.startsWith("/") || lower.startsWith("&")) { + return CSGObject.INTERSECTION; + } + else if (lower.startsWith("difference") || lower.startsWith("-")) { + return CSGObject.DIFFERENCE12; + } + else return -1; + } + + class CADObject + { + public double posX, posY, posZ; + } + + class CADSphere extends CADObject { + } + + + + /* + Recursively (Re-)evaluates the object tree rooted at the given root object + based on the operation encoded into the object name. + + The result should be one CSG object where the entire child tree is disabled. + If the operation is none or unknown, the parent will be returned unchanged. + */ + public ObjectInfo evaluateNode(ObjectInfo parent, UndoRecord undo) + { + int op = stringToOp(parent.name); + if (op == -1) return parent; + else { + // compute combined object + ObjectInfo csgobjinfo = combine(parent.getChildren(), op, undo); + Object3D csgobj = csgobjinfo.object; + + // This is necessary since we're not adding the object to the scene, just replacing an existing + // object. + if (csgobj.getTexture() == null) { + Texture tex = this.window.getScene().getDefaultTexture(); + csgobj.setTexture(tex, tex.getDefaultMapping(csgobj)); + } + + undo.addCommandAtBeginning(UndoRecord.COPY_OBJECT, new Object[] { parent.object, parent.object.duplicate() }); + parent.setObject(csgobj); + parent.clearCachedMeshes(); + this.window.updateImage(); + this.window.updateMenus(); + + parent.setVisible(true); + + return parent; + } + } + + /** + Recursively (Re-)deevaluates the object tree rooted at the given root object + based on the object name. + + This disables all implicit (parent) objects and enabled the leaf nodes. + */ + public void devaluateNode(ObjectInfo parent, UndoRecord undo) + { + int op = stringToOp(parent.name); + if (op != -1) { + if (undo != null) + undo.addCommand(UndoRecord.COPY_OBJECT_INFO, new Object [] {parent, parent.duplicate()}); + parent.setVisible(false); + + //TODO: should not be necessary since we don't modify the object (only the object info) + this.window.getScene().objectModified(parent.getObject()); + + ObjectInfo[] children = parent.getChildren(); + for (int i=0;i<children.length;i++) { + devaluateNode(children[i], undo); + } + } + else { + if (undo != null) + undo.addCommand(UndoRecord.COPY_OBJECT_INFO, new Object [] {parent, parent.duplicate()}); + parent.setVisible(true); + + //TODO: should not be necessary since we don't modify the object (only the object info) + this.window.getScene().objectModified(parent.getObject()); + } + } + + /** + Performs the given operation on the list of objects (of size >= 2), + and returns the resulting ObjectInfo containing a CSGObject. + + Calls evaluateNode() on each child before performing the operation. + Hides the children. + */ + public ObjectInfo combine(ObjectInfo[] objects, int operation, UndoRecord undo) + { + if (objects.length < 1) return null; + if (objects.length < 2) return objects[0]; + + ObjectInfo a = evaluateNode(objects[0], undo); + ObjectInfo b = evaluateNode(objects[1], undo); + + Object3D csgobj = new CSGObject(a, b, operation); + ObjectInfo csgobjinfo = new ObjectInfo(csgobj, new CoordinateSystem(), "tmp"); + + for (int i=2;i<objects.length;i++) { + csgobj = new CSGObject(csgobjinfo, evaluateNode(objects[i], undo), operation); + csgobjinfo = new ObjectInfo(csgobj, new CoordinateSystem(), "tmp"); + } + + for (int i=0;i<objects.length;i++) { + undo.addCommandAtBeginning(UndoRecord.COPY_OBJECT_INFO, new Object[] {objects[i], objects[i].duplicate()}); + + objects[i].setVisible(false); + + //FIXME: is this needed? comments in AOI source say no... + this.window.getScene().objectModified(objects[i].getObject()); + } + + return csgobjinfo; + } + + /** + Creates a new object consisting of the result of performing the given + operation on the given list of objects (of length >= 2). + + Inserts the new object into the scene and makes the original objects + children of the new object. Also hides the children. + */ + public ObjectInfo createNewObject(ObjectInfo[] objects, int operation, UndoRecord undo) + { + ObjectInfo granddad = objects[0].parent; + // create ObjectInfo for combined object + ObjectInfo resultinfo = combine(objects, operation, undo); + resultinfo.setName(opToString(operation)); + //resultinfo.parent = granddad; + + // add the object info to the window (which adds it to the scene and the item tree + // and creates the proper undo record commands) + // FIXME: The index is sometimes wrong since moving objects with the mouse confuses AoI's index system. + // Don't know how to get around this, so keep it like this for now. + this.window.getScene().addObject(resultinfo, this.window.getScene().indexOf(objects[0]), undo); + + // reparent children + for (int i=0;i<objects.length;i++) { + resultinfo.addChild(objects[i], i); + undo.addCommandAtBeginning(UndoRecord.REMOVE_FROM_GROUP, new Object[] {resultinfo, objects[i]}); + } + + return resultinfo; + } +} diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/reprap/artofillusion/CSGEvaluatorPlugin.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/reprap/artofillusion/CSGEvaluatorPlugin.java new file mode 100644 index 00000000..65a73513 --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/reprap/artofillusion/CSGEvaluatorPlugin.java @@ -0,0 +1,13 @@ +package org.reprap.artofillusion; + +import artofillusion.Plugin; + +public class CSGEvaluatorPlugin implements Plugin +{ + public void processMessage(int message, Object args[]) { + if (message == Plugin.APPLICATION_STARTING) { + } + else if (message == Plugin.SCENE_WINDOW_CREATED) { + } + } +} diff --git a/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/reprap/artofillusion/CSGEvaluatorTool.java b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/reprap/artofillusion/CSGEvaluatorTool.java new file mode 100644 index 00000000..bb334de1 --- /dev/null +++ b/trunk/users/metalab/AoI/plugins/CSGEvaluator/src/org/reprap/artofillusion/CSGEvaluatorTool.java @@ -0,0 +1,73 @@ +/*
+ * This program is free software; you can redistribute it and/or modify it under the
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation; either version 2 of the License, or (at your option) any later version.
+ * This program is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE. See the GNU General Public License for more details.
+ */
+package org.reprap.artofillusion;
+
+import java.awt.event.KeyEvent;
+
+import artofillusion.LayoutWindow;
+import artofillusion.ModellingTool;
+import artofillusion.keystroke.KeystrokeManager;
+import artofillusion.keystroke.KeystrokeRecord;
+
+
+/**
+ *
+ * Plugin interface for CSGEvaluator
+ *
+ * TODO:
+ * o How should we handle materials when combining objects?
+ * o Idea: Don't hide negative object, but set them to transparent.
+ * o Make window dockable
+ */
+public class CSGEvaluatorTool implements ModellingTool
+{
+ CSGEvaluatorDialog dialog;
+
+
+ /**
+ * instance this tool,load it in memory
+ */
+
+ public CSGEvaluatorTool()
+ {
+ KeystrokeManager.addRecord(new KeystrokeRecord(KeyEvent.VK_C, 0, "CSG Evaluator",
+ "ModellingTool plugin = (ModellingTool)" +
+ "PluginRegistry.getPluginObject(\"org.reprap.artofillusion.CSGEvaluatorTool\");" +
+ "plugin.commandSelected(window);"));
+ }
+
+ /**
+ * Get the text that appear as the menu item.
+ *
+ *@return The name value
+ */
+ public String getName()
+ {
+ return "CSG Evaluator...";
+ }
+
+
+ /**
+ * CSGEvaluator Command selection.
+ *
+ *@param window LayoutWindow
+ */
+ public void commandSelected(LayoutWindow window)
+ {
+ // Light check for whether the dialog is already visible and to then close it.
+ // FIXME: Should be done better, but then we need to keep track of the dialog per window.
+ if (this.dialog != null && this.dialog.isVisible() && this.dialog.getParent() == window) {
+ this.dialog.closeWindow();
+ }
+ else {
+ this.dialog = new CSGEvaluatorDialog(window);
+ }
+ //this class should do no more because it's always loaded.
+ }
+}
|