Giter VIP home page Giter VIP logo

visual-stylecop's People

Contributors

ghowlett2020 avatar gitter-badger avatar icnocop avatar kopelli avatar mrsynchro avatar pathyatt avatar ptittof57 avatar scorbiere avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

visual-stylecop's Issues

SA1101 false positive

The following line:

XmlNode node = ... ;
var property = node["properties"]?["property"];

incorrectly gives:
SA1011 : CSharp.Spacing : Invalid spacing around the closing square bracket.

Build 4.7.58.3

SA0102 false positive

The following line:

var when = new XElement("someelement");

incorrectly gives:
SA0102 : CSharp.CsParser : A syntax error has been discovered in file ... .

Changing when to another name fixes the issue.

Build 4.7.53

SA0102 parser exception with $@""

issue with the new "$" string interpolation when it is followed by an "@" symbol. IE string s = $@""; results in SA0102 : CSharp.CsParser : A syntax error has been discovered in file . This is a different issue than #2 and #20 , but related to both. Am I the only one that is having this issue?

Ability to DisableAllProcessing

I've made a local version that has by Global Settings or by SourceFile/Global Settings that allows you to completely disable processing.

The use case is that if you have a huge .cs file (such as a large Entity Framework Migrations that inserts lots of data), you can use this setting to ensure that absolutely NO processing happens for a file.

Let me know if you'd like to arrange review and me adding it back into the repository.

Thanks,
Christine Boersen

Syntax error in C# 6 while compiling OK

return modules?[0] is incorrectly reported as syntax error in the following code snippet (v4.7.55.26)

private static Module AssemblyModule
{
get
{
Module[] modules = Assembly.GetExecutingAssembly().GetModules();
Contract.Assume(modules?.Length > 0);
return modules?[0];
}
}

Thanks for the product !

Several C# 6.0 features still aren't supported

Hello @ptittof57,

I've been testing the functionality of this project at work, and have found a few C# 6.0 language features that still cause a syntax exception:
Index Initializers:

Dictionary<int, string> myDictionary = new Dictionary<int, string>()
{
    [1] = "One"
};

Exception Filters:

try
{
}
catch (Exception) when (true)
{
}

Expression-bodied function members / parameters

public string Test => "Test";
public string Test(string a) => a + "b";

Using static

using static System.Console;

I'm using version 4.7.52 on VS 2015 Enterprise.
Thanks for the work you have done to this project so far!

--Gustave Granroth.
Software Engineer, [email protected]

NullCoalescingSymbol parsing error

Hi Christoph,

I think there is a not considered use case with the NullCoalescingSymbol Symbol.
Line 8 of the The following code results in an error in VisualStyleCop in parsing the file
internal class myclass
{
private bool? singleBitValue;

    private bool? foo(object obj)
    {
        this.singleBitValue = obj as bool?;
        this.singleBitValue = obj as bool? ?? false;
        return true ? true : false;
    }
}

I was able to fix it by adding a check for checkNullCondition
In StyleCop.CSharp.CodeLexer.GetOperatorSymbor on line 2056

if (character == '?' && checkNullCondition.Length == 0)

In my opinion this makes sense as there must not be any tokes between the ?? operator.
Do you think it is possible to update the code accordingly?
Kind Regards
Ruedi

ExcludeFromStyleCop not respected by the VS extension

ExcludeFromStyleCop works fine for project's build.

But when using "Run StyleCop (Rescan All)" from the VS extension on a solution level it still raises warnings, e.g.:
SA1633 : CSharp.Documentation : The file has no header, the header Xml is invalid, or the header is not located at the top of the file.

I have installed the extension directly from nuget.

Visual-StyleCop.Build does not work

Hi,

I am trying to install the Visual-StyleCop.Build in my solution. But it doesnot work on the build server. The build failed with the message.

error MSB4018: The "StyleCopTask" task failed unexpectedly.
error MSB4018: System.MissingMethodException: Method not found: '!!0[] System.Array.Empty()'
error MSB4018: at StyleCop.StyleCopTask.Execute()
error MSB4018: at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
error MSB4018: at Microsoft.Build.BackEnd.TaskBuilder.d__20.MoveNext()

Can somebody give me some more hints, I have search on the internet but I have not yet found the solution.

Grtz.

SA1127 on non string literals

I have the following piece of code:

string.Format(Resources.Foo, "bar")

I am getting a SA1127 for this whereas I have no way to use string interpolation here.

Does not appear to work in VS 2013 unless VS 2015 is also installed.

Attempting to use in VS 2013 on a computer where VS 2015 is not also installed generates an error:

1553 2015/08/26 19:14:49.273 Error VisualStudio CreateInstance failed for package [StyleCop.VisualStudio.StyleCopVSPackage, StyleCop.VSPackage, Version=4.7.0.0, Culture=neutral, PublicKeyToken=f904653c63bc2738] {629EB7CC-69C2-43AC-9BC9-482B0F810C4E}
80070002 Could not load file or assembly 'Microsoft.VisualStudio.Shell.14.0, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

SA0102 - Syntax error - Collection init issue

Copy from #20

// Example 3 (AlternateNames)
var expected = new InstitutionalInfo
{
AgendaSource = _institutionalInfo.AgendaSource != 0,
AudioSource = _institutionalInfo.AudioSource != 0,
Calendar = _institutionalInfo.Calendar,
IdConferenceFrequency =
_institutionalInfo.IdConferenceFrequency,
ContactDescription = _institutionalInfo.ContactDescription,
ContactEmail = _institutionalInfo.ContactEmail,
ContactName = _institutionalInfo.ContactName,
ContactTelephone = _institutionalInfo.ContactTelephone,
ContactTitle = _institutionalInfo.ContactTitle,
Notes = _institutionalInfo.Notes,
AlternateNames = new List {
_names[0].AlternateName, _names[1].AlternateName } //Here problem
occurs
};

Distributions = new List { reader["Distribution1"].ToString(),
reader["Distribution2"].ToString() },

Proposal: remove new rule SA1127 (AvoidStringFormatUseStringInterpolation)

I propose rule SA1127 be removed for the following reasons:

  1. String interpolation does not always offer readability benefits over string.Format. Calls to string.Format have the ability to use the standard call syntax with one argument per line to express long formatting operations. These uses should not be required to suppress a warning.
  2. The use of string interpolation increases the complexity of updating single-culture code to properly support localization. The rule is therefore prone to increasing the technical debt associated with young projects that have not yet moved to proper resource-based strings.

Conclusion: the benefits provided by string interpolation are not consistent across a code base, and therefore do not meet the bar for declaring a general readability rule that will apply to whole code bases. Support for string interpolation should be limited to the creation of refactoring operations which can be applied to specific calls to string.Format if and when developers see readability benefits.

nameof() doesn't seem to be supported

I'm getting this error on a line that contains nameof()

1>D:\Dev\Project\Search.cs(89,1): error : SA0102 : CSharp.CsParser : A syntax error has been discovered in file D:\Dev\Project\Search.cs on line 89.

My line 89 looks like this:

nameof(this.index.SearchAsync),

Null conditional throw SA1126

From VSExtension comment open by ophioscorodon

First let me start off by saying thanks, if you are ever in Providence RI, I'll buy you dinner for doing this.

Have a slight problem,

            var handler = this.OpenEditorAndFileEvent;

            // Raise the PropertyChanged event.
            handler?.Invoke(this, filename);

produces a

SA1126 : CSharp.Readability : The call to Invoke must begin with the 'this.', 'base.', 'object.' or 'MevWpfUserControl.' or 'UserControl.' prefix to indicate the intended method call.     

Something weird is going on

Thanks
-jam

SA0102 - syntax error - wrapped string

Strings containing new lines and created by verbatim string literal causes SA0102.
Example:
const string Query = @"delete from [dbo].[OrganizationEventEntry] where [idOrganization] = 104
insert into [dbo].[OrganizationEventEntry](idOrganization, idTimezone (...)

Can't open settings dialog.

In Solution Explorer -> Right click Project -> click "StyleCop Settings" causes crash.
I'm using VS2015 Community in English, and the latest add-in is installed via "Extensions and Updates".

Dialog
2016-02-16

Info about my VS.
2016-02-16 1

'Method not found' exception when using context menu

When running StyleCop from the right-click context menu on a Solution Explorer item or on the file itself, I get a model dialog with the following message:

Method not found: 'Void StyleCop.CodeProject.ctor(Int32, System.String, StyleCop.Configuration, Double).

Version is 4.7.55.26 in VS2015 Enterprise

Syntax error with string interpolation

Comment from Visual Studio Gallery:

Hi,

First, thanks for this great Tool we are using on a daily basis.
Then talking about C#6, I have found a string interpolation syntax that seems not to be recognized by the parser (v 4.7.54) while correctly compiled and run in VS2015 :

WriteLine($"{argumentName}[{argIndex}] = "{arguments[argIndex]}"");

where argumentName is a const string (local auto)
where argIndex is an int
where arguments is an array of string

Thanks for fixing.

SA0001 : CoreParser : An exception occurred while parsing the file

Hi,

When I replaced v4.7.49 with Visual-StyleCop.MSBuild 4.7.58.3 from https://www.nuget.org/packages/Visual-StyleCop.MSBuild

I started to have following exception on some specific file:

...cs(1,1): error : SA0001 : CoreParser : An exception occurred while parsing the file: System.FormatException, Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
.cs(1,1): error : at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
.cs(1,1): error : at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
.cs(1,1): error : at System.String.Format(IFormatProvider provider, String format, Object[] args)
.cs(1,1): error : at StyleCop.StyleCopThread.RunAnalyzers(CodeDocument document, SourceParser parser, IEnumerable1 analyzers) .cs(1,1): error : at StyleCop.StyleCopThread.TestAndRunAnalyzers(CodeDocument document, SourceParser parser, IEnumerable1 analyzers, Int32 passNumber)
.cs(1,1): error : at StyleCop.StyleCopThread.ParseAndAnalyzeDocument(SourceCode sourceCode, DocumentAnalysisStatus documentStatus)
.cs(1,1): error : at StyleCop.StyleCopThread.DoWork(Object sender).

Same with Visual-StyleCop... 4.7.54

Syntax error parsing csharp

I get the following error
Warning SA0102 : CSharp.CsParser : A syntax error has been discovered in file ... on line 16

from the code:

public void test()
{
  string[] strings = null;
  var l = new List<string>
  {
    strings[9], // line 16
    strings[8],
    strings[0],
    strings[1],
    strings[2],
    strings[3],
    strings[4],
    strings[5],
    strings[6],
  };
}

First appeared in version 4.7.53, altso present in 4.7.54

Index initializers are not correctly parsed (v4.7.56.4)

// Index initializers
Dictionary<int, string> primaryNumbers = new Dictionary<int, string>()
{
[1] = "one",
[3] = "three",
[5] = "five",
[7] = "seven",
[11] = "eleven"
}; <= SA0102 : CSharp.CsParser : A syntax error has been discovered

SA0102 sytnax error for first usage of C# 6.0 syntax (string interpolation, null propogation) for a file

We've integrated visual-stylecop into our csproj and we've started using the C# 6.0 syntax throughout the files. We are using VS 2015.

We are finding that Visual-StyleCop is giving warnings for the "first appearance" of C# 6.0 syntax for a file:
"SA0102 : CSharp.CsParser : A syntax error has been discovered in **\fileA.cs on line 59."
"SA0102 : CSharp.CsParser : A syntax error has been discovered in file *
*\fileB.cs on line 67.
etc.

In fileA's case, we have multiple usages of C# 6.0 syntax particularly string interpolation and null propagation (ie. on line 59, 143, etc.) but the only warning being flagged is the first appearance of it (on line 59 but not line 143). This similar behavior is seen in fileB.cs as well.

Support for custom extensions

It would be nice if this had a better way of dealing with custom extensions. In order to get a custom extension to work you have to drop the extension dll in the install folder. With VS extensions it's difficult to identify the location and it changes with every update. It would be nice if StyleCop extensions could be placed in a more general location.

Installing in VS2015 as user fails

Trying to install the extension in a VS2015 that is not run by an administrator causes the installer to use up all available memory and crash.

ASP.NET 5 (.xproj) Projects Do Not Work

Running StyleCop over ASP.NET 5 (.xproj) projects does not work. It produces no output. This is probably because these project files do not include a list of all files within them.

C#6 features still not supported

Hi, I've already checked issue #7 where it says this has been resolved, however I just intalled Visual-Stylecop.MSBuild from nuget, version 4.7.58.3 and I am getting the SA0102 error on all the C#6 features that I tried out, like:

try
{

}
catch (Exception) when (true)
{

}

or

public virtual ICollection<CostType> CostTypes { get; protected set; } = new List<CostType>();

Am I doing anything wrong or there is a regression?

Thanks.

Remove unnecessary rule SA1127 (AvoidStringFormatUseStringInterpolation)

This rule has two major drawbacks:

  1. String interpolation requires the Roslyn compiler, but it does not require .NET 4.6. The newer framework is only required for the specific case where an interpolated string is assigned to a variable with the static type IFormattable. In other cases, including but not limited to assignments to string, object, and variables declared with var, string interpolation works at least going back to .NET 3.5 (we use it extensively for this where it improves code clarity; it may work going back to .NET 2.0 but we haven't been using it like this).

  2. The compiler and project system already have a feature specifically designed to restrict the use of newer language features in projects that still need to target older versions of .NET. For teams where some but not all developers are using Visual Studio 2015, the LangVersion property in the project file keeps everyone on the same page. This property is configured in the following location:

    image

SA0102 With string interpolation

Since I have a problem with string interpolation, I'll post it right here and won't open a new issue.
My code is

var message = $"ConnectionString missing: {ConfigurationManager.AppSettings["ConnectionStringName"]}";

The code analyzer gives a warning SA0102.

I guess it's a problem with the quotation marks inside of the curly brackets
#37

Invalid Syntax reported for valid C#

The following valid C# snippet is reported as a syntax error.

workArea.Leave(x => HandleWorkAreaLogoutLeave(wa, x, obj as bool? ?? true));

Name: SyntaxException
Namespace: StyleCop.CSharp.CsParser
Description:

SA0102 False positive

The following line:

var x = y ? z?.Invoke() : w?.Invoke();

incorrectly gives:
SA0102 : CSharp.CsParser : A syntax error has been discovered in file ....

Upon further investigation, it is the first use of the null conditional operator

z?.Invoke() 

which appears to causes the SA0102 error.

Build 4.7.58.3

SA0102 issue when using expression body for properties (C# 6)

We recently switched to C# 6 with VS2015 at work and after using ReSharper's kind suggestions to start going to C# 6 features like properties to expression body, I got an SA0102 issue with both the lines below.

public IEnumerable SelectableShiftHours => CreateSelectableShiftHours();

public OptimisationDayOfWeekEnum SelectedDay => selectedDay; (just a standard backing field to see if it was the method that did it)

Build 4.7.58.3

SA1009 false positive with null conditional operator

The following snippet:

var posts = new List<string>() { "abc", "123" };
posts.First()?.Replace('a', 'z');

incorrectly gives:
SA1009 : CSharp.Spacing : Invalid spacing around the closing parenthesis.
for the second line.

Build 4.7.53 and previous build 23/08/2015.

Null Conditional Operator causes SA1009 to trigger

The new Null Conditional Operator in C# version 6 causes SA1000 to trigger in some circumstances.

I have this code:

internal static class AssemblyInfo
{
internal static T Attribute() where T : Attribute
{
return typeof(AssemblyInfo).Assembly.GetCustomAttribute();
}
}

And this call:

string company = AssemblyInfo.Attribute()?.Company;

The call causes SA1009 CSharp.Spacing : Invalid spacing around the closing parenthesis

However in this case, a ? here is properly spaced.

Consider joining StyleCopAnalyzers

Hi @ptittof57,

I'd like to invite you to join the DotNetAnalyzers/StyleCopAnalyzers project. Over the past 9 months, more than 20 community members have joined together to build a faithful reproduction of StyleCop using the .NET Compiler Platform (Roslyn). The project implements the nearly all of the original StyleCop rules and even includes code fixes for most of them, all without requiring any special tools or Visual Studio extensions. We have over 5000 unit tests (including coverage of C# 6 features), a live status page, and an active discussion room on Gitter.

If you don't join us, please consider at least joining our chat room to discuss ways to make sure our diagnostic IDs stay in sync over time. ๐Ÿ˜„

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.