01: /*
02: * @(#)constant.java 1.2 04/12/06
03: *
04: * Copyright (c) 1997-2004 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package org.pnuts.lib;
10:
11: import pnuts.lang.*;
12: import pnuts.lang.Package;
13: import java.util.ResourceBundle;
14: import java.text.MessageFormat;
15:
16: /*
17: * constant()
18: * constant(pkg)
19: */
20: public class constant extends PnutsFunction implements Property {
21:
22: public constant() {
23: super ("constant");
24: }
25:
26: public boolean defined(int nargs) {
27: return nargs == 0 || nargs == 1;
28: }
29:
30: protected Object exec(Object[] args, final Context context) {
31: final Package pkg;
32: int nargs = args.length;
33: if (nargs == 0) {
34: pkg = context.getCurrentPackage();
35: } else if (nargs == 1) {
36: pkg = (Package) args[0];
37: } else {
38: undefined(args, context);
39: return null;
40: }
41: return new Property() {
42: public Object get(String name, Context ctx) {
43: return pkg.get(name, context);
44: }
45:
46: public void set(String name, Object value, Context ctx) {
47: try {
48: pkg.setConstant(name, value);
49: } catch (IllegalStateException e) {
50: rethrow(name, context);
51: }
52: }
53:
54: public String toString() {
55: return "<constant handler>";
56: }
57: };
58: }
59:
60: static void rethrow(String symbol, Context context) {
61: ResourceBundle bundle = ResourceBundle
62: .getBundle("pnuts.lang.pnuts");
63: String fmt = bundle.getString("constant.modification");
64: String msg = MessageFormat.format(fmt, new Object[] { symbol });
65: throw new PnutsException(msg, context);
66: }
67:
68: public Object get(String name, Context context) {
69: return context.getCurrentPackage().get(name, context);
70: }
71:
72: public void set(String name, Object value, Context context) {
73: try {
74: context.getCurrentPackage().setConstant(name, value);
75: } catch (IllegalStateException e) {
76: rethrow(name, context);
77: }
78: }
79:
80: public String toString() {
81: return "<constant handler>";
82: }
83: }
|