示例#1
0
        internal override IEnumerable <PSTypeName> GetInferredType(CompletionContext context)
        {
            TypeConstraintAst iteratorVariable0 = this.Attributes.OfType <TypeConstraintAst>().FirstOrDefault <TypeConstraintAst>();

            if (iteratorVariable0 != null)
            {
                Type reflectionType = iteratorVariable0.TypeName.GetReflectionType();
                if (reflectionType != null)
                {
                    yield return(new PSTypeName(reflectionType));
                }
                else
                {
                    yield return(new PSTypeName(iteratorVariable0.TypeName.FullName));
                }
            }
            IEnumerator <AttributeAst> enumerator = this.Attributes.OfType <AttributeAst>().GetEnumerator();

            while (enumerator.MoveNext())
            {
                AttributeAst        current   = enumerator.Current;
                PSTypeNameAttribute attribute = null;
                try
                {
                    attribute = current.GetAttribute() as PSTypeNameAttribute;
                }
                catch (RuntimeException)
                {
                }
                if (attribute != null)
                {
                    yield return(new PSTypeName(attribute.PSTypeName));
                }
            }
        }
示例#2
0
        public override AstVisitAction VisitAttribute(AttributeAst attributeAst)
        {
            HashSet <string> set = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            foreach (NamedAttributeArgumentAst ast in attributeAst.NamedArguments)
            {
                string argumentName = ast.ArgumentName;
                if (set.Contains(argumentName))
                {
                    this._parser.ReportError(ast.Extent, ParserStrings.DuplicateNamedArgument, new object[] { argumentName });
                }
                else
                {
                    set.Add(argumentName);
                    if (!ast.ExpressionOmitted && !this.IsValidAttributeArgument(ast.Argument))
                    {
                        this._parser.ReportError(ast.Argument.Extent, ParserStrings.ParameterAttributeArgumentNeedsToBeConstantOrScriptBlock, new object[0]);
                    }
                }
            }
            foreach (ExpressionAst ast2 in attributeAst.PositionalArguments)
            {
                if (!this.IsValidAttributeArgument(ast2))
                {
                    this._parser.ReportError(ast2.Extent, ParserStrings.ParameterAttributeArgumentNeedsToBeConstantOrScriptBlock, new object[0]);
                }
            }
            return(AstVisitAction.Continue);
        }
示例#3
0
    public System.Object VisitAttribute(System.Management.Automation.Language.AttributeAst attributeAst)
    {
        IScriptExtent mappedExtent = MapExtent(attributeAst.Extent);

        LinkedList <ExpressionAst> mappedPositionalArguments = new LinkedList <ExpressionAst>();

        foreach (ExpressionAst e in attributeAst.PositionalArguments)
        {
            mappedPositionalArguments.AddLast(_VisitExpression(e));
        }

        LinkedList <NamedAttributeArgumentAst> mappedNamedArguments = new LinkedList <NamedAttributeArgumentAst>();

        foreach (NamedAttributeArgumentAst na in attributeAst.NamedArguments)
        {
            mappedNamedArguments.AddLast((NamedAttributeArgumentAst)VisitNamedAttributeArgument(na));
        }

        return(new AttributeAst(mappedExtent, attributeAst.TypeName, mappedPositionalArguments, mappedNamedArguments));
    }
示例#4
0
        public override AstVisitAction VisitAttribute(AttributeAst attributeAst)
        {
            HashSet<string> names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            bool checkingAttributeOnClass = false;
            AttributeTargets attributeTargets = default(AttributeTargets);

            var parent = attributeAst.Parent;
            TypeDefinitionAst typeDefinitionAst = parent as TypeDefinitionAst;
            if (typeDefinitionAst != null)
            {
                checkingAttributeOnClass = true;
                attributeTargets = typeDefinitionAst.IsClass
                    ? AttributeTargets.Class
                    : typeDefinitionAst.IsEnum
                        ? AttributeTargets.Enum
                        : AttributeTargets.Interface;
            }
            else if (parent is PropertyMemberAst)
            {
                checkingAttributeOnClass = true;
                attributeTargets = AttributeTargets.Property | AttributeTargets.Field;
            }
            else
            {
                var functionMemberAst = parent as FunctionMemberAst;
                if (functionMemberAst != null)
                {
                    checkingAttributeOnClass = true;
                    attributeTargets = functionMemberAst.IsConstructor
                        ? AttributeTargets.Constructor
                        : AttributeTargets.Method;
                }
                else if (parent is ParameterAst && _memberScopeStack.Peek() is FunctionMemberAst)
                {
                    checkingAttributeOnClass = true;

                    // TODO: we aren't actually generating any attributes in the class metadata
                    attributeTargets = AttributeTargets.Parameter;
                }
            }

            var constantValueVisitor = checkingAttributeOnClass
                ? s_isConstantAttributeArgForClassVisitor
                : s_isConstantAttributeArgVisitor;

            if (checkingAttributeOnClass)
            {
                var attributeType = attributeAst.TypeName.GetReflectionAttributeType();
                if (attributeType == null)
                {
                    Diagnostics.Assert(_parser.ErrorList.Count > 0, "Symbol resolve should have reported error already");
                }
                else
                {
                    var usage = attributeType.GetTypeInfo().GetCustomAttribute<AttributeUsageAttribute>(true);
                    if (usage != null && (usage.ValidOn & attributeTargets) == 0)
                    {
                        _parser.ReportError(attributeAst.Extent, () => ParserStrings.AttributeNotAllowedOnDeclaration, ToStringCodeMethods.Type(attributeType), usage.ValidOn);
                    }

                    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);
                        if (members.Length != 1 || !(members[0] is PropertyInfo || members[0] is FieldInfo))
                        {
                            _parser.ReportError(namedArg.Extent,
                                () => ParserStrings.PropertyNotFoundForAttribute,
                                name,
                                ToStringCodeMethods.Type(attributeType),
                                GetValidNamedAttributeProperties(attributeType));

                            continue;
                        }

                        var propertyInfo = members[0] as PropertyInfo;
                        if (propertyInfo != null)
                        {
                            if (propertyInfo.GetSetMethod() == null)
                            {
                                _parser.ReportError(namedArg.Extent, () => ExtendedTypeSystem.ReadOnlyProperty, name);
                            }

                            continue;
                        }

                        var fieldInfo = (FieldInfo)members[0];
                        if (fieldInfo.IsInitOnly || fieldInfo.IsLiteral)
                        {
                            _parser.ReportError(namedArg.Extent, () => ExtendedTypeSystem.ReadOnlyProperty, name);
                        }
                    }
                }
            }

            foreach (var namedArg in attributeAst.NamedArguments)
            {
                string name = namedArg.ArgumentName;
                if (names.Contains(name))
                {
                    _parser.ReportError(namedArg.Extent, () => ParserStrings.DuplicateNamedArgument, name);
                }
                else
                {
                    names.Add(name);

                    if (!namedArg.ExpressionOmitted && !IsValidAttributeArgument(namedArg.Argument, constantValueVisitor))
                    {
                        _parser.ReportError(namedArg.Argument.Extent, GetNonConstantAttributeArgErrorExpr(constantValueVisitor));
                    }
                }
            }

            foreach (var posArg in attributeAst.PositionalArguments)
            {
                if (!IsValidAttributeArgument(posArg, constantValueVisitor))
                {
                    _parser.ReportError(posArg.Extent, GetNonConstantAttributeArgErrorExpr(constantValueVisitor));
                }
            }

            return AstVisitAction.Continue;
        }
示例#5
0
 /// <summary/>
 public virtual object VisitAttribute(AttributeAst attributeAst)
 {
     return(null);
 }
 /// <summary>
 /// Visit attribute
 /// </summary>
 /// <param name="attributeAst"></param>
 /// <returns></returns>
 public object VisitAttribute(AttributeAst attributeAst)
 {
     System.Diagnostics.Debug.Assert(false, "Code is unreachable");
     return null;
 }
示例#7
0
 public override AstVisitAction VisitAttribute(AttributeAst attributeAst)
 {
     DispatchTypeName(attributeAst.TypeName, genericArgumentCount: 0, isAttribute: true);
     return AstVisitAction.Continue;
 }
示例#8
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;
            }
        }
 public override AstVisitAction VisitAttribute(AttributeAst attributeAst)
 {
     this.ReportError(attributeAst, () => ParserStrings.AttributeNotSupportedInDataSection, new object[0]);
     return AstVisitAction.Continue;
 }
示例#10
0
 public object VisitAttribute(AttributeAst attributeAst) { return AutomationNull.Value; }
示例#11
0
 public object VisitAttribute(AttributeAst attributeAst)
 {
     return(AutomationNull.Value);
 }
 public override AstVisitAction VisitAttribute(AttributeAst attributeAst)
 {
     this.ReportError(attributeAst, () => ParserStrings.AttributeNotSupportedInDataSection, new object[0]);
     return(AstVisitAction.Continue);
 }
示例#13
0
 public override AstVisitAction VisitAttribute(AttributeAst ast)
 {
     return this.Check(ast);
 }
 public object VisitAttribute(AttributeAst attributeAst) { throw new UnexpectedElementException(); }
示例#15
0
        public override AstVisitAction VisitAttribute(AttributeAst attributeAst)
        {
            Diagnostics.Assert(FoundError, "an error should have been reported elsewhere, making this redunant");
            ReportError(attributeAst, () => ParserStrings.AttributeNotSupportedInDataSection);

            return AstVisitAction.Continue;
        }
示例#16
0
        /// <summary>
        /// Check if it is a qualified DSC resource type
        /// </summary>
        /// <param name="parser"></param>
        /// <param name="typeDefinitionAst"></param>
        /// <param name="dscResourceAttributeAst"></param>
        internal static void CheckType(Parser parser, TypeDefinitionAst typeDefinitionAst, AttributeAst dscResourceAttributeAst)
        {
            bool hasSet = false;
            bool hasTest = false;
            bool hasGet = false;
            bool hasDefaultCtor = false;
            bool hasNonDefaultCtor = false;
            bool hasKey = false;

            Diagnostics.Assert(dscResourceAttributeAst != null, "CheckType called only for DSC resources. dscResourceAttributeAst must be non-null.");

            foreach (var member in typeDefinitionAst.Members)
            {
                var functionMemberAst = member as FunctionMemberAst;

                if (functionMemberAst != null)
                {
                    CheckSet(functionMemberAst, ref hasSet);
                    CheckGet(parser, functionMemberAst, ref hasGet);
                    CheckTest(functionMemberAst, ref hasTest);

                    if (functionMemberAst.IsConstructor && !functionMemberAst.IsStatic)
                    {
                        if (functionMemberAst.Parameters.Count == 0)
                        {
                            hasDefaultCtor = true;
                        }
                        else
                        {
                            hasNonDefaultCtor = true;
                        }
                    }
                }
                else
                {
                    var propertyMemberAst = (PropertyMemberAst)member;
                    CheckKey(parser, propertyMemberAst, ref hasKey);
                }
            }

            if (typeDefinitionAst.BaseTypes != null && (!hasSet || !hasGet || !hasTest || !hasKey))
            {
                LookupRequiredMembers(parser, typeDefinitionAst, ref hasSet, ref hasGet, ref hasTest, ref hasKey);
            }

            var name = typeDefinitionAst.Name;

            if (!hasSet)
            {
                parser.ReportError(dscResourceAttributeAst.Extent, () => ParserStrings.DscResourceMissingSetMethod, name);
            }

            if (!hasGet)
            {
                parser.ReportError(dscResourceAttributeAst.Extent, () => ParserStrings.DscResourceMissingGetMethod, name);
            }

            if (!hasTest)
            {
                parser.ReportError(dscResourceAttributeAst.Extent, () => ParserStrings.DscResourceMissingTestMethod, name);
            }

            if (!hasDefaultCtor && hasNonDefaultCtor)
            {
                parser.ReportError(dscResourceAttributeAst.Extent, () => ParserStrings.DscResourceMissingDefaultConstructor, name);
            }

            if (!hasKey)
            {
                parser.ReportError(dscResourceAttributeAst.Extent, () => ParserStrings.DscResourceMissingKeyProperty, name);
            }
        }
示例#17
0
 public object VisitAttribute(AttributeAst attributeAst)
 {
     return false;
 }
        /// <summary>
        /// Returns rule suppression from an attribute ast that has the type suppressmessageattribute
        /// </summary>
        /// <param name="attrAst"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        public RuleSuppression(AttributeAst attrAst, int start, int end)
        {
            Error = String.Empty;

            if (attrAst != null)
            {
                StartAttributeLine = attrAst.Extent.StartLineNumber;
                var positionalArguments = attrAst.PositionalArguments;
                var namedArguments = attrAst.NamedArguments;

                int lastPositionalArgumentsOffset = -1;

                if (positionalArguments != null && positionalArguments.Count != 0)
                {
                    int count = positionalArguments.Count;
                    lastPositionalArgumentsOffset = positionalArguments[positionalArguments.Count - 1].Extent.StartOffset;

                    if (positionalArguments.Any(item => !(item is StringConstantExpressionAst)))
                    {
                        Error = Strings.StringConstantArgumentsSuppressionAttributeError;
                    }
                    else
                    {
                        switch (count)
                        {
                            case 5:
                                Justification = (positionalArguments[4] as StringConstantExpressionAst).Value;
                                goto case 4;

                            case 4:
                                Target = (positionalArguments[3] as StringConstantExpressionAst).Value;
                                goto case 3;

                            case 3:
                                Scope = (positionalArguments[2] as StringConstantExpressionAst).Value;
                                goto case 2;

                            case 2:
                                RuleSuppressionID = (positionalArguments[1] as StringConstantExpressionAst).Value;
                                goto case 1;

                            case 1:
                                RuleName = (positionalArguments[0] as StringConstantExpressionAst).Value;
                                goto default;

                            default:
                                break;
                        }
                    }
                }

                if (namedArguments != null && namedArguments.Count != 0)
                {
                    foreach (var name in namedArguments)
                    {
                        if (name.Extent.StartOffset < lastPositionalArgumentsOffset)
                        {
                            Error = Strings.NamedArgumentsBeforePositionalError;
                            break;
                        }
                        else if (!(name.Argument is StringConstantExpressionAst))
                        {
                            Error = Strings.StringConstantArgumentsSuppressionAttributeError;
                            break;
                        }

                        switch (name.ArgumentName.ToLower())
                        {
                            case "rulename":
                                if (!String.IsNullOrWhiteSpace(RuleName))
                                {
                                    Error = String.Format(Strings.NamedAndPositionalArgumentsConflictError, name);
                                }

                                RuleName = (name.Argument as StringConstantExpressionAst).Value;
                                goto default;

                            case "rulesuppressionid":
                                if (!String.IsNullOrWhiteSpace(RuleSuppressionID))
                                {
                                    Error = String.Format(Strings.NamedAndPositionalArgumentsConflictError, name);
                                }

                                RuleSuppressionID = (name.Argument as StringConstantExpressionAst).Value;
                                goto default;

                            case "scope":
                                if (!String.IsNullOrWhiteSpace(Scope))
                                {
                                    Error = String.Format(Strings.NamedAndPositionalArgumentsConflictError, name);
                                }

                                Scope = (name.Argument as StringConstantExpressionAst).Value;

                                if (!scopeSet.Contains(Scope))
                                {
                                    Error = Strings.WrongScopeArgumentSuppressionAttributeError;
                                }

                                goto default;

                            case "target":
                                if (!String.IsNullOrWhiteSpace(Target))
                                {
                                    Error = String.Format(Strings.NamedAndPositionalArgumentsConflictError, name);
                                }

                                Target = (name.Argument as StringConstantExpressionAst).Value;
                                goto default;

                            case "justification":
                                if (!String.IsNullOrWhiteSpace(Justification))
                                {
                                    Error = String.Format(Strings.NamedAndPositionalArgumentsConflictError, name);
                                }

                                Justification = (name.Argument as StringConstantExpressionAst).Value;
                                goto default;

                            default:
                                break;
                        }
                    }
                }

                if (!String.IsNullOrWhiteSpace(Error))
                {
                    // May be cases where the rulename is null because we didn't look at the rulename after
                    // we found out there is an error
                    RuleName = String.Empty;
                }
                else if (String.IsNullOrWhiteSpace(RuleName))
                {
                    RuleName = String.Empty;
                    Error = Strings.NullRuleNameError;
                }

                // Must have scope and target together
                if (String.IsNullOrWhiteSpace(Scope) && !String.IsNullOrWhiteSpace(Target))
                {
                    Error = Strings.TargetWithoutScopeSuppressionAttributeError;
                }
            }

            StartOffset = start;
            EndOffset = end;

            if (!String.IsNullOrWhiteSpace(Error))
            {
                Error = String.Format(CultureInfo.CurrentCulture, Strings.RuleSuppressionErrorFormat, StartAttributeLine,
                    System.IO.Path.GetFileName(attrAst.Extent.File), Error);
            }
        }
示例#19
0
 public override AstVisitAction VisitAttribute(AttributeAst attributeAst)
 {
     DispatchTypeName(attributeAst.TypeName, genericArgumentCount: 0, isAttribute: true);
     return(AstVisitAction.Continue);
 }
示例#20
0
 public object VisitAttribute(AttributeAst attributeAst) { throw PSTraceSource.NewArgumentException("ast"); }
示例#21
0
文件: Compiler.cs 项目: nickchal/pash
 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;
 }
示例#22
0
 private static void CheckNoPositionalArgs(AttributeAst ast)
 {
     var positionalArgCount = ast.PositionalArguments.Count;
     if (positionalArgCount > 0)
     {
         throw InterpreterError.NewInterpreterException(null, typeof(MethodException), ast.Extent,
             "MethodCountCouldNotFindBest", ExtendedTypeSystem.MethodArgumentCountException, ".ctor",
             positionalArgCount);
     }
 }
示例#23
0
 public object VisitAttribute(AttributeAst attributeAst)
 {
     Diagnostics.Assert(false, "Nothing to generate for an attribute");
     return null;
 }
示例#24
0
 private static void CheckNoNamedArgs(AttributeAst ast)
 {
     if (ast.NamedArguments.Count > 0)
     {
         var namedArg = ast.NamedArguments[0];
         var argumentName = namedArg.ArgumentName;
         throw InterpreterError.NewInterpreterException(namedArg, typeof(RuntimeException), namedArg.Extent,
             "PropertyNotFoundForType", ParserStrings.PropertyNotFoundForType, argumentName,
             typeof(CmdletBindingAttribute));
     }
 }
示例#25
0
 public object VisitAttribute(AttributeAst attributeAst)
 {
     return null;
 }
示例#26
0
 public override AstVisitAction VisitAttribute(AttributeAst attributeAst)
 {
     throw new NotImplementedException(); //VisitAttribute(attributeAst);
 }
 /// <summary/>
 public virtual object VisitAttribute(AttributeAst attributeAst)
 {
     return _decorated.VisitAttribute(attributeAst);
 }
示例#28
0
文件: PSType.cs 项目: 40a/PowerShell
        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());
        }
示例#29
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;
        }
示例#30
0
 /// <summary/>
 public virtual AstVisitAction VisitAttribute(AttributeAst attributeAst) => DefaultVisit(attributeAst);
示例#31
0
 public virtual AstVisitAction VisitAttribute(AttributeAst attributeAst)
 {
     return AstVisitAction.Continue;
 }
示例#32
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;
        }
示例#33
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;
        }
示例#34
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);
        }
示例#35
0
 public override AstVisitAction VisitAttribute(AttributeAst ast)
 {
     return(Check(ast));
 }
示例#36
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;
        }
示例#37
0
 public object VisitAttribute(AttributeAst attributeAst)
 {
     throw PSTraceSource.NewArgumentException("ast");
 }
示例#38
0
 private static Attribute NewDebuggerHiddenAttribute(AttributeAst ast)
 {
     CheckNoPositionalArgs(ast);
     CheckNoNamedArgs(ast);
     return new DebuggerHiddenAttribute();
 }
示例#39
0
 /// <summary/>
 public virtual AstVisitAction VisitAttribute(AttributeAst attributeAst)
 {
     return(AstVisitAction.Continue);
 }
示例#40
0
 private static Attribute NewValidateNotNullAttribute(AttributeAst ast)
 {
     CheckNoPositionalArgs(ast);
     CheckNoNamedArgs(ast);
     return new ValidateNotNullAttribute();
 }
示例#41
0
 public object VisitAttribute(AttributeAst attributeAst)
 {
     return(false);
 }
示例#42
0
 public override AstVisitAction VisitAttribute(AttributeAst attributeAst)
 {
     HashSet<string> set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
     foreach (NamedAttributeArgumentAst ast in attributeAst.NamedArguments)
     {
         string argumentName = ast.ArgumentName;
         if (set.Contains(argumentName))
         {
             this._parser.ReportError(ast.Extent, ParserStrings.DuplicateNamedArgument, new object[] { argumentName });
         }
         else
         {
             set.Add(argumentName);
             if (!ast.ExpressionOmitted && !this.IsValidAttributeArgument(ast.Argument))
             {
                 this._parser.ReportError(ast.Argument.Extent, ParserStrings.ParameterAttributeArgumentNeedsToBeConstantOrScriptBlock, new object[0]);
             }
         }
     }
     foreach (ExpressionAst ast2 in attributeAst.PositionalArguments)
     {
         if (!this.IsValidAttributeArgument(ast2))
         {
             this._parser.ReportError(ast2.Extent, ParserStrings.ParameterAttributeArgumentNeedsToBeConstantOrScriptBlock, new object[0]);
         }
     }
     return AstVisitAction.Continue;
 }