public bool LoadResults(SourceCode sourceCode, SourceParser parser, DateTime writeTime, DateTime settingsTimeStamp)
 {
     bool flag = false;
     lock (this)
     {
         XmlNode item = null;
         XmlDocument document = this.OpenResultsCache(sourceCode, parser, out item);
         if ((document == null) || (item == null))
         {
             return flag;
         }
         try
         {
             XmlElement timeStampNode = item["settings"];
             if (((timeStampNode != null) && IsNodeUpToDate(timeStampNode, settingsTimeStamp)) && IsNodeUpToDate(item, writeTime))
             {
                 XmlNode parentNode = item.SelectSingleNode("violations");
                 if ((parentNode != null) && parser.ImportViolations(sourceCode, parentNode))
                 {
                     flag = true;
                 }
             }
         }
         catch (XmlException)
         {
         }
         if (!this.documentHash.ContainsKey(sourceCode.Project.Location))
         {
             this.documentHash.Add(sourceCode.Project.Location, document);
         }
     }
     return flag;
 }
        /// <summary>
        /// Extracts the body of the given preprocessor directive symbol, parses it, and returns the parsed expression.
        /// </summary>
        /// <param name="parser">The C# parser.</param>
        /// <param name="sourceCode">The source code containing the preprocessor directive symbol.</param>
        /// <param name="preprocessorSymbol">The preprocessor directive symbol.</param>
        /// <param name="startIndex">The index of the start of the expression body within the text string.</param>
        /// <returns>Returns the expression.</returns>
        internal static Expression GetConditionalPreprocessorBodyExpression(
             CsParser parser, SourceCode sourceCode, Symbol preprocessorSymbol, int startIndex)
        {
            Param.AssertNotNull(parser, "parser");
            Param.AssertNotNull(sourceCode, "sourceCode");
            Param.AssertNotNull(preprocessorSymbol, "preprocessorSymbol");
            Param.AssertGreaterThanOrEqualToZero(startIndex, "startIndex");
            Debug.Assert(preprocessorSymbol.SymbolType == SymbolType.PreprocessorDirective, "The symbol is not a preprocessor directive.");

            string text = preprocessorSymbol.Text.Substring(startIndex, preprocessorSymbol.Text.Length - startIndex).Trim();
            if (text.Length > 0)
            {
                using (StringReader reader = new StringReader(text))
                {
                    // Extract the symbols within this text.
                    CodeLexer lexer = new CodeLexer(parser, sourceCode, new CodeReader(reader));
                    List<Symbol> symbolList = lexer.GetSymbols(sourceCode, null);
                    SymbolManager directiveSymbols = new SymbolManager(symbolList);

                    CodeParser preprocessorBodyParser = new CodeParser(parser, directiveSymbols);

                    // Parse these symbols to create the body expression.
                    return preprocessorBodyParser.GetNextConditionalPreprocessorExpression(sourceCode);
                }
            }

            // The directive has no body.
            return null;
        }
Exemple #3
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;
 }
Exemple #4
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;
            }
        }
 private ParenthesizedExpression GetConditionalPreprocessorParenthesizedExpression(SourceCode sourceCode)
 {
     this.AdvanceToNextConditionalDirectiveCodeSymbol();
     Symbol symbol = this.symbols.Peek(1);
     if ((symbol == null) || (symbol.SymbolType != SymbolType.OpenParenthesis))
     {
         throw new SyntaxException(sourceCode, symbol.LineNumber);
     }
     this.symbols.Advance();
     Bracket item = new Bracket(symbol.Text, CsTokenType.OpenParenthesis, symbol.Location, this.symbols.Generated);
     Microsoft.StyleCop.Node<CsToken> firstItemNode = this.tokens.InsertLast(item);
     Expression nextConditionalPreprocessorExpression = this.GetNextConditionalPreprocessorExpression(sourceCode, ExpressionPrecedence.None);
     if (nextConditionalPreprocessorExpression == null)
     {
         throw new SyntaxException(sourceCode, symbol.LineNumber);
     }
     this.AdvanceToNextConditionalDirectiveCodeSymbol();
     Symbol symbol2 = this.symbols.Peek(1);
     if ((symbol2 == null) || (symbol2.SymbolType != SymbolType.CloseParenthesis))
     {
         throw new SyntaxException(sourceCode, symbol.LineNumber);
     }
     this.symbols.Advance();
     Bracket bracket2 = new Bracket(symbol2.Text, CsTokenType.CloseParenthesis, symbol2.Location, this.symbols.Generated);
     Microsoft.StyleCop.Node<CsToken> node2 = this.tokens.InsertLast(bracket2);
     item.MatchingBracketNode = node2;
     bracket2.MatchingBracketNode = firstItemNode;
     return new ParenthesizedExpression(new CsTokenList(this.tokens, firstItemNode, this.tokens.Last), nextConditionalPreprocessorExpression);
 }
 public void AddViolation(SourceCode sourceCode, int line, string ruleName, params object[] values)
 {
     Rule type = base.GetRule(ruleName);
     if (type == null)
     {
         throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.RuleDoesNotExist, new object[] { ruleName }), "ruleName");
     }
     base.Core.AddViolation(sourceCode, type, line, values);
 }
 private UnaryExpression GetConditionalPreprocessorNotExpression(SourceCode sourceCode)
 {
     this.AdvanceToNextConditionalDirectiveCodeSymbol();
     Symbol symbol = this.symbols.Peek(1);
     OperatorSymbol item = new OperatorSymbol(symbol.Text, OperatorCategory.Unary, OperatorType.Not, symbol.Location, this.symbols.Generated);
     Microsoft.StyleCop.Node<CsToken> firstItemNode = this.tokens.InsertLast(item);
     this.symbols.Advance();
     Expression nextConditionalPreprocessorExpression = this.GetNextConditionalPreprocessorExpression(sourceCode, ExpressionPrecedence.Unary);
     if ((nextConditionalPreprocessorExpression == null) || (nextConditionalPreprocessorExpression.Tokens.First == null))
     {
         throw new SyntaxException(sourceCode, symbol.LineNumber);
     }
     return new UnaryExpression(new CsTokenList(this.tokens, firstItemNode, this.tokens.Last), UnaryExpression.Operator.Not, nextConditionalPreprocessorExpression);
 }
 private void ParseAndAnalyzeDocument(SourceCode sourceCode, DocumentAnalysisStatus documentStatus)
 {
     bool flag;
     this.data.Core.SignalOutput(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Pass {0}: {1}...\n", new object[] { this.data.PassNumber + 1, sourceCode.Name }));
     CodeDocument document = documentStatus.Document;
     ICollection<SourceAnalyzer> analyzers = this.GetAnalyzersForProjectFile(sourceCode.Project, sourceCode, this.data.Core.Parsers);
     try
     {
         flag = !sourceCode.Parser.ParseFile(sourceCode, this.data.PassNumber, ref document);
     }
     catch (Exception)
     {
         string output = string.Format(CultureInfo.CurrentCulture, "Exception thrown by parser '{0}' while processing '{1}'.", new object[] { sourceCode.Parser.Name, sourceCode.Path });
         this.data.Core.SignalOutput(MessageImportance.High, output);
         throw;
     }
     if (flag)
     {
         if (document == null)
         {
             documentStatus.Complete = true;
         }
         else if (this.TestAndRunAnalyzers(document, sourceCode.Parser, analyzers, this.data.PassNumber))
         {
             documentStatus.Complete = true;
             if (document != null)
             {
                 if ((this.data.ResultsCache != null) && sourceCode.Project.WriteCache)
                 {
                     this.data.ResultsCache.SaveDocumentResults(document, sourceCode.Parser, sourceCode.Project.Settings.WriteTime);
                 }
                 document.Dispose();
                 document = null;
             }
         }
     }
     if (!documentStatus.Complete)
     {
         this.complete = false;
         if (document != null)
         {
             documentStatus.Document = document;
         }
     }
 }
 internal void AddSourceCode(SourceCode sourceCode)
 {
     if (string.IsNullOrEmpty(sourceCode.Type))
     {
         throw new ArgumentException(Strings.SourceCodeTypePropertyNotSet);
     }
     this.sourceCodes.Add(sourceCode);
 }
        /// <summary>
        /// Attempts to load results for the given document from the cache.
        /// </summary>
        /// <param name="sourceCode">The source code document to load.</param>
        /// <returns>Returns true if the results were loaded from the cache.</returns>
        private bool LoadSourceCodeFromResultsCache(SourceCode sourceCode)
        {
            Param.AssertNotNull(sourceCode, "sourceCode");

            if (!this.data.IgnoreResultsCache && this.data.Core.Environment.SupportsResultsCache && this.data.ResultsCache != null)
            {
                // Check the project to see if the cache should be ignored.
                ProjectStatus projectStatus = this.data.GetProjectStatus(sourceCode.Project);
                Debug.Assert(projectStatus != null, "There is no status for the given project.");

                if (!projectStatus.IgnoreResultsCache)
                {
                    // Get the last write time for this file.
                    DateTime lastWriteTime = sourceCode.TimeStamp;

                    // Attempt to load the file from the cache.
                    if (this.data.ResultsCache.LoadResults(
                        sourceCode, sourceCode.Parser, lastWriteTime, sourceCode.Project.Settings.WriteTime))
                    {
                        return true;
                    }
                }
            }

            return false;
        }
 private ICollection<SourceAnalyzer> GetAnalyzersForProjectFile(CodeProject project, SourceCode sourceCode, ICollection<SourceParser> parsers)
 {
     if (!string.IsNullOrEmpty(sourceCode.Type))
     {
         ProjectStatus projectStatus = this.data.GetProjectStatus(project);
         lock (projectStatus.AnalyzerLists)
         {
             ICollection<SourceAnalyzer> is2 = null;
             if (!projectStatus.AnalyzerLists.TryGetValue(sourceCode.Type, out is2))
             {
                 is2 = DiscoverAnalyzerList(this.data.Core, project, parsers);
                 projectStatus.AnalyzerLists.Add(sourceCode.Type, is2);
                 foreach (SourceAnalyzer analyzer in is2)
                 {
                     this.data.Core.SignalOutput(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Loaded Analyzer: {0}...", new object[] { analyzer.Name }));
                 }
             }
             return is2;
         }
     }
     return null;
 }
        /// <summary>
        /// Adds one violation to the given source code document.
        /// </summary>
        /// <param name="sourceCode">The source code document 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(SourceCode sourceCode, int line, string ruleName, params object[] values)
        {
            Param.Ignore(sourceCode, line, ruleName, values);

            Rule rule = this.GetRule(ruleName);
            if (rule == null)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.RuleDoesNotExist, ruleName), "ruleName");
            }

            // Look up this violation type.
            this.Core.AddViolation(sourceCode, rule, line, values);
        }
        /// <summary>
        /// Adds one violation to the given source code document.
        /// </summary>
        /// <param name="sourceCode">The source code document 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(SourceCode sourceCode, int line, Enum ruleName, params object[] values)
        {
            Param.Ignore(sourceCode);
            Param.Ignore(line);
            Param.RequireNotNull(ruleName, "ruleName");
            Param.Ignore(values);

            this.AddViolation(sourceCode, line, ruleName.ToString(), values);
        }
        /// <summary>
        /// Adds a generic violation.
        /// </summary>
        /// <param name="sourceCode">The file to add the violation to.</param>
        /// <param name="violation">The violation to add to the element.</param>
        internal void AddViolation(SourceCode sourceCode, Violation violation)
        {
            Param.Ignore(sourceCode, "sourceCode");
            Param.AssertNotNull(violation, "violation");

            bool signal = true;

            // Add the violation to the file.
            if (sourceCode != null)
            {
                if (!sourceCode.AddViolation(violation))
                {
                    signal = false;
                }
            }

            // Signal that there is a new violation.
            if (signal)
            {
                this.OnViolationEncountered(new ViolationEventArgs(violation));
            }
        }
        /// <summary>
        /// Adds a generic violation.
        /// </summary>
        /// <param name="sourceCode">The source code document 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(SourceCode sourceCode, Rule type, int line, params object[] values)
        {
            Param.Ignore(sourceCode);
            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, sourceCode, line, message.ToString());

            // Finally, add the violation.
            this.AddViolation(sourceCode, violation);
        }
Exemple #16
0
 /// <summary>
 /// Parses a source code document.
 /// </summary>
 /// <param name="sourceCode">The source code to parse.</param>
 /// <param name="passNumber">The current pass number.</param>
 /// <param name="document">The parsed representation of the file.</param>
 /// <returns>Returns false if no further analyzation should be done on this file.</returns>
 public override bool ParseFile(SourceCode sourceCode, int passNumber, ref CodeDocument document)
 {
     Param.Ignore(sourceCode, passNumber, document);
     throw new NotImplementedException();
 }
 /// <summary>
 /// Reads the next expression from a conditional preprocessor directive.
 /// </summary>
 /// <param name="sourceCode">The source code.</param>
 /// <returns>Returns the expression.</returns>
 internal Expression GetNextConditionalPreprocessorExpression(SourceCode sourceCode)
 {
     Param.AssertNotNull(sourceCode, "sourceCode");
     return this.GetNextConditionalPreprocessorExpression(sourceCode, ExpressionPrecedence.None);
 }
 private XmlDocument OpenResultsCache(SourceCode sourceCode, SourceParser parser, out XmlNode item)
 {
     item = null;
     XmlDocument document = null;
     try
     {
         lock (this)
         {
             if (this.documentHash.TryGetValue(sourceCode.Project.Location, out document))
             {
                 item = document.DocumentElement.SelectSingleNode(string.Format(CultureInfo.InvariantCulture, "sourcecode[@name=\"{0}\"][@parser=\"{1}\"]", new object[] { sourceCode.Name, parser.Id }));
                 return document;
             }
             document = this.core.Environment.LoadResultsCache(sourceCode.Project.Location);
             if (document == null)
             {
                 return document;
             }
             XmlElement element = document["stylecopresultscache"]["version"];
             if (element.InnerText == "10")
             {
                 item = document.DocumentElement.SelectSingleNode(string.Format(CultureInfo.InvariantCulture, "sourcecode[@name=\"{0}\"][@parser=\"{1}\"]", new object[] { sourceCode.Name, parser.Id }));
                 return document;
             }
             return null;
         }
     }
     catch (XmlException)
     {
         document = null;
     }
     catch (NullReferenceException)
     {
         document = null;
     }
     return document;
 }
Exemple #19
0
 internal Expression GetNextConditionalPreprocessorExpression(SourceCode sourceCode)
 {
     return this.GetNextConditionalPreprocessorExpression(sourceCode, ExpressionPrecedence.None);
 }
 public abstract bool ParseFile(SourceCode sourceCode, int passNumber, ref CodeDocument document);
Exemple #21
0
        private Expression GetNextConditionalPreprocessorExpression(SourceCode sourceCode, ExpressionPrecedence previousPrecedence)
        {
            this.AdvanceToNextConditionalDirectiveCodeSymbol();
            Expression leftSide = null;
            Symbol symbol = this.symbols.Peek(1);
            if (symbol != null)
            {
                CsToken token;
                Microsoft.StyleCop.Node<CsToken> node;
                SymbolType symbolType = symbol.SymbolType;
                if (symbolType <= SymbolType.Not)
                {
                    switch (symbolType)
                    {
                        case SymbolType.OpenParenthesis:
                            leftSide = this.GetConditionalPreprocessorParenthesizedExpression(sourceCode);
                            goto Label_012D;

                        case SymbolType.Not:
                            leftSide = this.GetConditionalPreprocessorNotExpression(sourceCode);
                            goto Label_012D;
                    }
                    goto Label_010E;
                }
                switch (symbolType)
                {
                    case SymbolType.False:
                        this.symbols.Advance();
                        token = new CsToken(symbol.Text, CsTokenType.False, symbol.Location, this.symbols.Generated);
                        node = this.tokens.InsertLast(token);
                        leftSide = new LiteralExpression(new CsTokenList(this.tokens, node, node), node);
                        goto Label_012D;

                    case SymbolType.True:
                        this.symbols.Advance();
                        token = new CsToken(symbol.Text, CsTokenType.True, symbol.Location, this.symbols.Generated);
                        node = this.tokens.InsertLast(token);
                        leftSide = new LiteralExpression(new CsTokenList(this.tokens, node, node), node);
                        goto Label_012D;
                }
                if (symbolType != SymbolType.Other)
                {
                    goto Label_010E;
                }
                leftSide = this.GetConditionalPreprocessorConstantExpression();
            }
            goto Label_012D;
            Label_010E:
            throw new SyntaxException(sourceCode, symbol.LineNumber);
            Label_012D:
            while (leftSide != null)
            {
                Expression expression2 = this.GetConditionalPreprocessorExpressionExtension(sourceCode, leftSide, previousPrecedence);
                if (expression2 == null)
                {
                    return leftSide;
                }
                leftSide = expression2;
            }
            return leftSide;
        }
        /// <summary>
        /// Imports the cached violations under the given node.
        /// </summary>
        /// <param name="sourceCode">The source code containing the violations.</param>
        /// <param name="parentNode">The parent xml node containing the list of violations.</param>
        /// <returns>Returns true if all the data was loaded successfully from the file.</returns>
        internal bool ImportViolations(SourceCode sourceCode, XmlNode parentNode)
        {
            Param.AssertNotNull(sourceCode, "sourceCode");
            Param.AssertNotNull(parentNode, "parentNode");

            bool success = true;

            try
            {
                XmlNodeList violations = parentNode.SelectNodes("violation");
                if (violations != null && violations.Count > 0)
                {
                    foreach (XmlNode violationNode in violations)
                    {
                        // Get the violation data from the xml node.
                        XmlNode nameSpace = violationNode.SelectSingleNode("@namespace");
                        XmlNode ruleName = violationNode.SelectSingleNode("@rule");
                        XmlNode ruleCheckId = violationNode.SelectSingleNode("@ruleCheckId");
                        XmlNode context = violationNode.SelectSingleNode("context");
                        XmlNode lineNumber = violationNode.SelectSingleNode("line");
                        XmlNode warning = violationNode.SelectSingleNode("warning");

                        // Create a Rule object representing this data.
                        Rule rule = new Rule(
                            ruleName.InnerText,
                            nameSpace.InnerText,
                            ruleCheckId.InnerText,
                            context.InnerText,
                            Convert.ToBoolean(warning.InnerText, CultureInfo.InvariantCulture));

                        // Create a Violation object representing this data.
                        Violation violation = new Violation(
                            rule,
                            sourceCode,
                            Convert.ToInt32(lineNumber.InnerText, null),
                            context.InnerText);

                        this.AddViolation(violation);
                    }
                }
            }
            catch (ArgumentException)
            {
                success = false;
            }
            catch (XmlException)
            {
                success = false;
            }
            catch (FormatException)
            {
                success = false;
            }
            catch (OverflowException)
            {
                success = false;
            }

            return success;
        }
        /// <summary>
        /// Parses and analyzes the given document.
        /// </summary>
        /// <param name="sourceCode">The document to parse and analyze.</param>
        /// <param name="documentStatus">The current status of the documents.</param>
        private void ParseAndAnalyzeDocument(SourceCode sourceCode, DocumentAnalysisStatus documentStatus)
        {
            Param.AssertNotNull(sourceCode, "sourceCode");
            Param.AssertNotNull(documentStatus, "documentStatus");

            // Signal the output for this document.
            this.data.Core.SignalOutput(
                MessageImportance.Low,
                string.Format(CultureInfo.CurrentCulture, "Pass {0}: {1}...\n", this.data.PassNumber + 1, sourceCode.Name));

            // Extract the document to parse.
            CodeDocument parsedDocument = documentStatus.Document;

            // Get or load the analyzer list.
            IEnumerable<SourceAnalyzer> analyzers = sourceCode.Settings.EnabledAnalyzers;

            // Parse the document.
            bool parsingCompleted;
            try
            {
                parsingCompleted = !sourceCode.Parser.ParseFile(sourceCode, this.data.PassNumber, ref parsedDocument);
            }
            catch (System.Exception)
            {
                string details = string.Format(
                        CultureInfo.CurrentCulture,
                        "Exception thrown by parser '{0}' while processing '{1}'.",
                        sourceCode.Parser.Name,
                        sourceCode.Path);

                this.data.Core.SignalOutput(MessageImportance.High, details);
                throw;
            }

            if (parsingCompleted)
            {
                if (parsedDocument == null)
                {
                    documentStatus.Complete = true;
                }
                else if (this.TestAndRunAnalyzers(parsedDocument, sourceCode.Parser, analyzers, this.data.PassNumber))
                {
                    // Analysis of this document is completed.
                    documentStatus.Complete = true;

                    // Save the cache for this document and dispose it.
                    if (parsedDocument != null)
                    {
                        if (this.data.ResultsCache != null && sourceCode.Project.WriteCache)
                        {
                            this.data.ResultsCache.SaveDocumentResults(parsedDocument, sourceCode.Parser, sourceCode.Settings.WriteTime);
                        }

                        parsedDocument.Dispose();
                        parsedDocument = null;
                    }
                }
            }

            if (!documentStatus.Complete)
            {
                // Analysis of this document is not complete, so we will need to
                // perform another round of analysis after this one is finished.
                this.complete = false;

                // Cache the document if there is one.
                if (parsedDocument != null)
                {
                    documentStatus.Document = parsedDocument;
                }
            }
        }
        /// <summary>
        /// Reads the next expression from a conditional preprocessor directive.
        /// </summary>
        /// <param name="sourceCode">The source code.</param>
        /// <param name="previousPrecedence">The precedence of the expression just before this one.</param>
        /// <returns>Returns the expression.</returns>
        private Expression GetNextConditionalPreprocessorExpression(SourceCode sourceCode, ExpressionPrecedence previousPrecedence)
        {
            Param.AssertNotNull(sourceCode, "sourceCode");
            Param.Ignore(previousPrecedence);

            var parentReference = new Reference<ICodePart>();

            // Move past comments and whitepace.
            this.AdvanceToNextConditionalDirectiveCodeSymbol(parentReference);

            // Saves the next expression.
            Expression expression = null;

            // Get the next symbol.
            Symbol symbol = this.symbols.Peek(1);
            if (symbol != null)
            {
                switch (symbol.SymbolType)
                {
                    case SymbolType.Other:
                        expression = this.GetConditionalPreprocessorConstantExpression();
                        break;

                    case SymbolType.Not:
                        expression = this.GetConditionalPreprocessorNotExpression(sourceCode, parentReference);
                        break;

                    case SymbolType.OpenParenthesis:
                        expression = this.GetConditionalPreprocessorParenthesizedExpression(sourceCode, parentReference);
                        break;

                    case SymbolType.False:
                        this.symbols.Advance();

                        var falseExpressionReference = new Reference<ICodePart>();
                        CsToken token = new CsToken(symbol.Text, CsTokenType.False, symbol.Location, falseExpressionReference, this.symbols.Generated);
                        Node<CsToken> tokenNode = this.tokens.InsertLast(token);
                        expression = new LiteralExpression(new CsTokenList(this.tokens, tokenNode, tokenNode), tokenNode);
                        falseExpressionReference.Target = expression;
                        break;

                    case SymbolType.True:
                        this.symbols.Advance();

                        var trueExpressionReference = new Reference<ICodePart>();
                        token = new CsToken(symbol.Text, CsTokenType.True, symbol.Location, trueExpressionReference, this.symbols.Generated);
                        tokenNode = this.tokens.InsertLast(token);
                        expression = new LiteralExpression(new CsTokenList(this.tokens, tokenNode, tokenNode), tokenNode);
                        trueExpressionReference.Target = expression;
                        break;

                    default:
                        throw new SyntaxException(sourceCode, symbol.LineNumber);
                }
            }

            // Gather up all extensions to this expression.
            while (expression != null)
            {
                var expressionReference = new Reference<ICodePart>(expression);

                // Check if there is an extension to this expression.
                Expression extension = this.GetConditionalPreprocessorExpressionExtension(
                    sourceCode, expressionReference, expression, previousPrecedence);
                if (extension != null)
                {
                    // The larger expression is what we want to return here.
                    expression = extension;
                }
                else
                {
                    // There are no more extensions.
                    break;
                }
            }

            // Return the expression.
            return expression;
        }
 private bool LoadSourceCodeFromResultsCache(SourceCode sourceCode)
 {
     if ((!this.data.IgnoreResultsCache && this.data.Core.Environment.SupportsResultsCache) && ((this.data.ResultsCache != null) && !this.data.GetProjectStatus(sourceCode.Project).IgnoreResultsCache))
     {
         DateTime timeStamp = sourceCode.TimeStamp;
         if (this.data.ResultsCache.LoadResults(sourceCode, sourceCode.Parser, timeStamp, sourceCode.Project.Settings.WriteTime))
         {
             return true;
         }
     }
     return false;
 }
Exemple #26
0
        private RelationalExpression GetConditionalPreprocessorEqualityExpression(SourceCode sourceCode, Expression leftHandSide, ExpressionPrecedence previousPrecedence)
        {
            RelationalExpression expression = null;
            OperatorType type;
            OperatorCategory category;
            RelationalExpression.Operator equalTo;
            this.AdvanceToNextConditionalDirectiveCodeSymbol();
            Symbol symbol = this.symbols.Peek(1);
            if (symbol == null)
            {
                throw new SyntaxException(sourceCode, symbol.LineNumber);
            }
            GetOperatorType(symbol, out type, out category);
            OperatorSymbol item = new OperatorSymbol(symbol.Text, category, type, symbol.Location, this.symbols.Generated);
            ExpressionPrecedence operatorPrecedence = GetOperatorPrecedence(item.SymbolType);
            if (!CheckPrecedence(previousPrecedence, operatorPrecedence))
            {
                return expression;
            }
            this.symbols.Advance();
            this.tokens.Add(item);
            Expression nextConditionalPreprocessorExpression = this.GetNextConditionalPreprocessorExpression(sourceCode, operatorPrecedence);
            if (nextConditionalPreprocessorExpression == null)
            {
                throw new SyntaxException(sourceCode, item.LineNumber);
            }
            CsTokenList tokens = new CsTokenList(this.tokens, leftHandSide.Tokens.First, this.tokens.Last);
            switch (item.SymbolType)
            {
                case OperatorType.ConditionalEquals:
                    equalTo = RelationalExpression.Operator.EqualTo;
                    break;

                case OperatorType.NotEquals:
                    equalTo = RelationalExpression.Operator.NotEqualTo;
                    break;

                default:
                    throw new SyntaxException(sourceCode, item.LineNumber);
            }
            return new RelationalExpression(tokens, equalTo, leftHandSide, nextConditionalPreprocessorExpression);
        }
 public DocumentAnalysisStatus GetDocumentStatus(SourceCode sourceCode)
 {
     DocumentAnalysisStatus status;
     if (!this.sourceCodeInstanceStatus.TryGetValue(sourceCode, out status))
     {
         status = new DocumentAnalysisStatus();
         this.sourceCodeInstanceStatus.Add(sourceCode, status);
     }
     return status;
 }
Exemple #28
0
        private Expression GetConditionalPreprocessorExpressionExtension(SourceCode sourceCode, Expression leftSide, ExpressionPrecedence previousPrecedence)
        {
            OperatorType type;
            OperatorCategory category;
            this.AdvanceToNextConditionalDirectiveCodeSymbol();
            Symbol symbol = this.symbols.Peek(1);
            if (((symbol != null) && (symbol.SymbolType != SymbolType.CloseParenthesis)) && GetOperatorType(symbol, out type, out category))
            {
                switch (type)
                {
                    case OperatorType.ConditionalEquals:
                    case OperatorType.NotEquals:
                        return this.GetConditionalPreprocessorEqualityExpression(sourceCode, leftSide, previousPrecedence);

                    case OperatorType.ConditionalAnd:
                    case OperatorType.ConditionalOr:
                        return this.GetConditionalPreprocessorAndOrExpression(sourceCode, leftSide, previousPrecedence);
                }
            }
            return null;
        }
Exemple #29
0
 internal static Expression GetConditionalPreprocessorBodyExpression(CsParser parser, SourceCode sourceCode, Symbol preprocessorSymbol, int startIndex)
 {
     string s = preprocessorSymbol.Text.Substring(startIndex, preprocessorSymbol.Text.Length - startIndex).Trim();
     if (s.Length > 0)
     {
         StringReader code = new StringReader(s);
         CodeLexer lexer = new CodeLexer(parser, sourceCode, new CodeReader(code));
         SymbolManager symbols = new SymbolManager(lexer.GetSymbols(sourceCode, null));
         CodeParser parser2 = new CodeParser(parser, symbols);
         return parser2.GetNextConditionalPreprocessorExpression(sourceCode);
     }
     return null;
 }
 internal bool ImportViolations(SourceCode sourceCode, XmlNode parentNode)
 {
     bool flag = true;
     try
     {
         XmlNodeList list = parentNode.SelectNodes("violation");
         if ((list != null) && (list.Count > 0))
         {
             foreach (XmlNode node in list)
             {
                 XmlNode node2 = node.SelectSingleNode("@namespace");
                 XmlNode node3 = node.SelectSingleNode("@rule");
                 XmlNode node4 = node.SelectSingleNode("@ruleCheckId");
                 XmlNode node5 = node.SelectSingleNode("context");
                 XmlNode node6 = node.SelectSingleNode("line");
                 XmlNode node7 = node.SelectSingleNode("warning");
                 Rule rule = new Rule(node3.InnerText, node2.InnerText, node4.InnerText, node5.InnerText, Convert.ToBoolean(node7.InnerText, CultureInfo.InvariantCulture));
                 Violation violation = new Violation(rule, sourceCode, Convert.ToInt32(node6.InnerText, (IFormatProvider) null), node5.InnerText);
                 this.AddViolation(violation);
             }
         }
         return flag;
     }
     catch (ArgumentException)
     {
         flag = false;
     }
     catch (XmlException)
     {
         flag = false;
     }
     catch (FormatException)
     {
         flag = false;
     }
     catch (OverflowException)
     {
         flag = false;
     }
     return flag;
 }