001: /*
002: * CaseCmd.java
003: *
004: * Copyright (c) 1997 Sun Microsystems, Inc.
005: *
006: * See the file "license.terms" for information on usage and
007: * redistribution of this file, and for a DISCLAIMER OF ALL
008: * WARRANTIES.
009: *
010: * RCS: @(#) $Id: CaseCmd.java,v 1.2 1999/05/08 23:52:18 dejong Exp $
011: *
012: */
013:
014: package tcl.lang;
015:
016: /**
017: * This class implements the built-in "case" command in Tcl.
018: */
019:
020: class CaseCmd implements Command {
021: /**
022: * Executes a "case" statement. See Tcl user
023: * documentation for details.
024: *
025: * @param interp the current interpreter.
026: * @param argv command arguments.
027: * @exception TclException If incorrect number of arguments.
028: */
029:
030: public void cmdProc(Interp interp, TclObject argv[])
031: throws TclException {
032: if (argv.length < 3) {
033: throw new TclNumArgsException(interp, 1, argv,
034: "string ?in? patList body ... ?default body?");
035: }
036:
037: int i;
038: int body;
039: TclObject caseArgv[];
040: String string;
041:
042: string = argv[1].toString();
043: caseArgv = argv;
044: body = -1;
045:
046: if (argv[2].toString().equals("in")) {
047: i = 3;
048: } else {
049: i = 2;
050: }
051:
052: /*
053: * If all of the pattern/command pairs are lumped into a single
054: * argument, split them out again.
055: */
056:
057: if (argv.length - i == 1) {
058: caseArgv = TclList.getElements(interp, argv[i]);
059: i = 0;
060: }
061:
062: match_loop: {
063: for (; i < caseArgv.length; i += 2) {
064: int j;
065:
066: if (i == (caseArgv.length - 1)) {
067: throw new TclException(interp,
068: "extra case pattern with no body");
069: }
070:
071: /*
072: * Check for special case of single pattern (no list) with
073: * no backslash sequences.
074: */
075:
076: String caseString = caseArgv[i].toString();
077: int len = caseString.length();
078: for (j = 0; j < len; j++) {
079: char c = caseString.charAt(j);
080: if (Character.isWhitespace(c) || (c == '\\')) {
081: break;
082: }
083: }
084: if (j == len) {
085: if (caseString.equals("default")) {
086: body = i + 1;
087: }
088: if (Util.stringMatch(string, caseString)) {
089: body = i + 1;
090: break match_loop;
091: }
092: continue;
093: }
094:
095: /*
096: * Break up pattern lists, then check each of the patterns
097: * in the list.
098: */
099:
100: int numPats = TclList.getLength(interp, caseArgv[i]);
101: for (j = 0; j < numPats; j++) {
102: if (Util.stringMatch(string, TclList.index(interp,
103: caseArgv[i], j).toString())) {
104: body = i + 1;
105: break match_loop;
106: }
107: }
108: }
109: }
110:
111: if (body != -1) {
112: try {
113: interp.eval(caseArgv[body], 0);
114: } catch (TclException e) {
115: if (e.getCompletionCode() == TCL.ERROR) {
116: interp.addErrorInfo("\n (\""
117: + caseArgv[body - 1] + "\" arm line "
118: + interp.errorLine + ")");
119: }
120: throw e;
121: }
122: }
123: }
124: }
|