示例#1
0
        private bool TryBuildPropertyBlockFromTarget <T>(T prototype, DeclarationType letSetGetType, string propertyIdentifier, out string codeBlock, string accessibility = null, string content = null, string parameterIdentifier = null) where T : Declaration
        {
            codeBlock = string.Empty;
            if (!letSetGetType.HasFlag(DeclarationType.Property))
            {
                throw new ArgumentException();
            }

            if (!(prototype is VariableDeclaration || prototype.DeclarationType.HasFlag(DeclarationType.UserDefinedTypeMember)))
            {
                return(false);
            }

            var propertyValueParam = parameterIdentifier ?? Resources.Refactorings.Refactorings.CodeBuilder_DefaultPropertyRHSParam;

            var asType = prototype.IsArray
                ? $"{Tokens.Variant}"
                : IsEnumField(prototype) && prototype.AsTypeDeclaration.Accessibility.Equals(Accessibility.Private)
                        ? $"{Tokens.Long}"
                        : $"{prototype.AsTypeName}";

            var asTypeClause = $"{Tokens.As} {asType}";

            var paramMechanism = IsUserDefinedType(prototype) ? Tokens.ByRef : Tokens.ByVal;

            var letSetParamExpression = $"{paramMechanism} {propertyValueParam} {asTypeClause}";

            codeBlock = letSetGetType.HasFlag(DeclarationType.PropertyGet)
                ? string.Join(Environment.NewLine, $"{accessibility ?? Tokens.Public} {ProcedureTypeStatement(letSetGetType)} {propertyIdentifier}() {asTypeClause}", content, ProcedureEndStatement(letSetGetType))
                : string.Join(Environment.NewLine, $"{accessibility ?? Tokens.Public} {ProcedureTypeStatement(letSetGetType)} {propertyIdentifier}({letSetParamExpression})", content, ProcedureEndStatement(letSetGetType));
            return(true);
        }
示例#2
0
        private BindingFlags GetBindingFlags()
        {
            // can't get more specific than public or not public so access level is filtered manually

            BindingFlags binding = BindingFlags.Public | BindingFlags.NonPublic;

            if (IncludedDeclarations.HasFlag(DeclarationType.Static))
            {
                binding |= BindingFlags.Static;
            }
            if (IncludedDeclarations.HasFlag(DeclarationType.Instance))
            {
                binding |= BindingFlags.Instance;
            }

            if (IncludedDeclarations.HasFlag(DeclarationType.Inherited))
            {
                binding |= BindingFlags.FlattenHierarchy;
            }
            else
            {
                binding |= BindingFlags.DeclaredOnly;
            }

            return(binding);
        }
        protected virtual IEncapsulateFieldCandidate AssignNoConflictIdentifier(IEncapsulateFieldCandidate candidate, DeclarationType declarationType)
        {
            Debug.Assert(declarationType.HasFlag(DeclarationType.Property) ||
                         declarationType.HasFlag(DeclarationType.Variable));

            var isConflictingIdentifier = HasConflictingIdentifierIgnoreEncapsulationFlag(candidate, declarationType, out _);
            var guard = 0;

            while (guard++ < 10 && isConflictingIdentifier)
            {
                var identifier = IdentifierToCompare(candidate, declarationType);

                if (declarationType.HasFlag(DeclarationType.Property))
                {
                    candidate.PropertyIdentifier = identifier.IncrementEncapsulationIdentifier();
                }
                else
                {
                    candidate.BackingIdentifier = identifier.IncrementEncapsulationIdentifier();
                }
                isConflictingIdentifier = HasConflictingIdentifierIgnoreEncapsulationFlag(candidate, declarationType, out _);
            }

            return(candidate);
        }
 private bool IsIncluded(MethodInfo method, AccessLevel access)
 {
     if (method != null && !IncludedDeclarations.HasFlag(DeclarationType.Inherited) && method.GetBaseDefinition() != method)
     {
         return(false);
     }
     return(IsIncluded((MethodBase)method, access));
 }
        /// <summary>
        /// Evaluates an identifier string's conformance with MS-VBAL naming requirements.
        /// </summary>
        /// <returns>Message for first matching invalid identifier criteria.  Or, an empty string if the identifier is valid</returns>
        public static bool TryMatchInvalidIdentifierCriteria(string name, DeclarationType declarationType, out string criteriaMatchMessage)
        {
            criteriaMatchMessage = string.Empty;

            var maxNameLength = declarationType.HasFlag(DeclarationType.Module)
               ? Declaration.MaxModuleNameLength : Declaration.MaxMemberNameLength;

            if (string.IsNullOrEmpty(name))
            {
                criteriaMatchMessage = RubberduckUI.InvalidNameCriteria_IsNullOrEmpty;
                return(true);
            }

            //Does not start with a letter
            if (!char.IsLetter(name.First()))
            {
                criteriaMatchMessage = string.Format(RubberduckUI.InvalidNameCriteria_DoesNotStartWithLetterFormat, name);
                return(true);
            }

            //Has special characters
            if (name.Any(c => !char.IsLetterOrDigit(c) && c != '_'))
            {
                criteriaMatchMessage = string.Format(RubberduckUI.InvalidNameCriteria_InvalidCharactersFormat, name);
                return(true);
            }

            //Is a reserved identifier
            if (ReservedIdentifiers.Contains(name, StringComparer.InvariantCultureIgnoreCase))
            {
                criteriaMatchMessage = string.Format(RubberduckUI.InvalidNameCriteria_IsReservedKeywordFormat, name);
                return(true);
            }

            //"VBA" identifier not allowed for projects
            if (declarationType.HasFlag(DeclarationType.Project) &&
                name.Equals("VBA", StringComparison.InvariantCultureIgnoreCase))
            {
                criteriaMatchMessage = string.Format(RubberduckUI.InvalidNameCriteria_IsReservedKeywordFormat, name);
                return(true);
            }

            //Exceeds max length
            if (name.Length > maxNameLength)
            {
                criteriaMatchMessage = string.Format(RubberduckUI.InvalidNameCriteria_ExceedsMaximumLengthFormat, name);
                return(true);
            }
            return(false);
        }
示例#6
0
        public virtual bool IsTypeSpecified()
        {
            if (Context == null || _neverSpecified.Any(item => DeclarationType.HasFlag(item)))
            {
                return(false);
            }

            if (_isTypeSpecified.HasValue)
            {
                return(_isTypeSpecified.Value);
            }

            var method = Context.GetType().GetMethod("asTypeClause");

            if (method == null)
            {
                _isTypeSpecified = false;
                return(false);
            }

            if (HasTypeHint())
            {
                _isTypeSpecified = false;
                return(true);
            }

            _isTypeSpecified = ((dynamic)Context).asTypeClause() is VBAParser.AsTypeClauseContext;
            return(_isTypeSpecified.Value);
        }
示例#7
0
        public virtual bool IsArray()
        {
            if (Context == null || _neverArray.Any(item => DeclarationType.HasFlag(item)))
            {
                return(false);
            }

            if (_isArray.HasValue)
            {
                return(_isArray.Value);
            }

            var rParenMethod = Context.GetType().GetMethod("RPAREN");

            if (rParenMethod == null)
            {
                _isArray = false;
                return(_isArray.Value);
            }

            var declaration = (dynamic)Context;

            _isArray = declaration.LPAREN() != null && declaration.RPAREN() != null;
            return(_isArray.Value);
        }
        //The refactoring only inserts new code elements with the following Accessibilities:
        //Variables => Private
        //Properties => Public
        //UDTs => Private
        private bool IsAlwaysIgnoreNameConflictType(Declaration d, DeclarationType toEnapsulateDeclarationType)
        {
            //5.3.1.6 Each<subroutine-declaration> and<function-declaration> must have a procedure
            //name that is different from any other module variable name, module constant name,
            //enum member name, or procedure name that is defined within the same module.
            var NeverCauseNameConflictTypes = new List <DeclarationType>()
            {
                DeclarationType.Project,
                DeclarationType.ProceduralModule,
                DeclarationType.ClassModule,
                DeclarationType.Parameter,
                DeclarationType.EnumerationMember,
                DeclarationType.Enumeration,
                DeclarationType.UserDefinedType,
                DeclarationType.UserDefinedTypeMember
            };

            if (toEnapsulateDeclarationType.HasFlag(DeclarationType.Variable))
            {
                //5.2.3.4: An enum member name may not be the same as any variable name
                //or constant name that is defined within the same module
                NeverCauseNameConflictTypes.Remove(DeclarationType.EnumerationMember);
            }
            else if (toEnapsulateDeclarationType.HasFlag(DeclarationType.UserDefinedType))
            {
                //5.2.3.3 If an<udt-declaration > is an element of a<private-type-declaration> its
                //UDT name cannot be the same as the enum name of any<enum-declaration>
                //or the UDT name of any other<UDTdeclaration> within the same<module>
                NeverCauseNameConflictTypes.Remove(DeclarationType.UserDefinedType);
                NeverCauseNameConflictTypes.Remove(DeclarationType.Enumeration);
            }
            else if (toEnapsulateDeclarationType.HasFlag(DeclarationType.Property))
            {
                //Each < subroutine - declaration > and < function - declaration > must have a
                //procedure name that is different from any other module variable name,
                //module constant name, enum member name, or procedure name that is defined
                //within the same module.

                NeverCauseNameConflictTypes.Remove(DeclarationType.EnumerationMember);
            }
            return(d.IsLocalVariable() ||
                   d.IsLocalConstant() ||
                   NeverCauseNameConflictTypes.Contains(d.DeclarationType));
        }
        private static IEnumerable <IAnnotation> AnnotationsForDeclarationType(DeclarationType declarationType, IEnumerable <IAnnotation> annotations)
        {
            if (declarationType.HasFlag(DeclarationType.Module))
            {
                return(annotations.Where(annotation => annotation.Target.HasFlag(AnnotationTarget.Module)));
            }

            if (declarationType.HasFlag(DeclarationType.Member) &&
                declarationType != DeclarationType.LibraryProcedure &&
                declarationType != DeclarationType.LibraryFunction)
            {
                return(annotations.Where(annotation => annotation.Target.HasFlag(AnnotationTarget.Member)));
            }

            if (declarationType.HasFlag(DeclarationType.Variable))
            {
                return(annotations.Where(annotation => annotation.Target.HasFlag(AnnotationTarget.Variable)));
            }

            return(Enumerable.Empty <IAnnotation>());
        }
示例#10
0
        public void ImprovedArgumentList_AppliesByVal(DeclarationType declarationType)
        {
            var procedureIdentifier = "TestProperty";
            var procType            = ProcedureTypeIdentifier(declarationType);

            string inputCode =
                $@"
Public {procType.procType} {procedureIdentifier}(arg1 As Long, arg2 As String)
End {procType.endStmt}
";
            var result = ParseAndTest <ModuleBodyElementDeclaration>(inputCode,
                                                                     procedureIdentifier,
                                                                     declarationType,
                                                                     ImprovedArgumentListTest);

            var expected = declarationType.HasFlag(DeclarationType.Property)
                ? "arg1 As Long, ByVal arg2 As String"
                : "arg1 As Long, arg2 As String";

            StringAssert.AreEqualIgnoringCase(expected, result);
        }
示例#11
0
 public static string GetRusDeclarationType(DeclarationType dt)
 {
     string res = "";
     if (dt.HasFlag(DeclarationType.Clone))
     {
         res = "Дубликат";
     }
     else
     {
         if (dt.HasFlag(DeclarationType.Grant))
         {
             res = "Выдача";
         }
         else
         {
             if (dt.HasFlag(DeclarationType.Cancel))
             {
                 res = "Прекращение";
             }
             else
             {
                 if (dt.HasFlag(DeclarationType.Renew))
                 {
                     if (dt.HasFlag(DeclarationType.Prolong))
                     {
                         res = "Переоформление/Продление";
                     }
                     else
                     {
                         res = "Переоформление";
                     }
                 }
                 else
                 {
                     if (dt.HasFlag(DeclarationType.Prolong))
                     {
                         res = "Продление";
                     }
                     else
                     {
                         res = "";
                     }
                 }
             }
         }
     }
     return res;
 }
示例#12
0
        public void MemberBlockFromPrototype_AppliesByVal(DeclarationType declarationType)
        {
            var procedureIdentifier = "TestProcedure";
            var procType            = ProcedureTypeIdentifier(declarationType);

            string inputCode =
                $@"
Public {procType.procType} {procedureIdentifier}(arg1 As Long, arg2 As String)
End {procType.endStmt}
";
            var result = ParseAndTest <ModuleBodyElementDeclaration>(inputCode,
                                                                     procedureIdentifier,
                                                                     declarationType,
                                                                     new MemberBlockFromPrototypeTestParams(),
                                                                     MemberBlockFromPrototypeTest);

            var expected = declarationType.HasFlag(DeclarationType.Property)
                ? "(arg1 As Long, ByVal arg2 As String)"
                : "(arg1 As Long, arg2 As String)";

            StringAssert.Contains($"{procType.procType} {procedureIdentifier}{expected}", result);
        }
示例#13
0
        public bool HasTypeHint(out string token)
        {
            if (Context == null || _neverHinted.Any(item => DeclarationType.HasFlag(item)))
            {
                token        = null;
                _hasTypeHint = false;
                return(_hasTypeHint.Value);
            }

            try
            {
                var hint = ((dynamic)Context).typeHint();
                token        = hint == null ? null : hint.GetText();
                _hasTypeHint = hint != null;
                return(_hasTypeHint.Value);
            }
            catch (RuntimeBinderException)
            {
                token        = null;
                _hasTypeHint = false;
                return(_hasTypeHint.Value);
            }
        }
示例#14
0
 private static bool IsInstanceSensitive(DeclarationType memberType)
 {
     return(memberType.HasFlag(DeclarationType.Variable) || memberType == DeclarationType.Constant || memberType.HasFlag(DeclarationType.Procedure) || memberType.HasFlag(DeclarationType.Function));
 }
        /// <summary>
        /// Evaluates an identifier string's conformance with MS-VBAL naming requirements.
        /// </summary>
        /// <returns>Message for first matching invalid identifier criteria.  Or, an empty string if the identifier is valid</returns>
        public static bool TryMatchInvalidIdentifierCriteria(string name, DeclarationType declarationType, out string criteriaMatchMessage, bool isArrayDeclaration = false)
        {
            criteriaMatchMessage = string.Empty;

            var maxNameLength = declarationType.HasFlag(DeclarationType.Module)
               ? Declaration.MaxModuleNameLength : Declaration.MaxMemberNameLength;

            if (string.IsNullOrEmpty(name))
            {
                criteriaMatchMessage = RubberduckUI.InvalidNameCriteria_IsNullOrEmpty;
                return(true);
            }

            //Does not start with a letter
            if (!char.IsLetter(name.First()))
            {
                criteriaMatchMessage = string.Format(RubberduckUI.InvalidNameCriteria_DoesNotStartWithLetterFormat, name);
                return(true);
            }

            //Has special characters
            if (name.Any(c => !char.IsLetterOrDigit(c) && c != '_'))
            {
                criteriaMatchMessage = string.Format(RubberduckUI.InvalidNameCriteria_InvalidCharactersFormat, name);
                return(true);
            }

            //Is a reserved identifier
            if (!declarationType.HasFlag(DeclarationType.UserDefinedTypeMember))
            {
                if (ReservedIdentifiers.Contains(name, StringComparer.InvariantCultureIgnoreCase))
                {
                    criteriaMatchMessage = string.Format(RubberduckUI.InvalidNameCriteria_IsReservedKeywordFormat, name);
                    return(true);
                }
            }
            else if (isArrayDeclaration) //is a DeclarationType.UserDefinedTypeMember
            {
                //DeclarationType.UserDefinedTypeMember can have reserved identifier keywords
                //...unless the declaration is an array.  Adding the parentheses causes errors.

                //Name is not a reserved identifier, but when used as a UDTMember array declaration
                //it collides with the 'Name' Statement (Renames a disk file, directory, or folder)
                var invalidUDTArrayIdentifiers = ReservedIdentifiers.Concat(new List <string>()
                {
                    "Name"
                });

                if (invalidUDTArrayIdentifiers.Contains(name, StringComparer.InvariantCultureIgnoreCase))
                {
                    criteriaMatchMessage = string.Format(RubberduckUI.InvalidNameCriteria_IsReservedKeywordFormat, name);
                    return(true);
                }
            }

            //"VBA" identifier not allowed for projects
            if (declarationType.HasFlag(DeclarationType.Project) &&
                name.Equals("VBA", StringComparison.InvariantCultureIgnoreCase))
            {
                criteriaMatchMessage = string.Format(RubberduckUI.InvalidNameCriteria_IsReservedKeywordFormat, name);
                return(true);
            }

            //Exceeds max length
            if (name.Length > maxNameLength)
            {
                criteriaMatchMessage = string.Format(RubberduckUI.InvalidNameCriteria_ExceedsMaximumLengthFormat, name);
                return(true);
            }
            return(false);
        }
示例#16
0
        void AddDeclaration(DeclarationType forbidden)
        {
            if (_declarationType == DeclarationType.Document && !forbidden.HasFlag(DeclarationType.Document))
            {
                AddTreeNode(new HtmlDeclaration(_name));
            }
            else if (_declarationType == DeclarationType.CDDATA && !forbidden.HasFlag(DeclarationType.CDDATA))
            {
                AddTreeNode(new CDATAElement(_content.ToString()));
            }
            else if (_declarationType == DeclarationType.Comment && !forbidden.HasFlag(DeclarationType.Comment))
            {
                AddTreeNode(new HtmlComment(_content.ToString()));
            }

            if (!forbidden.HasFlag(DeclarationType.NoAny))
            {
                GenerateError("Unexpected declaration");
            }
        }
 protected string IdentifierToCompare(IEncapsulateFieldCandidate field, DeclarationType declarationType)
 {
     return(declarationType.HasFlag(DeclarationType.Property)
         ? field.PropertyIdentifier
         : field.BackingIdentifier);
 }