Inheritance: ScriptableObject
        public CodeGenerator(AttributeData attributeData)
        {
            Requires.NotNull(attributeData, nameof(attributeData));

            this.attributeData = attributeData;
            this.data = this.attributeData.NamedArguments.ToImmutableDictionary(kv => kv.Key, kv => kv.Value);
        }
        private RoslynAttributeMetadata(AttributeData a)
        {
            var declaration = a.ToString();
            var index = declaration.IndexOf("(", StringComparison.Ordinal);

            this.symbol = a.AttributeClass;
            this.name = symbol.Name;

            if (index > -1)
            {
                this.value = declaration.Substring(index + 1, declaration.Length - index - 2);

                // Trim {} from params
                if (this.value.EndsWith("\"}"))
                {
                    this.value = this.value.Remove(this.value.LastIndexOf("{\"", StringComparison.Ordinal), 1);
                    this.value = this.value.TrimEnd('}');
                }
                else if (this.value.EndsWith("}"))
                {
                    this.value = this.value.Remove(this.value.LastIndexOf("{", StringComparison.Ordinal), 1);
                    this.value = this.value.TrimEnd('}');
                }
            }

            if (name.EndsWith("Attribute"))
                name = name.Substring(0, name.Length - 9);
        }
Exemple #3
0
    public string ConvertToMessage(AttributeData attributeData)
    {
        var stringBuilder = new StringBuilder();
        var message = attributeData.Message;
        if (message != null)
        {
            message = message.Trim();
            message = message.Trim('.');
            stringBuilder.AppendFormat("{0}. ", message);
        }

        if (attributeData.Replacement != null)
        {
            stringBuilder.AppendFormat(ReplacementFormat, attributeData.Replacement);
        }

        if (assemblyVersion < attributeData.TreatAsErrorFromVersion)
        {
            stringBuilder.AppendFormat(TreatAsErrorFormat, attributeData.TreatAsErrorFromVersion.ToSemVer());
        }
        if (attributeData.ThrowsNotImplemented)
        {
            stringBuilder.Append(ThrowsNotImplementedText);
        }
        stringBuilder.AppendFormat(RemoveInVersionFormat, attributeData.RemoveInVersion.ToSemVer());

        return stringBuilder.ToString().Trim();
    }
 public LockInfo(
     FieldDeclarationSyntax declaration,
     FieldSymbol symbol,
     AttributeData associatedAttribute,
     SemanticModel semanticModel)
     : base(declaration, symbol, associatedAttribute, semanticModel)
 {
 }
 public static AttributeRemoveAction Create(
     AttributeData attribute,
     Project project,
     Diagnostic diagnostic,
     AbstractSuppressionCodeFixProvider fixer)
 {
     return new AttributeRemoveAction(attribute, project, diagnostic, fixer);
 }
 public GuardedFieldInfo(
     FieldDeclarationSyntax declaration,
     FieldSymbol symbol,
     AttributeData associatedAttribute,
     SemanticModel semanticModel)
     : base(declaration, symbol, associatedAttribute, semanticModel)
 {
     _declaredLockHierarchy = LockHierarchy.FromStringList(Attribute.ConstructorArguments.SelectMany(arg => arg.Values.Select(argVal => argVal.Value.ToString())).ToList());
 }
Exemple #7
0
 private static AttributeListSyntax GenerateAttributeDeclaration(
     AttributeData attribute, SyntaxToken? target, CodeGenerationOptions options)
 {
     var attributeSyntax = GenerateAttribute(attribute, options);
     return attributeSyntax == null
         ? null
         : SyntaxFactory.AttributeList(
             target.HasValue ? SyntaxFactory.AttributeTargetSpecifier(target.Value) : null,
             SyntaxFactory.SingletonSeparatedList(attributeSyntax));
 }
 private AttributeRemoveAction(
     AttributeData attribute,
     Project project,
     Diagnostic diagnostic,
     AbstractSuppressionCodeFixProvider fixer,
     bool forFixMultipleContext = false)
     : base(diagnostic, fixer, forFixMultipleContext)
 {
     _project = project;
     _attribute = attribute;
 }
Exemple #9
0
 bool GetIsError(AttributeData attributeData)
 {
     if (attributeData.TreatAsErrorFromVersion != null)
     {
         if (assemblyVersion >= attributeData.TreatAsErrorFromVersion)
         {
             return true;
         }
     }
     return false;
 }
        public override StatementSyntax EmitGuard(AttributeData attribute, TypeSymbol parameterType, string parameterName)
        {
            //TODO: Consider how to properly handle type conversions
            StatementSyntax guardStatement = Syntax.IfStatement(
                SimpleSyntaxWriter.InvokeStaticMethod(
                    ()=>string.IsNullOrWhiteSpace(Fake.String),
                    SimpleSyntaxWriter.ArgumentFromIdentifier(parameterName)),
                    Syntax.Block(
                        SimpleSyntaxWriter.GenerateThrowStatement(typeof(ArgumentException), parameterName, string.Format(@"""{0} cannot be null, empty or whitespace""", parameterName))));

            return guardStatement;
        }
        public override StatementSyntax EmitGuard(AttributeData attribute, TypeSymbol parameterType, string parameterName)
        {
            StatementSyntax guardStatement = Syntax.IfStatement(
                Syntax.BinaryExpression(
                    SyntaxKind.EqualsExpression,
                    Syntax.IdentifierName(parameterName),
                    Syntax.IdentifierName("null")),
                    Syntax.Block(
                        SimpleSyntaxWriter.GenerateThrowStatement(typeof(ArgumentNullException), parameterName)));

            return guardStatement;
        }
        public void AttributeData_Ctor()
        {
            AttributeData data;

            Console.WriteLine("Test with optional value and no default value.");
            data = new AttributeData("test", new XmlNameInfo("name"), true);
            Assert.IsNotNull(data.InheritanceList, "InheritanceList is not null.");
            Assert.AreEqual(0, data.InheritanceList.Count, "InheritanceList count is incorrect.");
            Assert.IsNull(data.ConverterTypeName, "ConverterTypeName is not null.");
            Assert.IsFalse(data.HasValue, "HasValue is incorrect.");
            Assert.IsFalse(data.InheritValue, "InheritValue is incorrect.");
            Assert.IsFalse(data.IsDefaultValue, "IsDefaultValue is incorrect.");
            Assert.IsTrue(data.IsOptional, "IsOptional is incorrect.");
            Assert.IsNull(data.Value, "Value is incorrect.");
            Assert.AreEqual("name", data.LocalName, "XmlName is incorrect.");

            Console.WriteLine("Test with required value and no default value.");
            data = new AttributeData("test", new XmlNameInfo("name"), false);
            Assert.IsNotNull(data.InheritanceList, "InheritanceList is not null.");
            Assert.AreEqual(0, data.InheritanceList.Count, "InheritanceList count is incorrect.");
            Assert.IsNull(data.ConverterTypeName, "ConverterTypeName is not null.");
            Assert.IsFalse(data.HasValue, "HasValue is incorrect.");
            Assert.IsFalse(data.InheritValue, "InheritValue is incorrect.");
            Assert.IsFalse(data.IsDefaultValue, "IsDefaultValue is incorrect.");
            Assert.IsFalse(data.IsOptional, "IsOptional is incorrect.");
            Assert.IsNull(data.Value, "Value is incorrect.");
            Assert.AreEqual("name", data.LocalName, "XmlName is incorrect.");

            Console.WriteLine("Test with optional value and default value.");
            data = new AttributeData("test", new XmlNameInfo("name"), true, 1);
            Assert.IsNotNull(data.InheritanceList, "InheritanceList is not null.");
            Assert.AreEqual(0, data.InheritanceList.Count, "InheritanceList count is incorrect.");
            Assert.IsNull(data.ConverterTypeName, "ConverterTypeName is not null.");
            Assert.IsFalse(data.HasValue, "HasValue is incorrect.");
            Assert.IsFalse(data.InheritValue, "InheritValue is incorrect.");
            Assert.IsTrue(data.IsDefaultValue, "IsDefaultValue is incorrect.");
            Assert.IsTrue(data.IsOptional, "IsOptional is incorrect.");
            Assert.AreEqual(1, data.Value, "Value is incorrect.");
            Assert.AreEqual("name", data.LocalName, "XmlName is incorrect.");

            Console.WriteLine("Test with required value and default value.");
            data = new AttributeData("test", new XmlNameInfo("name"), false, 1);
            Assert.IsNotNull(data.InheritanceList, "InheritanceList is not null.");
            Assert.AreEqual(0, data.InheritanceList.Count, "InheritanceList count is incorrect.");
            Assert.IsNull(data.ConverterTypeName, "ConverterTypeName is not null.");
            Assert.IsTrue(data.HasValue, "HasValue is incorrect.");
            Assert.IsFalse(data.InheritValue, "InheritValue is incorrect.");
            Assert.IsTrue(data.IsDefaultValue, "IsDefaultValue is incorrect.");
            Assert.IsFalse(data.IsOptional, "IsOptional is incorrect.");
            Assert.AreEqual(1, data.Value, "Value is incorrect.");
            Assert.AreEqual("name", data.LocalName, "XmlName is incorrect.");
        }
        public override StatementSyntax EmitGuard(AttributeData attribute, TypeSymbol parameterType, string parameterName)
        {
            //TODO: Modify to try cast to IList first, then try cast to IEnumerable
            StatementSyntax guardStatement = Syntax.IfStatement(
                Syntax.BinaryExpression(
                    SyntaxKind.LessThanOrEqualExpression,
                    SimpleSyntaxWriter.AccessMemberWithCast((IList x)=>x.Count, parameterName),
                            Syntax.IdentifierName("0")),
                    Syntax.Block(
                        SimpleSyntaxWriter.GenerateThrowStatement(typeof(ArgumentException), parameterName, string.Format(@"""{0} cannot be empty""", parameterName))));

            return guardStatement;
        }
 public void All()
 {
     var attributeData = new AttributeData
                             {
                                 Message = "Custom Message.",
                                 TreatAsErrorFromVersion = "2",
                                 RemoveInVersion = "4",
                                 Replacement = "NewMember"
                             };
     SemanticVersion assemblyVersion = "1";
     var dataFormatter = new ModuleWeaver {assemblyVersion = assemblyVersion};
     var message = dataFormatter.ConvertToMessage(attributeData);
     Assert.AreEqual("Custom Message. Use `NewMember` instead. Will be treated as an error from version 2.0.0. Will be removed in version 4.0.0.", message);
 }
 public void ForSample()
 {
     var attributeData = new AttributeData
                             {
                                 Message = "Custom Message.",
                                 TreatAsErrorFromVersion = "2",
                                 RemoveInVersion = "4",
                                 Replacement = "NewClass"
                             };
     var dataFormatter1 = new ModuleWeaver { assemblyVersion = "1"};
     Debug.WriteLine(dataFormatter1.ConvertToMessage(attributeData));
     var dataFormatter2 = new ModuleWeaver { assemblyVersion = "3"};
     Debug.WriteLine(dataFormatter2.ConvertToMessage(attributeData));
 }
Exemple #16
0
    void AddObsoleteAttribute(AttributeData attributeData, Collection<CustomAttribute> customAttributes)
    {
        var customAttribute = new CustomAttribute(ObsoleteConstructorReference);

        var message = ConvertToMessage(attributeData);
        var messageArgument = new CustomAttributeArgument(ModuleDefinition.TypeSystem.String, message);
        customAttribute.ConstructorArguments.Add(messageArgument);

        var isError = GetIsError(attributeData);
        var isErrorArgument = new CustomAttributeArgument(ModuleDefinition.TypeSystem.Boolean, isError);
        customAttribute.ConstructorArguments.Add(isErrorArgument);

        customAttributes.Add(customAttribute);
    }
        private RoslynAttributeMetadata(AttributeData a)
        {
            var declaration = a.ToString();
            var index = declaration.IndexOf("(", StringComparison.Ordinal);

            this.symbol = a.AttributeClass;
            this.name = symbol.Name;

            if (index > -1)
                this.value = declaration.Substring(index + 1, declaration.Length - index - 2);

            if (name.EndsWith("Attribute"))
                name = name.Substring(0, name.Length - 9);
        }
Exemple #18
0
        private static AttributeSyntax GenerateAttribute(AttributeData attribute, CodeGenerationOptions options)
        {
            if (!options.MergeAttributes)
            {
                var reusableSyntax = GetReuseableSyntaxNodeForAttribute<AttributeSyntax>(attribute, options);
                if (reusableSyntax != null)
                {
                    return reusableSyntax;
                }
            }

            var attributeArguments = GenerateAttributeArgumentList(attribute);
            var nameSyntax = attribute.AttributeClass.GenerateTypeSyntax() as NameSyntax;
            return nameSyntax == null ? null : SyntaxFactory.Attribute(nameSyntax, attributeArguments);
        }
        public override StatementSyntax EmitGuard(AttributeData attribute, TypeSymbol parameterType, string parameterName)
        {
            string comparisonValue = attribute.ConstructorArguments.First().Value.ToString();

            StatementSyntax guardStatement = Syntax.IfStatement(
                Syntax.BinaryExpression(
                    SyntaxKind.GreaterThanOrEqualExpression,
                    SimpleSyntaxWriter.InvokeMethodWithCast(
                        (IComparable x)=>x.CompareTo(Fake.Object),
                        parameterName,
                        SimpleSyntaxWriter.ArgumentFromLiteral(comparisonValue, false)),
                Syntax.IdentifierName("0")),
                Syntax.Block(
                    SimpleSyntaxWriter.GenerateThrowStatement(typeof(ArgumentException), parameterName, string.Format(@"""{0} is not less than '" + comparisonValue + @"'.""", parameterName))));

            return guardStatement;
        }
        public override StatementSyntax EmitGuard(AttributeData attribute, TypeSymbol parameterType, string parameterName)
        {
            //TODO: Consider how to properly handle type conversions
            StatementSyntax guardStatement = Syntax.IfStatement(
                Syntax.BinaryExpression(
                    SyntaxKind.EqualsExpression,
                    SimpleSyntaxWriter.InvokeStaticMethod(
                        () => Enum.IsDefined(Fake.Any<Type>(), Fake.Object),
                        SimpleSyntaxWriter.ArgumentFromTypeof(parameterType.Name),
                        SimpleSyntaxWriter.ArgumentFromLiteral(parameterName, false)
                    ),
                    Syntax.IdentifierName("false")),
                    Syntax.Block(
                        SimpleSyntaxWriter.GenerateThrowStatement(typeof(ArgumentException), parameterName, string.Format(@"""{0} value is not defined for the enum type.""", parameterName))));

            return guardStatement;
        }
Exemple #21
0
 void ApplyVersionConvention(AttributeData attributeData)
 {
     if (attributeData.TreatAsErrorFromVersion == null)
     {
         if (attributeData.RemoveInVersion == null)
         {
             attributeData.TreatAsErrorFromVersion = assemblyVersion.Increment(StepType);
         }
         else
         {
             attributeData.TreatAsErrorFromVersion = attributeData.RemoveInVersion.Decrement(StepType);
         }
     }
     if (attributeData.RemoveInVersion == null)
     {
         attributeData.RemoveInVersion = attributeData.TreatAsErrorFromVersion.Increment(StepType);
     }
 }
Exemple #22
0
        private static AttributeArgumentListSyntax GenerateAttributeArgumentList(AttributeData attribute)
        {
            if (attribute.ConstructorArguments.Length == 0 && attribute.NamedArguments.Length == 0)
            {
                return null;
            }

            var arguments = new List<AttributeArgumentSyntax>();
            arguments.AddRange(attribute.ConstructorArguments.Select(c =>
                SyntaxFactory.AttributeArgument(GenerateExpression(c))));

            arguments.AddRange(attribute.NamedArguments.Select(kvp =>
                SyntaxFactory.AttributeArgument(
                    SyntaxFactory.NameEquals(SyntaxFactory.IdentifierName(kvp.Key)), null,
                    GenerateExpression(kvp.Value))));

            return SyntaxFactory.AttributeArgumentList(SyntaxFactory.SeparatedList(arguments));
        }
        public override StatementSyntax EmitGuard(AttributeData attribute, TypeSymbol parameterType, string parameterName)
        {
            //TODO: Make defensive incase no argument supplied
            string regexMatchString = attribute.ConstructorArguments.First().Value.ToString();

            StatementSyntax guardStatement = Syntax.IfStatement(
                Syntax.BinaryExpression(
                    SyntaxKind.EqualsExpression,
                    SimpleSyntaxWriter.InvokeStaticMethod(
                    () => Regex.IsMatch(Fake.String, Fake.String),
                        SimpleSyntaxWriter.ArgumentFromIdentifier(parameterName),
                        SimpleSyntaxWriter.ArgumentFromLiteral(regexMatchString, true)
                    ),
                    Syntax.IdentifierName("false")),
                Syntax.Block(
                    SimpleSyntaxWriter.GenerateThrowStatement(typeof(ArgumentException), parameterName, string.Format(@"""{0} does not match the regular expression '" + regexMatchString + @"'.""", parameterName))));

            return guardStatement;
        }
Exemple #24
0
        /// <summary>
        /// Try to map one Attribute to Attribute specifications.
        /// </summary>
        /// <param name="attribute">The actual Attribute to map.</param>
        /// <param name="sortedAttributeListSpecification">The Attribute specifications to map to.</param>
        /// <returns>
        /// Indicates if the supplied actual Attribute and it's direct and indirect
        /// Attribute childs have been mapped.
        /// </returns>
        public static bool Map(Attribute attribute, SortedAttributeListSpecification sortedAttributeListSpecification)
        {
            bool attributesMapped = true;

            //
            // Determine which attribute specification instances have the same tag and level.
            //

            AttributeData attributeData = new AttributeData();

            attribute.Data = attributeData;

            attributeData.Mapping = sortedAttributeListSpecification.GetAttributes(attribute.Tag.GroupNumber, attribute.Tag.ElementNumber);

            if (attributeData.Mapping.Count == 0)
            {
                attributesMapped = false;
            }

            //
            // If this attribute is a Sequence Attribute, also map its children.
            //

            if (attribute is SequenceAttribute)
            {
                SequenceAttribute sequenceAttribute = attribute as SequenceAttribute;

                SortedAttributeListSpecification sequenceItemSpecification = GetSequenceItemSpecification(attributeData.Mapping);

                foreach (SequenceItem sequenceItem in sequenceAttribute.SequenceItems)
                {
                    bool sequenceItemMapped = Map(sequenceItem, sequenceItemSpecification);

                    attributesMapped = (attributesMapped && sequenceItemMapped);
                }
            }

            attributeData.AttributesMapped = attributesMapped;

            return (attributesMapped);
        }
        public void AttributeData_GetStringValue()
        {
            AttributeData data;

            data = new AttributeData("test", new XmlNameInfo("name"), true);

            Console.WriteLine("Test with null value.");
            Assert.IsNull(data.GetStringValue(), "Value is not null.");

            Console.WriteLine("Test with string value.");
            data.Value = "string";
            Assert.AreEqual("string", data.GetStringValue(), "Value is incorrect.");

            Console.WriteLine("Test with int value.");
            data.Value = 1;
            Assert.AreEqual("1", data.GetStringValue(), "Value is incorrect.");

            Console.WriteLine("Test with converter.");
            data.ConverterTypeName = typeof(HexConverter).FullName;
            data.Value = 10;
            Assert.AreEqual("000A", data.GetStringValue(), "Value is incorrect.");
        }
Exemple #26
0
 private static bool IsLocalizableAttribute(AttributeData attributeData)
 {
     return(attributeData.AttributeClass.Is(KnownType.System_ComponentModel_LocalizableAttribute) &&
            attributeData.ConstructorArguments.Any(c => (c.Value as bool?) ?? false));
 }
 public override void Serialize(AttributeData data)
 {
     data.WriteAttribute("UnitMmScale", _unitMmScale);
 }
Exemple #28
0
 /// <summary>기본 생성자</summary>
 public AZList()
 {
     list           = new List <AZData>();
     attribute_data = new AttributeData();
 }
Exemple #29
0
        public override void ReportInvalidAttributeArgument(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, AttributeData attribute)
        {
            var node = (AttributeSyntax)attributeSyntax;
            CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(parameterIndex, node);

            diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntax.Location, node.GetErrorDisplayName());
        }
 public static DeclaredApiResponseMetadata ForProducesDefaultResponse(AttributeData attributeData, IMethodSymbol attributeSource)
 {
     return(new DeclaredApiResponseMetadata(statusCode: 0, attributeData, attributeSource, @implicit: false, @default: true));
 }
            public void AnalyzeSymbol(SymbolAnalysisContext context)
            {
                var methodSymbol = (IMethodSymbol)context.Symbol;

                if (methodSymbol == null)
                {
                    return;
                }

                DllImportData dllImportData = methodSymbol.GetDllImportData();

                if (dllImportData == null)
                {
                    return;
                }

                AttributeData dllAttribute    = methodSymbol.GetAttributes().FirstOrDefault(attr => attr.AttributeClass.Equals(_dllImportType));
                Location      defaultLocation = dllAttribute == null?methodSymbol.Locations.FirstOrDefault() : GetAttributeLocation(dllAttribute);

                // CA1401 - PInvoke methods should not be visible
                if (methodSymbol.IsExternallyVisible())
                {
                    context.ReportDiagnostic(context.Symbol.CreateDiagnostic(RuleCA1401, methodSymbol.Name));
                }

                // CA2101 - Specify marshalling for PInvoke string arguments
                if (dllImportData.BestFitMapping != false)
                {
                    bool appliedCA2101ToMethod = false;
                    foreach (IParameterSymbol parameter in methodSymbol.Parameters)
                    {
                        if (parameter.Type.SpecialType == SpecialType.System_String || parameter.Type.Equals(_stringBuilderType))
                        {
                            AttributeData marshalAsAttribute = parameter.GetAttributes().FirstOrDefault(attr => attr.AttributeClass.Equals(_marshalAsType));
                            CharSet?      charSet            = marshalAsAttribute == null
                                ? dllImportData.CharacterSet
                                : MarshalingToCharSet(GetParameterMarshaling(marshalAsAttribute));

                            // only unicode marshaling is considered safe
                            if (charSet != CharSet.Unicode)
                            {
                                if (marshalAsAttribute != null)
                                {
                                    // track the diagnostic on the [MarshalAs] attribute
                                    Location marshalAsLocation = GetAttributeLocation(marshalAsAttribute);
                                    context.ReportDiagnostic(Diagnostic.Create(RuleCA2101, marshalAsLocation));
                                }
                                else if (!appliedCA2101ToMethod)
                                {
                                    // track the diagnostic on the [DllImport] attribute
                                    appliedCA2101ToMethod = true;
                                    context.ReportDiagnostic(Diagnostic.Create(RuleCA2101, defaultLocation));
                                }
                            }
                        }
                    }

                    // only unicode marshaling is considered safe, but only check this if we haven't already flagged the attribute
                    if (!appliedCA2101ToMethod && dllImportData.CharacterSet != CharSet.Unicode &&
                        (methodSymbol.ReturnType.SpecialType == SpecialType.System_String || methodSymbol.ReturnType.Equals(_stringBuilderType)))
                    {
                        context.ReportDiagnostic(Diagnostic.Create(RuleCA2101, defaultLocation));
                    }
                }
            }
Exemple #32
0
 public override void Deserialize(AttributeData data)
 {
 }
Exemple #33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OfferFriendlyOverloadsGenerator"/> class.
 /// </summary>
 /// <param name="data">Generator attribute data.</param>
 public OfferFriendlyOverloadsGenerator(AttributeData data)
 {
 }
Exemple #34
0
        private static void AnalyzeServerSideOperation(SymbolAnalysisContext context, ISymbol methodSymbol, string clientOperationName, AttributeData rpcServiceAttribute)
        {
            var serverDefinitionType = rpcServiceAttribute.NamedArguments.FirstOrDefault(pair => pair.Key == "ServerDefinitionType").Value;

            if (!serverDefinitionType.IsNull)
            {
                if (!string.IsNullOrEmpty(clientOperationName))
                {
                    if (serverDefinitionType.Value is ITypeSymbol serverTypeSymbol)
                    {
                        bool hasServerOperation = false;

                        foreach (var serverOp in EnumRpcOperations(serverTypeSymbol))
                        {
                            if (clientOperationName == serverOp.OperationName)
                            {
                                hasServerOperation = true;
                                break;
                            }
                        }

                        if (!hasServerOperation)
                        {
                            var mbrDiagnostic = Diagnostic.Create(RpcMissingServerOperationRule, methodSymbol.Locations[0], clientOperationName);
                            context.ReportDiagnostic(mbrDiagnostic);
                        }
                    }
                }
            }
        }
        private static void Analyze(Action <Diagnostic> reportDiagnostic, AttributeData attributeData)
        {
            var attributeConstructor = attributeData.AttributeConstructor;
            var constructorArguments = attributeData.ConstructorArguments;

            if (attributeConstructor == null || attributeConstructor.Parameters.Count() != constructorArguments.Count())
            {
                return;
            }

            var syntax = attributeData.ApplicationSyntaxReference.GetSyntax();

            for (int i = 0; i < attributeConstructor.Parameters.Count(); i++)
            {
                var parameter = attributeConstructor.Parameters[i];
                if (parameter.Type.SpecialType != SpecialType.System_String)
                {
                    continue;
                }

                // If the name of the parameter is not something which requires the value-passed
                // to the parameter to be validated then we don't have to do anything
                var valueValidator = GetValueValidator(parameter.Name);
                if (valueValidator != null && !valueValidator.IsIgnoredName(parameter.Name))
                {
                    if (constructorArguments[i].Value != null)
                    {
                        var    value = (string)constructorArguments[i].Value;
                        string classDisplayString = attributeData.AttributeClass.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat);
                        if (value.Equals(string.Empty, StringComparison.Ordinal))
                        {
                            reportDiagnostic(syntax.CreateDiagnostic(EmptyRule,
                                                                     classDisplayString,
                                                                     parameter.Name,
                                                                     valueValidator.TypeName));
                        }
                        else if (!valueValidator.IsValidValue(value))
                        {
                            reportDiagnostic(syntax.CreateDiagnostic(DefaultRule,
                                                                     classDisplayString,
                                                                     parameter.Name,
                                                                     value,
                                                                     valueValidator.TypeName));
                        }
                    }
                }
            }

            foreach (var namedArgument in attributeData.NamedArguments)
            {
                if (namedArgument.Value.IsNull ||
                    namedArgument.Value.Type.SpecialType != SpecialType.System_String)
                {
                    return;
                }

                var valueValidator = GetValueValidator(namedArgument.Key);
                if (valueValidator != null && !valueValidator.IsIgnoredName(namedArgument.Key))
                {
                    var    value = (string)(namedArgument.Value.Value);
                    string classDisplayString = attributeData.AttributeClass.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat);
                    if (value.Equals(string.Empty, StringComparison.Ordinal))
                    {
                        reportDiagnostic(syntax.CreateDiagnostic(EmptyRule,
                                                                 classDisplayString,
                                                                 $"{classDisplayString}.{namedArgument.Key}",
                                                                 valueValidator.TypeName));
                    }
                    else if (!valueValidator.IsValidValue(value))
                    {
                        reportDiagnostic(syntax.CreateDiagnostic(DefaultRule,
                                                                 classDisplayString,
                                                                 $"{classDisplayString}.{namedArgument.Key}",
                                                                 value,
                                                                 valueValidator.TypeName));
                    }
                }
            }
        }
 public override void ReportMarshalUnmanagedTypeOnlyValidForFields(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute)
 {
     throw new NotImplementedException();
 }
        private static bool TryDecodeSuppressMessageAttributeData(AttributeData attribute, out SuppressMessageInfo info)
        {
            info = default(SuppressMessageInfo);

            // We need at least the Category and Id to decode the diagnostic to suppress.
            // The only SuppressMessageAttribute constructor requires those two parameters.
            if (attribute.CommonConstructorArguments.Length < 2)
            {
                return false;
            }

            // Ignore the category parameter because it does not identify the diagnostic
            // and category information can be obtained from diagnostics themselves.
            info.Id = attribute.CommonConstructorArguments[1].Value as string;
            if (info.Id == null)
            {
                return false;
            }

            // Allow an optional human-readable descriptive name on the end of an Id.
            // See http://msdn.microsoft.com/en-us/library/ms244717.aspx
            var separatorIndex = info.Id.IndexOf(':');
            if (separatorIndex != -1)
            {
                info.Id = info.Id.Remove(separatorIndex);
            }

            info.Scope = attribute.DecodeNamedArgument<string>("Scope", SpecialType.System_String);
            info.Target = attribute.DecodeNamedArgument<string>("Target", SpecialType.System_String);
            info.MessageId = attribute.DecodeNamedArgument<string>("MessageId", SpecialType.System_String);

            return true;
        }
Exemple #38
0
 /// <summary>
 /// Removes the specified attribute node from the given declaration node.
 /// </summary>
 public static TDeclarationNode RemoveAttribute <TDeclarationNode>(TDeclarationNode destination, Workspace workspace, AttributeData attributeToRemove, CodeGenerationOptions options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode
 {
     return(GetCodeGenerationService(workspace, destination.Language).RemoveAttribute(destination, attributeToRemove, options ?? CodeGenerationOptions.Default, cancellationToken));
 }
Exemple #39
0
 [DllImport("usdi")] public static extern bool          usdiAttrWriteSample(Attribute attr, ref AttributeData src, double t);
Exemple #40
0
 [DllImport("usdi")] public static extern bool          usdiAttrReadSample(Attribute attr, ref AttributeData dst, double t, Bool copy);
 public override bool IsMatch(AttributeData value)
 {
     return(!AttributeNames.Contains(value.AttributeClass));
 }
 public override void Deserialize(AttributeData data)
 {
     UnitMmScale = data.ReadAttributeDouble("UnitMmScale");
 }
Exemple #43
0
        private static void AnalyzeServerSideMethod(SymbolAnalysisContext context, IMethodSymbol methodSymbol, AttributeData rpcServiceAttribute)
        {
            if (methodSymbol.AssociatedSymbol != null)
            {
                return;
            }

            string clientOperationName = GetOperationNameFromMemberSymbol(methodSymbol);

            AnalyzeServerSideOperation(context, methodSymbol, clientOperationName, rpcServiceAttribute);
        }
 public static DeclaredApiResponseMetadata ForProducesResponseType(int statusCode, AttributeData attributeData, IMethodSymbol attributeSource)
 {
     return(new DeclaredApiResponseMetadata(statusCode, attributeData, attributeSource, @implicit: false, @default: false));
 }
Exemple #45
0
        private void ConfigureDictionaryBoundAttribute(
            BoundAttributeDescriptorBuilder builder,
            IPropertySymbol property,
            INamedTypeSymbol containingType,
            AttributeData attributeNameAttribute,
            string attributeName,
            bool hasPublicSetter)
        {
            string dictionaryAttributePrefix    = null;
            var    dictionaryAttributePrefixSet = false;

            if (attributeNameAttribute != null)
            {
                foreach (var argument in attributeNameAttribute.NamedArguments)
                {
                    if (argument.Key == TagHelperTypes.HtmlAttributeName.DictionaryAttributePrefix)
                    {
                        dictionaryAttributePrefix    = (string)argument.Value.Value;
                        dictionaryAttributePrefixSet = true;
                        break;
                    }
                }
            }

            var dictionaryArgumentTypes = GetDictionaryArgumentTypes(property);

            if (dictionaryArgumentTypes != null)
            {
                var prefix = dictionaryAttributePrefix;
                if (attributeNameAttribute == null || !dictionaryAttributePrefixSet)
                {
                    prefix = attributeName + "-";
                }

                if (prefix != null)
                {
                    var dictionaryValueType     = dictionaryArgumentTypes[1];
                    var dictionaryValueTypeName = GetFullName(dictionaryValueType);
                    builder.AsDictionary(prefix, dictionaryValueTypeName);
                }
            }

            var dictionaryKeyType = dictionaryArgumentTypes?[0];

            if (dictionaryKeyType?.SpecialType != SpecialType.System_String)
            {
                if (dictionaryAttributePrefix != null)
                {
                    // DictionaryAttributePrefix is not supported unless associated with an
                    // IDictionary<string, TValue> property.
                    var diagnostic = RazorDiagnosticFactory.CreateTagHelper_InvalidAttributePrefixNotNull(GetFullName(containingType), property.Name);
                    builder.Diagnostics.Add(diagnostic);
                }

                return;
            }
            else if (!hasPublicSetter && attributeNameAttribute != null && !dictionaryAttributePrefixSet)
            {
                // Must set DictionaryAttributePrefix when using HtmlAttributeNameAttribute with a dictionary property
                // that lacks a public setter.
                var diagnostic = RazorDiagnosticFactory.CreateTagHelper_InvalidAttributePrefixNull(GetFullName(containingType), property.Name);
                builder.Diagnostics.Add(diagnostic);

                return;
            }
        }
Exemple #46
0
        public override void ReportMarshalUnmanagedTypeOnlyValidForFields(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute)
        {
            var node = (AttributeSyntax)attributeSyntax;
            CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(parameterIndex, node);

            diagnostics.Add(ErrorCode.ERR_MarshalUnmanagedTypeOnlyValidForFields, attributeArgumentSyntax.Location, unmanagedTypeName);
        }
Exemple #47
0
 public abstract TDeclarationNode RemoveAttribute <TDeclarationNode>(
     TDeclarationNode destination,
     AttributeData attributeToRemove,
     CodeGenerationOptions?options,
     CancellationToken cancellationToken
     ) where TDeclarationNode : SyntaxNode;
 public override bool IsApplicable(AttributeData value)
 {
     return(true);
 }
 public MultiplySuffixGenerator(AttributeData attributeData)
 {
     Requires.NotNull(attributeData, nameof(attributeData));
 }
 private static Location GetAttributeLocation(AttributeData attributeData)
 {
     return(attributeData.ApplicationSyntaxReference.SyntaxTree.GetLocation(attributeData.ApplicationSyntaxReference.Span));
 }
Exemple #51
0
 private void VerifyParameterManage_EventVerifyParameter(PropertyInfo propertity, object value, AttributeData attributeBaseData, List <AttributeData> attributeDataList)
 {
     attributeDataList.Add(new AttributeData()
     {
         AttributeCode = "Name",
         AttributeName = "书名",
         ErrorList     = new List <string>()
         {
             "测试1"
         }
     });
 }
Exemple #52
0
        private static string?GetFirstConstructorArgumentValueOfAttribute(AttributeData data)
        {
            var constructorArgument = data.ConstructorArguments.First();

            return((string?)constructorArgument.Value);
        }
Exemple #53
0
 [DllImport("usdi")] public static extern IntPtr usdiTaskCreateAttrReadSample(Attribute points, ref AttributeData dst, ref double t);
 /// <inheritdoc />
 public CpSatParametersAssemblyCodeGenerator(AttributeData attributeData)
     : base(attributeData)
 {
 }
Exemple #55
0
 public abstract void ReportMarshalUnmanagedTypeOnlyValidForFields(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute);
Exemple #56
0
        private static Location GetAttributeLocation(ref SymbolAnalysisContext symbolAnalysisContext, AttributeData attribute)
        {
            var syntax = attribute.ApplicationSyntaxReference.GetSyntax(symbolAnalysisContext.CancellationToken);

            return(syntax?.GetLocation() ?? Location.None);
        }
 public override void ReportInvalidAttributeArgument(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, AttributeData attribute)
 {
     throw new NotImplementedException();
 }
        public virtual async Task <IList <DtoController> > GetProjectDtoControllersWithTheirOperations(Project project, IList <Project> allSourceProjects = null)
        {
            if (project == null)
            {
                throw new ArgumentNullException(nameof(project));
            }

            IList <DtoController> dtoControllers = new List <DtoController>();

            foreach (Document doc in project.Documents)
            {
                if (!doc.SupportsSemanticModel)
                {
                    continue;
                }

                SemanticModel semanticModel = await doc.GetSemanticModelAsync();

                SyntaxNode root = await doc.GetSyntaxRootAsync();

                List <ClassDeclarationSyntax> dtoControllersClassDecs = new List <ClassDeclarationSyntax>();

                foreach (ClassDeclarationSyntax classDeclarationSyntax in root.DescendantNodes()
                         .OfType <ClassDeclarationSyntax>())
                {
                    if (classDeclarationSyntax.BaseList == null)
                    {
                        continue;
                    }

                    INamedTypeSymbol controllerSymbol = (INamedTypeSymbol)semanticModel.GetDeclaredSymbol(classDeclarationSyntax);

                    bool isController = controllerSymbol.IsDtoController();

                    if (isController == true)
                    {
                        dtoControllersClassDecs.Add(classDeclarationSyntax);
                    }
                }

                if (!dtoControllersClassDecs.Any())
                {
                    continue;
                }

                foreach (ClassDeclarationSyntax dtoControllerClassDec in dtoControllersClassDecs)
                {
                    INamedTypeSymbol controllerSymbol = (INamedTypeSymbol)semanticModel.GetDeclaredSymbol(dtoControllerClassDec);

                    DtoController dtoController = new DtoController
                    {
                        ControllerSymbol = controllerSymbol,
                        Name             = controllerSymbol.Name.Replace("Controller", string.Empty),
                        Operations       = new List <ODataOperation>(),
                        ModelSymbol      = controllerSymbol.BaseType.TypeArguments.ExtendedSingleOrDefault($"Looking for model of ${controllerSymbol.Name}", t => t.IsDto())
                    };

                    if (dtoController.ModelSymbol is ITypeParameterSymbol)
                    {
                        dtoController.ModelSymbol = ((ITypeParameterSymbol)dtoController.ModelSymbol).ConstraintTypes.ExtendedSingleOrDefault($"Looking for model on generic model {dtoController.ModelSymbol.Name}", t => t.IsDto());
                    }

                    if (dtoController.ModelSymbol == null)
                    {
                        continue;
                    }

                    dtoControllers.Add(dtoController);

                    if (dtoController.ControllerSymbol.IsGenericType)
                    {
                        continue;
                    }

                    foreach (MethodDeclarationSyntax methodDecSyntax in dtoControllerClassDec.DescendantNodes().OfType <MethodDeclarationSyntax>())
                    {
                        IMethodSymbol methodSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(methodDecSyntax);

                        ImmutableArray <AttributeData> attrs = methodSymbol.GetAttributes();

                        AttributeData actionAttribute = attrs.ExtendedSingleOrDefault($"Looking for action attribute on {methodSymbol.Name}", att => att.AttributeClass.Name == "ActionAttribute");

                        AttributeData functionAttribute = attrs.ExtendedSingleOrDefault($"Looking for function attribute on {methodSymbol.Name}", att => att.AttributeClass.Name == "FunctionAttribute");

                        if (actionAttribute == null && functionAttribute == null)
                        {
                            continue;
                        }

                        ODataOperation operation = new ODataOperation
                        {
                            Method     = methodSymbol,
                            Kind       = actionAttribute != null ? ODataOperationKind.Action : ODataOperationKind.Function,
                            ReturnType = methodSymbol.ReturnType
                        };

                        if (operation.Kind == ODataOperationKind.Function)
                        {
                            operation.Parameters = operation.Method.Parameters
                                                   .Where(p => p.Type.Name != "CancellationToken" && p.Type.Name != "ODataQueryOptions")
                                                   .Select(parameter => new ODataOperationParameter
                            {
                                Name = parameter.Name,
                                Type = parameter.Type
                            }).ToList();
                        }
                        else if (operation.Kind == ODataOperationKind.Action && operation.Method.Parameters.Any())
                        {
                            IParameterSymbol actionParameterContainer = operation.Method.Parameters
                                                                        .Where(p => p.Type.Name != "CancellationToken" && p.Type.Name != "ODataQueryOptions")
                                                                        .ExtendedSingleOrDefault($"Finding parameter of {operation.Method.ContainingType.Name}.{operation.Method.Name}. It's expected to see 0 or 1 parameter only.");

                            if (actionParameterContainer != null)
                            {
                                if (actionParameterContainer.Type.IsDto() || actionParameterContainer.Type.IsComplexType() || actionParameterContainer.Type.IsCollectionType())
                                {
                                    operation.Parameters = new List <ODataOperationParameter>
                                    {
                                        new ODataOperationParameter
                                        {
                                            Name = actionParameterContainer.Name,
                                            Type = actionParameterContainer.Type
                                        }
                                    };
                                }
                                // ToDo: else if (parameter is string or primitive or enum or date time or date time offset) { throw an exception; }
                                else
                                {
                                    operation.Parameters = actionParameterContainer.Type.GetMembers()
                                                           .OfType <IPropertySymbol>()
                                                           .Select(prop => new ODataOperationParameter
                                    {
                                        Name = prop.Name,
                                        Type = prop.Type
                                    }).ToList();
                                }
                            }
                        }

                        dtoController.Operations.Add(operation);
                    }
                }
            }

            return(dtoControllers);
        }
Exemple #59
0
 private static AttributeSyntax GetAttributeSyntax(AttributeData attr)
 {
     var attrTypeName = NameVisitorCreator.GetCSharp(NameOptions.None).GetName(attr.AttributeClass);
     if (attrTypeName.EndsWith(nameof(Attribute)))
     {
         attrTypeName = attrTypeName.Remove(attrTypeName.Length - nameof(Attribute).Length);
     }
     if (attr.ConstructorArguments.Length == 0 && attr.NamedArguments.Length == 0)
     {
         return SyntaxFactory.Attribute(SyntaxFactory.ParseName(attrTypeName));
     }
     return SyntaxFactory.Attribute(
         SyntaxFactory.ParseName(attrTypeName),
         SyntaxFactory.AttributeArgumentList(
             SyntaxFactory.SeparatedList(
                 (from item in attr.ConstructorArguments
                  select GetLiteralExpression(item) into expr
                  where expr != null
                  select SyntaxFactory.AttributeArgument(expr)
                 ).Concat(
                     from item in attr.NamedArguments
                     let expr = GetLiteralExpression(item.Value)
                     where expr != null
                     select SyntaxFactory.AttributeArgument(
                         SyntaxFactory.NameEquals(
                             SyntaxFactory.IdentifierName(item.Key)
                         ),
                         null,
                         expr
                     )
                 )
             )
         )
     );
 }
Exemple #60
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AttributeSemantics"/> class.
 /// </summary>
 /// <param name="semanticObject">The Roslyn semantic object.</param>
 public AttributeSemantics(AttributeData semanticObject)
     : base(semanticObject)
 {
 }