/// <summary> /// Verifies that fields are not declared public. /// </summary> /// <param name="element">The element to check.</param> private void CheckFieldAccessModifiers(Element element) { Param.AssertNotNull(element, "element"); Element parent = element.FindParentElement(); if (element.ElementType == ElementType.Field && (element.AccessModifierType != AccessModifierType.Private) && parent != null && parent.ElementType != ElementType.Struct) { // If the field is located within a native methods class, and the class that contains // the field is private or internal, then do not check the access modifiers on the field. bool nativeMethods = false; bool privateOrInternal = false; while (parent != null) { if (parent.ElementType != ElementType.Class && parent.ElementType != ElementType.Struct) { break; } if (parent.ActualAccessLevel == AccessModifierType.Private || parent.ActualAccessLevel == AccessModifierType.Internal) { privateOrInternal = true; } if (parent.Name.EndsWith("NativeMethods", StringComparison.Ordinal)) { nativeMethods = true; break; } parent = parent.FindParentElement(); } if (!nativeMethods || !privateOrInternal) { Field field = (Field)element; if (!field.Const && !field.Readonly && !field.Generated) { this.AddViolation(element, Rules.FieldsMustBePrivate); } } } }
/// <summary> /// Checks that using-directives are placed within the namespace element. /// </summary> /// <param name="element">The element to check.</param> private void CheckUsingDirectivePlacement(Element element) { Param.AssertNotNull(element, "element"); // Only check the positioning of using directives which are not within generated code. if (!element.Generated && element.ElementType == ElementType.UsingDirective) { Element parentElement = element.FindParentElement(); if (parentElement != null && parentElement.ElementType != ElementType.Namespace) { // This is acceptable if there is no namespace in the file at all. bool foundNamespace = false; if (parentElement.ElementType == ElementType.Document) { for (Element child = parentElement.FindFirstChildElement(); child != null; child = child.FindNextSiblingElement()) { if (child.ElementType == ElementType.Namespace) { foundNamespace = true; break; } } } if (foundNamespace) { this.AddViolation(element, Rules.UsingDirectivesMustBePlacedWithinNamespace); } } } }
/// <summary> /// Checks the access modifier on the element. /// </summary> /// <param name="element">The element being visited.</param> private void CheckAccessModifierRulesForElement(Element element) { Param.AssertNotNull(element, "element"); // Make sure this element is not generated. if (!element.Generated) { // Skip these rules if the element is a child of an interface. Element parent = element.FindParentElement(); if (parent == null || parent.ElementType != ElementType.Interface) { this.CheckForAccessModifier(element); this.CheckFieldAccessModifiers(element); } } }