Example #1
0
        public static string RetrieveAccessModifier(Accessibility declaredAccessibility)
        {
            var accessModifier = declaredAccessibility.ToString().ToLowerInvariant();

            if (declaredAccessibility == Accessibility.ProtectedAndInternal ||
                declaredAccessibility == Accessibility.ProtectedOrInternal)
            {
                accessModifier = "protected internal";
            }

            return accessModifier;
        }
Example #2
0
        public static string GetAccessibilityName(Accessibility accessibility)
        {
            switch (accessibility)
            {
            case Accessibility.Private:
                return("private");

            case Accessibility.Protected:
                return("protected");

            case Accessibility.Internal:
                return("internal");

            case Accessibility.ProtectedOrInternal:
                return("protected internal");

            case Accessibility.Public:
                return("public");
            }

            Debug.Fail(accessibility.ToString());

            return("");
        }
Example #3
0
        protected string AccessibilityToString(Accessibility ac)
        {
            switch (ac)
            {
            case Accessibility.Public:
                return("public");

            case Accessibility.Assembly:
                return("internal");

            case Accessibility.FamilyOrAssembly:
                return("protected internal");

            case Accessibility.Family:
                return("protected");

            case Accessibility.FamilyAndAssembly:
                return("protected");                            // TODO:

            case Accessibility.Private:
                return("private");
            }
            throw new Exception("Invalid accessibility: " + ac.ToString());
        }
 /// <summary>
 /// Gets the string/token representation of an accessibility specifier.
 /// </summary>
 /// <remarks>Implicit accessibility being unspecified, yields an empty string.</remarks>
 public static string TokenString(this Accessibility access)
 {
     return(access == Accessibility.Implicit ? string.Empty : access.ToString());
 }
Example #5
0
        public static Accessibilities GetValidAccessibilities(MemberDeclarationListSelection selectedMembers, bool allowOverride = false)
        {
            if (selectedMembers.Count < 2)
            {
                return(Accessibilities.None);
            }

            var all = Accessibilities.None;

            Accessibilities valid = Accessibilities.Public
                                    | Accessibilities.Internal
                                    | Accessibilities.Protected
                                    | Accessibilities.Private;

            foreach (MemberDeclarationSyntax member in selectedMembers)
            {
                Accessibility accessibility = SyntaxAccessibility.GetExplicitAccessibility(member);

                if (accessibility == Accessibility.NotApplicable)
                {
                    accessibility = SyntaxAccessibility.GetDefaultExplicitAccessibility(member);

                    if (accessibility == Accessibility.NotApplicable)
                    {
                        return(Accessibilities.None);
                    }
                }

                Accessibilities accessibilities = accessibility.GetAccessibilities();

                switch (accessibility)
                {
                case Accessibility.Private:
                case Accessibility.Protected:
                case Accessibility.ProtectedAndInternal:
                case Accessibility.ProtectedOrInternal:
                case Accessibility.Internal:
                case Accessibility.Public:
                {
                    all |= accessibilities;
                    break;
                }

                default:
                {
                    Debug.Fail(accessibility.ToString());
                    return(Accessibilities.None);
                }
                }

                foreach (Accessibility accessibility2 in AvailableAccessibilities)
                {
                    if (accessibility != accessibility2 &&
                        !SyntaxAccessibility.IsValidAccessibility(member, accessibility2, ignoreOverride: allowOverride))
                    {
                        valid &= ~accessibility2.GetAccessibilities();
                    }
                }
            }

            switch (all)
            {
            case Accessibilities.Private:
            case Accessibilities.Protected:
            case Accessibilities.Internal:
            case Accessibilities.Public:
            {
                valid &= ~all;
                break;
            }
            }

            return(valid);
        }
Example #6
0
        public static void Analyze(SyntaxNodeAnalysisContext context, MemberDeclarationSyntax declaration)
        {
            SyntaxTokenList modifiers = declaration.GetModifiers();

            Accessibility accessibility = GetAccessModifier(context, declaration, modifiers);

            if (accessibility != Accessibility.NotApplicable)
            {
                Location location = GetLocation(declaration);

                if (location != null)
                {
                    context.ReportDiagnostic(
                        DiagnosticDescriptors.AddDefaultAccessModifier,
                        location,
                        ImmutableDictionary.CreateRange(new KeyValuePair <string, string>[] { new KeyValuePair <string, string>(nameof(Accessibility), accessibility.ToString()) }));
                }
            }
        }
 private string GetAccessibilityName(Accessibility declaredAccessibility)
 {
     return(declaredAccessibility.ToString());
 }
        private static void Analyze(SyntaxNodeAnalysisContext context, MemberDeclarationSyntax declaration, SyntaxTokenList modifiers)
        {
            Accessibility accessibility = GetAccessibility(context, declaration, modifiers);

            if (accessibility == Accessibility.NotApplicable)
            {
                return;
            }

            Location location = GetLocation(declaration);

            if (location == null)
            {
                return;
            }

            DiagnosticHelpers.ReportDiagnostic(context,
                                               DiagnosticDescriptors.AddAccessibilityModifiers,
                                               location,
                                               ImmutableDictionary.CreateRange(new KeyValuePair <string, string>[] { new KeyValuePair <string, string>(nameof(Accessibility), accessibility.ToString()) }));
        }
 public CodeBlockBuilder AddBlock(Accessibility accessibility, string blockname, Action <CodeBlockBuilder> builder)
 {
     AddBlock($"{accessibility.ToString().ToLower()} {blockname}", builder);
     return(this);
 }
        public static VisibilityModifierBase ToVisibilityModifierBase(this Accessibility accessibility, LoggerProvider logprovider)
        {
            switch (accessibility)
            {
            case Microsoft.CodeAnalysis.Accessibility.Private:
                return(VisibilityModifierBase.Private);

            case Microsoft.CodeAnalysis.Accessibility.Protected:
                return(VisibilityModifierBase.Protected);

            case Microsoft.CodeAnalysis.Accessibility.Internal:
                return(VisibilityModifierBase.Internal);

            case Microsoft.CodeAnalysis.Accessibility.Public:
                return(VisibilityModifierBase.Public);

            default:
                logprovider.WriteToLog(string.Format("Could not convert visiblity {0}", accessibility.ToString()));
                return(VisibilityModifierBase.Default);
            }
        }
        public static AccessibilityFlags GetAllowedAccessibilityFlags(MemberDeclarationSelection selectedMembers, bool allowOverride = false)
        {
            if (selectedMembers.Count < 2)
            {
                return(AccessibilityFlags.None);
            }

            var allFlags = AccessibilityFlags.None;

            AccessibilityFlags allowedFlags = AccessibilityFlags.Public
                                              | AccessibilityFlags.Internal
                                              | AccessibilityFlags.Protected
                                              | AccessibilityFlags.Private;

            foreach (MemberDeclarationSyntax member in selectedMembers)
            {
                Accessibility accessibility = SyntaxInfo.AccessibilityInfo(member).Accessibility;

                if (accessibility == Accessibility.NotApplicable)
                {
                    accessibility = member.GetDefaultExplicitAccessibility();

                    if (accessibility == Accessibility.NotApplicable)
                    {
                        return(AccessibilityFlags.None);
                    }
                }

                AccessibilityFlags flag = accessibility.GetAccessibilityFlag();

                switch (accessibility)
                {
                case Accessibility.Private:
                case Accessibility.Protected:
                case Accessibility.ProtectedAndInternal:
                case Accessibility.ProtectedOrInternal:
                case Accessibility.Internal:
                case Accessibility.Public:
                {
                    allFlags |= flag;
                    break;
                }

                default:
                {
                    Debug.Fail(accessibility.ToString());
                    return(AccessibilityFlags.None);
                }
                }

                foreach (Accessibility accessibility2 in Accessibilities)
                {
                    if (accessibility != accessibility2 &&
                        !CSharpUtility.IsAllowedAccessibility(member, accessibility2, allowOverride: allowOverride))
                    {
                        allowedFlags &= ~accessibility2.GetAccessibilityFlag();
                    }
                }
            }

            switch (allFlags)
            {
            case AccessibilityFlags.Private:
            case AccessibilityFlags.Protected:
            case AccessibilityFlags.Internal:
            case AccessibilityFlags.Public:
            {
                allowedFlags &= ~allFlags;
                break;
            }
            }

            return(allowedFlags);
        }
 // Only works for private/protected/friend/internal/public for now
 public static string Format(this Accessibility accessibility) => accessibility.ToString().ToLower();
Example #13
0
            internal void ThrowsDescriptiveExceptionWhenAccessibilitiesCannotBeCombined(Accessibility first, Accessibility second)
            {
                var thrown = Assert.Throws <InvalidOperationException>(() => new AccessibleMembers(new AccessibleMembers(source, first), second));

                Assert.StartsWith($"'{first.ToString().ToLower()} {second.ToString().ToLower()}' is not a valid accessibility.", thrown.Message);
            }
Example #14
0
 internal static string ToString(Accessibility access)
 {
     return(access.ToString());
 }
Example #15
0
        private void ApppendSource(GeneratorExecutionContext context, StringBuilder sourceBuilder, GenerationDetails generateThis)
        {
            string propertyName  = generateThis.MethodNameNode.Identifier.ValueText;
            string dpMemberName  = propertyName + "Property";
            string dpkMemberName = propertyName + "PropertyKey";

            Accessibility dpAccess  = generateThis.FieldSymbol.DeclaredAccessibility;
            Accessibility dpkAccess = generateThis.FieldSymbol.DeclaredAccessibility;

            // If this is a DependencyPropertyKey, then we may need to create the corresponding DependencyProperty field.
            // We do this because it's proper to always have a DependencyProperty field & because the DependencyProperty
            // field is required when using TemplateBindings in XAML.
            if (generateThis.IsDpk)
            {
                ISymbol?dpMemberSymbol = generateThis.FieldSymbol.ContainingType.GetMembers(dpMemberName).FirstOrDefault();
                if (dpMemberSymbol != null)
                {
                    dpAccess = dpMemberSymbol.DeclaredAccessibility;
                }
                else
                {
                    dpAccess = Accessibility.Public;

                    // Something like...
                    //	public static readonly DependencyProperty FooProperty = FooPropertyKey.DependencyProperty;
                    sourceBuilder.Append($@"
		public static readonly DependencyProperty {dpMemberName} = {dpkMemberName}.DependencyProperty;"        );
                }
            }

            // Try to get the generic type argument (if it exists, this will be the type of the property).
            GeneratorOps.TryGetGenericTypeArgument(context, generateThis.MethodNameNode, out ITypeSymbol? genTypeArg);

            // We support 0, 1, or 2 arguments. Check for default value and/or flags arguments.
            //	(A) Gen.Foo<T>()
            //	(B) Gen.Foo(defaultValue)
            //	(C) Gen.Foo<T>(flags)
            //	(D) Gen.Foo(defaultValue, flags)
            // The first argument is either the default value or the flags.
            // Note: We do not support properties whose default value is `FrameworkPropertyMetadataOptions` because
            // it's a niche case that would add code complexity.
            ArgumentSyntax?defaultValueArgNode = null;
            ITypeSymbol?   typeOfFirstArg      = null;
            bool           hasFlags            = false;

            if (GeneratorOps.TryGetAncestor(generateThis.MethodNameNode, out InvocationExpressionSyntax? invocationExpressionNode))
            {
                var args = invocationExpressionNode.ArgumentList.Arguments;
                if (args.Count > 0)
                {
                    // If the first argument is the flags, then we generate (C); otherwise, we generate (B) or (D).
                    typeOfFirstArg = GetArgumentType(context, args[0]) ?? this.objTypeSymbol;
                    if (typeOfFirstArg.Equals(this.flagsTypeSymbol, SymbolEqualityComparer.Default))
                    {
                        hasFlags = true;
                    }
                    else
                    {
                        defaultValueArgNode = args[0];
                        hasFlags            = args.Count > 1;
                    }
                }
            }

            bool hasDefaultValue = defaultValueArgNode != null;

            // Determine the type of the property.
            // If there is a generic type argument, then use that; otherwise, use the type of the default value argument.
            // As a safety precaution - ensure that the generated code is always valid by defaulting to use `object`.
            // But really, if we were unable to get the type, that means the user's code doesn't compile anyhow.
            generateThis.PropertyType =
                genTypeArg
                ?? (hasDefaultValue ? typeOfFirstArg : null)
                ?? this.objTypeSymbol;

            generateThis.PropertyTypeName = generateThis.PropertyType.ToDisplayString();

            string genClassDecl;
            string?moreDox = null;

            if (generateThis.IsAttached)
            {
                string targetTypeName = "DependencyObject";

                if (generateThis.MethodNameNode.Parent is MemberAccessExpressionSyntax memberAccessExpr &&
                    memberAccessExpr.Expression is GenericNameSyntax genClassNameNode)
                {
                    genClassDecl = "GenAttached<__TTarget> where __TTarget : DependencyObject";

                    if (GeneratorOps.TryGetGenericTypeArgument(context, genClassNameNode, out ITypeSymbol? attachmentNarrowingType))
                    {
                        generateThis.AttachmentNarrowingType = attachmentNarrowingType;
                        targetTypeName = attachmentNarrowingType.ToDisplayString();
                        moreDox        = $@"<br/>This attached property is only for use with objects of type <typeparamref name=""__TTarget""/>.";
                    }
                }
                else
                {
                    genClassDecl = "GenAttached";
                }

                // Write the static get/set methods source code.
                string getterAccess = dpAccess.ToString().ToLower();
                string setterAccess = generateThis.IsDpk ? dpkAccess.ToString().ToLower() : getterAccess;
                string setterArg0   = generateThis.IsDpk ? dpkMemberName : dpMemberName;

                // Something like...
                //	public static int GetFoo(DependencyObject d) => (int)d.GetValue(FooProperty);
                //	private static void SetFoo(DependencyObject d, int value) => d.SetValue(FooPropertyKey);
                sourceBuilder.Append($@"
		{getterAccess} static {generateThis.PropertyTypeName} Get{propertyName}({targetTypeName} d) => ({generateThis.PropertyTypeName})d.GetValue({dpMemberName});
		{setterAccess} static void Set{propertyName}({targetTypeName} d, {generateThis.PropertyTypeName} value) => d.SetValue({setterArg0}, value);"        );
            }
        public static AccessibilityFilter GetValidAccessibilityFilter(
            MemberDeclarationListSelection selectedMembers,
            SemanticModel semanticModel,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (selectedMembers.Count < 2)
            {
                return(AccessibilityFilter.None);
            }

            ImmutableArray <Accessibility> avaiableAccessibilities = AvailableAccessibilities;

            var all = AccessibilityFilter.None;

            AccessibilityFilter valid = AccessibilityFilter.Public
                                        | AccessibilityFilter.Internal
                                        | AccessibilityFilter.Protected
                                        | AccessibilityFilter.Private;

            foreach (MemberDeclarationSyntax member in selectedMembers)
            {
                Accessibility accessibility = SyntaxAccessibility.GetExplicitAccessibility(member);

                if (accessibility == Accessibility.NotApplicable)
                {
                    accessibility = SyntaxAccessibility.GetDefaultExplicitAccessibility(member);

                    if (accessibility == Accessibility.NotApplicable)
                    {
                        return(AccessibilityFilter.None);
                    }
                }

                switch (accessibility)
                {
                case Accessibility.Private:
                case Accessibility.Protected:
                case Accessibility.ProtectedAndInternal:
                case Accessibility.ProtectedOrInternal:
                case Accessibility.Internal:
                case Accessibility.Public:
                {
                    all |= accessibility.GetAccessibilityFilter();
                    break;
                }

                default:
                {
                    Debug.Fail(accessibility.ToString());
                    return(AccessibilityFilter.None);
                }
                }

                ModifierListInfo modifiersInfo = SyntaxInfo.ModifierListInfo(member);

                if (modifiersInfo.Modifiers.ContainsAny(
                        SyntaxKind.AbstractKeyword,
                        SyntaxKind.VirtualKeyword,
                        SyntaxKind.OverrideKeyword))
                {
                    valid &= ~AccessibilityFilter.Private;
                }

                if (modifiersInfo.IsOverride &&
                    IsBaseDeclarationWithoutSource(member, semanticModel, cancellationToken))
                {
                    switch (accessibility)
                    {
                    case Accessibility.Private:
                    case Accessibility.Protected:
                    case Accessibility.Internal:
                    case Accessibility.Public:
                    {
                        valid &= accessibility.GetAccessibilityFilter();

                        if (valid == AccessibilityFilter.None)
                        {
                            return(AccessibilityFilter.None);
                        }

                        avaiableAccessibilities = _accessibilityArrayMap[accessibility];
                        continue;
                    }

                    default:
                    {
                        return(AccessibilityFilter.None);
                    }
                    }
                }

                foreach (Accessibility accessibility2 in avaiableAccessibilities)
                {
                    if (accessibility != accessibility2 &&
                        !SyntaxAccessibility.IsValidAccessibility(member, accessibility2, ignoreOverride: true))
                    {
                        valid &= ~accessibility2.GetAccessibilityFilter();

                        if (valid == AccessibilityFilter.None)
                        {
                            return(AccessibilityFilter.None);
                        }
                    }
                }
            }

            switch (all)
            {
            case AccessibilityFilter.Private:
            case AccessibilityFilter.Protected:
            case AccessibilityFilter.Internal:
            case AccessibilityFilter.Public:
            {
                valid &= ~all;
                break;
            }
            }

            return(valid);
        }
Example #17
0
 public CodeNodeBuilder AddNode(Accessibility accessibility, string nodename, Action <CodeNodeBuilder> builder)
 {
     AddNode($"{accessibility.ToString().ToLower()} {nodename}", builder);
     return(this);
 }