예제 #1
0
 /// <summary>
 /// 初始化类<see cref="MemberElement"/>。
 /// </summary>
 /// <param name="name">名称。</param>
 /// <param name="declarations">修饰符字符串列表。</param>
 /// <param name="parent">父级元素实例。</param>
 protected MemberElement(string name, List <string> declarations, ICodeElement parent) : base(parent)
 {
     Name         = name.Trim();
     Declarations = declarations;
     MemberType   = declarations[declarations.Count - 1];
     IsPublic     = declarations.Any(x => x == "public");
 }
예제 #2
0
 private void Walk(IEnumerable <ICodeElement> codeElements, ICodeElement current)
 {
     foreach (var element in codeElements)
     {
         element.Convert(this);
     }
 }
        public bool Check(ICodeElement elementToAnalyze, RecognitionContextBase context)
        {
            var type     = (NamedTypeBase)elementToAnalyze;
            var siblings = GetSiblings(type, context.Types);

            return(type.Methods.Count(m => m.IsCtor && m.Parameters.Any(p => p.Type != null && siblings.Any(s => s == (NamedTypeBase)p.Type))) > 0);
        }
        /// <summary>
        /// Initializes a new instance of the Violation class.
        /// </summary>
        /// <param name="rule">
        /// The rule that triggered the violation.
        /// </param>
        /// <param name="element">
        /// The element that this violation appears in.
        /// </param>
        /// <param name="location">
        /// The location in the source code where the violation occurs.
        /// </param>
        /// <param name="message">
        /// The context message for the violation.
        /// </param>
        internal Violation(Rule rule, ICodeElement element, CodeLocation location, string message)
        {
            Param.AssertNotNull(rule, "rule");
            Param.Ignore(element);
            Param.AssertNotNull(location, "location");
            Param.AssertNotNull(message, "message");

            this.rule = rule;
            this.element = element;

            // The CodeLocation passed in is zero based everywhere in StyleCop for the column. The line number is already 1 based.
            // We convert is to 1 based here so that are xml reports etc and VisualStudio UI friendly.
            this.location = new CodeLocation(
                location.StartPoint.Index, 
                location.EndPoint.Index, 
                location.StartPoint.IndexOnLine + 1, 
                location.EndPoint.IndexOnLine + 1, 
                location.StartPoint.LineNumber, 
                location.EndPoint.LineNumber);

            // If the location has been passed in we set the linenumber.
            this.line = location.LineNumber;
            this.message = message;

            if (this.element != null && this.element.Document != null)
            {
                this.sourceCode = this.element.Document.SourceCode;
            }

            this.UpdateKey();
        }
        private void GS分岐文(IStatement statement, StringWriter writer)
        {
            var st = statement as 分岐文;

            GenerateStruct(st.Sentence.Phrases, writer);

            //各case:
            var codeList = st.CodeList;

            for (int i = 0; i < codeList.Count; i++)
            {
                ICodeElement element = codeList[i];
                if (element is SwitchCaseBase)
                {
                    SwitchCaseBase switchCase = element as SwitchCaseBase;
                    if (switchCase is SwitchCase)
                    {
                        Generate((switchCase as SwitchCase).CasePhrase, writer);
                    }
                }
                else
                {
                    Generate(element, writer, null);
                }
            }
        }
예제 #6
0
        /// <summary>
        /// Gets the expression value.
        /// </summary>
        /// <param name="expression">The expression.</param>
        /// <param name="element">The element.</param>
        /// <returns>The expression value as text.</returns>
        private static string GetExpressionValue(IConditionExpression expression, ICodeElement element)
        {
            string value = string.Empty;

            if (expression != null && element != null)
            {
                StringExpression stringExpression = expression as StringExpression;
                if (stringExpression != null)
                {
                    value = stringExpression.Text;
                }
                else
                {
                    ElementAttributeExpression attributeExpression = expression as ElementAttributeExpression;

                    if (attributeExpression.Scope == ElementAttributeScope.Parent)
                    {
                        element = element.Parent;
                    }

                    if (attributeExpression != null)
                    {
                        value = ElementUtilities.GetAttribute(attributeExpression.ElementAttribute, element);
                    }
                }
            }

            return(value);
        }
예제 #7
0
        /// <summary>
        /// Initializes a new instance of the Violation class.
        /// </summary>
        /// <param name="rule">
        /// The rule that triggered the violation.
        /// </param>
        /// <param name="element">
        /// The element that this violation appears in.
        /// </param>
        /// <param name="location">
        /// The location in the source code where the violation occurs.
        /// </param>
        /// <param name="message">
        /// The context message for the violation.
        /// </param>
        internal Violation(Rule rule, ICodeElement element, CodeLocation location, string message)
        {
            Param.AssertNotNull(rule, "rule");
            Param.Ignore(element);
            Param.AssertNotNull(location, "location");
            Param.AssertNotNull(message, "message");

            this.rule    = rule;
            this.element = element;

            // The CodeLocation passed in is zero based everywhere in StyleCop for the column. The line number is already 1 based.
            // We convert is to 1 based here so that are xml reports etc and VisualStudio UI friendly.
            this.location = new CodeLocation(
                location.StartPoint.Index,
                location.EndPoint.Index,
                location.StartPoint.IndexOnLine + 1,
                location.EndPoint.IndexOnLine + 1,
                location.StartPoint.LineNumber,
                location.EndPoint.LineNumber);

            // If the location has been passed in we set the linenumber.
            this.line    = location.LineNumber;
            this.message = message;

            if (this.element != null && this.element.Document != null)
            {
                this.sourceCode = this.element.Document.SourceCode;
            }

            this.UpdateKey();
        }
        private ICodeElement __getElement(String nameOrId)
        {
            if (isEmpty)
            {
                return(null);
            }

            if (String.IsNullOrEmpty(nameOrId))
            {
                return(null);
            }
            nameOrId = nameOrId.Trim();
            nameOrId = nameOrId.ToUpper();

            ICodeElement output = null;

            if (nameOrId.isNumber())
            {
                output = items[Int32.Parse(nameOrId)];
            }
            else
            {
                output = items.Find(x => x.name.ToUpper() == nameOrId);
            }

            return(output);
        }
예제 #9
0
        /// <summary>
        /// Determines whether the given rule is suppressed for the given element.
        /// </summary>
        /// <param name="element">
        /// The element to check.
        /// </param>
        /// <param name="ruleCheckId">
        /// The Id of the rule to check.
        /// </param>
        /// <param name="ruleName">
        /// The Name of the rule to check.
        /// </param>
        /// <param name="ruleNamespace">
        /// The Namespace of the rule to check.
        /// </param>
        /// <returns>
        /// Returns true is the rule is suppressed; otherwise false.
        /// </returns>
        public override bool IsRuleSuppressed(ICodeElement element, string ruleCheckId, string ruleName, string ruleNamespace)
        {
            if (element != null && !string.IsNullOrEmpty(ruleCheckId) && ruleName != string.Empty && !string.IsNullOrEmpty(ruleNamespace))
            {
                SuppressedRule suppressedRule = new SuppressedRule {
                    RuleId = ruleCheckId, RuleName = ruleName, RuleNamespace = ruleNamespace
                };

                this.suppressionsLock.AcquireReaderLock(Timeout.Infinite);
                try
                {
                    if (ruleCheckId != "*")
                    {
                        // See if this namespace is suppressed completely.
                        if (this.IsRuleSuppressed(element, "*", null, ruleNamespace))
                        {
                            return(true);
                        }
                    }

                    List <CsElement> list = null;
                    if ((this.suppressions.Count != 0) && this.suppressions.TryGetValue(suppressedRule, out list))
                    {
                        return(MatchElementWithPossibleElementsTraversingParents((CsElement)element, list));
                    }
                }
                finally
                {
                    this.suppressionsLock.ReleaseReaderLock();
                }
            }

            return(false);
        }
예제 #10
0
        /// <summary>
        /// Determines whether the given rule is suppressed for the given element.
        /// </summary>
        /// <param name="element">The element to check.</param>
        /// <param name="rule">The rule to check.</param>
        /// <returns>Returns true is the rule is suppressed; otherwise false.</returns>
        public override bool IsRuleSuppressed(ICodeElement element, Rule rule)
        {
            Param.Ignore(element, rule);

            if (element != null && rule != null)
            {
                // If the lock throws we are okay with it unwinding
                this.suppressionsLock.AcquireReaderLock(Timeout.Infinite);

                try
                {
                    // First, check whether the entire rule namespace is suppressed for this element.
                    if (this.IsRuleSuppressed(element, rule.UniqueRuleNamespaceId))
                    {
                        return(true);
                    }

                    // Now determine whether the specific rule is suppressed.
                    if (this.IsRuleSuppressed(element, rule.UniqueRuleId))
                    {
                        return(true);
                    }
                }
                finally
                {
                    this.suppressionsLock.ReleaseReaderLock();
                }
            }

            return(false);
        }
예제 #11
0
        /// <summary>
        /// Gets the Attributes attribute.
        /// </summary>
        /// <param name="codeElement">The code element.</param>
        /// <returns>Attributes as a comma-separated list.</returns>
        private static string GetAttributesAttribute(ICodeElement codeElement)
        {
            StringBuilder attributesBuilder = new StringBuilder();

            AttributedElement attributedElement = codeElement as AttributedElement;

            if (attributedElement != null)
            {
                for (int attributeIndex = 0; attributeIndex < attributedElement.Attributes.Count; attributeIndex++)
                {
                    IAttributeElement attribute = attributedElement.Attributes[attributeIndex];
                    attributesBuilder.Append(attribute.Name);

                    foreach (ICodeElement attributeChild in attribute.Children)
                    {
                        IAttributeElement childAttributeElement = attributeChild as IAttributeElement;
                        if (childAttributeElement != null)
                        {
                            attributesBuilder.Append(", ");
                            attributesBuilder.Append(childAttributeElement.Name);
                        }
                    }

                    if (attributeIndex < attributedElement.Attributes.Count - 1)
                    {
                        attributesBuilder.Append(", ");
                    }
                }
            }

            return(attributesBuilder.ToString());
        }
예제 #12
0
 public void Build(ICodeElement left, ICodeElement right, ICodeElement body, IFinalizedScope scope)
 {
     buildableLeft.Set(left);
     buildableRight.Set(right);
     buildableBody.Set(body);
     buildableScope.Set(scope);
 }
예제 #13
0
        /// <summary>
        /// Gets the type attribute.
        /// </summary>
        /// <param name="codeElement">The code element.</param>
        /// <returns>The type attibute as text.</returns>
        private static string GetTypeAttribute(ICodeElement codeElement)
        {
            string attributeString = string.Empty;

            MemberElement memberElement = codeElement as MemberElement;

            if (memberElement != null)
            {
                attributeString = memberElement.Type;
            }
            else
            {
                switch (codeElement.ElementType)
                {
                case ElementType.Type:
                    attributeString = EnumUtilities.ToString(((TypeElement)codeElement).Type);
                    break;

                case ElementType.Comment:
                    attributeString = EnumUtilities.ToString(((CommentElement)codeElement).Type);
                    break;

                case ElementType.Using:
                    attributeString = EnumUtilities.ToString(((UsingElement)codeElement).Type);
                    break;
                }
            }

            return(attributeString);
        }
예제 #14
0
        /// <summary>
        /// 初始化类<see cref="AttributeElement"/>。
        /// </summary>
        /// <param name="attribute">特性字符串。</param>
        /// <param name="parent">父级元素。</param>
        internal AttributeElement(string attribute, ICodeElement parent)
        {
            _attribute = attribute.Trim();
            attribute  = _attribute.Substring(1).Trim();
            var index = attribute.IndexOf('(');

            if (index == -1)
            {
                Name = attribute.TrimEnd(']', ' ');
            }
            else
            {
                Name      = attribute.Substring(0, index);
                attribute = attribute.Substring(index + 1).Trim();
                index     = attribute.LastIndexOf(')');
                attribute = attribute.Substring(0, index).Trim();
                // "xx", 1, Name="lala", Order=1
                index = 0;
                while (attribute.TryReadUtil(ref index, ',', out var argument))
                {
                    argument = argument.Trim();
                    if (argument.IsQuote(0, out var quote, out _))
                    {
                        if (quote == '\'')
                        {
                            _arguments[$"$:{_arguments.Count}"] = argument[0];
                        }
                        else
                        {
                            _arguments[$"$:{_arguments.Count}"] = argument;
                        }
                    }
예제 #15
0
        /// <summary>
        /// Gets all static fields for a Type.
        /// </summary>
        /// <param name="typeElement">Type element.</param>
        /// <returns>All static fields for the specified Type element.</returns>
        private FieldElement[] GetTypeStaticFields(TypeElement typeElement)
        {
            List <FieldElement> staticFields = new List <FieldElement>();

            Action <ICodeElement> findStaticFields = delegate(ICodeElement codeElement)
            {
                FieldElement fieldElement = codeElement as FieldElement;
                if (fieldElement != null && fieldElement.MemberModifiers == MemberModifiers.Static)
                {
                    bool         isTypeChild   = false;
                    ICodeElement parentElement = codeElement.Parent;
                    while (!isTypeChild && parentElement != null)
                    {
                        isTypeChild = parentElement == typeElement;
                        if (!isTypeChild)
                        {
                            parentElement = parentElement.Parent;
                        }
                    }

                    if (isTypeChild)
                    {
                        staticFields.Add(fieldElement);
                    }
                }
            };

            ElementUtilities.ProcessElementTree(typeElement, findStaticFields);

            return(staticFields.ToArray());
        }
예제 #16
0
 public virtual void Visit(ICodeElement node)
 {
     if (null == node)
     {
         return;
     }
     node.Accept(this);
 }
예제 #17
0
 public static void WriteToFile(string fileName, ICodeElement element)
 {
     using (var stm = new FileStream(fileName, FileMode.Create)) {
         CodeWriter writer = new CodeWriter(stm);
         element.WriteAll(writer);
         writer.TextWriter.Flush();
     }
 }
예제 #18
0
 /// <summary>
 /// 初始化类<see cref="MethodElement"/>。
 /// </summary>
 /// <param name="name">名称。</param>
 /// <param name="declarations">修饰符字符串列表。</param>
 /// <param name="parent">父级元素实例。</param>
 internal MethodElement(string name, List <string> declarations, ICodeElement parent)
     : base(name, declarations, parent)
 {
     if (parent is TypeElement element)
     {
         IsConstructor = name.Equals(element.Name);
     }
 }
예제 #19
0
 public static T AttachAfter <T> (this T attacher, ICodeElement attachTo) where T : ICodeElement
 {
     Exceptions.ThrowOnNull(attachTo, nameof(attachTo));
     attachTo.End += (s, eventArgs) => {
         attacher.WriteAll(eventArgs.Writer);
     };
     return(attacher);
 }
예제 #20
0
        /// <summary>
        /// Adds one violation to the given code element.
        /// </summary>
        /// <param name="element">
        /// The element that the violation appears in.
        /// </param>
        /// <param name="ruleName">
        /// The name of the rule that triggered the violation.
        /// </param>
        /// <param name="values">
        /// String parameters to insert into the violation context string.
        /// </param>
        public void AddViolation(ICodeElement element, Enum ruleName, params object[] values)
        {
            Param.Ignore(element);
            Param.RequireNotNull(ruleName, "ruleName");
            Param.Ignore(values);

            this.AddViolation(element, ruleName.ToString(), values);
        }
예제 #21
0
        /// <summary>
        /// Gets a string representation of a code element using the specified
        /// format.
        /// </summary>
        /// <param name="format">The format.</param>
        /// <param name="codeElement">The code element.</param>
        /// <returns>Formatted string representation of the code element.</returns>
        public static string Format(string format, ICodeElement codeElement)
        {
            if (format == null)
            {
                throw new ArgumentNullException("format");
            }
            else if (codeElement == null)
            {
                throw new ArgumentNullException("codeElement");
            }

            StringBuilder formatted        = new StringBuilder(format.Length * 2);
            StringBuilder attributeBuilder = null;
            bool          inAttribute      = false;

            using (StringReader reader = new StringReader(format))
            {
                int data = reader.Read();
                while (data > 0)
                {
                    char ch = (char)data;

                    if (ch == ConditionExpressionParser.ExpressionPrefix &&
                        (char)(reader.Peek()) == ConditionExpressionParser.ExpressionStart)
                    {
                        reader.Read();
                        attributeBuilder = new StringBuilder(16);
                        inAttribute      = true;
                    }
                    else if (inAttribute)
                    {
                        if (ch == ConditionExpressionParser.ExpressionEnd)
                        {
                            ElementAttributeType elementAttribute = (ElementAttributeType)Enum.Parse(
                                typeof(ElementAttributeType), attributeBuilder.ToString());

                            string attribute = GetAttribute(elementAttribute, codeElement);
                            formatted.Append(attribute);
                            attributeBuilder = new StringBuilder(16);
                            inAttribute      = false;
                        }
                        else
                        {
                            attributeBuilder.Append(ch);
                        }
                    }
                    else
                    {
                        formatted.Append(ch);
                    }

                    data = reader.Read();
                }
            }

            return(formatted.ToString());
        }
예제 #22
0
 public CSLine(ICodeElement contents, bool addSemicolon = true)
 {
     Contents = Exceptions.ThrowOnNull(contents, nameof(contents));
     if (!(contents is ICSLineable) && addSemicolon)
     {
         throw new ArgumentException("contents must be ILineable", nameof(contents));
     }
     AddSemicolon = addSemicolon;
 }
예제 #23
0
        /// <summary>
        /// Gets a string representation of a code element using the specified
        /// format.
        /// </summary>
        /// <param name="format">The format.</param>
        /// <param name="codeElement">The code element.</param>
        /// <returns>Formatted string representation of the code element.</returns>
        public static string Format(string format, ICodeElement codeElement)
        {
            if (format == null)
            {
                throw new ArgumentNullException("format");
            }
            else if (codeElement == null)
            {
                throw new ArgumentNullException("codeElement");
            }

            StringBuilder formatted = new StringBuilder(format.Length*2);
            StringBuilder attributeBuilder = null;
            bool inAttribute = false;

            using (StringReader reader = new StringReader(format))
            {
                int data = reader.Read();
                while (data > 0)
                {
                    char ch = (char) data;

                    if (ch == ConditionExpressionParser.ExpressionPrefix &&
                        (char) (reader.Peek()) == ConditionExpressionParser.ExpressionStart)
                    {
                        reader.Read();
                        attributeBuilder = new StringBuilder(16);
                        inAttribute = true;
                    }
                    else if (inAttribute)
                    {
                        if (ch == ConditionExpressionParser.ExpressionEnd)
                        {
                            ElementAttributeType elementAttribute = (ElementAttributeType) Enum.Parse(
                                typeof (ElementAttributeType), attributeBuilder.ToString());

                            string attribute = GetAttribute(elementAttribute, codeElement);
                            formatted.Append(attribute);
                            attributeBuilder = new StringBuilder(16);
                            inAttribute = false;
                        }
                        else
                        {
                            attributeBuilder.Append(ch);
                        }
                    }
                    else
                    {
                        formatted.Append(ch);
                    }

                    data = reader.Read();
                }
            }

            return formatted.ToString();
        }
        public bool Check(ICodeElement elementToAnalyze, RecognitionContextBase context)
        {
            var type = (NamedTypeBase)elementToAnalyze;

            return
                (type.Methods.Where(m => m.IsCtor).All(m => (VisibilityModifierBase)m.Visibility == VisibilityModifierBase.Private)
                 &&
                 type.Methods.Any(m => m.IsCtor));
        }
        public bool Check(ICodeElement elementToAnalyze, RecognitionContextBase context)
        {
            MethodBase m = elementToAnalyze as MethodBase;

            if (m == null)
            {
                throw new ArgumentException();
            }
            return(m.IsOverride);
        }
예제 #26
0
        public static bool IsProperty(this ICodeElement codeElement)
        {
            if (!codeElement.IsMethod)
            {
                return(false);
            }

            var method = codeElement.AsMethod;

            return(method.IsPropertyGetter || method.IsPropertySetter);
        }
예제 #27
0
        public static bool IsFunctional(this ICodeElement codeElement)
        {
            if (!codeElement.IsMethod)
            {
                return(false);
            }

            var method = codeElement.AsMethod;

            return(!method.IsProperty() && !method.IsConstructor);
        }
예제 #28
0
 /// <summary>
 /// Processes each element in a code element tree.
 /// </summary>
 /// <param name="codeElement">Code element to process.</param>
 /// <param name="action">Action that performs processing.</param>
 public static void ProcessElementTree(ICodeElement codeElement, Action <ICodeElement> action)
 {
     if (codeElement != null)
     {
         action(codeElement);
         foreach (ICodeElement childElement in codeElement.Children)
         {
             ProcessElementTree(childElement, action);
         }
     }
 }
예제 #29
0
        public static Stream WriteToStream(ICodeElement element)
        {
            var stm        = new MemoryStream();
            var codeWriter = new CodeWriter(stm);

            element.WriteAll(codeWriter);
            codeWriter.TextWriter.Flush();
            stm.Flush();
            stm.Seek(0, SeekOrigin.Begin);
            return(stm);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public Int32 Add(ICodeElement item)
        {
            Int32 i = -1;

            if (_isAllowed(item))
            {
                i = _register(item);
            }

            return(i);
        }
 public virtual bool IsInstance(ICodeElement elementToAnalyze)
 {
     foreach (var criterion in this.Criteria)
     {
         if (!criterion.Check(elementToAnalyze, Context))
         {
             return(false);
         }
     }
     return(true);
 }
예제 #32
0
        /// <summary>
        /// Determines whether or not the specified code element matches the
        /// filter criteria.
        /// </summary>
        /// <param name="codeElement">Code element to analyze.</param>
        /// <returns>
        /// True if the elemet matches the filter, otherwise false.
        /// </returns>
        public bool IsMatch(ICodeElement codeElement)
        {
            bool isMatch = false;

            if (codeElement != null)
            {
                isMatch = ConditionExpressionEvaluator.Instance.Evaluate(_conditionExpression, codeElement);
            }

            return(isMatch);
        }
예제 #33
0
        /// <summary>
        /// Initializes a new instance of the Violation class.
        /// </summary>
        /// <param name="rule">The rule that triggered the violation.</param>
        /// <param name="element">The element that this violation appears in.</param>
        /// <param name="line">The line in the source code where the violation occurs.</param>
        /// <param name="message">The context message for the violation.</param>
        internal Violation(Rule rule, ICodeElement element, int line, string message)
        {
            Param.AssertNotNull(rule, "rule");
            Param.Ignore(element);
            Param.AssertGreaterThanOrEqualToZero(line, "line");
            Param.AssertNotNull(message, "message");

            this.rule = rule;
            this.element = element;
            this.line = line;
            this.message = message;

            if (this.element != null && this.element.Document != null)
            {
                this.sourceCode = this.element.Document.SourceCode;
            }
        }
 public void Add(ICodeElement codeElement)
 {
     this.root.Add(codeElement);
 }
            // todo: allow only multiple partial classes
            internal void Assign(ICodeElement codeElement)
            {
                if (codeElement == null)
                {
                    throw new ArgumentException("codeElement");
                }

                Contract.EndContractBlock();

                if (this.codeElement == null)
                {
                    this.codeElement = codeElement;
                }
                else
                {
                    if (this.codeElements == null)
                    {
                        this.codeElements = new List<ICodeElement>();
                    }

                    var typeDefinitionMetadataICodeElementAdapter = codeElement as TypeDefinitionMetadataICodeElementAdapter;
                    if (typeDefinitionMetadataICodeElementAdapter != null
                        && !typeDefinitionMetadataICodeElementAdapter.TypeDefinition.Type.HasFlag(CorTypeAttr.Import))
                    {
                        this.codeElements.Add(this.codeElement);
                        this.codeElement = codeElement;
                    }
                    else
                    {
                        this.codeElements.Add(codeElement);
                    }
                }
            }
            internal void Add(string path, ICodeElement codeElement)
            {
                if (string.IsNullOrEmpty(path))
                {
                    throw new ArgumentException("path");
                }

                if (codeElement == null)
                {
                    throw new ArgumentException("codeElement");
                }

                Contract.EndContractBlock();

                var declarations = codeElement is Namespace || codeElement is Class || codeElement is Struct
                                   || codeElement is Interface || codeElement is Enum || codeElement is Delegate
                                   || codeElement is Event || codeElement is MetadataICodeElementAdapter;

                // you should not add properties etc because you need types not parts of types like method. #
                // because Version type can be found as method Version
                // || codeElement is Field
                // || codeElement is Property
                // || codeElement is Method;
                if (declarations)
                {
                    this.Find(path, true).Assign(codeElement);
                }
            }
            internal void Add(ICodeElement codeElement)
            {
                if (codeElement == null)
                {
                    throw new ArgumentException("codeElement");
                }

                Contract.EndContractBlock();

                this.Add(codeElement.FullyQualifiedName, codeElement);
            }
        private void Process(ICodeElement codeElement)
        {
            this.Add(codeElement);

            this.Process(codeElement.ChildCodeElements);
        }
예제 #39
0
 /// <summary>
 /// Determines whether or not the specified element can be arranged by
 /// this arranger.
 /// </summary>
 /// <param name="codeElement">The code element.</param>
 /// <returns>
 /// 	<c>true</c> if this instance can arrange the specified code element; otherwise, <c>false</c>.
 /// </returns>
 public virtual bool CanArrange(ICodeElement codeElement)
 {
     return CanArrange(null, codeElement);
 }
		public virtual void Visit (ICodeElement node)
		{
			if (null == node) return;
			node.Accept (this);
		}
예제 #41
0
        /// <summary>
        /// Gets the type parent.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <returns>The Type parent.</returns>
        private static TypeElement GetTypeParent(ICodeElement element)
        {
            TypeElement parentTypeElement = element.Parent as TypeElement;

            if (parentTypeElement == null &&
                (element.Parent is GroupElement || element.Parent is RegionElement))
            {
                parentTypeElement = GetTypeParent(element.Parent);
            }

            return parentTypeElement;
        }
예제 #42
0
        /// <summary>
        /// Writes children for a block element.
        /// </summary>
        /// <param name="element">Block code element.</param>
        protected override void WriteBlockChildren(ICodeElement element)
        {
            if (element.Children.Count > 0)
            {
                Writer.WriteLine();
            }

            base.WriteBlockChildren(element);

            if (element.Children.Count > 0)
            {
                Writer.WriteLine();
            }
        }
예제 #43
0
 /// <summary>
 /// Removes a child from this element.
 /// </summary>
 /// <param name="childElement">Child element to remove.</param>
 public virtual void RemoveChild(ICodeElement childElement)
 {
     if (childElement != null && BaseChildren.Contains(childElement))
     {
         lock (_childrenLock)
         {
             if (childElement != null && BaseChildren.Contains(childElement))
             {
                 BaseChildren.Remove(childElement);
                 childElement.Parent = null;
             }
         }
     }
 }
예제 #44
0
 /// <summary>
 /// Writes children for a block element.
 /// </summary>
 /// <param name="element">Element whose children will be written.</param>
 protected virtual void WriteBlockChildren(ICodeElement element)
 {
     if (element.Children.Count == 0)
     {
         Writer.WriteLine();
     }
     else
     {
         //
         // Process all children
         //
         WriteChildren(element);
     }
 }
예제 #45
0
        /// <summary>
        /// Writes child elements.
        /// </summary>
        /// <param name="element">Element whose children will be written.</param>
        protected void WriteChildren(ICodeElement element)
        {
            if (element.Children.Count > 0)
            {
                Writer.WriteLine();
            }

            CodeWriter.WriteVisitElements(element.Children, Writer, this);

            if (element.Children.Count > 0)
            {
                Writer.WriteLine();
            }
        }
예제 #46
0
        /// <summary>
        /// Adds one violation to the given code element.
        /// </summary>
        /// <param name="element">The element that the violation appears in.</param>
        /// <param name="line">The line in the code where the violation occurs.</param>
        /// <param name="ruleName">The name of the rule that triggered the violation.</param>
        /// <param name="values">String parameters to insert into the violation string.</param>
        public void AddViolation(ICodeElement element, int line, Enum ruleName, params object[] values)
        {
            Param.Ignore(element);
            Param.Ignore(line);
            Param.RequireNotNull(ruleName, "ruleName");
            Param.Ignore(values);

            this.AddViolation(element, line, ruleName.ToString(), values);
        }
예제 #47
0
 /// <summary>
 /// Checks whether specified rule is suppressed.
 /// </summary>
 public override bool IsRuleSuppressed(ICodeElement element, Rule rule)
 {
     return false;
 }
예제 #48
0
 /// <summary>
 /// Determines whether or not this arranger can handle arrangement of
 /// the specified element.
 /// </summary>
 /// <param name="parentElement">The parent element.</param>
 /// <param name="codeElement">The code element.</param>
 /// <returns>
 /// 	<c>true</c> if this instance can arrange the specified parent element; otherwise, <c>false</c>.
 /// </returns>
 public bool CanArrange(ICodeElement parentElement, ICodeElement codeElement)
 {
     InitializeChildrenArranger();
     return _childrenArranger.CanArrange(parentElement, codeElement);
 }
예제 #49
0
        /// <summary>
        /// Adds a generic violation.
        /// </summary>
        /// <param name="element">The element to add the violation to.</param>
        /// <param name="violation">The violation to add to the element.</param>
        internal void AddViolation(ICodeElement element, Violation violation)
        {
            Param.Ignore(element, "element");
            Param.AssertNotNull(violation, "violation");

            // Add the violation to the element.
            if (element != null)
            {
                if (element.AddViolation(violation))
                {
                    this.OnViolationEncountered(new ViolationEventArgs(violation));
                }
            }
        }
예제 #50
0
        /// <summary>
        /// Adds a generic violation.
        /// </summary>
        /// <param name="element">The element to add the violation to.</param>
        /// <param name="type">The type of violation to add.</param>
        /// <param name="line">Line the violation appears on.</param>
        /// <param name="values">The string values to add to the context string.</param>
        internal void AddViolation(ICodeElement element, Rule type, int line, params object[] values)
        {
            Param.Ignore(element);
            Param.AssertNotNull(type, "type");
            Param.AssertGreaterThanZero(line, "line");
            Param.Ignore(values);

            // Build up the context string.
            StringBuilder message = new StringBuilder();
            message.AppendFormat(CultureInfo.CurrentCulture, type.Context, values);

            // Create the violation object and add it to the list.
            Violation violation = new Violation(type, element, line, message.ToString());

            // Finally, add the violation.
            this.AddViolation(element, violation);
        }
예제 #51
0
        /// <summary>
        /// Tries to parse a code element.
        /// </summary>
        /// <param name="parentElement">The parent element.</param>
        /// <param name="elementBuilder">The element builder.</param>
        /// <param name="comments">The comments.</param>
        /// <param name="attributes">The attributes.</param>
        /// <returns>Code element is succesful, otherwise null.</returns>
        private ICodeElement TryParseElement(
            ICodeElement parentElement,
            StringBuilder elementBuilder,
            ReadOnlyCollection<ICommentElement> comments,
            ReadOnlyCollection<AttributeElement> attributes)
        {
            CodeElement codeElement = null;

            string processedElementText =
                elementBuilder.ToString().Trim();

            switch (VBKeyword.Normalize(processedElementText))
            {
                case VBKeyword.Namespace:
                    codeElement = ParseNamespace();
                    break;

                case VBKeyword.Imports:
                    codeElement = ParseImport();
                    break;
            }

            if (codeElement == null)
            {
                string[] words = processedElementText.TrimEnd(
                    VBSymbol.Assignment,
                    VBSymbol.BeginParameterList).Split(
                    WhiteSpaceCharacters,
                    StringSplitOptions.RemoveEmptyEntries);

                if (words.Length > 0)
                {
                    string normalizedKeyWord = VBKeyword.Normalize(words[0]);

                    if (words.Length > 1 ||
                        normalizedKeyWord == VBKeyword.Class ||
                        normalizedKeyWord == VBKeyword.Structure ||
                        normalizedKeyWord == VBKeyword.Interface ||
                        normalizedKeyWord == VBKeyword.Enumeration ||
                        normalizedKeyWord == VBKeyword.Module ||
                        normalizedKeyWord == VBKeyword.Sub ||
                        normalizedKeyWord == VBKeyword.Function ||
                        normalizedKeyWord == VBKeyword.Property ||
                        normalizedKeyWord == VBKeyword.Delegate ||
                        normalizedKeyWord == VBKeyword.Event)
                    {
                        StringCollection wordList = new StringCollection();
                        wordList.AddRange(words);

                        StringCollection normalizedWordList = new StringCollection();
                        foreach (string word in wordList)
                        {
                            normalizedWordList.Add(VBKeyword.Normalize(word));
                        }

                        string name = string.Empty;
                        ElementType elementType;
                        CodeAccess access = CodeAccess.None;
                        MemberModifiers memberAttributes = MemberModifiers.None;
                        TypeElementType? typeElementType = null;

                        bool isAssignment = processedElementText[processedElementText.Length - 1] == VBSymbol.Assignment;
                        bool isField = normalizedWordList[normalizedWordList.Count - 1] == VBKeyword.As ||
                            isAssignment;
                        if (isField)
                        {
                            elementType = ElementType.Field;
                        }
                        else
                        {
                            GetElementType(normalizedWordList, out elementType, out typeElementType);
                        }

                        if (elementType == ElementType.Method ||
                            elementType == ElementType.Property ||
                            elementType == ElementType.Event ||
                            elementType == ElementType.Delegate ||
                            elementType == ElementType.Type ||
                            elementType == ElementType.Field)
                        {
                            access = GetAccess(normalizedWordList);
                            memberAttributes = GetMemberAttributes(normalizedWordList);
                        }

                        TypeElement parentTypeElement = parentElement as TypeElement;
                        bool inInterface = parentTypeElement != null &&
                            parentTypeElement.Type == TypeElementType.Interface;

                        switch (elementType)
                        {
                            case ElementType.Type:
                                TypeModifiers typeAttributes = (TypeModifiers)memberAttributes;
                                if (normalizedWordList.Contains(VBKeyword.Partial))
                                {
                                    typeAttributes |= TypeModifiers.Partial;
                                }

                                codeElement = ParseType(access, typeAttributes, typeElementType.Value);
                                break;

                            case ElementType.Event:
                                codeElement = ParseEvent(
                                    access, memberAttributes, normalizedWordList.Contains(VBKeyword.Custom));
                                break;

                            case ElementType.Field:
                                FieldElement fieldElement = ParseField(wordList, access, memberAttributes, isAssignment);
                                fieldElement[VBExtendedProperties.WithEvents] =
                                    normalizedWordList.Contains(VBKeyword.WithEvents);
                                fieldElement[VBExtendedProperties.Dim] =
                                    normalizedWordList.Contains(VBKeyword.Dim);
                                codeElement = fieldElement;
                                break;

                            case ElementType.Property:
                                string modifyAccess = null;
                                if (normalizedWordList.Contains(VBKeyword.ReadOnly))
                                {
                                    modifyAccess = VBKeyword.ReadOnly;
                                }
                                else if (normalizedWordList.Contains(VBKeyword.ReadWrite))
                                {
                                    modifyAccess = VBKeyword.ReadWrite;
                                }
                                else if (normalizedWordList.Contains(VBKeyword.WriteOnly))
                                {
                                    modifyAccess = VBKeyword.WriteOnly;
                                }

                                bool isDefault = normalizedWordList.Contains(VBKeyword.Default);
                                codeElement = ParseProperty(access, memberAttributes, isDefault, modifyAccess, inInterface);
                                break;

                            case ElementType.Delegate:
                                codeElement = ParseDelegate(access, memberAttributes);
                                break;

                            case ElementType.Method:
                                bool isOperator = normalizedWordList.Contains(VBKeyword.Operator);
                                OperatorType operatorType = OperatorType.None;
                                if (isOperator)
                                {
                                    operatorType = GetOperatorType(wordList);
                                }

                                bool external = false;
                                string externalModifier = null;
                                if (normalizedWordList.Contains(VBKeyword.Declare))
                                {
                                    external = true;
                                    if (normalizedWordList.Contains(VBKeyword.Ansi))
                                    {
                                        externalModifier = VBKeyword.Ansi;
                                    }
                                    else if (normalizedWordList.Contains(VBKeyword.Unicode))
                                    {
                                        externalModifier = VBKeyword.Unicode;
                                    }
                                    else if (normalizedWordList.Contains(VBKeyword.Auto))
                                    {
                                        externalModifier = VBKeyword.Auto;
                                    }
                                }

                                //
                                // Method
                                //
                                MethodElement methodElement = ParseMethod(
                                        access,
                                        memberAttributes,
                                        normalizedWordList.Contains(VBKeyword.Function),
                                        false,
                                        isOperator,
                                        operatorType,
                                        inInterface,
                                        external,
                                        externalModifier);
                                methodElement[VBExtendedProperties.Overloads] =
                                    normalizedWordList.Contains(VBKeyword.Overloads);
                                if (VBKeyword.Normalize(methodElement.Name) == VBKeyword.New)
                                {
                                    codeElement = CreateConstructor(methodElement);
                                }
                                else
                                {
                                    codeElement = methodElement;
                                }
                                break;
                        }

                        if (codeElement != null)
                        {
                            codeElement[VBExtendedProperties.Overloads] =
                                normalizedWordList.Contains(VBKeyword.Overloads);
                        }
                    }
                }
            }

            if (codeElement != null)
            {
                ApplyCommentsAndAttributes(codeElement, comments, attributes);
            }

            return codeElement;
        }
예제 #52
0
        /// <summary>
        /// Arranges the element in within the code tree represented in the specified
        /// builder.
        /// </summary>
        /// <param name="parentElement">The parent element.</param>
        /// <param name="codeElement">The code element.</param>
        public virtual void ArrangeElement(ICodeElement parentElement, ICodeElement codeElement)
        {
            if (codeElement.Children.Count > 0)
            {
                if (_childrenArranger == null)
                {
                    _childrenArranger = ElementArrangerFactory.CreateChildrenArranger(_elementConfiguration);
                }

                if (_childrenArranger != null)
                {
                    List<ICodeElement> children = new List<ICodeElement>(codeElement.Children);
                    codeElement.ClearChildren();

                    foreach (ICodeElement childElement in children)
                    {
                        ArrangeChildElement(codeElement, childElement);
                    }

                    //
                    // For condition directives, arrange the children of each node in the list.
                    //
                    ConditionDirectiveElement conditionDirective = codeElement as ConditionDirectiveElement;
                    if (conditionDirective != null)
                    {
                        //
                        // Skip the first instance since we've already arranged those child elements.
                        //
                        conditionDirective = conditionDirective.ElseCondition;
                    }
                    while (conditionDirective != null)
                    {
                        children = new List<ICodeElement>(conditionDirective.Children);
                        conditionDirective.ClearChildren();

                        foreach (ICodeElement childElement in children)
                        {
                            ArrangeChildElement(conditionDirective, childElement);
                        }
                        conditionDirective = conditionDirective.ElseCondition;
                    }
                }
            }

            if (_inserter == null)
            {
                _inserter = CreateElementInserter(
                    _elementConfiguration.ElementType,
                    _elementConfiguration.SortBy,
                    _elementConfiguration.GroupBy,
                    _parentConfiguration);
            }

            // For Type elements, if interdependent static fields are present, correct their
            // ordering.
            TypeElement typeElement = codeElement as TypeElement;
            if (typeElement != null &&
                (typeElement.Type == TypeElementType.Class || typeElement.Type == TypeElementType.Structure ||
                 typeElement.Type == TypeElementType.Module))
            {
                CorrectStaticFieldDependencies(typeElement);
            }

            _inserter.InsertElement(parentElement, codeElement);
        }
예제 #53
0
        /// <summary>
        /// Determines whether or not the specified element can be arranged by
        /// this arranger.
        /// </summary>
        /// <param name="parentElement">The parent element.</param>
        /// <param name="codeElement">The code element.</param>
        /// <returns>
        /// 	<c>true</c> if this instance can arrange the specified parent element; otherwise, <c>false</c>.
        /// </returns>
        public virtual bool CanArrange(ICodeElement parentElement, ICodeElement codeElement)
        {
            // Clone the instance and assign the parent
            ICodeElement testCodeElement = codeElement;

            if (_filter == null && _elementConfiguration.FilterBy != null)
            {
                _filter = CreateElementFilter(_elementConfiguration.FilterBy);
            }

            if (parentElement != null &&
                _filter != null && _filter.RequiredScope == ElementAttributeScope.Parent)
            {
                testCodeElement = codeElement.Clone() as ICodeElement;
                testCodeElement.Parent = parentElement.Clone() as ICodeElement;
            }

            return (_elementConfiguration.ElementType == ElementType.NotSpecified ||
                    codeElement.ElementType == _elementConfiguration.ElementType) &&
                   (_filter == null || _filter.IsMatch(testCodeElement));
        }
예제 #54
0
        /// <summary>
        /// Adds one violation to the given code element.
        /// </summary>
        /// <param name="element">The element that the violation appears in.</param>
        /// <param name="ruleName">The name of the rule that triggered the violation.</param>
        /// <param name="values">String parameters to insert into the violation context string.</param>
        public void AddViolation(ICodeElement element, string ruleName, params object[] values)
        {
            Param.Ignore(element, ruleName, values);

            int lineNumber = 0;
            if (element != null)
            {
                lineNumber = element.LineNumber;
            }

            this.AddViolation(element, lineNumber, ruleName, values);
        }
예제 #55
0
        /// <summary>
        /// Parses elements from the current point in the stream.
        /// </summary>
        /// <param name="parentElement">Parent element</param>
        /// <returns>A list of parsed code elements.</returns>
        private List<ICodeElement> ParseElements(ICodeElement parentElement)
        {
            List<ICodeElement> codeElements = new List<ICodeElement>();
            List<ICommentElement> comments = new List<ICommentElement>();
            List<AttributeElement> attributes = new List<AttributeElement>();
            Stack<ICodeElement> enclosingElementStack = new Stack<ICodeElement>();

            StringBuilder elementBuilder = new StringBuilder(DefaultBlockLength);

            char nextChar;
            bool end = false;
            bool lineContinuation = false;

            while (TryReadChar() && !end)
            {
                switch (CurrentChar)
                {
                    //
                    // Comments
                    //
                    case VBSymbol.BeginComment:
                        CommentElement commentLine = ParseCommentLine();
                        string commentDirectiveRegionName =
                                GetCommentDirectiveText(commentLine, Configuration.Formatting.Regions.CommentDirectiveBeginPattern, "Name");

                        if (commentDirectiveRegionName != null)
                        {
                            PushComments(codeElements, comments);

                            RegionElement regionElement = new RegionElement();
                            regionElement.Name = commentDirectiveRegionName;
                            enclosingElementStack.Push(regionElement);
                        }
                        else
                        {
                            commentDirectiveRegionName = GetCommentDirectiveText(commentLine, Configuration.Formatting.Regions.CommentDirectiveEndPattern, "Name");
                            if (commentDirectiveRegionName != null)
                            {
                                if (enclosingElementStack.Count == 0 ||
                                enclosingElementStack.Peek().ElementType != ElementType.Region)
                                {
                                    this.OnParseError("Unmatched end region directive");
                                }

                                ICodeElement enclosingElement = enclosingElementStack.Pop();

                                //
                                // Add any processed comments to the region or condition directive.
                                //
                                if (comments.Count > 0)
                                {
                                    foreach (ICommentElement commentElement in comments)
                                    {
                                        enclosingElement.AddChild(commentElement);
                                    }
                                    comments.Clear();
                                }

                                //
                                // Are we processing a nested region or condition directive?
                                //
                                if (enclosingElementStack.Count > 0)
                                {
                                    enclosingElementStack.Peek().AddChild(enclosingElement);
                                }
                                else
                                {
                                    codeElements.Add(enclosingElement);
                                }
                            }
                            else
                            {
                                comments.Add(commentLine);
                            }
                        }
                        break;

                    //
                    // Preprocessor
                    //
                    case VBSymbol.Preprocessor:
                        //
                        // TODO: Parse additional preprocessor directives.
                        //
                        string line = ReadLine().Trim();
                        string[] words = line.Split(WhiteSpaceCharacters, StringSplitOptions.RemoveEmptyEntries);
                        if (words.Length > 0 && VBKeyword.Normalize(words[0]) == VBKeyword.Region)
                        {
                            PushComments(codeElements, comments);

                            RegionElement regionElement = ParseRegion(line);
                            enclosingElementStack.Push(regionElement);
                        }
                        else if (words.Length > 0 &&
                            (VBKeyword.Normalize(words[0]) == VBKeyword.If ||
                            VBKeyword.Normalize(words[0]) == VBKeyword.Else ||
                            VBKeyword.Normalize(words[0]) == VBKeyword.ElseIf))
                        {
                            bool isIf;
                            ConditionDirectiveElement conditionDirective = ParseConditionDirective(line.Trim(), out isIf);

                            if (isIf)
                            {
                                enclosingElementStack.Push(conditionDirective);
                            }
                            else
                            {
                                if (enclosingElementStack.Count == 0 ||
                                    enclosingElementStack.Peek().ElementType != ElementType.ConditionDirective)
                                {
                                    this.OnParseError("Expected 'If' preprocessor directive.");
                                }
                                else
                                {
                                    ConditionDirectiveElement previousCondition =
                                        enclosingElementStack.Peek() as ConditionDirectiveElement;
                                    while (previousCondition.ElseCondition != null)
                                    {
                                        previousCondition = previousCondition.ElseCondition;
                                    }

                                    // Add the condition to the end of the condition linked list
                                    previousCondition.ElseCondition = conditionDirective;
                                }
                            }
                        }
                        else if (words.Length > 1 &&
                            VBKeyword.Normalize(words[0]) == VBKeyword.End &&
                            (VBKeyword.Normalize(words[1]) == VBKeyword.Region ||
                            VBKeyword.Normalize(words[1]) == VBKeyword.If))
                        {
                            ICodeElement enclosingElement = null;

                            if (VBKeyword.Normalize(words[1]) == VBKeyword.Region)
                            {
                                if (enclosingElementStack.Count == 0 ||
                                    enclosingElementStack.Peek().ElementType != ElementType.Region)
                                {
                                    this.OnParseError("Unmatched end region directive");
                                }
                            }
                            else if (enclosingElementStack.Count == 0 ||
                                enclosingElementStack.Peek().ElementType != ElementType.ConditionDirective)
                            {
                                this.OnParseError("Unmatched #End If");
                            }

                            enclosingElement = enclosingElementStack.Pop();

                            //
                            // If there are any attributes not associated with an element (e.g.
                            // a condition directive containing only an attribute, then
                            // throw an error as this is currently not supported.
                            //
                            if (enclosingElement.ElementType == ElementType.ConditionDirective &&
                                attributes.Count > 0)
                            {
                                this.OnParseError("Cannot arrange files with preprocessor directives containing attributes unassociated to an element");
                            }

                            if (comments.Count > 0)
                            {
                                foreach (ICommentElement commentElement in comments)
                                {
                                    enclosingElement.AddChild(commentElement);
                                }
                                comments.Clear();
                            }

                            if (enclosingElementStack.Count > 0)
                            {
                                enclosingElementStack.Peek().AddChild(enclosingElement);
                            }
                            else
                            {
                                codeElements.Add(enclosingElement);
                            }
                        }
                        else
                        {
                            this.OnParseError(
                                "Cannot arrange files with preprocessor directives " +
                                "other than #Region, #End Region and conditional compilation directives");
                        }
                        break;

                    //
                    // Attribute
                    //
                    case VBSymbol.BeginAttribute:
                        nextChar = NextChar;

                        //
                        // Parse attribute
                        //
                        AttributeElement attributeElement = ParseAttribute(comments.AsReadOnly());

                        attributes.Add(attributeElement);
                        codeElements.Add(attributeElement);
                        comments.Clear();
                        break;

                    case VBSymbol.LineContinuation:
                        if (IsWhiteSpace(PreviousChar) && IsWhiteSpace(NextChar))
                        {
                            lineContinuation = true;
                        }
                        else
                        {
                            elementBuilder.Append(CurrentChar);
                        }
                        break;

                    // Eat any unneeded whitespace
                    case ' ':
                    case '\n':
                    case '\r':
                    case '\t':
                    case ':':
                        if (elementBuilder.Length > 0)
                        {
                            string processedText = elementBuilder.ToString().Trim();
                            if (CurrentChar == '\n')
                            {
                                if (!lineContinuation)
                                {
                                    this.OnParseError(
                                        string.Format(
                                        Thread.CurrentThread.CurrentCulture,
                                        "Unhandled element text '{0}'",
                                        processedText));
                                }
                                else
                                {
                                    lineContinuation = false;
                                }
                            }

                            if (elementBuilder[elementBuilder.Length - 1] != ' ')
                            {
                                elementBuilder.Append(' ');
                            }
                        }
                        break;

                    default:
                        elementBuilder.Append(CurrentChar);

                        string upperElementText = elementBuilder.ToString().ToUpperInvariant();
                        nextChar = NextChar;

                        if (upperElementText == VBKeyword.End.ToUpperInvariant())
                        {
                            end = true;
                            elementBuilder = new StringBuilder(DefaultBlockLength);
                        }
                        else if (upperElementText == VBKeyword.Rem.ToUpperInvariant() &&
                            nextChar == ' ')
                        {
                            CommentElement remCommentLine = ParseCommentLine();
                            comments.Add(remCommentLine);
                            elementBuilder = new StringBuilder(DefaultBlockLength);
                        }
                        else if (upperElementText == VBKeyword.Option.ToUpperInvariant() &&
                            IsWhiteSpace(nextChar))
                        {
                            ICodeElement optionElement = ParseOption(comments.AsReadOnly());
                            comments.Clear();
                            codeElements.Add(optionElement);
                            elementBuilder = new StringBuilder(DefaultBlockLength);
                        }
                        else
                        {
                            if (char.IsWhiteSpace(nextChar) || VBSymbol.IsVBSymbol(CurrentChar))
                            {
                                string elementText = VBKeyword.Normalize(elementBuilder.ToString());
                                bool isImplements = elementText.StartsWith(
                                    VBKeyword.Implements, StringComparison.OrdinalIgnoreCase);
                                bool isInherits = !isImplements && elementText.StartsWith(
                                    VBKeyword.Inherits, StringComparison.OrdinalIgnoreCase);
                                TypeElement typeElement = parentElement as TypeElement;
                                if ((isImplements || isInherits) && typeElement != null)
                                {
                                    InterfaceReferenceType referenceType = InterfaceReferenceType.None;
                                    if (isInherits)
                                    {
                                        referenceType = InterfaceReferenceType.Class;
                                    }
                                    else if (isImplements)
                                    {
                                        referenceType = InterfaceReferenceType.Interface;
                                    }

                                    do
                                    {
                                        EatWhiteSpace(WhiteSpaceTypes.SpaceAndTab);
                                        if (NextChar == VBSymbol.AliasSeparator)
                                        {
                                            EatChar(VBSymbol.AliasSeparator);
                                        }

                                        string typeName = CaptureTypeName();
                                        InterfaceReference interfaceReference =
                                            new InterfaceReference(typeName, referenceType);
                                        typeElement.AddInterface(interfaceReference);
                                        EatWhiteSpace(WhiteSpaceTypes.SpaceAndTab);
                                    }
                                    while (NextChar == VBSymbol.AliasSeparator);

                                    elementBuilder = new StringBuilder(DefaultBlockLength);
                                }
                                else
                                {
                                    //
                                    // Try to parse a code element
                                    //
                                    ICodeElement element = TryParseElement(parentElement,
                                        elementBuilder, comments.AsReadOnly(), attributes.AsReadOnly());
                                    if (element != null)
                                    {
                                        if (element is CommentedElement)
                                        {
                                            UsingElement usingElement = element as UsingElement;

                                            //
                                            // If this is the first using statement, then don't attach
                                            // header comments to the element.
                                            //
                                            if (usingElement != null && parentElement == null && codeElements.Count == 0)
                                            {
                                                foreach (ICommentElement commentElement in usingElement.HeaderComments)
                                                {
                                                    if (enclosingElementStack.Count > 0)
                                                    {
                                                        enclosingElementStack.Peek().AddChild(commentElement);
                                                    }
                                                    else
                                                    {
                                                        codeElements.Add(commentElement);
                                                    }
                                                }
                                                usingElement.ClearHeaderCommentLines();
                                            }
                                            comments.Clear();
                                        }

                                        if (enclosingElementStack.Count > 0)
                                        {
                                            ICodeElement enclosingElement = enclosingElementStack.Peek();

                                            if (enclosingElement.ElementType == ElementType.ConditionDirective)
                                            {
                                                ConditionDirectiveElement conditionDirective = enclosingElement as ConditionDirectiveElement;
                                                while (conditionDirective.ElseCondition != null)
                                                {
                                                    conditionDirective = conditionDirective.ElseCondition;
                                                }

                                                enclosingElement = conditionDirective;
                                            }

                                            enclosingElement.AddChild(element);
                                        }
                                        else
                                        {
                                            codeElements.Add(element);
                                        }

                                        elementBuilder = new StringBuilder(DefaultBlockLength);

                                        if (element is IAttributedElement)
                                        {
                                            foreach (AttributeElement attribute in attributes)
                                            {
                                                codeElements.Remove(attribute);
                                            }

                                            attributes = new List<AttributeElement>();
                                        }
                                    }
                                }
                            }
                        }

                        break;
                }

                char nextCh = NextChar;
            }

            if (comments.Count > 0)
            {
                for (int commentIndex = 0; commentIndex < comments.Count; commentIndex++)
                {
                    ICommentElement comment = comments[commentIndex];
                    codeElements.Insert(commentIndex, comment);
                }
            }

            //
            // Make sure that all region elements have been closed
            //
            if (enclosingElementStack.Count > 0)
            {
                if (enclosingElementStack.Peek().ElementType == ElementType.Region)
                {
                    this.OnParseError(
                        string.Format(
                        CultureInfo.InvariantCulture,
                        "Missing end region directive for '{0}'",
                        enclosingElementStack.Peek().Name));
                }
                else
                {
                    this.OnParseError("Expected #End If");
                }
            }

            if (elementBuilder.Length > 0)
            {
                this.OnParseError(
                    string.Format(
                    Thread.CurrentThread.CurrentCulture,
                    "Unhandled element text '{0}'",
                    elementBuilder));
            }

            return codeElements;
        }
예제 #56
0
        /// <summary>
        /// Arranges the child element.
        /// </summary>
        /// <param name="codeElement">The code element.</param>
        /// <param name="childElement">The child element.</param>
        private void ArrangeChildElement(ICodeElement codeElement, ICodeElement childElement)
        {
            //
            // Region elements are ignored.  Only process their children.
            //
            RegionElement regionElement = childElement as RegionElement;
            if (regionElement != null)
            {
                List<ICodeElement> regionChildren = new List<ICodeElement>(regionElement.Children);
                regionElement.ClearChildren();

                foreach (ICodeElement regionChildElement in regionChildren)
                {
                    _childrenArranger.ArrangeElement(codeElement, regionChildElement);
                }
            }
            else
            {
                _childrenArranger.ArrangeElement(codeElement, childElement);
            }
        }
예제 #57
0
        /// <summary>
        /// Adds one violation to the given code element.
        /// </summary>
        /// <param name="element">The element that the violation appears in.</param>
        /// <param name="line">The line in the code where the violation occurs.</param>
        /// <param name="ruleName">The name of the rule that triggered the violation.</param>
        /// <param name="values">String parameters to insert into the violation string.</param>
        public void AddViolation(ICodeElement element, int line, string ruleName, params object[] values)
        {
            Param.RequireNotNull(element, "element");
            Param.Ignore(line);
            Param.RequireValidString(ruleName, "ruleName");
            Param.Ignore(values);

            // If the rule is disabled or suppressed, skip it.
            if (this.IsRuleEnabled(element.Document, ruleName))
            {
                Rule rule = this.GetRule(ruleName);
                if (rule == null)
                {
                    throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.RuleDoesNotExist, ruleName), "ruleName");
                }

                if (!this.IsRuleSuppressed(element, rule))
                {
                    // Look up this violation type.
                    this.core.AddViolation(element, rule, line, values);
                }
            }
        }
예제 #58
0
 /// <summary>
 /// Adds a child to this element.
 /// </summary>
 /// <param name="childElement">Child to add.</param>
 public virtual void AddChild(ICodeElement childElement)
 {
     if (childElement != null)
     {
         lock (_childrenLock)
         {
             if (childElement != null && !BaseChildren.Contains(childElement))
             {
                 BaseChildren.Add(childElement);
                 childElement.Parent = this;
             }
         }
     }
 }
예제 #59
0
 /// <summary>
 /// Gets a value indicating whether the given rule is suppressed for the given element.
 /// </summary>
 /// <param name="element">The element to check.</param>
 /// <param name="rule">The rule to check.</param>
 /// <returns>Returns true if the rule is suppressed; otherwise false.</returns>
 public virtual bool IsRuleSuppressed(ICodeElement element, Rule rule)
 {
     Param.Ignore(element, rule);
     return false;
 }
예제 #60
0
        /// <summary>
        /// Inserts a child element at the specified index.
        /// </summary>
        /// <param name="index">Index to insert at.</param>
        /// <param name="childElement">Element to insert.</param>
        public virtual void InsertChild(int index, ICodeElement childElement)
        {
            if (childElement != null)
            {
                lock (_childrenLock)
                {
                    if (BaseChildren.Contains(childElement))
                    {
                        BaseChildren.Remove(childElement);
                    }

                    BaseChildren.Insert(index, childElement);
                    childElement.Parent = this;
                }
            }
        }