Example #1
0
        public FunctionAnalysisUnit(FunctionAnalysisUnit originalUnit, CallChain callChain, ArgumentSet callArgs)
            : base(originalUnit.Ast, null) {
            _originalUnit = originalUnit;
            _declUnit = originalUnit._declUnit;
            Function = originalUnit.Function;

            CallChain = callChain;

            var scope = new FunctionScope(
                Function,
                Ast,
                originalUnit.Scope.OuterScope,
                originalUnit.DeclaringModule.ProjectEntry
            );
            scope.UpdateParameters(this, callArgs, false, originalUnit.Scope as FunctionScope);
            _scope = scope;

            var walker = new OverviewWalker(_originalUnit.ProjectEntry, this, Tree);
            if (Ast.Body != null) {
                Ast.Body.Walk(walker);
            }

            AnalysisLog.NewUnit(this);
            Enqueue();
        }
Example #2
0
        static Upper()
        {
            string description = "Converts text to uppercase.";

            IEnumerable<ArgumentInfo> requiredArguments = new ArgumentInfo[]
            {
                new ArgumentInfo("Text", "Text is the text you want converted to uppercase. Text can be a reference or text string.", ArgumentType.Text)
            };

            Info = new FunctionInfo(FunctionName, FunctionCategory.Text, description, requiredArguments);
        }
Example #3
0
        static Nand()
        {
            string description = "Returns the Sheffer stroke (or also known as the NAND operator) of two booleans.";

            IEnumerable<ArgumentInfo> requiredArguments = new ArgumentInfo[]
            {
                new ArgumentInfo("Logical", "The first logical argument.", ArgumentType.Logical),
                new ArgumentInfo("Logical", "The second logical argument.", ArgumentType.Logical)
            };

            Info = new FunctionInfo(FunctionName, FunctionCategory.Text, description, requiredArguments);
        }
Example #4
0
        static Indirect()
        {
            string description = "Returns the reference of the cell specified by a text string.";

            IEnumerable<ArgumentInfo> requiredArguments = new ArgumentInfo[]
            {
                new ArgumentInfo("Text",
                    "A reference to a cell that contains an A1-style reference, a name defined as a reference, or a reference to a cell as a text string.",
                    ArgumentType.Text),
            };

            Info = new FunctionInfo(FunctionName,FunctionCategory.LookupReference, description, requiredArguments);
        }
Example #5
0
 public FunctionScope(
     FunctionInfo function,
     Node node,
     InterpreterScope declScope,
     IPythonProjectEntry declModule
 )
     : base(function, node, declScope) {
     ReturnValue = new VariableDef();
     if (Function.FunctionDefinition.IsCoroutine) {
         Coroutine = new CoroutineInfo(function.ProjectState, declModule);
         ReturnValue.AddTypes(function.ProjectEntry, Coroutine.SelfSet, false);
     } else if (Function.FunctionDefinition.IsGenerator) {
         Generator = new GeneratorInfo(function.ProjectState, declModule);
         ReturnValue.AddTypes(function.ProjectEntry, Generator.SelfSet, false);
     }
 }
Example #6
0
        static GeoMean()
        {
            string description = "Returns the geometric mean of a sequance of numbers.";

            IEnumerable<ArgumentInfo> requiredArguments = new ArgumentInfo[]
            {
                new ArgumentInfo("Number", "Positive number", ArgumentType.Number),
            };

            IEnumerable<ArgumentInfo> optionalArguments = new ArgumentInfo[]
            {
                new ArgumentInfo("Number", "Positive number", ArgumentType.Number)
            };

            info = new FunctionInfo(FunctionName, FunctionCategory.Statistical, description, requiredArguments, optionalArguments, optionalArgumentsRepeatCount:255);
        }
Example #7
0
        static RepeatString()
        {
            IEnumerable<ArgumentInfo> requiredArguments = new ArgumentInfo[]
            {
                 new ArgumentInfo("Text", "Text is the text you want to repeat.", ArgumentType.Text)
            };

            IEnumerable<ArgumentInfo> optionalArguments = new ArgumentInfo[]
            {
                new ArgumentInfo("NumberTimes", "NumberTimes is a positive number specifying the number of times to repeat text.", ArgumentType.Number)
            };

            string description = "REPEAT.STRING repeats some text a desired number of times.";

            Info = new FunctionInfo(FunctionName, FunctionCategory.Text, description, requiredArguments, optionalArguments, 1, false);
        }
Example #8
0
        internal FunctionAnalysisUnit(
            FunctionInfo function,
            AnalysisUnit declUnit,
            InterpreterScope declScope,
            IPythonProjectEntry declEntry
        )
            : base(function.FunctionDefinition, null) {
            _declUnit = declUnit;
            Function = function;
            _decoratorCalls = new Dictionary<Node, Expression>();

            var scope = new FunctionScope(Function, Function.FunctionDefinition, declScope, declEntry);
            scope.EnsureParameters(this);
            _scope = scope;

            AnalysisLog.NewUnit(this);
        }
Example #9
0
        private static void IterateFunction(FunctionInfo fi, int indents)
        {
            PrintOutLine("Function Name", fi.Name, indents);
            PrintOutLine("  Is Anonymous", fi.IsAnonymous.ToString(), indents);
            PrintOutLine("  Is Nested", fi.IsInner.ToString(), indents);
            PrintOutLine("  Position", fi.Line + ":" + fi.CharIndex, indents);
            PrintOutLine("  Arguments", string.Join(", ", fi.Args), indents);
            PrintOutLine("  Local Variables ", string.Join(", ",
            fi.DeclaredLocalVariables.Select(vi => vi.Name).ToArray()), indents);

            Console.WriteLine();

            indents += 4;
            foreach (FunctionInfo innerFun in fi.DeclaredInnerFunctions)
            {
                IterateFunction(innerFun, indents);
            }
            indents -= 4;
        }
Example #10
0
        static Add()
        {
            #region FunctionInfo

            string description = "Adds all the numbers in range of cells.";

            IEnumerable<ArgumentInfo> requiredArguments = new ArgumentInfo[]
            {
                new ArgumentInfo("Number", "number1, number2,... are the numbers to sum. Logical values and text are ignored in cells, included if typed as arguments.", ArgumentType.Number),
            };

            IEnumerable<ArgumentInfo> optionalArguments = new ArgumentInfo[]
            {
                new ArgumentInfo("Number", "number1, number2,... are the numbers to sum. Logical values and text are ignored in cells, included if typed as arguments.", ArgumentType.Number),
            };

            Info = new FunctionInfo(FunctionName, FunctionCategory.MathTrig, description, requiredArguments, optionalArguments, 254, true);

            #endregion
        }
Example #11
0
        static Arguments()
        {
            string description = "Returns number of used arguments.";

            IEnumerable<ArgumentInfo> requiredArguments = new ArgumentInfo[]
            {
                new ArgumentInfo("First", "First argument.", ArgumentType.Any),
                new ArgumentInfo("Second", "Second argument.", ArgumentType.Any),
                new ArgumentInfo("Third", "Third argument.", ArgumentType.Any),
            };

            IEnumerable<ArgumentInfo> optionalArguments = new ArgumentInfo[]
            {
                new ArgumentInfo("First", "First argument.", ArgumentType.Any),
                new ArgumentInfo("Second", "Second argument.", ArgumentType.Any),
                new ArgumentInfo("Third", "Third argument.", ArgumentType.Any),
            };

            Info = new FunctionInfo(FunctionName, FunctionCategory.MathTrig, description, requiredArguments, optionalArguments, optionalArgumentsRepeatCount: 3);
        }
Example #12
0
 public override bool Build(ref CodeNode _this, int expressionDepth, Dictionary <string, VariableDescriptor> variables, CodeContext codeContext, CompilerMessageCallback message, FunctionInfo stats, Options opts)
 {
     if (stats != null)
     {
         stats.ContainsDebugger = true;
     }
     return(base.Build(ref _this, expressionDepth, variables, codeContext, message, stats, opts));
 }
        /// <summary>
        /// Generates a HelpInfo PSObject from a CmdletInfo object
        /// </summary>
        /// <param name="input">command info</param>
        /// <returns>HelpInfo PSObject</returns>
        internal static PSObject GetPSObjectFromCmdletInfo(CommandInfo input)
        {
            // Create a copy of commandInfo for GetCommandCommand so that we can generate parameter
            // sets based on Dynamic Parameters (+ optional arguments)
            CommandInfo commandInfo = input.CreateGetCommandCopy(null);

            PSObject obj = new PSObject();

            obj.TypeNames.Clear();
            obj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#{1}#command", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp, commandInfo.ModuleName));
            obj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#{1}", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp, commandInfo.ModuleName));
            obj.TypeNames.Add(DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp);
            obj.TypeNames.Add("CmdletHelpInfo");
            obj.TypeNames.Add("HelpInfo");

            if (commandInfo is CmdletInfo)
            {
                CmdletInfo cmdletInfo     = commandInfo as CmdletInfo;
                bool       common         = false;
                bool       commonWorkflow = false;
                if (cmdletInfo.Parameters != null)
                {
                    common         = HasCommonParameters(cmdletInfo.Parameters);
                    commonWorkflow = ((cmdletInfo.CommandType & CommandTypes.Workflow) == CommandTypes.Workflow);
                }

                obj.Properties.Add(new PSNoteProperty("CommonParameters", common));
                obj.Properties.Add(new PSNoteProperty("WorkflowCommonParameters", commonWorkflow));
                AddDetailsProperties(obj, cmdletInfo.Name, cmdletInfo.Noun, cmdletInfo.Verb, TypeNameForDefaultHelp);
                AddSyntaxProperties(obj, cmdletInfo.Name, cmdletInfo.ParameterSets, common, commonWorkflow, TypeNameForDefaultHelp);
                AddParametersProperties(obj, cmdletInfo.Parameters, common, commonWorkflow, TypeNameForDefaultHelp);
                AddInputTypesProperties(obj, cmdletInfo.Parameters);
                AddRelatedLinksProperties(obj, commandInfo.CommandMetadata.HelpUri);

                try
                {
                    AddOutputTypesProperties(obj, cmdletInfo.OutputType);
                }
                catch (PSInvalidOperationException)
                {
                    AddOutputTypesProperties(obj, new ReadOnlyCollection <PSTypeName>(new List <PSTypeName>()));
                }

                AddAliasesProperties(obj, cmdletInfo.Name, cmdletInfo.Context);

                if (HasHelpInfoUri(cmdletInfo.Module, cmdletInfo.ModuleName))
                {
                    AddRemarksProperties(obj, cmdletInfo.Name, cmdletInfo.CommandMetadata.HelpUri);
                }
                else
                {
                    obj.Properties.Add(new PSNoteProperty("remarks", HelpDisplayStrings.None));
                }

                obj.Properties.Add(new PSNoteProperty("PSSnapIn", cmdletInfo.PSSnapIn));
            }
            else if (commandInfo is FunctionInfo)
            {
                FunctionInfo funcInfo       = commandInfo as FunctionInfo;
                bool         common         = HasCommonParameters(funcInfo.Parameters);
                bool         commonWorkflow = ((commandInfo.CommandType & CommandTypes.Workflow) == CommandTypes.Workflow);

                obj.Properties.Add(new PSNoteProperty("CommonParameters", common));
                obj.Properties.Add(new PSNoteProperty("WorkflowCommonParameters", commonWorkflow));
                AddDetailsProperties(obj, funcInfo.Name, String.Empty, String.Empty, TypeNameForDefaultHelp);
                AddSyntaxProperties(obj, funcInfo.Name, funcInfo.ParameterSets, common, commonWorkflow, TypeNameForDefaultHelp);
                AddParametersProperties(obj, funcInfo.Parameters, common, commonWorkflow, TypeNameForDefaultHelp);
                AddInputTypesProperties(obj, funcInfo.Parameters);
                AddRelatedLinksProperties(obj, funcInfo.CommandMetadata.HelpUri);

                try
                {
                    AddOutputTypesProperties(obj, funcInfo.OutputType);
                }
                catch (PSInvalidOperationException)
                {
                    AddOutputTypesProperties(obj, new ReadOnlyCollection <PSTypeName>(new List <PSTypeName>()));
                }

                AddAliasesProperties(obj, funcInfo.Name, funcInfo.Context);

                if (HasHelpInfoUri(funcInfo.Module, funcInfo.ModuleName))
                {
                    AddRemarksProperties(obj, funcInfo.Name, funcInfo.CommandMetadata.HelpUri);
                }
                else
                {
                    obj.Properties.Add(new PSNoteProperty("remarks", HelpDisplayStrings.None));
                }
            }

            obj.Properties.Add(new PSNoteProperty("alertSet", null));
            obj.Properties.Add(new PSNoteProperty("description", null));
            obj.Properties.Add(new PSNoteProperty("examples", null));
            obj.Properties.Add(new PSNoteProperty("Synopsis", commandInfo.Syntax));
            obj.Properties.Add(new PSNoteProperty("ModuleName", commandInfo.ModuleName));
            obj.Properties.Add(new PSNoteProperty("nonTerminatingErrors", String.Empty));
            obj.Properties.Add(new PSNoteProperty("xmlns:command", "http://schemas.microsoft.com/maml/dev/command/2004/10"));
            obj.Properties.Add(new PSNoteProperty("xmlns:dev", "http://schemas.microsoft.com/maml/dev/2004/10"));
            obj.Properties.Add(new PSNoteProperty("xmlns:maml", "http://schemas.microsoft.com/maml/2004/10"));

            return(obj);
        }
Example #14
0
        private object GetMemberValueInternal(AnalysisValue type, ModuleInfo declModule, bool isRef)
        {
            SpecializedNamespace specialCallable = type as SpecializedNamespace;

            if (specialCallable != null)
            {
                if (specialCallable.Original == null)
                {
                    return(null);
                }
                return(GetMemberValueInternal(specialCallable.Original, declModule, isRef));
            }

            switch (type.MemberType)
            {
            case PythonMemberType.Function:
                FunctionInfo fi = type as FunctionInfo;
                if (fi != null)
                {
                    if (fi.DeclaringModule.GetModuleInfo() != declModule)
                    {
                        return(GenerateFuncRef(fi));
                    }
                    else
                    {
                        return(GenerateFunction(fi));
                    }
                }

                BuiltinFunctionInfo bfi = type as BuiltinFunctionInfo;
                if (bfi != null)
                {
                    return(GenerateFuncRef(bfi));
                }

                return("function");

            case PythonMemberType.Method:
                BoundMethodInfo mi = type as BoundMethodInfo;
                if (mi != null)
                {
                    return(GenerateMethod(mi));
                }
                return("method");

            case PythonMemberType.Property:
                FunctionInfo prop = type as FunctionInfo;
                if (prop != null)
                {
                    return(GenerateProperty(prop));
                }
                break;

            case PythonMemberType.Class:
                ClassInfo ci = type as ClassInfo;
                if (ci != null)
                {
                    if (isRef || ci.DeclaringModule.GetModuleInfo() != declModule)
                    {
                        // TODO: Save qualified name so that classes defined in classes/function can be resolved
                        return(GetTypeRef(ci.DeclaringModule.ModuleName, ci.Name));
                    }
                    else
                    {
                        return(GenerateClass(ci, declModule));
                    }
                }

                BuiltinClassInfo bci = type as BuiltinClassInfo;
                if (bci != null)
                {
                    return(GetTypeRef(bci.PythonType.DeclaringModule.Name, bci.PythonType.Name));
                }
                return("type");

            case PythonMemberType.Constant:
                ConstantInfo constantInfo = type as ConstantInfo;
                if (constantInfo != null)
                {
                    return(GenerateConstant(constantInfo));
                }
                break;

            case PythonMemberType.Module:
                if (type is ModuleInfo)
                {
                    return(GetModuleName(((ModuleInfo)type).Name));
                }
                else if (type is BuiltinModule)
                {
                    return(GetModuleName(((BuiltinModule)type).Name));
                }
                break;

            case PythonMemberType.Instance:
                return(new Dictionary <string, object> {
                    { "type", GenerateTypeName(type, true) }
                });

            default:
                return(new Dictionary <string, object>()
                {
                    { "type", GenerateTypeName(type.PythonType) }
                });
            }
            return(null);
        }
Example #15
0
 internal FunctionAnalysisUnit(FunctionInfo function, AnalysisUnit declUnit)
     : base(function.FunctionDefinition, null)
 {
     _declUnit = declUnit;
     Function = function;
 }
Example #16
0
        static E()
        {
            string description = "Returns the Napier's constant.";

            Info = new FunctionInfo(FunctionName, FunctionCategory.MathTrig, description);
        }
Example #17
0
        protected void Initialize()
        {
            runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();

            eventHandlerDelegate = new EventHandler(EventDispatcher);

            SPContext ctx = SPContext.Current;

            runspace.SessionStateProxy.SetVariable("this", this);
            runspace.SessionStateProxy.SetVariable("viewState", this.ViewState);
            runspace.SessionStateProxy.SetVariable("spContext", ctx);
            runspace.SessionStateProxy.SetVariable("httpContext", HttpContext.Current);
            runspace.SessionStateProxy.SetVariable("site", ctx.Site);
            runspace.SessionStateProxy.SetVariable("web", ctx.Web);
            runspace.SessionStateProxy.SetVariable("list", ctx.List);
            runspace.SessionStateProxy.SetVariable("item", ctx.Item);
            runspace.SessionStateProxy.SetVariable(VariableAjaxEnabled, false);
            runspace.SessionStateProxy.SetVariable(VariableProgressTemplate, null);
            runspace.SessionStateProxy.SetVariable(VariableProgressDynamicLayout, true);
            runspace.SessionStateProxy.SetVariable(VariableProgressDisplayAfter, 500);
            runspace.SessionStateProxy.SetVariable(VariableRefreshInterval, 0);
            runspace.SessionStateProxy.SetVariable("param1", this.Parameter1);
            runspace.SessionStateProxy.SetVariable("param2", this.Parameter2);
            runspace.SessionStateProxy.SetVariable("param3", this.Parameter3);
            runspace.SessionStateProxy.SetVariable("param4", this.Parameter4);

            if (this.Page != null)
            {
                runspace.SessionStateProxy.SetVariable("isPostBack", this.Page.IsPostBack);
                runspace.SessionStateProxy.SetVariable("page", this.Page);
            }

            if (String.IsNullOrEmpty(Script) == false)
            {
                try
                {
                    Pipeline pipe = null;

                    if (!String.IsNullOrEmpty(PredefinedFunctions))
                    {
                        pipe = runspace.CreatePipeline(PredefinedFunctions);
                        InvokePipeline(pipe);
                    }

                    if (!String.IsNullOrEmpty(Script))
                    {
                        pipe = runspace.CreatePipeline(Script);
                        InvokePipeline(pipe);

                        pipe = runspace.CreatePipeline("get-childitem function:\\");
                        Collection <PSObject> result = InvokePipeline(pipe);

                        foreach (PSObject obj in result)
                        {
                            FunctionInfo func = (FunctionInfo)obj.BaseObject;
                            functions.Add(func.Name.ToLower(), func);
                        }
                    }

                    if (AjaxEnabled && this.Page != null)
                    {
                        EnsureScriptManager();
                        EnsureUpdatePanelFixup();
                    }
                }
                catch (Exception ex)
                {
                    powerWebPartException = new PowerWebPartException("Intitialization", ex);
                }
            }
        }
Example #18
0
        public override bool Build(ref CodeNode _this, int expressionDepth, Dictionary <string, VariableDescriptor> variables, CodeContext codeContext, InternalCompilerMessageCallback message, FunctionInfo stats, Options opts)
        {
            expressionDepth = System.Math.Max(1, expressionDepth);
            Parser.Build(ref body, expressionDepth, variables, codeContext | CodeContext.Conditional | CodeContext.InLoop, message, stats, opts);
            Parser.Build(ref condition, 2, variables, codeContext | CodeContext.InLoop | CodeContext.InExpression, message, stats, opts);
            if ((opts & Options.SuppressUselessExpressionsElimination) == 0 && condition is ConvertToBoolean)
            {
                if (message != null)
                {
                    message(MessageLevel.Warning, condition.Position, 2, "Useless conversion. Remove double negation in condition");
                }
                condition = (condition as Expression)._left;
            }
            try
            {
                if (allowRemove && (condition is Constant || (condition is Expression && (condition as Expression).ContextIndependent)))
                {
                    Eliminated = true;
                    if ((bool)condition.Evaluate(null))
                    {
                        if ((opts & Options.SuppressUselessExpressionsElimination) == 0 && body != null)
                        {
                            _this = new InfinityLoop(body, labels);
                        }
                    }
                    else if ((opts & Options.SuppressUselessStatementsElimination) == 0)
                    {
                        _this = null;
                        if (body != null)
                        {
                            body.Eliminated = true;
                        }
                    }
                    condition.Eliminated = true;
                }
                else if ((opts & Options.SuppressUselessExpressionsElimination) == 0 &&
                         ((this.condition is Expressions.ObjectDefinition && (this.condition as Expressions.ObjectDefinition).FieldNames.Length == 0) ||
                          (this.condition is ArrayDefinition && (this.condition as ArrayDefinition).Elements.Length == 0)))
                {
                    _this = new InfinityLoop(this.body, this.labels);
                    this.condition.Eliminated = true;
                }
            }
#if (PORTABLE || NETCORE)
            catch
            {
Example #19
0
        } // GetSessionStateItem

        /// <summary>
        /// Sets the function of the specified name to the specified value
        /// </summary>
        ///
        /// <param name="name">
        /// The name of the function to set.
        /// </param>
        ///
        /// <param name="value">
        /// The new value for the function.
        /// </param>
        ///
        /// <param name="writeItem">
        /// If true, the item that was set should be written to WriteItemObject.
        /// </param>
        ///
#pragma warning disable 0162
        internal override void SetSessionStateItem(string name, object value, bool writeItem)
        {
            Dbg.Diagnostics.Assert(
                !String.IsNullOrEmpty(name),
                "The caller should verify this parameter");

            FunctionProviderDynamicParameters dynamicParameters =
                DynamicParameters as FunctionProviderDynamicParameters;

            CommandInfo modifiedItem = null;

            bool dynamicParametersSpecified = dynamicParameters != null && dynamicParameters.OptionsSet;

            if (value == null)
            {
                // If the value wasn't specified but the options were, just set the
                // options on the existing function.
                // If the options weren't specified, then remove the function

                if (dynamicParametersSpecified)
                {
                    modifiedItem = (CommandInfo)GetSessionStateItem(name);

                    if (modifiedItem != null)
                    {
                        SetOptions(modifiedItem, dynamicParameters.Options);
                    }
                }
                else
                {
                    RemoveSessionStateItem(name);
                }
            }
            else
            {
                do // false loop
                {
                    // Unwrap the PSObject before binding it as a scriptblock...
                    PSObject pso = value as PSObject;
                    if (pso != null)
                    {
                        value = pso.BaseObject;
                    }

                    ScriptBlock scriptBlockValue = value as ScriptBlock;
                    if (scriptBlockValue != null)
                    {
                        if (dynamicParametersSpecified)
                        {
                            modifiedItem = SessionState.Internal.SetFunction(name, scriptBlockValue,
                                                                             null, dynamicParameters.Options, Force, Context.Origin);
                        }
                        else
                        {
                            modifiedItem = SessionState.Internal.SetFunction(name, scriptBlockValue, null, Force, Context.Origin);
                        }
                        break;
                    }

                    FunctionInfo function = value as FunctionInfo;
                    if (function != null)
                    {
                        ScopedItemOptions options = function.Options;

                        if (dynamicParametersSpecified)
                        {
                            options = dynamicParameters.Options;
                        }

                        modifiedItem = SessionState.Internal.SetFunction(name, function.ScriptBlock, function, options, Force, Context.Origin);
                        break;
                    }

                    String stringValue = value as string;
                    if (stringValue != null)
                    {
                        ScriptBlock scriptBlock = ScriptBlock.Create(Context.ExecutionContext, stringValue);

                        if (dynamicParametersSpecified)
                        {
                            modifiedItem = SessionState.Internal.SetFunction(name, scriptBlock, null, dynamicParameters.Options, Force, Context.Origin);
                        }
                        else
                        {
                            modifiedItem = SessionState.Internal.SetFunction(name, scriptBlock, null, Force, Context.Origin);
                        }
                        break;
                    }

                    throw PSTraceSource.NewArgumentException("value");
                } while (false);

                if (writeItem && modifiedItem != null)
                {
                    WriteItemObject(modifiedItem, modifiedItem.Name, false);
                }
            }
        } // SetSessionStateItem
Example #20
0
        public override bool Build(ref CodeNode _this, int expressionDepth, Dictionary <string, VariableDescriptor> variables, CodeContext codeContext, CompilerMessageCallback message, FunctionInfo stats, Options opts)
        {
            var res = base.Build(ref _this, expressionDepth, variables, codeContext, message, stats, opts);

            if (!res && _this == this)
            {
                try
                {
                    if (_left.ContextIndependent && Tools.JSObjectToInt32((_left).Evaluate(null)) == 0)
                    {
                        _this = new Constant(0);
                    }
                    else if (_right.ContextIndependent && Tools.JSObjectToInt32((_right).Evaluate(null)) == 0)
                    {
                        _this = new ConvertToInteger(_left);
                    }
                }
                catch
                {
                }
            }
            return(res);
        }
Example #21
0
 public override void Optimize(ref CodeNode _this, FunctionDefinition owner, InternalCompilerMessageCallback message, Options opts, FunctionInfo stats)
 {
     baseOptimize(ref _this, owner, message, opts, stats);
     if (_this == this)
     {
         if (_left.ResultType == PredictedType.Number && _right.ResultType == PredictedType.Number)
         {
             _this = new NumberMore(_left, _right);
             return;
         }
     }
 }
Example #22
0
 private static IAnalysisSet GetFunctionReturnTypes(FunctionInfo func)
 {
     return(func.GetReturnValue());
 }
        private void OnGenerateCppScriptWrapperFunction(Builder.BuildData buildData, ClassInfo classInfo, FunctionInfo functionInfo, int scriptVTableSize, int scriptVTableIndex, StringBuilder contents)
        {
            // Generate C++ wrapper function to invoke Visual Script instead of overridden native function (with support for base method callback)

            BindingsGenerator.CppIncludeFiles.Add("Engine/Content/Assets/VisualScript.h");

            contents.AppendFormat("    {0} {1}_VisualScriptWrapper(", functionInfo.ReturnType, functionInfo.UniqueName);
            var separator = false;

            for (var i = 0; i < functionInfo.Parameters.Count; i++)
            {
                var parameterInfo = functionInfo.Parameters[i];
                if (separator)
                {
                    contents.Append(", ");
                }
                separator = true;

                contents.Append(parameterInfo.Type);
                contents.Append(' ');
                contents.Append(parameterInfo.Name);
            }

            contents.Append(')');
            contents.AppendLine();
            contents.AppendLine("    {");
            contents.AppendLine($"        auto object = ({classInfo.NativeName}*)this;");
            contents.AppendLine("        static THREADLOCAL void* WrapperCallInstance = nullptr;");
            contents.AppendLine("        if (WrapperCallInstance == object)");
            contents.AppendLine("        {");
            contents.AppendLine("            // Prevent stack overflow by calling base method");
            contents.AppendLine("            const auto scriptVTableBase = object->GetType().Script.ScriptVTableBase;");
            contents.Append($"            return (object->**({functionInfo.UniqueName}_Signature*)&scriptVTableBase[{scriptVTableIndex} + 2])(");
            separator = false;
            for (var i = 0; i < functionInfo.Parameters.Count; i++)
            {
                var parameterInfo = functionInfo.Parameters[i];
                if (separator)
                {
                    contents.Append(", ");
                }
                separator = true;
                contents.Append(parameterInfo.Name);
            }
            contents.AppendLine(");");
            contents.AppendLine("        }");
            contents.AppendLine("        auto scriptVTable = (VisualScript::Method**)object->GetType().Script.ScriptVTable;");
            contents.AppendLine($"        ASSERT(scriptVTable && scriptVTable[{scriptVTableIndex}]);");

            if (functionInfo.Parameters.Count != 0)
            {
                contents.AppendLine($"        Variant parameters[{functionInfo.Parameters.Count}];");
                for (var i = 0; i < functionInfo.Parameters.Count; i++)
                {
                    var parameterInfo = functionInfo.Parameters[i];
                    contents.AppendLine($"        parameters[{i}] = {BindingsGenerator.GenerateCppWrapperNativeToVariant(buildData, parameterInfo.Type, classInfo, parameterInfo.Name)};");
                }
            }
            else
            {
                contents.AppendLine("        Variant* parameters = nullptr;");
            }

            contents.AppendLine("        auto prevWrapperCallInstance = WrapperCallInstance;");
            contents.AppendLine("        WrapperCallInstance = object;");
            contents.AppendLine($"        auto __result = VisualScripting::Invoke(scriptVTable[{scriptVTableIndex}], object, Span<Variant>(parameters, {functionInfo.Parameters.Count}));");
            contents.AppendLine("        WrapperCallInstance = prevWrapperCallInstance;");

            if (!functionInfo.ReturnType.IsVoid)
            {
                contents.AppendLine($"        return {BindingsGenerator.GenerateCppWrapperVariantToNative(buildData, functionInfo.ReturnType, classInfo, "__result")};");
            }

            contents.AppendLine("    }");
            contents.AppendLine();
        }
		internal UnmanagedCallTreeNode64(UnmanagedProfilingDataSet dataSet, FunctionInfo* data, CallTreeNode parent)
		{
			this.data = data;
			this.dataSet = dataSet;
			this.parent = parent;
		}
Example #25
0
        public override void Optimize(ref CodeNode _this, FunctionDefinition owner, InternalCompilerMessageCallback message, Options opts, FunctionInfo stats)
        {
            base.Optimize(ref _this, owner, message, opts, stats);
            if (message != null)
            {
                var fc = _left as Constant ?? _right as Constant;
                if (fc != null)
                {
                    switch (fc.value._valueType)
                    {
                    case JSValueType.Undefined:
                        message(MessageLevel.Warning, Position, Length, "To compare with undefined use '===' or '!==' instead of '==' or '!='.");
                        break;

                    case JSValueType.Object:
                        if (fc.value._oValue == null)
                        {
                            message(MessageLevel.Warning, Position, Length, "To compare with null use '===' or '!==' instead of '==' or '!='.");
                        }
                        break;
                    }
                }
            }
        }
Example #26
0
    //
    // Method:  DefineType
    //
    // Given a type name and a 'method string', construct a new
    // type in a dynamic module in a dynamic assembly. The new type's
    // function in life is to wrap up Hugs functions, so that when
    // its methods are invoked, they will delegate the call to their
    // corresponding Hugs function.
    //
    public static String DefineType(String typeName, String super, String methodSpecs)
    {
        Int32 count   = 0;
           Int32 idx     = 0;
           Int32 i       = 0;
           Int32 len     = methodSpecs.Length;
           MethodBuilder   methodBuilder;

           // Ideally, we want to pass the method strings in an array, but
           // I'm running into issues passing arrays via the Hugs .NET primops
           // (specifically, how to make Convert.ChangeType() deal with the
           // arrays.)
           //
           // So, temporarily, we separate the method strings by '/'.
           //
           while (idx >= 0 ) {
         idx = methodSpecs.IndexOf('/');
         count++;
         methodSpecs = methodSpecs.Substring(idx+1);
           }

           String[] methods = new String[count];
           idx = 0; count = 0;
           while (idx >= 0 ) {
         idx = methodSpecs.IndexOf('/');
         if (idx == (-1)) {
           methods[count] = methodSpecs.Substring(0);
         } else {
           methods[count] = methodSpecs.Substring(0,Math.Max(0,idx));
         }
         count++;
           }
           Int32 no = methods.Length;
           String theTypeName;
           TypeBuilder typeBuilder = null;

           theTypeName = typeName;
           while (true) {
         try {
           if (super != null && super.Length > 0) {
         Type supTy = DynInvoke.InvokeBridge.GetType(super);
         typeBuilder = moduleBuilder.DefineType(theTypeName, TypeAttributes.Public, supTy);
         Console.WriteLine("Succeeded creating {0} type", supTy);
           } else {
         typeBuilder = moduleBuilder.DefineType(theTypeName, TypeAttributes.Public);
           }
           break;
         } catch (ArgumentException) {
           uniq++;
           theTypeName = typeName + uniq;
         }
           }
           Console.WriteLine("Succeeded creating {0} type", theTypeName);

           ConstructorBuilder constructorBuilder =
         typeBuilder.DefineConstructor(MethodAttributes.Public,
                   CallingConventions.Standard,
                   null);
           ILGenerator ilGenerator = constructorBuilder.GetILGenerator();
           FieldBuilder fieldBuilder;

           // Call the base constructor -- required?
           ilGenerator.Emit(OpCodes.Ldarg_0);
           Type[] ctor_args = new Type[0];
           ilGenerator.Emit(OpCodes.Call,Type.GetType("System.Object").GetConstructor(ctor_args));

           for (i=0;i < no; i++) {
         fieldBuilder =
           typeBuilder.DefineField("spec_" + i,
                   typeof(String),
                   FieldAttributes.Private);
         // assign the field.
         ilGenerator.Emit(OpCodes.Ldarg_0);
         ilGenerator.Emit(OpCodes.Ldstr,methods[i]);
         ilGenerator.Emit(OpCodes.Stfld, fieldBuilder);

         FunctionInfo fi = new FunctionInfo(methods[i]);

         methodBuilder =
           typeBuilder.DefineMethod(fi.methodName,
                MethodAttributes.Public | MethodAttributes.Virtual,
                CallingConventions.Standard,
                (fi.resTy.Length == 0 ? Type.GetType("System.Void") : FunctionInfo.tagToType(fi.resTy[0])),
                FunctionInfo.tagsToType(fi.argTys));

         ILGenerator ilGen = methodBuilder.GetILGenerator();

         ilGen.DeclareLocal(typeof(Object[]));
         ilGen.Emit(OpCodes.Ldc_I4,fi.argTys.Length);
         ilGen.Emit(OpCodes.Newarr,typeof(Object));
         ilGen.Emit(OpCodes.Stloc_0);

         for (Int32 j=0; j < fi.argTys.Length; j++) {
           ilGen.Emit(OpCodes.Ldloc_0);
           ilGen.Emit(OpCodes.Ldc_I4,j);
           switch (j+1) {
           case 1 : ilGen.Emit(OpCodes.Ldarg_1); break;
           case 2 : ilGen.Emit(OpCodes.Ldarg_2); break;
           case 3 : ilGen.Emit(OpCodes.Ldarg_3); break;
           default: ilGen.Emit(OpCodes.Ldarg,j+1); break;
           }
           if (fi.argTys[j] == 'I') {
         ilGen.Emit(OpCodes.Box,Type.GetType("System.Int32"));
           }
           ilGen.Emit(OpCodes.Stelem_Ref);
         }
         ilGen.Emit(OpCodes.Ldarg_0);
         ilGen.Emit(OpCodes.Ldfld,fieldBuilder);
         ilGen.Emit(OpCodes.Ldloc_0);
         ilGen.Emit(OpCodes.Call, Type.GetType("HugsWrapper").GetMethod("InvokeFunction"));

         // pop the result off of the stack when returning void.
         if (fi.resTy.Length > 0 && fi.resTy[0] == 'V') {
           ilGen.Emit(OpCodes.Pop);
         }
         ilGen.Emit(OpCodes.Ret);

         // of 'delegator' shape?
         if ((fi.resTy.Length  == 1 && fi.resTy[0] == 'V') &&
         (fi.argTys.Length == 2 && fi.argTys[1] == 'O' && fi.argTys[1] == 'O')) {
           Type[] del_args = new Type[2];
           del_args[0] = typeof(Object);
           del_args[1] = Type.GetType("System.EventArgs");
           MethodBuilder delegator =
         typeBuilder.DefineMethod(fi.methodName + "_delegator",
                  MethodAttributes.Public,
                  CallingConventions.Standard,
                  typeof(void),
                  del_args);
           // Simple stuff - just delegate the call (do we really need this meth?)
           ILGenerator delIl = delegator.GetILGenerator();
           delIl.Emit(OpCodes.Ldarg_0);
           delIl.Emit(OpCodes.Ldarg_1);
           delIl.Emit(OpCodes.Ldarg_2);
           delIl.Emit(OpCodes.Call,methodBuilder);
           delIl.Emit(OpCodes.Ret);

           // Type compatible with a delegator, create impedance matchers for free.
           fieldBuilder =
         typeBuilder.DefineField(fi.methodName + "_handler",
                 Type.GetType("System.EventHandler"),
                 FieldAttributes.Public);

           ilGenerator.Emit(OpCodes.Ldarg_0);
           ilGenerator.Emit(OpCodes.Ldarg_0);
           ilGenerator.Emit(OpCodes.Ldftn,delegator);
           Type[] eh_args = new Type[2];
           eh_args[0] = typeof(Object);
           eh_args[1] = Type.GetType("System.IntPtr");
           ConstructorInfo ci = Type.GetType("System.EventHandler").GetConstructor(eh_args);
           ilGenerator.Emit(OpCodes.Newobj,ci);
           ilGenerator.Emit(OpCodes.Stfld,fieldBuilder);
         }
           }
           ilGenerator.Emit(OpCodes.Ret);

           Type res = typeBuilder.CreateType();

           Console.WriteLine("Succeeded creating {0} type..", res);

           // For debugging purposes, persist the generated assembly.
           // (this goes hand-in-hand with the dynamic, persistable module
           // we created above).
           //   assemblyBuilder.Save("foo.dll");
           return theTypeName;
    }
Example #27
0
        public override void Optimize(ref CodeNode _this, Expressions.FunctionDefinition owner, InternalCompilerMessageCallback message, Options opts, FunctionInfo stats)
        {
            if (value != null)
            {
                var t = value as CodeNode;
                value.Optimize(ref t, owner, message, opts, stats);
                value = (Expression)t;

                if (value is Empty || ((value is Constant) && value.Evaluate(null) == JSValue.undefined))
                {
                    value = null;
                }
            }
        }
Example #28
0
        internal static FunctionInfo CreateFunctionInfo(
            Delegate generatorFactory,
            string name,
            DebugSourceSpan[] locationSpanMap,
            IList<VariableInfo>[] scopedVariables,
            IList<VariableInfo> variables,
            object customPayload) {
            FunctionInfo funcInfo = new FunctionInfo(
                generatorFactory,
                name,
                locationSpanMap,
                scopedVariables,
                variables,
                customPayload);
            
            foreach (DebugSourceSpan sourceSpan in (DebugSourceSpan[])locationSpanMap) {
                lock (sourceSpan.SourceFile.FunctionInfoMap) {
                    sourceSpan.SourceFile.FunctionInfoMap[sourceSpan] = funcInfo;
                }
            }

            return funcInfo;
        }
Example #29
0
        public override bool Build(ref CodeNode _this, int expressionDepth, Dictionary <string, VariableDescriptor> variables, CodeContext codeContext, InternalCompilerMessageCallback message, FunctionInfo stats, Options opts)
        {
            Parser.Build(ref value, expressionDepth + 1, variables, codeContext | CodeContext.InExpression, message, stats, opts);
            // Улучшает работу оптимизатора хвостовой рекурсии
            if (message == null && value is Conditional)
            {
                var bat = value as NiL.JS.Expressions.Conditional;

                var bts = bat.Threads;
                _this = new IfElse(bat.LeftOperand, new Return(bts[0]), new Return(bts[1]))
                {
                    Position = bat.Position, Length = bat.Length
                };
                return(true);
            }
            else if (value is Call)
            {
                (value as Call).allowTCO = true;
            }

            stats.Returns.Add(value ?? Empty.Instance);

            return(false);
        }
Example #30
0
 public static void ReduceCallDepth(FunctionInfo functionInfo, int callCount, int newLimit) {
     Add("R", functionInfo, callCount, newLimit);
 }
Example #31
0
 public override bool Build(ref CodeNode _this, int expressionDepth, Dictionary <string, VariableDescriptor> variables, CodeContext codeContext, InternalCompilerMessageCallback message, FunctionInfo stats, Options opts)
 {
     Parser.Build(ref _body, 2, variables, codeContext | CodeContext.InExpression, message, stats, opts);
     return(false);
 }
Example #32
0
        /// <summary>
        /// Initializes a new Module with specified code, callback for output compiler messages and compiler options.
        /// </summary>
        /// <param name="path">Path to file with script. Used for resolving paths to other modules for importing via import directive. Can be null or empty</param>
        /// <param name="code">JavaScript code.</param>
        /// <param name="messageCallback">Callback used to output compiler messages or null</param>
        /// <param name="options">Compiler options</param>
        public Module(string path, string code, CompilerMessageCallback messageCallback, Options options)
        {
            if (code == null)
            {
                throw new ArgumentNullException();
            }

            Code            = code;
            Context         = new Context(Context.CurrentGlobalContext, true, null);
            Context._module = this;
            if (!string.IsNullOrWhiteSpace(path))
            {
                lock (__modulesCache)
                {
                    if (!__modulesCache.ContainsKey(path))
                    {
                        __modulesCache[path] = this;
                    }
                }

                FilePath = path;
            }

            if (code == "")
            {
                return;
            }

            var internalCallback = messageCallback != null ?
                                   (level, position, length, message) => messageCallback(level, CodeCoordinates.FromTextPosition(code, position, length), message)
                : null as InternalCompilerMessageCallback;

            int i = 0;

            _root = (CodeBlock)CodeBlock.Parse(new ParseInfo(Tools.removeComments(code, 0), Code, internalCallback), ref i);

            var stat = new FunctionInfo();

            Parser.Build(ref _root, 0, new Dictionary <string, VariableDescriptor>(), CodeContext.None, internalCallback, stat, options);
            var body = _root as CodeBlock;

            body._suppressScopeIsolation = SuppressScopeIsolationMode.Suppress;
            Context._thisBind            = new GlobalObject(Context);
            Context._strict = body._strict;

            var tv = stat.WithLexicalEnvironment ? null : new Dictionary <string, VariableDescriptor>();

            body.RebuildScope(stat, tv, body._variables.Length == 0 || !stat.WithLexicalEnvironment ? 1 : 0);
            var bd = body as CodeNode;

            body.Optimize(ref bd, null, internalCallback, options, stat);
            if (tv != null)
            {
                body._variables = new List <VariableDescriptor>(tv.Values).ToArray();
            }

            if (stat.NeedDecompose)
            {
                body.Decompose(ref bd);
            }
        }
Example #33
0
 public override void Optimize(ref CodeNode _this, FunctionDefinition owner, InternalCompilerMessageCallback message, Options opts, FunctionInfo stats)
 {
     if (_body != null)
     {
         _body.Optimize(ref _body, owner, message, opts, stats);
     }
 }
Example #34
0
 public override bool Build(ref CodeNode _this, int expressionDepth, Dictionary <string, VariableDescriptor> variables, CodeContext codeContext, InternalCompilerMessageCallback message, FunctionInfo stats, Options opts)
 {
     return(_definition.Build(ref _this, expressionDepth, variables, codeContext, message, stats, opts));
 }
Example #35
0
        public override bool Build(ref CodeNode _this, int expressionDepth, Dictionary <string, VariableDescriptor> variables, CodeContext codeContext, CompilerMessageCallback message, FunctionInfo stats, Options opts)
        {
            _codeContext = codeContext;

            VariableDescriptor desc = null;

            if (!variables.TryGetValue(_variableName, out desc) || desc == null)
            {
                desc = new VariableDescriptor(this, 1)
                {
                    isDefined = false
                };
                variables[_variableName] = this.Descriptor;
            }
            else
            {
                if (!desc.references.Contains(this))
                {
                    desc.references.Add(this);
                }
                _descriptor = desc;
            }

            if (_variableName == "this")
            {
                stats.ContainsThis        = true;
                desc.definitionScopeLevel = -1;
            }
            else if (((codeContext & CodeContext.InWith) != 0) || (stats.ContainsEval && !desc.isDefined))
            {
                ScopeLevel = -Math.Abs(ScopeLevel);
                desc.definitionScopeLevel = -Math.Abs(desc.definitionScopeLevel);
            }

            _ForceThrow |= desc.lexicalScope; // часть TDZ

            if (expressionDepth >= 0 && expressionDepth < 2 && desc.IsDefined && !desc.lexicalScope && (opts & Options.SuppressUselessExpressionsElimination) == 0)
            {
                _this      = null;
                Eliminated = true;
                if (message != null)
                {
                    message(MessageLevel.Warning, new CodeCoordinates(0, Position, Length), "Unused getting of defined variable was removed. Maybe something missing.");
                }
            }
            else if (_variableName == "arguments" && (codeContext & CodeContext.InFunction) != 0)
            {
                if (stats != null)
                {
                    stats.ContainsArguments = true;
                }
                _this = new GetArgumentsExpression(ScopeLevel)
                {
                    _descriptor = _descriptor
                };
            }

            return(false);
        }
Example #36
0
 public FunctionPredifined(FunctionInfo functionInfo, ElementGenerator <T> functionGenerator)
 {
     FunctionInfo      = functionInfo;
     FunctionGenerator = functionGenerator;
 }
Example #37
0
        public override void Optimize(ref CodeNode _this, FunctionDefinition owner, CompilerMessageCallback message, Options opts, FunctionInfo stats)
        {
            if ((opts & Options.SuppressConstantPropogation) == 0 &&
                !_descriptor.captured &&
                _descriptor.isDefined &&
                !stats.ContainsWith &&
                !stats.ContainsEval &&
                (_descriptor.owner != owner || !owner._functionInfo.ContainsArguments))
            {
                var assigns = _descriptor.assignments;
                if (assigns != null && assigns.Count > 0)
                {
                    /*
                     * Применение оптимизации зависит от порядка добавления присваиваний.
                     * Этот порядок в свою очередь зависит от порядка следования операций в CodeBlock.
                     * Раньше этот порядок был обратным, сейчас прямой, поэтому здесь присваивания нужно перебирать
                     * в обратном порядке. Оптимизация не применится если найдется изменение в котором first указывает на
                     * это использование. Это говорит о том, что в данном месте этой переменной
                     * присваивается значение
                     */
                    CodeNode lastAssign = null;
                    for (var i = assigns.Count; i-- > 0;)
                    {
                        if (assigns[i]._left == this ||
                            ((assigns[i]._left is AssignmentOperatorCache) && assigns[i]._left._left == this))
                        {
                            // оптимизация не применяется
                            lastAssign = null;
                            break;
                        }

                        if (assigns[i].Position > Position)
                        {
                            if ((_codeContext & CodeContext.InLoop) != 0 && ((assigns[i] as Expression)._codeContext & CodeContext.InLoop) != 0)
                            // присваивание может быть после этого использования, но если всё это в цикле, то выполнение вернётся сюда.
                            {
                                // оптимизация не применяется
                                lastAssign = null;
                                break;
                            }
                            continue; // пропускаем ноду
                        }

                        if (_descriptor.isReadOnly)
                        {
                            if (assigns[i] is ForceAssignmentOperator)
                            {
                                lastAssign = assigns[i];
                                break;
                            }
                        }
                        else if (lastAssign == null || assigns[i].Position > lastAssign.Position)
                        {
                            lastAssign = assigns[i];
                        }
                    }
                    var assign = lastAssign as Assignment;
                    if (assign != null && (assign._codeContext & CodeContext.Conditional) == 0 && assign._right is Constant)
                    {
                        _this = assign._right;
                    }
                }
            }
        }
Example #38
0
        /// <summary>
        /// Gets a list of matching commands
        /// </summary>
        /// <param name="pattern">command pattern</param>
        /// <param name="commandOrigin"></param>
        /// <param name="context"></param>
        /// <param name="rediscoverImportedModules"></param>
        /// <param name="moduleVersionRequired"></param>
        /// <returns></returns>
        internal static IEnumerable<CommandInfo> GetMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, bool rediscoverImportedModules = false, bool moduleVersionRequired = false)
        {
            // Otherwise, if it had wildcards, just return the "AvailableCommand"
            // type of command info.
            WildcardPattern commandPattern = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);

            CmdletInfo cmdletInfo = context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Get-Module");
            PSModuleAutoLoadingPreference moduleAutoLoadingPreference = CommandDiscovery.GetCommandDiscoveryPreference(context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference");

            if ((moduleAutoLoadingPreference != PSModuleAutoLoadingPreference.None) &&
                    ((commandOrigin == CommandOrigin.Internal) || ((cmdletInfo != null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public))
                    )
                )
            {
                foreach (string modulePath in GetDefaultAvailableModuleFiles(true, false, context))
                {
                    // Skip modules that have already been loaded so that we don't expose private commands.
                    string moduleName = Path.GetFileNameWithoutExtension(modulePath);
                    var modules = context.Modules.GetExactMatchModules(moduleName, all: false, exactMatch: true);
                    PSModuleInfo tempModuleInfo = null;

                    if (modules.Count != 0)
                    {
                        // 1. We continue to the next module path if we don't want to re-discover those imported modules
                        // 2. If we want to re-discover the imported modules, but one or more commands from the module were made private, 
                        //    then we don't do re-discovery
                        if (!rediscoverImportedModules || modules.Exists(module => module.ModuleHasPrivateMembers))
                        {
                            continue;
                        }

                        if (modules.Count == 1)
                        {
                            PSModuleInfo psModule = modules[0];
                            tempModuleInfo = new PSModuleInfo(psModule.Name, psModule.Path, null, null);
                            tempModuleInfo.SetModuleBase(psModule.ModuleBase);

                            foreach (var entry in psModule.ExportedCommands)
                            {
                                if (commandPattern.IsMatch(entry.Value.Name))
                                {
                                    CommandInfo current = null;
                                    switch (entry.Value.CommandType)
                                    {
                                        case CommandTypes.Alias:
                                            current = new AliasInfo(entry.Value.Name, null, context);
                                            break;
                                        case CommandTypes.Workflow:
                                            current = new WorkflowInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                            break;
                                        case CommandTypes.Function:
                                            current = new FunctionInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                            break;
                                        case CommandTypes.Filter:
                                            current = new FilterInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                            break;
                                        case CommandTypes.Configuration:
                                            current = new ConfigurationInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                            break;
                                        case CommandTypes.Cmdlet:
                                            current = new CmdletInfo(entry.Value.Name, null, null, null, context);
                                            break;
                                        default:
                                            Dbg.Assert(false, "cannot be hit");
                                            break;
                                    }

                                    current.Module = tempModuleInfo;
                                    yield return current;
                                }
                            }

                            continue;
                        }
                    }

                    string moduleShortName = System.IO.Path.GetFileNameWithoutExtension(modulePath);
                    var exportedCommands = AnalysisCache.GetExportedCommands(modulePath, false, context);

                    if (exportedCommands == null) { continue; }

                    tempModuleInfo = new PSModuleInfo(moduleShortName, modulePath, null, null);
                    if (InitialSessionState.IsEngineModule(moduleShortName))
                    {
                        tempModuleInfo.SetModuleBase(Utils.GetApplicationBase(Utils.DefaultPowerShellShellID));
                    }

                    //moduleVersionRequired is bypassed by FullyQualifiedModule from calling method. This is the only place where guid will be involved.
                    if (moduleVersionRequired && modulePath.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
                    {
                        tempModuleInfo.SetVersion(ModuleIntrinsics.GetManifestModuleVersion(modulePath));
                        tempModuleInfo.SetGuid(ModuleIntrinsics.GetManifestGuid(modulePath));
                    }

                    foreach (var pair in exportedCommands)
                    {
                        var commandName = pair.Key;
                        var commandTypes = pair.Value;

                        if (commandPattern.IsMatch(commandName))
                        {
                            bool shouldExportCommand = true;

                            // Verify that we don't already have it represented in the initial session state.
                            if ((context.InitialSessionState != null) && (commandOrigin == CommandOrigin.Runspace))
                            {
                                foreach (SessionStateCommandEntry commandEntry in context.InitialSessionState.Commands[commandName])
                                {
                                    string moduleCompareName = null;

                                    if (commandEntry.Module != null)
                                    {
                                        moduleCompareName = commandEntry.Module.Name;
                                    }
                                    else if (commandEntry.PSSnapIn != null)
                                    {
                                        moduleCompareName = commandEntry.PSSnapIn.Name;
                                    }

                                    if (String.Equals(moduleShortName, moduleCompareName, StringComparison.OrdinalIgnoreCase))
                                    {
                                        if (commandEntry.Visibility == SessionStateEntryVisibility.Private)
                                        {
                                            shouldExportCommand = false;
                                        }
                                    }
                                }
                            }

                            if (shouldExportCommand)
                            {
                                if ((commandTypes & CommandTypes.Alias) == CommandTypes.Alias)
                                {
                                    yield return new AliasInfo(commandName, null, context)
                                    {
                                        Module = tempModuleInfo
                                    };
                                }
                                if ((commandTypes & CommandTypes.Cmdlet) == CommandTypes.Cmdlet)
                                {
                                    yield return new CmdletInfo(commandName, implementingType: null, helpFile: null, PSSnapin: null, context: context)
                                    {
                                        Module = tempModuleInfo
                                    };
                                }
                                if ((commandTypes & CommandTypes.Function) == CommandTypes.Function)
                                {
                                    yield return new FunctionInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
                                    {
                                        Module = tempModuleInfo
                                    };
                                }
                                if ((commandTypes & CommandTypes.Configuration) == CommandTypes.Configuration)
                                {
                                    yield return new ConfigurationInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
                                    {
                                        Module = tempModuleInfo
                                    };
                                }
                                if ((commandTypes & CommandTypes.Workflow) == CommandTypes.Workflow)
                                {
                                    yield return new WorkflowInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
                                    {
                                        Module = tempModuleInfo
                                    };
                                }
                            }
                        }
                    }
                }
            }
        }
Example #39
0
        CreateCommandProcessor
        (
            ExecutionContext executionContext,
            bool addToHistory,
            CommandOrigin origin
        )
        {
            Dbg.Assert(executionContext != null, "Caller should verify the parameters");

            CommandProcessorBase commandProcessorBase;

            if (IsScript)
            {
                if ((executionContext.LanguageMode == PSLanguageMode.NoLanguage) &&
                    (origin == Automation.CommandOrigin.Runspace))
                {
                    throw InterpreterError.NewInterpreterException(CommandText, typeof(ParseException),
                                                                   null, "ScriptsNotAllowed", ParserStrings.ScriptsNotAllowed);
                }

                ScriptBlock scriptBlock = executionContext.Engine.ParseScriptBlock(CommandText, addToHistory);
                if (origin == Automation.CommandOrigin.Internal)
                {
                    scriptBlock.LanguageMode = PSLanguageMode.FullLanguage;
                }

                // If running in restricted language mode, verify that the parse tree represents on legitimate
                // constructions...
                switch (scriptBlock.LanguageMode)
                {
                case PSLanguageMode.RestrictedLanguage:
                    scriptBlock.CheckRestrictedLanguage(null, null, false);
                    break;

                case PSLanguageMode.FullLanguage:
                    // Interactive script commands are permitted in this mode.
                    break;

                case PSLanguageMode.ConstrainedLanguage:
                    // Constrained Language is checked at runtime.
                    break;

                default:
                    // This should never happen...
                    Diagnostics.Assert(false, "Invalid language mode was set when building a ScriptCommandProcessor");
                    throw new InvalidOperationException("Invalid language mode was set when building a ScriptCommandProcessor");
                }

                if (scriptBlock.UsesCmdletBinding)
                {
                    FunctionInfo functionInfo = new FunctionInfo(string.Empty, scriptBlock, executionContext);
                    commandProcessorBase = new CommandProcessor(functionInfo, executionContext,
                                                                _useLocalScope ?? false, fromScriptFile: false, sessionState: executionContext.EngineSessionState);
                }
                else
                {
                    commandProcessorBase = new DlrScriptCommandProcessor(scriptBlock,
                                                                         executionContext, _useLocalScope ?? false,
                                                                         origin,
                                                                         executionContext.EngineSessionState,
                                                                         DollarUnderbar);
                }
            }
            else
            {
                // RestrictedLanguage / NoLanguage do not support dot-sourcing when CommandOrigin is Runspace
                if ((_useLocalScope.HasValue) && (!_useLocalScope.Value))
                {
                    switch (executionContext.LanguageMode)
                    {
                    case PSLanguageMode.RestrictedLanguage:
                    case PSLanguageMode.NoLanguage:
                        string message = StringUtil.Format(RunspaceStrings.UseLocalScopeNotAllowed,
                                                           "UseLocalScope",
                                                           nameof(PSLanguageMode.RestrictedLanguage),
                                                           nameof(PSLanguageMode.NoLanguage));
                        throw new RuntimeException(message);

                    case PSLanguageMode.FullLanguage:
                        // Interactive script commands are permitted in this mode...
                        break;
                    }
                }

                commandProcessorBase = executionContext.CommandDiscovery.LookupCommandProcessor(CommandText, origin, _useLocalScope);
            }

            CommandParameterCollection parameters = Parameters;

            if (parameters != null)
            {
                bool isNativeCommand = commandProcessorBase is NativeCommandProcessor;
                foreach (CommandParameter publicParameter in parameters)
                {
                    CommandParameterInternal internalParameter = CommandParameter.ToCommandParameterInternal(publicParameter, isNativeCommand);
                    commandProcessorBase.AddParameter(internalParameter);
                }
            }

            string       helpTarget;
            HelpCategory helpCategory;

            if (commandProcessorBase.IsHelpRequested(out helpTarget, out helpCategory))
            {
                commandProcessorBase = CommandProcessorBase.CreateGetHelpCommandProcessor(
                    executionContext,
                    helpTarget,
                    helpCategory);
            }

            // Set the merge settings
            SetMergeSettingsOnCommandProcessor(commandProcessorBase);

            return(commandProcessorBase);
        }
Example #40
0
 public FunctionListItem(FunctionInfo function)
 {
     this.Function = function;
 }
Example #41
0
 public override bool Build(ref CodeNode _this, int expressionDepth, Dictionary <string, VariableDescriptor> variables, CodeContext codeContext, InternalCompilerMessageCallback message, FunctionInfo stats, Options opts)
 {
     if (expressionDepth < 1)
     {
         throw new InvalidOperationException();
     }
     Parser.Build(ref image, 2, variables, codeContext | CodeContext.InExpression, message, stats, opts);
     for (int i = 0; i < lines.Length; i++)
     {
         Parser.Build(ref lines[i], 1, variables, codeContext | CodeContext.Conditional, message, stats, opts);
     }
     for (int i = 0; functions != null && i < functions.Length; i++)
     {
         CodeNode stat = functions[i];
         Parser.Build(ref stat, 1, variables, codeContext, message, stats, opts);
     }
     functions = null;
     for (int i = 1; i < cases.Length; i++)
     {
         Parser.Build(ref cases[i].statement, 2, variables, codeContext, message, stats, opts);
     }
     return(false);
 }
		static WixPreprocessorExtension() {
			//Debugger.Launch();
			Type IWiXExtensionType = typeof(IWiXPreprocessorExtension);
			Type IWiXDocumentExtensionType = typeof(IWiXDocumentExtension);

			classes = new Dictionary<string, FunctionInfo>(3);
			documentClasses = new Dictionary<string, NodeInfo>(3);
			List<string> names = new List<string>(1);
			List<string> documentNames = new List<string>(1);

			foreach (Type t in typeof(WixPreprocessorExtension).Assembly.GetTypes()) {
				#region Load document extensions
				if (IWiXDocumentExtensionType.IsAssignableFrom(t)) {
					//Create an instance of this object and hold onto it
					IWiXDocumentExtension instance = null;
					try { instance = (IWiXDocumentExtension)t.Assembly.CreateInstance(t.FullName, true); } catch { }
					if (instance != null) {
						string name = camelCaseName(t.Name);

						NodeInfo info = new NodeInfo() {
							Instance = instance,
							ExtensionType = t,
							CamelCaseName = name, 
							Name = t.Name
						};

						documentClasses.Add(t.Name.ToLower(), info);
						documentNames.Add(t.Name);
					}
				}
				#endregion

				#region Load function extensions
				if (IWiXExtensionType.IsAssignableFrom(t)) {
					#region Look for public methods
					MethodInfo[] methods = t.GetMethods();
					if (methods == null || methods.Length <= 0)
						continue;
					#endregion

					List<MethodInfo> validMethods = new List<MethodInfo>(3);
					foreach (MethodInfo mi in methods) {
						#region Double check it's public and NOT static
						if (!mi.IsPublic || mi.IsStatic)
							continue;
						#endregion

						#region Check return type
						if (mi.ReturnType == null || !mi.ReturnType.Equals(typeof(string)))
							continue;
						#endregion

						#region Check parameters
						ParameterInfo[] parameters = mi.GetParameters();
						if (parameters == null || parameters.Length <= 0)
							continue;

						//Must have 1 param
						if (parameters.Length != 1)
							continue;

						if (/* must have (string[] args) param */!parameters[0].ParameterType.Equals(typeof(string[])))
							continue;
						#endregion

						validMethods.Add(mi);
					}

					//If we couldn't find any methods that fit the bill, then don't add this as a 
					//valid prefix and enable access to it.
					if (validMethods.Count <= 0)
						continue;

					//Create an instance of this object and hold onto it
					object instance = null;
					try { instance = t.Assembly.CreateInstance(t.FullName, true); } catch { }
					if (instance == null)
						continue;

					string name = camelCaseName(t.Name);

					FunctionInfo info = new FunctionInfo() {
						ExtensionType = t, 
						Functions = validMethods.ToArray(), 
						Instance = instance, 
						Name = name
					};

					classes.Add(t.Name.ToLower(), info);
					names.Add(name);
				}
				#endregion
			}

			prefixes = names.ToArray();
			nodeNames = documentNames.ToArray();
		}
Example #43
0
 public override void Optimize(ref CodeNode _this, Expressions.FunctionDefinition owner, InternalCompilerMessageCallback message, Options opts, FunctionInfo stats)
 {
     image.Optimize(ref image, owner, message, opts, stats);
     for (var i = 1; i < cases.Length; i++)
     {
         cases[i].statement.Optimize(ref cases[i].statement, owner, message, opts, stats);
     }
     for (var i = lines.Length; i-- > 0;)
     {
         if (lines[i] == null)
         {
             continue;
         }
         var cn = lines[i] as CodeNode;
         cn.Optimize(ref cn, owner, message, opts, stats);
         lines[i] = cn;
     }
 }
Example #44
0
        internal static FunctionInfo AddFunction(FunctionDefinition node, AnalysisUnit outerUnit, InterpreterScope prevScope) {
            InterpreterScope scope;
            if (!prevScope.TryGetNodeScope(node, out scope)) {
                if (node.Body == null || node.Name == null) {
                    return null;
                }

                var func = new FunctionInfo(node, outerUnit, prevScope);
                var unit = func.AnalysisUnit;
                scope = unit.Scope;

                prevScope.Children.Add(scope);
                prevScope.AddNodeScope(node, scope);

                if (!node.IsLambda && node.Name != "<genexpr>") {
                    // lambdas don't have their names published

                    var funcVar = prevScope.AddLocatedVariable(node.Name, node.NameExpression, unit);
                    // Decorated functions don't have their type set yet
                    if (node.Decorators == null) {
                        funcVar.AddTypes(unit, func.SelfSet);
                    }
                }

                unit.Enqueue();
            }
            return scope.AnalysisValue as FunctionInfo;
        }
Example #45
0
        private static IReadOnlyList <IFunctionInfo> ParseFunctions(RdParseContext context)
        {
            IReadOnlyList <ISignatureInfo>       signatureInfos       = null;
            IReadOnlyDictionary <string, string> argumentDescriptions = null;
            string functionDescription = null; // Description is normally one for all similar functions
            bool   isInternal          = false;
            string returnValue         = null;

            while (!context.Tokens.IsEndOfStream() && argumentDescriptions == null)
            {
                RdToken token = context.Tokens.CurrentToken;

                if (context.IsAtKeywordWithParameters())
                {
                    if (string.IsNullOrEmpty(functionDescription) && context.IsAtKeyword(@"\description"))
                    {
                        functionDescription = RdText.GetText(context);
                    }
                    else if (context.IsAtKeyword(@"\keyword"))
                    {
                        string keyword = RdText.GetText(context);
                        if (!string.IsNullOrEmpty(keyword) && keyword.Contains("internal"))
                        {
                            isInternal = true;
                        }
                    }
                    else if (string.IsNullOrEmpty(returnValue) && context.IsAtKeyword(@"\value"))
                    {
                        returnValue = RdText.GetText(context);
                    }
                    else if (argumentDescriptions == null && context.IsAtKeyword(@"\arguments"))
                    {
                        // Extract arguments and their descriptions
                        argumentDescriptions = RdArgumentDescription.ExtractArgumentDecriptions(context);
                    }
                    else if (signatureInfos == null && context.IsAtKeyword(@"\usage"))
                    {
                        // Extract signatures with function names
                        signatureInfos = RdFunctionSignature.ExtractSignatures(context);
                    }
                    else
                    {
                        context.Tokens.Advance(2);
                    }
                }
                else
                {
                    context.Tokens.MoveToNextToken();
                }
            }

            // Merge descriptions into signatures. Add all arguments
            // listed in the \arguments{} section since function signature
            // does not always list all possible arguments.
            if (argumentDescriptions != null && signatureInfos != null)
            {
                foreach (ISignatureInfo sigInfo in signatureInfos)
                {
                    // Add missing arguments from the \arguments{} section
                    foreach (string name in argumentDescriptions.Keys)
                    {
                        // TODO: do we need HashSet here instead? Generally arguments
                        // list is relatively short, about 10 items on average.
                        if (sigInfo.Arguments.FirstOrDefault(x => x.Name.Equals(name)) == null)
                        {
                            sigInfo.Arguments.Add(new ArgumentInfo(name));
                        }
                    }

                    // Add description if it is not there yet
                    foreach (var arg in sigInfo.Arguments.Where(x => string.IsNullOrEmpty(x.Description)))
                    {
                        string description;
                        if (argumentDescriptions.TryGetValue(arg.Name, out description))
                        {
                            ((NamedItemInfo)arg).Description = description ?? string.Empty;
                        }
                    }
                }
            }

            // Merge signatures into function infos
            Dictionary <string, FunctionInfo> functionInfos = new Dictionary <string, FunctionInfo>();

            if (signatureInfos != null)
            {
                Dictionary <string, List <ISignatureInfo> > functionSignatures = new Dictionary <string, List <ISignatureInfo> >();
                foreach (ISignatureInfo sigInfo in signatureInfos)
                {
                    FunctionInfo          functionInfo;
                    List <ISignatureInfo> sigList;
                    if (!functionInfos.TryGetValue(sigInfo.FunctionName, out functionInfo))
                    {
                        // Create function info
                        functionInfo = new FunctionInfo(sigInfo.FunctionName, functionDescription);
                        functionInfos[sigInfo.FunctionName] = functionInfo;
                        functionInfo.IsInternal             = isInternal;
                        functionInfo.ReturnValue            = returnValue;
                        // Create list of signatures for this function
                        sigList = new List <ISignatureInfo>();
                        functionSignatures[sigInfo.FunctionName] = sigList;
                        functionInfo.Signatures = sigList;
                    }
                    else
                    {
                        sigList = functionSignatures[sigInfo.FunctionName];
                    }

                    sigList.Add(sigInfo);
                }
            }

            return(functionInfos.Values.ToList());
        }
Example #46
0
    //
    // Method: InvokeFunction()
    //
    // Given a 'method string' and an object array holding the arguments,
    // construct a (Hugs) function application and then perform it.
    //
    public static Object InvokeFunction(String str,Object[] args)
    {
        Int32 i = 0;
           FunctionInfo fi = new FunctionInfo(str);

           Server.LookupName(fi.moduleName,fi.functionName);
           Console.WriteLine("lookupName({0},{1},{2});", fi.moduleName,fi.functionName,fi.argTys);
           while (i < fi.argTys.Length) {
         switch (fi.argTys[i]) {
         case 'I':
           Server.mkInt((int)args[i]);
           break;
         case 'H':
           Server.pushHVal((int)args[i]);
           break;
         case 'S':
           Server.mkString((String)args[i]);
           break;
         case 'O':
           Server.mkObject(args[i]);
           break;
         default:
           Console.WriteLine("bogus type tag {0};ignoring.", fi.argTys[i]);
           break;
         }
         i++;
         if (i % 2 == 1) {
         Console.WriteLine("apply");
           Server.apply();
         }
           }
           if (i > 0 && i%2 == 0) {
         // make sure the last argument is hooked up to an @ node too.
         Server.apply();
         Console.WriteLine("apply");
           }

           if (fi.resTy.Length > 0) {
         switch (fi.resTy[0]) {
         case 'I':
           unsafe {
         int res;
         Server.doIO_Int(&res);
         return (Object)res;
           }
         case 'S':
           unsafe {
         Object res = new Object();
         Server.doIO_Object(ref res);
         return (String)res;
           }
         case 'O':
           unsafe {
         Object res = new Object();
         Server.doIO_Object(ref res);
         return res;
           }
         default:
           Server.doIO();
           return null;
         }
           }
           return null;
    }
Example #47
0
        private void GetFunctionsNameAndCode()
        {
            const int functionNameGroup = 2;
            const int functionCodeGroup = 1;

            string patternFunctionCode = @"(func\s(\w+)\s*\([^\)]*\)[^{]*{)";
            Regex regexFunctionCode = new Regex(patternFunctionCode);
            Match matchFunctionCode = regexFunctionCode.Match(_codeText);

            int numberMatches = 0;
            while (matchFunctionCode.Success)
            {
                Array.Resize(ref _arrayFunction, numberMatches + 1);
                string functionName = matchFunctionCode.Groups[functionNameGroup].Value;
                string functionCode = GetFunctionCode(matchFunctionCode.Groups[functionCodeGroup].Value, matchFunctionCode.Index);
                FunctionInfo elem = new FunctionInfo(functionName, functionCode);
                _arrayFunction[numberMatches] = elem;
                matchFunctionCode = matchFunctionCode.NextMatch();
                numberMatches++;
            }
        }
Example #48
0
 public BoundMethodInfo(FunctionInfo function, AnalysisValue instance) {
     _function = function;
     _instanceInfo = instance;
 }
Example #49
0
        public override void RebuildScope(FunctionInfo functionInfo, Dictionary <string, VariableDescriptor> transferedVariables, int scopeBias)
        {
            base.RebuildScope(functionInfo, transferedVariables, scopeBias);

            _value.RebuildScope(functionInfo, transferedVariables, scopeBias);
        }
Example #50
0
 internal DebugFrame CreateFrameForGenerator(FunctionInfo func) {
     DebugThread thread = GetCurrentThread();
     DebugFrame frame = new DebugFrame(thread, func);
     return frame;
 }
Example #51
0
        static E()
        {
            string description = "Returns the Napier's constant.";

            Info = new FunctionInfo(FunctionName, FunctionCategory.MathTrig, description);
        }
Example #52
0
 internal Expression(ParseNode parent, FunctionInfo function, List<Expression> parameters)
     : base(parent, null)
 {
     type = Type.FunctionCall;
     this.function = function;
     this.parameters = parameters;
 }
Example #53
0
 public FunctionCall(FunctionInfo info)
 {
     Info = info;
 }
Example #54
0
 public override bool Build(ref CodeNode _this, int expressionDepth, Dictionary <string, VariableDescriptor> variables, CodeContext codeContext, InternalCompilerMessageCallback message, FunctionInfo stats, Options opts)
 {
     _codeContext = codeContext;
     return(false);
 }
Example #55
0
        /// <summary>
        /// Gets a list of matching commands
        /// </summary>
        /// <param name="pattern">command pattern</param>
        /// <param name="commandOrigin"></param>
        /// <param name="context"></param>
        /// <param name="rediscoverImportedModules"></param>
        /// <param name="moduleVersionRequired"></param>
        /// <returns></returns>
        internal static IEnumerable <CommandInfo> GetMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, bool rediscoverImportedModules = false, bool moduleVersionRequired = false)
        {
            // Otherwise, if it had wildcards, just return the "AvailableCommand"
            // type of command info.
            WildcardPattern commandPattern = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);

            CmdletInfo cmdletInfo = context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Get-Module");
            PSModuleAutoLoadingPreference moduleAutoLoadingPreference = CommandDiscovery.GetCommandDiscoveryPreference(context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference");

            if ((moduleAutoLoadingPreference != PSModuleAutoLoadingPreference.None) &&
                ((commandOrigin == CommandOrigin.Internal) || ((cmdletInfo != null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public))
                )
                )
            {
                foreach (string modulePath in GetDefaultAvailableModuleFiles(isForAutoDiscovery: false, context))
                {
                    // Skip modules that have already been loaded so that we don't expose private commands.
                    string       moduleName     = Path.GetFileNameWithoutExtension(modulePath);
                    var          modules        = context.Modules.GetExactMatchModules(moduleName, all: false, exactMatch: true);
                    PSModuleInfo tempModuleInfo = null;

                    if (modules.Count != 0)
                    {
                        // 1. We continue to the next module path if we don't want to re-discover those imported modules
                        // 2. If we want to re-discover the imported modules, but one or more commands from the module were made private,
                        //    then we don't do re-discovery
                        if (!rediscoverImportedModules || modules.Exists(module => module.ModuleHasPrivateMembers))
                        {
                            continue;
                        }

                        if (modules.Count == 1)
                        {
                            PSModuleInfo psModule = modules[0];
                            tempModuleInfo = new PSModuleInfo(psModule.Name, psModule.Path, null, null);
                            tempModuleInfo.SetModuleBase(psModule.ModuleBase);

                            foreach (var entry in psModule.ExportedCommands)
                            {
                                if (commandPattern.IsMatch(entry.Value.Name))
                                {
                                    CommandInfo current = null;
                                    switch (entry.Value.CommandType)
                                    {
                                    case CommandTypes.Alias:
                                        current = new AliasInfo(entry.Value.Name, null, context);
                                        break;

                                    case CommandTypes.Function:
                                        current = new FunctionInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                        break;

                                    case CommandTypes.Filter:
                                        current = new FilterInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                        break;

                                    case CommandTypes.Configuration:
                                        current = new ConfigurationInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                        break;

                                    case CommandTypes.Cmdlet:
                                        current = new CmdletInfo(entry.Value.Name, null, null, null, context);
                                        break;

                                    default:
                                        Dbg.Assert(false, "cannot be hit");
                                        break;
                                    }

                                    current.Module = tempModuleInfo;
                                    yield return(current);
                                }
                            }

                            continue;
                        }
                    }

                    string moduleShortName  = System.IO.Path.GetFileNameWithoutExtension(modulePath);
                    var    exportedCommands = AnalysisCache.GetExportedCommands(modulePath, false, context);

                    if (exportedCommands == null)
                    {
                        continue;
                    }

                    tempModuleInfo = new PSModuleInfo(moduleShortName, modulePath, null, null);
                    if (InitialSessionState.IsEngineModule(moduleShortName))
                    {
                        tempModuleInfo.SetModuleBase(Utils.DefaultPowerShellAppBase);
                    }

                    //moduleVersionRequired is bypassed by FullyQualifiedModule from calling method. This is the only place where guid will be involved.
                    if (moduleVersionRequired && modulePath.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
                    {
                        tempModuleInfo.SetVersion(ModuleIntrinsics.GetManifestModuleVersion(modulePath));
                        tempModuleInfo.SetGuid(ModuleIntrinsics.GetManifestGuid(modulePath));
                    }

                    foreach (var pair in exportedCommands)
                    {
                        var commandName  = pair.Key;
                        var commandTypes = pair.Value;

                        if (commandPattern.IsMatch(commandName))
                        {
                            bool shouldExportCommand = true;

                            // Verify that we don't already have it represented in the initial session state.
                            if ((context.InitialSessionState != null) && (commandOrigin == CommandOrigin.Runspace))
                            {
                                foreach (SessionStateCommandEntry commandEntry in context.InitialSessionState.Commands[commandName])
                                {
                                    string moduleCompareName = null;

                                    if (commandEntry.Module != null)
                                    {
                                        moduleCompareName = commandEntry.Module.Name;
                                    }
                                    else if (commandEntry.PSSnapIn != null)
                                    {
                                        moduleCompareName = commandEntry.PSSnapIn.Name;
                                    }

                                    if (String.Equals(moduleShortName, moduleCompareName, StringComparison.OrdinalIgnoreCase))
                                    {
                                        if (commandEntry.Visibility == SessionStateEntryVisibility.Private)
                                        {
                                            shouldExportCommand = false;
                                        }
                                    }
                                }
                            }

                            if (shouldExportCommand)
                            {
                                if ((commandTypes & CommandTypes.Alias) == CommandTypes.Alias)
                                {
                                    yield return(new AliasInfo(commandName, null, context)
                                    {
                                        Module = tempModuleInfo
                                    });
                                }
                                if ((commandTypes & CommandTypes.Cmdlet) == CommandTypes.Cmdlet)
                                {
                                    yield return(new CmdletInfo(commandName, implementingType: null, helpFile: null, PSSnapin: null, context: context)
                                    {
                                        Module = tempModuleInfo
                                    });
                                }
                                if ((commandTypes & CommandTypes.Function) == CommandTypes.Function)
                                {
                                    yield return(new FunctionInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
                                    {
                                        Module = tempModuleInfo
                                    });
                                }
                                if ((commandTypes & CommandTypes.Configuration) == CommandTypes.Configuration)
                                {
                                    yield return(new ConfigurationInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
                                    {
                                        Module = tempModuleInfo
                                    });
                                }
                            }
                        }
                    }
                }
            }
        }
Example #56
0
        public override void Optimize(ref CodeNode _this, FunctionDefinition owner, InternalCompilerMessageCallback message, Options opts, FunctionInfo stats)
        {
            var cn = _value as CodeNode;

            _value.Optimize(ref cn, owner, message, opts, stats);
            _value = cn as Expression;
            base.Optimize(ref _this, owner, message, opts, stats);
        }
Example #57
0
 public void AddFunctionInfo(FunctionInfo functionInfo)
 {
     _gateway.Add(functionInfo);
     Save();
 }