Пример #1
0
        /// <summary> This procedure is invoked to process the "eof" Tcl command.
        /// See the user documentation for details on what it does.
        /// 
        /// </summary>
        /// <param name="interp">the current interpreter.
        /// </param>
        /// <param name="argv">command arguments.
        /// </param>

        public TCL.CompletionCode CmdProc(Interp interp, TclObject[] argv)
        {

            Channel chan; /* The channel being operated on this method */

            if (argv.Length != 2)
            {
                throw new TclNumArgsException(interp, 1, argv, "channelId");
            }


            chan = TclIO.getChannel(interp, argv[1].ToString());
            if (chan == null)
            {

                throw new TclException(interp, "can not find channel named \"" + argv[1].ToString() + "\"");
            }

            if (chan.eof())
            {
                interp.SetResult(TclInteger.NewInstance(1));
            }
            else
            {
                interp.SetResult(TclInteger.NewInstance(0));
            }
            return TCL.CompletionCode.RETURN;
        }
Пример #2
0
        /// <summary> See Tcl user documentation for details.</summary>

        public TCL.CompletionCode CmdProc(Interp interp, TclObject[] argv)
        {
            if ((argv.Length < 2) || (argv.Length > 3))
            {
                throw new TclNumArgsException(interp, 1, argv, "script ?count?");
            }

            int count;
            if (argv.Length == 2)
            {
                count = 1;
            }
            else
            {
                count = TclInteger.Get(interp, argv[2]);
            }

            long startTime = System.DateTime.Now.Ticks;
            for (int i = 0; i < count; i++)
            {
                interp.Eval(argv[1], 0);
            }
            long endTime = System.DateTime.Now.Ticks;
            long uSecs = (((endTime - startTime) / 10) / count);
            if (uSecs == 1)
            {
                interp.SetResult(TclString.NewInstance("1 microsecond per iteration"));
            }
            else
            {
                interp.SetResult(TclString.NewInstance(uSecs + " microseconds per iteration"));
            }
            return TCL.CompletionCode.RETURN;
        }
Пример #3
0
        /// <summary> Creates an exception with the appropiate Tcl error message to
        /// indicate an error with variable access.
        /// 
        /// </summary>
        /// <param name="interp">currrent interpreter.
        /// </param>
        /// <param name="name1">first part of a variable name.
        /// </param>
        /// <param name="name2">second part of a variable name. May be null.
        /// </param>
        /// <param name="operation">either "read" or "set".
        /// </param>
        /// <param name="reason">a string message to explain why the operation fails..
        /// </param>

        internal TclVarException(Interp interp, string name1, string name2, string operation, string reason)
            : base(TCL.CompletionCode.ERROR)
        {
            if (interp != null)
            {
                interp.ResetResult();
                if ((System.Object)name2 == null)
                {
                    interp.SetResult("can't " + operation + " \"" + name1 + "\": " + reason);
                }
                else
                {
                    interp.SetResult("can't " + operation + " \"" + name1 + "(" + name2 + ")\": " + reason);
                }
            }
        }
Пример #4
0
        /// <summary> See Tcl user documentation for details.</summary>
        /// <exception cref=""> TclException If incorrect number of arguments.
        /// </exception>

        public TCL.CompletionCode CmdProc(Interp interp, TclObject[] argv)
        {
            if (argv.Length != 2)
            {
                throw new TclNumArgsException(interp, 1, argv, "list");
            }
            interp.SetResult(TclInteger.NewInstance(TclList.getLength(interp, argv[1])));
            return TCL.CompletionCode.RETURN;
        }
Пример #5
0
        public TCL.CompletionCode CmdProc(Interp interp, TclObject[] argv)
        {
            bool debug;

            if (argv.Length == 2)
            {
                System.Diagnostics.Debug.WriteLine("getting value of \"" + argv[1].ToString() + "\"");

                interp.SetResult(interp.GetVar(argv[1], 0));
            }
            else if (argv.Length == 3)
            {
                System.Diagnostics.Debug.WriteLine("setting value of \"" + argv[1].ToString() + "\" to \"" + argv[2].ToString() + "\"");
                interp.SetResult(interp.SetVar(argv[1], argv[2], 0));
            }
            else
            {
                throw new TclNumArgsException(interp, 1, argv, "varName ?newValue?");
            }
            return TCL.CompletionCode.RETURN;
        }
Пример #6
0
        /// <summary> This procedure is invoked to process the "incr" Tcl command.
        /// See the user documentation for details on what it does.
        /// </summary>
        /// <exception cref=""> TclException if wrong # of args or increment is not an
        /// integer.
        /// </exception>

        public TCL.CompletionCode CmdProc(Interp interp, TclObject[] objv)
        {
            int incrAmount;
            TclObject newValue;

            if ((objv.Length != 2) && (objv.Length != 3))
            {
                throw new TclNumArgsException(interp, 1, objv, "varName ?increment?");
            }

            // Calculate the amount to increment by.

            if (objv.Length == 2)
            {
                incrAmount = 1;
            }
            else
            {
                try
                {
                    incrAmount = TclInteger.Get(interp, objv[2]);
                }
                catch (TclException e)
                {
                    interp.AddErrorInfo("\n    (reading increment)");
                    throw;
                }
            }

            // Increment the variable's value.

            newValue = Var.incrVar(interp, objv[1], null, incrAmount, TCL.VarFlag.LEAVE_ERR_MSG);

            // FIXME: we need to look at this exception throwing problem again
            /*
            if (newValue == null) {
            return TCL_ERROR;
            }
            */

            // Set the interpreter's object result to refer to the variable's new
            // value object.

            interp.SetResult(newValue);
            return TCL.CompletionCode.RETURN;
        }
Пример #7
0
        /// <summary> See Tcl user documentation for details.</summary>
        public TCL.CompletionCode CmdProc(Interp interp, TclObject[] argv)
        {
            TclObject list = TclList.NewInstance();

            list.Preserve();
            try
            {
                for (int i = 1; i < argv.Length; i++)
                    TclList.Append(interp, list, argv[i]);
                interp.SetResult(list);
            }
            finally
            {
                list.Release();
            }
            return TCL.CompletionCode.RETURN;
        }
Пример #8
0
        /// <summary> See Tcl user documentation for details.</summary>
        public TCL.CompletionCode CmdProc(Interp interp, TclObject[] argv)
        {
            string sep = null;

            if (argv.Length == 2)
            {
                sep = null;
            }
            else if (argv.Length == 3)
            {

                sep = argv[2].ToString();
            }
            else
            {
                throw new TclNumArgsException(interp, 1, argv, "list ?joinString?");
            }
            TclObject list = argv[1];
            int size = TclList.getLength(interp, list);

            if (size == 0)
            {
                interp.ResetResult();
                return TCL.CompletionCode.RETURN;
            }


            StringBuilder sbuf = new StringBuilder(TclList.index(interp, list, 0).ToString());

            for (int i = 1; i < size; i++)
            {
                if ((System.Object)sep == null)
                {
                    sbuf.Append(' ');
                }
                else
                {
                    sbuf.Append(sep);
                }

                sbuf.Append(TclList.index(interp, list, i).ToString());
            }
            interp.SetResult(sbuf.ToString());
            return TCL.CompletionCode.RETURN;
        }
Пример #9
0
        public TCL.CompletionCode CmdProc(Interp interp, TclObject[] argv)
        {
            if (argv.Length != 1)
            {
                throw new TclNumArgsException(interp, 1, argv, null);
            }

            // Get the name of the working dir.

            string dirName = interp.getWorkingDir().ToString();

            // Java File Object methods use backslashes on Windows.
            // Convert them to forward slashes before returning the dirName to Tcl.

            if (JACL.PLATFORM == JACL.PLATFORM_WINDOWS)
            {
                dirName = dirName.Replace('\\', '/');
            }

            interp.SetResult(dirName);
            return TCL.CompletionCode.RETURN;
        }
Пример #10
0
        /// <summary> This procedure is invoked to process the "fconfigure" Tcl command.
        /// See the user documentation for details on what it does.
        /// 
        /// </summary>
        /// <param name="interp">the current interpreter.
        /// </param>
        /// <param name="argv">command arguments.
        /// </param>

        public TCL.CompletionCode CmdProc(Interp interp, TclObject[] argv)
        {

            Channel chan; // The channel being operated on this method

            if ((argv.Length < 2) || (((argv.Length % 2) == 1) && (argv.Length != 3)))
            {
                throw new TclNumArgsException(interp, 1, argv, "channelId ?optionName? ?value? ?optionName value?...");
            }


            chan = TclIO.getChannel(interp, argv[1].ToString());
            if (chan == null)
            {

                throw new TclException(interp, "can not find channel named \"" + argv[1].ToString() + "\"");
            }

            if (argv.Length == 2)
            {
                // return list of all name/value pairs for this channelId
                TclObject list = TclList.NewInstance();

                TclList.Append(interp, list, TclString.NewInstance("-blocking"));
                TclList.Append(interp, list, TclBoolean.newInstance(chan.Blocking));

                TclList.Append(interp, list, TclString.NewInstance("-buffering"));
                TclList.Append(interp, list, TclString.NewInstance(TclIO.getBufferingString(chan.Buffering)));

                TclList.Append(interp, list, TclString.NewInstance("-buffersize"));
                TclList.Append(interp, list, TclInteger.NewInstance(chan.BufferSize));

                // -encoding

                TclList.Append(interp, list, TclString.NewInstance("-encoding"));

                System.Text.Encoding javaEncoding = chan.Encoding;
                string tclEncoding;
                if ((System.Object)javaEncoding == null)
                {
                    tclEncoding = "binary";
                }
                else
                {
                    tclEncoding = EncodingCmd.getTclName(javaEncoding);
                }
                TclList.Append(interp, list, TclString.NewInstance(tclEncoding));

                // -eofchar

                TclList.Append(interp, list, TclString.NewInstance("-eofchar"));
                if (chan.ReadOnly)
                {
                    char eofChar = chan.InputEofChar;
                    TclList.Append(interp, list, (eofChar == 0) ? TclString.NewInstance("") : TclString.NewInstance(eofChar));
                }
                else if (chan.WriteOnly)
                {
                    char eofChar = chan.OutputEofChar;
                    TclList.Append(interp, list, (eofChar == 0) ? TclString.NewInstance("") : TclString.NewInstance(eofChar));
                }
                else if (chan.ReadWrite)
                {
                    char inEofChar = chan.InputEofChar;
                    char outEofChar = chan.OutputEofChar;

                    TclObject eofchar_pair = TclList.NewInstance();

                    TclList.Append(interp, eofchar_pair, (inEofChar == 0) ? TclString.NewInstance("") : TclString.NewInstance(inEofChar));

                    TclList.Append(interp, eofchar_pair, (outEofChar == 0) ? TclString.NewInstance("") : TclString.NewInstance(outEofChar));

                    TclList.Append(interp, list, eofchar_pair);
                }
                else
                {
                    // Not readable or writeable, do nothing
                }

                // -translation

                TclList.Append(interp, list, TclString.NewInstance("-translation"));

                if (chan.ReadOnly)
                {
                    TclList.Append(interp, list, TclString.NewInstance(TclIO.getTranslationString(chan.InputTranslation)));
                }
                else if (chan.WriteOnly)
                {
                    TclList.Append(interp, list, TclString.NewInstance(TclIO.getTranslationString(chan.OutputTranslation)));
                }
                else if (chan.ReadWrite)
                {
                    TclObject translation_pair = TclList.NewInstance();

                    TclList.Append(interp, translation_pair, TclString.NewInstance(TclIO.getTranslationString(chan.InputTranslation)));
                    TclList.Append(interp, translation_pair, TclString.NewInstance(TclIO.getTranslationString(chan.OutputTranslation)));

                    TclList.Append(interp, list, translation_pair);
                }
                else
                {
                    // Not readable or writeable, do nothing
                }

                interp.SetResult(list);
            }

            if (argv.Length == 3)
            {
                // return value for supplied name

                int index = TclIndex.Get(interp, argv[2], validCmds, "option", 0);

                switch (index)
                {

                    case OPT_BLOCKING:
                        {
                            // -blocking
                            interp.SetResult(chan.Blocking);
                            break;
                        }

                    case OPT_BUFFERING:
                        {
                            // -buffering
                            interp.SetResult(TclIO.getBufferingString(chan.Buffering));
                            break;
                        }

                    case OPT_BUFFERSIZE:
                        {
                            // -buffersize
                            interp.SetResult(chan.BufferSize);
                            break;
                        }

                    case OPT_ENCODING:
                        {
                            // -encoding
                            System.Text.Encoding javaEncoding = chan.Encoding;
                            if ((System.Object)javaEncoding == null)
                            {
                                interp.SetResult("binary");
                            }
                            else
                            {
                                interp.SetResult(EncodingCmd.getTclName(javaEncoding));
                            }
                            break;
                        }

                    case OPT_EOFCHAR:
                        {
                            // -eofchar
                            if (chan.ReadOnly)
                            {
                                char eofChar = chan.InputEofChar;
                                interp.SetResult((eofChar == 0) ? TclString.NewInstance("") : TclString.NewInstance(eofChar));
                            }
                            else if (chan.WriteOnly)
                            {
                                char eofChar = chan.OutputEofChar;
                                interp.SetResult((eofChar == 0) ? TclString.NewInstance("") : TclString.NewInstance(eofChar));
                            }
                            else if (chan.ReadWrite)
                            {
                                char inEofChar = chan.InputEofChar;
                                char outEofChar = chan.OutputEofChar;

                                TclObject eofchar_pair = TclList.NewInstance();

                                TclList.Append(interp, eofchar_pair, (inEofChar == 0) ? TclString.NewInstance("") : TclString.NewInstance(inEofChar));

                                TclList.Append(interp, eofchar_pair, (outEofChar == 0) ? TclString.NewInstance("") : TclString.NewInstance(outEofChar));

                                interp.SetResult(eofchar_pair);
                            }
                            else
                            {
                                // Not readable or writeable, do nothing
                            }

                            break;
                        }

                    case OPT_TRANSLATION:
                        {
                            // -translation
                            if (chan.ReadOnly)
                            {
                                interp.SetResult(TclIO.getTranslationString(chan.InputTranslation));
                            }
                            else if (chan.WriteOnly)
                            {
                                interp.SetResult(TclIO.getTranslationString(chan.OutputTranslation));
                            }
                            else if (chan.ReadWrite)
                            {
                                TclObject translation_pair = TclList.NewInstance();

                                TclList.Append(interp, translation_pair, TclString.NewInstance(TclIO.getTranslationString(chan.InputTranslation)));
                                TclList.Append(interp, translation_pair, TclString.NewInstance(TclIO.getTranslationString(chan.OutputTranslation)));

                                interp.SetResult(translation_pair);
                            }
                            else
                            {
                                // Not readable or writeable, do nothing
                            }

                            break;
                        }

                    default:
                        {
                            throw new TclRuntimeError("Fconfigure.cmdProc() error: " + "incorrect index returned from TclIndex.get()");
                        }

                }
            }
            for (int i = 3; i < argv.Length; i += 2)
            {
                // Iterate through the list setting the name with the 
                // corresponding value.

                int index = TclIndex.Get(interp, argv[i - 1], validCmds, "option", 0);

                switch (index)
                {

                    case OPT_BLOCKING:
                        {
                            // -blocking
                            chan.Blocking = TclBoolean.get(interp, argv[i]);
                            break;
                        }

                    case OPT_BUFFERING:
                        {
                            // -buffering

                            int id = TclIO.getBufferingID(argv[i].ToString());

                            if (id == -1)
                            {
                                throw new TclException(interp, "bad value for -buffering: must be " + "one of full, line, or none");
                            }

                            chan.Buffering = id;
                            break;
                        }

                    case OPT_BUFFERSIZE:
                        {
                            // -buffersize
                            chan.BufferSize = TclInteger.Get(interp, argv[i]);
                            break;
                        }

                    case OPT_ENCODING:
                        {
                            // -encoding

                            string tclEncoding = argv[i].ToString();

                            if (tclEncoding.Equals("") || tclEncoding.Equals("binary"))
                            {
                                chan.Encoding = null;
                            }
                            else
                            {
                                System.Text.Encoding javaEncoding = EncodingCmd.getJavaName(tclEncoding);
                                if ((System.Object)javaEncoding == null)
                                {
                                    throw new TclException(interp, "unknown encoding \"" + tclEncoding + "\"");
                                }
                                chan.Encoding = javaEncoding;
                            }

                            break;
                        }

                    case OPT_EOFCHAR:
                        {
                            // -eofchar
                            TclList.setListFromAny(interp, argv[i]);
                            int length = TclList.getLength(interp, argv[i]);

                            if (length > 2)
                            {
                                throw new TclException(interp, "bad value for -eofchar: " + "should be a list of zero, one, or two elements");
                            }

                            char inputEofChar, outputEofChar;
                            string s;

                            if (length == 0)
                            {
                                inputEofChar = outputEofChar = (char)(0);
                            }
                            else if (length == 1)
                            {

                                s = TclList.index(interp, argv[i], 0).ToString();
                                inputEofChar = outputEofChar = s[0];
                            }
                            else
                            {

                                s = TclList.index(interp, argv[i], 0).ToString();
                                inputEofChar = s[0];


                                s = TclList.index(interp, argv[i], 1).ToString();
                                outputEofChar = s[0];
                            }

                            chan.InputEofChar = inputEofChar;
                            chan.OutputEofChar = outputEofChar;

                            break;
                        }

                    case OPT_TRANSLATION:
                        {
                            // -translation
                            TclList.setListFromAny(interp, argv[i]);
                            int length = TclList.getLength(interp, argv[i]);

                            if (length < 1 || length > 2)
                            {
                                throw new TclException(interp, "bad value for -translation: " + "must be a one or two element list");
                            }

                            string inputTranslationArg, outputTranslationArg;
                            int inputTranslation, outputTranslation;

                            if (length == 2)
                            {

                                inputTranslationArg = TclList.index(interp, argv[i], 0).ToString();
                                inputTranslation = TclIO.getTranslationID(inputTranslationArg);

                                outputTranslationArg = TclList.index(interp, argv[i], 1).ToString();
                                outputTranslation = TclIO.getTranslationID(outputTranslationArg);
                            }
                            else
                            {

                                outputTranslationArg = inputTranslationArg = argv[i].ToString();
                                outputTranslation = inputTranslation = TclIO.getTranslationID(outputTranslationArg);
                            }

                            if ((inputTranslation == -1) || (outputTranslation == -1))
                            {
                                throw new TclException(interp, "bad value for -translation: " + "must be one of auto, binary, cr, lf, " + "crlf, or platform");
                            }

                            if (outputTranslation == TclIO.TRANS_AUTO)
                                outputTranslation = TclIO.TRANS_PLATFORM;

                            if (chan.ReadOnly)
                            {
                                chan.InputTranslation = inputTranslation;
                                if (inputTranslationArg.Equals("binary"))
                                {
                                    chan.Encoding = null;
                                }
                            }
                            else if (chan.WriteOnly)
                            {
                                chan.OutputTranslation = outputTranslation;
                                if (outputTranslationArg.Equals("binary"))
                                {
                                    chan.Encoding = null;
                                }
                            }
                            else if (chan.ReadWrite)
                            {
                                chan.InputTranslation = inputTranslation;
                                chan.OutputTranslation = outputTranslation;
                                if (inputTranslationArg.Equals("binary") || outputTranslationArg.Equals("binary"))
                                {
                                    chan.Encoding = null;
                                }
                            }
                            else
                            {
                                // Not readable or writeable, do nothing
                            }

                            break;
                        }

                    default:
                        {
                            throw new TclRuntimeError("Fconfigure.cmdProc() error: " + "incorrect index returned from TclIndex.get()");
                        }

                }
            }
            return TCL.CompletionCode.RETURN;
        }
Пример #11
0
        /// <summary> This procedure is invoked to process the "scan" Tcl command.
        /// See the user documentation for details on what it does.
        /// 
        /// Each iteration of the cmdProc compares the scanArr's current index to 
        /// the frmtArr's index.  If the chars are equal then the indicies are
        /// incremented.  If a '%' is found in the frmtArr, the formatSpecifier 
        /// is parced from the frmtArr, the corresponding value is extracted from 
        /// the scanArr, and that value is set in the Tcl Interp.
        /// 
        /// If the chars are not equal, or the conversion fails, the boolean 
        /// scanArrDone is set to true, indicating the scanArr is not to be 
        /// parced and no new values are to be set.  However the frmtArr is still 
        /// parced because of the priority of error messages.  In the C version 
        /// of Tcl, bad format specifiers throw errors before incorrect argument 
        /// input or other scan errors.  Thus we need to parce the entire frmtArr 
        /// to verify correct formating.  This is dumb and inefficient but it is 
        /// consistent w/ the current C-version of Tcl.
        /// </summary>

        public TCL.CompletionCode CmdProc(Interp interp, TclObject[] argv)
        {

            if (argv.Length < 3)
            {
                throw new TclNumArgsException(interp, 1, argv, "string format ?varName varName ...?");
            }
            ;

            StrtoulResult strul; // Return value for parcing the scanArr when
            // extracting integers/longs
            StrtodResult strd;
            ; // Return value for parcing the scanArr when
            // extracting doubles
            char[] scanArr; // Array containing parce info
            char[] frmtArr; // Array containing info on how to 
            // parse the scanArr
            int scanIndex; // Index into the scan array
            int frmtIndex; // Index into the frmt array
            int tempIndex; // Temporary index holder
            int argIndex; // Index into the current arg
            int width; // Stores the user specified result width 
            int base_; // Base of the integer being converted
            int numUnMatched; // Number of fields actually set.
            int numMatched; // Number of fields actually matched.
            int negateScan; // Mult by result, set to -1 if true
            int i; // Generic variable
            char ch; // Generic variable
            bool cont; // Used in loops to indicate when to stop
            bool scanOK; // Set to false if strtoul/strtod fails
            bool scanArrDone; // Set to false if strtoul/strtod fails
            bool widthFlag; // True is width is specified
            bool discardFlag; // If a "%*" is in the formatString dont 
            // write output to arg


            scanArr = argv[1].ToString().ToCharArray();

            frmtArr = argv[2].ToString().ToCharArray();
            width = base_ = numMatched = numUnMatched = 0;
            scanIndex = frmtIndex = 0;
            scanOK = true;
            scanArrDone = false;
            argIndex = 3;

            // Skip all (if any) of the white space before getting to a char

            frmtIndex = skipWhiteSpace(frmtArr, frmtIndex);

            // Search through the frmtArr.  If the next char is a '%' parse the
            // next chars and determine the type (if any) of the format specifier.
            // If the scanArr has been fully searched, do nothing but incerment
            // "numUnMatched".  The reason to continue the frmtArr search is for 
            // consistency in output.  Previously scan format errors were reported
            // before arg input mismatch, so this maintains the same level of error
            // checking.

            while (frmtIndex < frmtArr.Length)
            {
                discardFlag = widthFlag = false;
                negateScan = 1;
                cont = true;

                // Parce the format array and read in the correct value from the 
                // scan array.  When the correct value is retrieved, set the 
                // variable (from argv) in the interp.

                if (frmtArr[frmtIndex] == '%')
                {

                    frmtIndex++;
                    checkOverFlow(interp, frmtArr, frmtIndex);

                    // Two '%'s in a row, do nothing...

                    if (frmtArr[frmtIndex] == '%')
                    {
                        frmtIndex++;
                        scanIndex++;
                        continue;
                    }

                    // Check for a discard field flag

                    if (frmtArr[frmtIndex] == '*')
                    {
                        discardFlag = true;
                        frmtIndex++;
                        checkOverFlow(interp, frmtArr, frmtIndex);
                    }

                    // Check for a width field and accept the 'h', 'l', 'L'
                    // characters, but do nothing with them.
                    //
                    // Note: The order of the width specifier and the other
                    // chars is unordered, so we need to iterate until all
                    // of the specifiers are identified.

                    while (cont)
                    {
                        cont = false;

                        switch (frmtArr[frmtIndex])
                        {

                            case 'h':
                            case 'l':
                            case 'L':
                                {
                                    // Just ignore these values

                                    frmtIndex++;
                                    cont = true;
                                    break;
                                }

                            default:
                                {
                                    if (System.Char.IsDigit(frmtArr[frmtIndex]))
                                    {
                                        strul = Util.Strtoul(new string(frmtArr), frmtIndex, base_);
                                        frmtIndex = strul.Index;
                                        width = (int)strul.value;
                                        widthFlag = true;
                                        cont = true;
                                    }
                                }
                                break;

                        }
                        checkOverFlow(interp, frmtArr, frmtIndex);
                    }

                    // On all conversion specifiers except 'c', move the
                    // scanIndex to the next non-whitespace.

                    ch = frmtArr[frmtIndex];
                    if ((ch != 'c') && (ch != '[') && !scanArrDone)
                    {
                        scanIndex = skipWhiteSpace(scanArr, scanIndex);
                    }
                    if (scanIndex >= scanArr.Length)
                    {
                        scanArrDone = true;
                    }

                    if ((scanIndex < scanArr.Length) && (ch != 'c') && (ch != '['))
                    {
                        // Since strtoul dosent take signed numbers, make the
                        // value positive and store the sign.

                        if (scanArr[scanIndex] == '-')
                        {
                            negateScan = -1;
                            scanIndex++;
                            width--;
                        }
                        else if (scanArr[scanIndex] == '+')
                        {
                            scanIndex++;
                            width--;
                        }

                        // The width+scanIndex might be greater than
                        // the scanArr so we need to re-adjust when this
                        // happens.

                        if (widthFlag && (width + scanIndex > scanArr.Length))
                        {
                            width = scanArr.Length - scanIndex;
                        }
                    }

                    if (scanIndex >= scanArr.Length)
                    {
                        scanArrDone = true;
                    }

                    // Foreach iteration we want strul and strd to be
                    // null since we error check on this case.

                    strul = null;
                    strd = null;

                    switch (ch)
                    {

                        case 'd':
                        case 'o':
                        case 'x':
                            {

                                if (!scanArrDone)
                                {

                                    if (ch == 'd')
                                    {
                                        base_ = 10;
                                    }
                                    else if (ch == 'o')
                                    {
                                        base_ = 8;
                                    }
                                    else
                                    {
                                        base_ = 16;
                                    }

                                    // If the widthFlag is set then convert only 
                                    // "width" characters to an ascii representation, 
                                    // else read in until the end of the integer.  The 
                                    // scanIndex is moved to the point where we stop
                                    // reading in.

                                    if (widthFlag)
                                    {
                                        strul = Util.Strtoul(new string(scanArr, 0, width + scanIndex), scanIndex, base_);
                                    }
                                    else
                                    {
                                        strul = Util.Strtoul(new string(scanArr), scanIndex, base_);
                                    }
                                    if (strul.errno != 0)
                                    {
                                        scanOK = false;
                                        break;
                                    }
                                    scanIndex = strul.Index;

                                    if (!discardFlag)
                                    {
                                        i = (int)strul.value * negateScan;
                                        if (argIndex == argv.Length)
                                            numMatched--;
                                        else
                                            testAndSetVar(interp, argv, argIndex++, TclInteger.NewInstance(i));
                                    }
                                }
                                break;
                            }

                        case 'c':
                            {
                                if (widthFlag)
                                {
                                    errorCharFieldWidth(interp);
                                }
                                if (!discardFlag && !scanArrDone)
                                {
                                    testAndSetVar(interp, argv, argIndex++, TclInteger.NewInstance(scanArr[scanIndex++]));
                                }
                                break;
                            }

                        case 's':
                            {
                                if (!scanArrDone)
                                {
                                    // If the widthFlag is set then read only "width"
                                    // characters into the string, else read in until 
                                    // the first whitespace or endArr is found.  The 
                                    // scanIndex is moved to the point where we stop 
                                    // reading in.

                                    tempIndex = scanIndex;
                                    if (!widthFlag)
                                    {
                                        width = scanArr.Length;
                                    }
                                    for (i = 0; (scanIndex < scanArr.Length) && (i < width); i++)
                                    {
                                        ch = scanArr[scanIndex];
                                        if ((ch == ' ') || (ch == '\n') || (ch == '\r') || (ch == '\t') || (ch == '\f'))
                                        {
                                            break;
                                        }
                                        scanIndex++;
                                    }

                                    if (!discardFlag)
                                    {
                                        string str = new string(scanArr, tempIndex, scanIndex - tempIndex);
                                        testAndSetVar(interp, argv, argIndex++, TclString.NewInstance(str));
                                    }
                                }
                                break;
                            }

                        case 'e':
                        case 'f':
                        case 'g':
                            {
                                if (!scanArrDone)
                                {
                                    // If the wisthFlag is set then read only "width"
                                    // characters into the string, else read in until 
                                    // the first whitespace or endArr is found.  The 
                                    // scanIndex is moved to the point where we stop 
                                    // reading in.

                                    if (widthFlag)
                                    {
                                        strd = Util.Strtod(new string(scanArr, 0, width + scanIndex), scanIndex);
                                    }
                                    else
                                    {
                                        strd = Util.Strtod(new string(scanArr), scanIndex);
                                    }
                                    if (strd.errno != 0)
                                    {
                                        scanOK = false;
                                        break;
                                    }
                                    scanIndex = strd.index;

                                    if (!discardFlag)
                                    {
                                        double d = strd.value * negateScan;
                                        testAndSetVar(interp, argv, argIndex++, TclDouble.NewInstance(d));
                                    }
                                }
                                break;
                            }

                        case '[':
                            {
                                bool charMatchFound = false;
                                bool charNotMatch = false;
                                char[] tempArr;
                                int startIndex;
                                int endIndex;
                                string unmatched = "unmatched [ in format string";

                                if ((++frmtIndex) >= frmtArr.Length)
                                {
                                    throw new TclException(interp, unmatched);
                                }

                                if (frmtArr[frmtIndex] == '^')
                                {
                                    charNotMatch = true;
                                    frmtIndex += 2;
                                }
                                else
                                {
                                    frmtIndex++;
                                }
                                tempIndex = frmtIndex - 1;

                                if (frmtIndex >= frmtArr.Length)
                                {
                                    throw new TclException(interp, unmatched);
                                }

                                // Extract the list of chars for matching.

                                while (frmtArr[frmtIndex] != ']')
                                {
                                    if ((++frmtIndex) >= frmtArr.Length)
                                    {
                                        throw new TclException(interp, unmatched);
                                    }
                                }
                                tempArr = new string(frmtArr, tempIndex, frmtIndex - tempIndex).ToCharArray();

                                startIndex = scanIndex;
                                if (charNotMatch)
                                {
                                    // Format specifier contained a '^' so interate
                                    // until one of the chars in tempArr is found.

                                    while (scanOK && !charMatchFound)
                                    {
                                        if (scanIndex >= scanArr.Length)
                                        {
                                            scanOK = false;
                                            break;
                                        }
                                        for (i = 0; i < tempArr.Length; i++)
                                        {
                                            if (tempArr[i] == scanArr[scanIndex])
                                            {
                                                charMatchFound = true;
                                                break;
                                            }
                                        }
                                        if (widthFlag && ((scanIndex - startIndex) >= width))
                                        {
                                            break;
                                        }
                                        if (!charMatchFound)
                                        {
                                            scanIndex++;
                                        }
                                    }
                                }
                                else
                                {
                                    // Iterate until the char in the scanArr is not 
                                    // in the tempArr.

                                    charMatchFound = true;
                                    while (scanOK && charMatchFound)
                                    {
                                        if (scanIndex >= scanArr.Length)
                                        {
                                            scanOK = false;
                                            break;
                                        }
                                        charMatchFound = false;
                                        for (i = 0; i < tempArr.Length; i++)
                                        {
                                            if (tempArr[i] == scanArr[scanIndex])
                                            {
                                                charMatchFound = true;
                                                break;
                                            }
                                        }
                                        if (widthFlag && (scanIndex - startIndex) >= width)
                                        {
                                            break;
                                        }
                                        if (charMatchFound)
                                        {
                                            scanIndex++;
                                        }
                                    }
                                }

                                // Indicates nothing was found.

                                endIndex = scanIndex - startIndex;
                                if (endIndex <= 0)
                                {
                                    scanOK = false;
                                    break;
                                }

                                if (!discardFlag)
                                {
                                    string str = new string(scanArr, startIndex, endIndex);
                                    testAndSetVar(interp, argv, argIndex++, TclString.NewInstance(str));
                                }
                                break;
                            }

                        default:
                            {
                                errorBadField(interp, ch);
                            }
                            break;

                    }

                    // As long as the scan was successful (scanOK), the format
                    // specifier did not contain a '*' (discardFlag), and
                    // we are not at the end of the scanArr (scanArrDone);
                    // increment the num of vars set in the interp.  Otherwise
                    // increment the number of valid format specifiers.

                    if (scanOK && !discardFlag && !scanArrDone)
                    {
                        numMatched++;
                    }
                    else if ((scanArrDone || !scanOK) && !discardFlag)
                    {
                        numUnMatched++;
                    }
                    frmtIndex++;
                }
                else if (scanIndex < scanArr.Length && scanArr[scanIndex] == frmtArr[frmtIndex])
                {
                    // No '%' was found, but the characters matched

                    scanIndex++;
                    frmtIndex++;
                }
                else
                {
                    // No '%' found and the characters int frmtArr & scanArr
                    // did not match.

                    frmtIndex++;
                }
            }

            // The numMatched is the return value: a count of the num of vars set.
            // While the numUnMatched is the number of formatSpecifiers that
            // passed the parsing stage, but did not match anything in the scanArr.

            if ((numMatched + numUnMatched) != (argv.Length - 3))
            {
                errorDiffVars(interp);
            }
            interp.SetResult(TclInteger.NewInstance(numMatched));
            return TCL.CompletionCode.RETURN;
        }
Пример #12
0
        /// <summary> This procedure is invoked to process the "subst" Tcl command.
        /// See the user documentation for details on what it does.
        /// 
        /// </summary>
        /// <param name="interp">the current interpreter.
        /// </param>
        /// <param name="argv">command arguments.
        /// </param>
        /// <exception cref=""> TclException if wrong # of args or invalid argument(s).
        /// </exception>

        public TCL.CompletionCode CmdProc(Interp interp, TclObject[] argv)
        {
            int currentObjIndex, len, i;
            int objc = argv.Length - 1;
            bool doBackslashes = true;
            bool doCmds = true;
            bool doVars = true;
            StringBuilder result = new StringBuilder();
            string s;
            char c;

            for (currentObjIndex = 1; currentObjIndex < objc; currentObjIndex++)
            {

                if (!argv[currentObjIndex].ToString().StartsWith("-"))
                {
                    break;
                }
                int opt = TclIndex.Get(interp, argv[currentObjIndex], validCmds, "switch", 0);
                switch (opt)
                {

                    case OPT_NOBACKSLASHES:
                        doBackslashes = false;
                        break;

                    case OPT_NOCOMMANDS:
                        doCmds = false;
                        break;

                    case OPT_NOVARS:
                        doVars = false;
                        break;

                    default:
                        throw new TclException(interp, "SubstCmd.cmdProc: bad option " + opt + " index to cmds");

                }
            }
            if (currentObjIndex != objc)
            {
                throw new TclNumArgsException(interp, currentObjIndex, argv, "?-nobackslashes? ?-nocommands? ?-novariables? string");
            }

            /*
            * Scan through the string one character at a time, performing
            * command, variable, and backslash substitutions.
            */


            s = argv[currentObjIndex].ToString();
            len = s.Length;
            i = 0;
            while (i < len)
            {
                c = s[i];

                if ((c == '[') && doCmds)
                {
                    ParseResult res;
                    try
                    {
                        interp._evalFlags = Parser.TCL_BRACKET_TERM;
                        interp.Eval(s.Substring(i + 1, (len) - (i + 1)));
                        TclObject interp_result = interp.GetResult();
                        interp_result.Preserve();
                        res = new ParseResult(interp_result, i + interp._termOffset);
                    }
                    catch (TclException e)
                    {
                        i = e.errIndex + 1;
                        throw;
                    }
                    i = res.nextIndex + 2;

                    result.Append(res.Value.ToString());
                    res.Release();
                }
                else if (c == '\r')
                {
                    /*
                    * (ToDo) may not be portable on Mac
                    */

                    i++;
                }
                else if ((c == '$') && doVars)
                {
                    ParseResult vres = Parser.parseVar(interp, s.Substring(i, (len) - (i)));
                    i += vres.nextIndex;

                    result.Append(vres.Value.ToString());
                    vres.Release();
                }
                else if ((c == '\\') && doBackslashes)
                {
                    BackSlashResult bs = Tcl.Lang.Interp.backslash(s, i, len);
                    i = bs.NextIndex;
                    if (bs.IsWordSep)
                    {
                        break;
                    }
                    else
                    {
                        result.Append(bs.C);
                    }
                }
                else
                {
                    result.Append(c);
                    i++;
                }
            }

            interp.SetResult(result.ToString());
            return TCL.CompletionCode.RETURN;
        }
Пример #13
0
        /// <summary> This procedure is invoked to process the "encoding" Tcl command.
        /// See the user documentation for details on what it does.
        /// 
        /// </summary>
        /// <param name="interp">the current interpreter.
        /// </param>
        /// <param name="argv">command arguments.
        /// </param>

        public TCL.CompletionCode CmdProc(Interp interp, TclObject[] argv)
        {
            if (argv.Length < 2)
            {
                throw new TclNumArgsException(interp, 1, argv, "option ?arg ...?");
            }

            int index = TclIndex.Get(interp, argv[1], validCmds, "option", 0);

            switch (index)
            {

                case OPT_CONVERTTO:
                case OPT_CONVERTFROM:
                    {
                        string tclEncoding;
                        Encoding javaEncoding;
                        TclObject data;

                        if (argv.Length == 3)
                        {
                            tclEncoding = systemTclEncoding;
                            data = argv[2];
                        }
                        else if (argv.Length == 4)
                        {

                            tclEncoding = argv[2].ToString();
                            data = argv[3];
                        }
                        else
                        {
                            throw new TclNumArgsException(interp, 2, argv, "?encoding? data");
                        }

                        javaEncoding = getJavaName(tclEncoding);

                        if ((System.Object)javaEncoding == null)
                        {
                            throw new TclException(interp, "unknown encoding \"" + tclEncoding + "\"");
                        }

                        try
                        {
                            if (index == OPT_CONVERTFROM)
                            {
                                // Treat the string as binary data
                                byte[] bytes = TclByteArray.getBytes(interp, data);

                                // ATK
                                interp.SetResult(System.Text.Encoding.UTF8.GetString(bytes, 0, bytes.Length));
                            }
                            else
                            {
                                // Store the result as binary data


                                // ATK byte[] bytes = data.ToString().getBytes(javaEncoding);
                                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data.ToString());
                                interp.SetResult(TclByteArray.NewInstance(bytes));
                            }
                        }
                        catch (IOException ex)
                        {
                            throw new TclRuntimeError("Encoding.cmdProc() error: " + "unsupported java encoding \"" + javaEncoding + "\"");
                        }

                        break;
                    }

                case OPT_NAMES:
                    {
                        if (argv.Length > 2)
                        {
                            throw new TclNumArgsException(interp, 2, argv, null);
                        }

                        TclObject list = TclList.NewInstance();
                        for (int i = 0; i < tclNames.Length; i++)
                        {
                            TclList.Append(interp, list, TclString.NewInstance(tclNames[i]));
                        }
                        interp.SetResult(list);
                        break;
                    }

                case OPT_SYSTEM:
                    {
                        if (argv.Length > 3)
                            throw new TclNumArgsException(interp, 2, argv, "?encoding?");

                        if (argv.Length == 2)
                        {
                            interp.SetResult(systemTclEncoding);
                        }
                        else
                        {

                            string tclEncoding = argv[2].ToString();
                            Encoding javaEncoding = getJavaName(tclEncoding);

                            if (javaEncoding == null)
                            {
                                throw new TclException(interp, "unknown encoding \"" + tclEncoding + "\"");
                            }

                            systemTclEncoding = tclEncoding;
                            systemJavaEncoding = javaEncoding;
                        }

                        break;
                    }

                default:
                    {
                        throw new TclRuntimeError("Encoding.cmdProc() error: " + "incorrect index returned from TclIndex.get()");
                    }

            }
            return TCL.CompletionCode.RETURN;
        }
Пример #14
0
        /// <summary> 
        /// Tcl_LappendObjCmd -> LappendCmd.cmdProc
        /// 
        /// This procedure is invoked to process the "lappend" Tcl command.
        /// See the user documentation for details on what it does.
        /// </summary>

        public TCL.CompletionCode CmdProc(Interp interp, TclObject[] objv)
        {
            TclObject varValue, newValue = null;
            int i;//int numElems, i, j;
            bool createdNewObj, createVar;

            if (objv.Length < 2)
            {
                throw new TclNumArgsException(interp, 1, objv, "varName ?value value ...?");
            }
            if (objv.Length == 2)
            {
                try
                {
                    newValue = interp.GetVar(objv[1], 0);
                }
                catch (TclException e)
                {
                    // The variable doesn't exist yet. Just create it with an empty
                    // initial value.
                    varValue = TclList.NewInstance();

                    try
                    {
                        newValue = interp.SetVar(objv[1], varValue, 0);
                    }
                    finally
                    {
                        if (newValue == null)
                            varValue.Release(); // free unneeded object
                    }

                    interp.ResetResult();
                    return TCL.CompletionCode.RETURN;
                }
            }
            else
            {
                // We have arguments to append. We used to call Tcl_SetVar2 to
                // append each argument one at a time to ensure that traces were run
                // for each append step. We now append the arguments all at once
                // because it's faster. Note that a read trace and a write trace for
                // the variable will now each only be called once. Also, if the
                // variable's old value is unshared we modify it directly, otherwise
                // we create a new copy to modify: this is "copy on write".

                createdNewObj = false;
                createVar = true;

                try
                {
                    varValue = interp.GetVar(objv[1], 0);
                }
                catch (TclException e)
                {
                    // We couldn't read the old value: either the var doesn't yet
                    // exist or it's an array element. If it's new, we will try to
                    // create it with Tcl_ObjSetVar2 below.

                    // FIXME : not sure we even need this parse for anything!
                    // If we do not need to parse could we at least speed it up a bit

                    string varName;
                    int nameBytes;


                    varName = objv[1].ToString();
                    nameBytes = varName.Length; // Number of Unicode chars in string

                    for (i = 0; i < nameBytes; i++)
                    {
                        if (varName[i] == '(')
                        {
                            i = nameBytes - 1;
                            if (varName[i] == ')')
                            {
                                // last char is ')' => array ref
                                createVar = false;
                            }
                            break;
                        }
                    }
                    varValue = TclList.NewInstance();
                    createdNewObj = true;
                }

                // We only take this branch when the catch branch was not run
                if (createdNewObj == false && varValue.Shared)
                {
                    varValue = varValue.duplicate();
                    createdNewObj = true;
                }

                // Insert the new elements at the end of the list.

                for (i = 2; i < objv.Length; i++)
                    TclList.Append(interp, varValue, objv[i]);

                // No need to call varValue.invalidateStringRep() since it
                // is called during the TclList.append operation.

                // Now store the list object back into the variable. If there is an
                // error setting the new value, decrement its ref count if it
                // was new and we didn't create the variable.

                try
                {

                    newValue = interp.SetVar(objv[1].ToString(), varValue, 0);
                }
                catch (TclException e)
                {
                    if (createdNewObj && !createVar)
                    {
                        varValue.Release(); // free unneeded obj
                    }
                    throw;
                }
            }

            // Set the interpreter's object result to refer to the variable's value
            // object.

            interp.SetResult(newValue);
            return TCL.CompletionCode.RETURN;
        }
Пример #15
0
 /// <summary> See Tcl user documentation for details.</summary>
 public TCL.CompletionCode CmdProc(Interp interp, TclObject[] argv)
 {
     interp.SetResult(Util.concat(1, argv.Length, argv));
     return TCL.CompletionCode.RETURN;
 }
Пример #16
0
        public TCL.CompletionCode CmdProc(Interp interp, TclObject[] argv)
        {
            if (argv.Length < 2)
            {
                throw new TclNumArgsException(interp, 1, argv, "option ?arg ...?");
            }

            int opt = TclIndex.Get(interp, argv[1], validCmds, "option", 0);
            string path;
            FileInfo fileObj = null;

            switch (opt)
            {

                case OPT_ATIME:
                    if (argv.Length != 3)
                    {
                        throw new TclNumArgsException(interp, 2, argv, "name");
                    }

                    // FIXME:  Currently returns the same thing as MTIME.
                    // Java does not support retrieval of access time.



                    fileObj = FileUtil.getNewFileObj(interp, argv[2].ToString());

                    interp.SetResult(getMtime(interp, argv[2].ToString(), fileObj));
                    return TCL.CompletionCode.RETURN;


                case OPT_ATTRIBUTES:
                    if (argv[3].ToString() == "-readonly")
                        fileSetReadOnly(interp, argv);
                    else
                        throw new TclException(interp, "sorry, \"file attributes\" is not implemented yet");
                    return TCL.CompletionCode.RETURN;


                case OPT_CHANNELS:

                    throw new TclException(interp, "sorry, \"file channels\" is not implemented yet");


                case OPT_COPY:
                    fileCopyRename(interp, argv, true);
                    return TCL.CompletionCode.RETURN;


                case OPT_DELETE:
                    fileDelete(interp, argv);
                    return TCL.CompletionCode.RETURN;


                case OPT_DIRNAME:
                    if (argv.Length != 3)
                    {
                        throw new TclNumArgsException(interp, 2, argv, "name");
                    }

                    path = argv[2].ToString();

                    // Return all but the last component.  If there is only one
                    // component, return it if the path was non-relative, otherwise
                    // return the current directory.


                    TclObject[] splitArrayObj = TclList.getElements(interp, FileUtil.splitAndTranslate(interp, path));

                    if (splitArrayObj.Length > 1)
                    {
                        interp.SetResult(FileUtil.joinPath(interp, splitArrayObj, 0, splitArrayObj.Length - 1));
                    }
                    else if ((splitArrayObj.Length == 0) || (FileUtil.getPathType(path) == FileUtil.PATH_RELATIVE))
                    {
                        if (JACL.PLATFORM == JACL.PLATFORM_MAC)
                        {
                            interp.SetResult(":");
                        }
                        else
                        {
                            interp.SetResult(".");
                        }
                    }
                    else
                    {

                        interp.SetResult(splitArrayObj[0].ToString());
                    }
                    return TCL.CompletionCode.RETURN;


                case OPT_EXECUTABLE:
                    if (argv.Length != 3)
                    {
                        throw new TclNumArgsException(interp, 2, argv, "name");
                    }
                    bool isExe = false;

                    fileObj = FileUtil.getNewFileObj(interp, argv[2].ToString());

                    // A file must exist to be executable.  Directories are always
                    // executable. 

                    bool tmpBool;
                    if (File.Exists(fileObj.FullName))
                        tmpBool = true;
                    else
                        tmpBool = Directory.Exists(fileObj.FullName);
                    if (tmpBool)
                    {
                        isExe = Directory.Exists(fileObj.FullName);
                        if (isExe)
                        {
                            interp.SetResult(isExe);
                            return TCL.CompletionCode.RETURN;
                        }

                        if (Util.Windows)
                        {
                            // File that ends with .exe, .com, or .bat is executable.


                            string fileName = argv[2].ToString();
                            isExe = (fileName.EndsWith(".exe") || fileName.EndsWith(".com") || fileName.EndsWith(".bat"));
                        }
                        else if (Util.Mac)
                        {
                            // FIXME:  Not yet implemented on Mac.  For now, return true.
                            // Java does not support executability checking.

                            isExe = true;
                        }
                        else
                        {
                            // FIXME:  Not yet implemented on Unix.  For now, return true.
                            // Java does not support executability checking.

                            isExe = true;
                        }
                    }
                    interp.SetResult(isExe);
                    return TCL.CompletionCode.RETURN;


                case OPT_EXISTS:
                    if (argv.Length != 3)
                    {
                        throw new TclNumArgsException(interp, 2, argv, "name");
                    }

                    fileObj = FileUtil.getNewFileObj(interp, argv[2].ToString());
                    bool tmpBool2;
                    if (File.Exists(fileObj.FullName))
                        tmpBool2 = true;
                    else
                        tmpBool2 = Directory.Exists(fileObj.FullName);
                    interp.SetResult(tmpBool2);
                    return TCL.CompletionCode.RETURN;


                case OPT_EXTENSION:
                    if (argv.Length != 3)
                    {
                        throw new TclNumArgsException(interp, 2, argv, "name");
                    }

                    interp.SetResult(getExtension(argv[2].ToString()));
                    return TCL.CompletionCode.RETURN;


                case OPT_ISDIRECTORY:
                    if (argv.Length != 3)
                    {
                        throw new TclNumArgsException(interp, 2, argv, "name");
                    }

                    fileObj = FileUtil.getNewFileObj(interp, argv[2].ToString());
                    interp.SetResult(Directory.Exists(fileObj.FullName));
                    return TCL.CompletionCode.RETURN;


                case OPT_ISFILE:
                    if (argv.Length != 3)
                    {
                        throw new TclNumArgsException(interp, 2, argv, "name");
                    }

                    fileObj = FileUtil.getNewFileObj(interp, argv[2].ToString());
                    interp.SetResult(File.Exists(fileObj.FullName));
                    return TCL.CompletionCode.RETURN;


                case OPT_JOIN:
                    if (argv.Length < 3)
                    {
                        throw new TclNumArgsException(interp, 2, argv, "name ?name ...?");
                    }
                    interp.SetResult(FileUtil.joinPath(interp, argv, 2, argv.Length));
                    return TCL.CompletionCode.RETURN;


                case OPT_LINK:

                    throw new TclException(interp, "sorry, \"file link\" is not implemented yet");


                case OPT_LSTAT:
                    if (argv.Length != 4)
                    {
                        throw new TclNumArgsException(interp, 2, argv, "name varName");
                    }

                    // FIXME:  Not yet implemented.
                    // Java does not support link access.


                    throw new TclException(interp, "file command with opt " + argv[1].ToString() + " is not yet implemented");



                case OPT_MTIME:
                    if (argv.Length != 3)
                    {
                        throw new TclNumArgsException(interp, 2, argv, "name");
                    }

                    fileObj = FileUtil.getNewFileObj(interp, argv[2].ToString());

                    interp.SetResult(getMtime(interp, argv[2].ToString(), fileObj));
                    return TCL.CompletionCode.RETURN;


                case OPT_MKDIR:
                    fileMakeDirs(interp, argv);
                    return TCL.CompletionCode.RETURN;


                case OPT_NATIVENAME:
                    if (argv.Length != 3)
                    {
                        throw new TclNumArgsException(interp, 2, argv, "name");
                    }


                    interp.SetResult(FileUtil.translateFileName(interp, argv[2].ToString()));
                    return TCL.CompletionCode.RETURN;


                case OPT_NORMALIZE:

                    throw new TclException(interp, "sorry, \"file normalize\" is not implemented yet");


                case OPT_OWNED:
                    if (argv.Length != 3)
                    {
                        throw new TclNumArgsException(interp, 2, argv, "name");
                    }

                    fileObj = FileUtil.getNewFileObj(interp, argv[2].ToString());
                    interp.SetResult(isOwner(interp, fileObj));
                    return TCL.CompletionCode.RETURN;


                case OPT_PATHTYPE:
                    if (argv.Length != 3)
                    {
                        throw new TclNumArgsException(interp, 2, argv, "name");
                    }

                    switch (FileUtil.getPathType(argv[2].ToString()))
                    {

                        case FileUtil.PATH_RELATIVE:
                            interp.SetResult("relative");
                            return TCL.CompletionCode.RETURN;

                        case FileUtil.PATH_VOLUME_RELATIVE:
                            interp.SetResult("volumerelative");
                            return TCL.CompletionCode.RETURN;

                        case FileUtil.PATH_ABSOLUTE:
                            interp.SetResult("absolute");
                            break;
                    }
                    return TCL.CompletionCode.RETURN;


                case OPT_READABLE:
                    if (argv.Length != 3)
                    {
                        throw new TclNumArgsException(interp, 2, argv, "name");
                    }

                    fileObj = FileUtil.getNewFileObj(interp, argv[2].ToString());

                    // interp.setResult(fileObj.canRead());
                    // HACK
                    interp.SetResult(true);
                    return TCL.CompletionCode.RETURN;


                case OPT_READLINK:
                    if (argv.Length != 3)
                    {
                        throw new TclNumArgsException(interp, 2, argv, "name");
                    }

                    // FIXME:  Not yet implemented.
                    // Java does not support link access.


                    throw new TclException(interp, "file command with opt " + argv[1].ToString() + " is not yet implemented");


                case OPT_RENAME:
                    fileCopyRename(interp, argv, false);
                    return TCL.CompletionCode.RETURN;


                case OPT_ROOTNAME:
                    if (argv.Length != 3)
                    {
                        throw new TclNumArgsException(interp, 2, argv, "name");
                    }

                    string fileName2 = argv[2].ToString();
                    string extension = getExtension(fileName2);
                    int diffLength = fileName2.Length - extension.Length;
                    interp.SetResult(fileName2.Substring(0, (diffLength) - (0)));
                    return TCL.CompletionCode.RETURN;


                case OPT_SEPARATOR:

                    throw new TclException(interp, "sorry, \"file separator\" is not implemented yet");


                case OPT_SIZE:
                    if (argv.Length != 3)
                    {
                        throw new TclNumArgsException(interp, 2, argv, "name");
                    }

                    fileObj = FileUtil.getNewFileObj(interp, argv[2].ToString());
                    bool tmpBool3;
                    if (File.Exists(fileObj.FullName))
                        tmpBool3 = true;
                    else
                        tmpBool3 = Directory.Exists(fileObj.FullName);
                    if (!tmpBool3)
                    {

                        throw new TclPosixException(interp, TclPosixException.ENOENT, true, "could not read \"" + argv[2].ToString() + "\"");
                    }
                    interp.SetResult((int)SupportClass.FileLength(fileObj));
                    return TCL.CompletionCode.RETURN;


                case OPT_SPLIT:
                    if (argv.Length != 3)
                    {
                        throw new TclNumArgsException(interp, 2, argv, "name");
                    }

                    interp.SetResult(FileUtil.splitPath(interp, argv[2].ToString()));
                    return TCL.CompletionCode.RETURN;


                case OPT_STAT:
                    if (argv.Length != 4)
                    {
                        throw new TclNumArgsException(interp, 2, argv, "name varName");
                    }

                    getAndStoreStatData(interp, argv[2].ToString(), argv[3].ToString());
                    return TCL.CompletionCode.RETURN;


                case OPT_SYSTEM:

                    throw new TclException(interp, "sorry, \"file system\" is not implemented yet");


                case OPT_TAIL:
                    if (argv.Length != 3)
                    {
                        throw new TclNumArgsException(interp, 2, argv, "name");
                    }

                    interp.SetResult(getTail(interp, argv[2].ToString()));
                    return TCL.CompletionCode.RETURN;


                case OPT_TYPE:
                    if (argv.Length != 3)
                    {
                        throw new TclNumArgsException(interp, 2, argv, "name");
                    }

                    fileObj = FileUtil.getNewFileObj(interp, argv[2].ToString());

                    interp.SetResult(getType(interp, argv[2].ToString(), fileObj));
                    return TCL.CompletionCode.RETURN;


                case OPT_VOLUMES:
                    if (argv.Length != 2)
                    {
                        throw new TclNumArgsException(interp, 2, argv, null);
                    }

                    // use Java 1.2's File.listRoots() method if available

                    if (listRootsMethod == null)
                        throw new TclException(interp, "\"file volumes\" is not supported");

                    try
                    {
                        FileInfo[] roots = (FileInfo[])listRootsMethod.Invoke(null, (System.Object[])new System.Object[0]);
                        if (roots != null)
                        {
                            TclObject list = TclList.NewInstance();
                            for (int i = 0; i < roots.Length; i++)
                            {
                                string root = roots[i].FullName;
                                TclList.Append(interp, list, TclString.NewInstance(root));
                            }
                            interp.SetResult(list);
                        }
                    }
                    catch (System.UnauthorizedAccessException ex)
                    {
                        throw new TclRuntimeError("IllegalAccessException in volumes cmd");
                    }
                    catch (System.ArgumentException ex)
                    {
                        throw new TclRuntimeError("IllegalArgumentException in volumes cmd");
                    }
                    catch (System.Reflection.TargetInvocationException ex)
                    {
                        System.Exception t = ex.GetBaseException();

                        if (t is System.ApplicationException)
                        {
                            throw (System.ApplicationException)t;
                        }
                        else
                        {
                            throw new TclRuntimeError("unexected exception in volumes cmd");
                        }
                    }

                    return TCL.CompletionCode.RETURN;

                case OPT_WRITABLE:
                    if (argv.Length != 3)
                    {
                        throw new TclNumArgsException(interp, 2, argv, "name");
                    }

                    fileObj = FileUtil.getNewFileObj(interp, argv[2].ToString());
                    interp.SetResult(SupportClass.FileCanWrite(fileObj));
                    return TCL.CompletionCode.RETURN;

                default:

                    throw new TclRuntimeError("file command with opt " + argv[1].ToString() + " is not implemented");

            }
        }
Пример #17
0
        private void FormatClock(Interp interp, int clockVal, bool useGMT, string format)
        {
            DateTime date = new DateTime((long)clockVal * 10000 * 1000 + 621355968000000000);

            DateTimeFormatInfo formatInfo = new DateTimeFormatInfo();
            string fmt, locFmt;

            GregorianCalendar calendar = new GregorianCalendar();

            System.Int32[] temp_int_array;
            temp_int_array = new System.Int32[3];
            temp_int_array[0] = 0;
            temp_int_array[1] = 0;
            temp_int_array[2] = 0;
            System.Int32[] fp = temp_int_array;
            StringBuilder result = new StringBuilder();

            if ((System.Object)format == null)
            {
                format = new StringBuilder("%a %b %d %H:%M:%S %Z %Y").ToString();
            }

            if (useGMT)
            {
                date = date.ToUniversalTime();
            }
            if (format.Equals("%Q"))
            {
                // Enterprise Stardate. (seems to be Star Track fan coding)
                // ATK not tested 
                int trekYear = date.Year + 377 - 2323;
                int trekDay = (date.DayOfYear * 1000) / (calendar.IsLeapYear(date.Year) ? 366 : 365);
                int trekHour = (24 * 60 + date.Minute) / 144;

                interp.SetResult("Stardate " + (trekYear < 10 ? "0" : "") + (trekYear * 1000 + trekDay) + '.' + trekHour);
                return;
            }

            for (int ix = 0; ix < format.Length; ix++)
            {
                if (format[ix] == '%' && ix + 1 < format.Length)
                {
                    switch (format[++ix])
                    {

                        case '%':
                            result.Append('%');
                            break;

                        case 'a':
                            result.Append(date.ToString("ddd", formatInfo));
                            break;

                        case 'A':
                            result.Append(date.ToString("dddd", formatInfo));
                            break;
                        case 'b':
                        case 'h':
                            result.Append(date.ToString("MMM", formatInfo));
                            break;
                        case 'B':
                            result.Append(date.ToString("MMMM", formatInfo));
                            break;
                        case 'c':
                            result.Append(date.ToString());
                            break;
                        case 'C':
                            int century = date.Year / 100;
                            result.Append((century < 10 ? "0" : "") + century);
                            break;
                        case 'd':
                            result.Append(date.ToString("dd", formatInfo));
                            break;
                        case 'D':
                            result.Append(date.ToString("MM/dd/yy", formatInfo));
                            break;
                        case 'e':
                            result.Append(date.ToString("%d", formatInfo));
                            break;
                        case 'H':
                            result.Append(date.ToString("HH", formatInfo));
                            break;
                        case 'I':
                            result.Append(date.ToString("hh", formatInfo));
                            break;
                        case 'j':
                            result.Append(date.Year.ToString("0###"));
                            break;
                        case 'k':
                            result.Append(date.ToString("H", formatInfo));
                            break;
                        case 'l':
                            result.Append(date.ToString("%h", formatInfo));
                            break;
                        case 'm':
                            // Month number (01 - 12). 
                            result.Append(date.ToString("MM", formatInfo));
                            break;
                        case 'M':
                            // Minute (00 - 59). 
                            result.Append(date.ToString("mm", formatInfo));
                            break;
                        case 'n':
                            // Insert a newline.
                            result.Append('\n');
                            break;
                        case 'p':
                            // AM/PM indicator. 
                            result.Append(date.ToString("tt", formatInfo));
                            break;
                        case 'r':
                            // %r 
                            //Time in a locale-specific "meridian" format. The "meridian" format in the default "C" locale is "%I:%M:%S %p". 
                            result.Append(date.ToString("hh:mm:ss tt", formatInfo));
                            break;
                        case 'R':
                            //%R 
                            //Time as %H:%M. 
                            result.Append(date.ToString("HH:MM", formatInfo));
                            break;
                        case 's':
                            //%s 
                            //Count of seconds since the epoch, expressed as a decimal integer. 
                            result.Append((date.Ticks / 1000).ToString());
                            break;

                        case 'S':
                            //%S 
                            //Seconds (00 - 59). 
                            result.Append(date.ToString("ss", formatInfo));
                            break;
                        case 't':
                            //%t 
                            //Insert a tab. 
                            result.Append('\t');
                            break;

                        case 'T':
                            //%T 
                            //Time as %H:%M:%S. 
                            result.Append(date.ToString("HH:mm:ss", formatInfo));
                            break;

                        case 'u':
                            //%u 
                            //Weekday number (Monday = 1, Sunday = 7). 
                            if (date.DayOfWeek == DayOfWeek.Sunday)
                            {
                                result.Append("7");
                            }
                            else
                            {
                                result.Append(((int)date.DayOfWeek).ToString());
                            }
                            break;
                        case 'U':
                            //%U 
                            //Week of year (00 - 52), Sunday is the first day of the week. 
                            int weekS = GetWeek(date, System.DayOfWeek.Sunday, false);
                            result.Append((weekS < 10 ? "0" : "") + weekS);
                            break;

                        case 'V':
                            //%V 
                            //Week of year according to ISO-8601 rules. Week 1 of a given year is the week containing 4 January. 
                            int isoWeek = GetWeek(date, System.DayOfWeek.Monday, true);
                            result.Append((isoWeek < 10 ? "0" : "") + isoWeek);
                            break;

                        case 'w':
                            //%w 
                            //Weekday number (Sunday = 0, Saturday = 6). 
                            result.Append(((int)date.DayOfWeek).ToString());
                            break;

                        case 'W':
                            //%W 
                            //Week of year (00 - 52), Monday is the first day of the week. 
                            int weekM = GetWeek(date, System.DayOfWeek.Monday, false);
                            result.Append((weekM < 10 ? "0" : "") + weekM);
                            break;
                        case 'x':
                            //%x 
                            //Locale specific date format. The format for a date in the default "C" locale for Unix/Mac is "%m/%d/%y". On Windows, this value is the locale specific short date format, as specified in the Regional Options control panel settings. 
                            result.Append(date.ToShortDateString());
                            break;

                        case 'X':
                            //%X 
                            //Locale specific 24-hour time format. The format for a 24-hour time in the default "C" locale for Unix/Mac is "%H:%M:%S". On Windows, this value is the locale specific time format, as specified in the Regional Options control panel settings. 
                            result.Append(date.ToShortTimeString());
                            break;
                        case 'y':
                            //%y 
                            //Year without century (00 - 99). 
                            result.Append(date.ToString("yy", formatInfo));
                            break;

                        case 'Y':
                            //%Y 
                            //Year with century (e.g. 1990) 
                            result.Append(date.ToString("yyyy", formatInfo));
                            break;
                        case 'Z':
                            //%Z 
                            //Time zone name. 
                            result.Append(date.ToString("zzz", formatInfo));
                            break;
                        default:
                            result.Append(format[ix]);
                            break;
                    }
                }
                else
                {
                    result.Append(format[ix]);
                }
            }
            interp.SetResult(result.ToString());
        }
Пример #18
0
        public TCL.CompletionCode CmdProc(Interp interp, TclObject[] objv)
        {
            int len;

            if (objv.Length < 2)
            {
                throw new TclNumArgsException(interp, 1, objv, "option [arg arg ...]");
            }
            int opt = TclIndex.Get(interp, objv[1], validCmds, "option", 0);

            switch (opt)
            {

                case OPT_VARIABLE:
                case OPT_VDELETE:
                    if (objv.Length != 5)
                    {
                        if (opt == OPT_VARIABLE)
                        {
                            throw new TclNumArgsException(interp, 1, objv, "variable name ops command");
                        }
                        else
                        {
                            throw new TclNumArgsException(interp, 1, objv, "vdelete name ops command");
                        }
                    }

                    TCL.VarFlag flags = 0;

                    string ops = objv[3].ToString();
                    len = ops.Length;
                    {
                        for (int i = 0; i < len; i++)
                        {
                            switch (ops[i])
                            {

                                case 'r':
                                    flags |= TCL.VarFlag.TRACE_READS;
                                    break;

                                case 'w':
                                    flags |= TCL.VarFlag.TRACE_WRITES;
                                    break;

                                case 'u':
                                    flags |= TCL.VarFlag.TRACE_UNSETS;
                                    break;

                                default:
                                    flags = 0;
                                    goto check_ops_brk;

                            }
                        }
                    }

                check_ops_brk:
                    ;


                    if (flags == 0)
                    {

                        throw new TclException(interp, "bad operations \"" + objv[3] + "\": should be one or more of rwu");
                    }

                    if (opt == OPT_VARIABLE)
                    {

                        CmdTraceProc trace = new CmdTraceProc(objv[4].ToString(), flags);
                        Var.TraceVar(interp, objv[2], flags, trace);
                    }
                    else
                    {
                        // Search through all of our traces on this variable to
                        // see if there's one with the given command.  If so, then
                        // delete the first one that matches.


                        ArrayList traces = Var.getTraces(interp, objv[2].ToString(), 0);
                        if (traces != null)
                        {
                            len = traces.Count;
                            for (int i = 0; i < len; i++)
                            {
                                TraceRecord rec = (TraceRecord)traces[i];

                                if (rec.trace is CmdTraceProc)
                                {
                                    CmdTraceProc proc = (CmdTraceProc)rec.trace;

                                    if (proc.flags == flags && proc.command.ToString().Equals(objv[4].ToString()))
                                    {
                                        Var.UntraceVar(interp, objv[2], flags, proc);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    break;


                case OPT_VINFO:
                    if (objv.Length != 3)
                    {
                        throw new TclNumArgsException(interp, 2, objv, "name");
                    }

                    ArrayList traces2 = Var.getTraces(interp, objv[2].ToString(), 0);
                    if (traces2 != null)
                    {
                        len = traces2.Count;
                        TclObject list = TclList.NewInstance();
                        TclObject cmd = null;
                        list.Preserve();

                        try
                        {
                            for (int i = 0; i < len; i++)
                            {
                                TraceRecord rec = (TraceRecord)traces2[i];

                                if (rec.trace is CmdTraceProc)
                                {
                                    CmdTraceProc proc = (CmdTraceProc)rec.trace;
                                    TCL.VarFlag mode = proc.flags;
                                    mode &= (TCL.VarFlag.TRACE_READS | TCL.VarFlag.TRACE_WRITES | TCL.VarFlag.TRACE_UNSETS);
                                    int modeInt = (int)mode;
                                    modeInt /= ((int)TCL.VarFlag.TRACE_READS);

                                    cmd = TclList.NewInstance();
                                    TclList.Append(interp, cmd, opStr[modeInt]);
                                    TclList.Append(interp, cmd, TclString.NewInstance(proc.command));
                                    TclList.Append(interp, list, cmd);
                                }
                            }
                            interp.SetResult(list);
                        }
                        finally
                        {
                            list.Release();
                        }
                    }
                    break;
            }
            return TCL.CompletionCode.RETURN;
        }
Пример #19
0
    public TCL.CompletionCode CmdProc( Interp interp, TclObject[] objv )
    {
      if ( objv.Length < 2 )
      {
        throw new TclNumArgsException( interp, 1, objv, "cmd ?arg ...?" );
      }
      int cmd = TclIndex.Get( interp, objv[1], options, "option", 0 );

      switch ( cmd )
      {

        case OPT_ALIAS:
          if ( objv.Length == 3 )
          {
            InterpAliasCmd.describe( interp, slaveInterp, objv[2] );
            return TCL.CompletionCode.RETURN;
          }

          if ( "".Equals( objv[3].ToString() ) )
          {
            if ( objv.Length == 4 )
            {
              InterpAliasCmd.delete( interp, slaveInterp, objv[2] );
              return TCL.CompletionCode.RETURN;
            }
          }
          else
          {
            InterpAliasCmd.create( interp, slaveInterp, interp, objv[2], objv[3], 4, objv );
            return TCL.CompletionCode.RETURN;
          }
          throw new TclNumArgsException( interp, 2, objv, "aliasName ?targetName? ?args..?" );

        case OPT_ALIASES:
          InterpAliasCmd.list( interp, slaveInterp );
          break;

        case OPT_EVAL:
          if ( objv.Length < 3 )
          {
            throw new TclNumArgsException( interp, 2, objv, "arg ?arg ...?" );
          }
          eval( interp, slaveInterp, 2, objv );
          break;

        case OPT_EXPOSE:
          if ( objv.Length < 3 || objv.Length > 4 )
          {
            throw new TclNumArgsException( interp, 2, objv, "hiddenCmdName ?cmdName?" );
          }
          expose( interp, slaveInterp, 2, objv );
          break;

        case OPT_HIDE:
          if ( objv.Length < 3 || objv.Length > 4 )
          {
            throw new TclNumArgsException( interp, 2, objv, "cmdName ?hiddenCmdName?" );
          }
          hide( interp, slaveInterp, 2, objv );
          break;

        case OPT_HIDDEN:
          if ( objv.Length != 2 )
          {
            throw new TclNumArgsException( interp, 2, objv, null );
          }
          InterpSlaveCmd.hidden( interp, slaveInterp );
          break;

        case OPT_ISSAFE:
          interp.SetResult( slaveInterp._isSafe );
          break;

        case OPT_INVOKEHIDDEN:
          bool global = false;
          int i;
          for ( i = 2; i < objv.Length; i++ )
          {

            if ( objv[i].ToString()[0] != '-' )
            {
              break;
            }
            int index = TclIndex.Get( interp, objv[i], hiddenOptions, "option", 0 );
            if ( index == OPT_HIDDEN_GLOBAL )
            {
              global = true;
            }
            else
            {
              i++;
              break;
            }
          }
          if ( objv.Length - i < 1 )
          {
            throw new TclNumArgsException( interp, 2, objv, "?-global? ?--? cmd ?arg ..?" );
          }
          InterpSlaveCmd.invokeHidden( interp, slaveInterp, global, i, objv );
          break;

        case OPT_MARKTRUSTED:
          if ( objv.Length != 2 )
          {
            throw new TclNumArgsException( interp, 2, objv, null );
          }
          markTrusted( interp, slaveInterp );
          break;
      }
      return TCL.CompletionCode.RETURN;
    }
Пример #20
0
    internal static void hidden( Interp interp, Interp slaveInterp )
    {
      if ( slaveInterp._hiddenCmdTable == null )
      {
        return;
      }

      TclObject result = TclList.NewInstance();
      interp.SetResult( result );

      IEnumerator hiddenCmds = slaveInterp._hiddenCmdTable.Keys.GetEnumerator();
      while ( hiddenCmds.MoveNext() )
      {
        string cmdName = (string)hiddenCmds.Current;
        TclList.Append( interp, result, TclString.NewInstance( cmdName ) );
      }
    }
Пример #21
0
        public TCL.CompletionCode CmdProc(Interp interp, TclObject[] argv)
        {
            bool nocase = false;
            bool indices = false;

            try
            {
                int i = 1;

                while (argv[i].ToString().StartsWith("-"))
                {
                    int index = TclIndex.Get(interp, argv[i], validOpts, "switch", 0);
                    i++;
                    switch (index)
                    {

                        case OPT_INDICES:
                            {
                                indices = true;
                                break;
                            }

                        case OPT_NOCASE:
                            {
                                nocase = true;
                                break;
                            }

                        case OPT_LAST:
                            {
                                goto opts_brk;
                            }
                    }
                }

            opts_brk:
                ;


                TclObject exp = TclString.NewInstance(argv[i++].ToString().Replace("\\d", "[0-9]"));

                string inString = argv[i++].ToString();

                int matches = argv.Length - i;

                Regexp r = TclRegexp.compile(interp, exp, nocase);

                int[] args = new int[matches * 2];
                bool matched = r.match(inString, args);
                if (matched)
                {
                    for (int match = 0; i < argv.Length; i++)
                    {
                        TclObject obj;

                        int start = args[match++];
                        int end = args[match++];
                        if (indices)
                        {
                            if (end >= 0)
                            {
                                end--;
                            }
                            obj = TclList.NewInstance();
                            TclList.Append(interp, obj, TclInteger.NewInstance(start));
                            TclList.Append(interp, obj, TclInteger.NewInstance(end));
                        }
                        else
                        {
                            string range = (start >= 0) ? inString.Substring(start, (end) - (start)) : "";
                            obj = TclString.NewInstance(range);
                        }
                        try
                        {

                            interp.SetVar(argv[i].ToString(), obj, 0);
                        }
                        catch (TclException e)
                        {

                            throw new TclException(interp, "couldn't set variable \"" + argv[i] + "\"");
                        }
                    }
                }
                interp.SetResult(matched);
            }
            catch (System.IndexOutOfRangeException e)
            {
                throw new TclNumArgsException(interp, 1, argv, "?switches? exp string ?matchVar? ?subMatchVar subMatchVar ...?");
            }
            return TCL.CompletionCode.RETURN;
        }
Пример #22
0
        /// <summary> This procedure is invoked to process the "read" Tcl command.
        /// See the user documentation for details on what it does.
        /// 
        /// </summary>
        /// <param name="interp">the current interpreter.
        /// </param>
        /// <param name="argv">command arguments.
        /// </param>

        public TCL.CompletionCode CmdProc(Interp interp, TclObject[] argv)
        {

            Channel chan; // The channel being operated on this 
            // method 
            int i = 1; // Index to the next arg in argv
            int toRead = 0; // Number of bytes or chars to read from channel
            int charactersRead; // Number of bytes or chars read from channel
            bool readAll = true; // If true read-all else toRead
            bool noNewline = false; // If true, strip the newline if there
            TclObject result;


            if ((argv.Length != 2) && (argv.Length != 3))
            {

                errorWrongNumArgs(interp, argv[0].ToString());
            }


            if (argv[i].ToString().Equals("-nonewline"))
            {
                noNewline = true;
                i++;
            }

            if (i == argv.Length)
            {

                errorWrongNumArgs(interp, argv[0].ToString());
            }


            chan = TclIO.getChannel(interp, argv[i].ToString());
            if (chan == null)
            {

                throw new TclException(interp, "can not find channel named \"" + argv[i].ToString() + "\"");
            }

            // Consumed channel name. 

            i++;

            // Compute how many bytes or chars to read, and see whether the final
            // noNewline should be dropped.

            if (i < argv.Length)
            {

                string arg = argv[i].ToString();

                if (System.Char.IsDigit(arg[0]))
                {
                    toRead = TclInteger.Get(interp, argv[i]);
                    readAll = false;
                }
                else if (arg.Equals("nonewline"))
                {
                    noNewline = true;
                }
                else
                {
                    throw new TclException(interp, "bad argument \"" + arg + "\": should be \"nonewline\"");
                }
            }

            try
            {
                if ((System.Object)chan.Encoding == null)
                {
                    result = TclByteArray.NewInstance();
                }
                else
                {
                    result = TclString.NewInstance(new StringBuilder(64));
                }
                if (readAll)
                {
                    charactersRead = chan.read(interp, result, TclIO.READ_ALL, 0);

                    // If -nonewline was specified, and we have not hit EOF
                    // and the last char is a "\n", then remove it and return.

                    if (noNewline)
                    {

                        string inStr = result.ToString();
                        if ((charactersRead > 0) && (inStr[charactersRead - 1] == '\n'))
                        {
                            interp.SetResult(inStr.Substring(0, ((charactersRead - 1)) - (0)));
                            return TCL.CompletionCode.RETURN;
                        }
                    }
                }
                else
                {
                    // FIXME: Bug here, the -nonewline flag must be respected
                    // when reading a set number of bytes
                    charactersRead = chan.read(interp, result, TclIO.READ_N_BYTES, toRead);
                }

                /*
                // FIXME: Port this -nonewline logic from the C code.
                if (charactersRead < 0) {
                Tcl_ResetResult(interp);
                Tcl_AppendResult(interp, "error reading \"", name, "\": ",
                Tcl_PosixError(interp), (char *) NULL);
                Tcl_DecrRefCount(resultPtr);
                return TCL_ERROR;
                }
				
                // If requested, remove the last newline in the channel if at EOF.
				
                if ((charactersRead > 0) && (newline != 0)) {
                char *result;
                int length;
				
                result = Tcl_GetStringFromObj(resultPtr, length);
                if (result[length - 1] == '\n') {
                Tcl_SetObjLength(resultPtr, length - 1);
                }
                }
				
                */

                interp.SetResult(result);
            }
            catch (IOException e)
            {
                throw new TclRuntimeError("ReadCmd.cmdProc() Error: IOException when reading " + chan.ChanName);
            }
            return TCL.CompletionCode.RETURN;
        }
Пример #23
0
        public TCL.CompletionCode CmdProc(Interp interp, TclObject[] objv)
        {
            int clockVal; // Time value as seconds of epoch.
            string dateString; // Time value as string.
            int argIx; // Counter over arguments.
            string format = null; // User specified format string.
            bool useGmt = false; // User specified flag to use gmt.
            TclObject baseObj = null; // User specified raw value of baseClock.
            System.DateTime baseClock; // User specified time value.
            System.DateTime date; // Parsed date value.

            if (objv.Length < 2)
            {
                throw new TclNumArgsException(interp, 1, objv, "option ?arg ...?");
            }
            int cmd = TclIndex.Get(interp, objv[1], validCmds, "option", 0);

            switch (cmd)
            {

                case CMD_CLICKS:
                    {
                        if (objv.Length > 3)
                        {
                            throw new TclNumArgsException(interp, 2, objv, "?-milliseconds?");
                        }
                        if (objv.Length == 3)
                        {
                            // We can safely ignore the -milliseconds options, since
                            // we measure the clicks in milliseconds anyway...
                            int clicksOpt = TclIndex.Get(interp, objv[2], clicksOpts, "switch", 0);
                        }
                        long millis = (System.DateTime.Now.Ticks - 621355968000000000) / 10000;
                        int clicks = (int)(millis % System.Int32.MaxValue);
                        interp.SetResult(clicks);
                        break;
                    }


                case CMD_FORMAT:
                    {
                        if ((objv.Length < 3) || (objv.Length > 7))
                        {
                            throw new TclNumArgsException(interp, 2, objv, "clockval ?-format string? ?-gmt boolean?");
                        }
                        clockVal = TclInteger.Get(interp, objv[2]);

                        for (argIx = 3; argIx + 1 < objv.Length; argIx += 2)
                        {
                            int formatOpt = TclIndex.Get(interp, objv[argIx], formatOpts, "switch", 0);
                            switch (formatOpt)
                            {

                                case OPT_FORMAT_FORMAT:
                                    {

                                        format = objv[argIx + 1].ToString();
                                        break;
                                    }

                                case OPT_FORMAT_GMT:
                                    {
                                        useGmt = TclBoolean.get(interp, objv[argIx + 1]);
                                        break;
                                    }
                            }
                        }
                        if (argIx < objv.Length)
                        {
                            throw new TclNumArgsException(interp, 2, objv, "clockval ?-format string? ?-gmt boolean?");
                        }
                        FormatClock(interp, clockVal, useGmt, format);
                        break;
                    }


                case CMD_SCAN:
                    {
                        if ((objv.Length < 3) || (objv.Length > 7))
                        {
                            throw new TclNumArgsException(interp, 2, objv, "dateString ?-base clockValue? ?-gmt boolean?");
                        }

                        dateString = objv[2].ToString();

                        for (argIx = 3; argIx + 1 < objv.Length; argIx += 2)
                        {
                            int scanOpt = TclIndex.Get(interp, objv[argIx], scanOpts, "switch", 0);
                            switch (scanOpt)
                            {

                                case OPT_SCAN_BASE:
                                    {
                                        baseObj = objv[argIx + 1];
                                        break;
                                    }

                                case OPT_SCAN_GMT:
                                    {
                                        useGmt = TclBoolean.get(interp, objv[argIx + 1]);
                                        break;
                                    }
                            }
                        }
                        if (argIx < objv.Length)
                        {
                            throw new TclNumArgsException(interp, 2, objv, "clockval ?-format string? ?-gmt boolean?");
                        }
                        if (baseObj != null)
                        {
                            long seconds = TclInteger.Get(interp, baseObj);
                            baseClock = new System.DateTime((long)seconds * 10000 * 1000 + 621355968000000000);
                        }
                        else
                        {
                            baseClock = System.DateTime.Now;
                        }
                        try
                        {
                            date = GetDate(dateString, baseClock, useGmt);
                        }
                        catch (FormatException)
                        {
                            throw new TclException(interp, "unable to convert date-time string \"" + dateString + "\"");
                        }
                        long millis = (date.Ticks - 621355968000000000) / 10000;
                        int seconds2 = (int)(millis / 1000);
                        interp.SetResult(seconds2);
                        break;
                    }


                case CMD_SECONDS:
                    {
                        if (objv.Length != 2)
                        {
                            throw new TclNumArgsException(interp, 2, objv, null);
                        }
                        long millis = (System.DateTime.Now.Ticks - 621355968000000000) / 10000;
                        int seconds = (int)(millis / 1000);
                        interp.SetResult(seconds);
                        break;
                    }
            }
            return TCL.CompletionCode.RETURN;
        }
Пример #24
0
        public TCL.CompletionCode CmdProc(Interp interp, TclObject[] argv)
        {
            int firstWord; /* Index to the first non-switch arg */
            int argLen = argv.Length; /* No of args to copy to argStrs     */
            int exit; /* denotes exit status of process    */
            int errorBytes = 0; /* number of bytes of process stderr */
            //bool background; /* Indicates a bg process            */
            //bool keepNewline; /* Retains newline in pipline output */
            System.Diagnostics.Process p; /* The exec-ed process               */
            string argStr; /* Conversion of argv to a string    */
            StringBuilder sbuf;

            /*
            * Check for a leading "-keepnewline" argument.
            */

            for (firstWord = 1; firstWord < argLen; firstWord++)
            {
                argStr = argv[firstWord].ToString();
                if ((argStr.Length > 0) && (argStr[0] == '-'))
                {
                    //if (argStr.Equals("-keepnewline"))
                    //{
                    //  keepNewline = true;
                    //}
                    //else 
                    if (argStr.Equals("--"))
                    {
                        firstWord++;
                        break;
                    }
                    else
                    {
                        throw new TclException(interp, "bad switch \"" + argStr + "\": must be -keepnewline or --");
                    }
                }
            }

            if (argLen <= firstWord)
            {
                throw new TclNumArgsException(interp, 1, argv, "?switches? arg ?arg ...?");
            }


            /*
            * See if the command is to be run in background.
            * Currently this does nothing, it is just for compatibility
            */


            //if (argv[argLen - 1].ToString().Equals("&"))
            //{
            //  argLen--;
            //  background = true;
            //}

            try
            {
                /*
                * It is necessary to perform system specific 
                * operations before calling exec.  For now Solaris
                * and Windows execs are somewhat supported, in all other cases
                * we simply call exec and give it our "best shot"
                */

                if (execMethod != null)
                {
                    p = execReflection(interp, argv, firstWord, argLen);
                }
                else if (Util.Unix)
                {
                    p = execUnix(interp, argv, firstWord, argLen);
                }
                else if (Util.Windows)
                {
                    p = execWin(interp, argv, firstWord, argLen);
                }
                else
                {
                    p = execDefault(interp, argv, firstWord, argLen);
                }


                //note to self : buffer reading should be done in
                //a separate thread and not by calling waitFor()
                //because a process that is waited for can block


                //Wait for the process to finish running,
                try
                {
                    p.Start();
                    p.WaitForExit();
                    exit = p.ExitCode;
                }
                catch (Exception e)
                {
                    throw new TclException(interp, "exception in exec process: " + e.Message);
                }


                //Make buffer for the results of the subprocess execution
                sbuf = new StringBuilder();

                //read data on stdout stream into  result buffer
                readStreamIntoBuffer(p.StandardOutput.BaseStream, sbuf);

                //if there is data on the stderr stream then append
                //this data onto the result StringBuffer
                //check for the special case where there is no error
                //data but the process returns an error result

                errorBytes = readStreamIntoBuffer(p.StandardError.BaseStream, sbuf);

                if ((errorBytes == 0) && (exit != 0))
                {
                    sbuf.Append("child process exited abnormally");
                }

                //If the last character of the result buffer is a newline, then 
                //remove the newline character (the newline would just confuse 
                //things).  Finally, we set pass the result to the interpreter.



                // Tcl supports lots of child status conditions.
                // Unfortunately, we can only find the child's
                // exit status using the Java API

                if (exit != 0)
                {
                    TclObject childstatus = TclList.NewInstance();
                    TclList.Append(interp, childstatus, TclString.NewInstance("CHILDSTATUS"));

                    // We don't know how to find the child's pid
                    TclList.Append(interp, childstatus, TclString.NewInstance("?PID?"));

                    TclList.Append(interp, childstatus, TclInteger.NewInstance(exit));

                    interp.SetErrorCode(childstatus);
                }

                //when the subprocess writes to its stderr stream or returns
                //a non zero result we generate an error
                if ((exit != 0) || (errorBytes != 0))
                {
                    throw new TclException(interp, sbuf.ToString());
                }

                //otherwise things went well so set the result
                interp.SetResult(sbuf.ToString());
            }
            catch (IOException e)
            {
                //if exec fails we end up catching the exception here


                throw new TclException(interp, "couldn't execute \"" + argv[firstWord].ToString() + "\": no such file or directory");
            }
            catch (System.Threading.ThreadInterruptedException e)
            {
                /*
                * Do Nothing...
                */
            }
            return TCL.CompletionCode.RETURN;
        }