001: /*
002: * @(#)MapPackage.java 1.3 05/02/17
003: *
004: * Copyright (c) 1997-2005 Sun Microsystems, Inc. All Rights Reserved.
005: *
006: * See the file "LICENSE.txt" for information on usage and redistribution
007: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
008: */
009: package org.pnuts.lib;
010:
011: import java.util.Map;
012: import java.util.Collections;
013: import java.util.Enumeration;
014: import pnuts.lang.Pnuts;
015: import pnuts.lang.NamedValue;
016: import pnuts.lang.PnutsImpl;
017: import pnuts.lang.PnutsFunction;
018: import pnuts.lang.Context;
019: import pnuts.lang.Package;
020:
021: /**
022: * A wrapper class that makes pnuts.lang.Package from java.util.Map
023: */
024: class MapPackage extends Package {
025:
026: private Map map;
027: private static PnutsImpl pureImpl = new PnutsImpl();
028:
029: /*
030: * Constructor
031: *
032: * @param map the map
033: */
034: public MapPackage(Map map) {
035: this .map = map;
036: }
037:
038: /**
039: * Add key-value mappings from a Pnuts expression <em>def</em> to the specified <em>map</em>.
040: *
041: * @param map the map
042: * @param def a Pnuts expression
043: * @param context the context in which the Pnuts expression is evaluated.
044: */
045: public static void defineMap(Map map, String def, Context context) {
046: Context ctx = new Context(context);
047: ctx.setImplementation(pureImpl);
048: ctx.setCurrentPackage(new MapPackage(map));
049: Pnuts.eval(def, ctx);
050: }
051:
052: public Object get(String symbol, Context context) {
053: return map.get(symbol);
054: }
055:
056: public void set(String symbol, Object value, Context context) {
057: map.put(symbol, value);
058: }
059:
060: public boolean defined(String name, Context context) {
061: return map.containsKey(name);
062: }
063:
064: public Enumeration keys() {
065: return Collections.enumeration(map.keySet());
066: }
067:
068: public Enumeration values() {
069: return Collections.enumeration(map.values());
070: }
071:
072: public int size() {
073: return map.size();
074: }
075:
076: public NamedValue lookup(final String symbol, Context context) {
077: final Object value = map.get(symbol);
078: if (value != null) {
079: return new NamedValue() {
080: public String getName() {
081: return symbol;
082: }
083:
084: public Object get() {
085: return value;
086: }
087:
088: public void set(Object obj) {
089: map.put(symbol, obj);
090: }
091: };
092: } else {
093: return null;
094: }
095: }
096:
097: public static class Function extends PnutsFunction {
098: protected Object exec(Object[] args, Context context) {
099: if (args.length != 2) {
100: undefined(args, context);
101: return null;
102: }
103: Map m = (Map) args[0];
104: String def = (String) args[1];
105: defineMap(m, def, context);
106: return m;
107: }
108: }
109: }
|