示例#1
0
        private static int runLines(Interpreter interp,
                                    IEnumerable <string> lines)
        {
            var ls  = new LocalScope("code-inner");
            var obj = new UserObject();

            interp.Extend(obj);
            ls.AddLocalDef("self", obj);
            interp.ExtendMinor(ls);
            var         memo = interp.Memorise();
            bool        unfinished;
            GraceObject result;

            foreach (var line in lines)
            {
                int r = REPL.RunLine(interp, obj, memo, line, out unfinished,
                                     out result);
                if (r != 0)
                {
                    return(r);
                }
                if (unfinished)
                {
                    return(1);
                }
            }
            return(0);
        }
示例#2
0
 public ClassDeclaration(INode parent, Scope parentScope, bool isPrintable = true, bool codeGeneration = true)
 {
     Parent         = parent;
     Scope          = new LocalScope(parentScope);
     IsPrintable    = isPrintable;
     CodeGeneration = codeGeneration;
 }
        //public override void SendUpdateToClient(UpdateMessage update)
        //{
        //    Console.WriteLine("Send update...");
        //    WebSocketOODSSServer server = (WebSocketOODSSServer) LocalScope.Get(SessionObjects.WebSocketOODSSServer);
        //}

        /// <summary>
        /// send update message to client
        /// </summary>
        /// <param name="update">update message</param>
        /// <param name="receivingSessionId">sessionId of the client</param>
        public override void SendUpdateToClient(UpdateMessage update, string receivingSessionId)
        {
            Console.WriteLine("Send Update Message Please");
            WebSocketOODSSServer server = (WebSocketOODSSServer)LocalScope.Get(SessionObjects.WebSocketOODSSServer);

            server.SendUpdateMessage(receivingSessionId, update);
        }
示例#4
0
        /// <summary>Performs set-up behaviour shared by multiple
        /// constructors</summary>
        private void initialise()
        {
            var s = new LocalScope();

            scope.scope = s;
            majorScope  = s;
            s.AddMethod("print(_)",
                        new DelegateMethod1Ctx(Print));
            s.AddLocalDef("true", GraceBoolean.True);
            s.AddLocalDef("false", GraceBoolean.False);
            s.AddMethod("_base_while_do(_,_)",
                        new DelegateMethodReq(BaseWhileDo));
            s.AddMethod("_base_try_catch_finally(_,_)",
                        new DelegateMethodReq(BaseTryCatchFinally));
            s.AddMethod("_base_try_catch_finally(_,_,_)",
                        new DelegateMethodReq(BaseTryCatchFinally));
            s.AddMethod("_base_try_catch_finally(_,_,_,_)",
                        new DelegateMethodReq(BaseTryCatchFinally));
            s.AddMethod("_base_try_catch_finally(_,_,_,_,_)",
                        new DelegateMethodReq(BaseTryCatchFinally));
            s.AddMethod("_base_try_catch_finally(_,_,_,_,_,_)",
                        new DelegateMethodReq(BaseTryCatchFinally));
            s.AddMethod("_base_try_catch_finally(_,_,_,_,_,_,_)",
                        new DelegateMethodReq(BaseTryCatchFinally));
            s.AddMethod("Exception",
                        new ConstantMethod(
                            new GraceExceptionKind("Exception")));
        }
示例#5
0
        private static int wsrepl(string filename)
        {
            var ws     = new Grace.Execution.WebSocketServer();
            var wss    = ws.Start();
            var ls     = new LocalScope("repl-inner");
            var obj    = new UserObject();
            var interp = REPL.CreateInterpreter(obj, ls,
                                                new WSOutputSink(wss));

            interp.LoadPrelude();
            var dir = Path.GetFullPath(".");

            interp.AddModuleRoot(dir);
            ErrorReporting.SilenceError("P1001");
            var         memo  = interp.Memorise();
            string      accum = String.Empty;
            bool        unfinished;
            GraceObject result;

            wss.JsonReceived += (o, e) => {
                var je   = (JsonWSEvent)e;
                var root = je.Root;
                var cn   = root.XPathSelectElement("//code");
                if (cn == null)
                {
                    return;
                }
                var line = cn.Value;
                //var line = ((TextWSEvent)e).Text;
                Console.WriteLine("got text: " + line);
                accum += line.Replace("\u0000", "") + "\n";
                var r = REPL.RunLine(
                    interp, obj, memo, accum, out unfinished,
                    out result);
                if (result != null)
                {
                    ls["LAST"] = result;
                }
                if (unfinished)
                {
                    // "Unexpected end of file" is expected here
                    // for unfinished statements.
                    unfinished = false;
                }
                else if (r != 0)
                {
                    // All other errors are errors, and should
                    // clear the accumulated buffer and let the
                    // user start again.
                    accum = String.Empty;
                }
                else
                {
                    accum = String.Empty;
                }
            };
            wss.Run();
            return(0);
        }
示例#6
0
文件: REPL.cs 项目: smarr/kernan
        /// <summary>
        /// Create a REPL-ready interpreter using a given
        /// module object and interior scope.
        /// </summary>
        /// <param name="obj">
        /// Module object
        /// </param>
        /// <param name="localScope">
        /// Interior scope which holds (at least) "self".
        /// </param>
        public static Interpreter CreateInterpreter(UserObject obj,
                                                    LocalScope localScope)
        {
            var interp = new Interpreter();

            configureInterpreter(interp, obj, localScope);
            return(interp);
        }
示例#7
0
        /// <summary>
        /// Creates a new isolated scope. After than any value added to this content object will be released once
        /// <see cref="ReleaseScope" /> is called. The previous scope is linked such that its values are still available.
        /// </summary>
        public void EnterChildScope()
        {
            if (MaxRecursion > 0 && _recursion++ > MaxRecursion)
            {
                throw new InvalidOperationException("The maximum level of recursion has been reached. Your script must have a cyclic include statement.");
            }

            LocalScope = LocalScope.EnterChildScope();
        }
示例#8
0
文件: REPL.cs 项目: smarr/kernan
 private static void configureInterpreter(Interpreter interp,
                                          UserObject obj, LocalScope localScope)
 {
     interp.LoadPrelude();
     interp.Extend(obj);
     localScope.AddLocalDef("self", obj);
     localScope.AddLocalDef("LAST", GraceObject.Done);
     interp.ExtendMinor(localScope);
 }
示例#9
0
 /// <summary>
 /// Constructs a new scope.
 /// </summary>
 /// <param name="localScope">The current local scope.</param>
 /// <param name="metadataReader">The assocated metadata reader.</param>
 internal MethodScope(
     LocalScope localScope,
     MetadataReader metadataReader)
 {
     MetadataReader = metadataReader;
     StartOffset    = localScope.StartOffset;
     Length         = localScope.Length;
     localVariables = localScope.GetLocalVariables();
 }
示例#10
0
 public LocalScopeEntry(PEFile module, MetadataReader metadata, bool isEmbedded, LocalScopeHandle handle)
 {
     this.offset = isEmbedded ? null : (int?)metadata.GetTableMetadataOffset(TableIndex.LocalScope)
                   + metadata.GetTableRowSize(TableIndex.LocalScope) * (MetadataTokens.GetRowNumber(handle) - 1);
     this.module     = module;
     this.metadata   = metadata;
     this.handle     = handle;
     this.localScope = metadata.GetLocalScope(handle);
 }
示例#11
0
        public void ReleaseScope()
        {
            LocalScope = LocalScope.ReleaseScope();

            if (LocalScope == null)
            {
                throw new InvalidOperationException();
            }
        }
示例#12
0
        /// <summary>
        /// Ends a scope.
        /// </summary>
        /// <param name="isLocalScope">If set to <c>true</c> is local scope.</param>
        public void EndScope(bool isLocalScope = false)
        {
            if (isLocalScope)
            {
                currentLocalScope = currentLocalScope.ParentScope;
            }

            CurrentScope = CurrentScope.ParentScope;
        }
示例#13
0
            public Object Invoke(Object[] arguments)
            {
                var scope = new LocalScope(_parentScope);
                var ctx   = new ExecutionContext(_operations, scope);

                ctx.Push(_pointer);
                ctx.Push(arguments);
                ctx.Execute();
                return(ctx.Pop());
            }
示例#14
0
 public LocalScope(CodeGenerator codegen, LocalScope parent, ScopeType type, int from, int to)
 {
     Contract.ThrowIfNull(codegen);
     Debug.Assert(from < to);
     _codegen = codegen;
     _parent  = parent;
     _type    = type;
     _from    = from;
     _to      = to;
 }
示例#15
0
 /// <summary>
 /// Frees the memory associated with the specified scope, and
 /// generates code to decrement the stack pointer accordingly.
 /// </summary>
 /// <param name="scope">the scope to free</param>
 /// <param name="unDeclareVars">whether to also un-define the local
 /// variables to prevent further use</param>
 private void FreeLocalVariables(LocalScope scope, bool unDeclareVars)
 {
     foreach (ScriptVariable variable in scope.Members)
     {
         // TODO: Generate code to free local variables
         if (unDeclareVars)
         {
             // TODO: Undefine local variables
         }
     }
 }
示例#16
0
 /// <summary>
 /// Frees the memory associated with the specified scope, and
 /// generates code to decrement the stack pointer accordingly.
 /// </summary>
 /// <param name="scope">the scope to free</param>
 /// <param name="unDeclareVars">whether to also un-define the local
 /// variables to prevent further use</param>
 private void FreeLocalVariables(LocalScope scope, bool unDeclareVars)
 {
     foreach (ScriptVariable variable in scope.Members)
     {
         // TODO: Generate code to free local variables
         if (unDeclareVars)
         {
             // TODO: Undefine local variables
         }
     }
 }
示例#17
0
 public BlockStatement(INode parent, Scope parentScope, bool introduceScope = true)
 {
     Parent = parent;
     if (introduceScope)
     {
         Scope = new LocalScope(parentScope);
     }
     else
     {
         Scope = parentScope;
     }
 }
示例#18
0
        private static bool GetLocalsInfoForMethod(string assemblyPath, int methodToken, out List <LocalVarInfo> locals)
        {
            locals = null;

            OpenedReader openedReader = GetReader(assemblyPath, isFileLayout: true, peStream: null, pdbStream: null);

            if (openedReader == null)
            {
                return(false);
            }

            using (openedReader)
            {
                try
                {
                    Handle handle = MetadataTokens.Handle(methodToken);
                    if (handle.Kind != HandleKind.MethodDefinition)
                    {
                        return(false);
                    }

                    locals = new List <LocalVarInfo>();

                    MethodDebugInformationHandle methodDebugHandle =
                        ((MethodDefinitionHandle)handle).ToDebugInformationHandle();
                    LocalScopeHandleCollection localScopes = openedReader.Reader.GetLocalScopes(methodDebugHandle);
                    foreach (LocalScopeHandle scopeHandle in localScopes)
                    {
                        LocalScope scope = openedReader.Reader.GetLocalScope(scopeHandle);
                        LocalVariableHandleCollection localVars = scope.GetLocalVariables();
                        foreach (LocalVariableHandle varHandle in localVars)
                        {
                            LocalVariable localVar = openedReader.Reader.GetLocalVariable(varHandle);
                            if (localVar.Attributes == LocalVariableAttributes.DebuggerHidden)
                            {
                                continue;
                            }
                            LocalVarInfo info = new LocalVarInfo();
                            info.startOffset = scope.StartOffset;
                            info.endOffset   = scope.EndOffset;
                            info.name        = openedReader.Reader.GetString(localVar.Name);
                            locals.Add(info);
                        }
                    }
                }
                catch
                {
                    return(false);
                }
            }
            return(true);
        }
示例#19
0
        private LocalScope CreateLocalScope(Scope parent, Vector <Parameter> parameters)
        {
            var locals = new LocalScope(parent);

            foreach (var parameter in parameters)
            {
                if (!locals.TryIncludeUniqueBinding(parameter))
                {
                    LogError(CompilerError.DuplicateIdentifier(parameter.Position, parameter));
                }
            }

            return(locals);
        }
示例#20
0
        /// <summary>
        /// Exits the current scope that has been created by <see cref="EnterChildScope" />
        /// </summary>
        public void ReleaseScope()
        {
            if (_recursion > 0)
            {
                _recursion--;
            }

            LocalScope = LocalScope.ReleaseScope();

            if (LocalScope == null)
            {
                throw new InvalidOperationException();
            }
        }
示例#21
0
        protected static Scope Scope(params TypeMapping[] locals)
        {
            var globalScope = new GlobalScope();
            var localScope  = new LocalScope(globalScope);

            foreach (var local in locals)
            {
                var item = local(null);
                var name = local.Method.GetParameters()[0].Name;
                localScope.Bind(name, item);
            }

            return(localScope);
        }
示例#22
0
        internal static bool GetLocalVariableAndScopeByIndex(IntPtr symbolReaderHandle, int methodToken, int localIndex, out string localVarName, out int ilStartOffset, out int ilEndOffset)
        {
            Debug.Assert(symbolReaderHandle != IntPtr.Zero);
            localVarName  = null;
            ilStartOffset = 0;
            ilEndOffset   = 0;

            GCHandle       gch    = GCHandle.FromIntPtr(symbolReaderHandle);
            MetadataReader reader = ((OpenedReader)gch.Target).Reader;

            try
            {
                Handle handle = MetadataTokens.Handle(methodToken);
                if (handle.Kind != HandleKind.MethodDefinition)
                {
                    return(false);
                }

                MethodDebugInformationHandle methodDebugHandle = ((MethodDefinitionHandle)handle).ToDebugInformationHandle();
                LocalScopeHandleCollection   localScopes       = reader.GetLocalScopes(methodDebugHandle);
                foreach (LocalScopeHandle scopeHandle in localScopes)
                {
                    LocalScope scope = reader.GetLocalScope(scopeHandle);
                    LocalVariableHandleCollection localVars = scope.GetLocalVariables();
                    foreach (LocalVariableHandle varHandle in localVars)
                    {
                        LocalVariable localVar = reader.GetLocalVariable(varHandle);
                        if (localVar.Index == localIndex)
                        {
                            if (localVar.Attributes == LocalVariableAttributes.DebuggerHidden)
                            {
                                return(false);
                            }

                            localVarName  = reader.GetString(localVar.Name);
                            ilStartOffset = scope.StartOffset;
                            ilEndOffset   = scope.EndOffset;
                            return(true);
                        }
                    }
                }
            }
            catch
            {
            }
            return(false);
        }
示例#23
0
        /// <summary>
        /// Helper method to return local variable name for given local index and IL offset.
        /// </summary>
        /// <param name="assemblyFileName">file name of the assembly</param>
        /// <param name="methodToken">method token</param>
        /// <param name="localIndex">local variable index</param>
        /// <param name="localVarName">local variable name return</param>
        /// <returns>true if name has been found</returns>
        public static bool GetLocalVariableByIndex(string assemblyFileName, int methodToken, int localIndex, out string localVarName)
        {
            MetadataReader peReader, pdbReader;

            localVarName = null;

            try
            {
                if (!GetReaders(assemblyFileName, out peReader, out pdbReader))
                {
                    return(false);
                }

                Handle handle = MetadataTokens.Handle(methodToken);
                if (handle.Kind != HandleKind.MethodDefinition)
                {
                    return(false);
                }

                MethodDebugInformationHandle methodDebugHandle = ((MethodDefinitionHandle)handle).ToDebugInformationHandle();
                LocalScopeHandleCollection   localScopes       = pdbReader.GetLocalScopes(methodDebugHandle);
                foreach (LocalScopeHandle scopeHandle in localScopes)
                {
                    LocalScope scope = pdbReader.GetLocalScope(scopeHandle);
                    LocalVariableHandleCollection localVars = scope.GetLocalVariables();
                    foreach (LocalVariableHandle varHandle in localVars)
                    {
                        LocalVariable localVar = pdbReader.GetLocalVariable(varHandle);
                        if (localVar.Index == localIndex)
                        {
                            if (localVar.Attributes == LocalVariableAttributes.DebuggerHidden)
                            {
                                return(false);
                            }
                            localVarName = pdbReader.GetString(localVar.Name);
                            return(true);
                        }
                    }
                }
                return(false);
            }
            finally
            {
                peReader  = null;
                pdbReader = null;
            }
        }
示例#24
0
        private static bool conditionsMet(
            string l,
            Dictionary <string, string> data
            )
        {
            var interpreter = new Interpreter();

            interpreter.LoadPrelude();
            var ls = new LocalScope();

            foreach (var k in data.Keys)
            {
                switch (k)
                {
                case "method":
                case "type":
                case "class":
                case "object":
                case "def":
                case "var":
                case "dialect":
                case "import":
                case "return":
                case "is":
                case "where":
                    ls.AddLocalDef(k + "_", GraceString.Create(data[k]));
                    break;

                default:
                    ls.AddLocalDef(k, GraceString.Create(data[k]));
                    break;
                }
            }
            interpreter.Extend(ls);
            while (l.StartsWith("|["))
            {
                int end       = l.IndexOf("]|");
                var condition = l.Substring(2, end - 2);
                if (!conditionMet(condition, data, interpreter))
                {
                    return(false);
                }
                l = l.Substring(end + 2);
            }
            return(true);
        }
示例#25
0
        /// <summary>
        /// Helper method to return local variable name for given local index and IL offset.
        /// </summary>
        /// <param name="openedReader">symbol reader returned by LoadSymbolsForModule</param>
        /// <param name="methodToken">method token</param>
        /// <param name="localIndex">local variable index</param>
        /// <param name="localVarName">local variable name return</param>
        /// <returns>true if name has been found</returns>
        private bool GetLocalVariableByIndex(
            OpenedReader openedReader,
            int methodToken,
            int localIndex,
            out string localVarName)
        {
            localVarName = null;
            MetadataReader reader = openedReader.Reader;

            try
            {
                Handle handle = MetadataTokens.Handle(methodToken);
                if (handle.Kind != HandleKind.MethodDefinition)
                {
                    return(false);
                }

                MethodDebugInformationHandle methodDebugHandle = ((MethodDefinitionHandle)handle).ToDebugInformationHandle();
                LocalScopeHandleCollection   localScopes       = reader.GetLocalScopes(methodDebugHandle);
                foreach (LocalScopeHandle scopeHandle in localScopes)
                {
                    LocalScope scope = reader.GetLocalScope(scopeHandle);
                    LocalVariableHandleCollection localVars = scope.GetLocalVariables();
                    foreach (LocalVariableHandle varHandle in localVars)
                    {
                        LocalVariable localVar = reader.GetLocalVariable(varHandle);
                        if (localVar.Index == localIndex)
                        {
                            if (localVar.Attributes == LocalVariableAttributes.DebuggerHidden)
                            {
                                return(false);
                            }

                            localVarName = reader.GetString(localVar.Name);
                            return(true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError($"GetLocalVariableByIndex: {ex.Message}");
            }
            return(false);
        }
示例#26
0
        public void HasATypeInWhichOnlyGenericTypeVariablesAreFreshenedOnEachScopeLookup()
        {
            using (TypeVariable.TestFactory())
            {
                //Prevent type '1' from being freshened on type lookup by marking it as non-generic:
                var typeVariable0 = TypeVariable.CreateGeneric();
                var typeVariable1 = TypeVariable.CreateNonGeneric();

                var expectedTypeAfterLookup = new NamedType("A", new TypeVariable(4), typeVariable1, new NamedType("B", new TypeVariable(4), typeVariable1));
                var definedType = new NamedType("A", typeVariable0, typeVariable1, new NamedType("B", typeVariable0, typeVariable1));

                var typeChecker = new TypeChecker();
                var globalScope = new GlobalScope();
                var localScope = new LocalScope(globalScope);
                localScope.Bind("foo", definedType);

                Type("foo", localScope, typeChecker).ShouldEqual(expectedTypeAfterLookup);
            }
        }
示例#27
0
        public void HasATypeInWhichOnlyGenericTypeVariablesAreFreshenedOnEachScopeLookup()
        {
            using (TypeVariable.TestFactory())
            {
                //Prevent type '1' from being freshened on type lookup by marking it as non-generic:
                var typeVariable0 = TypeVariable.CreateGeneric();
                var typeVariable1 = TypeVariable.CreateNonGeneric();

                var expectedTypeAfterLookup = new NamedType("A", new TypeVariable(8), typeVariable1, new NamedType("B", new TypeVariable(8), typeVariable1));
                var definedType             = new NamedType("A", typeVariable0, typeVariable1, new NamedType("B", typeVariable0, typeVariable1));

                var typeChecker = new TypeChecker();
                var globalScope = new GlobalScope();
                var localScope  = new LocalScope(globalScope);
                localScope.Bind("foo", definedType);

                Type("foo", localScope, typeChecker).ShouldEqual(expectedTypeAfterLookup);
            }
        }
示例#28
0
        internal void GenerateScope(BoundBlock block, ScopeType type, int to)
        {
            Contract.ThrowIfNull(block);

            // open scope
            _scope = new LocalScope(this, _scope, type, block.Ordinal, to);
            _scope.ContinueWith(block);

            while ((block = _scope.Dequeue()) != null)
            {
                GenerateBlock(block);
            }

            // close scope
            _scope = _scope.Parent;

            //
            _il.AssertStackEmpty();
        }
示例#29
0
        /// <summary>
        /// Begins a new scope.
        /// </summary>
        /// <param name="isLocalScope">If set to <c>true</c> is local scope.</param>
        public void BeginScope(bool isLocalScope = false)
        {
            if (isLocalScope)
            {
                currentLocalScope = new LocalScope(currentLocalScope);
            }
            Scope newScope = new Scope(CurrentScope);

            if (lastScope != null)
            {
                lastScope.NextScope = newScope;
            }
            else
            {
                globalScope.NextScope = newScope;
            }
            CurrentScope.AddScope(newScope);
            CurrentScope = newScope;
            lastScope    = newScope;
        }
示例#30
0
 internal void Dump()
 {
     Console.WriteLine("Code offset: {0:X8}", CodeReader.Offset);
     Console.WriteLine("EvalStack: {0}", _evalStack.Count);
     if (_evalStack.Count > 0)
     {
         var evalStackValues = new JSValue[_evalStack.Count];
         _evalStack.CopyTo(evalStackValues, 0);
         for (var i = evalStackValues.Length - 1; i >= 0; i--)
         {
             Console.WriteLine("[{0:D3}] - {1}", i, evalStackValues[i]);
         }
     }
     Console.WriteLine("Local variables: {0}", Function.CompiledFunction.DeclaredVariables.Length);
     foreach (var variableName in Function.CompiledFunction.DeclaredVariables)
     {
         Console.WriteLine("{0} = {1}", variableName, LocalScope.GetVariable(variableName));
     }
     Console.WriteLine();
 }
示例#31
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PdbLocalScope"/> class.
        /// </summary>
        /// <param name="function">Function that contains this scope.</param>
        /// <param name="handle">Our metadata reader handle.</param>
        /// <param name="parent">Parent scope.</param>
        internal PdbLocalScope(PdbFunction function, LocalScopeHandle handle, IPdbLocalScope parent = null)
        {
            Function        = function;
            localScopeCache = SimpleCache.CreateStruct(() => function.PdbFile.Reader.GetLocalScope(handle));
            childrenCache   = SimpleCache.CreateStruct(() =>
            {
                var enumerator = LocalScope.GetChildren();
                List <IPdbLocalScope> children = new List <IPdbLocalScope>();

                while (enumerator.MoveNext())
                {
                    children.Add(new PdbLocalScope(function, enumerator.Current, this));
                }
                return(children);
            });
            constantsCache = SimpleCache.CreateStruct(() =>
            {
                var localConstants            = LocalScope.GetLocalConstants();
                IPdbLocalConstant[] constants = new IPdbLocalConstant[localConstants.Count];
                int i = 0;

                foreach (var c in localConstants)
                {
                    constants[i++] = new PdbLocalConstant(this, c);
                }
                return(constants);
            });
            variablesCache = SimpleCache.CreateStruct(() =>
            {
                var localVariables            = LocalScope.GetLocalVariables();
                IPdbLocalVariable[] variables = new IPdbLocalVariable[localVariables.Count];
                int i = 0;

                foreach (var v in localVariables)
                {
                    variables[i++] = new PdbLocalVariable(this, v);
                }
                return(variables);
            });
        }
        /// <summary>
        /// Binds the parameters to local variables in the function scope.
        /// </summary>
        /// <param name="name">
        ///     The name of the parameter to bind the value to.
        /// </param>
        /// <param name="value">
        ///     The value to bind to the parameter. It should be assumed by
        ///     derived classes that the proper type coercion has already taken
        ///     place and that any prerequisite metadata has been satisfied.
        /// </param>
        /// <param name="parameterMetadata"></param>
        internal override void BindParameter(string name, object value, CompiledCommandParameter parameterMetadata)
        {
            if (value == AutomationNull.Value || value == UnboundParameter.Value)
            {
                value = null;
            }

            Diagnostics.Assert(name != null, "The caller should verify that name is not null");

            var varPath = new VariablePath(name, VariablePathFlags.Variable);

            // If the parameter was allocated in the LocalsTuple, we can avoid creating a PSVariable,
            if (LocalScope != null &&
                varPath.IsAnyLocal() &&
                LocalScope.TrySetLocalParameterValue(varPath.UnqualifiedPath, CopyMutableValues(value)))
            {
                return;
            }

            // Otherwise we'll fall through and enter a new PSVariable in the current scope.  This
            // is what normally happens when dotting (though the above may succeed if a parameter name
            // was an automatic variable like $PSBoundParameters.

            // First we need to make a variable instance and apply
            // any attributes from the script.

            PSVariable variable = new PSVariable(varPath.UnqualifiedPath, value,
                                                 varPath.IsPrivate ? ScopedItemOptions.Private : ScopedItemOptions.None);

            Context.EngineSessionState.SetVariable(varPath, variable, false, CommandOrigin.Internal);
            RuntimeDefinedParameter runtimeDefinedParameter;

            if (Script.RuntimeDefinedParameters.TryGetValue(name, out runtimeDefinedParameter))
            {
                // The attributes have already been checked and conversions run, so it is wrong
                // to do so again.
                variable.AddParameterAttributesNoChecks(runtimeDefinedParameter.Attributes);
            }
        }
示例#33
0
        public Expression TypeCheck(Block block, Scope scope)
        {
            var position = block.Position;
            var variableDeclarations = block.VariableDeclarations;
            var innerExpressions = block.InnerExpressions;

            var localScope = new LocalScope(scope);

            var typedVariableDeclarations = new List<VariableDeclaration>();
            foreach (var variable in variableDeclarations)
            {
                var typedValue = TypeCheck(variable.Value, localScope);

                var bindingType = variable.IsImplicitlyTyped
                    ? typedValue.Type /*Replaces implicit type.*/
                    : TypeOf(variable.DeclaredTypeName);

                var binding = new VariableDeclaration(variable.Position, variable.DeclaredTypeName, variable.Identifier, typedValue, bindingType);

                if (!localScope.TryIncludeUniqueBinding(binding))
                    LogError(CompilerError.DuplicateIdentifier(binding.Position, binding));

                Unify(typedValue.Position, bindingType, typedValue.Type);

                typedVariableDeclarations.Add(binding);
            }

            var typedInnerExpressions = TypeCheck(innerExpressions, localScope);

            var blockType = typedInnerExpressions.Last().Type;

            return new Block(position, typedVariableDeclarations.ToVector(), typedInnerExpressions, blockType);
        }
示例#34
0
		/// <summary>
		/// Ends a scope.
		/// </summary>
		/// <param name="isLocalScope">If set to <c>true</c> is local scope.</param>
		public void EndScope (bool isLocalScope = false)
		{
			if (isLocalScope) {
				currentLocalScope = currentLocalScope.ParentScope;
			}

			CurrentScope = CurrentScope.ParentScope;
		}
示例#35
0
			public LocalScope (LocalScope parentScope)
			{
				ParentScope = parentScope;
				NextLocal = 0;
			}
示例#36
0
		/// <summary>
		/// Begins a new scope.
		/// </summary>
		/// <param name="isLocalScope">If set to <c>true</c> is local scope.</param>
		public void BeginScope (bool isLocalScope = false)
		{
			if (isLocalScope) {
				currentLocalScope = new LocalScope (currentLocalScope);
			}
			Scope newScope = new Scope (CurrentScope);
			if (lastScope != null) {
				lastScope.NextScope = newScope;
			} else {
				globalScope.NextScope = newScope;
			}
			CurrentScope.AddScope (newScope);
			CurrentScope = newScope;
			lastScope = newScope;
		}
示例#37
0
        private LocalScope CreateLocalScope(Scope parent, Vector<Function> methods)
        {
            var locals = new LocalScope(parent);

            foreach (var method in methods)
                if (!locals.TryIncludeUniqueBinding(method))
                    LogError(CompilerError.DuplicateIdentifier(method.Position, method));

            return locals;
        }
示例#38
0
        private LocalScope CreateLocalScope(Scope parent, Vector<Parameter> parameters)
        {
            var locals = new LocalScope(parent);

            foreach (var parameter in parameters)
                if (!locals.TryIncludeUniqueBinding(parameter))
                    LogError(CompilerError.DuplicateIdentifier(parameter.Position, parameter));

            return locals;
        }
示例#39
0
        private void DefineScopeLocals(LocalScope currentScope, StandaloneSignatureHandle localSignatureHandleOpt)
        {
            foreach (ILocalDefinition scopeConstant in currentScope.Constants)
            {
                var signatureHandle = _metadataWriter.SerializeLocalConstantStandAloneSignature(scopeConstant);
                if (!_metadataWriter.IsLocalNameTooLong(scopeConstant))
                {
                    DefineLocalConstant(scopeConstant.Name, scopeConstant.CompileTimeValue.Value, _metadataWriter.GetConstantTypeCode(scopeConstant), signatureHandle);
                }
            }

            foreach (ILocalDefinition scopeLocal in currentScope.Variables)
            {
                if (!_metadataWriter.IsLocalNameTooLong(scopeLocal))
                {
                    Debug.Assert(scopeLocal.SlotIndex >= 0);
                    DefineLocalVariable((uint)scopeLocal.SlotIndex, scopeLocal.Name, scopeLocal.PdbAttributes, localSignatureHandleOpt);
                }
            }
        }