Ejemplo n.º 1
0
        ///////////////////////////////////////////////////////////////////////

        public static IScript Create(
            string name,
            string group,
            string description,
            string type,
            string text,
            string fileName,
            int startLine,
            int endLine,
            bool viaSource,
            DateTime timeStamp,
            EngineMode engineMode,
            ScriptFlags scriptFlags,
            EngineFlags engineFlags,
            SubstitutionFlags substitutionFlags,
            EventFlags eventFlags,
            ExpressionFlags expressionFlags,
            IClientData clientData
            )
        {
            return(PrivateCreate(
                       Guid.Empty, name, group, description, type, text, fileName,
                       startLine, endLine, viaSource,
#if XML
                       XmlBlockType.None, timeStamp, null, null,
#endif
                       engineMode, scriptFlags, engineFlags, substitutionFlags,
                       eventFlags, expressionFlags, clientData));
        }
Ejemplo n.º 2
0
        ///////////////////////////////////////////////////////////////////////

        //
        // NOTE: For use by InteractiveOps.Commands._break() and
        //       Engine.CheckBreakpoints() only.
        //
        internal InteractiveLoopData(
            ReturnCode code,
            BreakpointType breakpointType,
            string breakpointName,
            IToken token,
            ITraceInfo traceInfo,
            EngineFlags engineFlags,
            SubstitutionFlags substitutionFlags,
            EventFlags eventFlags,
            ExpressionFlags expressionFlags,
            HeaderFlags headerFlags,
            IClientData clientData,
            ArgumentList arguments
            )
            : this()
        {
            this.code              = code;
            this.breakpointType    = breakpointType;
            this.breakpointName    = breakpointName;
            this.token             = token;
            this.traceInfo         = traceInfo;
            this.engineFlags       = engineFlags;
            this.substitutionFlags = substitutionFlags;
            this.eventFlags        = eventFlags;
            this.expressionFlags   = expressionFlags;
            this.headerFlags       = headerFlags;
            this.clientData        = clientData;
            this.arguments         = arguments;
        }
Ejemplo n.º 3
0
        internal AsynchronousContext(
            int threadId,
            EngineMode engineMode,
            Interpreter interpreter,
            string text,
            EngineFlags engineFlags,
            SubstitutionFlags substitutionFlags,
            EventFlags eventFlags,
            ExpressionFlags expressionFlags,
            AsynchronousCallback callback,
            IClientData clientData
            )
        {
            this.threadId = threadId;

            this.engineMode        = engineMode;
            this.interpreter       = interpreter;
            this.text              = text;
            this.engineFlags       = engineFlags;
            this.substitutionFlags = substitutionFlags;
            this.eventFlags        = eventFlags;
            this.expressionFlags   = expressionFlags;
            this.callback          = callback;
            this.clientData        = clientData;
        }
Ejemplo n.º 4
0
        public void Render(IRendererContext context, RenderPasses renderPass, IRenderable renderable)
        {
            var c  = (VeldridRendererContext)context;
            var cl = c.CommandList;
            var sc = c.SceneContext;

            ITextureManager      textureManager = Resolve <ITextureManager>();
            IDeviceObjectManager dom            = Resolve <IDeviceObjectManager>();
            EngineFlags          engineFlags    = Resolve <IEngineSettings>().Flags;
            // float depth = gd.IsDepthRangeZeroToOne ? 0 : 1;
            var sprite    = (MultiSprite)renderable;
            var shaderKey = new SpriteShaderKey(sprite, engineFlags);

            sprite.PipelineId = shaderKey.GetHashCode();

            //if (!shaderKey.UseArrayTexture)
            //    return;

            cl.PushDebugGroup(sprite.Name);

            if (sc.PaletteView == null)
            {
                return;
            }

            TextureView textureView    = (TextureView)textureManager?.GetTexture(sprite.Key.Texture);
            var         resourceSet    = dom.Get <ResourceSet>((sprite, textureView));
            var         instanceBuffer = dom.Get <DeviceBuffer>((sprite, sprite));
            var         uniformInfo    = new SpriteUniformInfo
            {
                Flags         = sprite.Key.Flags,
                TextureWidth  = textureView?.Target.Width ?? 1,
                TextureHeight = textureView?.Target.Height ?? 1
            };

            if (sprite.Key.ScissorRegion.HasValue)
            {
                IWindowManager wm = Resolve <IWindowManager>();
                var            screenCoordinates = wm.UiToPixel(sprite.Key.ScissorRegion.Value);
                cl.SetScissorRect(0, (uint)screenCoordinates.X, (uint)screenCoordinates.Y, (uint)screenCoordinates.Width, (uint)screenCoordinates.Height);
            }

            cl.UpdateBuffer(_uniformBuffer, 0, uniformInfo);
            cl.SetPipeline(_pipelines[shaderKey]);
            cl.SetGraphicsResourceSet(0, resourceSet);
            cl.SetGraphicsResourceSet(1, sc.CommonResourceSet);
            cl.SetVertexBuffer(0, _vertexBuffer);
            cl.SetIndexBuffer(_indexBuffer, IndexFormat.UInt16);
            cl.SetVertexBuffer(1, instanceBuffer);

            //cl.SetViewport(0, new Viewport(0, 0, sc.MainSceneColorTexture.Width, sc.MainSceneColorTexture.Height, depth, depth));
            cl.DrawIndexed((uint)Indices.Length, (uint)sprite.ActiveInstances, 0, 0, 0);
            //cl.SetViewport(0, new Viewport(0, 0, sc.MainSceneColorTexture.Width, sc.MainSceneColorTexture.Height, 0, 1));
            if (sprite.Key.ScissorRegion.HasValue)
            {
                cl.SetFullScissorRect(0);
            }
            cl.PopDebugGroup();
        }
Ejemplo n.º 5
0
 public SpriteShaderKey(MultiSprite sprite, EngineFlags engineFlags) : this(
         sprite.Key.Texture.ArrayLayers > 1,
         (sprite.Key.Flags & SpriteKeyFlags.NoDepthTest) == 0,
         sprite.Key.Texture is EightBitTexture,
         (engineFlags & EngineFlags.UseCylindricalBillboards) != 0 &&
         (sprite.Key.Flags & SpriteKeyFlags.UseCylindrical) != 0)
 {
 }
Ejemplo n.º 6
0
        ///////////////////////////////////////////////////////////////////////

        public EngineFlags BeginExternalExecution()
        {
            CheckDisposed();

            levels++;

            engineFlags |= EngineFlags.ExternalExecution;
            return(Engine.AddStackCheckFlags(ref engineFlags));
        }
Ejemplo n.º 7
0
        ///////////////////////////////////////////////////////////////////////

        public override ReturnCode GetIExecute(
            ICallFrame frame,
            EngineFlags engineFlags,
            string name,
            ArgumentList arguments,
            LookupFlags lookupFlags,
            ref bool ambiguous,
            ref long token,
            ref IExecute execute,
            ref Result error
            )
        {
            if (!Engine.HasGlobalOnly(engineFlags))
            {
                IResolve resolve = null;
                string   tail    = null;

                INamespace @namespace = GetNamespaceForIExecute(
                    frame, name, ref resolve, ref tail, ref error);

                if (@namespace != null)
                {
                    if (resolve != null)
                    {
                        return(resolve.GetIExecute(
                                   frame, engineFlags, tail, arguments, lookupFlags,
                                   ref ambiguous, ref token, ref execute, ref error));
                    }
                    else
                    {
                        Interpreter interpreter = base.Interpreter;

                        if (!NamespaceOps.IsGlobal(interpreter, @namespace))
                        {
                            string qualifiedName =
                                NamespaceOps.MakeQualifiedName(
                                    interpreter, @namespace, name);

                            if (base.GetIExecute(frame,
                                                 engineFlags | EngineFlags.ExactMatch,
                                                 qualifiedName, arguments, lookupFlags,
                                                 ref ambiguous, ref token, ref execute,
                                                 ref error) == ReturnCode.Ok)
                            {
                                return(ReturnCode.Ok);
                            }
                        }
                    }
                }
            }

            return(base.GetIExecute(
                       frame, engineFlags, name, arguments, lookupFlags,
                       ref ambiguous, ref token, ref execute, ref error));
        }
Ejemplo n.º 8
0
        ///////////////////////////////////////////////////////////////////////

        public int EndExternalExecution(
            EngineFlags savedEngineFlags
            )
        {
            CheckDisposed();

            Engine.RemoveStackCheckFlags(savedEngineFlags, ref engineFlags);
            engineFlags &= ~EngineFlags.ExternalExecution;

            return(--levels);
        }
Ejemplo n.º 9
0
        ///////////////////////////////////////////////////////////////////////

        public override ReturnCode GetIExecute(
            ICallFrame frame,
            EngineFlags engineFlags,
            string name,
            ArgumentList arguments, /* NOT USED */
            LookupFlags lookupFlags,
            ref bool ambiguous,
            ref long token,
            ref IExecute execute,
            ref Result error
            )
        {
            Interpreter interpreter = base.Interpreter;

            if (interpreter != null)
            {
                //
                // NOTE: Lookup the command or procedure to execute.  We
                //       use inexact (unique prefix) matching here unless
                //       we are forbidden from doing so; in that case, we
                //       use exact matching.
                //
                if (Engine.HasExactMatch(engineFlags))
                {
                    return(interpreter.GetAnyIExecute(
                               frame, engineFlags | EngineFlags.GetHidden,
                               name, lookupFlags, ref token, ref execute,
                               ref error));
                }
                else
                {
                    //
                    // NOTE: Include hidden commands in the resolution
                    //       phase here because the policy decisions about
                    //       whether or not to execute them are not made
                    //       here.
                    //
                    return(interpreter.MatchAnyIExecute(
                               frame, engineFlags | EngineFlags.MatchHidden,
                               name, lookupFlags, ref ambiguous, ref token,
                               ref execute, ref error));
                }
            }
            else
            {
                error = "invalid interpreter";
            }

            return(ReturnCode.Error);
        }
Ejemplo n.º 10
0
        ///////////////////////////////////////////////////////////////////////

        public virtual ReturnCode GetIExecute(
            ICallFrame frame,
            EngineFlags engineFlags,
            string name,
            ArgumentList arguments,
            LookupFlags lookupFlags,
            ref bool ambiguous,
            ref long token,
            ref IExecute execute,
            ref Result error
            )
        {
            error = "not implemented";
            return(ReturnCode.Error);
        }
Ejemplo n.º 11
0
        ///////////////////////////////////////////////////////////////////////

        /* INTERNAL STATIC OK */
        internal static IScript CreateForPolicy(
            string name,
            string type,
            string text,
            EngineFlags engineFlags,
            SubstitutionFlags substitutionFlags,
            EventFlags eventFlags,
            ExpressionFlags expressionFlags
            )
        {
            return(Create(
                       name, null, null, type, text, TimeOps.GetUtcNow(),
                       EngineMode.EvaluateScript, ScriptFlags.None,
                       engineFlags, substitutionFlags, eventFlags,
                       expressionFlags, null));
        }
Ejemplo n.º 12
0
        ///////////////////////////////////////////////////////////////////////

#if DEBUGGER
        public static bool CanHitBreakpoints(
            Interpreter interpreter,
            EngineFlags engineFlags,
            BreakpointType breakpointType
            )
        {
            if ((interpreter == null) || interpreter.Disposed)
            {
                return(false);
            }

            if (Engine.HasNoBreakpoint(engineFlags))
            {
                return(false);
            }

            return(interpreter.CanHitBreakpoints(breakpointType));
        }
Ejemplo n.º 13
0
        ///////////////////////////////////////////////////////////////////////////////////////////////

        #region Protected Constructors
        //
        // NOTE: Sets up default values for the properties we use.  The MSBuild
        //       documentation is not entirely clear about whether or not having
        //       constructors is allowed; however, it does not appear to forbid
        //       them.
        //
        protected Script()
        {
            //
            // NOTE: Get the effective interpreter creation flags from the
            //       environment, etc.
            //
            createFlags = Interpreter.GetStartupCreateFlags(null,
                                                            DefaultCreateFlags, OptionOriginFlags.Standard, true, true);

            //
            // NOTE: By default, we do not want any special evaluation flags.
            //
            engineFlags = EngineFlags.None;

            //
            // NOTE: By default, we want all the substitution flags.
            //
            substitutionFlags = SubstitutionFlags.Default;

            //
            // NOTE: By default, we want to handle events targeted at the
            //       engine.
            //
            eventFlags = EventFlags.Default;

            //
            // NOTE: By default, we want all the expression flags.
            //
            expressionFlags = ExpressionFlags.Default;

            //
            // NOTE: By default, we do not want to allow "exceptional" (non-Ok)
            //       success return codes.
            //
            exceptions = false;

            //
            // NOTE: By default, we want to show the exception stack trace.
            //
            showStackTrace = true;
        }
Ejemplo n.º 14
0
        ///////////////////////////////////////////////////////////////////////

        private static IScript PrivateCreate(
            Guid id,
            string name,
            string group,
            string description,
            string type,
            string text,
            string fileName,
            int startLine,
            int endLine,
            bool viaSource,
#if XML
            XmlBlockType blockType,
            DateTime timeStamp,
            string publicKeyToken,
            byte[] signature,
#endif
            EngineMode engineMode,
            ScriptFlags scriptFlags,
            EngineFlags engineFlags,
            SubstitutionFlags substitutionFlags,
            EventFlags eventFlags,
            ExpressionFlags expressionFlags,
            IClientData clientData
            )
        {
            return(new Script(
                       id, name, group, description, type, text, fileName,
                       startLine, endLine, viaSource,
#if XML
                       blockType, timeStamp, publicKeyToken, signature,
#endif
#if CAS_POLICY
                       DefaultEvidence,
                       DefaultHashValue,
                       DefaultHashAlgorithm,
#endif
                       engineMode, scriptFlags, engineFlags, substitutionFlags,
                       eventFlags, expressionFlags, clientData));
        }
Ejemplo n.º 15
0
        ///////////////////////////////////////////////////////////////////////

        public static IScript Create(
            string name,
            string group,
            string description,
            string type,
            string text,
            DateTime timeStamp,
            EngineMode engineMode,
            ScriptFlags scriptFlags,
            EngineFlags engineFlags,
            SubstitutionFlags substitutionFlags,
            EventFlags eventFlags,
            ExpressionFlags expressionFlags,
            IClientData clientData
            )
        {
            return(Create(
                       name, group, description, type, text, null, Parser.UnknownLine,
                       Parser.UnknownLine, false, timeStamp, engineMode, scriptFlags,
                       engineFlags, substitutionFlags, eventFlags, expressionFlags,
                       clientData));
        }
Ejemplo n.º 16
0
            ///////////////////////////////////////////////////////////////////

            private static EngineFlags GetEngineFlags(
                NameValueCollection appSettings,
                EngineFlags @default
                )
            {
                try
                {
                    string value = Utility.GetEnvironmentVariable(
                        EngineFlags, true, true);

                    if (String.IsNullOrEmpty(value) && (appSettings != null))
                    {
                        value = appSettings[EngineFlags];
                    }

                    //
                    // NOTE: Were we able to get the value from somewhere?
                    //
                    if (!String.IsNullOrEmpty(value))
                    {
                        Result error = null;

                        object enumValue = Utility.TryParseFlagsEnum(
                            null, typeof(EngineFlags), @default.ToString(),
                            value, null, true, true, true, ref error);

                        if (enumValue is EngineFlags)
                        {
                            return((EngineFlags)enumValue);
                        }
                    }
                }
                catch
                {
                    // do nothing.
                }

                return(@default);
            }
Ejemplo n.º 17
0
 private InteractiveLoopData(
     bool debug,
     IEnumerable <string> args,
     ReturnCode code,
     BreakpointType breakpointType,
     string breakpointName,
     IToken token,
     ITraceInfo traceInfo,
     EngineFlags engineFlags,
     SubstitutionFlags substitutionFlags,
     EventFlags eventFlags,
     ExpressionFlags expressionFlags,
     HeaderFlags headerFlags,
     IClientData clientData,
     ArgumentList arguments,
     bool exit
     )
 {
     this.kind              = IdentifierKind.InteractiveLoopData;
     this.id                = AttributeOps.GetObjectId(this);
     this.debug             = debug;
     this.args              = args;
     this.code              = code;
     this.breakpointType    = breakpointType;
     this.breakpointName    = breakpointName;
     this.token             = token;
     this.traceInfo         = traceInfo;
     this.engineFlags       = engineFlags;
     this.substitutionFlags = substitutionFlags;
     this.eventFlags        = eventFlags;
     this.expressionFlags   = expressionFlags;
     this.headerFlags       = headerFlags;
     this.clientData        = clientData;
     this.arguments         = arguments;
     this.exit              = exit;
 }
Ejemplo n.º 18
0
        ///////////////////////////////////////////////////////////////////////

        #region Background Error Executor
        private static ReturnCode ExecuteBackgroundError(
            Interpreter interpreter,
            string handlerName,
            IExecute execute,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result,
            ref int errorLine
            )
        {
            if (interpreter == null)
            {
                result = "invalid interpreter";
                return(ReturnCode.Error);
            }

            //
            // NOTE: Create a new call frame for the background error handler
            //       and push it.
            //
            ICallFrame frame = interpreter.NewTrackingCallFrame(
                StringList.MakeList("bgerror", handlerName),
                CallFrameFlags.BackgroundError);

            interpreter.PushAutomaticCallFrame(frame);

            try
            {
                //
                // NOTE: Save current engine flags and then enable external
                //       execution.
                //
                EngineFlags savedEngineFlags =
                    interpreter.BeginExternalExecution();

                try
                {
                    //
                    // NOTE: If the interpreter is configured to reset the
                    //       script cancellation flags prior to executing
                    //       the background error handler, do that now.
                    //
                    if (ScriptOps.HasFlags(
                            interpreter, InterpreterFlags.BgErrorResetCancel,
                            true))
                    {
                        /* IGNORED */
                        Engine.ResetCancel(interpreter, CancelFlags.BgError);
                    }

                    //
                    // NOTE: Evaluate the script and then check the result to
                    //       see if the background error handler failed or
                    //       canceled further background error handling for
                    //       this invocation of ProcessEvents.
                    //
                    ReturnCode code;

                    code = interpreter.Execute(
                        handlerName, execute, clientData, arguments,
                        ref result);

                    //
                    // NOTE: Maybe grab the new error line number, if any.
                    //
                    if (code != ReturnCode.Ok)
                    {
                        errorLine = Interpreter.GetErrorLine(interpreter);
                    }

                    //
                    // NOTE: We are done now, return.
                    //
                    return(code);
                }
                finally
                {
                    //
                    // NOTE: Restore saved engine flags, disabling external
                    //       execution as necessary.
                    //
                    /* IGNORED */
                    interpreter.EndAndCleanupExternalExecution(
                        savedEngineFlags);
                }
            }
            finally
            {
                //
                // NOTE: Pop the original call frame that we pushed above
                //       and any intervening scope call frames that may be
                //       leftover (i.e. they were not explicitly closed).
                //
                /* IGNORED */
                interpreter.PopScopeCallFramesAndOneMore();
            }
        }
Ejemplo n.º 19
0
        ///////////////////////////////////////////////////////////////////////////////////////////////

        #region Tcl Command Callbacks
        ///////////////////////////////////////////////////////////////////////////////////////////////
        // **** WARNING ***** BEGIN CODE DIRECTLY CALLED BY THE NATIVE TCL RUNTIME ***** WARNING **** /
        ///////////////////////////////////////////////////////////////////////////////////////////////

        //
        // -- ObjCmdProc --
        //
        // When proc is invoked, the clientData and interp parameters will be copies of
        // the clientData and interp arguments given to Tcl_CreateObjCommand. Typically,
        // clientData points to an application-specific data structure that describes
        // what to do when the command procedure is invoked. Objc and objv describe the
        // arguments to the command, objc giving the number of argument objects
        // (including the command name) and objv giving the values of the arguments. The
        // objv array will contain objc values, pointing to the argument objects. Unlike
        // argv[argv] used in a string-based command procedure, objv[objc] will not
        // contain NULL. Additionally, when proc is invoked, it must not modify the
        // contents of the objv array by assigning new pointer values to any element of
        // the array (for example, objv[2] = NULL) because this will cause memory to be
        // lost and the runtime stack to be corrupted. The CONST in the declaration of
        // objv will cause ANSI-compliant compilers to report any such attempted
        // assignment as an error. However, it is acceptable to modify the internal
        // representation of any individual object argument. For instance, the user may
        // call Tcl_GetIntFromObj on objv[2] to obtain the integer representation of that
        // object; that call may change the type of the object that objv[2] points at,
        // but will not change where objv[2] points. proc must return an integer code
        // that is either TCL_OK, TCL_ERROR, TCL_RETURN, TCL_BREAK, or TCL_CONTINUE. See
        // the Tcl overview man page for details on what these codes mean. Most normal
        // commands will only return TCL_OK or TCL_ERROR. In addition, if proc needs to
        // return a non-empty result, it can call Tcl_SetObjResult to set the
        // interpreter's result. In the case of a TCL_OK return code this gives the
        // result of the command, and in the case of TCL_ERROR this gives an error
        // message. Before invoking a command procedure, Tcl_EvalObjEx sets interpreter's
        // result to point to an object representing an empty string, so simple commands
        // can return an empty result by doing nothing at all. The contents of the objv
        // array belong to Tcl and are not guaranteed to persist once proc returns: proc
        // should not modify them. Call Tcl_SetObjResult if you want to return something
        // from the objv array.
        //
        private static ReturnCode ObjCmdProc(
            IntPtr clientData,
            IntPtr interp,
            int objc,
            IntPtr objv
            )
        {
            ReturnCode code;

            try
            {
                //
                // NOTE: Rehydrate the handle from the clientData that Tcl just
                //       passed us.
                //
                GCHandle handle = GCHandle.FromIntPtr(clientData); /* throw */

                //
                // NOTE: Make sure the handle has a valid target.
                //
                if (handle.IsAllocated && (handle.Target != null))
                {
                    //
                    // NOTE: Attempt to cast the handle to a TclBridge object; if this
                    //       fails, we cannot continue to handle this call.
                    //
                    TclBridge tclBridge = handle.Target as TclBridge;

                    if (tclBridge != null)
                    {
                        Interlocked.Increment(ref tclBridge.objCmdProcLevels);

                        try
                        {
                            //
                            // NOTE: Grab the interpreter reference NOW, it may go bye bye if the
                            //       TclBridge object gets disposed.
                            //
                            Interpreter interpreter = tclBridge.interpreter;

                            if (interpreter != null)
                            {
                                //
                                // NOTE: Cache the fields of the interpreter object that we will
                                //       need to access below without holding a lock.
                                //
                                ITclApi     tclApi           = TclApi.GetTclApi(interpreter);
                                EngineFlags savedEngineFlags = interpreter.BeginExternalExecution();
                                bool        noCacheArgument  = false;

#if ARGUMENT_CACHE
                                if (Engine.HasNoCacheArgument(savedEngineFlags))
                                {
                                    noCacheArgument = true;
                                }
#endif

                                try
                                {
                                    if (tclApi != null)
                                    {
                                        Result   result  = null;
                                        IExecute execute = tclBridge.execute;

                                        if (execute != null)
                                        {
                                            ArgumentList arguments = new ArgumentList();

                                            for (int index = 0; index < objc; index++)
                                            {
                                                IntPtr objPtr =
                                                    Marshal.ReadIntPtr(objv, index * IntPtr.Size);

                                                string value =
                                                    TclWrapper.GetString(tclApi, objPtr);

                                                if (value == null)
                                                {
                                                    value = String.Empty;
                                                }

                                                arguments.Add(Argument.GetOrCreate(
                                                                  interpreter, value, noCacheArgument));
                                            }

                                            string name = (arguments.Count > 0) ? arguments[0] : null;

                                            try
                                            {
                                                code = interpreter.Execute(
                                                    name, execute, tclBridge.clientData, arguments,
                                                    ref result);
                                            }
                                            catch (Exception e)
                                            {
                                                result = String.Format(
                                                    "caught exception while executing: {0}",
                                                    e);

                                                code = ReturnCode.Error;
                                            }
                                        }
                                        else
                                        {
                                            result = "invalid execute object";
                                            code   = ReturnCode.Error;
                                        }

                                        //
                                        // NOTE: Set the Tcl interpreter result to the result of the
                                        //       Eagle command.
                                        //
                                        if (!String.IsNullOrEmpty(result))
                                        {
                                            TclWrapper.SetResult(
                                                tclApi, interp, TclWrapper.NewString(tclApi, result));
                                        }
                                        else
                                        {
                                            TclWrapper.ResetResult(tclApi, interp);
                                        }
                                    }
                                    else
                                    {
                                        //
                                        // NOTE: There is no available Tcl API object; therefore, we
                                        //       cannot set the Tcl interpreter result.
                                        //
                                        TraceOps.DebugTrace(
                                            "invalid Tcl API object",
                                            typeof(Tcl_ObjCmdProc).Name,
                                            TracePriority.MarshalError);

                                        code = ReturnCode.Error;
                                    }
                                }
                                finally
                                {
                                    /* IGNORED */
                                    interpreter.EndAndCleanupExternalExecution(savedEngineFlags);
                                }
                            }
                            else
                            {
                                //
                                // NOTE: An invalid interpreter means that we have no Tcl API object to
                                //       work with either, punt on setting the Tcl interpreter result.
                                //
                                TraceOps.DebugTrace(
                                    "invalid interpreter",
                                    typeof(Tcl_ObjCmdProc).Name,
                                    TracePriority.MarshalError);

                                code = ReturnCode.Error;
                            }
                        }
                        finally
                        {
                            Interlocked.Decrement(ref tclBridge.objCmdProcLevels);
                        }
                    }
                    else
                    {
                        //
                        // NOTE: What now?  We have no way of communicating with Tcl at this
                        //       point.
                        //
                        TraceOps.DebugTrace(
                            "invalid Tcl bridge object",
                            typeof(Tcl_ObjCmdProc).Name,
                            TracePriority.MarshalError);

                        code = ReturnCode.Error;
                    }
                }
                else
                {
                    //
                    // NOTE: Again, nothing we can do at this point.
                    //
                    TraceOps.DebugTrace(
                        "invalid GC handle",
                        typeof(Tcl_ObjCmdProc).Name,
                        TracePriority.MarshalError);

                    code = ReturnCode.Error;
                }
            }
            catch (Exception e)
            {
                //
                // NOTE: Nothing we can do here except log the failure.
                //
                TraceOps.DebugTrace(
                    e, typeof(Tcl_ObjCmdProc).Name,
                    TracePriority.NativeError);

                //
                // NOTE: At this point, we may not even be able to get to the Tcl API object
                //       we need to set the Tcl interpreter result; therefore, we are going
                //       to punt for now.
                //
                code = ReturnCode.Error;
            }

            return(code);
        }
Ejemplo n.º 20
0
        ///////////////////////////////////////////////////////////////////////

        #region IExecute Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if (arguments.Count >= 2)
                    {
                        string subCommand = arguments[1];
                        bool   tried      = false;

                        code = ScriptOps.TryExecuteSubCommandFromEnsemble(
                            interpreter, this, clientData, arguments, true,
                            false, ref subCommand, ref tried, ref result);

                        if ((code == ReturnCode.Ok) && !tried)
                        {
                            if (code == ReturnCode.Ok)
                            {
                                switch (subCommand)
                                {
                                case "command":
                                {
                                    if (arguments.Count >= 3)
                                    {
                                        OptionDictionary options = new OptionDictionary(
                                            new IOption[] {
                                                new Option(typeof(EngineFlags), OptionFlags.MustHaveEnumValue | OptionFlags.Unsafe,
                                                           Index.Invalid, Index.Invalid, "-engineflags", new Variant(interpreter.EngineFlags)),
                                                new Option(typeof(SubstitutionFlags), OptionFlags.MustHaveEnumValue, Index.Invalid, Index.Invalid, "-substitutionflags",
                                                           new Variant(interpreter.SubstitutionFlags)),
                                                new Option(null, OptionFlags.MustHaveIntegerValue, Index.Invalid, Index.Invalid, "-startindex", null),
                                                new Option(null, OptionFlags.MustHaveIntegerValue, Index.Invalid, Index.Invalid, "-characters", null),
                                                new Option(null, OptionFlags.MustHaveBooleanValue, Index.Invalid, Index.Invalid, "-nested", null),
                                                new Option(null, OptionFlags.MustHaveBooleanValue, Index.Invalid, Index.Invalid, "-noready", null),
                                                new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, Option.EndOfOptions, null)
                                            });

                                        int argumentIndex = Index.Invalid;

                                        code = interpreter.GetOptions(
                                            options, arguments, 0, 2, Index.Invalid, true, ref argumentIndex,
                                            ref result);

                                        if (code == ReturnCode.Ok)
                                        {
                                            if ((argumentIndex != Index.Invalid) &&
                                                ((argumentIndex + 1) == arguments.Count))
                                            {
                                                Variant     value       = null;
                                                EngineFlags engineFlags = interpreter.EngineFlags;

                                                if (options.IsPresent("-engineflags", ref value))
                                                {
                                                    engineFlags = (EngineFlags)value.Value;
                                                }

                                                SubstitutionFlags substitutionFlags = interpreter.SubstitutionFlags;

                                                if (options.IsPresent("-substitutionflags", ref value))
                                                {
                                                    substitutionFlags = (SubstitutionFlags)value.Value;
                                                }

                                                int startIndex = 0;

                                                if (options.IsPresent("-startindex", ref value))
                                                {
                                                    startIndex = (int)value.Value;
                                                }

                                                int characters = arguments[argumentIndex].Length;

                                                if (options.IsPresent("-characters", ref value))
                                                {
                                                    characters = (int)value.Value;
                                                }

                                                bool nested = false;

                                                if (options.IsPresent("-nested", ref value))
                                                {
                                                    nested = (bool)value.Value;
                                                }

                                                bool noReady = false;

                                                if (options.IsPresent("-noready", ref value))
                                                {
                                                    noReady = (bool)value.Value;
                                                }

                                                IParseState state = new ParseState(
                                                    engineFlags, substitutionFlags);

                                                code = Parser.ParseCommand(
                                                    interpreter, arguments[argumentIndex],
                                                    startIndex, characters, nested, state,
                                                    noReady, ref result);

                                                if (code == ReturnCode.Ok)
                                                {
                                                    //
                                                    // NOTE: Success, return the entire
                                                    //       state as a string.
                                                    //
                                                    result = state.ToString();
                                                }
                                            }
                                            else
                                            {
                                                if ((argumentIndex != Index.Invalid) &&
                                                    Option.LooksLikeOption(arguments[argumentIndex]))
                                                {
                                                    result = OptionDictionary.BadOption(options, arguments[argumentIndex]);
                                                }
                                                else
                                                {
                                                    result = "wrong # args: should be \"parse command ?options? text\"";
                                                }

                                                code = ReturnCode.Error;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        result = "wrong # args: should be \"parse command ?options? text\"";
                                        code   = ReturnCode.Error;
                                    }
                                    break;
                                }

                                case "expression":
                                {
                                    if (arguments.Count >= 3)
                                    {
                                        OptionDictionary options = new OptionDictionary(
                                            new IOption[] {
                                                new Option(typeof(EngineFlags), OptionFlags.MustHaveEnumValue | OptionFlags.Unsafe,
                                                           Index.Invalid, Index.Invalid, "-engineflags", new Variant(interpreter.EngineFlags)),
                                                new Option(typeof(SubstitutionFlags), OptionFlags.MustHaveEnumValue, Index.Invalid, Index.Invalid, "-substitutionflags",
                                                           new Variant(interpreter.SubstitutionFlags)),
                                                new Option(null, OptionFlags.MustHaveIntegerValue, Index.Invalid, Index.Invalid, "-startindex", null),
                                                new Option(null, OptionFlags.MustHaveIntegerValue, Index.Invalid, Index.Invalid, "-characters", null),
                                                new Option(null, OptionFlags.MustHaveBooleanValue, Index.Invalid, Index.Invalid, "-noready", null),
                                                new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, Option.EndOfOptions, null)
                                            });

                                        int argumentIndex = Index.Invalid;

                                        code = interpreter.GetOptions(
                                            options, arguments, 0, 2, Index.Invalid, true, ref argumentIndex,
                                            ref result);

                                        if (code == ReturnCode.Ok)
                                        {
                                            if ((argumentIndex != Index.Invalid) &&
                                                ((argumentIndex + 1) == arguments.Count))
                                            {
                                                Variant     value       = null;
                                                EngineFlags engineFlags = interpreter.EngineFlags;

                                                if (options.IsPresent("-engineflags", ref value))
                                                {
                                                    engineFlags = (EngineFlags)value.Value;
                                                }

                                                SubstitutionFlags substitutionFlags = interpreter.SubstitutionFlags;

                                                if (options.IsPresent("-substitutionflags", ref value))
                                                {
                                                    substitutionFlags = (SubstitutionFlags)value.Value;
                                                }

                                                int startIndex = 0;

                                                if (options.IsPresent("-startindex", ref value))
                                                {
                                                    startIndex = (int)value.Value;
                                                }

                                                int characters = arguments[argumentIndex].Length;

                                                if (options.IsPresent("-characters", ref value))
                                                {
                                                    characters = (int)value.Value;
                                                }

                                                bool noReady = false;

                                                if (options.IsPresent("-noready", ref value))
                                                {
                                                    noReady = (bool)value.Value;
                                                }

                                                IParseState state = new ParseState(
                                                    engineFlags, substitutionFlags);

                                                code = ExpressionParser.ParseExpression(
                                                    interpreter, arguments[argumentIndex],
                                                    startIndex, characters, state, noReady,
                                                    ref result);

                                                if (code == ReturnCode.Ok)
                                                {
                                                    //
                                                    // NOTE: Success, return the entire
                                                    //       state as a string.
                                                    //
                                                    result = state.ToString();
                                                }
                                            }
                                            else
                                            {
                                                if ((argumentIndex != Index.Invalid) &&
                                                    Option.LooksLikeOption(arguments[argumentIndex]))
                                                {
                                                    result = OptionDictionary.BadOption(options, arguments[argumentIndex]);
                                                }
                                                else
                                                {
                                                    result = "wrong # args: should be \"parse expression ?options? text\"";
                                                }

                                                code = ReturnCode.Error;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        result = "wrong # args: should be \"parse expression ?options? text\"";
                                        code   = ReturnCode.Error;
                                    }
                                    break;
                                }

                                case "options":
                                {
                                    if (arguments.Count >= 4)
                                    {
                                        OptionDictionary options = new OptionDictionary(
                                            new IOption[] {
                                                new Option(typeof(OptionBehaviorFlags), OptionFlags.MustHaveEnumValue, Index.Invalid, Index.Invalid, "-flags",
                                                           new Variant(OptionBehaviorFlags.Default)),
                                                new Option(null, OptionFlags.MustHaveValue, Index.Invalid, Index.Invalid, "-optionsvar", null),
                                                new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-indexes", null),
                                                new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-allowinteger", null),
                                                new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-strict", null),
                                                new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-verbose", null),
                                                new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-nocase", null),
                                                new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-novalue", null),
                                                new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-noset", null),
                                                new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-noready", null),
                                                new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-simple", null),
                                                new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, Option.EndOfOptions, null)
                                            });

                                        int argumentIndex = Index.Invalid;

                                        code = interpreter.GetOptions(
                                            options, arguments, 0, 2, Index.Invalid, true, ref argumentIndex,
                                            ref result);

                                        if (code == ReturnCode.Ok)
                                        {
                                            if ((argumentIndex != Index.Invalid) &&
                                                ((argumentIndex + 2) == arguments.Count))
                                            {
                                                Variant value          = null;
                                                string  optionsVarName = Vars.OptionSet.Options;

                                                if (options.IsPresent("-optionsvar", ref value))
                                                {
                                                    optionsVarName = value.ToString();
                                                }

                                                OptionBehaviorFlags flags = OptionBehaviorFlags.Default;

                                                if (options.IsPresent("-flags", ref value))
                                                {
                                                    flags = (OptionBehaviorFlags)value.Value;
                                                }

                                                bool indexes = false;

                                                if (options.IsPresent("-indexes"))
                                                {
                                                    indexes = true;
                                                }

                                                bool allowInteger = false;

                                                if (options.IsPresent("-allowinteger"))
                                                {
                                                    allowInteger = true;
                                                }

                                                bool strict = false;

                                                if (options.IsPresent("-strict"))
                                                {
                                                    strict = true;
                                                }

                                                bool verbose = false;

                                                if (options.IsPresent("-verbose"))
                                                {
                                                    verbose = true;
                                                }

                                                bool noCase = false;

                                                if (options.IsPresent("-nocase"))
                                                {
                                                    noCase = true;
                                                }

                                                bool noValue = false;

                                                if (options.IsPresent("-novalue"))
                                                {
                                                    noValue = true;
                                                }

                                                bool noSet = false;

                                                if (options.IsPresent("-noset"))
                                                {
                                                    noSet = true;
                                                }

                                                bool noReady = false;

                                                if (options.IsPresent("-noready"))
                                                {
                                                    noReady = true;
                                                }

                                                bool simple = false;

                                                if (options.IsPresent("-simple"))
                                                {
                                                    simple = true;
                                                }

                                                OptionDictionary newOptions  = null;
                                                AppDomain        appDomain   = interpreter.GetAppDomain();
                                                CultureInfo      cultureInfo = interpreter.CultureInfo;

                                                if (simple)
                                                {
                                                    newOptions = OptionDictionary.FromString(
                                                        interpreter, arguments[argumentIndex],
                                                        appDomain, Value.GetTypeValueFlags(
                                                            allowInteger, strict, verbose, noCase),
                                                        cultureInfo, ref result);
                                                }
                                                else
                                                {
                                                    newOptions = OptionDictionary.FromString(
                                                        interpreter, arguments[argumentIndex],
                                                        appDomain, allowInteger, strict, verbose,
                                                        noCase, cultureInfo, ref result);
                                                }

                                                if (newOptions != null)
                                                {
                                                    StringList list = StringList.FromString(
                                                        arguments[argumentIndex + 1], ref result);

                                                    if (list != null)
                                                    {
                                                        ArgumentList newArguments = new ArgumentList(list);

                                                        int nextIndex = Index.Invalid;
                                                        int endIndex  = Index.Invalid;

                                                        code = interpreter.GetOptions(
                                                            newOptions, newArguments, 0, 0, Index.Invalid, flags,
                                                            noCase, noValue, noSet, ref nextIndex, ref endIndex,
                                                            ref result);

                                                        if (code == ReturnCode.Ok)
                                                        {
                                                            VariableFlags variableFlags = VariableFlags.None;

                                                            if (noReady)
                                                            {
                                                                variableFlags |= VariableFlags.NoReady;
                                                            }

                                                            if (indexes)
                                                            {
                                                                code = interpreter.SetVariableValue2(
                                                                    variableFlags, optionsVarName,
                                                                    Vars.OptionSet.NextIndex, nextIndex.ToString(),
                                                                    null, ref result);

                                                                if (code == ReturnCode.Ok)
                                                                {
                                                                    code = interpreter.SetVariableValue2(
                                                                        variableFlags, optionsVarName,
                                                                        Vars.OptionSet.EndIndex, endIndex.ToString(),
                                                                        null, ref result);
                                                                }
                                                            }

                                                            if (code == ReturnCode.Ok)
                                                            {
                                                                foreach (KeyValuePair <string, IOption> pair in newOptions)
                                                                {
                                                                    IOption option = pair.Value;

                                                                    if (option == null)
                                                                    {
                                                                        continue;
                                                                    }

                                                                    if (option.IsIgnored(newOptions))
                                                                    {
                                                                        continue;
                                                                    }

                                                                    /* REUSED */
                                                                    value = null;

                                                                    bool present = option.IsPresent(newOptions, ref value);

                                                                    if (present &&
                                                                        !option.CanBePresent(newOptions, ref result))
                                                                    {
                                                                        code = ReturnCode.Error;
                                                                        break;
                                                                    }

                                                                    code = interpreter.SetVariableValue2(
                                                                        variableFlags, optionsVarName, pair.Key,
                                                                        present.ToString(), null, ref result);

                                                                    if (code != ReturnCode.Ok)
                                                                    {
                                                                        break;
                                                                    }

                                                                    if (option.MustHaveValue(newOptions))
                                                                    {
                                                                        //
                                                                        // NOTE: If the option was not actually present,
                                                                        //       grab and use the default value instead.
                                                                        //
                                                                        if (!present)
                                                                        {
                                                                            value = option.Value;
                                                                        }

                                                                        //
                                                                        // NOTE: Only set the value if the option was
                                                                        //       actually present OR there is a bonafide
                                                                        //       default value.
                                                                        //
                                                                        if (present || (value != null))
                                                                        {
                                                                            string index = pair.Key +
                                                                                           Characters.Comma + Vars.OptionSet.Value;

                                                                            code = interpreter.SetVariableValue2(
                                                                                variableFlags, optionsVarName, index,
                                                                                (value != null) ? value.ToString() : null,
                                                                                null, ref result);

                                                                            if (code != ReturnCode.Ok)
                                                                            {
                                                                                break;
                                                                            }
                                                                        }
                                                                    }
                                                                }

                                                                if (code == ReturnCode.Ok)
                                                                {
                                                                    result = String.Empty;
                                                                }
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        code = ReturnCode.Error;
                                                    }
                                                }
                                                else
                                                {
                                                    code = ReturnCode.Error;
                                                }
                                            }
                                            else
                                            {
                                                if ((argumentIndex != Index.Invalid) &&
                                                    Option.LooksLikeOption(arguments[argumentIndex]))
                                                {
                                                    result = OptionDictionary.BadOption(options, arguments[argumentIndex]);
                                                }
                                                else
                                                {
                                                    result = "wrong # args: should be \"parse options ?options? optionList argumentList\"";
                                                }

                                                code = ReturnCode.Error;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        result = "wrong # args: should be \"parse options ?options? options optionList argumentList\"";
                                        code   = ReturnCode.Error;
                                    }
                                    break;
                                }

                                case "script":
                                {
                                    if (arguments.Count >= 3)
                                    {
                                        OptionDictionary options = new OptionDictionary(
                                            new IOption[] {
                                                new Option(typeof(EngineFlags), OptionFlags.MustHaveEnumValue | OptionFlags.Unsafe,
                                                           Index.Invalid, Index.Invalid, "-engineflags", new Variant(interpreter.EngineFlags)),
                                                new Option(typeof(SubstitutionFlags), OptionFlags.MustHaveEnumValue, Index.Invalid, Index.Invalid, "-substitutionflags",
                                                           new Variant(interpreter.SubstitutionFlags)),
                                                new Option(null, OptionFlags.MustHaveValue, Index.Invalid, Index.Invalid, "-filename", null),
                                                new Option(null, OptionFlags.MustHaveIntegerValue, Index.Invalid, Index.Invalid, "-currentline", null),
                                                new Option(null, OptionFlags.MustHaveIntegerValue, Index.Invalid, Index.Invalid, "-startindex", null),
                                                new Option(null, OptionFlags.MustHaveIntegerValue, Index.Invalid, Index.Invalid, "-characters", null),
                                                new Option(null, OptionFlags.MustHaveBooleanValue, Index.Invalid, Index.Invalid, "-nested", null),
                                                new Option(null, OptionFlags.MustHaveBooleanValue, Index.Invalid, Index.Invalid, "-syntax", null),
                                                new Option(null, OptionFlags.MustHaveBooleanValue, Index.Invalid, Index.Invalid, "-strict", null),
                                                new Option(null, OptionFlags.MustHaveBooleanValue, Index.Invalid, Index.Invalid, "-roundtrip", null),
                                                new Option(null, OptionFlags.MustHaveBooleanValue, Index.Invalid, Index.Invalid, "-noready", null),
                                                new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, Option.EndOfOptions, null)
                                            });

                                        int argumentIndex = Index.Invalid;

                                        code = interpreter.GetOptions(
                                            options, arguments, 0, 2, Index.Invalid, true, ref argumentIndex,
                                            ref result);

                                        if (code == ReturnCode.Ok)
                                        {
                                            if ((argumentIndex != Index.Invalid) &&
                                                ((argumentIndex + 1) == arguments.Count))
                                            {
                                                Variant     value       = null;
                                                EngineFlags engineFlags = interpreter.EngineFlags;

                                                if (options.IsPresent("-engineflags", ref value))
                                                {
                                                    engineFlags = (EngineFlags)value.Value;
                                                }

                                                SubstitutionFlags substitutionFlags = interpreter.SubstitutionFlags;

                                                if (options.IsPresent("-substitutionflags", ref value))
                                                {
                                                    substitutionFlags = (SubstitutionFlags)value.Value;
                                                }

                                                string fileName = null;

                                                if (options.IsPresent("-filename", ref value))
                                                {
                                                    fileName = value.ToString();
                                                }

                                                int currentLine = Parser.StartLine;

                                                if (options.IsPresent("-currentline", ref value))
                                                {
                                                    currentLine = (int)value.Value;
                                                }

                                                int startIndex = 0;

                                                if (options.IsPresent("-startindex", ref value))
                                                {
                                                    startIndex = (int)value.Value;
                                                }

                                                int characters = arguments[argumentIndex].Length;

                                                if (options.IsPresent("-characters", ref value))
                                                {
                                                    characters = (int)value.Value;
                                                }

                                                bool nested = false;

                                                if (options.IsPresent("-nested", ref value))
                                                {
                                                    nested = (bool)value.Value;
                                                }

                                                bool syntax = false;

                                                if (options.IsPresent("-syntax", ref value))
                                                {
                                                    syntax = (bool)value.Value;
                                                }

                                                bool strict = false;

                                                if (options.IsPresent("-strict", ref value))
                                                {
                                                    strict = (bool)value.Value;
                                                }

                                                bool roundTrip = false;

                                                if (options.IsPresent("-roundtrip", ref value))
                                                {
                                                    roundTrip = (bool)value.Value;
                                                }

                                                bool noReady = false;

                                                if (options.IsPresent("-noready", ref value))
                                                {
                                                    noReady = (bool)value.Value;
                                                }

                                                IParseState state = new ParseState(
                                                    engineFlags, substitutionFlags);

                                                TokenList tokens = null;

                                                code = Parser.ParseScript(
                                                    interpreter, fileName, currentLine,
                                                    arguments[argumentIndex], startIndex,
                                                    characters, engineFlags, substitutionFlags,
                                                    nested, noReady, syntax, strict, ref state,
                                                    ref tokens, ref result);

                                                if (code == ReturnCode.Ok)
                                                {
                                                    if (roundTrip)
                                                    {
                                                        //
                                                        // NOTE: Return only the tokens that
                                                        //       are absolutely necessary to
                                                        //       rebuild the script text.
                                                        //
                                                        TokenList newTokens = new TokenList();

                                                        for (int index = 0; index < tokens.Count; index++)
                                                        {
                                                            IToken token = tokens[index];

                                                            if (token.Type == TokenType.Variable)
                                                            {
                                                                index += token.Components;
                                                            }
                                                            else if ((token.Type != TokenType.Separator) &&
                                                                     (token.Components != 0))
                                                            {
                                                                continue;
                                                            }

                                                            newTokens.Add(token);
                                                        }

                                                        result = newTokens.ToString();
                                                    }
                                                    else
                                                    {
                                                        //
                                                        // NOTE: Replace final token list
                                                        //       with the one we have been
                                                        //       building.
                                                        //
                                                        state.Tokens = tokens;

                                                        //
                                                        // NOTE: Success, return the entire
                                                        //       state as a string.
                                                        //
                                                        result = state.ToString();
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                if ((argumentIndex != Index.Invalid) &&
                                                    Option.LooksLikeOption(arguments[argumentIndex]))
                                                {
                                                    result = OptionDictionary.BadOption(options, arguments[argumentIndex]);
                                                }
                                                else
                                                {
                                                    result = "wrong # args: should be \"parse script ?options? text\"";
                                                }

                                                code = ReturnCode.Error;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        result = "wrong # args: should be \"parse script ?options? text\"";
                                        code   = ReturnCode.Error;
                                    }
                                    break;
                                }

                                default:
                                {
                                    result = ScriptOps.BadSubCommand(
                                        interpreter, null, null, subCommand, this, null, null);

                                    code = ReturnCode.Error;
                                    break;
                                }
                                }
                            }
                        }
                    }
                    else
                    {
                        result = "wrong # args: should be \"parse type ?arg ...?\"";
                        code   = ReturnCode.Error;
                    }
                }
                else
                {
                    result = "invalid argument list";
                    code   = ReturnCode.Error;
                }
            }
            else
            {
                result = "invalid interpreter";
                code   = ReturnCode.Error;
            }

            return(code);
        }
Ejemplo n.º 21
0
        public IEnumerable <IRenderable> UpdatePerFrameResources(IRendererContext context, IEnumerable <IRenderable> renderables)
        {
            var c  = (VeldridRendererContext)context;
            var cl = c.CommandList;
            var gd = c.GraphicsDevice;
            var sc = c.SceneContext;

            ITextureManager      textureManager = Resolve <ITextureManager>();
            IDeviceObjectManager objectManager  = Resolve <IDeviceObjectManager>();
            EngineFlags          engineFlags    = Resolve <IEngineSettings>().Flags;

            foreach (var renderable in renderables)
            {
                var sprite = (MultiSprite)renderable;
                if (sprite.ActiveInstances == 0)
                {
                    continue;
                }

                var shaderKey = new SpriteShaderKey(sprite, engineFlags);
                if (!_pipelines.ContainsKey(shaderKey))
                {
                    _pipelines.Add(shaderKey, BuildPipeline(gd, sc, shaderKey));
                }

                uint bufferSize = (uint)sprite.Instances.Length * SpriteInstanceData.StructSize;
                var  buffer     = objectManager.Get <DeviceBuffer>((sprite, sprite));
                if (buffer?.SizeInBytes != bufferSize)
                {
                    buffer      = gd.ResourceFactory.CreateBuffer(new BufferDescription(bufferSize, BufferUsage.VertexBuffer));
                    buffer.Name = $"B_SpriteInst:{sprite.Name}";
                    PerfTracker.IncrementFrameCounter("Create InstanceBuffer");
                    objectManager.Set((sprite, sprite), buffer);
                }

                if (sprite.InstancesDirty)
                {
                    cl.UpdateBuffer(buffer, 0, sprite.Instances);
                    PerfTracker.IncrementFrameCounter("Update InstanceBuffers");
                }

                textureManager?.PrepareTexture(sprite.Key.Texture, context);
                TextureView textureView = (TextureView)textureManager?.GetTexture(sprite.Key.Texture);

                var resourceSet = objectManager.Get <ResourceSet>((sprite, textureView));
                if (resourceSet == null)
                {
                    resourceSet = gd.ResourceFactory.CreateResourceSet(new ResourceSetDescription(
                                                                           _perSpriteResourceLayout,
                                                                           gd.PointSampler,
                                                                           textureView,
                                                                           _uniformBuffer));
                    resourceSet.Name = $"RS_Sprite:{sprite.Key.Texture.Name}";
                    PerfTracker.IncrementFrameCounter("Create ResourceSet");
                    objectManager.Set((sprite, textureView), resourceSet);
                }

                sprite.InstancesDirty = false;
                yield return(sprite);
            }

            Resolve <ISpriteManager>().Cleanup();
        }
Ejemplo n.º 22
0
 public EngineCore(EngineFlags flags)
 {
 }
Ejemplo n.º 23
0
        ///////////////////////////////////////////////////////////////////////

        #region IExecute Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    IScriptLocation location = null;

                    code = ScriptOps.GetAndCheckProcedureLocation(
                        interpreter, this, ref location, ref result);

                    if (code == ReturnCode.Ok)
                    {
                        string       procedureName      = this.Name;
                        ArgumentList procedureArguments = this.Arguments;

                        if (procedureArguments != null)
                        {
                            bool hasArgs      = procedureArguments.IsVariadic(true);
                            int  totalArgs    = hasArgs ? procedureArguments.Count - 1 : procedureArguments.Count;
                            int  optionalArgs = procedureArguments.GetOptionalCount();

                            if ((arguments.Count > 0) &&
                                ((((arguments.Count - 1) >= (totalArgs - optionalArgs)) &&
                                  ((arguments.Count - 1) <= totalArgs)) ||
                                 (hasArgs && ((arguments.Count - 1) >= (totalArgs - optionalArgs)))))
                            {
                                ICallFrame frame = null;

                                try
                                {
                                    frame = interpreter.NewProcedureCallFrame(
                                        procedureName, CallFrameFlags.Procedure,
                                        null, this, arguments);

                                    VariableDictionary variables = frame.Variables;

                                    frame.ProcedureArguments = new ArgumentList(arguments[0]);

                                    for (int argumentIndex = 0; argumentIndex < procedureArguments.Count; argumentIndex++)
                                    {
                                        string varName = procedureArguments[argumentIndex].Name;

                                        if (!variables.ContainsKey(varName))
                                        {
                                            ArgumentFlags flags = ArgumentFlags.None;
                                            object        varValue;

                                            if (hasArgs && (argumentIndex == (procedureArguments.Count - 1)))
                                            {
                                                //
                                                // NOTE: This argument is part of an argument list.
                                                //
                                                flags |= ArgumentFlags.ArgumentList;

                                                //
                                                // NOTE: Build the list for the final formal argument value,
                                                //       which consists of all the remaining argument values.
                                                //
                                                ArgumentList argsArguments = new ArgumentList();

                                                for (int argsArgumentIndex = argumentIndex + 1;
                                                     argsArgumentIndex < arguments.Count; argsArgumentIndex++)
                                                {
                                                    //
                                                    // NOTE: Sync up the argument name and flags for use when
                                                    //       debugging (below).
                                                    //
                                                    Argument argsArgument = Argument.GetOrCreate(
                                                        interpreter, arguments[argsArgumentIndex].Flags | flags,
                                                        String.Format("{0}{1}{2}", varName, Characters.Space,
                                                                      argsArguments.Count), arguments[argsArgumentIndex],
                                                        interpreter.HasNoCacheArgument());

                                                    argsArguments.Add(argsArgument);
                                                }

                                                varValue = argsArguments;
                                            }
                                            else
                                            {
                                                if ((argumentIndex + 1) < arguments.Count)
                                                {
                                                    //
                                                    // NOTE: Sync up the argument name for use when
                                                    //       debugging (below) and use the value
                                                    //       supplied by the caller.
                                                    //
                                                    varValue = Argument.GetOrCreate(interpreter,
                                                                                    arguments[argumentIndex + 1].Flags | flags,
                                                                                    varName, arguments[argumentIndex + 1],
                                                                                    interpreter.HasNoCacheArgument());
                                                }
                                                else
                                                {
                                                    //
                                                    // NOTE: We cannot sync up the argument name here
                                                    //       because we are out-of-bounds on that list
                                                    //       and it cannot be extended (i.e. it would
                                                    //       break [info level]); therefore, we punt
                                                    //       on that for now.  Use the default value
                                                    //       for this argument, if any; otherwise, use
                                                    //       an empty string.
                                                    //
                                                    object @default = procedureArguments[argumentIndex].Default;
                                                    varValue = (@default != null) ? @default : Argument.NoValue;
                                                }
                                            }

                                            code = interpreter.SetVariableValue2(VariableFlags.Argument, frame,
                                                                                 varName, varValue, ref result);

                                            if (code != ReturnCode.Ok)
                                            {
                                                break;
                                            }

                                            //
                                            // BUGFIX: Now, also keep track of this argument in the procedure
                                            //         arguments list.  Primarily because we do not want to
                                            //         have to redo this logic later (i.e. for [scope]).
                                            //
                                            frame.ProcedureArguments.Add(Argument.GetOrCreate(
                                                                             interpreter, flags, varName, varValue,
                                                                             interpreter.HasNoCacheArgument()));
                                        }
                                    }

                                    //
                                    // NOTE: Make sure we succeeded in creating the call frame.
                                    //
                                    if (code == ReturnCode.Ok)
                                    {
                                        ICallFrame savedFrame = null;
                                        interpreter.PushProcedureCallFrame(frame, true, ref savedFrame);

                                        try
                                        {
#if DEBUGGER && DEBUGGER_EXECUTE
                                            if (DebuggerOps.CanHitBreakpoints(interpreter,
                                                                              EngineFlags.None, BreakpointType.BeforeProcedureBody))
                                            {
                                                code = interpreter.CheckBreakpoints(
                                                    code, BreakpointType.BeforeProcedureBody, procedureName,
                                                    null, null, this, null, clientData, arguments,
                                                    ref result);
                                            }
#endif

                                            if (code == ReturnCode.Ok)
                                            {
                                                bool locked = false;

                                                try
                                                {
                                                    bool atomic = EntityOps.IsAtomic(this);

                                                    if (atomic)
                                                    {
                                                        interpreter.InternalTryLock(ref locked); /* TRANSACTIONAL */
                                                    }
                                                    if (!atomic || locked)
                                                    {
#if ARGUMENT_CACHE || PARSE_CACHE
                                                        EngineFlags savedEngineFlags = EngineFlags.None;
                                                        bool        nonCaching       = EntityOps.IsNonCaching(this);

                                                        if (nonCaching)
                                                        {
                                                            interpreter.BeginProcedureBodyNoCaching(
                                                                ref savedEngineFlags);
                                                        }

                                                        try
                                                        {
#endif
                                                        string body = this.Body;

                                                        interpreter.ReturnCode = ReturnCode.Ok;

                                                        code = interpreter.EvaluateScript(
                                                            body, location, ref result);
#if ARGUMENT_CACHE || PARSE_CACHE
                                                    }
                                                    finally
                                                    {
                                                        if (nonCaching)
                                                        {
                                                            interpreter.EndProcedureBodyNoCaching(
                                                                ref savedEngineFlags);
                                                        }
                                                    }
#endif
                                                    }
                                                    else
                                                    {
                                                        result = "could not lock interpreter";
                                                        code   = ReturnCode.Error;
                                                    }
                                                }
                                                finally
                                                {
                                                    interpreter.InternalExitLock(ref locked); /* TRANSACTIONAL */
                                                }

#if DEBUGGER && DEBUGGER_EXECUTE
                                                if (DebuggerOps.CanHitBreakpoints(interpreter,
                                                                                  EngineFlags.None, BreakpointType.AfterProcedureBody))
                                                {
                                                    code = interpreter.CheckBreakpoints(
                                                        code, BreakpointType.AfterProcedureBody, procedureName,
                                                        null, null, this, null, clientData, arguments,
                                                        ref result);
                                                }
#endif

                                                //
                                                // BUGFIX: If an opaque object handle is being returned, add
                                                //         a reference to it now.
                                                //
                                                if ((code == ReturnCode.Ok) || (code == ReturnCode.Return))
                                                {
                                                    code = interpreter.AddObjectReference(
                                                        code, result, ObjectReferenceType.Return,
                                                        ref result);
                                                }

                                                if (code == ReturnCode.Return)
                                                {
                                                    code = Engine.UpdateReturnInformation(interpreter);
                                                }
                                                else if (code == ReturnCode.Error)
                                                {
                                                    Engine.AddErrorInformation(interpreter, result,
                                                                               String.Format("{0}    (procedure \"{1}\" line {2})",
                                                                                             Environment.NewLine, FormatOps.Ellipsis(procedureName),
                                                                                             Interpreter.GetErrorLine(interpreter)));
                                                }
                                            }
                                        }
                                        finally
                                        {
                                            /* IGNORED */
                                            interpreter.PopProcedureCallFrame(frame, ref savedFrame);
                                        }
                                    }
                                }
                                finally
                                {
                                    if (frame != null)
                                    {
                                        IDisposable disposable = frame as IDisposable;

                                        if (disposable != null)
                                        {
                                            disposable.Dispose();
                                            disposable = null;
                                        }

                                        frame = null;
                                    }
                                }
                            }
                            else
                            {
                                if (procedureArguments.Count > 0)
                                {
                                    result = String.Format(
                                        "wrong # args: should be \"{0} {1}\"",
                                        Parser.Quote(procedureName),
                                        procedureArguments.ToRawString(ToStringFlags.Decorated,
                                                                       Characters.Space.ToString()));
                                }
                                else
                                {
                                    result = String.Format(
                                        "wrong # args: should be \"{0}\"",
                                        Parser.Quote(procedureName));
                                }

                                code = ReturnCode.Error;
                            }
                        }
                        else
                        {
                            result = "invalid procedure argument list";
                            code   = ReturnCode.Error;
                        }
                    }
                }
                else
                {
                    result = "invalid argument list";
                    code   = ReturnCode.Error;
                }
            }
            else
            {
                result = "invalid interpreter";
                code   = ReturnCode.Error;
            }

            return(code);
        }
Ejemplo n.º 24
0
        ///////////////////////////////////////////////////////////////////////

        private static ReturnCode SetupInterpreter(
            NameValueCollection appSettings,
            Interpreter interpreter,
            ref Result result
            )
        {
            try
            {
                string value = Utility.GetEnvironmentVariable(
                    Settings.SetupScript, true, true);

                if ((value == null) && (appSettings != null))
                {
                    value = appSettings[Settings.SetupScript];
                }

                //
                // NOTE: Were we able to get the value from somewhere?
                //
                if (value != null)
                {
                    //
                    // NOTE: Get the normal engine flags for script
                    //       evaluation.
                    //
                    EngineFlags engineFlags = Settings.GetEngineFlags(
                        appSettings);

                    //
                    // NOTE: If the setup script is considered "trusted"
                    //       add the IgnoreHidden flag to override the
                    //       normal safe interpreter behavior.
                    //
                    if (Settings.GetTrustedSetup(appSettings))
                    {
                        engineFlags |= EngineFlags.IgnoreHidden;
                    }

                    //
                    // NOTE: Evaluate the setup script and return the
                    //       results to the caller verbatim.
                    //
                    return(Engine.EvaluateScript(
                               interpreter, value, engineFlags,
                               Settings.GetSubstitutionFlags(appSettings),
                               Settings.GetEventFlags(appSettings),
                               Settings.GetExpressionFlags(appSettings),
                               ref result));
                }

                //
                // NOTE: No setup script to evaluate, this is fine.
                //
                return(ReturnCode.Ok);
            }
            catch (Exception e)
            {
                result = e;
            }

            return(ReturnCode.Error);
        }
Ejemplo n.º 25
0
        ///////////////////////////////////////////////////////////////////////

#if XML
        /* INTERNAL STATIC OK */
        internal static IScript CreateFromXmlNode( /* NOTE: Engine use only. */
            string type,
            XmlNode node,
            EngineMode engineMode,
            ScriptFlags scriptFlags,
            EngineFlags engineFlags,
            SubstitutionFlags substitutionFlags,
            EventFlags eventFlags,
            ExpressionFlags expressionFlags,
            IClientData clientData,
            ref Result error
            )
        {
            try
            {
                XmlElement element = node as XmlElement;

                if (element != null)
                {
                    foreach (string attribute in _XmlAttribute.RequiredList)
                    {
                        if ((attribute != null) && !element.HasAttribute(attribute))
                        {
                            error = String.Format(
                                "missing required attribute \"{0}\"",
                                attribute);

                            return(null);
                        }
                    }

                    /* REQUIRED */
                    Guid id = element.HasAttribute(_XmlAttribute.Id) ?
                              new Guid(element.GetAttribute(_XmlAttribute.Id)) : Guid.Empty;

                    /* REQUIRED */
                    XmlBlockType blockType = element.HasAttribute(_XmlAttribute.Type) ?
                                             (XmlBlockType)Enum.Parse(typeof(XmlBlockType),
                                                                      element.GetAttribute(_XmlAttribute.Type), true) :
                                             XmlBlockType.None;

                    /* REQUIRED */
                    string text = element.InnerText;

                    /* OPTIONAL */
                    string name = element.HasAttribute(_XmlAttribute.Name) ?
                                  element.GetAttribute(_XmlAttribute.Name) : null;

                    /* OPTIONAL */
                    string group = element.HasAttribute(_XmlAttribute.Group) ?
                                   element.GetAttribute(_XmlAttribute.Group) : null;

                    /* OPTIONAL */
                    string description = element.HasAttribute(_XmlAttribute.Description) ?
                                         element.GetAttribute(_XmlAttribute.Description) : null;

                    /* OPTIONAL */
                    DateTime timeStamp = element.HasAttribute(_XmlAttribute.TimeStamp) ?
                                         DateTime.Parse(element.GetAttribute(_XmlAttribute.TimeStamp)).ToUniversalTime() :
                                         DateTime.MinValue;

                    /* OPTIONAL */
                    string publicKeyToken = element.HasAttribute(_XmlAttribute.PublicKeyToken) ?
                                            element.GetAttribute(_XmlAttribute.PublicKeyToken) : null;

                    /* OPTIONAL */
                    byte[] signature = element.HasAttribute(_XmlAttribute.Signature) ?
                                       Convert.FromBase64String(
                        element.GetAttribute(_XmlAttribute.Signature)) : null;

                    //
                    // NOTE: Create the script using the values extracted from the XML element.
                    //
                    return(PrivateCreate(
                               id, name, group, description, type, text, null, Parser.UnknownLine,
                               Parser.UnknownLine, false, blockType, timeStamp, publicKeyToken,
                               signature, engineMode, scriptFlags, engineFlags, substitutionFlags,
                               eventFlags, expressionFlags, clientData));
                }
                else
                {
                    error = "xml node is not an element";
                }
            }
            catch (Exception e)
            {
                error = e;
            }

            return(null);
        }
Ejemplo n.º 26
0
        ///////////////////////////////////////////////////////////////////////

        private /* protected virtual */ void Dispose(
            bool disposing
            )
        {
            TraceOps.DebugTrace(String.Format(
                                    "Dispose: disposing = {0}, interpreter = {1}, disposed = {2}",
                                    disposing, FormatOps.InterpreterNoThrow(interpreter), disposed),
                                typeof(EngineContext).Name, TracePriority.CleanupDebug);

            if (!disposed)
            {
                if (disposing)
                {
                    ////////////////////////////////////
                    // dispose managed resources here...
                    ////////////////////////////////////

                    interpreter = null; /* NOT OWNED: Do not dispose. */
                    threadId    = 0;

                    ///////////////////////////////////////////////////////////

#if DEBUGGER
                    interactiveLoopCallback = null;
#endif

                    ///////////////////////////////////////////////////////////

#if SHELL
                    argumentCallback            = null;
                    evaluateScriptCallback      = null;
                    evaluateFileCallback        = null;
                    evaluateEncodedFileCallback = null;
#endif

                    ///////////////////////////////////////////////////////////

                    levels        = 0;
                    maximumLevels = 0;

                    scriptLevels        = 0;
                    maximumScriptLevels = 0;

                    parserLevels        = 0;
                    maximumParserLevels = 0;

                    expressionLevels        = 0;
                    maximumExpressionLevels = 0;

                    previousLevels   = 0;
                    catchLevels      = 0;
                    unknownLevels    = 0;
                    traceLevels      = 0;
                    subCommandLevels = 0;

#if ARGUMENT_CACHE
                    cacheArgument = null;
#endif

#if DEBUGGER
                    watchpointLevels = 0;
#endif

#if NOTIFY || NOTIFY_OBJECT
                    notifyLevels = 0;
                    notifyTypes  = NotifyType.None;
                    notifyFlags  = NotifyFlags.None;
#endif

                    policyLevels = 0;
                    testLevels   = 0;

#if DEBUGGER
                    isDebuggerExiting = false;
#endif

                    stackOverflow = false;

#if DEBUGGER
                    if (debugger != null)
                    {
                        IDisposable disposable = debugger as IDisposable;

                        if (disposable != null)
                        {
                            disposable.Dispose();
                            disposable = null;
                        }

                        debugger = null;
                    }
#endif

#if PREVIOUS_RESULT
                    previousResult = null;
#endif

                    engineFlags    = EngineFlags.None;
                    parseState     = null;
                    returnCode     = ReturnCode.Ok;
                    errorLine      = 0;
                    errorCode      = null;
                    errorInfo      = null;
                    errorFrames    = 0;
                    exception      = null;
                    scriptLocation = null;

                    ///////////////////////////////////////////////////////////

                    if (scriptLocations != null)
                    {
                        scriptLocations.Clear();
                        scriptLocations = null;
                    }

                    ///////////////////////////////////////////////////////////

                    previousProcessId = 0;

                    ///////////////////////////////////////////////////////////

                    if (arraySearches != null)
                    {
                        arraySearches.Clear();
                        arraySearches = null;
                    }

                    ///////////////////////////////////////////////////////////

#if HISTORY
                    historyEngineFilter = null;

                    if (history != null)
                    {
                        history.Clear();
                        history = null;
                    }
#endif

                    ///////////////////////////////////////////////////////////

                    complaint = null;
                }

                //////////////////////////////////////
                // release unmanaged resources here...
                //////////////////////////////////////

                disposed = true;
            }
        }
Ejemplo n.º 27
0
        ///////////////////////////////////////////////////////////////////////

        #region Private Constructors
        private Script(
            Guid id,
            string name,
            string group,
            string description,
            string type,
            string text,
            string fileName,
            int startLine,
            int endLine,
            bool viaSource,
#if XML
            XmlBlockType blockType,
            DateTime timeStamp,
            string publicKeyToken,
            byte[] signature,
#endif
#if CAS_POLICY
            Evidence evidence,
            byte[] hashValue,
            HashAlgorithm hashAlgorithm,
#endif
            EngineMode engineMode,
            ScriptFlags scriptFlags,
            EngineFlags engineFlags,
            SubstitutionFlags substitutionFlags,
            EventFlags eventFlags,
            ExpressionFlags expressionFlags,
            IClientData clientData
            )
        {
            this.kind        = IdentifierKind.Script;
            this.id          = id;
            this.name        = name;
            this.group       = group;
            this.description = description;
            this.type        = type;
            this.parts       = null; /* TODO: If we ever support scripts with multiple
                                      *       parts, change this to be a formal argument
                                      *       to this constructor and remove text? */
            this.text        = text;
            this.fileName    = fileName;
            this.startLine   = startLine;
            this.endLine     = endLine;
            this.viaSource   = viaSource;

#if XML
            this.blockType      = blockType;
            this.timeStamp      = timeStamp;
            this.publicKeyToken = publicKeyToken;
            this.signature      = signature;
#endif

#if CAS_POLICY
            this.evidence      = evidence;
            this.hashValue     = hashValue;
            this.hashAlgorithm = hashAlgorithm;
#endif

            this.engineMode        = engineMode;
            this.scriptFlags       = scriptFlags;
            this.engineFlags       = engineFlags;
            this.substitutionFlags = substitutionFlags;
            this.expressionFlags   = expressionFlags;
            this.eventFlags        = eventFlags;
            this.clientData        = clientData;
        }
Ejemplo n.º 28
0
        ///////////////////////////////////////////////////////////////////////

        #region IExecute Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            if (targetInterpreter == null)
            {
                result = "invalid interpreter";
                return(ReturnCode.Error);
            }

            ReturnCode   code;
            string       targetName      = null;
            ArgumentList targetArguments = null;

            code = targetInterpreter.GetAliasArguments(
                this, arguments, ref targetName, ref targetArguments,
                ref result);

            if (code == ReturnCode.Ok)
            {
                //
                // NOTE: Grab the target of the alias (this will be null if we
                //       are late-bound).
                //
                IExecute target     = null;
                bool     useUnknown = false;

                code = targetInterpreter.GetAliasTarget(this, targetName,
                                                        targetArguments, LookupFlags.Default, true, ref target,
                                                        ref useUnknown, ref result);

                //
                // NOTE: Do we have a valid target now (we may have already had
                //       one or we may have just succeeded in looking it up)?
                //
                if (code == ReturnCode.Ok)
                {
                    //
                    // NOTE: Create and push a new call frame to track the
                    //       activation of this alias.
                    //
                    string name = StringList.MakeList("alias", this.Name);

                    AliasFlags aliasFlags = this.AliasFlags;

                    ICallFrame frame = interpreter.NewTrackingCallFrame(name,
                                                                        CallFrameFlags.Alias);

                    interpreter.PushAutomaticCallFrame(frame);

                    ///////////////////////////////////////////////////////////

                    bool targetUsable;

                    if (useUnknown)
                    {
                        targetInterpreter.EnterUnknownLevel();
                    }

                    try
                    {
                        if (FlagOps.HasFlags(
                                aliasFlags, AliasFlags.Evaluate, true))
                        {
                            code = targetInterpreter.EvaluateScript(
                                targetArguments, 0, ref result);
                        }
                        else
                        {
                            //
                            // NOTE: Save the current engine flags and then
                            //       enable the external execution flags.
                            //
                            EngineFlags savedEngineFlags =
                                targetInterpreter.BeginExternalExecution();

                            code = targetInterpreter.Execute(
                                targetName, target, clientData,
                                targetArguments, ref result);

                            //
                            // NOTE: Restore the saved engine flags, masking
                            //       off the external execution flags as
                            //       necessary.
                            //
                            /* IGNORED */
                            targetInterpreter.EndAndCleanupExternalExecution(
                                savedEngineFlags);
                        }
                    }
                    finally
                    {
                        targetUsable = Engine.IsUsable(targetInterpreter);

                        if (useUnknown && targetUsable)
                        {
                            targetInterpreter.ExitUnknownLevel();
                        }
                    }

                    ///////////////////////////////////////////////////////////

                    //
                    // NOTE: Pop the original call frame that we pushed above
                    //       and any intervening scope call frames that may be
                    //       leftover (i.e. they were not explicitly closed).
                    //
                    /* IGNORED */
                    interpreter.PopScopeCallFramesAndOneMore();
                }
            }

            return(code);
        }
Ejemplo n.º 29
0
 public EngineFlagEvent(FlagOperation operation, EngineFlags flag)
 {
     Operation = operation;
     Flag      = flag;
 }
Ejemplo n.º 30
0
        ///////////////////////////////////////////////////////////////////////

        #region IExecute Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            if (interpreter == null)
            {
                result = "invalid interpreter";
                return(ReturnCode.Error);
            }

            if (arguments == null)
            {
                result = "invalid argument list";
                return(ReturnCode.Error);
            }

            if ((arguments.Count < 2) || (arguments.Count > 4))
            {
                result = ScriptOps.WrongNumberOfArguments(this, 1,
                                                          arguments, "script ?resultVarName? ?optionsVarName?");

                return(ReturnCode.Error);
            }

            string name = StringList.MakeList(this.Name);

            ICallFrame frame = interpreter.NewTrackingCallFrame(name,
                                                                CallFrameFlags.Catch);

            interpreter.PushAutomaticCallFrame(frame);

            EngineFlags engineFlags = interpreter.EngineFlags;

            if (Engine.HasNoResetError(engineFlags))
            {
                engineFlags |= EngineFlags.ErrorAlreadyLogged;
            }

            ReturnCode code;
            Result     localResult = null;
            int        errorLine   = 0;

            /* IGNORED */
            interpreter.EnterCatchLevel();

            try
            {
                code = interpreter.EvaluateScript(
                    arguments[1], engineFlags, ref localResult,
                    ref errorLine);
            }
            finally
            {
                if (interpreter.ExitCatchLevel() == 0)
                {
                    if (ScriptOps.HasFlags(interpreter,
                                           InterpreterFlags.CatchResetCancel, true))
                    {
                        ReturnCode resetCode;
                        Result     resetError = null;

                        resetCode = Engine.ResetCancel(
                            interpreter, CancelFlags.CatchBlock,
                            ref resetError);

                        if (resetCode != ReturnCode.Ok)
                        {
                            DebugOps.Complain(
                                interpreter, resetCode, resetError);
                        }
                    }

                    if (ScriptOps.HasFlags(interpreter,
                                           InterpreterFlags.CatchResetExit, true))
                    {
                        bool exit = interpreter.Exit;

                        if (exit)
                        {
                            interpreter.Exit = false;
                        }
                    }
                }
            }

            //
            // BUGFIX: Prevent messing up the custom errorInfo from the [error]
            //         command by checking to see if the "error already logged"
            //         flag has been set.
            //
            engineFlags = interpreter.EngineFlags;

            if ((code == ReturnCode.Error) &&
                !Engine.HasErrorAlreadyLogged(engineFlags) &&
                !Engine.HasNoResetError(engineFlags))
            {
                Engine.AddErrorInformation(interpreter, localResult,
                                           String.Format("{0}    (\"catch\" body line {1})",
                                                         Environment.NewLine, errorLine));
            }

            //
            // NOTE: Pop the original call frame that we pushed above and any
            //       intervening scope call frames that may be leftover (i.e.
            //       they were not explicitly closed).
            //
            /* IGNORED */
            interpreter.PopScopeCallFramesAndOneMore();

            //
            // NOTE: The result of this command is the integer conversion of
            //       the return code received from the evaluated script.
            //
            Engine.ResetResult(interpreter, ref result);
            result            = ConversionOps.ToInt(code);
            result.ReturnCode = code; /* NOTE: For ease of use. */

            //
            // NOTE: See if the caller wants to save the result and/or error
            //       message in a variable.
            //
            if (arguments.Count >= 3)
            {
                Result error = null;

                code = interpreter.SetVariableValue(
                    VariableFlags.NoReady, arguments[2], localResult, null,
                    ref error);

                if (code != ReturnCode.Ok)
                {
                    Engine.ResetResult(interpreter, ref result);

                    result = String.Format(
                        "couldn't save command result in variable: {0}",
                        error);

                    return(code);
                }
            }

            //
            // NOTE: See if the caller wants to save the "return options" in a
            //       variable.
            //
            if (arguments.Count >= 4)
            {
                StringList list  = new StringList();
                Result     error = null;

                if (result.ReturnCode == ReturnCode.Return)
                {
                    int level = 0;

                    code = interpreter.GetInfoLevel(
                        null, ref level, ref error);

                    if (code != ReturnCode.Ok)
                    {
                        Engine.ResetResult(interpreter, ref error);

                        result = String.Format(
                            "couldn't get current level: {0}", error);

                        return(code);
                    }

                    list.Add("-code",
                             ((int)interpreter.ReturnCode).ToString());

                    list.Add("-level", level.ToString());
                }
                else
                {
                    list.Add("-code", result.String);
                    list.Add("-level", Value.ZeroString);
                }

                if (result.ReturnCode == ReturnCode.Error)
                {
                    Result     errorCode = null;
                    Result     errorInfo = null;
                    ResultList errors    = null;

                    code = interpreter.CopyErrorInformation(
                        VariableFlags.None, true, ref errorCode, ref errorInfo,
                        ref errors);

                    if (code != ReturnCode.Ok)
                    {
                        Engine.ResetResult(interpreter, ref result);

                        result = errors;
                        return(code);
                    }

                    list.Add("-errorcode", errorCode);
                    list.Add("-errorinfo", errorInfo);
                    list.Add("-errorline", errorLine.ToString());
                }

                code = interpreter.SetVariableValue(
                    VariableFlags.NoReady, arguments[3], list.ToString(), null,
                    ref error);

                if (code != ReturnCode.Ok)
                {
                    Engine.ResetResult(interpreter, ref result);

                    result = String.Format(
                        "couldn't save return options in variable: {0}",
                        error);

                    return(code);
                }
            }

            //
            // NOTE: We are "catching" (masking) the error; therefore, do not
            //       propogate it.
            //
            return(ReturnCode.Ok);
        }