예제 #1
0
        internal void EnterScope(IParameterMetadataProvider ast, ScopeType scopeType)
        {
            var scope = new Scope(ast, scopeType);

            _scopes.Add(scope);
            AddTypesInScope((Ast)ast);
        }
예제 #2
0
 internal Scope(IParameterMetadataProvider ast, ScopeType scopeType)
 {
     _ast           = (Ast)ast;
     _scopeType     = scopeType;
     _typeTable     = new Dictionary <string, TypeLookupResult>(StringComparer.OrdinalIgnoreCase);
     _variableTable = new Dictionary <string, Ast>(StringComparer.OrdinalIgnoreCase);
 }
예제 #3
0
 /// <summary>
 /// Constructor to be called when the wrapper is for a static member method.
 /// </summary>
 internal ScriptBlockMemberMethodWrapper(IParameterMetadataProvider ast, SessionStateKeeper sessionStateKeeper)
     : this(ast)
 {
     _isStatic                 = true;
     _sessionStateKeeper       = sessionStateKeeper;
     _defaultSessionStateToUse = new WeakReference <SessionStateInternal>(null);
 }
예제 #4
0
 /// <summary>
 /// Constructor to be called when the wrapper is for an instance member method.
 /// </summary>
 internal ScriptBlockMemberMethodWrapper(IParameterMetadataProvider ast)
 {
     _ast = ast;
     // This 'Lazy<T>' constructor ensures that only a single thread can initialize the instance in a thread-safe manner.
     _scriptBlock      = new Lazy <ScriptBlock>(() => new ScriptBlock(_ast, isFilter: false));
     _boundScriptBlock = new ThreadLocal <ScriptBlock>(() => _scriptBlock.Value.Clone());
 }
예제 #5
0
 internal Scope(IParameterMetadataProvider ast, ScopeType scopeType)
 {
     _ast = (Ast)ast;
     _scopeType = scopeType;
     _typeTable = new Dictionary<string, TypeLookupResult>(StringComparer.OrdinalIgnoreCase);
     _variableTable = new Dictionary<string, Ast>(StringComparer.OrdinalIgnoreCase);
 }
예제 #6
0
        private IEnumerable <string> GetFunctionAliases(IParameterMetadataProvider ipmp)
        {
            if (ipmp == null || ipmp.Body.ParamBlock == null)
            {
                yield break;
            }

            var attributes = ipmp.Body.ParamBlock.Attributes;

            foreach (var attributeAst in attributes)
            {
                var attributeType = attributeAst.TypeName.GetReflectionAttributeType();
                if (attributeType == typeof(AliasAttribute))
                {
                    var cvv = new ConstantValueVisitor {
                        AttributeArgument = true
                    };
                    for (int i = 0; i < attributeAst.PositionalArguments.Count; i++)
                    {
                        yield return(Compiler._attrArgToStringConverter.Target(Compiler._attrArgToStringConverter,
                                                                               attributeAst.PositionalArguments[i].Accept(cvv)));
                    }
                }
            }
        }
예제 #7
0
 internal ScriptBlockMemberMethodWrapper(IParameterMetadataProvider ast)
 {
     _ast              = ast;
     _scriptBlock      = new Lazy <ScriptBlock>(() => new ScriptBlock(_ast, isFilter: false));
     _boundScriptBlock = new ThreadLocal <ScriptBlock>(
         () =>
     {
         var sb = _scriptBlock.Value.Clone();
         return(sb);
     });
 }
예제 #8
0
 internal static Dictionary<string, VariableAnalysisDetails> Visit(IParameterMetadataProvider ast, bool disableOptimizations, bool scriptCmdlet, out int localsAllocated, out bool forceNoOptimizing)
 {
     FindAllVariablesVisitor visitor = new FindAllVariablesVisitor(disableOptimizations, scriptCmdlet);
     ast.Body.InternalVisit(visitor);
     forceNoOptimizing = visitor._disableOptimizations;
     if (ast.Parameters != null)
     {
         visitor.VisitParameters(ast.Parameters);
     }
     localsAllocated = (from details in visitor._variables
         where details.Value.LocalTupleIndex != -1
         select details).Count<KeyValuePair<string, VariableAnalysisDetails>>();
     return visitor._variables;
 }
예제 #9
0
        internal static Dictionary <string, VariableAnalysisDetails> Visit(IParameterMetadataProvider ast, bool disableOptimizations, bool scriptCmdlet, out int localsAllocated, out bool forceNoOptimizing)
        {
            FindAllVariablesVisitor visitor = new FindAllVariablesVisitor(disableOptimizations, scriptCmdlet);

            ast.Body.InternalVisit(visitor);
            forceNoOptimizing = visitor._disableOptimizations;
            if (ast.Parameters != null)
            {
                visitor.VisitParameters(ast.Parameters);
            }
            localsAllocated = (from details in visitor._variables
                               where details.Value.LocalTupleIndex != -1
                               select details).Count <KeyValuePair <string, VariableAnalysisDetails> >();
            return(visitor._variables);
        }
예제 #10
0
 private Tuple <Type, Dictionary <string, int> > AnalyzeImpl(IParameterMetadataProvider ast, bool disableOptimizations, bool scriptCmdlet)
 {
     this._variables = FindAllVariablesVisitor.Visit(ast, disableOptimizations, scriptCmdlet, out this._localsAllocated, out this._disableOptimizations);
     this.Init();
     if (ast.Parameters != null)
     {
         foreach (ParameterAst ast2 in ast.Parameters)
         {
             VariablePath variablePath = ast2.Name.VariablePath;
             if (variablePath.IsAnyLocal())
             {
                 bool flag = false;
                 int  num  = -1;
                 Type c    = null;
                 foreach (AttributeBaseAst ast3 in ast2.Attributes)
                 {
                     if (ast3 is TypeConstraintAst)
                     {
                         num++;
                         if (c == null)
                         {
                             c = ast3.TypeName.GetReflectionType();
                         }
                     }
                     else
                     {
                         Type reflectionAttributeType = ast3.TypeName.GetReflectionAttributeType();
                         if (typeof(ValidateArgumentsAttribute).IsAssignableFrom(reflectionAttributeType) || typeof(ArgumentTransformationAttribute).IsAssignableFrom(reflectionAttributeType))
                         {
                             flag = true;
                         }
                     }
                 }
                 string unaliasedVariableName    = GetUnaliasedVariableName(variablePath);
                 VariableAnalysisDetails details = this._variables[unaliasedVariableName];
                 c = c ?? (details.Type ?? typeof(object));
                 if (((flag || (num > 0)) || (typeof(PSReference).IsAssignableFrom(c) || MustBeBoxed(c))) && (!details.Automatic && !details.PreferenceVariable))
                 {
                     details.LocalTupleIndex = -2;
                 }
                 this._entryBlock.AddAst(new AssignmentTarget(unaliasedVariableName, c));
             }
         }
     }
     ast.Body.Accept(this);
     return(this.FinishAnalysis(scriptCmdlet));
 }
예제 #11
0
 internal CompiledScriptBlockData(IParameterMetadataProvider ast)
 {
     this.Ast         = ast;
     this._syncObject = new object();
 }
 internal ScriptBlockExpressionWrapper(IParameterMetadataProvider ast)
 {
     this._ast = ast;
 }
예제 #13
0
 public ProcedureCallAsXmlMessage(nutility.ITypeClassMapper typemap)
 {
   xml = typemap.GetValue<XDocument>(RPC_Constant.SerializedRPCDataType);
   metadata = typemap.GetService<IParameterMetadataProvider>();
   metadata.LoadSchemaFor(GetOperationName());
 }
예제 #14
0
파일: PSType.cs 프로젝트: 40a/PowerShell
            private void DefineMethodBody(
                IParameterMetadataProvider ipmp,
                ILGenerator ilGenerator,
                string metadataToken,
                bool isStatic,
                Type[] parameterTypes,
                Type returnType,
                Action<int, string> parameterNameSetter)
            {
                var wrapperFieldName = string.Format(CultureInfo.InvariantCulture, "<{0}>", metadataToken);
                var scriptBlockWrapperField = _staticHelpersTypeBuilder.DefineField(wrapperFieldName,
                                                                       typeof(ScriptBlockMemberMethodWrapper),
                                                                       FieldAttributes.Assembly | FieldAttributes.Static);

                ilGenerator.Emit(OpCodes.Ldsfld, scriptBlockWrapperField);
                if (isStatic)
                {
                    ilGenerator.Emit(OpCodes.Ldnull);                   // pass null (no this)
                    ilGenerator.Emit(OpCodes.Ldnull);                   // pass null (no sessionStateInternal)
                }
                else
                {
                    EmitLdarg(ilGenerator, 0);                            // pass this
                    ilGenerator.Emit(OpCodes.Ldarg_0);                    // pass 'this' for Ldfld call
                    ilGenerator.Emit(OpCodes.Ldfld, _sessionStateField);  // pass sessionStateInternal
                }

                int parameterCount = parameterTypes.Length;
                if (parameterCount > 0)
                {
                    var parameters = ipmp.Parameters;
                    var local = ilGenerator.DeclareLocal(typeof(object[]));

                    EmitLdc(ilGenerator, parameterCount);               // Create an array to hold all
                    ilGenerator.Emit(OpCodes.Newarr, typeof(object));  //     of the parameters
                    ilGenerator.Emit(OpCodes.Stloc, local);             // Save array for repeated use
                    int j = isStatic ? 0 : 1;
                    for (int i = 0; i < parameterCount; i++, j++)
                    {
                        ilGenerator.Emit(OpCodes.Ldloc, local);           // load array
                        EmitLdc(ilGenerator, i);                          // index to save at
                        EmitLdarg(ilGenerator, j);                        // load argument (skipping this)
                        if (parameterTypes[i].GetTypeInfo().IsValueType)  // value types must be boxed
                        {
                            ilGenerator.Emit(OpCodes.Box, parameterTypes[i]);
                        }
                        ilGenerator.Emit(OpCodes.Stelem_Ref);           // save the argument in the array

                        // Set the parameter name, mostly for Get-Member
                        // Parameters are indexed beginning with the number 1 for the first parameter
                        parameterNameSetter(i + 1, parameters[i].Name.VariablePath.UserPath);
                    }
                    ilGenerator.Emit(OpCodes.Ldloc, local);         // load array
                }
                else
                {
                    ilGenerator.Emit(OpCodes.Ldsfld, typeof(ScriptBlockMemberMethodWrapper).GetField("_emptyArgumentArray", BindingFlags.Static | BindingFlags.Public));
                }

                MethodInfo invokeHelper;
                if (returnType == typeof(void))
                {
                    invokeHelper = typeof(ScriptBlockMemberMethodWrapper).GetMethod("InvokeHelper", BindingFlags.Instance | BindingFlags.Public);
                }
                else
                {
                    invokeHelper = typeof(ScriptBlockMemberMethodWrapper).GetMethod("InvokeHelperT", BindingFlags.Instance | BindingFlags.Public).MakeGenericMethod(returnType);
                }
                ilGenerator.Emit(OpCodes.Tailcall);
                ilGenerator.EmitCall(OpCodes.Call, invokeHelper, null);
                ilGenerator.Emit(OpCodes.Ret);

                var methodWrapper = new ScriptBlockMemberMethodWrapper(ipmp);
                _fieldsToInitForMemberFunctions.Add(Tuple.Create(wrapperFieldName, (object)methodWrapper));
            }
예제 #15
0
 internal static Tuple <Type, Dictionary <string, int> > Analyze(IParameterMetadataProvider ast, bool disableOptimizations, bool scriptCmdlet)
 {
     return(new VariableAnalysis().AnalyzeImpl(ast, disableOptimizations, scriptCmdlet));
 }
예제 #16
0
 internal CompiledScriptBlockData(IParameterMetadataProvider ast, bool isFilter)
 {
     _ast = ast;
     this.IsFilter = isFilter;
     this.Id = Guid.NewGuid();
 }
예제 #17
0
 internal ScriptBlockExpressionWrapper(IParameterMetadataProvider ast)
 {
     this._ast = ast;
 }
예제 #18
0
 internal static Tuple<Type, Dictionary<string, int>> Analyze(IParameterMetadataProvider ast, bool disableOptimizations, bool scriptCmdlet)
 {
     return new VariableAnalysis().AnalyzeImpl(ast, disableOptimizations, scriptCmdlet);
 }
예제 #19
0
 private Tuple<Type, Dictionary<string, int>> AnalyzeImpl(IParameterMetadataProvider ast, bool disableOptimizations, bool scriptCmdlet)
 {
     this._variables = FindAllVariablesVisitor.Visit(ast, disableOptimizations, scriptCmdlet, out this._localsAllocated, out this._disableOptimizations);
     this.Init();
     if (ast.Parameters != null)
     {
         foreach (ParameterAst ast2 in ast.Parameters)
         {
             VariablePath variablePath = ast2.Name.VariablePath;
             if (variablePath.IsAnyLocal())
             {
                 bool flag = false;
                 int num = -1;
                 Type c = null;
                 foreach (AttributeBaseAst ast3 in ast2.Attributes)
                 {
                     if (ast3 is TypeConstraintAst)
                     {
                         num++;
                         if (c == null)
                         {
                             c = ast3.TypeName.GetReflectionType();
                         }
                     }
                     else
                     {
                         Type reflectionAttributeType = ast3.TypeName.GetReflectionAttributeType();
                         if (typeof(ValidateArgumentsAttribute).IsAssignableFrom(reflectionAttributeType) || typeof(ArgumentTransformationAttribute).IsAssignableFrom(reflectionAttributeType))
                         {
                             flag = true;
                         }
                     }
                 }
                 string unaliasedVariableName = GetUnaliasedVariableName(variablePath);
                 VariableAnalysisDetails details = this._variables[unaliasedVariableName];
                 c = c ?? (details.Type ?? typeof(object));
                 if (((flag || (num > 0)) || (typeof(PSReference).IsAssignableFrom(c) || MustBeBoxed(c))) && (!details.Automatic && !details.PreferenceVariable))
                 {
                     details.LocalTupleIndex = -2;
                 }
                 this._entryBlock.AddAst(new AssignmentTarget(unaliasedVariableName, c));
             }
         }
     }
     ast.Body.Accept(this);
     return this.FinishAnalysis(scriptCmdlet);
 }
예제 #20
0
        internal static Dictionary<string, VariableAnalysisDetails> Visit(IParameterMetadataProvider ast,
                                                                          bool disableOptimizations,
                                                                          bool scriptCmdlet,
                                                                          out int localsAllocated,
                                                                          out bool forceNoOptimizing)
        {
            var visitor = new FindAllVariablesVisitor(disableOptimizations, scriptCmdlet);

            // Visit the body before the parameters so we don't allocate any tuple slots for parameters
            // if we won't be optimizing because of a call to new-variable/remove-variable, etc.

            ast.Body.InternalVisit(visitor);
            forceNoOptimizing = visitor._disableOptimizations;

            if (ast.Parameters != null)
            {
                visitor.VisitParameters(ast.Parameters);
            }
            localsAllocated = visitor._variables.Where(details => details.Value.LocalTupleIndex != VariableAnalysis.Unanalyzed).Count();
            return visitor._variables;
        }
예제 #21
0
        private Tuple<Type, Dictionary<string, int>> AnalyzeImpl(IParameterMetadataProvider ast, bool disableOptimizations, bool scriptCmdlet)
        {
            _variables = FindAllVariablesVisitor.Visit(ast, disableOptimizations, scriptCmdlet, out _localsAllocated, out _disableOptimizations);
            Init();

            if (ast.Parameters != null)
            {
                foreach (var parameter in ast.Parameters)
                {
                    var variablePath = parameter.Name.VariablePath;
                    if (variablePath.IsAnyLocal())
                    {
                        bool anyAttributes = false;
                        int countConverts = -1; // First convert is really the parameter type, so it doesn't count
                        Type type = null;
                        bool anyUnresolvedTypes = false;
                        foreach (var paramAst in parameter.Attributes)
                        {
                            if (paramAst is TypeConstraintAst)
                            {
                                countConverts += 1;
                                if (type == null)
                                {
                                    type = paramAst.TypeName.GetReflectionType();
                                    if (type == null)
                                    {
                                        anyUnresolvedTypes = true;
                                    }
                                }
                            }
                            else
                            {
                                var attrType = paramAst.TypeName.GetReflectionAttributeType();
                                if (attrType == null)
                                {
                                    anyUnresolvedTypes = true;
                                }
                                else if (typeof(ValidateArgumentsAttribute).IsAssignableFrom(attrType)
                                    || typeof(ArgumentTransformationAttribute).IsAssignableFrom(attrType))
                                {
                                    // If there are any attributes that have semantic meaning, we need to use a PSVariable.
                                    anyAttributes = true;
                                }
                            }
                        }

                        var varName = GetUnaliasedVariableName(variablePath);
                        var details = _variables[varName];
                        details.Assigned = true;
                        type = type ?? details.Type ?? typeof(object);

                        // automatic and preference variables are pre-allocated, so they can't be unallocated
                        // and forced to be dynamic.
                        // unresolved types can happen at parse time
                        // [ref] parameters are forced to dynamic so that we can assign $null in the parameter
                        // binder w/o conversions kicking in (the setter in MutableTuple will convert $null to PSReference<Null>
                        // but that won't happen if we create a PSVariable (this is an ugly hack, but it works.)
                        if ((anyAttributes || anyUnresolvedTypes || countConverts > 0 || typeof(PSReference).IsAssignableFrom(type) || MustBeBoxed(type)) &&
                            !details.Automatic && !details.PreferenceVariable)
                        {
                            details.LocalTupleIndex = ForceDynamic;
                        }

                        _entryBlock.AddAst(new AssignmentTarget(varName, type));
                    }
                }
            }

            ast.Body.Accept(this);

            return FinishAnalysis(scriptCmdlet);
        }
예제 #22
0
        } // GetFunction 

        private IEnumerable<string> GetFunctionAliases(IParameterMetadataProvider ipmp)
        {
            if (ipmp == null || ipmp.Body.ParamBlock == null)
                yield break;

            var attributes = ipmp.Body.ParamBlock.Attributes;
            foreach (var attributeAst in attributes)
            {
                var attributeType = attributeAst.TypeName.GetReflectionAttributeType();
                if (attributeType == typeof(AliasAttribute))
                {
                    var cvv = new ConstantValueVisitor { AttributeArgument = true };
                    for (int i = 0; i < attributeAst.PositionalArguments.Count; i++)
                    {
                        yield return Compiler._attrArgToStringConverter.Target(Compiler._attrArgToStringConverter,
                            attributeAst.PositionalArguments[i].Accept(cvv));
                    }
                }
            }
        }
예제 #23
0
        private IParameterMetadataProvider DelayParseScriptText()
        {
            lock (this)
            {
                if (_ast != null)
                    return _ast;

                ParseError[] errors;
                _ast = (new Parser()).Parse(null, _scriptText, null, out errors, ParseMode.Default);
                if (errors.Length != 0)
                {
                    throw new ParseException(errors);
                }

                _scriptText = null;
                return _ast;
            }
        }
예제 #24
0
 internal ScriptBlock(IParameterMetadataProvider ast, bool isFilter) :
     this(new CompiledScriptBlockData(ast, isFilter))
 {
 }
예제 #25
0
 private ScriptBlock(IParameterMetadataProvider ast, bool isFilter, CompiledScriptBlockData _scriptBlockData)
 {
     this.languageMode = null;
     this._ast = ast;
     this._scriptBlockData = _scriptBlockData;
     this._isFilter = isFilter;
     this.SetLanguageModeFromContext();
 }
예제 #26
0
 internal CompiledScriptBlockData(IParameterMetadataProvider ast)
 {
     this.Ast = ast;
     this._syncObject = new object();
 }
예제 #27
0
 public OperationCallBuilder(nutility.ITypeClassMapper typemap)
 {
   xml = typemap.GetService<XDocument>();
   metadata = typemap.GetService<IParameterMetadataProvider>();
   metadata.LoadSchemaFor(GetOperationName());
 }
예제 #28
0
        internal static Tuple <List <System.Management.Automation.Language.Token>, List <string> > GetHelpCommentTokens(IParameterMetadataProvider ipmp, Dictionary <Ast, System.Management.Automation.Language.Token[]> scriptBlockTokenCache)
        {
            int num;
            int num2;
            int num3;
            List <System.Management.Automation.Language.Token> commentBlock;
            Ast ast = (Ast)ipmp;
            Ast key = ast;

            while (key.Parent != null)
            {
                key = key.Parent;
            }
            System.Management.Automation.Language.Token[] tokenArray = null;
            scriptBlockTokenCache.TryGetValue(key, out tokenArray);
            if (tokenArray == null)
            {
                ParseError[] errorArray;
                Parser.ParseInput(key.Extent.Text, out tokenArray, out errorArray);
                scriptBlockTokenCache[key] = tokenArray;
            }
            FunctionDefinitionAst ast3 = ast as FunctionDefinitionAst;

            if (ast3 != null)
            {
                int tokenIndex = num = FirstTokenInExtent(tokenArray, ast.Extent, 0);
                commentBlock = GetPrecedingCommentBlock(tokenArray, tokenIndex, 2);
                if (IsCommentHelpText(commentBlock))
                {
                    return(Tuple.Create <List <System.Management.Automation.Language.Token>, List <string> >(commentBlock, GetParameterComments(tokenArray, ipmp, num)));
                }
                num2 = FirstTokenInExtent(tokenArray, ast3.Body.Extent, 0) + 1;
                num3 = LastTokenInExtent(tokenArray, ast.Extent, tokenIndex);
            }
            else if (ast == key)
            {
                num2 = num = 0;
                num3 = tokenArray.Length - 1;
            }
            else
            {
                num2 = num = FirstTokenInExtent(tokenArray, ast.Extent, 0) - 1;
                num3 = LastTokenInExtent(tokenArray, ast.Extent, num2);
            }
            do
            {
                commentBlock = GetCommentBlock(tokenArray, ref num2);
                if (commentBlock.Count == 0)
                {
                    goto Label_0195;
                }
            }while (!IsCommentHelpText(commentBlock));
            if (ast == key)
            {
                NamedBlockAst endBlock = ((ScriptBlockAst)ast).EndBlock;
                if ((endBlock == null) || !endBlock.Unnamed)
                {
                    return(Tuple.Create <List <System.Management.Automation.Language.Token>, List <string> >(commentBlock, GetParameterComments(tokenArray, ipmp, num)));
                }
                StatementAst ast5 = endBlock.Statements.FirstOrDefault <StatementAst>();
                if (ast5 is FunctionDefinitionAst)
                {
                    int num5 = ast5.Extent.StartLineNumber - commentBlock.Last <System.Management.Automation.Language.Token>().Extent.EndLineNumber;
                    if (num5 > 2)
                    {
                        return(Tuple.Create <List <System.Management.Automation.Language.Token>, List <string> >(commentBlock, GetParameterComments(tokenArray, ipmp, num)));
                    }
                    goto Label_0195;
                }
            }
            return(Tuple.Create <List <System.Management.Automation.Language.Token>, List <string> >(commentBlock, GetParameterComments(tokenArray, ipmp, num)));

Label_0195:
            commentBlock = GetPrecedingCommentBlock(tokenArray, num3, tokenArray[num3].Extent.StartLineNumber);
            if (IsCommentHelpText(commentBlock))
            {
                return(Tuple.Create <List <System.Management.Automation.Language.Token>, List <string> >(commentBlock, GetParameterComments(tokenArray, ipmp, num)));
            }
            return(null);
        }
예제 #29
0
 private static List<string> GetParameterComments(System.Management.Automation.Language.Token[] tokens, IParameterMetadataProvider ipmp, int startIndex)
 {
     List<string> list = new List<string>();
     ReadOnlyCollection<ParameterAst> parameters = ipmp.Parameters;
     if ((parameters != null) && (parameters.Count != 0))
     {
         foreach (ParameterAst ast in parameters)
         {
             List<string> commentLines = new List<string>();
             int tokenIndex = FirstTokenInExtent(tokens, ast.Extent, startIndex);
             List<System.Management.Automation.Language.Token> commentBlock = GetPrecedingCommentBlock(tokens, tokenIndex, 2);
             if (commentBlock != null)
             {
                 foreach (System.Management.Automation.Language.Token token in commentBlock)
                 {
                     CollectCommentText(token, commentLines);
                 }
             }
             int num2 = LastTokenInExtent(tokens, ast.Extent, tokenIndex);
             for (int i = tokenIndex; i < num2; i++)
             {
                 if (tokens[i].Kind == TokenKind.Comment)
                 {
                     CollectCommentText(tokens[i], commentLines);
                 }
             }
             num2++;
             commentBlock = GetCommentBlock(tokens, ref num2);
             if (commentBlock != null)
             {
                 foreach (System.Management.Automation.Language.Token token2 in commentBlock)
                 {
                     CollectCommentText(token2, commentLines);
                 }
             }
             int num4 = -1;
             list.Add(GetSection(commentLines, ref num4));
         }
     }
     return list;
 }
예제 #30
0
 internal static Tuple<List<System.Management.Automation.Language.Token>, List<string>> GetHelpCommentTokens(IParameterMetadataProvider ipmp, Dictionary<Ast, System.Management.Automation.Language.Token[]> scriptBlockTokenCache)
 {
     int num;
     int num2;
     int num3;
     List<System.Management.Automation.Language.Token> commentBlock;
     Ast ast = (Ast) ipmp;
     Ast key = ast;
     while (key.Parent != null)
     {
         key = key.Parent;
     }
     System.Management.Automation.Language.Token[] tokenArray = null;
     scriptBlockTokenCache.TryGetValue(key, out tokenArray);
     if (tokenArray == null)
     {
         ParseError[] errorArray;
         Parser.ParseInput(key.Extent.Text, out tokenArray, out errorArray);
         scriptBlockTokenCache[key] = tokenArray;
     }
     FunctionDefinitionAst ast3 = ast as FunctionDefinitionAst;
     if (ast3 != null)
     {
         int tokenIndex = num = FirstTokenInExtent(tokenArray, ast.Extent, 0);
         commentBlock = GetPrecedingCommentBlock(tokenArray, tokenIndex, 2);
         if (IsCommentHelpText(commentBlock))
         {
             return Tuple.Create<List<System.Management.Automation.Language.Token>, List<string>>(commentBlock, GetParameterComments(tokenArray, ipmp, num));
         }
         num2 = FirstTokenInExtent(tokenArray, ast3.Body.Extent, 0) + 1;
         num3 = LastTokenInExtent(tokenArray, ast.Extent, tokenIndex);
     }
     else if (ast == key)
     {
         num2 = num = 0;
         num3 = tokenArray.Length - 1;
     }
     else
     {
         num2 = num = FirstTokenInExtent(tokenArray, ast.Extent, 0) - 1;
         num3 = LastTokenInExtent(tokenArray, ast.Extent, num2);
     }
     do
     {
         commentBlock = GetCommentBlock(tokenArray, ref num2);
         if (commentBlock.Count == 0)
         {
             goto Label_0195;
         }
     }
     while (!IsCommentHelpText(commentBlock));
     if (ast == key)
     {
         NamedBlockAst endBlock = ((ScriptBlockAst) ast).EndBlock;
         if ((endBlock == null) || !endBlock.Unnamed)
         {
             return Tuple.Create<List<System.Management.Automation.Language.Token>, List<string>>(commentBlock, GetParameterComments(tokenArray, ipmp, num));
         }
         StatementAst ast5 = endBlock.Statements.FirstOrDefault<StatementAst>();
         if (ast5 is FunctionDefinitionAst)
         {
             int num5 = ast5.Extent.StartLineNumber - commentBlock.Last<System.Management.Automation.Language.Token>().Extent.EndLineNumber;
             if (num5 > 2)
             {
                 return Tuple.Create<List<System.Management.Automation.Language.Token>, List<string>>(commentBlock, GetParameterComments(tokenArray, ipmp, num));
             }
             goto Label_0195;
         }
     }
     return Tuple.Create<List<System.Management.Automation.Language.Token>, List<string>>(commentBlock, GetParameterComments(tokenArray, ipmp, num));
 Label_0195:
     commentBlock = GetPrecedingCommentBlock(tokenArray, num3, tokenArray[num3].Extent.StartLineNumber);
     if (IsCommentHelpText(commentBlock))
     {
         return Tuple.Create<List<System.Management.Automation.Language.Token>, List<string>>(commentBlock, GetParameterComments(tokenArray, ipmp, num));
     }
     return null;
 }
예제 #31
0
        private static List<string> GetParameterComments(Language.Token[] tokens, IParameterMetadataProvider ipmp, int startIndex)
        {
            var result = new List<string>();
            var parameters = ipmp.Parameters;
            if (parameters == null || parameters.Count == 0)
            {
                return result;
            }

            foreach (var parameter in parameters)
            {
                var commentLines = new List<string>();

                var firstToken = FirstTokenInExtent(tokens, parameter.Extent, startIndex);
                var comments = GetPrecedingCommentBlock(tokens, firstToken, CommentBlockProximity);
                if (comments != null)
                {
                    foreach (var comment in comments)
                    {
                        CollectCommentText(comment, commentLines);
                    }
                }

                var lastToken = LastTokenInExtent(tokens, parameter.Extent, firstToken);
                for (int i = firstToken; i < lastToken; ++i)
                {
                    if (tokens[i].Kind == TokenKind.Comment)
                    {
                        CollectCommentText(tokens[i], commentLines);
                    }
                }

                lastToken += 1;
                comments = GetCommentBlock(tokens, ref lastToken);
                if (comments != null)
                {
                    foreach (var comment in comments)
                    {
                        CollectCommentText(comment, commentLines);
                    }
                }


                int n = -1;
                result.Add(GetSection(commentLines, ref n));
            }
            return result;
        }
예제 #32
0
파일: PSType.cs 프로젝트: 40a/PowerShell
            private void DefineConstructor(IParameterMetadataProvider ipmp, ReadOnlyCollection<AttributeAst> attributeAsts, bool isHidden, Reflection.MethodAttributes methodAttributes, Type[] parameterTypes)
            {
                bool isStatic = (methodAttributes & Reflection.MethodAttributes.Static) != 0;
                var ctor = isStatic
                    ? _typeBuilder.DefineTypeInitializer()
                    : _typeBuilder.DefineConstructor(methodAttributes, CallingConventions.Standard, parameterTypes);
                DefineCustomAttributes(ctor, attributeAsts, _parser, AttributeTargets.Constructor);
                if (isHidden)
                {
                    ctor.SetCustomAttribute(s_hiddenCustomAttributeBuilder);
                }
                var ilGenerator = ctor.GetILGenerator();

                if (!isStatic)
                {
                    ilGenerator.Emit(OpCodes.Ldarg_0); // load 'this' on stack for Stfld call

                    ilGenerator.Emit(OpCodes.Ldnull);
                    ilGenerator.Emit(OpCodes.Ldfld, _sessionStateKeeperField);
                    ilGenerator.EmitCall(OpCodes.Call, s_sessionStateKeeper_GetSessionState, null); // load 'sessionState' on stack for Stfld call

                    ilGenerator.Emit(OpCodes.Stfld, _sessionStateField);
                }

                DefineMethodBody(ipmp, ilGenerator, GetMetaDataName(ctor.Name, parameterTypes.Count()), isStatic, parameterTypes, typeof(void),
                    (i, n) => ctor.DefineParameter(i, ParameterAttributes.None, n));
            }
예제 #33
0
        internal static Tuple<List<Language.Token>, List<string>> GetHelpCommentTokens(IParameterMetadataProvider ipmp,
            Dictionary<Ast, Token[]> scriptBlockTokenCache)
        {
            Diagnostics.Assert(scriptBlockTokenCache != null, "scriptBlockTokenCache cannot be null");
            var ast = (Ast)ipmp;

            var rootAst = ast;
            Ast configAst = null;
            while (rootAst.Parent != null)
            {
                rootAst = rootAst.Parent;
                if (rootAst is ConfigurationDefinitionAst)
                {
                    configAst = rootAst;
                }
            }

            //  tokens saved from reparsing the script.
            Language.Token[] tokens = null;
            scriptBlockTokenCache.TryGetValue(rootAst, out tokens);

            if (tokens == null)
            {
                ParseError[] errors;
                // storing all comment tokens
                Language.Parser.ParseInput(rootAst.Extent.Text, out tokens, out errors);
                scriptBlockTokenCache[rootAst] = tokens;
            }

            int savedStartIndex;
            int startTokenIndex;
            int lastTokenIndex;

            var funcDefnAst = ast as FunctionDefinitionAst;
            List<Language.Token> commentBlock;
            if (funcDefnAst != null || configAst != null)
            {
                // The first comment block preceding the function or configuration keyword is a candidate help comment block.
                var funcOrConfigTokenIndex =
                    savedStartIndex = FirstTokenInExtent(tokens, configAst == null ? ast.Extent : configAst.Extent);

                commentBlock = GetPrecedingCommentBlock(tokens, funcOrConfigTokenIndex, CommentBlockProximity);

                if (HelpCommentsParser.IsCommentHelpText(commentBlock))
                {
                    return Tuple.Create(commentBlock, GetParameterComments(tokens, ipmp, savedStartIndex));
                }

                // comment block is behind function definition
                // we don't support it for configuration declaration as this style is rarely used
                if (funcDefnAst != null)
                {
                    startTokenIndex =
                        FirstTokenInExtent(tokens, funcDefnAst.Body.Extent) + 1;
                    lastTokenIndex = LastTokenInExtent(tokens, ast.Extent, funcOrConfigTokenIndex);

                    Diagnostics.Assert(tokens[startTokenIndex - 1].Kind == TokenKind.LCurly,
                        "Unexpected first token in function");
                    Diagnostics.Assert(tokens[lastTokenIndex].Kind == TokenKind.RCurly,
                        "Unexpected last token in function");
                }
                else
                {
                    return null;
                }
            }
            else if (ast == rootAst)
            {
                startTokenIndex = savedStartIndex = 0;
                lastTokenIndex = tokens.Length - 1;
            }
            else
            {
                // This case should be rare (but common with implicit remoting).
                // We have a script block that was used to generate a function like:
                //     $sb = { }
                //     set-item function:foo $sb
                //     help foo
                startTokenIndex = savedStartIndex = FirstTokenInExtent(tokens, ast.Extent) - 1;
                lastTokenIndex = LastTokenInExtent(tokens, ast.Extent, startTokenIndex);

                Diagnostics.Assert(tokens[startTokenIndex + 1].Kind == TokenKind.LCurly,
                    "Unexpected first token in script block");
                Diagnostics.Assert(tokens[lastTokenIndex].Kind == TokenKind.RCurly,
                    "Unexpected last token in script block");
            }

            while (true)
            {
                commentBlock = GetCommentBlock(tokens, ref startTokenIndex);
                if (commentBlock.Count == 0)
                    break;

                if (!HelpCommentsParser.IsCommentHelpText(commentBlock))
                    continue;

                if (ast == rootAst)
                {
                    // One more check - make sure the comment doesn't belong to the first function in the script.
                    var endBlock = ((ScriptBlockAst)ast).EndBlock;
                    if (endBlock == null || !endBlock.Unnamed)
                    {
                        return Tuple.Create(commentBlock, GetParameterComments(tokens, ipmp, savedStartIndex));
                    }

                    var firstStatement = endBlock.Statements.FirstOrDefault();
                    if (firstStatement is FunctionDefinitionAst)
                    {
                        int linesBetween = firstStatement.Extent.StartLineNumber -
                                            commentBlock.Last().Extent.EndLineNumber;
                        if (linesBetween > CommentBlockProximity)
                        {
                            return Tuple.Create(commentBlock, GetParameterComments(tokens, ipmp, savedStartIndex));
                        }
                        break;
                    }
                }

                return Tuple.Create(commentBlock, GetParameterComments(tokens, ipmp, savedStartIndex));
            }

            commentBlock = GetPrecedingCommentBlock(tokens, lastTokenIndex, tokens[lastTokenIndex].Extent.StartLineNumber);
            if (HelpCommentsParser.IsCommentHelpText(commentBlock))
            {
                return Tuple.Create(commentBlock, GetParameterComments(tokens, ipmp, savedStartIndex));
            }

            return null;
        }
예제 #34
0
 internal void EnterScope(IParameterMetadataProvider ast, ScopeType scopeType)
 {
     var scope = new Scope(ast, scopeType);
     _scopes.Add(scope);
     AddTypesInScope((Ast)ast);
 }
예제 #35
0
        private static List <string> GetParameterComments(System.Management.Automation.Language.Token[] tokens, IParameterMetadataProvider ipmp, int startIndex)
        {
            List <string> list = new List <string>();
            ReadOnlyCollection <ParameterAst> parameters = ipmp.Parameters;

            if ((parameters != null) && (parameters.Count != 0))
            {
                foreach (ParameterAst ast in parameters)
                {
                    List <string> commentLines = new List <string>();
                    int           tokenIndex   = FirstTokenInExtent(tokens, ast.Extent, startIndex);
                    List <System.Management.Automation.Language.Token> commentBlock = GetPrecedingCommentBlock(tokens, tokenIndex, 2);
                    if (commentBlock != null)
                    {
                        foreach (System.Management.Automation.Language.Token token in commentBlock)
                        {
                            CollectCommentText(token, commentLines);
                        }
                    }
                    int num2 = LastTokenInExtent(tokens, ast.Extent, tokenIndex);
                    for (int i = tokenIndex; i < num2; i++)
                    {
                        if (tokens[i].Kind == TokenKind.Comment)
                        {
                            CollectCommentText(tokens[i], commentLines);
                        }
                    }
                    num2++;
                    commentBlock = GetCommentBlock(tokens, ref num2);
                    if (commentBlock != null)
                    {
                        foreach (System.Management.Automation.Language.Token token2 in commentBlock)
                        {
                            CollectCommentText(token2, commentLines);
                        }
                    }
                    int num4 = -1;
                    list.Add(GetSection(commentLines, ref num4));
                }
            }
            return(list);
        }