01: // Copyright (c) 2002, 2003, 2006 Per M.A. Bothner.
02: // This is free software; for terms and warranty disclaimer see ./COPYING.
03:
04: package gnu.xquery.util;
05:
06: import gnu.mapping.*;
07: import gnu.lists.*;
08: import gnu.math.Numeric;
09: import gnu.math.RealNum;
10: import gnu.kawa.xml.UntypedAtomic;
11: import gnu.expr.*;
12: import gnu.bytecode.Type;
13: import gnu.kawa.xml.XDataType;
14: import gnu.xquery.lang.XQuery;
15:
16: public class BooleanValue extends Procedure1 implements CanInline {
17: public static final BooleanValue booleanValue = new BooleanValue(
18: "boolean-value");
19:
20: public BooleanValue(String name) {
21: super (name);
22: }
23:
24: public static boolean booleanValue(Object value) {
25: if (value instanceof Boolean)
26: return ((Boolean) value).booleanValue();
27: if (value instanceof Number
28: && (value instanceof RealNum || !(value instanceof Numeric))) {
29: double d = ((Number) value).doubleValue();
30: return d != 0 && !Double.isNaN(d);
31: }
32: if (value instanceof SeqPosition)
33: return true;
34: if (value instanceof String || value instanceof gnu.text.Path
35: || value instanceof UntypedAtomic)
36: return value.toString().length() > 0;
37: if (value instanceof Values) {
38: Values values = (Values) value;
39: Object value1 = values.getPosNext(0);
40: if (value1 == Sequence.eofValue)
41: return false;
42: int next = values.nextDataIndex(0);
43: if (next < 0)
44: return booleanValue(value1);
45: if (value1 instanceof SeqPosition)
46: return true;
47: }
48: throw new WrongType("fn:boolean", 1, value,
49: "boolean-convertible-value");
50: }
51:
52: public static boolean not(Object value) {
53: return !booleanValue(value);
54: }
55:
56: public Object apply1(Object arg) {
57: return booleanValue(arg) ? Boolean.TRUE : Boolean.FALSE;
58: }
59:
60: public Expression inline(ApplyExp exp, ExpWalker walker) {
61: Expression[] args = exp.getArgs();
62: if (args.length == 1) {
63: Expression arg = args[0];
64: Type type = arg.getType();
65: if (type == XDataType.booleanType)
66: return arg;
67: if (type == null)
68: exp.setType(XDataType.booleanType);
69: if (arg instanceof QuoteExp) {
70: Object value = ((QuoteExp) arg).getValue();
71: try {
72: return booleanValue(value) ? XQuery.trueExp
73: : XQuery.falseExp;
74: } catch (Throwable ex) {
75: String message = "cannot convert to a boolean";
76: walker.getMessages().error('e', message);
77: return new ErrorExp(message);
78: }
79: }
80: }
81: return exp;
82: }
83: }
|