Exemple #1
0
 public static bool IsConstant(Ast ast, out object constantValue, bool forAttribute = false, bool forRequires = false)
 {
     try
     {
         IsConstantValueVisitor visitor2 = new IsConstantValueVisitor {
             CheckingAttributeArgument = forAttribute,
             CheckingRequiresArgument  = forRequires
         };
         if ((bool)ast.Accept(visitor2))
         {
             Ast parent = ast.Parent;
             while (parent != null)
             {
                 if (parent is DataStatementAst)
                 {
                     break;
                 }
                 parent = parent.Parent;
             }
             if (parent == null)
             {
                 ConstantValueVisitor visitor = new ConstantValueVisitor {
                     AttributeArgument = forAttribute,
                     RequiresArgument  = forRequires
                 };
                 constantValue = ast.Accept(visitor);
                 return(true);
             }
         }
     }
     catch (Exception exception)
     {
         CommandProcessorBase.CheckForSevereException(exception);
     }
     constantValue = null;
     return(false);
 }
 public static bool IsConstant(Ast ast, out object constantValue, bool forAttribute = false, bool forRequires = false)
 {
     try
     {
         IsConstantValueVisitor visitor2 = new IsConstantValueVisitor {
             CheckingAttributeArgument = forAttribute,
             CheckingRequiresArgument = forRequires
         };
         if ((bool) ast.Accept(visitor2))
         {
             Ast parent = ast.Parent;
             while (parent != null)
             {
                 if (parent is DataStatementAst)
                 {
                     break;
                 }
                 parent = parent.Parent;
             }
             if (parent == null)
             {
                 ConstantValueVisitor visitor = new ConstantValueVisitor {
                     AttributeArgument = forAttribute,
                     RequiresArgument = forRequires
                 };
                 constantValue = ast.Accept(visitor);
                 return true;
             }
         }
     }
     catch (Exception exception)
     {
         CommandProcessorBase.CheckForSevereException(exception);
     }
     constantValue = null;
     return false;
 }
Exemple #3
0
        private Action<List<Expression>, Expression> GetSwitchBodyGenerator(SwitchStatementAst switchStatementAst, AutomaticVarSaver avs, ParameterExpression skipDefault)
        {
            return (exprs, newValue) =>
                   {
                       var clauseEvalBinder = PSSwitchClauseEvalBinder.Get(switchStatementAst.Flags);
                       exprs.Add(avs.SetNewValue(newValue));

                       if (skipDefault != null)
                       {
                           exprs.Add(Expression.Assign(skipDefault, ExpressionCache.Constant(false)));
                       }

                       IsConstantValueVisitor iscvv = new IsConstantValueVisitor();
                       ConstantValueVisitor cvv = new ConstantValueVisitor();

                       int clauseCount = switchStatementAst.Clauses.Count;
                       for (int i = 0; i < clauseCount; i++)
                       {
                           var clause = switchStatementAst.Clauses[i];

                           Expression test;
                           object constValue = ((bool)clause.Item1.Accept(iscvv)) ? clause.Item1.Accept(cvv) : null;
                           if (constValue is ScriptBlock)
                           {
                               var call = Expression.Call(Expression.Constant(constValue),
                                                           CachedReflectionInfo.ScriptBlock_DoInvokeReturnAsIs,
                               /*useLocalScope=*/         ExpressionCache.Constant(true),
                               /*errorHandlingBehavior=*/ Expression.Constant(ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe),
                               /*dollarUnder=*/           GetLocal((int)AutomaticVariable.Underbar).Convert(typeof(object)),
                               /*input=*/                 ExpressionCache.AutomationNullConstant,
                               /*scriptThis=*/            ExpressionCache.AutomationNullConstant,
                               /*args=*/                  ExpressionCache.NullObjectArray);
                               test = DynamicExpression.Dynamic(PSConvertBinder.Get(typeof(bool)), typeof(bool), call);
                           }
                           else if (constValue != null)
                           {
                               SwitchFlags flags = switchStatementAst.Flags;
                               Expression conditionExpr = constValue is Regex || constValue is WildcardPattern
                                                    ? (Expression)Expression.Constant(constValue)
                                                    : DynamicExpression.Dynamic(PSToStringBinder.Get(), typeof(string),
                                                                                (constValue is Type)
                                                                                    ? Expression.Constant(constValue, typeof(Type))
                                                                                    : Expression.Constant(constValue),
                                                                                _executionContextParameter);
                               Expression currentAsString =
                                   DynamicExpression.Dynamic(PSToStringBinder.Get(), typeof(string), GetLocal((int)AutomaticVariable.Underbar),
                                                             _executionContextParameter);
                               if ((flags & SwitchFlags.Regex) != 0 || constValue is Regex)
                               {
                                   test = Expression.Call(CachedReflectionInfo.SwitchOps_ConditionSatisfiedRegex,
                                       /*caseSensitive=*/ ExpressionCache.Constant((flags & SwitchFlags.CaseSensitive) != 0),
                                       /*condition=*/     conditionExpr,
                                       /*errorPosition=*/ Expression.Constant(clause.Item1.Extent),
                                       /*str=*/           currentAsString,
                                       /*context=*/       _executionContextParameter);
                               }
                               else if ((flags & SwitchFlags.Wildcard) != 0 || constValue is WildcardPattern)
                               {
                                   // It would be a little better to just build the wildcard at compile time, but
                                   // the runtime method must exist when variable cases are involved.
                                   test = Expression.Call(CachedReflectionInfo.SwitchOps_ConditionSatisfiedWildcard,
                                       /*caseSensitive=*/ ExpressionCache.Constant((flags & SwitchFlags.CaseSensitive) != 0),
                                       /*condition=*/     conditionExpr,
                                       /*str=*/           currentAsString,
                                       /*context=*/       _executionContextParameter);
                               }
                               else
                               {
                                   test = CallStringEquals(conditionExpr, currentAsString,
                                                           ((flags & SwitchFlags.CaseSensitive) == 0));
                               }
                           }
                           else
                           {
                               var cond = Compile(clause.Item1);
                               test = DynamicExpression.Dynamic(clauseEvalBinder, typeof(bool),
                                                                cond, GetLocal((int)AutomaticVariable.Underbar), _executionContextParameter);
                           }

                           exprs.Add(UpdatePosition(clause.Item1));
                           if (skipDefault != null)
                           {
                               exprs.Add(Expression.IfThen(
                                   test,
                                   Expression.Block(Compile(clause.Item2),
                                                    Expression.Assign(skipDefault, ExpressionCache.Constant(true)))));
                           }
                           else
                           {
                               exprs.Add(Expression.IfThen(test, Compile(clause.Item2)));
                           }
                       }

                       if (skipDefault != null)
                       {
                           exprs.Add(Expression.IfThen(Expression.Not(skipDefault), Compile(switchStatementAst.Default)));
                       }
                   };
        }
Exemple #4
0
        internal static Attribute GetAttribute(AttributeAst attributeAst)
        {
            var attributeType = attributeAst.TypeName.GetReflectionAttributeType();
            if (attributeType == null)
            {
                throw InterpreterError.NewInterpreterException(attributeAst, typeof(RuntimeException), attributeAst.Extent,
                    "CustomAttributeTypeNotFound", ParserStrings.CustomAttributeTypeNotFound, attributeAst.TypeName.FullName);
            }

            Func<AttributeAst, Attribute> generator;
            if (s_builtinAttributeGenerator.TryGetValue(attributeType, out generator))
            {
                return generator(attributeAst);
            }

            var positionalArgCount = attributeAst.PositionalArguments.Count;
            var argumentNames = attributeAst.NamedArguments.Select(name => name.ArgumentName).ToArray();
            var totalArgCount = positionalArgCount + argumentNames.Length;
            var callInfo = new CallInfo(totalArgCount, argumentNames);

            var delegateArgs = new object[totalArgCount + 1];
            delegateArgs[0] = attributeType;

            var cvv = new ConstantValueVisitor { AttributeArgument = true };
            int i = 1;
            for (int index = 0; index < attributeAst.PositionalArguments.Count; index++)
            {
                var posArg = attributeAst.PositionalArguments[index];
                delegateArgs[i++] = posArg.Accept(cvv);
            }
            for (int index = 0; index < attributeAst.NamedArguments.Count; index++)
            {
                var namedArg = attributeAst.NamedArguments[index];
                delegateArgs[i++] = namedArg.Argument.Accept(cvv);
            }

            try
            {
                return (Attribute)GetAttributeGenerator(callInfo).DynamicInvoke(delegateArgs);
            }
            catch (TargetInvocationException tie)
            {
                // Unwrap the wrapped exception
                var innerException = tie.InnerException;
                var rte = innerException as RuntimeException;
                if (rte == null)
                {
                    rte = InterpreterError.NewInterpreterExceptionWithInnerException(null, typeof(RuntimeException), attributeAst.Extent,
                        "ExceptionConstructingAttribute", ExtendedTypeSystem.ExceptionConstructingAttribute, innerException,
                        innerException.Message, attributeAst.TypeName.FullName);
                }
                InterpreterError.UpdateExceptionErrorRecordPosition(rte, attributeAst.Extent);
                throw rte;
            }
        }
Exemple #5
0
        private static Attribute NewValidateSetAttribute(AttributeAst ast)
        {
            var cvv = new ConstantValueVisitor { AttributeArgument = true };
            var args = new string[ast.PositionalArguments.Count];
            for (int i = 0; i < ast.PositionalArguments.Count; i++)
            {
                args[i] = _attrArgToStringConverter.Target(_attrArgToStringConverter,
                    ast.PositionalArguments[i].Accept(cvv));
            }

            var result = new ValidateSetAttribute(args);
            foreach (var namedArg in ast.NamedArguments)
            {
                var argValue = namedArg.Argument.Accept(cvv);
                var argumentName = namedArg.ArgumentName;
                if (argumentName.Equals("IgnoreCase", StringComparison.OrdinalIgnoreCase))
                {
                    result.IgnoreCase = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue);
                }
                else
                {
                    throw InterpreterError.NewInterpreterException(namedArg, typeof(RuntimeException), namedArg.Extent,
                        "PropertyNotFoundForType", ParserStrings.PropertyNotFoundForType, argumentName,
                        typeof(CmdletBindingAttribute));
                }
            }

            return result;
        }
Exemple #6
0
        private static Attribute NewAliasAttribute(AttributeAst ast)
        {
            CheckNoNamedArgs(ast);

            var cvv = new ConstantValueVisitor { AttributeArgument = true };
            var args = new string[ast.PositionalArguments.Count];
            for (int i = 0; i < ast.PositionalArguments.Count; i++)
            {
                args[i] = _attrArgToStringConverter.Target(_attrArgToStringConverter,
                    ast.PositionalArguments[i].Accept(cvv));
            }
            return new AliasAttribute(args);
        }
Exemple #7
0
        private static Attribute NewOutputTypeAttribute(AttributeAst ast)
        {
            var cvv = new ConstantValueVisitor { AttributeArgument = true };

            OutputTypeAttribute result;
            if (ast.PositionalArguments.Count == 0)
            {
                result = new OutputTypeAttribute(Utils.EmptyArray<string>());
            }
            else if (ast.PositionalArguments.Count == 1)
            {
                var typeArg = ast.PositionalArguments[0] as TypeExpressionAst;
                if (typeArg != null)
                {
                    var type = TypeOps.ResolveTypeName(typeArg.TypeName, typeArg.Extent);
                    result = new OutputTypeAttribute(type);
                }
                else
                {
                    var argValue = ast.PositionalArguments[0].Accept(cvv);
                    result = new OutputTypeAttribute(_attrArgToStringConverter.Target(_attrArgToStringConverter, argValue));
                }
            }
            else
            {
                var args = new object[ast.PositionalArguments.Count];
                for (int i = 0; i < ast.PositionalArguments.Count; i++)
                {
                    var positionalArgument = ast.PositionalArguments[i];
                    var typeArg = positionalArgument as TypeExpressionAst;
                    args[i] = typeArg != null
                        ? TypeOps.ResolveTypeName(typeArg.TypeName, typeArg.Extent)
                        : positionalArgument.Accept(cvv);
                }

                if (args[0] is Type)
                {
                    result = new OutputTypeAttribute(LanguagePrimitives.ConvertTo<Type[]>(args));
                }
                else
                {
                    result = new OutputTypeAttribute(LanguagePrimitives.ConvertTo<string[]>(args));
                }
            }

            foreach (var namedArg in ast.NamedArguments)
            {
                var argValue = namedArg.Argument.Accept(cvv);
                var argumentName = namedArg.ArgumentName;

                if (argumentName.Equals("ParameterSetName", StringComparison.OrdinalIgnoreCase))
                {
                    result.ParameterSetName = s_attrArgToStringArrayConverter.Target(s_attrArgToStringArrayConverter, argValue);
                }
                else if (argumentName.Equals("ProviderCmdlet", StringComparison.OrdinalIgnoreCase))
                {
                    result.ProviderCmdlet = _attrArgToStringConverter.Target(_attrArgToStringConverter, argValue);
                }
                else
                {
                    throw InterpreterError.NewInterpreterException(namedArg, typeof(RuntimeException), namedArg.Extent,
                        "PropertyNotFoundForType", ParserStrings.PropertyNotFoundForType, argumentName,
                        typeof(CmdletBindingAttribute));
                }
            }

            return result;
        }
Exemple #8
0
        private static Attribute NewParameterAttribute(AttributeAst ast)
        {
            CheckNoPositionalArgs(ast);

            var cvv = new ConstantValueVisitor { AttributeArgument = true };

            var result = new ParameterAttribute();

            foreach (var namedArg in ast.NamedArguments)
            {
                var argValue = namedArg.Argument.Accept(cvv);
                var argumentName = namedArg.ArgumentName;

                if (argumentName.Equals("Position", StringComparison.OrdinalIgnoreCase))
                {
                    result.Position = s_attrArgToIntConverter.Target(s_attrArgToIntConverter, argValue);
                }
                else if (argumentName.Equals("ParameterSetName", StringComparison.OrdinalIgnoreCase))
                {
                    result.ParameterSetName = _attrArgToStringConverter.Target(_attrArgToStringConverter, argValue);
                }
                else if (argumentName.Equals("Mandatory", StringComparison.OrdinalIgnoreCase))
                {
                    result.Mandatory = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue);
                }
                else if (argumentName.Equals("ValueFromPipeline", StringComparison.OrdinalIgnoreCase))
                {
                    result.ValueFromPipeline = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue);
                }
                else if (argumentName.Equals("ValueFromPipelineByPropertyName", StringComparison.OrdinalIgnoreCase))
                {
                    result.ValueFromPipelineByPropertyName = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue);
                }
                else if (argumentName.Equals("ValueFromRemainingArguments", StringComparison.OrdinalIgnoreCase))
                {
                    result.ValueFromRemainingArguments = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue);
                }
                else if (argumentName.Equals("HelpMessage", StringComparison.OrdinalIgnoreCase))
                {
                    result.HelpMessage = _attrArgToStringConverter.Target(_attrArgToStringConverter, argValue);
                }
                else if (argumentName.Equals("HelpMessageBaseName", StringComparison.OrdinalIgnoreCase))
                {
                    result.HelpMessageBaseName = _attrArgToStringConverter.Target(_attrArgToStringConverter, argValue);
                }
                else if (argumentName.Equals("HelpMessageResourceId", StringComparison.OrdinalIgnoreCase))
                {
                    result.HelpMessageResourceId = _attrArgToStringConverter.Target(_attrArgToStringConverter, argValue);
                }
                else if (argumentName.Equals("DontShow", StringComparison.OrdinalIgnoreCase))
                {
                    result.DontShow = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue);
                }
                else
                {
                    throw InterpreterError.NewInterpreterException(namedArg, typeof(RuntimeException), namedArg.Extent,
                        "PropertyNotFoundForType", ParserStrings.PropertyNotFoundForType, argumentName,
                        typeof(CmdletBindingAttribute));
                }
            }

            return result;
        }
Exemple #9
0
        private static Attribute NewCmdletBindingAttribute(AttributeAst ast)
        {
            CheckNoPositionalArgs(ast);

            var cvv = new ConstantValueVisitor { AttributeArgument = true };

            var result = new CmdletBindingAttribute();

            foreach (var namedArg in ast.NamedArguments)
            {
                var argValue = namedArg.Argument.Accept(cvv);
                var argumentName = namedArg.ArgumentName;
                if (argumentName.Equals("DefaultParameterSetName", StringComparison.OrdinalIgnoreCase))
                {
                    result.DefaultParameterSetName = _attrArgToStringConverter.Target(_attrArgToStringConverter, argValue);
                }
                else if (argumentName.Equals("HelpUri", StringComparison.OrdinalIgnoreCase))
                {
                    result.HelpUri = _attrArgToStringConverter.Target(_attrArgToStringConverter, argValue);
                }
                else if (argumentName.Equals("SupportsShouldProcess", StringComparison.OrdinalIgnoreCase))
                {
                    result.SupportsShouldProcess = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue);
                }
                else if (argumentName.Equals("PositionalBinding", StringComparison.OrdinalIgnoreCase))
                {
                    result.PositionalBinding = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue);
                }
                else if (argumentName.Equals("ConfirmImpact", StringComparison.OrdinalIgnoreCase))
                {
                    result.ConfirmImpact = s_attrArgToConfirmImpactConverter.Target(s_attrArgToConfirmImpactConverter, argValue);
                }
                else if (argumentName.Equals("SupportsTransactions", StringComparison.OrdinalIgnoreCase))
                {
                    result.SupportsTransactions = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue);
                }
                else if (argumentName.Equals("SupportsPaging", StringComparison.OrdinalIgnoreCase))
                {
                    result.SupportsPaging = s_attrArgToBoolConverter.Target(s_attrArgToBoolConverter, argValue);
                }
                else if (argumentName.Equals("RemotingCapability", StringComparison.OrdinalIgnoreCase))
                {
                    result.RemotingCapability = s_attrArgToRemotingCapabilityConverter.Target(s_attrArgToRemotingCapabilityConverter, argValue);
                }
                else
                {
                    throw InterpreterError.NewInterpreterException(namedArg, typeof(RuntimeException), namedArg.Extent,
                        "PropertyNotFoundForType", ParserStrings.PropertyNotFoundForType, argumentName,
                        typeof(CmdletBindingAttribute));
                }
            }

            return result;
        }
        } // 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));
                    }
                }
            }
        }
Exemple #11
0
        private static CustomAttributeBuilder GetAttributeBuilder(Parser parser, AttributeAst attributeAst, AttributeTargets attributeTargets)
        {
            var attributeType = attributeAst.TypeName.GetReflectionAttributeType();
            Diagnostics.Assert(attributeType != null, "Semantic checks should have verified attribute type exists");

            Diagnostics.Assert(
                attributeType.GetTypeInfo().GetCustomAttribute<AttributeUsageAttribute>(true) == null ||
                (attributeType.GetTypeInfo().GetCustomAttribute<AttributeUsageAttribute>(true).ValidOn & attributeTargets) != 0, "Semantic checks should have verified attribute usage");

            var positionalArgs = new object[attributeAst.PositionalArguments.Count];
            var cvv = new ConstantValueVisitor { AttributeArgument = false };
            for (var i = 0; i < attributeAst.PositionalArguments.Count; i++)
            {
                var posArg = attributeAst.PositionalArguments[i];
                positionalArgs[i] = posArg.Accept(cvv);
            }

            var ctorInfos = attributeType.GetConstructors();
            var newConstructors = DotNetAdapter.GetMethodInformationArray(ctorInfos);

            string errorId = null;
            string errorMsg = null;
            bool expandParamsOnBest;
            bool callNonVirtually;
            var positionalArgCount = positionalArgs.Length;
            var bestMethod = Adapter.FindBestMethod(newConstructors, null, positionalArgs, ref errorId, ref errorMsg, out expandParamsOnBest, out callNonVirtually);
            if (bestMethod == null)
            {
                parser.ReportError(new ParseError(attributeAst.Extent, errorId,
                    string.Format(CultureInfo.InvariantCulture, errorMsg, attributeType.Name, attributeAst.PositionalArguments.Count)));
                return null;
            }

            var constructorInfo = (ConstructorInfo)bestMethod.method;

            var parameterInfo = constructorInfo.GetParameters();
            var ctorArgs = new object[parameterInfo.Length];
            object arg;
            for (var argIndex = 0; argIndex < parameterInfo.Length; ++argIndex)
            {
                var resultType = parameterInfo[argIndex].ParameterType;

                // The extension method 'CustomAttributeExtensions.GetCustomAttributes(ParameterInfo, Type, Boolean)' has inconsistent
                // behavior on its return value in both FullCLR and CoreCLR. According to MSDN, if the attribute cannot be found, it
                // should return an empty collection. However, it returns null in some rare cases [when the parameter isn't backed by
                // actual metadata].
                // This inconsistent behavior affects OneCore powershell because we are using the extension method here when compiling
                // against CoreCLR. So we need to add a null check until this is fixed in CLR.
                var paramArrayAttrs = parameterInfo[argIndex].GetCustomAttributes(typeof(ParamArrayAttribute), true);
                if (paramArrayAttrs != null && paramArrayAttrs.Any() && expandParamsOnBest)
                {
                    var elementType = parameterInfo[argIndex].ParameterType.GetElementType();
                    var paramsArray = Array.CreateInstance(elementType, positionalArgCount - argIndex);
                    ctorArgs[argIndex] = paramsArray;

                    for (var i = 0; i < paramsArray.Length; ++i, ++argIndex)
                    {
                        if (!TryConvertArg(positionalArgs[argIndex], elementType, out arg,
                            parser, attributeAst.PositionalArguments[argIndex].Extent))
                        {
                            return null;
                        }
                        paramsArray.SetValue(arg, i);
                    }
                    break;
                }

                if (!TryConvertArg(positionalArgs[argIndex], resultType, out arg,
                    parser, attributeAst.PositionalArguments[argIndex].Extent))
                {
                    return null;
                }
                ctorArgs[argIndex] = arg;
            }

            if (attributeAst.NamedArguments.Count == 0)
            {
                return new CustomAttributeBuilder(constructorInfo, ctorArgs);
            }

            var propertyInfoList = new List<PropertyInfo>();
            var propertyArgs = new List<object>();
            var fieldInfoList = new List<FieldInfo>();
            var fieldArgs = new List<object>();
            foreach (var namedArg in attributeAst.NamedArguments)
            {
                var name = namedArg.ArgumentName;
                var members = attributeType.GetMember(name, MemberTypes.Field | MemberTypes.Property,
                    BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
                Diagnostics.Assert(members.Length == 1 && (members[0] is PropertyInfo || members[0] is FieldInfo),
                    "Semantic checks should have ensured names attribute argument exists");

                arg = namedArg.Argument.Accept(cvv);

                var propertyInfo = members[0] as PropertyInfo;
                if (propertyInfo != null)
                {
                    Diagnostics.Assert(propertyInfo.GetSetMethod() != null, "Semantic checks ensures property is settable");

                    if (!TryConvertArg(arg, propertyInfo.PropertyType, out arg, parser, namedArg.Argument.Extent))
                    {
                        return null;
                    }

                    propertyInfoList.Add(propertyInfo);
                    propertyArgs.Add(arg);
                    continue;
                }

                var fieldInfo = (FieldInfo)members[0];
                Diagnostics.Assert(!fieldInfo.IsInitOnly && !fieldInfo.IsLiteral, "Semantic checks ensures field is settable");

                if (!TryConvertArg(arg, fieldInfo.FieldType, out arg, parser, namedArg.Argument.Extent))
                {
                    return null;
                }
                fieldInfoList.Add(fieldInfo);
                fieldArgs.Add(arg);
            }

            return new CustomAttributeBuilder(constructorInfo, ctorArgs,
                propertyInfoList.ToArray(), propertyArgs.ToArray(),
                fieldInfoList.ToArray(), fieldArgs.ToArray());
        }
Exemple #12
0
 internal static Attribute GetAttribute(AttributeAst attributeAst)
 {
     Attribute attribute;
     int count = attributeAst.PositionalArguments.Count;
     IEnumerable<string> source = from name in attributeAst.NamedArguments select name.ArgumentName;
     int argCount = count + source.Count<string>();
     CallInfo callInfo = new CallInfo(argCount, source);
     object[] args = new object[argCount + 1];
     Type reflectionAttributeType = attributeAst.TypeName.GetReflectionAttributeType();
     if (reflectionAttributeType == null)
     {
         throw InterpreterError.NewInterpreterException(attributeAst, typeof(RuntimeException), attributeAst.Extent, "CustomAttributeTypeNotFound", ParserStrings.CustomAttributeTypeNotFound, new object[] { attributeAst.TypeName.FullName });
     }
     args[0] = reflectionAttributeType;
     ConstantValueVisitor visitor = new ConstantValueVisitor {
         AttributeArgument = true
     };
     int num3 = 1;
     foreach (ExpressionAst ast in attributeAst.PositionalArguments)
     {
         args[num3++] = ast.Accept(visitor);
     }
     foreach (NamedAttributeArgumentAst ast2 in attributeAst.NamedArguments)
     {
         args[num3++] = ast2.Argument.Accept(visitor);
     }
     try
     {
         attribute = (Attribute) GetAttributeGenerator(callInfo).DynamicInvoke(args);
     }
     catch (TargetInvocationException exception)
     {
         Exception innerException = exception.InnerException;
         RuntimeException exception3 = innerException as RuntimeException;
         if (exception3 == null)
         {
             exception3 = InterpreterError.NewInterpreterExceptionWithInnerException(null, typeof(RuntimeException), attributeAst.Extent, "ExceptionConstructingAttribute", ExtendedTypeSystem.ExceptionConstructingAttribute, innerException, new object[] { innerException.Message, attributeAst.TypeName.FullName });
         }
         InterpreterError.UpdateExceptionErrorRecordPosition(exception3, attributeAst.Extent);
         throw exception3;
     }
     return attribute;
 }
Exemple #13
0
 private Action<List<Expression>, Expression> GetSwitchBodyGenerator(SwitchStatementAst switchStatementAst, AutomaticVarSaver avs, ParameterExpression skipDefault)
 {
     return delegate (List<Expression> exprs, Expression newValue) {
         PSSwitchClauseEvalBinder binder = PSSwitchClauseEvalBinder.Get(switchStatementAst.Flags);
         exprs.Add(avs.SetNewValue(newValue));
         if (skipDefault != null)
         {
             exprs.Add(Expression.Assign(skipDefault, ExpressionCache.Constant(false)));
         }
         IsConstantValueVisitor visitor = new IsConstantValueVisitor();
         ConstantValueVisitor visitor2 = new ConstantValueVisitor();
         int count = switchStatementAst.Clauses.Count;
         for (int j = 0; j < count; j++)
         {
             Expression expression;
             Tuple<ExpressionAst, StatementBlockAst> tuple = switchStatementAst.Clauses[j];
             object obj2 = ((bool) tuple.Item1.Accept(visitor)) ? tuple.Item1.Accept(visitor2) : null;
             if (obj2 is ScriptBlock)
             {
                 MethodCallExpression expression2 = Expression.Call(Expression.Constant(obj2), CachedReflectionInfo.ScriptBlock_DoInvokeReturnAsIs, new Expression[] { ExpressionCache.Constant(true), Expression.Constant(ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe), this.GetLocal(0).Convert(typeof(object)), ExpressionCache.AutomationNullConstant, ExpressionCache.AutomationNullConstant, ExpressionCache.NullObjectArray });
                 expression = Expression.Dynamic(PSConvertBinder.Get(typeof(bool)), typeof(bool), expression2);
             }
             else if (obj2 != null)
             {
                 SwitchFlags flags = switchStatementAst.Flags;
                 Expression expression3 = Expression.Constant(((obj2 is Regex) || (obj2 is WildcardPattern)) ? obj2 : obj2.ToString());
                 Expression expression4 = Expression.Dynamic(PSToStringBinder.Get(), typeof(string), this.GetLocal(0), _executionContextParameter);
                 if (((flags & SwitchFlags.Regex) != SwitchFlags.None) || (obj2 is Regex))
                 {
                     expression = Expression.Call(CachedReflectionInfo.SwitchOps_ConditionSatisfiedRegex, ExpressionCache.Constant((flags & SwitchFlags.CaseSensitive) != SwitchFlags.None), expression3, Expression.Constant(tuple.Item1.Extent), expression4, _executionContextParameter);
                 }
                 else if (((flags & SwitchFlags.Wildcard) != SwitchFlags.None) || (obj2 is WildcardPattern))
                 {
                     expression = Expression.Call(CachedReflectionInfo.SwitchOps_ConditionSatisfiedWildcard, ExpressionCache.Constant((flags & SwitchFlags.CaseSensitive) != SwitchFlags.None), expression3, expression4, _executionContextParameter);
                 }
                 else
                 {
                     expression = CallStringEquals(expression3, expression4, (flags & SwitchFlags.CaseSensitive) == SwitchFlags.None);
                 }
             }
             else
             {
                 Expression expression5 = this.Compile(tuple.Item1);
                 expression = Expression.Dynamic(binder, typeof(bool), expression5, this.GetLocal(0), _executionContextParameter);
             }
             exprs.Add(this.UpdatePosition(tuple.Item1));
             if (skipDefault != null)
             {
                 exprs.Add(Expression.IfThen(expression, Expression.Block(this.Compile(tuple.Item2), Expression.Assign(skipDefault, ExpressionCache.Constant(true)))));
             }
             else
             {
                 exprs.Add(Expression.IfThen(expression, this.Compile(tuple.Item2)));
             }
         }
         if (skipDefault != null)
         {
             exprs.Add(Expression.IfThen(Expression.Not(skipDefault), this.Compile(switchStatementAst.Default)));
         }
     };
 }