01: /*
02: * LreplaceCmd.java
03: *
04: * Copyright (c) 1997 Cornell University.
05: * Copyright (c) 1997 Sun Microsystems, Inc.
06: *
07: * See the file "license.terms" for information on usage and
08: * redistribution of this file, and for a DISCLAIMER OF ALL
09: * WARRANTIES.
10: *
11: * RCS: @(#) $Id: LreplaceCmd.java,v 1.5 2003/01/09 02:15:39 mdejong Exp $
12: *
13: */
14:
15: package tcl.lang;
16:
17: /**
18: * This class implements the built-in "lreplace" command in Tcl.
19: */
20:
21: class LreplaceCmd implements Command {
22: /**
23: * See Tcl user documentation for details.
24: * @exception TclException If incorrect number of arguments.
25: */
26:
27: public void cmdProc(Interp interp, TclObject argv[])
28: throws TclException {
29: if (argv.length < 4) {
30: throw new TclNumArgsException(interp, 1, argv,
31: "list first last ?element element ...?");
32: }
33: int size = TclList.getLength(interp, argv[1]);
34: int first = Util.getIntForIndex(interp, argv[2], size - 1);
35: int last = Util.getIntForIndex(interp, argv[3], size - 1);
36: int numToDelete;
37:
38: if (first < 0) {
39: first = 0;
40: }
41:
42: // Complain if the user asked for a start element that is greater
43: // than the list length. This won't ever trigger for the "end*"
44: // case as that will be properly constrained by getIntForIndex
45: // because we use size-1 (to allow for replacing the last elem).
46:
47: if ((first >= size) && (size > 0)) {
48: throw new TclException(interp,
49: "list doesn't contain element " + argv[2]);
50: }
51: if (last >= size) {
52: last = size - 1;
53: }
54: if (first <= last) {
55: numToDelete = (last - first + 1);
56: } else {
57: numToDelete = 0;
58: }
59:
60: TclObject list = argv[1];
61: boolean isDuplicate = false;
62:
63: // If the list object is unshared we can modify it directly. Otherwise
64: // we create a copy to modify: this is "copy on write".
65:
66: if (list.isShared()) {
67: list = list.duplicate();
68: isDuplicate = true;
69: }
70:
71: try {
72: TclList.replace(interp, list, first, numToDelete, argv, 4,
73: argv.length - 1);
74: interp.setResult(list);
75: } catch (TclException e) {
76: if (isDuplicate) {
77: list.release();
78: }
79: throw e;
80: }
81: }
82: }
|