/// <summary> /// Gets element by name. /// </summary> private static CsElement GetElementByName(CsDocument document, string name) { return GetElementByName( document.RootElement.ChildElements, name, false); }
/// <summary> /// Gets element by name. /// </summary> private static CsElement GetElementByQualifiedName(CsDocument document, string qualifiedName) { return GetElementByName( document.RootElement.ChildElements, qualifiedName, true); }
internal Method(CsDocument document, CsElement parent, XmlHeader header, ICollection<Microsoft.StyleCop.CSharp.Attribute> attributes, Declaration declaration, TypeToken returnType, IList<Parameter> parameters, ICollection<TypeParameterConstraintClause> typeConstraints, bool unsafeCode, bool generated) : base(document, parent, ElementType.Method, "method " + declaration.Name, header, attributes, declaration, unsafeCode, generated) { this.returnType = returnType; this.parameters = parameters; this.typeConstraints = typeConstraints; if ((this.parameters.Count > 0) && base.Declaration.ContainsModifier(new CsTokenType[] { CsTokenType.Static })) { foreach (Parameter parameter in this.parameters) { if ((parameter.Modifiers & ParameterModifiers.This) != ParameterModifiers.None) { this.extensionMethod = true; } break; } } base.QualifiedName = CodeParser.AddQualifications(this.parameters, base.QualifiedName); if ((base.Declaration.Name.IndexOf(".", StringComparison.Ordinal) > -1) && !base.Declaration.Name.StartsWith("this.", StringComparison.Ordinal)) { base.Declaration.AccessModifierType = AccessModifierType.Public; } if (typeConstraints != null) { foreach (TypeParameterConstraintClause clause in typeConstraints) { clause.ParentElement = this; } } }
/// <summary> /// Initializes a new instance of the ClassBase class. /// </summary> /// <param name="document"> /// The document that contains the element. /// </param> /// <param name="parent"> /// The parent of the element. /// </param> /// <param name="type"> /// The element type. /// </param> /// <param name="name"> /// The name of this element. /// </param> /// <param name="header"> /// The Xml header for this element. /// </param> /// <param name="attributes"> /// The list of attributes attached to this element. /// </param> /// <param name="declaration"> /// The declaration code for this element. /// </param> /// <param name="typeConstraints"> /// The list of type constraints on the element. /// </param> /// <param name="unsafeCode"> /// Indicates whether the element resides within a block of unsafe code. /// </param> /// <param name="generated"> /// Indicates whether the code element was generated or written by hand. /// </param> internal ClassBase( CsDocument document, CsElement parent, ElementType type, string name, XmlHeader header, ICollection<Attribute> attributes, Declaration declaration, ICollection<TypeParameterConstraintClause> typeConstraints, bool unsafeCode, bool generated) : base(document, parent, type, name, header, attributes, declaration, unsafeCode, generated) { Param.Ignore(document, parent, type, name, header, attributes, declaration, typeConstraints, unsafeCode, generated); this.typeConstraints = typeConstraints; // Set the parent of the type constraint clauses. if (typeConstraints != null) { Debug.Assert(typeConstraints.IsReadOnly, "The typeconstraints collection should be read-only."); foreach (TypeParameterConstraintClause constraint in typeConstraints) { constraint.ParentElement = this; } } }
/// <summary> /// Initializes a new instance of the Property class. /// </summary> /// <param name="document"> /// The document that contains the element. /// </param> /// <param name="parent"> /// The parent of the element. /// </param> /// <param name="header"> /// The Xml header for this element. /// </param> /// <param name="attributes"> /// The list of attributes attached to this element. /// </param> /// <param name="declaration"> /// The declaration code for this element. /// </param> /// <param name="returnType"> /// The property return type. /// </param> /// <param name="unsafeCode"> /// Indicates whether the element resides within a block of unsafe code. /// </param> /// <param name="generated"> /// Indicates whether the code element was generated or written by hand. /// </param> internal Property( CsDocument document, CsElement parent, XmlHeader header, ICollection<Attribute> attributes, Declaration declaration, TypeToken returnType, bool unsafeCode, bool generated) : base(document, parent, ElementType.Property, "property " + declaration.Name, header, attributes, declaration, unsafeCode, generated) { Param.AssertNotNull(document, "document"); Param.AssertNotNull(parent, "parent"); Param.Ignore(header); Param.Ignore(attributes); Param.AssertNotNull(declaration, "declaration"); Param.AssertNotNull(returnType, "returnType"); Param.Ignore(unsafeCode); Param.Ignore(generated); this.returnType = returnType; // If this is an explicit interface member implementation and our access modifier // is currently set to private because we don't have one, then it should be public instead. if (this.Declaration.Name.IndexOf(".", StringComparison.Ordinal) > -1 && !this.Declaration.Name.StartsWith("this.", StringComparison.Ordinal)) { this.Declaration.AccessModifierType = AccessModifierType.Public; } }
/// <summary> /// Analyzes source code as plain text. /// </summary> private void AnalyzePlainText(CsDocument document, CustomRulesSettings settings) { string source; using (TextReader reader = document.SourceCode.Read()) { source = reader.ReadToEnd(); } List<string> lines = new List<string>( source.Split( new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None)); for (int i = 0; i < lines.Count; i++) { int currentLineNumber = i + 1; string currentLine = lines[i]; string previousLine = i > 0 ? lines[i - 1] : null; CheckLineEnding(document, currentLine, currentLineNumber); CheckIndentation(document, currentLine, previousLine, currentLineNumber, settings); CheckLineLength(document, currentLine, currentLineNumber, settings); } CheckLastLine(document, source, lines.Count, settings); }
internal Field(CsDocument document, CsElement parent, XmlHeader header, ICollection<Microsoft.StyleCop.CSharp.Attribute> attributes, Declaration declaration, TypeToken fieldType, bool unsafeCode, bool generated) : base(document, parent, ElementType.Field, "field " + declaration.Name, header, attributes, declaration, unsafeCode, generated) { this.type = fieldType; this.isConst = base.Declaration.ContainsModifier(new CsTokenType[] { CsTokenType.Const }); this.isReadOnly = base.Declaration.ContainsModifier(new CsTokenType[] { CsTokenType.Readonly }); }
/// <summary> /// Initializes a new instance of the EnumItem class. /// </summary> /// <param name="document">The document that contains the element.</param> /// <param name="parent">The parent of the element.</param> /// <param name="header">The Xml header for this element.</param> /// <param name="attributes">The list of attributes attached to this element.</param> /// <param name="declaration">The declaration code for this element.</param> /// <param name="initialization">The initialization expression, if there is one.</param> /// <param name="unsafeCode">Indicates whether the element resides within a block of unsafe code.</param> /// <param name="generated">Indicates whether the code element was generated or written by hand.</param> internal EnumItem( CsDocument document, Enum parent, XmlHeader header, ICollection<Attribute> attributes, Declaration declaration, Expression initialization, bool unsafeCode, bool generated) : base(document, parent, ElementType.EnumItem, "enum item " + declaration.Name, header, attributes, declaration, unsafeCode, generated) { Param.Ignore(document, parent, header, attributes, declaration, initialization, unsafeCode, generated); this.initialization = initialization; if (this.initialization != null) { this.AddExpression(this.initialization); } }
private void CheckLineLength(CsDocument csharpDocument) { var lengthProperty = GetSetting(csharpDocument.Settings, LineLengthProperty) as IntProperty; if (lengthProperty == null) { return; } using (var reader = csharpDocument.SourceCode.Read()) { string line; var lineNumber = 0; while ((line = reader.ReadLine()) != null) { lineNumber++; if (line.Length > lengthProperty.Value) { AddViolation( csharpDocument.RootElement, lineNumber, RuleName, lengthProperty.Value); } } } }
/// <summary> /// Initializes a new instance of the UsingDirective class. /// </summary> /// <param name="document">The document that contains the element.</param> /// <param name="parent">The parent of the element.</param> /// <param name="declaration">The declaration code for this element.</param> /// <param name="generated">Indicates whether the code element was generated or written by hand.</param> /// <param name="namespace">The namespace being used.</param> /// <param name="alias">Optional alias for the namespace, if any.</param> internal UsingDirective( CsDocument document, CsElement parent, Declaration declaration, bool generated, string @namespace, string alias) : base(document, parent, ElementType.UsingDirective, "using " + declaration.Name, null, null, declaration, false, generated) { Param.Ignore(document); Param.Ignore(parent); Param.Ignore(declaration); Param.Ignore(generated); Param.AssertValidString(@namespace, "namespace"); Param.Ignore(alias); this.namespaceType = @namespace; if (alias != null) { this.alias = alias; } }
/// <summary> /// Initializes a new instance of the Accessor class. /// </summary> /// <param name="document"> /// The document that contains the element. /// </param> /// <param name="parent"> /// The parent of the element. /// </param> /// <param name="accessorType"> /// The type of the accessor. /// </param> /// <param name="header"> /// The Xml header for this element. /// </param> /// <param name="attributes"> /// The list of attributes attached to this element. /// </param> /// <param name="declaration"> /// The declaration code for this element. /// </param> /// <param name="unsafeCode"> /// Indicates whether the element resides within a block of unsafe code. /// </param> /// <param name="generated"> /// Indicates whether the code element was generated or written by hand. /// </param> internal Accessor( CsDocument document, CsElement parent, AccessorType accessorType, XmlHeader header, ICollection<Attribute> attributes, Declaration declaration, bool unsafeCode, bool generated) : base(document, parent, ElementType.Accessor, declaration.Name + " accessor", header, attributes, declaration, unsafeCode, generated) { Param.AssertNotNull(document, "document"); Param.AssertNotNull(parent, "parent"); Param.Ignore(accessorType); Param.Ignore(header); Param.Ignore(attributes); Param.AssertNotNull(declaration, "declaration"); Param.Ignore(unsafeCode); Param.Ignore(generated); this.accessorType = accessorType; // Make sure the type and name match. Debug.Assert( (accessorType == AccessorType.Get && declaration.Name == "get") || (accessorType == AccessorType.Set && declaration.Name == "set") || (accessorType == AccessorType.Add && declaration.Name == "add") || (accessorType == AccessorType.Remove && declaration.Name == "remove"), "The accessor type does not match its name."); this.FillDetails(parent); }
/// <summary> /// Gets first code element at specified line number. /// </summary> /// <remarks> /// Returns object because it is ICodeElement for 4.4 and CodeElement for 4.3. /// </remarks> public static object GetElementByLine(CsDocument document, int lineNumber) { object[] args = new object[] { lineNumber, null }; document.WalkDocument(FindByLineElementVisitor, null, args); return args[1]; }
/// <summary> /// Initializes a new instance of the CodeUnitProxy class. /// </summary> /// <param name="document">The parent document.</param> public CodeUnitProxy(CsDocument document) { Param.Ignore(document); this.document = document; this.children = new CodeUnitCollection(this); }
/// <summary> /// Initializes a new instance of the DocumentRoot class. /// </summary> /// <param name="document"> /// The document that this element belongs to. /// </param> /// <param name="declaration"> /// The declaration class for this element. /// </param> /// <param name="generated"> /// Indicates whether the element contains generated code. /// </param> internal DocumentRoot(CsDocument document, Declaration declaration, bool generated) : base(document, null, ElementType.Root, Strings.DocumentRoot, null, null, declaration, false, generated) { Param.AssertNotNull(document, "document"); Param.AssertNotNull(declaration, "declaration"); Param.Ignore(generated); }
/// <summary> /// Initializes a new instance of the Field class. /// </summary> /// <param name="document">The documenent that contains the element.</param> /// <param name="parent">The parent of the element.</param> /// <param name="header">The Xml header for this element.</param> /// <param name="attributes">The list of attributes attached to this element.</param> /// <param name="declaration">The declaration code for this element.</param> /// <param name="fieldType">The type of the field.</param> /// <param name="unsafeCode">Indicates whether the element resides within a block of unsafe code.</param> /// <param name="generated">Indicates whether the code element was generated or written by hand.</param> internal Field( CsDocument document, CsElement parent, XmlHeader header, ICollection<Attribute> attributes, Declaration declaration, TypeToken fieldType, bool unsafeCode, bool generated) : base(document, parent, ElementType.Field, "field " + declaration.Name, header, attributes, declaration, unsafeCode, generated) { Param.AssertNotNull(document, "document"); Param.AssertNotNull(parent, "parent"); Param.Ignore(header); Param.Ignore(attributes); Param.AssertNotNull(declaration, "declaration"); Param.AssertNotNull(fieldType, "fieldType"); Param.Ignore(unsafeCode); Param.Ignore(generated); this.type = fieldType; // Determine whether the item is const or readonly. this.isConst = this.Declaration.ContainsModifier(CsTokenType.Const); this.isReadOnly = this.Declaration.ContainsModifier(CsTokenType.Readonly); }
/// <summary> /// Initializes a new instance of the Destructor class. /// </summary> /// <param name="document">The documenent that contains the element.</param> /// <param name="parent">The parent of the element.</param> /// <param name="header">The Xml header for this element.</param> /// <param name="attributes">The list of attributes attached to this element.</param> /// <param name="declaration">The declaration code for this element.</param> /// <param name="unsafeCode">Indicates whether the element resides within a block of unsafe code.</param> /// <param name="generated">Indicates whether the code element was generated or written by hand.</param> internal Destructor( CsDocument document, CsElement parent, XmlHeader header, ICollection<Attribute> attributes, Declaration declaration, bool unsafeCode, bool generated) : base(document, parent, ElementType.Destructor, "destructor " + declaration.Name, header, attributes, declaration, unsafeCode, generated) { Param.AssertNotNull(document, "document"); Param.AssertNotNull(parent, "parent"); Param.Ignore(header); Param.Ignore(attributes); Param.AssertNotNull(declaration, "declaration"); Param.Ignore(unsafeCode); Param.Ignore(generated); // Static destructors are always public. if (this.Declaration.ContainsModifier(CsTokenType.Static)) { this.Declaration.AccessModifierType = AccessModifierType.Public; } }
/// <summary> /// Initializes a new instance of the MultiplicationOperator class. /// </summary> /// <param name="document">The parent document.</param> /// <param name="text">The text of the item.</param> /// <param name="location">The location of the item.</param> /// <param name="generated">Indicates whether the item is generated.</param> internal MultiplicationOperator(CsDocument document, string text, CodeLocation location, bool generated) : base(document, text, OperatorCategory.Arithmetic, OperatorType.Multiplication, location, generated) { Param.AssertNotNull(document, "document"); Param.AssertValidString(text, "text"); Param.AssertNotNull(location, "location"); Param.Ignore(generated); }
/// <summary> /// Initializes a new instance of the RegionDirective class. /// </summary> /// <param name="document">The parent document.</param> /// <param name="text">The line text.</param> /// <param name="location">The location of the preprocessor in the code.</param> /// <param name="generated">Indicates whether the preprocessor lies within a block of generated code.</param> internal RegionDirective(CsDocument document, string text, CodeLocation location, bool generated) : base(document, text, PreprocessorType.Region, location, generated) { Param.AssertNotNull(document, "document"); Param.AssertValidString(text, "text"); Param.AssertNotNull(location, "location"); Param.Ignore(generated); }
/// <summary> /// Initializes a new instance of the PointerOperator class. /// </summary> /// <param name="document">The parent document.</param> /// <param name="text">The text of the item.</param> /// <param name="location">The location of the item.</param> /// <param name="generated">Indicates whether the item is generated.</param> internal PointerOperator(CsDocument document, string text, CodeLocation location, bool generated) : base(document, text, OperatorCategory.Reference, OperatorType.Pointer, location, generated) { Param.AssertNotNull(document, "document"); Param.AssertValidString(text, "text"); Param.AssertNotNull(location, "location"); Param.Ignore(generated); }
/// <summary> /// Initializes a new instance of the ConditionalQuestionMarkOperator class. /// </summary> /// <param name="document">The parent document.</param> /// <param name="text">The text of the item.</param> /// <param name="location">The location of the item.</param> /// <param name="generated">Indicates whether the item is generated.</param> internal ConditionalQuestionMarkOperator(CsDocument document, string text, CodeLocation location, bool generated) : base(document, text, OperatorCategory.Conditional, OperatorType.ConditionalQuestionMark, location, generated) { Param.AssertNotNull(document, "document"); Param.AssertValidString(text, "text"); Param.AssertNotNull(location, "location"); Param.Ignore(generated); }
/// <summary> /// Initializes a new instance of the Whitespace class. /// </summary> /// <param name="document">The parent document.</param> /// <param name="text">The whitespace text.</param> internal Whitespace(CsDocument document, string text) : base(document, LexicalElementType.WhiteSpace) { Param.AssertNotNull(document, "document"); Param.AssertValidString(text, "text"); this.Text = text; }
/// <summary> /// Initializes a new instance of the SimpleToken class. /// </summary> /// <param name="document">The parent document.</param> /// <param name="text">The token string.</param> /// <param name="tokenType">The token type.</param> /// <param name="location">The location of the token within the code document.</param> /// <param name="generated">True if the token is inside of a block of generated code.</param> internal SimpleToken(CsDocument document, string text, int tokenType, CodeLocation location, bool generated) : base(new CodeUnitProxy(document), tokenType, location) { Param.Ignore(document, text, tokenType, location, generated); this.Text = text; this.Generated = generated; }
/// <summary> /// Initializes a new instance of the BitwiseComplementOperator class. /// </summary> /// <param name="document">The parent document.</param> /// <param name="text">The text of the item.</param> /// <param name="location">The location of the item.</param> /// <param name="generated">Indicates whether the item is generated.</param> internal BitwiseComplementOperator(CsDocument document, string text, CodeLocation location, bool generated) : base(document, text, OperatorCategory.Unary, OperatorType.BitwiseComplement, location, generated) { Param.AssertNotNull(document, "document"); Param.AssertValidString(text, "text"); Param.AssertNotNull(location, "location"); Param.Ignore(generated); }
/// <summary> /// Initializes a new instance of the SimpleLexicalElement class. /// </summary> /// <param name="document">The parent document.</param> /// <param name="lexicalElementType">The lexical element type.</param> internal SimpleLexicalElement(CsDocument document, int lexicalElementType) : base(new CodeUnitProxy(document), lexicalElementType) { Param.AssertNotNull(document, "document"); Param.Ignore(lexicalElementType); CsLanguageService.Debug.Assert(System.Enum.IsDefined(typeof(LexicalElementType), this.LexicalElementType), "The type is invalid."); }
/// <summary> /// Initializes a new instance of the ParamsToken class. /// </summary> /// <param name="document">The parent document.</param> /// <param name="text">The text of the item.</param> /// <param name="location">The location of the item.</param> /// <param name="generated">Indicates whether the item is generated.</param> internal ParamsToken(CsDocument document, string text, CodeLocation location, bool generated) : base(document, text, TokenType.Params, location, generated) { Param.AssertNotNull(document, "document"); Param.AssertValidString(text, "text"); Param.AssertNotNull(location, "location"); Param.Ignore(generated); }
/// <summary> /// Initializes a new instance of the LogicalAndOperator class. /// </summary> /// <param name="document">The parent document.</param> /// <param name="text">The text of the item.</param> /// <param name="location">The location of the item.</param> /// <param name="generated">Indicates whether the item is generated.</param> internal LogicalAndOperator(CsDocument document, string text, CodeLocation location, bool generated) : base(document, text, OperatorCategory.Logical, OperatorType.LogicalAnd, location, generated) { Param.AssertNotNull(document, "document"); Param.AssertValidString(text, "text"); Param.AssertNotNull(location, "location"); Param.Ignore(generated); }
/// <summary> /// Initializes a new instance of the ElementHeaderLine class. /// </summary> /// <param name="document">The parent document.</param> /// <param name="text">The text of the item.</param> /// <param name="location">The location of the item.</param> /// <param name="generated">Indicates whether the item is generated.</param> internal ElementHeaderLine(CsDocument document, string text, CodeLocation location, bool generated) : base(document, text, CommentType.ElementHeaderLine, location, generated) { Param.AssertNotNull(document, "document"); Param.AssertValidString(text, "text"); Param.AssertNotNull(location, "location"); Param.Ignore(generated); }
/// <summary> /// Initializes a new instance of the XorEqualsOperator class. /// </summary> /// <param name="document">The parent document.</param> /// <param name="text">The text of the item.</param> /// <param name="location">The location of the item.</param> /// <param name="generated">Indicates whether the item is generated.</param> internal XorEqualsOperator(CsDocument document, string text, CodeLocation location, bool generated) : base(document, text, OperatorCategory.Assignment, OperatorType.XorEquals, location, generated) { Param.AssertNotNull(document, "document"); Param.AssertValidString(text, "text"); Param.AssertNotNull(location, "location"); Param.Ignore(generated); }
public void Get_Local_Declarations() { CsDocument document = BuildCodeDocument(Source.LocalDeclarations); CsElement element = GetElementByName(document, "constructor Class1"); List <LocalDeclarationItem> declarations = CodeHelper.GetLocalDeclarations(element); Assert.AreEqual(50, declarations.Count); AssertLocalDeclaration("a1", false, 15, declarations[0]); AssertLocalDeclaration("a2", false, 15, declarations[1]); AssertLocalDeclaration("a3", false, 15, declarations[2]); AssertLocalDeclaration("b1", true, 16, declarations[3]); AssertLocalDeclaration("b2", true, 16, declarations[4]); AssertLocalDeclaration("ex1", false, 20, declarations[5]); AssertLocalDeclaration("ex2", false, 24, declarations[6]); AssertLocalDeclaration("i1", false, 30, declarations[7]); AssertLocalDeclaration("i2", false, 31, declarations[8]); AssertLocalDeclaration("i3", false, 32, declarations[9]); AssertLocalDeclaration("j1", false, 35, declarations[10]); AssertLocalDeclaration("j2", false, 35, declarations[11]); AssertLocalDeclaration("j3", false, 36, declarations[12]); AssertLocalDeclaration("a1", false, 40, declarations[13]); AssertLocalDeclaration("a2", false, 40, declarations[14]); AssertLocalDeclaration("a3", false, 40, declarations[15]); AssertLocalDeclaration("b1", true, 41, declarations[16]); AssertLocalDeclaration("b2", true, 41, declarations[17]); AssertLocalDeclaration("s1", false, 46, declarations[18]); AssertLocalDeclaration("s2", false, 47, declarations[19]); AssertLocalDeclaration("a1", false, 49, declarations[20]); AssertLocalDeclaration("a2", false, 49, declarations[21]); AssertLocalDeclaration("a3", false, 49, declarations[22]); AssertLocalDeclaration("b1", true, 50, declarations[23]); AssertLocalDeclaration("b2", true, 50, declarations[24]); AssertLocalDeclaration("ms1", false, 55, declarations[25]); AssertLocalDeclaration("ms2", false, 56, declarations[26]); AssertLocalDeclaration("ms3", false, 57, declarations[27]); AssertLocalDeclaration("a1", false, 59, declarations[28]); AssertLocalDeclaration("a2", false, 59, declarations[29]); AssertLocalDeclaration("a3", false, 59, declarations[30]); AssertLocalDeclaration("b1", true, 60, declarations[31]); AssertLocalDeclaration("b2", true, 60, declarations[32]); AssertLocalDeclaration("c1", false, 66, declarations[33]); AssertLocalDeclaration("c2", false, 66, declarations[34]); AssertLocalDeclaration("c3", false, 67, declarations[35]); AssertLocalDeclaration("d1", true, 69, declarations[36]); AssertLocalDeclaration("d2", true, 70, declarations[37]); AssertLocalDeclaration("thread1", false, 74, declarations[38]); AssertLocalDeclaration("a1", false, 77, declarations[39]); AssertLocalDeclaration("a2", false, 78, declarations[40]); AssertLocalDeclaration("a3", false, 79, declarations[41]); AssertLocalDeclaration("b1", true, 81, declarations[42]); AssertLocalDeclaration("b2", true, 82, declarations[43]); AssertLocalDeclaration("thread2", false, 87, declarations[44]); AssertLocalDeclaration("a1", false, 89, declarations[45]); AssertLocalDeclaration("a2", false, 89, declarations[46]); AssertLocalDeclaration("a3", false, 90, declarations[47]); AssertLocalDeclaration("b1", true, 91, declarations[48]); AssertLocalDeclaration("b2", true, 92, declarations[49]); }
public override void AnalyzeDocument(CodeDocument document) { CsDocument csdocument = (CsDocument)document; if (csdocument.RootElement != null && !csdocument.RootElement.Generated) { csdocument.WalkDocument(new CodeWalkerElementVisitor <object>(VisitElement)); } }
/// <summary> /// Initializes a new instance of the EmptyElement class. /// </summary> /// <param name="document"> /// The document that contains the element. /// </param> /// <param name="parent"> /// The parent of the element. /// </param> /// <param name="declaration"> /// The declaration code for this element. /// </param> /// <param name="unsafeCode"> /// Indicates whether the element resides within a block of unsafe code. /// </param> /// <param name="generated"> /// Indicates whether the code element was generated or written by hand. /// </param> internal EmptyElement(CsDocument document, CsElement parent, Declaration declaration, bool unsafeCode, bool generated) : base(document, parent, ElementType.EmptyElement, Strings.EmptyElement, null, null, declaration, unsafeCode, generated) { Param.AssertNotNull(document, "document"); Param.AssertNotNull(parent, "parent"); Param.AssertNotNull(declaration, "declaration"); Param.Ignore(unsafeCode); Param.Ignore(generated); }
internal Property(CsDocument document, CsElement parent, XmlHeader header, ICollection<Microsoft.StyleCop.CSharp.Attribute> attributes, Declaration declaration, TypeToken returnType, bool unsafeCode, bool generated) : base(document, parent, ElementType.Property, "property " + declaration.Name, header, attributes, declaration, unsafeCode, generated) { this.returnType = returnType; if ((base.Declaration.Name.IndexOf(".", StringComparison.Ordinal) > -1) && !base.Declaration.Name.StartsWith("this.", StringComparison.Ordinal)) { base.Declaration.AccessModifierType = AccessModifierType.Public; } }
/// <summary> /// Analyzes source document. /// </summary> public void AnalyzeDocument(CodeDocument document) { CurrentNamingSettings settings = new CurrentNamingSettings(); settings.Initialize(m_parent, document); CsDocument doc = (CsDocument)document; AnalyzeElements(doc.RootElement.ChildElements, settings); }
/// <summary> /// Checks the line spacing within the given document. /// </summary> /// <param name="document">The document to check.</param> private void CheckLineSpacing(CsDocument document) { Param.AssertNotNull(document, "document"); // Set up some variables. int count = 0; LexicalElement precedingItem = null; bool fileHeader = true; bool firstTokenOnLine = true; // Loop through all the tokens in the document. for (LexicalElement item = document.FindFirstDescendentLexicalElement(); item != null; item = item.FindNextDescendentLexicalElementOf(document)) { // Check for cancel. if (this.Cancel) { break; } // Check whether we're through the file header yet. if (fileHeader && item.LexicalElementType != LexicalElementType.EndOfLine && item.LexicalElementType != LexicalElementType.WhiteSpace && item.LexicalElementType != LexicalElementType.Comment) { fileHeader = false; } // Check whether this token is an end-of-line character. if (item.Text == "\n") { ++count; // This sets up for the next token, which will the be first token on its line. firstTokenOnLine = true; // Process the newline character. this.CheckLineSpacingNewline(precedingItem, item, count); } else if (item.LexicalElementType != LexicalElementType.WhiteSpace) { // Process the non-whitespace character. this.CheckLineSpacingNonWhitespace(document, precedingItem, item, fileHeader, firstTokenOnLine, count); count = 0; precedingItem = item; if (firstTokenOnLine && item.LexicalElementType != LexicalElementType.Comment) { firstTokenOnLine = false; } } } }
public override void AnalyzeDocument(CodeDocument document) { Param.RequireNotNull(document, "document"); CsDocument csdocument = (CsDocument)document; if (csdocument.RootElement != null && !csdocument.RootElement.Generated) { this.CheckSpacing(csdocument.Tokens); } }
/// <summary> /// Checks indentation in specified code line. /// </summary> private void CheckIndentation( CsDocument document, string currentLine, string previousLine, int currentLineNumber, CustomRulesSettings settings) { if (currentLine.Trim().Length == 0) { return; } string currentIndent = ExtractIndentation(currentLine); bool failed = true; switch (settings.IndentOptions.Mode) { case IndentMode.Tabs: failed = currentIndent.Contains(" "); break; case IndentMode.Spaces: failed = currentIndent.Contains("\t"); break; case IndentMode.Both: failed = currentIndent.Contains(" ") && currentIndent.Contains("\t"); break; } if (!failed) { return; } if (settings.IndentOptions.AllowPadding) { if (previousLine != null) { string previousIndent = ExtractIndentation(previousLine); if (IsPaddingAllowed(document, currentIndent, previousIndent, currentLineNumber)) { return; } } } AddViolation( document, currentLineNumber, Rules.CheckAllowedIndentationCharacters, settings.IndentOptions.GetContextValues()); }
public override void AnalyzeDocument(CodeDocument codeDocument) { Param.RequireNotNull(codeDocument, "codeDocument"); CsDocument csharpDocument = (CsDocument)codeDocument; if (csharpDocument.RootElement != null && !csharpDocument.RootElement.Generated) { csharpDocument.WalkDocument(VisitElement, null, null); } }
/// <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); }
/// <summary> /// Checks the case of element names within the given document. /// </summary> /// <param name="document">The document to check.</param> public override void AnalyzeDocument(ICodeDocument document) { Param.RequireNotNull(document, "document"); CsDocument csdocument = document.AsCsDocument(); if (!csdocument.Generated) { Dictionary <string, string> validPrefixes = this.GetPrefixes(document.Settings); this.ProcessElement(csdocument, validPrefixes, false); } }
/// <summary> /// Fires violation. /// </summary> private void AddViolation( CsDocument document, int lineNumber, Rules rule, params object[] values) { m_parent.AddViolation( CodeHelper.GetElementByLine(document, lineNumber) ?? document.RootElement, lineNumber, rule, values); }
private void CheckLineSpace( CsDocument csharpDocument, bool checkTrailingWhiteSpaces, bool checkTabIndentation) { if (!checkTrailingWhiteSpaces && !checkTabIndentation) { return; } using (var reader = csharpDocument.SourceCode.Read()) { string line; var lineNumber = 0; while ((line = reader.ReadLine()) != null) { lineNumber++; if (line.Length == 0) { continue; } if (checkTrailingWhiteSpaces && char.IsWhiteSpace(line[line.Length - 1])) { AddViolation( csharpDocument.RootElement, lineNumber, TrailingWhiteSpacesRuleName); } if (checkTabIndentation) { foreach (var c in line) { if (!char.IsWhiteSpace(c)) { break; } if (c == '\t') { AddViolation( csharpDocument.RootElement, lineNumber, TabIndentationRuleName); break; } } } } } }
/// <summary> /// Gets first node by specified line number. /// </summary> public static Node <CsToken> GetNodeByLine(CsDocument document, int lineNumber) { for (Node <CsToken> node = document.Tokens.First; node != null; node = node.Next) { if (node.Value.LineNumber == lineNumber) { return(node); } } return(null); }
/// <summary> /// Extremely simple analyzer for demo purposes. /// </summary> public override void AnalyzeDocument(CodeDocument document) { CsDocument doc = (CsDocument)document; // skipping wrong or auto-generated documents if (doc.RootElement == null || doc.RootElement.Generated) { return; } // check all class entries doc.WalkDocument(CheckClasses); }
/// <summary> /// Checks a type to determine whether it should use one of the built-in types. /// </summary> /// <param name="type">The type to check.</param> /// <param name="parentElement">The parent element.</param> private void CheckBuiltInType(TypeToken type, Element parentElement) { Param.AssertNotNull(type, "type"); Param.AssertNotNull(parentElement, "parentElement"); if (!type.IsGeneric) { for (int i = 0; i < this.builtInTypes.Length; ++i) { string[] builtInType = this.builtInTypes[i]; if (type.MatchTokens(builtInType[ShortNameIndex]) || type.MatchTokens("System", ".", builtInType[ShortNameIndex])) { // If the previous token is an equals sign, then this is a using alias directive. For example: // using SomeAlias = System.String; bool usingAliasDirective = false; for (LexicalElement previous = type.FindPreviousLexicalElement(); previous != null; previous = previous.FindPreviousLexicalElement()) { if (previous.LexicalElementType != LexicalElementType.Comment && previous.LexicalElementType != LexicalElementType.WhiteSpace && previous.LexicalElementType != LexicalElementType.EndOfLine) { if (previous.Text == "=") { usingAliasDirective = true; } break; } } if (!usingAliasDirective) { this.Violation( Rules.UseBuiltInTypeAlias, new ViolationContext(parentElement, type.LineNumber, builtInType[AliasIndex], builtInType[ShortNameIndex], builtInType[LongNameIndex]), (c, o) => { // Insert a new type token with the correct aliased version of the type. CsDocument document = type.Document; TypeToken aliasType = document.CreateTypeToken(document.CreateLiteralToken(builtInType[AliasIndex])); document.Replace(type, aliasType); }); } break; } } } }
/// <summary> /// Checks the placement of brackets within the given document. /// </summary> /// <param name="document">The document to check.</param> public override void AnalyzeDocument(ICodeDocument document) { Param.RequireNotNull(document, "document"); CsDocument csdocument = document.AsCsDocument(); if (csdocument != null && !csdocument.Generated) { csdocument.WalkCodeModel(this.VisitCodeUnit); // Check line spacing rules. this.CheckLineSpacing(csdocument); } }
private void CheckDocumentHeader(CsDocument csharpDocument) { var prop = GetSetting(csharpDocument.Settings, FileHeaderTextPropertyName) as StringProperty; if (prop != null) { var expectedText = prop.Value; var text = csharpDocument.FileHeader.HeaderText; if (!string.Equals(text, expectedText, StringComparison.Ordinal)) { AddViolation(csharpDocument.RootElement, 1, RuleName); } } }
/// <summary> /// Checks whether specified line is suitable for padding. /// </summary> private static bool IsSuitableForPadding(CsDocument document, int lineNumber) { Expression expr = CodeHelper.GetExpressionByLine(document, lineNumber); if (expr != null) { Expression root = CodeHelper.GetRootExpression(expr); if (root.Location.LineSpan > 1) { return(true); } } return(false); }
public void Is_Protected_Event_Handler() { CsDocument document = BuildCodeDocument(Source.ProtectedEventHandlers); Assert.IsFalse(CodeHelper.IsProtectedEventHandler(GetElementByName(document, "method FalseMethodIsNotProtected"))); Assert.IsFalse(CodeHelper.IsProtectedEventHandler(GetElementByName(document, "method FalseFirstArgumentIsNotObject"))); Assert.IsFalse(CodeHelper.IsProtectedEventHandler(GetElementByName(document, "method FalseFirstArgumentHasWrongName"))); Assert.IsFalse(CodeHelper.IsProtectedEventHandler(GetElementByName(document, "method FalseSecondArgumentIsNotEventArgs"))); Assert.IsFalse(CodeHelper.IsProtectedEventHandler(GetElementByName(document, "method FalseSecondArgumentHasWrongName"))); Assert.IsFalse(CodeHelper.IsProtectedEventHandler(GetElementByName(document, "method FalseUseAliasForObject1"))); Assert.IsFalse(CodeHelper.IsProtectedEventHandler(GetElementByName(document, "method FalseUseAliasForObject2"))); Assert.IsFalse(CodeHelper.IsProtectedEventHandler(GetElementByName(document, "method FalseReturnTypeIsNotVoid"))); Assert.IsTrue(CodeHelper.IsProtectedEventHandler(GetElementByName(document, "method TrueSimple"))); Assert.IsTrue(CodeHelper.IsProtectedEventHandler(GetElementByName(document, "method TrueComplexEventArgs"))); Assert.IsTrue(CodeHelper.IsProtectedEventHandler(GetElementByName(document, "method TrueGenericEventArgs"))); }
/// <summary> /// Initializes a new instance of the UsingDirective class. /// </summary> /// <param name="document"> /// The document that contains the element. /// </param> /// <param name="parent"> /// The parent of the element. /// </param> /// <param name="declaration"> /// The declaration code for this element. /// </param> /// <param name="generated"> /// Indicates whether the code element was generated or written by hand. /// </param> /// <param name="namespace"> /// The namespace being used. /// </param> /// <param name="alias"> /// Optional alias for the namespace, if any. /// </param> internal UsingDirective(CsDocument document, CsElement parent, Declaration declaration, bool generated, string @namespace, string alias) : base(document, parent, ElementType.UsingDirective, "using " + declaration.Name, null, null, declaration, false, generated) { Param.Ignore(document); Param.Ignore(parent); Param.Ignore(declaration); Param.Ignore(generated); Param.AssertValidString(@namespace, "namespace"); Param.Ignore(alias); this.namespaceType = @namespace; if (alias != null) { this.alias = alias; } }
////[TestMethod] public void TestNamespace() { string sourceCode = @"namespace Namespace1 { public class Class1 { } }"; CsLanguageService languageService = new CsLanguageService(); CsDocument document1 = languageService.CreateCodeModel(sourceCode, "source1.cs", "test"); CsDocument document2 = languageService.CreateCodeModel(sourceCode, "source2.cs", "test"); Comparer comparer = new Comparer(); comparer.AreEqual(document1, document2); }
public void Get_Element_By_Line() { CsDocument document = BuildCodeDocument(Source.GetByLine); Assert.AreEqual(GetElementByName(document, "method Method1"), CodeHelper.GetElementByLine(document, 5)); Assert.AreEqual(GetElementByName(document, "method Method1"), CodeHelper.GetElementByLine(document, 6)); Assert.AreEqual(GetElementByName(document, "method Method1"), CodeHelper.GetElementByLine(document, 7)); Assert.AreEqual(GetElementByName(document, "method Method1"), CodeHelper.GetElementByLine(document, 8)); Assert.AreEqual(GetElementByName(document, "method Method1"), CodeHelper.GetElementByLine(document, 9)); Assert.AreEqual(GetElementByName(document, "method Method1"), CodeHelper.GetElementByLine(document, 10)); Assert.AreEqual(GetElementByName(document, "method Method1"), CodeHelper.GetElementByLine(document, 11)); Assert.AreEqual(GetElementByName(document, "method Method1"), CodeHelper.GetElementByLine(document, 12)); Assert.AreEqual(GetElementByName(document, "method Method1"), CodeHelper.GetElementByLine(document, 13)); Assert.IsNull(CodeHelper.GetElementByLine(document, 0)); Assert.IsNull(CodeHelper.GetElementByLine(document, 1000)); }
/// <summary> /// Analyzes source document. /// </summary> public override void AnalyzeDocument(CodeDocument document) { CsDocument doc = (CsDocument)document; if (doc.RootElement == null || doc.RootElement.Generated) { return; } if (IsRuleEnabled(document, Rules.AdvancedNamingRules.ToString())) { m_advancedNamingRules.AnalyzeDocument(document); } m_extendedOriginalRules.AnalyzeDocument(document); m_moreCustomRules.AnalyzeDocument(document); }
public void Get_Labels() { CsDocument document = BuildCodeDocument(Source.Labels); CsElement element = GetElementByName(document, "constructor Class1"); List <LabelItem> labels = CodeHelper.GetLabels(element); Assert.AreEqual(10, labels.Count); AssertLabel("lab1", 15, labels[0]); AssertLabel("lab2", 24, labels[1]); AssertLabel("lab3", 29, labels[2]); AssertLabel("lab4", 34, labels[3]); AssertLabel("lab5", 38, labels[4]); AssertLabel("lab6", 40, labels[5]); AssertLabel("lab7", 41, labels[6]); AssertLabel("lab8", 44, labels[7]); AssertLabel("lab9", 48, labels[8]); AssertLabel("lab10", 53, labels[9]); }
/// <summary> /// Checks whether padding is allowed in specified situation. /// </summary> private static bool IsPaddingAllowed( CsDocument document, string currentIndent, string previousIndent, int currentLineNumber) { if (currentIndent.TrimStart('\t').TrimEnd(' ').Length > 0) { return(false); } if (currentIndent.TrimEnd(' ').Length != previousIndent.TrimEnd(' ').Length) { return(false); } return(IsSuitableForPadding(document, currentLineNumber)); }
private void ReadAndWriteFile(string filePath) { Console.WriteLine("Checking file " + filePath); if (File.Exists(filePath)) { string fileContents = null; try { fileContents = File.ReadAllText(filePath); } catch (IOException) { } CsLanguageService languageService = new CsLanguageService(preprocessorDefinitions); CsDocument doc = null; try { doc = languageService.CreateCodeModel(fileContents, Path.GetFileName(filePath), filePath); } catch (SyntaxException) { } catch (Exception ex) { Assert.Fail("Exception from CodeModel: " + ex.GetType() + ", " + ex.Message + ". FilePath=" + filePath); } if (doc != null) { using (StringWriter writer = new StringWriter()) { doc.Write(writer); this.CompareDocs(fileContents, writer.ToString(), filePath); } } } }
public void Is_Test_Method() { CsDocument document = BuildCodeDocument(Source.TestMethods); Assert.IsFalse(CodeHelper.IsTestMethod(GetElementByName(document, "method FalseUsualMethod"))); Assert.IsFalse(CodeHelper.IsTestMethod(GetElementByName(document, "method FalseUnkownAttribute"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueMSTestMethod"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueMSTestMethodParenthesis"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueMSTestMethodParameter"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueMSTestMethodParameters"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueMSTestMethodAttribute"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueMSTestMethodAttributeParenthesis"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueMSTestMethodAttributeParameter"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueMSTestMethodAttributeParameters"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueNUnitMethod"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueNUnitMethodParenthesis"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueNUnitMethodParameter"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueNUnitMethodParameters"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueNUnitMethodAttribute"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueNUnitMethodAttributeParenthesis"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueNUnitMethodAttributeParameter"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueNUnitMethodAttributeParameters"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueXUnitFactMethod"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueXUnitFactMethodParenthesis"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueXUnitFactMethodParameter"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueXUnitFactMethodParameters"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueXUnitFactMethodAttribute"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueXUnitFactMethodAttributeParenthesis"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueXUnitFactMethodAttributeParameter"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueXUnitFactMethodAttributeParameters"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueXUnitTheoryMethod"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueXUnitTheoryMethodParenthesis"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueXUnitTheoryMethodParameter"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueXUnitTheoryMethodParameters"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueXUnitTheoryMethodAttribute"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueXUnitTheoryMethodAttributeParenthesis"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueXUnitTheoryMethodAttributeParameter"))); Assert.IsTrue(CodeHelper.IsTestMethod(GetElementByName(document, "method TrueXUnitTheoryMethodAttributeParameters"))); }
public void Get_Element_Size_By_Declaration() { int size; CsDocument document = BuildCodeDocument(Source.ElementsSize); size = CodeHelper.GetElementSizeByDeclaration( GetElementByQualifiedName(document, "Root.StyleCopPlus.Tests.Class1.Class1")); Assert.AreEqual(3, size); size = CodeHelper.GetElementSizeByDeclaration( GetElementByQualifiedName(document, "Root.StyleCopPlus.Tests.Class1.Class1%int%int")); Assert.AreEqual(4, size); size = CodeHelper.GetElementSizeByDeclaration( GetElementByQualifiedName(document, "Root.StyleCopPlus.Tests.Class1.~Class1")); Assert.AreEqual(1, size); size = CodeHelper.GetElementSizeByDeclaration( GetElementByQualifiedName(document, "Root.StyleCopPlus.Tests.Class1.Property.get")); Assert.AreEqual(1, size); size = CodeHelper.GetElementSizeByDeclaration( GetElementByQualifiedName(document, "Root.StyleCopPlus.Tests.Class1.Property.set")); Assert.AreEqual(6, size); size = CodeHelper.GetElementSizeByDeclaration( GetElementByQualifiedName(document, "Root.StyleCopPlus.Tests.Class1.this%int.get")); Assert.AreEqual(2, size); size = CodeHelper.GetElementSizeByDeclaration( GetElementByQualifiedName(document, "Root.StyleCopPlus.Tests.Class1.this%int.set")); Assert.AreEqual(2, size); size = CodeHelper.GetElementSizeByDeclaration(GetElementByName(document, "method Method1")); Assert.AreEqual(3, size); size = CodeHelper.GetElementSizeByDeclaration(GetElementByName(document, "method Method2<T>")); Assert.AreEqual(4, size); size = CodeHelper.GetElementSizeByDeclaration(GetElementByName(document, "method operator +")); Assert.AreEqual(3, size); }
/// <summary> /// Checks the ending of specified code line. /// </summary> private void CheckLineEnding( CsDocument document, string currentLine, int currentLineNumber) { if (currentLine.Length == 0) { return; } char lastChar = currentLine[currentLine.Length - 1]; if (Char.IsWhiteSpace(lastChar)) { AddViolation( document, currentLineNumber, Rules.CodeLineMustNotEndWithWhitespace); } }
/// <summary> /// Initializes a new instance of the CodeWalker class. /// </summary> /// <param name="document">The document to walk through.</param> /// <param name="elementCallback">Callback executed when an element is visited.</param> /// <param name="statementCallback">Callback executed when a statement is visited.</param> /// <param name="expressionCallback">Callback executed when an expression is visited.</param> /// <param name="queryClauseCallback">Callback executed when a query clause is visited.</param> /// <param name="context">The optional visitor context data.</param> private CodeWalker( CsDocument document, CodeWalkerElementVisitor <T> elementCallback, CodeWalkerStatementVisitor <T> statementCallback, CodeWalkerExpressionVisitor <T> expressionCallback, CodeWalkerQueryClauseVisitor <T> queryClauseCallback, T context) { Param.AssertNotNull(document, "document"); Param.Ignore(elementCallback); Param.Ignore(statementCallback); Param.Ignore(expressionCallback); Param.Ignore(queryClauseCallback); Param.Ignore(context); this.elementCallback = elementCallback; this.statementCallback = statementCallback; this.expressionCallback = expressionCallback; this.queryClauseCallback = queryClauseCallback; this.WalkElement(document.RootElement, null, context); }