2 * Copyright (C) 2001, 2002 The Mir-coders group
4 * This file is part of Mir.
6 * Mir is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * Mir is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with Mir; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 * In addition, as a special exception, The Mir-coders gives permission to link
21 * the code of this program with the com.oreilly.servlet library, any library
22 * licensed under the Apache Software License, The Sun (tm) Java Advanced
23 * Imaging library (JAI), The Sun JIMI library (or with modified versions of
24 * the above that use the same license as the above), and distribute linked
25 * combinations including the two. You must obey the GNU General Public
26 * License in all respects for all of the code used other than the above
27 * mentioned libraries. If you modify this file, you may extend this exception
28 * to your version of the file, but you are not obligated to do so. If you do
29 * not wish to do so, delete this exception statement from your version.
34 import multex.Failure;
38 import mir.generator.*;
40 public class ParameterExpander {
41 final static String NODE_SEPARATOR = ".";
42 final static char STRING_ESCAPE_CHARACTER = '\\';
44 private static Object findNode(String aKey, Map aMap, List aParts, boolean aMakeIfNotPresent) throws Exception {
50 i = aParts.iterator();
53 String part = (String) i.next();
55 if (!(node instanceof Map)) {
56 throw new Exception( "Can't expand key " + aKey + ": " + location + " is not a map" );
59 if (location.length()>0) {
60 location=location + NODE_SEPARATOR;
62 location = location + part;
64 newNode = ((Map) node).get(part);
67 if (aMakeIfNotPresent) {
68 newNode = new HashMap();
69 ((Map) node).put(part, newNode);
72 throw new ParameterExpanderExc( "Can't expand key {1}: {2} does not exist", new Object[]{aKey,location} );
80 public static Object findValueForKey(Map aMap, String aKey) throws Exception {
82 List parts = StringRoutines.splitString(aKey, NODE_SEPARATOR);
84 node = findNode(aKey, aMap, parts, false);
89 public static String findStringForKey(Map aMap, String aKey) throws Exception {
90 Object expandedValue = findValueForKey(aMap, aKey);
92 if (!(expandedValue instanceof String))
93 throw new ParameterExpanderExc( "Value of key is not a string but a {1}", new Object[]{expandedValue.getClass().getName()} );
95 return (String) expandedValue;
98 public static void setValueForKey(Map aMap, String aKey, Object aValue) throws Exception {
99 List parts = StringRoutines.splitString(aKey, NODE_SEPARATOR);
101 String key = (String) parts.get(parts.size()-1);
102 parts.remove(parts.size()-1);
104 Object node=findNode(aKey, aMap, parts, true);
106 if (node instanceof Map) {
107 ((Map) node).put(key, aValue);
110 throw new ParameterExpanderExc( "Can't set key {1}: not inside a Map", new Object[]{aKey} );
113 public static String expandExpression(Map aMap, String anExpression) throws Exception {
114 int previousPosition = 0;
116 int endOfExpressionPosition;
117 StringBuffer result = new StringBuffer();
119 while ((position=anExpression.indexOf("$", previousPosition))>=0) {
120 result.append(anExpression.substring(previousPosition, position));
122 if (position>=anExpression.length()-1) {
123 result.append(anExpression.substring(position, anExpression.length()));
124 previousPosition=anExpression.length();
128 if (anExpression.charAt(position+1) == '{') {
129 endOfExpressionPosition=position+2;
130 while (endOfExpressionPosition<anExpression.length() && anExpression.charAt(endOfExpressionPosition) != '}') {
131 if (anExpression.charAt(endOfExpressionPosition)=='\'' || anExpression.charAt(endOfExpressionPosition)=='"') {
132 char boundary = anExpression.charAt(endOfExpressionPosition);
134 endOfExpressionPosition++;
135 while (endOfExpressionPosition<anExpression.length() && anExpression.charAt(endOfExpressionPosition) != boundary) {
136 if (anExpression.charAt(endOfExpressionPosition) == STRING_ESCAPE_CHARACTER)
137 endOfExpressionPosition++;
138 endOfExpressionPosition++;
140 if (endOfExpressionPosition>=anExpression.length()) {
141 throw new ParameterExpanderExc("Unterminated string in {1}",new Object[]{anExpression});
144 endOfExpressionPosition++;
146 if (endOfExpressionPosition<anExpression.length()) {
147 result.append(evaluateStringExpression(aMap, anExpression.substring(position+2, endOfExpressionPosition)));
148 previousPosition=endOfExpressionPosition+1;
151 throw new ParameterExpanderExc("Missing } in {1}",new Object[]{anExpression});
156 previousPosition=position+2;
157 result.append(anExpression.charAt(position+1));
161 result.append(anExpression.substring(previousPosition, anExpression.length()));
163 return result.toString();
166 public static boolean evaluateBooleanExpression(Map aMap, String anExpression) throws Exception {
167 Parser parser = new Parser(anExpression, aMap);
169 return parser.parseBoolean();
172 public static String evaluateStringExpression(Map aMap, String anExpression) throws Exception {
173 Parser parser = new Parser(anExpression, aMap);
175 return parser.parseString();
178 public static int evaluateIntegerExpressionWithDefault(Map aMap, String anExpression, int aDefault) throws Exception {
179 if (anExpression == null || anExpression.trim().equals(""))
182 return evaluateIntegerExpression(aMap, anExpression);
185 public static int evaluateIntegerExpression(Map aMap, String anExpression) throws Exception {
186 Parser parser = new Parser(anExpression, aMap);
188 return parser.parseInteger();
191 public static Object evaluateExpression(Map aMap, String anExpression) throws Exception {
192 Parser parser = new Parser(anExpression, aMap);
194 return parser.parseWhole();
197 private static class Reader {
199 private int position;
201 public Reader(String aData) {
206 public Character peek() {
207 if (position<data.length()) {
208 return (new Character(data.charAt(position)));
214 public boolean hasNext() {
218 public Character getNext() {
219 Character result = peek();
227 public String getPositionString() {
228 return data.substring(0, position) + "<__>" + data.substring(position) ;
232 private static abstract class Token {
235 public static abstract class PunctuationToken extends Token { public PunctuationToken() { }; }
236 private static class LeftSquareBraceToken extends PunctuationToken {};
237 private static class RightSquareBraceToken extends PunctuationToken {};
238 private static class EqualsToken extends PunctuationToken {};
239 private static class EqualsNotToken extends PunctuationToken {};
240 private static class NOTToken extends PunctuationToken {};
241 private static class LeftParenthesisToken extends PunctuationToken {};
242 private static class RightParenthesisToken extends PunctuationToken {};
243 private static class CommaToken extends PunctuationToken {};
244 private static class PeriodToken extends PunctuationToken {};
245 private static class PlusToken extends PunctuationToken {};
246 private static class TimesToken extends PunctuationToken {};
247 private static class DivideToken extends PunctuationToken {};
248 private static class MinusToken extends PunctuationToken {};
249 private static class ConcatenateToken extends PunctuationToken {};
250 private static class LessThanOrEqualsToken extends PunctuationToken {};
251 private static class GreaterThanOrEqualsToken extends PunctuationToken {};
252 private static class LessThanToken extends PunctuationToken {};
253 private static class GreaterThanToken extends PunctuationToken {};
256 private static class IdentifierToken extends Token {
259 public IdentifierToken(String aName) {
263 public String getName() {
269 private static class LiteralToken extends Token {
270 private Object value;
272 public LiteralToken(Object aValue) {
276 public Object getValue() {
281 private static class Scanner {
282 private Reader reader;
283 private Token nextToken;
284 private String positionString;
286 public Scanner(Reader aReader) {
289 positionString = reader.getPositionString();
292 public Token scanStringLiteral() {
293 StringBuffer result = new StringBuffer();
296 delimiter = reader.getNext();
298 while (reader.hasNext() && !reader.peek().equals(delimiter)) {
299 if (reader.peek().charValue()==STRING_ESCAPE_CHARACTER) {
301 if (reader.hasNext())
302 result.append(reader.getNext());
305 result.append(reader.getNext());
309 if (!reader.hasNext())
310 throw new RuntimeException("unterminated string");
314 return new LiteralToken(result.toString());
317 public String getPositionString() {
318 return positionString;
321 private Token scanNumber() {
322 StringBuffer result = new StringBuffer();
323 result.append(reader.getNext());
325 while (reader.hasNext() && isNumberRest(reader.peek().charValue())) {
326 result.append(reader.getNext());
330 return new LiteralToken(new Integer(Integer.parseInt(result.toString())));
332 catch (NumberFormatException e) {
333 throw new RuntimeException("Invalid number: " + e.getMessage());
337 private Token scanIdentifierKeyword() {
338 StringBuffer result = new StringBuffer();
339 result.append(reader.getNext());
341 while (reader.hasNext() && isIdentifierRest(reader.peek().charValue())) {
342 result.append(reader.getNext());
345 return new IdentifierToken(result.toString());
348 private Token scanPunctuation() {
351 c = reader.getNext();
353 switch(c.charValue()) {
354 case '[': return new LeftSquareBraceToken();
355 case ']': return new RightSquareBraceToken();
357 if (reader.hasNext() && reader.peek().charValue() == '=') {
359 return new EqualsToken();
362 throw new RuntimeException("Unknown character: '='");
366 if (reader.hasNext() && reader.peek().charValue() == '=') {
368 return new EqualsNotToken();
371 return new NOTToken();
374 case '(': return new LeftParenthesisToken ();
376 case ')': return new RightParenthesisToken ();
377 case ',': return new CommaToken ();
378 case '.': return new PeriodToken ();
380 if (reader.hasNext() && reader.peek().charValue() == '+') {
382 return new ConcatenateToken();
385 return new PlusToken ();
387 case '*': return new TimesToken ();
388 case '/': return new DivideToken ();
389 case '-': return new MinusToken ();
391 if (reader.hasNext() && reader.peek().charValue() == '=') {
393 return new LessThanOrEqualsToken();
396 return new LessThanToken();
400 if (reader.hasNext() && reader.peek().charValue() == '=') {
402 return new GreaterThanOrEqualsToken();
405 return new GreaterThanToken();
408 throw new RuntimeException("Unexpected character: "+c);
412 public void skipWhitespace() {
413 while (reader.hasNext() && Character.isWhitespace(reader.peek().charValue()))
417 private boolean isIdentifierStart(char c) {
418 return Character.isLetter(c) || (c == '_');
421 private boolean isIdentifierRest(char c) {
422 return Character.isLetterOrDigit(c) || (c == '_');
425 private boolean isNumberStart(char c) {
426 return Character.isDigit(c);
429 private boolean isNumberRest(char c) {
430 return Character.isDigit(c);
433 public Token scanNext() {
438 if (reader.hasNext()) {
439 Character c = reader.peek();
441 switch(c.charValue()) {
444 result = scanStringLiteral();
448 if (isIdentifierStart(c.charValue())) {
449 result = scanIdentifierKeyword();
451 else if (isNumberStart(c.charValue())) {
452 result = scanNumber();
455 result = scanPunctuation();
465 public Token scan() {
466 Token result = peek();
468 positionString = reader.getPositionString();
473 public Token peek() {
474 if (nextToken==null) {
475 nextToken = scanNext();
481 public boolean hasToken() {
486 private static class Parser {
487 private Scanner scanner;
488 private Map valueMap;
490 public Parser(String anExpression, Map aValueMap) {
491 scanner = new Scanner(new Reader(anExpression));
492 valueMap = aValueMap;
495 public boolean parseBoolean() {
497 return interpretAsBoolean(parseWhole());
499 catch (Throwable t) {
500 throw new RuntimeException("Parser error at '" + getLocation()+ "': "+t.getMessage());
504 public int parseInteger() {
506 return interpretAsInteger(parseWhole());
508 catch (Throwable t) {
509 throw new RuntimeException("Parser error at '" + getLocation()+ "': "+t.getMessage());
513 public String parseString() {
515 return interpretAsString(parseWhole());
517 catch (Throwable t) {
518 throw new RuntimeException("Parser error at '" + getLocation()+ "': "+t.getMessage());
522 private String getLocation() {
523 return scanner.getPositionString();
526 private Object parseWhole() {
527 Object result = parse();
529 if (scanner.hasToken()) {
530 throw new RuntimeException("Operator expected");
536 private Object parse() {
537 return parseUntil(MAX_OPERATOR_LEVEL);
540 private List parseList() {
543 List result = new Vector();
545 token = scanner.scan();
546 if (!(token instanceof LeftParenthesisToken)) {
547 throw new RuntimeException("( expected");
550 if (scanner.peek() instanceof RightParenthesisToken) {
556 expression = parse();
558 if (expression==null) {
559 throw new RuntimeException("expression expected");
562 result.add(expression);
564 token = scanner.scan();
566 while (token instanceof CommaToken);
568 if (!(token instanceof RightParenthesisToken)) {
569 throw new RuntimeException(") or , expected");
575 private Object parseVariable() {
578 Object currentValue = valueMap;
583 token = scanner.peek();
585 if (token instanceof LeftSquareBraceToken) {
587 qualifier = parseUntil(MAX_OPERATOR_LEVEL);
588 token = scanner.scan();
589 if (!(token instanceof RightSquareBraceToken))
590 throw new RuntimeException("] expected");
592 if (currentValue instanceof Map) {
593 currentValue = ((Map) currentValue).get(qualifier);
596 throw new RuntimeException("cannot reference into anything other than a map ('"+qualifier+"')");
599 else if (token instanceof IdentifierToken) {
601 qualifier = ((IdentifierToken) token).getName();
603 if (currentValue instanceof Map) {
604 currentValue = ((Map) currentValue).get(qualifier);
607 throw new RuntimeException("cannot reference into anything other than a map ('"+qualifier+"')");
610 else if (token instanceof LeftParenthesisToken) {
611 if (currentValue instanceof Generator.GeneratorFunction) {
612 parameters = parseList();
614 currentValue = ((Generator.GeneratorFunction) currentValue).perform(parameters);
616 catch (GeneratorExc t) {
617 throw new RuntimeException(t.getMessage());
621 throw new RuntimeException("not a function");
624 throw new RuntimeException("fieldname or [ expected");
626 if (scanner.peek() instanceof PeriodToken ||
627 scanner.peek() instanceof LeftSquareBraceToken ||
628 scanner.peek() instanceof LeftParenthesisToken) {
631 if (scanner.peek() instanceof PeriodToken)
642 private Object parseUntil(int aMaxOperatorLevel) {
643 Token token = scanner.peek();
646 if (token instanceof LeftParenthesisToken) {
649 token = scanner.peek();
650 if (!(token instanceof RightParenthesisToken))
651 throw new RuntimeException(") expected");
654 else if (isUnaryOperator(token)) {
656 value = parseUntil(unaryOperatorLevel(token));
657 value = expandOperatorExpression(token, value);
659 else if (token instanceof IdentifierToken || token instanceof LeftSquareBraceToken) {
660 value = parseVariable();
662 else if (token instanceof LiteralToken) {
664 value = ((LiteralToken) token).getValue();
667 throw new RuntimeException("Expression expected");
669 token = scanner.peek();
671 while (isBinaryOperator(token) && binaryOperatorLevel(token)<aMaxOperatorLevel) {
675 if (isINOperator(token)) {
676 value2 = parseList();
679 value2 = parseUntil(binaryOperatorLevel(token));
682 value = expandOperatorExpression(token, value, value2);
684 token = scanner.peek();
690 private static final int MAX_OPERATOR_LEVEL = 1000; //
691 private static final int LOGICAL_OPERATOR_LEVEL = 5; // && || !
692 private static final int COMPARISON_OPERATOR_LEVEL = 4; // == <= >= in < >
693 private static final int ADDITION_OPERATOR_LEVEL = 3; // + - &
694 private static final int MULTIPLICATION_OPERATOR_LEVEL = 2; // * /
696 private int unaryOperatorLevel(Token aToken) {
697 if (aToken instanceof NOTToken)
698 return LOGICAL_OPERATOR_LEVEL;
699 else if (aToken instanceof MinusToken)
700 return ADDITION_OPERATOR_LEVEL;
702 throw new RuntimeException("Internal error: unknown unary operator: " + aToken.getClass().getName());
705 private boolean isUnaryOperator(Token aToken) {
707 ((aToken instanceof NOTToken) ||
708 (aToken instanceof MinusToken));
711 private int binaryOperatorLevel(Token aToken) {
712 if (isANDOperator(aToken) ||
713 isOROperator(aToken))
714 return LOGICAL_OPERATOR_LEVEL;
716 if ((aToken instanceof EqualsToken) ||
717 (aToken instanceof EqualsNotToken) ||
718 (aToken instanceof LessThanOrEqualsToken) ||
719 (aToken instanceof LessThanToken) ||
720 (aToken instanceof GreaterThanOrEqualsToken) ||
721 (aToken instanceof GreaterThanToken) ||
722 isINOperator(aToken))
723 return COMPARISON_OPERATOR_LEVEL;
725 if ((aToken instanceof PlusToken) ||
726 (aToken instanceof ConcatenateToken) ||
727 (aToken instanceof MinusToken))
728 return ADDITION_OPERATOR_LEVEL;
730 if ((aToken instanceof TimesToken) ||
731 (aToken instanceof DivideToken))
732 return MULTIPLICATION_OPERATOR_LEVEL;
734 throw new RuntimeException("Internal error: unknown binary operator: " + aToken.getClass().getName());
737 private boolean isINOperator(Token aToken) {
738 return (aToken instanceof IdentifierToken && ((IdentifierToken) aToken).getName().equals("in"));
741 private boolean isANDOperator(Token aToken) {
742 return (aToken instanceof IdentifierToken && ((IdentifierToken) aToken).getName().equals("and"));
745 private boolean isOROperator(Token aToken) {
746 return (aToken instanceof IdentifierToken && ((IdentifierToken) aToken).getName().equals("or"));
749 private boolean isBinaryOperator(Token aToken) {
751 (aToken instanceof EqualsToken) ||
752 (aToken instanceof EqualsNotToken) ||
753 (aToken instanceof PlusToken) ||
754 (aToken instanceof TimesToken) ||
755 (aToken instanceof DivideToken) ||
756 (aToken instanceof MinusToken) ||
757 (aToken instanceof ConcatenateToken) ||
758 (aToken instanceof LessThanOrEqualsToken) ||
759 (aToken instanceof LessThanToken) ||
760 (aToken instanceof GreaterThanOrEqualsToken) ||
761 (aToken instanceof GreaterThanToken) ||
762 isINOperator(aToken) ||
763 isOROperator(aToken) ||
764 isANDOperator(aToken);
767 private boolean interpretAsBoolean(Object aValue) {
768 if (aValue instanceof Boolean)
769 return ((Boolean) aValue).booleanValue();
774 private int interpretAsInteger(Object aValue) {
775 if (aValue instanceof Integer)
776 return ((Integer) aValue).intValue();
778 if (aValue instanceof String) {
780 return Integer.parseInt((String) aValue);
782 catch (Throwable t) {
786 throw new RuntimeException("Not an integer");
789 private String interpretAsString(Object aValue) {
790 if (aValue instanceof String)
791 return (String) aValue;
792 if (aValue instanceof Integer)
793 return ((Integer) aValue).toString();
795 throw new RuntimeException("Not a string");
798 private Object expandOperatorExpression(Token aToken, Object aValue) {
799 if (aToken instanceof NOTToken)
800 return new Boolean(!interpretAsBoolean(aValue));
801 else if (aToken instanceof MinusToken)
802 return new Integer(-interpretAsInteger(aValue));
804 throw new RuntimeException("Internal error: unknown unary operator: " + aToken.getClass().getName());
807 private boolean areEqual(Object aValue1, Object aValue2) {
808 if (aValue1==null || aValue2==null)
809 return (aValue1==null) && (aValue2==null);
811 return aValue1.equals(aValue2);
814 private Object expandOperatorExpression(Token aToken, Object aValue1, Object aValue2) {
815 if (isINOperator(aToken)) {
816 if (!(aValue2 instanceof List)) {
817 throw new RuntimeException("Internal error: List expected");
820 Iterator i = ((List) aValue2).iterator();
822 while (i.hasNext()) {
823 if (areEqual(aValue1, i.next()))
827 return Boolean.FALSE;
830 if (isANDOperator(aToken))
831 return new Boolean(interpretAsBoolean(aValue1) && interpretAsBoolean(aValue2));
832 if (isOROperator(aToken))
833 return new Boolean(interpretAsBoolean(aValue1) || interpretAsBoolean(aValue2));
834 if (aToken instanceof EqualsToken) {
835 return new Boolean(areEqual(aValue1, aValue2));
837 if (aToken instanceof EqualsNotToken)
838 return new Boolean(!areEqual(aValue1, aValue2));
839 if (aToken instanceof PlusToken)
840 return new Integer(interpretAsInteger(aValue1) + interpretAsInteger(aValue2));
841 if (aToken instanceof TimesToken)
842 return new Integer(interpretAsInteger(aValue1) * interpretAsInteger(aValue2));
843 if (aToken instanceof DivideToken)
844 return new Integer(interpretAsInteger(aValue1) / interpretAsInteger(aValue2));
845 if (aToken instanceof MinusToken)
846 return new Integer(interpretAsInteger(aValue1) - interpretAsInteger(aValue2));
848 if (aToken instanceof ConcatenateToken)
849 return interpretAsString(aValue1) + interpretAsString(aValue2);
851 if (aToken instanceof LessThanOrEqualsToken)
852 return new Boolean(interpretAsInteger(aValue1) <= interpretAsInteger(aValue2));
853 if (aToken instanceof LessThanToken)
854 return new Boolean(interpretAsInteger(aValue1) < interpretAsInteger(aValue2));
855 if (aToken instanceof GreaterThanOrEqualsToken)
856 return new Boolean(interpretAsInteger(aValue1) >= interpretAsInteger(aValue2));
857 if (aToken instanceof GreaterThanToken)
858 return new Boolean(interpretAsInteger(aValue1) > interpretAsInteger(aValue2));
860 throw new RuntimeException("Internal error: unknown binary operator: " + aToken.getClass().getName());
864 public static class ParameterExpanderExc extends Exc {
865 public ParameterExpanderExc(String msg, Object[] objects) {