Exemplo n.º 1
0
        /// <summary>
        /// Checks the methods within the given document.
        /// </summary>
        /// <param name="document">The document to check.</param>
        public override void AnalyzeDocument(CodeDocument document)
        {
            Param.RequireNotNull(document, "document");

            /*
            // Get the autoupdate setting.
            string flag = null;
            if (document.File.Project.LocalSettings != null)
            {
                flag = document.File.Project.LocalSettings.GetProperty("ParamCheckAutomatic");
                if (flag == null && document.File.Project.GlobalSettings != null)
                {
                    flag = document.File.Project.GlobalSettings.GetProperty("ParamCheckAutomatic");
                }
            }

            this.autoUpdate = (flag != null && flag == "1");
             */

            // Analyze the document.
            CsDocument csdocument = (CsDocument)document;
            if (csdocument.RootElement != null && !csdocument.RootElement.Generated)
            {
                this.ProcessElement(csdocument, csdocument.RootElement);
            }
        }
 public override void AnalyzeDocument(CodeDocument document)
 {
     Param.RequireNotNull(document, "document");
     CsDocument document2 = (CsDocument) document;
     if ((document2.RootElement != null) && !document2.RootElement.Generated)
     {
         TopLevelElements context = new TopLevelElements();
         document2.WalkDocument<TopLevelElements>(new CodeWalkerElementVisitor<TopLevelElements>(this.ProcessElement), new CodeWalkerStatementVisitor<TopLevelElements>(this.ProcessStatement), new CodeWalkerExpressionVisitor<TopLevelElements>(this.ProcessExpression), context);
         if (context.Classes.Count > 1)
         {
             string fullNamespaceName = string.Empty;
             foreach (Class class2 in context.Classes)
             {
                 if (!class2.Declaration.ContainsModifier(new CsTokenType[] { CsTokenType.Partial }) || (!string.IsNullOrEmpty(fullNamespaceName) && (string.Compare(fullNamespaceName, class2.FullNamespaceName, StringComparison.Ordinal) != 0)))
                 {
                     base.AddViolation(class2, 1, Microsoft.StyleCop.CSharp.Rules.FileMayOnlyContainASingleClass, new object[0]);
                     break;
                 }
                 fullNamespaceName = class2.FullNamespaceName;
             }
         }
         if (context.Namespaces.Count > 1)
         {
             base.AddViolation(document2.RootElement, Microsoft.StyleCop.CSharp.Rules.FileMayOnlyContainASingleNamespace, new object[0]);
         }
     }
 }
Exemplo n.º 3
0
        /// <summary>
        /// Checks the methods within the given document.
        /// </summary>
        /// <param name="document">The document to check.</param>
        public override void AnalyzeDocument(CodeDocument document)
        {
            Param.RequireNotNull(document, "document");

            CsDocument csdocument = (CsDocument)document;

            Settings settings = new Settings();
            settings.DoNotUseRegions = this.IsRuleEnabled(document, Rules.DoNotUseRegions.ToString());
            settings.DoNotPlaceRegionsWithinElements = this.IsRuleEnabled(document, Rules.DoNotPlaceRegionsWithinElements.ToString());

            if (csdocument.RootElement != null && !csdocument.RootElement.Generated)
            {
                // Checks various formatting rules.
                csdocument.WalkDocument(
                    new CodeWalkerElementVisitor<object>(this.ProcessElement),
                    null,
                    new CodeWalkerExpressionVisitor<object>(this.ProcessExpression),
                    settings);

                // Check statement formatting rules.
                this.CheckStatementFormattingRulesForElement(csdocument.RootElement);

                // Check the class member rules.
                this.CheckClassMemberRulesForElements(csdocument.RootElement, null, null);

                // Looks for empty comments.
                this.CheckForEmptyComments(csdocument.RootElement);

                // Checks the usage of the built-in types and empty strings.
                this.IterateTokenList(csdocument, settings);
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Checks the order of the elements within the given document.
        /// </summary>
        /// <param name="document">The document to check.</param>
        public override void AnalyzeDocument(CodeDocument document)
        {
            Param.RequireNotNull(document, "document");

            CsDocument csdocument = (CsDocument)document;

            if (csdocument.RootElement != null)
            {
                // Get the value of the GeneratedCodeElementOrder property.
                bool checkGeneratedCode = OrderingRules.GeneratedCodeElementOrderDefaultValueProperty;

                if (document.Settings != null)
                {
                    BooleanProperty setting = this.GetSetting(document.Settings, OrderingRules.GeneratedCodeElementOrderProperty) as BooleanProperty;
                    if (setting != null)
                    {
                        checkGeneratedCode = setting.Value;
                    }

                    // Check the rest of the elements.
                    this.ProcessElements(csdocument.RootElement, checkGeneratedCode);
                }

                this.CheckUsingDirectiveOrder(csdocument.RootElement);
            }
        }
Exemplo n.º 5
0
 public override bool ParseFile(SourceCode sourceCode, int passNumber, ref CodeDocument document)
 {
     Param.RequireNotNull(sourceCode, "sourceCode");
     Param.RequireGreaterThanOrEqualToZero(passNumber, "passNumber");
     if (passNumber == 0)
     {
         try
         {
             using (TextReader reader = sourceCode.Read())
             {
                 if (reader == null)
                 {
                     base.AddViolation(sourceCode, 1, Microsoft.StyleCop.CSharp.Rules.FileMustBeReadable, new object[0]);
                 }
                 else
                 {
                     CodeLexer lexer = new CodeLexer(this, sourceCode, new CodeReader(reader));
                     CodeParser parser = new CodeParser(this, lexer);
                     parser.ParseDocument();
                     document = parser.Document;
                 }
             }
         }
         catch (SyntaxException exception)
         {
             base.AddViolation(exception.SourceCode, exception.LineNumber, Microsoft.StyleCop.CSharp.Rules.SyntaxException, new object[] { exception.Message });
             CsDocument document2 = new CsDocument(sourceCode, this);
             document2.FileHeader = new FileHeader(string.Empty);
             document = document2;
         }
     }
     return false;
 }
Exemplo n.º 6
0
        /// <summary>
        /// Analyzes source document.
        /// </summary>
        public void AnalyzeDocument(CodeDocument document)
        {
            CustomRulesSettings settings = new CustomRulesSettings();
            settings.Initialize(m_parent, document);

            CsDocument doc = (CsDocument)document;
            AnalyzePlainText(doc, settings);
            AnalyzeElements(doc.RootElement.ChildElements, settings);
        }
Exemplo n.º 7
0
 public override void AnalyzeDocument(CodeDocument document)
 {
     Param.RequireNotNull(document, "document");
     var csDocument = (CsDocument)document;
     if ((csDocument.RootElement != null) && !csDocument.RootElement.Generated)
     {
         csDocument.WalkDocument(VisitElement);
     }
 }
Exemplo n.º 8
0
 public override void AnalyzeDocument(CodeDocument document)
 {
     Param.RequireNotNull(document, "document");
     CsDocument document2 = (CsDocument) document;
     if ((document2.RootElement != null) && !document2.RootElement.Generated)
     {
         this.CheckSpacing(document2.RootElement, document2.Tokens, false);
     }
 }
Exemplo n.º 9
0
 public override void AnalyzeDocument(CodeDocument document)
 {
     Param.RequireNotNull(document, "document");
     CsDocument document2 = (CsDocument) document;
     if ((document2.RootElement != null) && !document2.RootElement.Generated)
     {
         Dictionary<string, string> prefixes = this.GetPrefixes(document.Settings);
         this.ProcessElement(document2.RootElement, prefixes, false);
     }
 }
Exemplo n.º 10
0
 public override void AnalyzeDocument(CodeDocument document)
 {
     Param.RequireNotNull(document, "document");
     CsDocument document2 = (CsDocument) document;
     if ((document2.RootElement != null) && !document2.RootElement.Generated)
     {
         document2.WalkDocument(new CodeWalkerElementVisitor<object>(this.VisitElement), new CodeWalkerStatementVisitor<object>(this.CheckStatementCurlyBracketPlacement), new CodeWalkerExpressionVisitor<object>(this.CheckExpressionCurlyBracketPlacement));
         this.CheckLineSpacing(document2);
     }
 }
        /// <summary>
        /// Analyzes source document.
        /// </summary>
        public void AnalyzeDocument(CodeDocument document)
        {
            CheckOriginalRule(document, Constants.LayoutRulesAnalyzerId, Rules.ElementMustNotBeOnSingleLine);
            CheckOriginalRule(document, Constants.LayoutRulesAnalyzerId, Rules.OpeningCurlyBracketsMustNotBePrecededByBlankLine);
            CheckOriginalRule(document, Constants.LayoutRulesAnalyzerId, Rules.ClosingCurlyBracketMustBeFollowedByBlankLine);
            CheckOriginalRule(document, Constants.LayoutRulesAnalyzerId, Rules.ElementsMustBeSeparatedByBlankLine);

            m_customNamingAnalyzer.AnalyzeDocument(document);
            m_customLayoutAnalyzer.AnalyzeDocument(document);
            m_customDocumentationAnalyzer.AnalyzeDocument(document);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Checks whether specified rule is enabled.
        /// </summary>
        public override bool IsRuleEnabled(CodeDocument document, string ruleName)
        {
            if (SpecialRunningParameters != null)
            {
                if (!String.IsNullOrEmpty(SpecialRunningParameters.OnlyEnabledRule))
                {
                    return ruleName == SpecialRunningParameters.OnlyEnabledRule;
                }
            }

            return base.IsRuleEnabled(document, ruleName);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Analyzes source document.
        /// </summary>
        public override void AnalyzeDocument(CodeDocument document)
        {
            CsDocument doc = (CsDocument)document;
            if (doc.RootElement.Generated)
                return;

            if (IsRuleEnabled(document, Rules.AdvancedNamingRules.ToString()))
                m_advancedNamingRules.AnalyzeDocument(document);

            m_extendedOriginalRules.AnalyzeDocument(document);
            m_moreCustomRules.AnalyzeDocument(document);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Checks the placement of brackets within the given document.
        /// </summary>
        /// <param name="document">The document to check.</param>
        public override void AnalyzeDocument(CodeDocument document)
        {
            Param.RequireNotNull(document, "document");

            CsDocument csdocument = (CsDocument)document;

            if (csdocument.RootElement != null && !csdocument.RootElement.Generated)
            {
                // Check placement of curly brackets.
                csdocument.WalkDocument(
                    new CodeWalkerElementVisitor<object>(this.VisitElement),
                    new CodeWalkerStatementVisitor<object>(this.CheckStatementCurlyBracketPlacement),
                    new CodeWalkerExpressionVisitor<object>(this.CheckExpressionCurlyBracketPlacement));

                // Check line spacing rules.
                this.CheckLineSpacing(csdocument);
            }
        }
Exemplo n.º 15
0
 public override void AnalyzeDocument(CodeDocument document)
 {
     Param.RequireNotNull(document, "document");
     CsDocument document2 = (CsDocument) document;
     if (document2.RootElement != null)
     {
         bool checkGeneratedCode = true;
         if (document.Settings != null)
         {
             BooleanProperty setting = base.GetSetting(document.Settings, "GeneratedCodeElementOrder") as BooleanProperty;
             if (setting != null)
             {
                 checkGeneratedCode = setting.Value;
             }
             this.ProcessElements(document2.RootElement, checkGeneratedCode);
         }
         this.CheckUsingDirectiveOrder(document2.RootElement);
     }
 }
        /// <summary>
        /// Returns a value indicating whether to delay analysis of this document until the next pass.
        /// </summary>
        /// <param name="document">The document to analyze.</param>
        /// <param name="passNumber">The current pass number.</param>
        /// <returns>Returns true if analysis should be delayed.</returns>
        public override bool DelayAnalysis(CodeDocument document, int passNumber)
        {
            Param.RequireNotNull(document, "document");
            Param.Ignore(passNumber);

            bool delay = false;

            // We sometimes delay pass zero, but never pass one.
            if (passNumber == 0)
            {
                // Get the root element.
                CsDocument csdocument = document as CsDocument;
                if (csdocument != null && csdocument.RootElement != null)
                {
                    // If the element has any partial classes, structs, or interfaces, delay. This is due
                    // to the fact that the class members rules need knowledge about all parts of the class
                    // in order to find all class members.
                    delay = this.ContainsPartialMembers(csdocument.RootElement);
                }
            }

            return delay;
        }
Exemplo n.º 17
0
        /// <summary>
        /// Clears the analyzer tags for the given document and all of its children.
        /// </summary>
        /// <param name="document">The document to clear.</param>
        /// <remarks>
        /// <para>During each analysis run, analyzers can store data within each analyzed document for
        /// later use. Analyzers store and retrieve this data using the <see cref="SourceAnalyzer.GetDocumentData"/>
        /// and <see cref="SourceAnalyzer.SetDocumentData"/> methods.</para>
        /// <para>After all analysis has been completed, this analyzer data should be cleared so that
        /// it will not conflict with the next analysis. This method can be called to clear all
        /// analyzer data which was stored during the previous analysis.</para>
        /// </remarks>
        internal static void ClearAnalyzerTags(CodeDocument document)
        {
            Param.AssertNotNull(document, "document");

            if (document != null && document.DocumentContents != null)
            {
                document.DocumentContents.ClearAnalyzerTags();
            }
        }
Exemplo n.º 18
0
 public override bool SkipAnalysisForDocument(CodeDocument document)
 {
     Param.RequireNotNull(document, "document");
     BooleanProperty setting = base.GetSetting(document.Settings, "AnalyzeDesignerFiles") as BooleanProperty;
     bool flag = true;
     if (setting != null)
     {
         flag = setting.Value;
     }
     if (flag || !document.SourceCode.Name.EndsWith(".Designer.cs", StringComparison.OrdinalIgnoreCase))
     {
         BooleanProperty property2 = base.GetSetting(document.Settings, "AnalyzeGeneratedFiles") as BooleanProperty;
         bool flag2 = false;
         if (property2 != null)
         {
             flag2 = property2.Value;
         }
         if (flag2 || (!document.SourceCode.Name.EndsWith(".g.cs", StringComparison.OrdinalIgnoreCase) && !document.SourceCode.Name.EndsWith(".generated.cs", StringComparison.OrdinalIgnoreCase)))
         {
             return false;
         }
     }
     return true;
 }
Exemplo n.º 19
0
 /// <summary>
 /// Checks whether specified rule is enabled.
 /// </summary>
 public override bool IsRuleEnabled(CodeDocument document, string ruleName)
 {
     return true;
 }
        /// <summary>
        /// Initializes settings from specified document.
        /// </summary>
        public void Initialize(SourceAnalyzer analyzer, CodeDocument document)
        {
            m_names.Clear();
            m_examples.Clear();
            m_regulars.Clear();
            m_derivings.Clear();

            string abbreviations = SettingsManager.GetValue<string>(
                analyzer,
                document.Settings,
                NamingSettings.Abbreviations);

            string words = SettingsManager.GetValue<string>(
                analyzer,
                document.Settings,
                NamingSettings.Words);

            foreach (string setting in NamingSettings.GetCommon())
            {
                string name = SettingsManager.GetFriendlyName(analyzer, setting);
                m_names.Add(setting, name);

                string value = SettingsManager.GetValue<string>(analyzer, document.Settings, setting);
                if (String.IsNullOrEmpty(value))
                {
                    m_examples.Add(setting, null);
                    m_regulars.Add(setting, null);
                }
                else
                {
                    string example = NamingMacro.BuildExample(value);
                    m_examples.Add(setting, example);

                    Regex regex = NamingMacro.BuildRegex(value, abbreviations, words);
                    m_regulars.Add(setting, regex);
                }
            }

            string derivings = SettingsManager.GetValue<string>(
                analyzer,
                document.Settings,
                NamingSettings.Derivings);

            m_derivings.AddRange(
                derivings.Split(
                    new[] { ' ' },
                    StringSplitOptions.RemoveEmptyEntries));
        }
Exemplo n.º 21
0
 private bool TestAndRunAnalyzers(CodeDocument document, SourceParser parser, ICollection<SourceAnalyzer> analyzers, int passNumber)
 {
     if (analyzers == null)
     {
         return true;
     }
     bool flag = false;
     foreach (SourceAnalyzer analyzer in analyzers)
     {
         if (analyzer.DelayAnalysis(document, passNumber))
         {
             flag = true;
             break;
         }
     }
     if (!flag)
     {
         this.RunAnalyzers(document, parser, analyzers);
     }
     return !flag;
 }
Exemplo n.º 22
0
 public override bool IsRuleEnabled(CodeDocument document, string ruleName)
 {
     Param.RequireNotNull(document, "document");
     Param.RequireValidString(ruleName, "ruleName");
     if (this.enabledRules != null)
     {
         Dictionary<string, Rule> dictionary = null;
         if (this.enabledRules.TryGetValue(document.SourceCode.Project, out dictionary))
         {
             return dictionary.ContainsKey(ruleName);
         }
     }
     return base.IsRuleEnabled(document, ruleName);
 }
Exemplo n.º 23
0
 private void RunAnalyzers(CodeDocument document, SourceParser parser, ICollection<SourceAnalyzer> analyzers)
 {
     if (analyzers != null)
     {
         if (parser.SkipAnalysisForDocument(document))
         {
             this.data.Core.SignalOutput(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Skipping {0}...", new object[] { document.SourceCode.Name }));
         }
         else
         {
             foreach (SourceAnalyzer analyzer in analyzers)
             {
                 if (this.data.Core.Cancel)
                 {
                     return;
                 }
                 SourceParser.ClearAnalyzerTags(document);
                 try
                 {
                     analyzer.AnalyzeDocument(document);
                     continue;
                 }
                 catch (Exception)
                 {
                     string output = string.Format(CultureInfo.CurrentCulture, "Exception thrown by analyzer '{0}' while processing '{1}'.", new object[] { analyzer.Name, document.SourceCode.Path });
                     this.data.Core.SignalOutput(MessageImportance.High, output);
                     throw;
                 }
             }
         }
     }
 }
Exemplo n.º 24
0
        /// <summary>
        /// Checks the element headers within the given document.
        /// </summary>
        /// <param name="document">The document to check.</param>
        public override void AnalyzeDocument(CodeDocument document)
        {
            Param.RequireNotNull(document, "document");

            CsDocument csdocument = (CsDocument)document;

            if (csdocument.RootElement != null && !csdocument.RootElement.Generated)
            {
                this.CheckElementDocumentation(csdocument);
                this.CheckFileHeader(csdocument);
                this.CheckSingleLineComments(csdocument.RootElement);
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Runs the analyzers against the given document.
        /// </summary>
        /// <param name="document">The document to analyze.</param>
        /// <param name="parser">The parser that created the document.</param>
        /// <param name="analyzers">The analyzers to run against the document.</param>
        /// <param name="passNumber">The current pass number.</param>
        /// <returns>Returns true if analysis was run, or false if analysis was delayed until the next pass.</returns>
        private bool TestAndRunAnalyzers(
            CodeDocument document, SourceParser parser, IEnumerable<SourceAnalyzer> analyzers, int passNumber)
        {
            Param.AssertNotNull(document, "document");
            Param.AssertNotNull(parser, "parser");
            Param.Ignore(analyzers);
            Param.Ignore(passNumber);

            if (analyzers == null)
            {
                return true;
            }

            // Determine whether any of the analyzers wish to delay parsing until the next pass.
            bool delay = false;
            foreach (SourceAnalyzer analyzer in analyzers)
            {
                if (analyzer.DelayAnalysis(document, passNumber))
                {
                    delay = true;
                    break;
                }
            }

            if (!delay)
            {
                this.RunAnalyzers(document, parser, analyzers);
            }

            return !delay;
        }
Exemplo n.º 26
0
        /// <summary>
        /// Runs the list of analyzers against the given document.
        /// </summary>
        /// <param name="document">The document to analyze.</param>
        /// <param name="parser">The parser that created the document.</param>
        /// <param name="analyzers">The list of analyzsers to run against the document.</param>
        private void RunAnalyzers(
            CodeDocument document, SourceParser parser, IEnumerable<SourceAnalyzer> analyzers)
        {
            Param.AssertNotNull(document, "document");
            Param.AssertNotNull(parser, "parser");
            Param.Ignore(analyzers, "analyzers");

            if (analyzers != null)
            {
                if (parser.SkipAnalysisForDocument(document))
                {
                    this.data.Core.SignalOutput(
                        MessageImportance.Normal,
                        string.Format(CultureInfo.CurrentCulture, "Skipping {0}...", document.SourceCode.Name));
                }
                else
                {
                    // Loop through each of the analyzers attached to the parser.
                    foreach (SourceAnalyzer analyzer in analyzers)
                    {
                        // Make sure the user hasn't cancelled us.
                        if (this.data.Core.Cancel)
                        {
                            break;
                        }

                        SourceParser.ClearAnalyzerTags(document);
                        try
                        {
                            analyzer.AnalyzeDocument(document);
                        }
                        catch (System.Exception)
                        {
                            string details = string.Format(
                                    CultureInfo.CurrentCulture,
                                    "Exception thrown by analyzer '{0}' while processing '{1}'.",
                                    analyzer.Name,
                                    document.SourceCode.Path);

                            this.data.Core.SignalOutput(MessageImportance.High, details);
                            throw;
                        }
                    }
                }
            }
        }
Exemplo n.º 27
0
 public abstract bool ParseFile(SourceCode sourceCode, int passNumber, ref CodeDocument document);
Exemplo n.º 28
0
        /// <summary>
        /// Indicates whether to skip analyzis on the given document.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <returns>Returns true to skip analysis on the document.</returns>
        public virtual bool SkipAnalysisForDocument(CodeDocument document)
        {
            Param.Ignore(document);

            return false;
        }
Exemplo n.º 29
0
 /// <summary>
 /// Gets a value indicating whether the given rule is enabled for the given document.
 /// </summary>
 /// <param name="document">The document being analyzed.</param>
 /// <param name="ruleName">The rule to check.</param>
 /// <returns>Returns true if the rule is enabled; otherwise false.</returns>
 public virtual bool IsRuleEnabled(CodeDocument document, string ruleName)
 {
     Param.Ignore(document, ruleName);
     return true;
 }
Exemplo n.º 30
0
        /// <summary>
        /// Exports the violations found within this document into the given xml node.
        /// </summary>
        /// <param name="document">The document containing the violations.</param>
        /// <param name="violationsDocument">The xml document in which to store the violation information.</param>
        /// <param name="parentNode">The parent node within this xml document under which to store the violation information.</param>
        internal static void ExportViolations(CodeDocument document, XmlDocument violationsDocument, XmlNode parentNode)
        {
            Param.AssertNotNull(document, "document");
            Param.AssertNotNull(violationsDocument, "violationsDocument");
            Param.AssertNotNull(parentNode, "parentNode");

            if (document.DocumentContents != null)
            {
                SourceParser.ExportElementViolations(document.DocumentContents, violationsDocument, parentNode);
            }

            if (document.SourceCode != null)
            {
                // Add the violations from the source code.
                foreach (Violation violation in document.SourceCode.Violations)
                {
                    SourceParser.ExportViolation(violation, violationsDocument, parentNode);
                }
            }
        }