0001: /*
0002: * $Id: LangModule.java,v 1.71 2002/09/16 08:05:02 jkl Exp $
0003: *
0004: * Copyright (c) 2002 Njet Communications Ltd. All Rights Reserved.
0005: *
0006: * Use is subject to license terms, as defined in
0007: * Anvil Sofware License, Version 1.1. See LICENSE
0008: * file, or http://njet.org/license-1.1.txt
0009: */
0010: package anvil.core;
0011:
0012: import java.io.IOException;
0013: import java.io.ByteArrayOutputStream;
0014: import java.util.Enumeration;
0015: import java.util.Arrays;
0016: import java.util.Comparator; /*import java.lang.reflect.Proxy;*/
0017: import org.apache.oro.text.regex.MatchResult;
0018: import org.apache.oro.text.regex.Pattern;
0019: import org.apache.oro.text.regex.PatternMatcherInput;
0020: import org.apache.oro.text.regex.Perl5Compiler;
0021: import org.apache.oro.text.regex.Perl5Matcher;
0022: import anvil.script.Type;
0023: import anvil.script.Context;
0024: import anvil.script.Function;
0025: import anvil.script.StackFrame;
0026: import anvil.server.Zone;
0027: import anvil.core.reflect.Reflection;
0028: import anvil.core.runtime.AnyType;
0029: import anvil.core.runtime.AnyFunction;
0030: import anvil.core.runtime.AnyScope;
0031: import anvil.script.compiler.NativeNamespace;
0032: import anvil.java.util.BindingEnumeration;
0033: import anvil.util.Conversions;
0034: import anvil.util.Format;
0035:
0036: ///
0037: /// @module anvil.lang
0038: /// Set of elementary functions and classes.
0039: /// Entities at anvil.lang are accessible directly without a need
0040: /// to import or use <code>anvil.lang</code> prefix.
0041: ///
0042: public class LangModule {
0043:
0044: /*public static final Any proxy(Context context, Any handler, Any[] interfaces)
0045: {
0046: Zone zone = context.address().getZone();
0047: ClassLoader classloader = zone.getClassLoader();
0048: int n = interfaces.length;
0049: Class[] classes = new Class[n];
0050: int c = 0;
0051: for(int i=0; i<n; i++) {
0052: Any candidate = interfaces[i];
0053: if (candidate instanceof Reflection) {
0054: Reflection reflection = (Reflection)candidate;
0055: if (reflection.getType() == Type.INTERFACE) {
0056: classes[c++] = reflection.getJavaClass();
0057: } else {
0058: throw context.BadParameter("Parameter #"+(2+i)+" is not java interface");
0059: }
0060: }
0061: }
0062:
0063: Object proxy = Proxy.newProxyInstance(classloader, classes,
0064: new AnyUtils.FunctionInvocationHandler(zone, handler));
0065: return Any.create(proxy);
0066: }*/
0067:
0068: /// @function canDo
0069: /// Checks if given tool permission exists, against
0070: /// current security policy
0071: /// @synopsis boolean canDo(String name)
0072: /// @synopsis boolean canDo(String name, String actions)
0073: public static final Object[] p_canDo = new Object[] { null, "name",
0074: "*actions", null };
0075:
0076: public static final Any canDo(Context context, String name,
0077: String actions) {
0078: ToolPermission tool;
0079: if (actions == null) {
0080: tool = new ToolPermission(name);
0081: } else {
0082: tool = new ToolPermission(name, actions);
0083: }
0084: return context.checkPermission(tool) ? Any.TRUE : Any.FALSE;
0085: }
0086:
0087: /// @function loadClass
0088: /// Loads the given java class or interface.
0089: /// @synopsis Type loadClass(String classname)
0090: /// @exception ClassNotFound If class couldn't be loaded
0091: public static final Object[] p_loadClass = new Object[] { null,
0092: "classname" };
0093:
0094: public static final Any loadClass(Context context, String classname) {
0095: return context.reflect(classname);
0096: }
0097:
0098: /// @function deref
0099: /// Returns the value referred by this given ref.
0100: /// @synopsis object deref(object ref)
0101: /// @param ref Ref to variable
0102: /// @param derefAll If <code>true</code>, all references are followed until
0103: /// first non-ref value is encountered.
0104: public static final Object[] p_deref = new Object[] { "ref",
0105: "*derefAll", Boolean.FALSE };
0106:
0107: public static final Any deref(Any ref, boolean derefAll) {
0108: if (derefAll) {
0109: while (ref.isRef()) {
0110: ref = ref.getRef();
0111: }
0112: } else {
0113: if (ref.isRef()) {
0114: ref = ref.getRef();
0115: }
0116: }
0117: return ref;
0118: }
0119:
0120: /// @function ref
0121: /// Generates and returns programmable ref from given class instance.
0122: /// @synopsis object ref(object provider)
0123: /// @param impl Class having <code>_getRef</code> (and <code>_setRef</code>) methods
0124: public static final Object[] p_ref = new Object[] { "impl" };
0125:
0126: public static final Any ref(Any impl) {
0127: return new AnyClassRef(impl);
0128: }
0129:
0130: /// @function reveal
0131: /// Reveals and returns the ref implementation, encapsulated with <code>ref()</code>.
0132: /// @synopsis object reveal(object ref)
0133: /// @param ref Programmable ref
0134: public static final Object[] p_reveal = new Object[] { "ref" };
0135:
0136: public static final Any reveal(Any impl) {
0137: if (impl instanceof AnyClassRef) {
0138: return ((AnyClassRef) impl).getProvider();
0139: } else {
0140: return impl.getRef();
0141: }
0142: }
0143:
0144: /// @function areSame
0145: /// Checks if two objects share the same memory address.
0146: /// @synopsis boolean areSame(a, b)
0147: public static final Any areSame(Any a, Any b) {
0148: return a == b ? Any.TRUE : Any.FALSE;
0149: }
0150:
0151: /// @function reduce
0152: /// Iterates through the given elements and calls reducer function so
0153: /// that the first parameter will be either the result of previous reducer
0154: /// call or intialValue (if it was given), and all other parameters, up to
0155: /// count are taken from then elements.
0156: /// @synopsis object reduce(object reducer, object elements)
0157: /// @synopsis object reduce(object reducer, int count, object elements)
0158: /// @synopsis object reduce(object reducer, int count, object initialValue, object elements)
0159: /// @param reducer Callable reducer taking from count parameters
0160: /// @param count number of parameters to pass to reducer, default is two.
0161: /// @param intialValue initial value of reduction
0162: /// @return the return value of last call to reducer or initialValue
0163: public static final Object[] p_reduce = { "<context>", "reducer",
0164: "data1", "*data2", null, "*data2", null };
0165:
0166: public static final Any reduce(Context context, Any reducer,
0167: Any data1, Any data2, Any data3) {
0168: int count = 2;
0169: Any elements;
0170: Any rv = null;
0171: if (data2 != null) {
0172: count = data1.toInt();
0173: if (data3 != null) {
0174: rv = data2;
0175: elements = data3;
0176: } else {
0177: elements = data2;
0178: }
0179: } else {
0180: elements = data1;
0181: }
0182: if (count < 2) {
0183: throw context.BadParameter("count must be >= 2");
0184: }
0185: Enumeration e = elements.enumeration();
0186: Any[] params = new Any[count];
0187: out: while (e.hasMoreElements()) {
0188: int c = 0;
0189: if (rv != null) {
0190: params[c++] = rv;
0191: }
0192: while (c < count) {
0193: if (e.hasMoreElements()) {
0194: params[c++] = Any.create(e.nextElement());
0195: } else {
0196: Any[] newparams = new Any[c];
0197: if (c > 0) {
0198: System.arraycopy(params, 0, newparams, 0, c);
0199: params = newparams;
0200: break;
0201: } else {
0202: break out;
0203: }
0204: }
0205: }
0206: if (c == 0) {
0207: return Any.UNDEFINED;
0208: }
0209: if (c == 1) {
0210: return params[0];
0211: }
0212: rv = reducer.execute(context, params);
0213: }
0214: return Any.create(rv);
0215: }
0216:
0217: /// @function join
0218: /// Joins the elements together with given clue.
0219: /// @synopsis string join(object elements)
0220: /// @synopsis string join(object elements, string clue)
0221: /// @param clue Clue to join with, default is <code>", "</code>.
0222: public static final Object[] p_join = new Object[] { "elements",
0223: "*clue", ", " };
0224:
0225: public static final Any join(Any elements, String clue)
0226: {
0227: StringBuffer buffer = new StringBuffer();
0228: BindingEnumeration enum = elements.enumeration();
0229: boolean more = enum.hasMoreElements();
0230: while(more) {
0231: buffer.append(enum.nextElement().toString());
0232: more = enum.hasMoreElements();
0233: if (more) {
0234: buffer.append(clue);
0235: }
0236: }
0237: return new AnyString(buffer.toString());
0238: }
0239:
0240: /// @function sort
0241: /// Sorts the elements of sequence with given comparator.
0242: /// @synopsis enumeration sort(object sorter, object elements)
0243: /// @synopsis enumeration sort(object sorter, object elements, object data)
0244: /// @param sorter Callable comparator receiving parameters <code>(value1, value2, data)</code>
0245: /// @param data Data passed as a third parameter to comparator.
0246: public static final Object[] p_sort = new Object[] { "callable",
0247: "list", "*data", Any.UNDEFINED };
0248:
0249: public static final Any sort(Context context, Any callable, Any list, Any data)
0250: {
0251: Comparator comparator = new AnyUtils.EnumerationComparator(context, callable, data);
0252: java.util.TreeSet set = new java.util.TreeSet(comparator);
0253: BindingEnumeration enum = list.enumeration();
0254: while(enum.hasMoreElements()) {
0255: set.add(Any.create(enum.nextElement()));
0256: }
0257: return new AnyBindingEnumeration(new AnyUtils.IteratorToEnumeration(set.iterator()));
0258: } /// @function select
0259: /// Returns enumeration of all elements for which the
0260: /// given function returned <code>true</code>.
0261: /// @synopsis enumeration select(object selector, object elements)
0262: /// @synopsis enumeration select(object selector, object elements, object data)
0263: /// @param pipe Callable selector receiving parameters
0264: /// <code>(element, index, data)</code>
0265: /// @param data Data passed as third parameter to selector.
0266: public static final Object[] p_select = { "<context>", "selector",
0267: "list", "*data", Any.UNDEFINED };
0268:
0269: public static final Any select(Context context, Any selector,
0270: Any list, Any data) {
0271: return new AnyBindingEnumeration(
0272: new AnyUtils.SelectEnumeration(context, selector, list
0273: .enumeration(), data));
0274: }
0275:
0276: /// @function pipe
0277: /// Returns enumeration that iterates through given elements
0278: /// and pipes the return value of given function as element
0279: /// on call to <code>enumeration.next</code>.
0280: /// @synopsis enumeration pipe(object converter, object elements)
0281: /// @synopsis enumeration pipe(object converter, object elements, object data)
0282: /// @param converter Callable converter receiving parameters <code>element, index, data)</code>
0283: /// @param data Data passed as a third parameter to converter
0284: public static final Object[] p_pipe = { "<context>", "pipe",
0285: "list", "*data", Any.UNDEFINED };
0286:
0287: public static final Any pipe(Context context, Any pipe, Any list,
0288: Any data) {
0289: return new AnyBindingEnumeration(new AnyUtils.PipeEnumeration(
0290: context, pipe, list.enumeration(), data));
0291: }
0292:
0293: /// @function apply
0294: /// Iterates through given elements and applies given applier for
0295: /// each element.
0296: /// @synopsis int apply(object applier, object elements)
0297: /// @synopsis int apply(object applier, object elements, object data)
0298: /// @param applier Callable applier receiving parameters <code>(element, index, data)</code>
0299: /// @param data Data passed as a third parameter to applier
0300: /// @return Number of times applier function was called
0301: public static final Object[] p_apply = { "<context>", "walker",
0302: "list", "*data", Any.UNDEFINED };
0303:
0304: public static final Any apply(Context context, Any walker, Any list, Any data)
0305: {
0306: Any[] params = new Any[3];
0307: params[2] = data;
0308: int count = 0;
0309: BindingEnumeration enum = list.enumeration();
0310: while(enum.hasMoreElements()) {
0311: count++;
0312: Any key = Any.create(enum.nextKey());
0313: Any value = Any.create(enum.nextElement());
0314: params[0] = value;
0315: params[1] = key;
0316: if (!walker.execute(context, params).toBoolean()) {
0317: break;
0318: }
0319: }
0320: return Any.create(count);
0321: }
0322:
0323: /// @function toLower
0324: /// Converts given parameter to lower case.
0325: /// @synopsis string toLower(string str)
0326: public static final Any toLower(String str) {
0327: return Any.create(str.toLowerCase());
0328: }
0329:
0330: /// @function toLower
0331: /// Converts given parameter to upper case.
0332: /// @synopsis string toUpper(string str)
0333: public static final Any toUpper(String str) {
0334: return Any.create(str.toUpperCase());
0335: }
0336:
0337: /// @function serialize
0338: /// Serializes data.
0339: /// @synopsis string serialize(object data)
0340: /// @return Data serialized to string representation.
0341: public static final Any serialize(Context context, Any value) {
0342: try {
0343: return new AnyString(Serialization
0344: .serialize(context, value));
0345: } catch (IOException e) {
0346: throw context.exception(e);
0347: }
0348: }
0349:
0350: /// @function bserialize
0351: /// Serializes data.
0352: /// @synopsis binary serialize(object data)
0353: /// @return Data serialized to binary.
0354: public static final Any bserialize(Context context, Any value) {
0355: try {
0356: ByteArrayOutputStream out = new ByteArrayOutputStream();
0357: Serialization.serialize(context, value, out);
0358: return new AnyBinary(out.toByteArray());
0359: } catch (IOException e) {
0360: throw context.exception(e);
0361: }
0362: }
0363:
0364: /// @function unserialize
0365: /// Unserializes data representation.
0366: /// @synopsis object unserialize(string repr)
0367: /// @synopsis object unserialize(binary repr)
0368: public static final Any unserialize(Context context, Any value) {
0369: try {
0370: if (value.isString()) {
0371: return Serialization.unserialize(context, value
0372: .toString());
0373: } else if (value.isBinary()) {
0374: return Serialization.unserialize(context, value
0375: .toBinary(), 0, value.sizeOf());
0376: }
0377: } catch (UnserializationException e) {
0378: e.printStackTrace();
0379: throw context.CorruptedSerialization();
0380: }
0381: return Any.UNDEFINED;
0382: }
0383:
0384: /// @function addressOf
0385: /// Returns memory address of parameters. Returned value for
0386: /// same value is not guaranteed to be same between calls.
0387: /// @synopsis int addressOf(object data)
0388: public static Any addressOf(Any value) {
0389: return Any.create(System.identityHashCode(value));
0390: }
0391:
0392: /// @function chr
0393: /// Converts given character code into character (to string
0394: /// which has the length of one).
0395: /// @synopsis string chr(int code)
0396: public static final Object[] p_chr = { "code" };
0397:
0398: public static final Any chr(int code) {
0399: return Any.create((char) code);
0400: }
0401:
0402: /// @function ord
0403: /// Converts first character of given string to its
0404: /// ordinal value.
0405: /// @synopsis int ord(string str)
0406: public static final Object[] p_ord = { "str" };
0407:
0408: public static final Any ord(String value) {
0409: return value.length() > 0 ? Any.create((int) value.charAt(0))
0410: : Any.ZERO;
0411: }
0412:
0413: /// @function parseNumber
0414: /// Attempts to parse given string to integer. Valid formats are
0415: /// 123 (decimal), 0x123 (hex) , 0b101 (binary) , 0123 (octal)
0416: /// @synopsis parseNumber(string str)
0417: /// @synopsis parseNumber(string str, int defaultValue)
0418: /// @param str String to convert
0419: /// @param defaultValue Value returned if parsing failed, by default null.
0420: /// @return Integer parsed.
0421: public static final Object[] p_parseNumber = { "str",
0422: "*defaultValue", Any.NULL };
0423:
0424: public static final Any parseNumber(String value, Any defaultValue) {
0425: try {
0426: return Any.create(Conversions.parseNumberUnsafe(value));
0427: } catch (NumberFormatException e) {
0428: return defaultValue;
0429: }
0430: }
0431:
0432: /// @function parseInt
0433: /// Attempts to parse given string to integer.
0434: /// @synopsis parseInt(string str)
0435: /// @synopsis parseInt(string str, int radix)
0436: /// @synopsis parseInt(string str, int radix, int defaultValue)
0437: /// @param str String to convert
0438: /// @param radix Radix of string, default is 10.
0439: /// @param defaultValue Value returned if parsing failed, by default null.
0440: /// @return Parsed integer.
0441: public static final Object[] p_parseInt = { "str", "*radix",
0442: new Integer(10), "*defaultValue", Any.NULL };
0443:
0444: public static final Any parseInt(String value, int radix,
0445: Any defaultValue) {
0446: if (radix < Character.MIN_RADIX) {
0447: radix = 10;
0448: } else if (radix > Character.MAX_RADIX) {
0449: radix = 10;
0450: }
0451: try {
0452: return Any.create(Long.parseLong(value, radix));
0453: } catch (NumberFormatException e) {
0454: return defaultValue;
0455: }
0456: }
0457:
0458: /// @function parseFloat
0459: /// Attempts to parse given string to float.
0460: /// @synopsis parseFloat(string str)
0461: /// @synopsis parseFloat(string str, float defaultValue)
0462: /// @param str String to convert
0463: /// @param defaultValue Value returned if parsing failed, by default null.
0464: /// @return Parsed float.
0465: public static final Object[] p_parseFloat = { "str",
0466: "*defaultValue", Any.NULL };
0467:
0468: public static final Any parseFloat(String value, Any defaultValue) {
0469: try {
0470: return Any.create(Double.parseDouble(value));
0471: } catch (NumberFormatException e) {
0472: return defaultValue;
0473: }
0474: }
0475:
0476: /// @function createArray
0477: /// Creates multidimensional rectangular array with given dimensions.
0478: /// @synopsis createArray(range dimensions...)
0479: /// @param dimension Integer for upper bound or list as (lobound, hibound).
0480: /// @return Array created
0481: public static final Object[] p_createArray = { new Integer(1),
0482: "dimensions" };
0483:
0484: public static final Any createArray(Any[] parameters) {
0485: int max = (parameters != null) ? parameters.length : 0;
0486: if (max < 1) {
0487: return Any.NULL;
0488: }
0489: return createArray(null, parameters, 0);
0490: }
0491:
0492: /// @function createMatrix
0493: /// Creates multidimensional rectangular array with default values.
0494: /// @synopsis createMatrix(range dimensions...)
0495: /// @param defaultValue Default value for each leaf element.
0496: /// @param dimension Integer for upper bound or list as (lobound, hibound).
0497: /// @return Array created
0498: public static final Object[] p_createMatrix = { new Integer(2),
0499: "initialValue", "dimensions" };
0500:
0501: public static final Any createMatrix(Any initialValue,
0502: Any[] parameters) {
0503: int max = (parameters != null) ? parameters.length : 0;
0504: if (max < 1) {
0505: return Any.NULL;
0506: }
0507: return createArray(initialValue, parameters, 0);
0508: }
0509:
0510: private static final Any createArray(Any initialValue,
0511: Any[] ranges, int level) {
0512: if (level >= ranges.length) {
0513: return initialValue;
0514: }
0515:
0516: Any range = ranges[level];
0517: int start = 0;
0518: int end = 0;
0519: if (range.isRange()) {
0520: AnyRange r = range.toRange();
0521: start = r.getLeft().toInt();
0522: end = r.getRight().toInt();
0523: } else {
0524: end = range.toInt() - 1;
0525: }
0526:
0527: if (start <= end) {
0528: Array array = new Array(end - start);
0529: Any value;
0530: while (start <= end) {
0531: value = createArray(initialValue, ranges, level + 1);
0532: if (value == null) {
0533: value = new Array();
0534: }
0535: array.append(new AnyInt(start), value);
0536: start++;
0537: }
0538: return array;
0539: } else {
0540: return new Array();
0541: }
0542: }
0543:
0544: /// @function or
0545: /// Returns the result of binary arithmetic OR.
0546: /// @synopsis int or(object a, int b, ...);
0547: /// @return Result of binary OR.
0548: public static final Object[] p_or = { new Integer(2), "a", "b",
0549: "rest" };
0550:
0551: public static final Any or(long a, long b, Any[] rest) {
0552: long r = a | b;
0553: final int n = rest.length;
0554: if (n > 0) {
0555: for (int i = 0; i < n; i++) {
0556: r = r | rest[i].toLong();
0557: }
0558: }
0559: return Any.create(r);
0560: }
0561:
0562: /// @function and
0563: /// Returns the result of binary arithmetic AND.
0564: /// @synopsis int and(int a, int b, ...);
0565: /// @return Result of binary AND.
0566: public static final Object[] p_and = { new Integer(2), "a", "b",
0567: "rest" };
0568:
0569: public static final Any and(long a, long b, Any[] rest) {
0570: long r = a & b;
0571: final int n = rest.length;
0572: if (n > 0) {
0573: for (int i = 0; i < n; i++) {
0574: r = r & rest[i].toLong();
0575: }
0576: }
0577: return Any.create(r);
0578: }
0579:
0580: /// @function xor
0581: /// Returns the result of logical xor.
0582: /// @synopsis xor(object a, object b, ...);
0583: /// @return Result of logical xor.
0584: public static final Object[] p_xor = { new Integer(2), "a", "b",
0585: "rest" };
0586:
0587: public static final Any xor(long a, long b, Any[] rest) {
0588: long r = a ^ b;
0589: final int n = rest.length;
0590: if (n > 0) {
0591: for (int i = 0; i < n; i++) {
0592: r = r ^ rest[i].toLong();
0593: }
0594: }
0595: return Any.create(r);
0596: }
0597:
0598: /// @function neg
0599: /// Returns the result of logical negation.
0600: /// @synopsis int neg(int a)
0601: /// @return Result of logical negation.
0602: public static final Object[] p_neg = { "a" };
0603:
0604: public static final Any neg(long a) {
0605: return Any.create(~a);
0606: }
0607:
0608: /// @function shift
0609: /// Shifts the parameter to left or right for given amount.
0610: /// @synopsis int shift(int a, int amount)
0611: /// @param amount Left shift if positive, right shift if negative.
0612: /// @return Result of shift.
0613: public static final Object[] p_shift = { "a", "amount" };
0614:
0615: public static final Any shift(long a, int amount) {
0616: if (amount < 0) {
0617: return Any.create(a >> -amount);
0618: } else {
0619: return Any.create(a << amount);
0620: }
0621: }
0622:
0623: private static final void appendHrefTo(StringBuffer buffer, Any value, boolean isAlone)
0624: {
0625: if (isAlone && (buffer.length()>0)) {
0626: buffer.append('&');
0627: }
0628: switch(value.typeOf()) {
0629: case Any.IS_NULL:
0630: case Any.IS_UNDEFINED:
0631: break;
0632:
0633: case Any.IS_BOOLEAN:
0634: case Any.IS_INT:
0635: case Any.IS_DOUBLE:
0636: buffer.append(value.toString());
0637: if (isAlone) {
0638: buffer.append('=');
0639: }
0640: break;
0641:
0642: case Any.IS_STRING:
0643: buffer.append(Conversions.URLEncode(value.toString()));
0644: if (isAlone) {
0645: buffer.append('=');
0646: }
0647: break;
0648:
0649: case Any.IS_MAP:
0650: AnyMap map = value.toMap();
0651: buffer.append(Conversions.URLEncode(map.getLeft().toString()));
0652: buffer.append('=');
0653: buffer.append(Conversions.URLEncode(map.getRight().toString()));
0654: break;
0655:
0656: case Any.IS_TUPLE:
0657: case Any.IS_LIST:
0658: case Any.IS_ARRAY:
0659: if (isAlone) {
0660: BindingEnumeration enum = value.enumeration();
0661: Any key;
0662: while(enum.hasMoreElements()) {
0663: key = (Any)enum.nextKey();
0664: if (!key.isInt()) {
0665: buffer.append(Conversions.URLEncode(key.toString()));
0666: buffer.append('=');
0667: }
0668: appendHrefTo(buffer, (Any)enum.nextElement(), false);
0669: if (enum.hasMoreElements()) {
0670: buffer.append('&');
0671: }
0672: }
0673: }
0674: break;
0675:
0676: default:
0677: buffer.append(Conversions.URLEncode(value.toString()));
0678: if (isAlone) {
0679: buffer.append('=');
0680: }
0681: break;
0682: }
0683: }
0684:
0685: /// @function toHref
0686: /// Creates query string.
0687: /// @synopsis toHref(param, ...)
0688: /// @param param Map <code>key=>value</code> for mapped values,
0689: /// array or sequence of values or anything else for mappings with empty value.
0690: /// @return Query string
0691: public static final Object[] p_toHref = { "p1", "*p2", null, "rest" };
0692:
0693: public static final Any toHref(Any p1, Any p2, Any[] rest) {
0694: StringBuffer href = new StringBuffer();
0695: appendHrefTo(href, p1, true);
0696: if (p2 != null) {
0697: appendHrefTo(href, p2, true);
0698: if (rest != null) {
0699: int n = rest.length;
0700: for (int i = 0; i < n; i++) {
0701: appendHrefTo(href, rest[i], true);
0702: }
0703: }
0704: }
0705: return new AnyString(href.toString());
0706: }
0707:
0708: /// @function format
0709: /// Format 'sprintf' style format string with given parameters. Format
0710: /// may contain fields:
0711: /// <br><br>
0712: /// <table border=1>
0713: /// <tr><td colspan=2>
0714: /// <tt>% [-]? [+]? [0]? [width] ( [.] [precision] ) [csdifg]</tt>
0715: /// </td></tr>
0716: /// <tr><td>-</td><td>
0717: /// Adjust left, instead of right.
0718: /// </td>
0719: /// <tr><td>+</td><td>Numbers with sign</td>
0720: /// <tr><td>0</td><td>Pad numbers with zeros, instead of spaces</td>
0721: /// <tr><td>width</td><td>Width of field, if '*' width will be taken from arguments</td>
0722: /// <tr><td>precision</td><td>Width of fraction part (doubles), if '*' width will be
0723: /// taken from arguments</td>
0724: /// <tr><td>c</td><td>
0725: /// Character (integer or first character from string).
0726: /// </td>
0727: /// <tr><td>s</td><td>String</td>
0728: /// <tr><td>d,i</td><td>Integer</td>
0729: /// <tr><td>f</td><td>
0730: /// Float, follows width.precision stricly
0731: /// </td>
0732: /// <tr><td>g</td><td>
0733: /// Float with signicant fraction shown, if precision is zero (or not given)
0734: /// shows significant digits from it.
0735: /// </td>
0736: /// </table>
0737: ///
0738: /// Use %% to escape %.<br>
0739: /// @synopsis format(string format, ...)
0740: /// @param format Format string
0741: /// @return Formatted string
0742: public static final Object[] p_format = { "format", "parameters" };
0743:
0744: public static final Any format(String format, Any[] arguments) {
0745: return Any.create(anvil.util.Format.format(format, arguments));
0746: }
0747:
0748: /// @function escape
0749: /// Converts string to backslash escaped format.
0750: /// @synopsis string escape(string str)
0751: /// @param str String to escape
0752: /// @return Escaped string
0753: public static final Object[] p_escape = { "str" };
0754:
0755: public static final Any escape(String str) {
0756: return Any.create(anvil.util.Conversions.escape(str));
0757: }
0758:
0759: /// @function quote
0760: /// Converts all applicable characters in string to html-entities.
0761: /// @synopsis string quote(string str)
0762: /// @param str String to quote
0763: /// @return Quoted string
0764: public static final Object[] p_quote = { "str" };
0765:
0766: public static final Any quote(String str) {
0767: return Any.create(anvil.util.Conversions.encodeEntities(str));
0768: }
0769:
0770: /// @function unquote
0771: /// Converts all applicable "entities; to their character counterparts.
0772: /// @synopsis string unquote(string str)
0773: /// @param str String to unquote
0774: /// @return Unquoted string
0775: public static final Object[] p_unquote = { "str" };
0776:
0777: public static final Any unquote(String str) {
0778: return Any.create(anvil.util.Conversions.decodeEntities(str));
0779: }
0780:
0781: /// @function encode Encodes string.
0782: /// @synopsis string encode(string str)
0783: /// @param str String
0784: /// @return Encoded string
0785: public static final Object[] p_encode = { "str" };
0786:
0787: public static final Any encode(String str) {
0788: return Any.create(anvil.util.Conversions.URLEncode(str));
0789: }
0790:
0791: /// @function decode Decodes URL encoded string.
0792: /// @synopsis string decode(string str)
0793: /// @param str URL encoded string
0794: /// @return Decoded string
0795: public static final Object[] p_decode = { "str" };
0796:
0797: public static final Any decode(String str) {
0798: return Any.create(anvil.util.Conversions.URLDecode(str));
0799: }
0800:
0801: private static Any SUFFIX_TH = Any.create("th");
0802: private static Any SUFFIX_ST = Any.create("st");
0803: private static Any SUFFIX_ND = Any.create("nd");
0804: private static Any SUFFIX_RD = Any.create("rd");
0805:
0806: /// @function th
0807: /// Returns english numeral suffix (st, nd, th) for given value.
0808: /// @synopsis string th(int number)
0809: /// @param value
0810: /// @return Numeral suffix.
0811: public static final Object[] p_th = { "value" };
0812:
0813: public static final Any th(int i) {
0814: if ((i >= 11) && (i <= 13)) {
0815: return SUFFIX_TH;
0816: } else {
0817: switch (i % 10) {
0818: case 1:
0819: return SUFFIX_ST;
0820: case 2:
0821: return SUFFIX_ND;
0822: case 3:
0823: return SUFFIX_RD;
0824: default:
0825: return SUFFIX_TH;
0826: }
0827: }
0828: }
0829:
0830: /// @function clone
0831: /// Creates shallow copy from given value.
0832: /// @synopsis object clone(object value)
0833: /// @param value Value to be cloned.
0834: /// @return Cloned value
0835: public static final Object[] p_clone = { null, "value" };
0836:
0837: public static final Any clone(Context context, Any value) {
0838: return (Any) value.clone();
0839: }
0840:
0841: /// @function copy
0842: /// Creates deep copy from 'value'.
0843: /// @synopsis object copy(object value)
0844: /// @param value Value to be copied.
0845: /// @return Copied value
0846: public static final Object[] p_copy = { null, "value" };
0847:
0848: public static final Any copy(Context context, Any value) {
0849: return value.copy();
0850: }
0851:
0852: /// @function coerce
0853: /// Returns list containing 'a' and 'b' converted
0854: /// to similar types according to same rules
0855: /// applied to arithmetic operations.
0856: /// If second parameter is omitted tries to convert
0857: /// string to int or float, if conversion fails
0858: /// returns self.
0859: /// @synopsis tuple coerce(object a, object b)
0860: /// @synopsis object coerce(object a)
0861: public static final Object[] p_coerce = { "a", "*b", null };
0862:
0863: public static final Any coerce(Any a, Any b) {
0864: if (b == null) {
0865: return a.coerce();
0866: }
0867: int typeOfA = a.typeOf();
0868: int typeOfB = b.typeOf();
0869: if (typeOfA == Any.IS_DOUBLE || typeOfB == Any.IS_DOUBLE) {
0870: return new AnyTuple(new Any[] { a.toAnyDouble(),
0871: b.toAnyDouble() });
0872: } else {
0873: return new AnyTuple(
0874: new Any[] { a.toAnyInt(), b.toAnyInt() });
0875: }
0876: }
0877:
0878: /// @function divmod
0879: /// Performs division operation with parameters and
0880: /// returns result of division and remainder.
0881: /// @synopsis list divmod(object a, object b)
0882: /// @return List (divisionResult, remainder)
0883: public static final Object[] p_divmod = { "a", "b" };
0884:
0885: public static final Any divmod(Any a, Any b) {
0886: int typeOfA = a.typeOf();
0887: int typeOfB = b.typeOf();
0888: if (typeOfA == Any.IS_DOUBLE || typeOfB == Any.IS_DOUBLE) {
0889: double da = a.toDouble();
0890: double db = b.toDouble();
0891: return new AnyTuple(new Any[] { new AnyDouble(da / db),
0892: new AnyDouble(Math.IEEEremainder(da, db)) });
0893: } else {
0894: int ia = a.toInt();
0895: int ib = b.toInt();
0896: if (ib == 0) {
0897: return new AnyTuple(new Any[] { Any.ZERO, Any.ZERO });
0898: } else {
0899: return new AnyTuple(new Any[] { Any.create(ia / ib),
0900: Any.create(ia % ib) });
0901: }
0902: }
0903: }
0904:
0905: /// @function test
0906: /// Compares parameters.
0907: /// @synopsis int test(object a, object b)
0908: /// @return -1 if a<b, 0 if a==b, 1 if a>b.
0909: public static final Object[] p_test = { "a", "b" };
0910:
0911: public static final Any test(Any a, Any b) {
0912: return Any.create(Any.Op.test(a, b));
0913: }
0914:
0915: /// @function compareTo
0916: /// Compares parameters.
0917: /// @synopsis int compareTo(object a, object b)
0918: /// @return -1 if a<b, 0 if a==b, 1 if a>b.
0919: public static final Object[] p_compareTo = { "a", "b" };
0920:
0921: public static final Any compareTo(Any a, Any b) {
0922: return Any.create(a.compareTo(b));
0923: }
0924:
0925: /// @function equals
0926: /// Compares parameters.
0927: /// @synopsis boolean equals(object a, object b)
0928: /// @return true if a==b, false otherwise.
0929: public static final Object[] p_equals = { "a", "b" };
0930:
0931: public static final Any equals(Any a, Any b) {
0932: return a.equals(b) ? Any.TRUE : Any.FALSE;
0933: }
0934:
0935: /// @function toHex
0936: /// Converts number to hexadecimal format.
0937: /// @synopsis string toHex(int number)
0938: /// @synopsis string toHex(int number, int length)
0939: /// @synopsis string toHex(int number, int length, string pad)
0940: /// @param number Number to convert
0941: /// @param length Length of resulting string
0942: /// @param pad Padding character, default is '0'
0943: /// @return Number converted to hexadecimal
0944: public static final Object[] p_toHex = { "number", "*length",
0945: new Integer(0), "*pad", "0" };
0946:
0947: public static final Any toHex(long value, int length, String pad) {
0948: return doPad(Long.toHexString(value), length, pad);
0949: }
0950:
0951: /// @function toOctal
0952: /// Converts number to octal format.
0953: /// @synopsis string toOctal(int number)
0954: /// @synopsis string toOctal(int number, int length)
0955: /// @synopsis string toOctal(int number, int length, string pad)
0956: /// @param number Number to convert
0957: /// @param length Length of resulting string
0958: /// @param pad Padding character, default is '0'
0959: /// @return Number converted to octal
0960: public static final Object[] p_toOctal = { "number", "*length",
0961: new Integer(0), "*pad", "0" };
0962:
0963: public static final Any toOctal(long value, int length, String pad) {
0964: return doPad(Long.toOctalString(value), length, pad);
0965: }
0966:
0967: /// @function toBin
0968: /// Converts number to binary format.
0969: /// @synopsis string toBin(int number)
0970: /// @synopsis string toBin(int number, int length)
0971: /// @synopsis string toBin(int number, int length, string pad)
0972: /// @param number Number to convert
0973: /// @param length Length of resulting string
0974: /// @param pad Padding character, default is '0'
0975: /// @return Number converted to binary
0976: public static final Object[] p_toBin = { "number", "*length",
0977: new Integer(0), "*pad", "0" };
0978:
0979: public static final Any toBin(long value, int length, String pad) {
0980: return doPad(Long.toBinaryString(value), length, pad);
0981: }
0982:
0983: /// @function toRadix
0984: /// Converts number to given radix format.
0985: /// @synopsis string toRadix(int number, int radix)
0986: /// @synopsis string toRadix(int number, int radix, int length)
0987: /// @synopsis string toRadix(int number, int radix, int length, string pad)
0988: /// @param number Number to convert
0989: /// @param radix Radix
0990: /// @param length Length of resulting string
0991: /// @param pad Padding character, default is '0'
0992: /// @return Number converted to given radix
0993: public static final Object[] p_toRadix = { "number", "radix",
0994: "*length", new Integer(0), "*pad", "0" };
0995:
0996: public static final Any toRadix(long value, int radix, int length,
0997: String pad) {
0998: return doPad(Long.toString(value, radix), length, pad);
0999: }
1000:
1001: private static final Any doPad(String string, int length,
1002: String padstr) {
1003: if (length == 0) {
1004: return ObjectPool.createString(string);
1005: }
1006:
1007: char pad;
1008: if (padstr == null || padstr.length() == 0) {
1009: pad = '0';
1010: } else {
1011: pad = padstr.charAt(0);
1012: }
1013:
1014: if (length > 0) {
1015: int n = string.length();
1016: if (n < length) {
1017: StringBuffer buffer = new StringBuffer(length);
1018: while (n++ < length) {
1019: buffer.append(pad);
1020: }
1021: buffer.append(string);
1022: return ObjectPool.createString(buffer.toString());
1023: } else {
1024: return ObjectPool.createString(string);
1025: }
1026: } else {
1027: int n = string.length();
1028: length = -length;
1029: if (n < length) {
1030: StringBuffer buffer = new StringBuffer(length);
1031: buffer.append(string);
1032: while (n++ < length) {
1033: buffer.append(pad);
1034: }
1035: return ObjectPool.createString(buffer.toString());
1036: } else {
1037: return ObjectPool.createString(string);
1038: }
1039: }
1040: }
1041:
1042: /// @function toAnvil
1043: /// Converts value to valid code producing the same value.
1044: /// @synopsis string toAnvil(object value)
1045: public static final Object[] p_toAnvil = { "value" };
1046:
1047: public static final Any toAnvil(Any value) {
1048: return new AnyString(value.toAnvil());
1049: }
1050:
1051: /// @function toJava
1052: /// Converts value to valid code producing the same value.
1053: /// @synopsis string toJava(object value)
1054: public static final Object[] p_toJava = { "value" };
1055:
1056: public static final Any toJava(Any value) {
1057: return new AnyString(value.toJava());
1058: }
1059:
1060: /// @function toString
1061: /// Converts sequence to string. Useful with sequences, arrays, enumerations
1062: /// and any other values returning enumeration.
1063: /// @synopsis string toString(object value)
1064: public static final Object[] p_toString = { "value" };
1065:
1066: public static final Any toString(Any value) {
1067: int n;
1068: byte[] bytes;
1069: StringBuffer buf;
1070: switch (value.typeOf()) {
1071: case Any.IS_STRING:
1072: return value;
1073:
1074: case Any.IS_BUFFER:
1075: return value.toAnyString();
1076:
1077: case Any.IS_BINARY:
1078: return new AnyString(new String(value.toBinary(), 0, value
1079: .sizeOf()));
1080:
1081: case Any.IS_TUPLE:
1082: case Any.IS_LIST:
1083: Any[] list = value.toTuple();
1084: n = value.sizeOf();
1085: buf = new StringBuffer(n);
1086: for (int i = 0; i < n; i++) {
1087: buf.append(list[i].toChar());
1088: }
1089: return new AnyString(buf.toString());
1090:
1091: case Any.IS_ARRAY:
1092: Array array = value.toArray();
1093: n = array.size();
1094: buf = new StringBuffer(n);
1095: Enumeration e = array.elements();
1096: while (e.hasMoreElements()) {
1097: buf.append(((Any) e.nextElement()).toChar());
1098: }
1099: return new AnyString(buf.toString());
1100:
1101: default:
1102: return new AnyString(value.toString());
1103: }
1104: }
1105:
1106: /// @function toBuffer
1107: /// Converts sequence to buffer. Useful with sequences, arrays, enumerations
1108: /// and any other values returning enumeration.
1109: /// @synopsis string toBuffer(object value)
1110: public static final Object[] p_toBuffer = { "value" };
1111:
1112: public static final Any toBuffer(Any value) {
1113: int n;
1114: byte[] bytes;
1115: StringBuffer buf;
1116: switch (value.typeOf()) {
1117: case Any.IS_STRING:
1118: return new AnyBuffer(new StringBuffer(value.toString()));
1119:
1120: case Any.IS_BUFFER:
1121: return value;
1122:
1123: case Any.IS_BINARY:
1124: return new AnyBuffer(new StringBuffer(new String(value
1125: .toBinary(), 0, value.sizeOf())));
1126:
1127: case Any.IS_TUPLE:
1128: case Any.IS_LIST:
1129: Any[] list = value.toTuple();
1130: n = value.sizeOf();
1131: buf = new StringBuffer(n);
1132: for (int i = 0; i < n; i++) {
1133: buf.append(list[i].toChar());
1134: }
1135: return new AnyBuffer(buf);
1136:
1137: case Any.IS_ARRAY:
1138: Array array = value.toArray();
1139: n = array.size();
1140: buf = new StringBuffer(n);
1141: Enumeration e = array.elements();
1142: while (e.hasMoreElements()) {
1143: buf.append(((Any) e.nextElement()).toChar());
1144: }
1145: return new AnyBuffer(buf);
1146:
1147: default:
1148: return new AnyBuffer(new StringBuffer(value.toString()));
1149: }
1150: }
1151:
1152: /// @function toBinary
1153: /// Converts sequence to binary. Useful with sequences, arrays, enumerations
1154: /// and any other values returning enumeration.
1155: /// @synopsis binary toBinary(object value)
1156: public static final Object[] p_toBinary = { "value" };
1157:
1158: public static final Any toBinary(Any value) {
1159: int n;
1160: byte[] bytes;
1161: switch (value.typeOf()) {
1162: case Any.IS_STRING:
1163: case Any.IS_BUFFER:
1164: return new AnyBinary(anvil.util.Conversions.getBytes(value
1165: .toString()));
1166:
1167: case Any.IS_BINARY:
1168: return value;
1169:
1170: case Any.IS_TUPLE:
1171: case Any.IS_LIST:
1172: Any[] list = value.toTuple();
1173: n = value.sizeOf();
1174: bytes = new byte[n];
1175: for (int i = 0; i < n; i++) {
1176: Any e = list[i];
1177: if (e.coerce().isString()) {
1178: bytes[i] = (byte) e.toChar();
1179: } else {
1180: bytes[i] = e.toByte();
1181: }
1182: }
1183: return new AnyBinary(bytes);
1184:
1185: case Any.IS_ARRAY: {
1186: Array array = value.toArray();
1187: n = array.size();
1188: bytes = new byte[n];
1189: int i = 0;
1190: Enumeration e = array.elements();
1191: while (i < n && e.hasMoreElements()) {
1192: bytes[i++] = (byte) ((Any) e.nextElement()).toInt();
1193: }
1194: return new AnyBinary(bytes);
1195: }
1196:
1197: default: {
1198: AnyBinary binary = new AnyBinary();
1199: Enumeration e = value.enumeration();
1200: while (e.hasMoreElements()) {
1201: binary.append(Any.create(e.nextElement()));
1202: }
1203: return binary;
1204: }
1205: }
1206: }
1207:
1208: /// @function toTuple
1209: /// Converts sequence to binary. Useful with sequences, arrays, enumerations
1210: /// and any other values returning enumeration.
1211: /// @synopsis tuple toTuple(object value)
1212: public static final Object[] p_toTuple = { "value" };
1213:
1214: public static final Any toTuple(Any value) {
1215: Any[] list;
1216: int n;
1217:
1218: switch (value.typeOf()) {
1219: case Any.IS_STRING:
1220: String str = value.toString();
1221: n = str.length();
1222: if (n == 0) {
1223: break;
1224: }
1225: list = new Any[n];
1226: for (int i = 0; i < n; i++) {
1227: list[i] = Any.create(str.charAt(i));
1228: }
1229: return new AnyTuple(list);
1230:
1231: case Any.IS_BUFFER:
1232: StringBuffer buf = value.toBuffer();
1233: n = buf.length();
1234: if (n == 0) {
1235: break;
1236: }
1237: list = new Any[n];
1238: for (int i = 0; i < n; i++) {
1239: list[i] = Any.create(buf.charAt(i));
1240: }
1241: return new AnyTuple(list);
1242:
1243: case Any.IS_TUPLE:
1244: return value;
1245:
1246: case Any.IS_LIST:
1247: list = value.toList();
1248: n = value.sizeOf();
1249: if (n == 0) {
1250: break;
1251: }
1252: Any[] newlist = new Any[n];
1253: System.arraycopy(list, 0, newlist, 0, n);
1254: return new AnyList(newlist);
1255:
1256: case Any.IS_BINARY:
1257: byte[] bytes = value.toBinary();
1258: n = value.sizeOf();
1259: if (n == 0) {
1260: break;
1261: }
1262: list = new Any[n];
1263: for (int i = 0; i < n; i++) {
1264: list[i] = Any.create(bytes[i]);
1265: }
1266: return new AnyTuple(list);
1267:
1268: case Any.IS_ARRAY: {
1269: Array array = value.toArray();
1270: n = array.size();
1271: if (n == 0) {
1272: break;
1273: }
1274: list = new Any[n];
1275: Enumeration e = array.elements();
1276: int i = 0;
1277: while (i < n && e.hasMoreElements()) {
1278: list[i++] = (Any) e.nextElement();
1279: }
1280: return new AnyTuple(list);
1281: }
1282:
1283: default: {
1284: AnyTuple tuple = new AnyTuple();
1285: Enumeration e = value.enumeration();
1286: while (e.hasMoreElements()) {
1287: tuple = (AnyTuple) tuple.append(Any.create(e
1288: .nextElement()));
1289: }
1290: return tuple;
1291: }
1292: }
1293: return Any.EMPTY_TUPLE;
1294: }
1295:
1296: /// @function toList
1297: /// Converts value to binary. Useful with sequences, arrays, enumerations
1298: /// and any other values returning enumeration.
1299: /// @synopsis list toList(object value)
1300: public static final Object[] p_toList = { "value" };
1301:
1302: public static final Any toList(Any value) {
1303: Any[] list;
1304: int n;
1305: switch (value.typeOf()) {
1306: case Any.IS_STRING:
1307: String str = value.toString();
1308: n = str.length();
1309: list = new Any[n];
1310: for (int i = 0; i < n; i++) {
1311: list[i] = Any.create(str.charAt(i));
1312: }
1313: return new AnyList(list);
1314:
1315: case Any.IS_BUFFER:
1316: StringBuffer buf = value.toBuffer();
1317: n = buf.length();
1318: list = new Any[n];
1319: for (int i = 0; i < n; i++) {
1320: list[i] = Any.create(buf.charAt(i));
1321: }
1322: return new AnyList(list);
1323:
1324: case Any.IS_TUPLE:
1325: list = value.toList();
1326: n = value.sizeOf();
1327: Any[] newlist = new Any[n];
1328: System.arraycopy(list, 0, newlist, 0, n);
1329: return new AnyList(newlist);
1330:
1331: case Any.IS_LIST:
1332: return value;
1333:
1334: case Any.IS_BINARY:
1335: byte[] bytes = value.toBinary();
1336: n = value.sizeOf();
1337: list = new Any[n];
1338: for (int i = 0; i < n; i++) {
1339: list[i] = Any.create(bytes[i]);
1340: }
1341: return new AnyList(list);
1342:
1343: case Any.IS_ARRAY: {
1344: Array array = value.toArray();
1345: n = array.size();
1346: list = new Any[n];
1347: Enumeration e = array.elements();
1348: int i = 0;
1349: while (i < n && e.hasMoreElements()) {
1350: list[i++] = (Any) e.nextElement();
1351: }
1352: return new AnyList(list);
1353: }
1354:
1355: default: {
1356: AnyList anylist = new AnyList();
1357: Enumeration e = value.enumeration();
1358: while (e.hasMoreElements()) {
1359: anylist.append(Any.create(e.nextElement()));
1360: }
1361: return anylist;
1362: }
1363: }
1364: }
1365:
1366: /// @function toArray
1367: /// Converts value to array. Useful with sequences, arrays, enumerations
1368: /// and any other values returning enumeration.
1369: /// @synopsis array toArray(object value)
1370: public static final Object[] p_toArray = { "value" };
1371:
1372: public static final Any toArray(Any value) {
1373: Array array;
1374: int n;
1375: switch (value.typeOf()) {
1376: case Any.IS_STRING:
1377: String str = value.toString();
1378: n = str.length();
1379: array = new Array(n);
1380: for (int i = 0; i < n; i++) {
1381: array.append(Any.create(str.charAt(i)));
1382: }
1383: return array;
1384:
1385: case Any.IS_BUFFER:
1386: StringBuffer buf = value.toBuffer();
1387: n = buf.length();
1388: array = new Array(n);
1389: for (int i = 0; i < n; i++) {
1390: array.append(Any.create(buf.charAt(i)));
1391: }
1392: return array;
1393:
1394: case Any.IS_BINARY:
1395: byte[] bytes = value.toBinary();
1396: n = value.sizeOf();
1397: array = new Array(n);
1398: for (int i = 0; i < n; i++) {
1399: array.append(Any.create(bytes[i]));
1400: }
1401: return array;
1402:
1403: case Any.IS_TUPLE:
1404: case Any.IS_LIST:
1405: Any[] list = value.toTuple();
1406: n = value.sizeOf();
1407: array = new Array(n);
1408: for (int i = 0; i < n; i++) {
1409: array.append(i, list[i]);
1410: }
1411: return array;
1412:
1413: case Any.IS_ARRAY:
1414: return value;
1415:
1416: default:
1417: array = new Array();
1418: BindingEnumeration e = value.enumeration();
1419: while (e.hasMoreElements()) {
1420: array.append(Any.create(e.nextKey()), Any.create(e
1421: .nextElement()));
1422: }
1423: return array;
1424: }
1425: }
1426:
1427: /// @function context
1428: /// Returns context of current custom tag.
1429: /// @synopsis object context()
1430: /// @return Current context.
1431: public static final Any context(Context context) {
1432: return context.frame().peek();
1433: }
1434:
1435: /// @function println
1436: /// Same as builtin statement <code>println</code>. Prints all
1437: /// parameters and newline.
1438: /// @synopsis void println(...)
1439: public static final Object[] p_println = { new Integer(0), null,
1440: "parameter" };
1441:
1442: public static final Any println(Context context, Any[] params) {
1443: final int n = params.length;
1444: for (int i = 0; i < n; i++) {
1445: context.print(params[i]);
1446: }
1447: context.println();
1448: return Any.TRUE;
1449: }
1450:
1451: /// @function print
1452: /// Same as builtin statement <code>print</code>. Prints all
1453: /// parameters.
1454: /// @synopsis void print(...)
1455: public static final Object[] p_print = { new Integer(0), null,
1456: "parameter" };
1457:
1458: public static final Any print(Context context, Any[] params) {
1459: final int n = params.length;
1460: for (int i = 0; i < n; i++) {
1461: context.print(params[i]);
1462: }
1463: return Any.TRUE;
1464: }
1465:
1466: /// @function printbr
1467: /// Same as builtin statement <code>printbr</code>. Prints all
1468: /// parameters, <br;gt; and a newline.
1469: /// @synopsis void printbr(...)
1470: private static final byte[] BRLN = "<br>\n".getBytes();
1471: public static final Object[] p_printbr = { new Integer(0), null,
1472: "parameter" };
1473:
1474: public static final Any printbr(Context context, Any[] params) {
1475: final int n = params.length;
1476: for (int i = 0; i < n; i++) {
1477: context.print(params[i]);
1478: }
1479: context.print(BRLN);
1480: return Any.TRUE;
1481: }
1482:
1483: public static final anvil.script.compiler.NativeNamespace __module__ = new anvil.script.compiler.NativeNamespace(
1484: "lang",
1485: LangModule.class,
1486: new String[] {
1487: "anvil.core.AnyBinary",
1488: "anvil.core.AnyBindingEnumeration",
1489: "anvil.core.AnyBoolean",
1490: "anvil.core.AnyBuffer",
1491: "anvil.core.Any",
1492: "anvil.core.AnyDouble",
1493: "anvil.core.AnyFalse",
1494: "anvil.core.AnyHashlistIterator",
1495: "anvil.core.AnyInfinity",
1496: "anvil.core.AnyInt",
1497: "anvil.core.AnyList",
1498: "anvil.core.AnyMap",
1499: "anvil.core.AnyNull",
1500: "anvil.core.AnyNumber",
1501: "anvil.core.AnyPattern",
1502: "anvil.core.AnyRange",
1503: "anvil.core.AnySequence",
1504: "anvil.core.AnyString",
1505: "anvil.core.AnyThrowable",
1506: "anvil.core.AnyTrue",
1507: "anvil.core.AnyTuple",
1508: "anvil.core.AnyUndefined",
1509: "anvil.core.Array",
1510:
1511: "anvil.core.Throwables$TypeError",
1512: "anvil.core.Throwables$TypeError$BadParameter",
1513: "anvil.core.Throwables$TypeError$NotEnoughParameters",
1514: "anvil.core.Throwables$TypeError$NoSuchMethod",
1515: "anvil.core.Throwables$TypeError$NoSuchMember",
1516: "anvil.core.Throwables$TypeError$NoSuchFunction",
1517: "anvil.core.Throwables$TypeError$NoSuchClass",
1518: "anvil.core.Throwables$TypeError$NoSuchEntity",
1519: "anvil.core.Throwables$TypeError$NoInstance",
1520: "anvil.core.Throwables$TypeError$InstantiationError",
1521: "anvil.core.Throwables$TypeError$AttributeError",
1522: "anvil.core.Throwables$TypeError$ReferenceError",
1523: "anvil.core.Throwables$TypeError$CallError",
1524:
1525: "anvil.core.Throwables$JavaError",
1526: "anvil.core.Throwables$BadState",
1527: "anvil.core.Throwables$AssertFailed",
1528: "anvil.core.Throwables$CorruptedSerialization",
1529: "anvil.core.Throwables$MalformedPattern",
1530: "anvil.core.Throwables$AcquireError",
1531: "anvil.core.Throwables$XMLError",
1532: "anvil.core.Throwables$ImportError",
1533: "anvil.core.Throwables$AccessDenied",
1534: "anvil.core.Throwables$ClassNotFound",
1535: "anvil.core.Throwables$InternalError",
1536: "anvil.core.Throwables$Interrupted",
1537: "anvil.core.Throwables$OperationFailed",
1538:
1539: },
1540: //DOC{{
1541: ""
1542: + "\n"
1543: + " @module anvil.lang\n"
1544: + " Set of elementary functions and classes.\n"
1545: + " Entities at anvil.lang are accessible directly without a need\n"
1546: + " to import or use <code>anvil.lang</code> prefix.\n"
1547: + "\n"
1548: + " @function canDo\n"
1549: + " Checks if given tool permission exists, against\n"
1550: + " current security policy\n"
1551: + " @synopsis boolean canDo(String name)\n"
1552: + " @synopsis boolean canDo(String name, String actions)\n"
1553: + " @function loadClass\n"
1554: + " Loads the given java class or interface.\n"
1555: + " @synopsis Type loadClass(String classname)\n"
1556: + " @exception ClassNotFound If class couldn't be loaded\n"
1557: + " @function deref\n"
1558: + " Returns the value referred by this given ref.\n"
1559: + " @synopsis object deref(object ref)\n"
1560: + " @param ref Ref to variable\n"
1561: + " @param derefAll If <code>true</code>, all references are followed until\n"
1562: + " first non-ref value is encountered.\n"
1563: + " @function ref\n"
1564: + " Generates and returns programmable ref from given class instance.\n"
1565: + " @synopsis object ref(object provider)\n"
1566: + " @param impl Class having <code>_getRef</code> (and <code>_setRef</code>) methods\n"
1567: + " @function reveal\n"
1568: + " Reveals and returns the ref implementation, encapsulated with <code>ref()</code>.\n"
1569: + " @synopsis object reveal(object ref)\n"
1570: + " @param ref Programmable ref\n"
1571: + " @function areSame\n"
1572: + " Checks if two objects share the same memory address.\n"
1573: + " @synopsis boolean areSame(a, b)\n"
1574: + " @function reduce\n"
1575: + " Iterates through the given elements and calls reducer function so \n"
1576: + " that the first parameter will be either the result of previous reducer\n"
1577: + " call or intialValue (if it was given), and all other parameters, up to\n"
1578: + " count are taken from then elements. \n"
1579: + " @synopsis object reduce(object reducer, object elements)\n"
1580: + " @synopsis object reduce(object reducer, int count, object elements)\n"
1581: + " @synopsis object reduce(object reducer, int count, object initialValue, object elements)\n"
1582: + " @param reducer Callable reducer taking from count parameters\n"
1583: + " @param count number of parameters to pass to reducer, default is two.\n"
1584: + " @param intialValue initial value of reduction\n"
1585: + " @return the return value of last call to reducer or initialValue\n"
1586: + " @function join\n"
1587: + " Joins the elements together with given clue.\n"
1588: + " @synopsis string join(object elements)\n"
1589: + " @synopsis string join(object elements, string clue)\n"
1590: + " @param clue Clue to join with, default is <code>\", \"</code>.\n"
1591: + " @function sort\n"
1592: + " Sorts the elements of sequence with given comparator.\n"
1593: + " @synopsis enumeration sort(object sorter, object elements)\n"
1594: + " @synopsis enumeration sort(object sorter, object elements, object data)\n"
1595: + " @param sorter Callable comparator receiving parameters <code>(value1, value2, data)</code>\n"
1596: + " @param data Data passed as a third parameter to comparator.\n"
1597: + " @function select\n"
1598: + " Returns enumeration of all elements for which the\n"
1599: + " given function returned <code>true</code>. \n"
1600: + " @synopsis enumeration select(object selector, object elements)\n"
1601: + " @synopsis enumeration select(object selector, object elements, object data)\n"
1602: + " @param pipe Callable selector receiving parameters\n"
1603: + " <code>(element, index, data)</code>\n"
1604: + " @param data Data passed as third parameter to selector.\n"
1605: + " @function pipe\n"
1606: + " Returns enumeration that iterates through given elements\n"
1607: + " and pipes the return value of given function as element\n"
1608: + " on call to <code>enumeration.next</code>.\n"
1609: + " @synopsis enumeration pipe(object converter, object elements)\n"
1610: + " @synopsis enumeration pipe(object converter, object elements, object data)\n"
1611: + " @param converter Callable converter receiving parameters <code>element, index, data)</code>\n"
1612: + " @param data Data passed as a third parameter to converter\n"
1613: + " @function apply\n"
1614: + " Iterates through given elements and applies given applier for\n"
1615: + " each element.\n"
1616: + " @synopsis int apply(object applier, object elements)\n"
1617: + " @synopsis int apply(object applier, object elements, object data)\n"
1618: + " @param applier Callable applier receiving parameters <code>(element, index, data)</code>\n"
1619: + " @param data Data passed as a third parameter to applier\n"
1620: + " @return Number of times applier function was called\n"
1621: + " @function toLower\n"
1622: + " Converts given parameter to lower case.\n"
1623: + " @synopsis string toLower(string str)\n"
1624: + " @function toLower\n"
1625: + " Converts given parameter to upper case.\n"
1626: + " @synopsis string toUpper(string str)\n"
1627: + " @function serialize\n"
1628: + " Serializes data.\n"
1629: + " @synopsis string serialize(object data)\n"
1630: + " @return Data serialized to string representation.\n"
1631: + " @function bserialize\n"
1632: + " Serializes data.\n"
1633: + " @synopsis binary serialize(object data)\n"
1634: + " @return Data serialized to binary.\n"
1635: + " @function unserialize\n"
1636: + " Unserializes data representation.\n"
1637: + " @synopsis object unserialize(string repr)\n"
1638: + " @synopsis object unserialize(binary repr)\n"
1639: + " @function addressOf\n"
1640: + " Returns memory address of parameters. Returned value for\n"
1641: + " same value is not guaranteed to be same between calls.\n"
1642: + " @synopsis int addressOf(object data)\n"
1643: + " @function chr\n"
1644: + " Converts given character code into character (to string\n"
1645: + " which has the length of one).\n"
1646: + " @synopsis string chr(int code)\n"
1647: + " @function ord\n"
1648: + " Converts first character of given string to its \n"
1649: + " ordinal value.\n"
1650: + " @synopsis int ord(string str)\n"
1651: + " @function parseNumber\n"
1652: + " Attempts to parse given string to integer. Valid formats are\n"
1653: + " 123 (decimal), 0x123 (hex) , 0b101 (binary) , 0123 (octal)\n"
1654: + " @synopsis parseNumber(string str)\n"
1655: + " @synopsis parseNumber(string str, int defaultValue)\n"
1656: + " @param str String to convert\n"
1657: + " @param defaultValue Value returned if parsing failed, by default null.\n"
1658: + " @return Integer parsed.\n"
1659: + " @function parseInt\n"
1660: + " Attempts to parse given string to integer. \n"
1661: + " @synopsis parseInt(string str)\n"
1662: + " @synopsis parseInt(string str, int radix)\n"
1663: + " @synopsis parseInt(string str, int radix, int defaultValue)\n"
1664: + " @param str String to convert\n"
1665: + " @param radix Radix of string, default is 10.\n"
1666: + " @param defaultValue Value returned if parsing failed, by default null.\n"
1667: + " @return Parsed integer.\n"
1668: + " @function parseFloat\n"
1669: + " Attempts to parse given string to float. \n"
1670: + " @synopsis parseFloat(string str)\n"
1671: + " @synopsis parseFloat(string str, float defaultValue)\n"
1672: + " @param str String to convert\n"
1673: + " @param defaultValue Value returned if parsing failed, by default null.\n"
1674: + " @return Parsed float.\n"
1675: + " @function createArray\n"
1676: + " Creates multidimensional rectangular array with given dimensions.\n"
1677: + " @synopsis createArray(range dimensions...)\n"
1678: + " @param dimension Integer for upper bound or list as (lobound, hibound).\n"
1679: + " @return Array created\n"
1680: + " @function createMatrix\n"
1681: + " Creates multidimensional rectangular array with default values.\n"
1682: + " @synopsis createMatrix(range dimensions...)\n"
1683: + " @param defaultValue Default value for each leaf element.\n"
1684: + " @param dimension Integer for upper bound or list as (lobound, hibound).\n"
1685: + " @return Array created\n"
1686: + " @function or\n"
1687: + " Returns the result of binary arithmetic OR.\n"
1688: + " @synopsis int or(object a, int b, ...);\n"
1689: + " @return Result of binary OR.\n"
1690: + " @function and\n"
1691: + " Returns the result of binary arithmetic AND.\n"
1692: + " @synopsis int and(int a, int b, ...);\n"
1693: + " @return Result of binary AND.\n"
1694: + " @function xor\n"
1695: + " Returns the result of logical xor.\n"
1696: + " @synopsis xor(object a, object b, ...);\n"
1697: + " @return Result of logical xor.\n"
1698: + " @function neg\n"
1699: + " Returns the result of logical negation.\n"
1700: + " @synopsis int neg(int a)\n"
1701: + " @return Result of logical negation.\n"
1702: + " @function shift\n"
1703: + " Shifts the parameter to left or right for given amount.\n"
1704: + " @synopsis int shift(int a, int amount)\n"
1705: + " @param amount Left shift if positive, right shift if negative.\n"
1706: + " @return Result of shift.\n"
1707: + " @function toHref\n"
1708: + " Creates query string.\n"
1709: + " @synopsis toHref(param, ...)\n"
1710: + " @param param Map <code>key=>value</code> for mapped values, \n"
1711: + " array or sequence of values or anything else for mappings with empty value.\n"
1712: + " @return Query string\n"
1713: + " @function format\n"
1714: + " Format 'sprintf' style format string with given parameters. Format\n"
1715: + " may contain fields:\n"
1716: + " <br><br>\n"
1717: + " <table border=1>\n"
1718: + " <tr><td colspan=2>\n"
1719: + " <tt>% [-]? [+]? [0]? [width] ( [.] [precision] ) [csdifg]</tt>\n"
1720: + " </td></tr>\n"
1721: + " <tr><td>-</td><td>\n"
1722: + " Adjust left, instead of right.\n"
1723: + " </td>\n"
1724: + " <tr><td>+</td><td>Numbers with sign</td>\n"
1725: + " <tr><td>0</td><td>Pad numbers with zeros, instead of spaces</td>\n"
1726: + " <tr><td>width</td><td>Width of field, if '*' width will be taken from arguments</td>\n"
1727: + " <tr><td>precision</td><td>Width of fraction part (doubles), if '*' width will be\n"
1728: + " taken from arguments</td>\n"
1729: + " <tr><td>c</td><td>\n"
1730: + " Character (integer or first character from string).\n"
1731: + " </td>\n"
1732: + " <tr><td>s</td><td>String</td>\n"
1733: + " <tr><td>d,i</td><td>Integer</td>\n"
1734: + " <tr><td>f</td><td>\n"
1735: + " Float, follows width.precision stricly\n"
1736: + " </td>\n"
1737: + " <tr><td>g</td><td>\n"
1738: + " Float with signicant fraction shown, if precision is zero (or not given)\n"
1739: + " shows significant digits from it.\n"
1740: + " </td>\n"
1741: + " </table>\n"
1742: + "\n"
1743: + " Use %% to escape %.<br>\n"
1744: + " @synopsis format(string format, ...)\n"
1745: + " @param format Format string\n"
1746: + " @return Formatted string\n"
1747: + " @function escape\n"
1748: + " Converts string to backslash escaped format.\n"
1749: + " @synopsis string escape(string str)\n"
1750: + " @param str String to escape\n"
1751: + " @return Escaped string\n"
1752: + " @function quote\n"
1753: + " Converts all applicable characters in string to html-entities.\n"
1754: + " @synopsis string quote(string str)\n"
1755: + " @param str String to quote\n"
1756: + " @return Quoted string\n"
1757: + " @function unquote\n"
1758: + " Converts all applicable "entities; to their character counterparts.\n"
1759: + " @synopsis string unquote(string str)\n"
1760: + " @param str String to unquote\n"
1761: + " @return Unquoted string\n"
1762: + " @function encode Encodes string.\n"
1763: + " @synopsis string encode(string str)\n"
1764: + " @param str String\n"
1765: + " @return Encoded string\n"
1766: + " @function decode Decodes URL encoded string.\n"
1767: + " @synopsis string decode(string str)\n"
1768: + " @param str URL encoded string\n"
1769: + " @return Decoded string\n"
1770: + " @function th \n"
1771: + " Returns english numeral suffix (st, nd, th) for given value.\n"
1772: + " @synopsis string th(int number)\n"
1773: + " @param value\n"
1774: + " @return Numeral suffix.\n"
1775: + " @function clone\n"
1776: + " Creates shallow copy from given value.\n"
1777: + " @synopsis object clone(object value)\n"
1778: + " @param value Value to be cloned.\n"
1779: + " @return Cloned value\n"
1780: + " @function copy\n"
1781: + " Creates deep copy from 'value'.\n"
1782: + " @synopsis object copy(object value)\n"
1783: + " @param value Value to be copied.\n"
1784: + " @return Copied value\n"
1785: + " @function coerce\n"
1786: + " Returns list containing 'a' and 'b' converted\n"
1787: + " to similar types according to same rules\n"
1788: + " applied to arithmetic operations.\n"
1789: + " If second parameter is omitted tries to convert\n"
1790: + " string to int or float, if conversion fails\n"
1791: + " returns self.\n"
1792: + " @synopsis tuple coerce(object a, object b)\n"
1793: + " @synopsis object coerce(object a)\n"
1794: + " @function divmod\n"
1795: + " Performs division operation with parameters and\n"
1796: + " returns result of division and remainder.\n"
1797: + " @synopsis list divmod(object a, object b)\n"
1798: + " @return List (divisionResult, remainder)\n"
1799: + " @function test\n"
1800: + " Compares parameters.\n"
1801: + " @synopsis int test(object a, object b)\n"
1802: + " @return -1 if a<b, 0 if a==b, 1 if a>b.\n"
1803: + " @function compareTo\n"
1804: + " Compares parameters.\n"
1805: + " @synopsis int compareTo(object a, object b)\n"
1806: + " @return -1 if a<b, 0 if a==b, 1 if a>b.\n"
1807: + " @function equals\n"
1808: + " Compares parameters.\n"
1809: + " @synopsis boolean equals(object a, object b)\n"
1810: + " @return true if a==b, false otherwise.\n"
1811: + " @function toHex\n"
1812: + " Converts number to hexadecimal format.\n"
1813: + " @synopsis string toHex(int number)\n"
1814: + " @synopsis string toHex(int number, int length)\n"
1815: + " @synopsis string toHex(int number, int length, string pad)\n"
1816: + " @param number Number to convert\n"
1817: + " @param length Length of resulting string\n"
1818: + " @param pad Padding character, default is '0'\n"
1819: + " @return Number converted to hexadecimal\n"
1820: + " @function toOctal\n"
1821: + " Converts number to octal format.\n"
1822: + " @synopsis string toOctal(int number)\n"
1823: + " @synopsis string toOctal(int number, int length)\n"
1824: + " @synopsis string toOctal(int number, int length, string pad)\n"
1825: + " @param number Number to convert\n"
1826: + " @param length Length of resulting string\n"
1827: + " @param pad Padding character, default is '0'\n"
1828: + " @return Number converted to octal\n"
1829: + " @function toBin\n"
1830: + " Converts number to binary format.\n"
1831: + " @synopsis string toBin(int number)\n"
1832: + " @synopsis string toBin(int number, int length)\n"
1833: + " @synopsis string toBin(int number, int length, string pad)\n"
1834: + " @param number Number to convert\n"
1835: + " @param length Length of resulting string\n"
1836: + " @param pad Padding character, default is '0'\n"
1837: + " @return Number converted to binary\n"
1838: + " @function toRadix\n"
1839: + " Converts number to given radix format.\n"
1840: + " @synopsis string toRadix(int number, int radix)\n"
1841: + " @synopsis string toRadix(int number, int radix, int length)\n"
1842: + " @synopsis string toRadix(int number, int radix, int length, string pad)\n"
1843: + " @param number Number to convert\n"
1844: + " @param radix Radix \n"
1845: + " @param length Length of resulting string\n"
1846: + " @param pad Padding character, default is '0'\n"
1847: + " @return Number converted to given radix\n"
1848: + " @function toAnvil\n"
1849: + " Converts value to valid code producing the same value.\n"
1850: + " @synopsis string toAnvil(object value)\n"
1851: + " @function toJava\n"
1852: + " Converts value to valid code producing the same value.\n"
1853: + " @synopsis string toJava(object value)\n"
1854: + " @function toString\n"
1855: + " Converts sequence to string. Useful with sequences, arrays, enumerations\n"
1856: + " and any other values returning enumeration.\n"
1857: + " @synopsis string toString(object value)\n"
1858: + " @function toBuffer\n"
1859: + " Converts sequence to buffer. Useful with sequences, arrays, enumerations\n"
1860: + " and any other values returning enumeration.\n"
1861: + " @synopsis string toBuffer(object value)\n"
1862: + " @function toBinary\n"
1863: + " Converts sequence to binary. Useful with sequences, arrays, enumerations\n"
1864: + " and any other values returning enumeration.\n"
1865: + " @synopsis binary toBinary(object value)\n"
1866: + " @function toTuple\n"
1867: + " Converts sequence to binary. Useful with sequences, arrays, enumerations\n"
1868: + " and any other values returning enumeration.\n"
1869: + " @synopsis tuple toTuple(object value)\n"
1870: + " @function toList\n"
1871: + " Converts value to binary. Useful with sequences, arrays, enumerations\n"
1872: + " and any other values returning enumeration.\n"
1873: + " @synopsis list toList(object value)\n"
1874: + " @function toArray\n"
1875: + " Converts value to array. Useful with sequences, arrays, enumerations\n"
1876: + " and any other values returning enumeration.\n"
1877: + " @synopsis array toArray(object value)\n"
1878: + " @function context\n"
1879: + " Returns context of current custom tag.\n"
1880: + " @synopsis object context()\n"
1881: + " @return Current context.\n"
1882: + " @function println\n"
1883: + " Same as builtin statement <code>println</code>. Prints all\n"
1884: + " parameters and newline.\n"
1885: + " @synopsis void println(...)\n"
1886: + " @function print\n"
1887: + " Same as builtin statement <code>print</code>. Prints all\n"
1888: + " parameters.\n"
1889: + " @synopsis void print(...)\n"
1890: + " @function printbr\n"
1891: + " Same as builtin statement <code>printbr</code>. Prints all\n"
1892: + " parameters, <br;gt; and a newline.\n"
1893: + " @synopsis void printbr(...)\n"
1894: //}}DOC
1895: );
1896:
1897: }
|