Enable and fix IDE0055 (Fix formatting)

This commit is contained in:
Sam Harwell 2022-05-05 09:00:55 -07:00
Родитель 1d117f8d85
Коммит 6bf30e8dc8
18 изменённых файлов: 187 добавлений и 126 удалений

Просмотреть файл

@ -1,5 +1,8 @@
is_global = true
# IDE0055: Fix formatting
dotnet_diagnostic.IDE0055.severity = warning
dotnet_diagnostic.SA1101.severity = none
dotnet_diagnostic.SA1201.severity = none
dotnet_diagnostic.SA1202.severity = none

Просмотреть файл

@ -1656,8 +1656,8 @@ class Class1
where declaration.Identifier.Text.Equals(name)
select model.GetDeclaredSymbol(declaration)).Single();
INamedTypeSymbol attributeSymbol = (from declaration in tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>()
where declaration.Identifier.Text.Equals("ExampleAttribute")
select model.GetDeclaredSymbol(declaration)).Single();
where declaration.Identifier.Text.Equals("ExampleAttribute")
select model.GetDeclaredSymbol(declaration)).Single();
// Verify that a method has no attributes
IMethodSymbol methodSymbol = getMethod("Method1");

Просмотреть файл

@ -1210,8 +1210,8 @@ namespace CSharpToVisualBasicConverter
public override SyntaxNode VisitConditionalExpression(CS.Syntax.ConditionalExpressionSyntax node)
{
VB.Syntax.ArgumentSyntax[] argumentsArray = new VB.Syntax.ArgumentSyntax[]
{
VB.Syntax.ArgumentSyntax[] argumentsArray = new VB.Syntax.ArgumentSyntax[]
{
VB.SyntaxFactory.SimpleArgument(VisitExpression(node.Condition)),
VB.SyntaxFactory.SimpleArgument(VisitExpression(node.WhenTrue)),
VB.SyntaxFactory.SimpleArgument(VisitExpression(node.WhenFalse))
@ -2012,7 +2012,7 @@ namespace CSharpToVisualBasicConverter
VB.SyntaxFactory.EndOperatorStatement());
}
public override SyntaxNode VisitPointerType(CS.Syntax.PointerTypeSyntax node)
public override SyntaxNode VisitPointerType(CS.Syntax.PointerTypeSyntax node)
// just ignore the pointer part
=> Visit<SyntaxNode>(node.ElementType);

Просмотреть файл

@ -80,7 +80,7 @@ namespace Roslyn.Samples.AddOrRemoveRefOutModifier
}
else
{
return RemoveOutOrRefCodeAction.Applicable(semanticModel, argument, parameters)
return RemoveOutOrRefCodeAction.Applicable(semanticModel, argument, parameters)
? new RemoveOutOrRefCodeAction(document, semanticModel, argument, parameters)
: null;
}

Просмотреть файл

@ -11,10 +11,10 @@ namespace GeneratedDemo
{
public static void Run()
{
WriteLine("## CARS");
Cars.All.ToList().ForEach(c => WriteLine($"{c.Brand}\t{c.Model}\t{c.Year}\t{c.Cc}"));
WriteLine("\n## PEOPLE");
People.All.ToList().ForEach(p => WriteLine($"{p.Name}\t{p.Address}\t{p._11Age}"));
WriteLine("## CARS");
Cars.All.ToList().ForEach(c => WriteLine($"{c.Brand}\t{c.Model}\t{c.Year}\t{c.Cc}"));
WriteLine("\n## PEOPLE");
People.All.ToList().ForEach(p => WriteLine($"{p.Name}\t{p.Address}\t{p._11Age}"));
}
}
}

Просмотреть файл

@ -52,7 +52,7 @@ namespace AutoNotify
foreach (IGrouping<INamedTypeSymbol, IFieldSymbol> group in receiver.Fields.GroupBy<IFieldSymbol, INamedTypeSymbol>(f => f.ContainingType, SymbolEqualityComparer.Default))
{
string classSource = ProcessClass(group.Key, group.ToList(), attributeSymbol, notifySymbol, context);
context.AddSource($"{group.Key.Name}_autoNotify.cs", SourceText.From(classSource, Encoding.UTF8));
context.AddSource($"{group.Key.Name}_autoNotify.cs", SourceText.From(classSource, Encoding.UTF8));
}
}

Просмотреть файл

@ -13,8 +13,10 @@ using System.Diagnostics;
#pragma warning disable IDE0008 // Use explicit type
namespace MathsGenerator {
public enum TokenType {
namespace MathsGenerator
{
public enum TokenType
{
Number,
Identifier,
Operation,
@ -29,17 +31,21 @@ namespace MathsGenerator {
None
}
public struct Token {
public struct Token
{
public TokenType Type;
public string Value;
public int Line;
public int Column;
}
public static class Lexer {
public static class Lexer
{
public static void PrintTokens(IEnumerable<Token> tokens) {
foreach (var token in tokens) {
public static void PrintTokens(IEnumerable<Token> tokens)
{
foreach (var token in tokens)
{
WriteLine($"{token.Line}, {token.Column}, {token.Type}, {token.Value}");
}
}
@ -62,19 +68,23 @@ namespace MathsGenerator {
t => (t.Item1, new Regex($"^{t.Item2}", RegexOptions.Compiled | RegexOptions.Singleline)));
// Can be optimized with spans to avoid so many allocations ...
static public Tokens Tokenize(string source) {
static public Tokens Tokenize(string source)
{
var currentLine = 1;
var currentColumn = 1;
while (source.Length > 0) {
while (source.Length > 0)
{
var matchLength = 0;
var tokenType = TokenType.None;
var value = "";
foreach (var (type, rule) in tokenExpressions) {
foreach (var (type, rule) in tokenExpressions)
{
var match = rule.Match(source);
if(match.Success) {
if (match.Success)
{
matchLength = match.Length;
tokenType = type;
value = match.Value;
@ -82,22 +92,27 @@ namespace MathsGenerator {
}
}
if (matchLength == 0) {
if (matchLength == 0)
{
throw new Exception($"Unrecognized symbol '{source[currentLine - 1]}' at index {currentLine - 1} (line {currentLine}, column {currentColumn}).");
} else {
}
else
{
if(tokenType != TokenType.Spaces)
yield return new Token {
Type = tokenType,
Value = value,
Line = currentLine,
Column = currentColumn
};
if (tokenType != TokenType.Spaces)
yield return new Token
{
Type = tokenType,
Value = value,
Line = currentLine,
Column = currentColumn
};
currentColumn += matchLength;
if(tokenType == TokenType.EOL) {
if (tokenType == TokenType.EOL)
{
currentLine += 1;
currentColumn = 0;
}
@ -106,11 +121,12 @@ namespace MathsGenerator {
}
}
yield return new Token {
Type = TokenType.EOF,
Line = currentLine,
Column = currentColumn
};
yield return new Token
{
Type = TokenType.EOF,
Line = currentLine,
Column = currentColumn
};
}
}
@ -125,23 +141,26 @@ namespace MathsGenerator {
func = identifier lround expr {comma expr} rround;
sum = lround identifier comma expr comma expr comma expr rround;
*/
public static class Parser {
public static class Parser
{
public static string Parse(Tokens tokens) {
var globalSymbolTable = new SymTable();
var symbolTable = new SymTable();
var buffer = new StringBuilder();
public static string Parse(Tokens tokens)
{
var globalSymbolTable = new SymTable();
var symbolTable = new SymTable();
var buffer = new StringBuilder();
var en = tokens.GetEnumerator();
en.MoveNext();
buffer = Lines(new Context {
buffer = Lines(new Context
{
tokens = en,
globalSymbolTable = globalSymbolTable,
symbolTable = symbolTable,
buffer = buffer
});
});
return buffer.ToString();
}
@ -158,14 +177,15 @@ namespace Maths {
}
}";
private struct Context {
private struct Context
{
public IEnumerator<Token> tokens;
public SymTable globalSymbolTable;
public SymTable symbolTable;
public StringBuilder buffer;
}
private static StringBuilder Error(Token token, TokenType type, string value = "") =>
private static StringBuilder Error(Token token, TokenType type, string value = "") =>
throw new Exception($"Expected {type} {(value == "" ? "" : $" with {token.Value}")} at {token.Line},{token.Column} Instead found {token.Type} with value {token.Value}");
static HashSet<string> validFunctions =
@ -175,79 +195,93 @@ namespace Maths {
{"'''", "Third" }, {"''", "Second" }, {"'", "Prime"}
};
private static StringBuilder EmitIdentifier(Context ctx, Token token) {
private static StringBuilder EmitIdentifier(Context ctx, Token token)
{
var val = token.Value;
if(val == "pi") {
if (val == "pi")
{
ctx.buffer.Append("PI"); // Doesn't follow pattern
return ctx.buffer;
}
if(validFunctions.Contains(val)) {
if (validFunctions.Contains(val))
{
ctx.buffer.Append(char.ToUpper(val[0]) + val.Substring(1));
return ctx.buffer;
}
string id = token.Value;
if(ctx.globalSymbolTable.Contains(token.Value) ||
ctx.symbolTable.Contains(token.Value)) {
foreach (var r in replacementStrings) {
if (ctx.globalSymbolTable.Contains(token.Value) ||
ctx.symbolTable.Contains(token.Value))
{
foreach (var r in replacementStrings)
{
id = id.Replace(r.Key, r.Value);
}
return ctx.buffer.Append(id);
} else {
}
else
{
throw new Exception($"{token.Value} not a known identifier or function.");
}
}
private static StringBuilder Emit(Context ctx, Token token) => token.Type switch
{
TokenType.EOL => ctx.buffer.Append("\n"),
TokenType.CloseParens => ctx.buffer.Append(')'), // All parens become rounded
TokenType.OpenParens => ctx.buffer.Append('('),
TokenType.Equal => ctx.buffer.Append("=>"),
TokenType.Comma => ctx.buffer.Append(token.Value),
TokenType.EOL => ctx.buffer.Append("\n"),
TokenType.CloseParens => ctx.buffer.Append(')'), // All parens become rounded
TokenType.OpenParens => ctx.buffer.Append('('),
TokenType.Equal => ctx.buffer.Append("=>"),
TokenType.Comma => ctx.buffer.Append(token.Value),
// Identifiers are normalized and checked for injection attacks
TokenType.Identifier => EmitIdentifier(ctx, token),
TokenType.Number => ctx.buffer.Append(token.Value),
TokenType.Operation => ctx.buffer.Append(token.Value),
TokenType.Sum => ctx.buffer.Append("MySum"),
_ => Error(token, TokenType.None)
TokenType.Identifier => EmitIdentifier(ctx, token),
TokenType.Number => ctx.buffer.Append(token.Value),
TokenType.Operation => ctx.buffer.Append(token.Value),
TokenType.Sum => ctx.buffer.Append("MySum"),
_ => Error(token, TokenType.None)
};
private static bool Peek(Context ctx, TokenType type, string value = "") {
private static bool Peek(Context ctx, TokenType type, string value = "")
{
var token = ctx.tokens.Current;
return (token.Type == type && value == "") ||
(token.Type == type && value == token.Value);
}
private static Token NextToken(Context ctx) {
private static Token NextToken(Context ctx)
{
var token = ctx.tokens.Current;
ctx.tokens.MoveNext();
return token;
}
private static void Consume(Context ctx, TokenType type, string value = "") {
private static void Consume(Context ctx, TokenType type, string value = "")
{
var token = NextToken(ctx);
if((token.Type == type && value == "") ||
(token.Type == type && value == token.Value)) {
if ((token.Type == type && value == "") ||
(token.Type == type && value == token.Value))
{
ctx.buffer.Append(" ");
Emit(ctx, token);
} else {
}
else
{
Error(token, type, value);
}
}
private static StringBuilder Lines(Context ctx) {
private static StringBuilder Lines(Context ctx)
{
// lines = {line} EOF
ctx.buffer.Append(Preamble);
while(!Peek(ctx, TokenType.EOF))
while (!Peek(ctx, TokenType.EOF))
Line(ctx);
ctx.buffer.Append(Ending);
@ -255,28 +289,37 @@ namespace Maths {
return ctx.buffer;
}
private static void AddGlobalSymbol(Context ctx) {
private static void AddGlobalSymbol(Context ctx)
{
var token = ctx.tokens.Current;
if(Peek(ctx, TokenType.Identifier)) {
if (Peek(ctx, TokenType.Identifier))
{
ctx.globalSymbolTable.Add(token.Value);
} else {
}
else
{
Error(token, TokenType.Identifier);
}
}
private static void AddSymbol(Context ctx) {
private static void AddSymbol(Context ctx)
{
var token = ctx.tokens.Current;
if(Peek(ctx, TokenType.Identifier)) {
if (Peek(ctx, TokenType.Identifier))
{
ctx.symbolTable.Add(token.Value);
} else {
}
else
{
Error(token, TokenType.Identifier);
}
}
private static void Line(Context ctx) {
private static void Line(Context ctx)
{
// line = {EOL} identifier [lround args rround] equal expr EOL {EOL}
ctx.symbolTable.Clear();
while(Peek(ctx, TokenType.EOL))
while (Peek(ctx, TokenType.EOL))
Consume(ctx, TokenType.EOL);
ctx.buffer.Append("\tpublic static double ");
@ -284,7 +327,8 @@ namespace Maths {
AddGlobalSymbol(ctx);
Consume(ctx, TokenType.Identifier);
if(Peek(ctx, TokenType.OpenParens, "(")) {
if (Peek(ctx, TokenType.OpenParens, "("))
{
Consume(ctx, TokenType.OpenParens, "("); // Just round parens
Args(ctx);
Consume(ctx, TokenType.CloseParens, ")");
@ -296,10 +340,11 @@ namespace Maths {
Consume(ctx, TokenType.EOL);
while(Peek(ctx, TokenType.EOL))
while (Peek(ctx, TokenType.EOL))
Consume(ctx, TokenType.EOL);
}
private static void Args(Context ctx) {
private static void Args(Context ctx)
{
// args = identifier {comma identifier}
// It doesn't make sense for a math function to have zero args (I think)
@ -307,7 +352,8 @@ namespace Maths {
AddSymbol(ctx);
Consume(ctx, TokenType.Identifier);
while(Peek(ctx, TokenType.Comma)) {
while (Peek(ctx, TokenType.Comma))
{
Consume(ctx, TokenType.Comma);
ctx.buffer.Append("double ");
AddSymbol(ctx);
@ -319,48 +365,57 @@ namespace Maths {
private static Action<Context, string> ConsOp = (ctx, op)
=> Consume(ctx, TokenType.Operation, op);
private static void Expr(Context ctx) {
private static void Expr(Context ctx)
{
// expr = [plus|minus] term { (plus|minus) term }
if(IsOp(ctx, "+")) ConsOp(ctx, "+");
if(IsOp(ctx, "-")) ConsOp(ctx, "-");
if (IsOp(ctx, "+")) ConsOp(ctx, "+");
if (IsOp(ctx, "-")) ConsOp(ctx, "-");
Term(ctx);
while(IsOp(ctx, "+") || IsOp(ctx, "-")) {
while (IsOp(ctx, "+") || IsOp(ctx, "-"))
{
if(IsOp(ctx, "+")) ConsOp(ctx, "+");
if(IsOp(ctx, "-")) ConsOp(ctx, "-");
if (IsOp(ctx, "+")) ConsOp(ctx, "+");
if (IsOp(ctx, "-")) ConsOp(ctx, "-");
Term(ctx);
}
}
private static void Term(Context ctx) {
private static void Term(Context ctx)
{
// term = factor { (times|divide) factor };
Factor(ctx);
while(IsOp(ctx, "*") || IsOp(ctx, "/")) {
if(IsOp(ctx, "*")) ConsOp(ctx, "*");
if(IsOp(ctx, "/")) ConsOp(ctx, "/");
while (IsOp(ctx, "*") || IsOp(ctx, "/"))
{
if (IsOp(ctx, "*")) ConsOp(ctx, "*");
if (IsOp(ctx, "/")) ConsOp(ctx, "/");
Term(ctx);
}
}
private static void Factor(Context ctx) {
private static void Factor(Context ctx)
{
// factor = number | var | func | lround expr rround;
if(Peek(ctx, TokenType.Number)) {
if (Peek(ctx, TokenType.Number))
{
Consume(ctx, TokenType.Number);
return;
}
if(Peek(ctx, TokenType.Identifier)) {
if (Peek(ctx, TokenType.Identifier))
{
Consume(ctx, TokenType.Identifier); // Is either var or func
if(Peek(ctx, TokenType.OpenParens, "(")) { // Is Func, but we already consumed its name
if (Peek(ctx, TokenType.OpenParens, "("))
{ // Is Func, but we already consumed its name
Funct(ctx);
}
return;
}
if(Peek(ctx, TokenType.Sum)) {
if (Peek(ctx, TokenType.Sum))
{
Sum(ctx);
return;
}
@ -369,7 +424,8 @@ namespace Maths {
Expr(ctx);
Consume(ctx, TokenType.CloseParens);
}
private static void Sum(Context ctx) {
private static void Sum(Context ctx)
{
// sum = ∑ lround identifier comma expr1 comma expr2 comma expr3 rround;
// TODO: differentiate in the language between integer and double, but complicated for a sample.
Consume(ctx, TokenType.Sum);
@ -388,16 +444,18 @@ namespace Maths {
Consume(ctx, TokenType.Comma);
ctx.buffer.Append($"{varName} => "); // It needs to be a lambda
Expr(ctx); // expr to evaluate at each iteration
Consume(ctx, TokenType.CloseParens, ")");
}
private static void Funct(Context ctx) {
private static void Funct(Context ctx)
{
// func = identifier lround expr {comma expr} rround;
Consume(ctx, TokenType.OpenParens, "(");
Expr(ctx);
while(Peek(ctx, TokenType.Comma)) {
while (Peek(ctx, TokenType.Comma))
{
Consume(ctx, TokenType.Comma);
Expr(ctx);
}
@ -438,10 +496,10 @@ namespace Maths {
var mathText = file.GetText();
var mathString = "";
if(mathText != null)
if (mathText != null)
{
mathString = mathText.ToString();
}
}
else
{
throw new Exception($"Cannot load file {file.Path}");
@ -455,13 +513,13 @@ namespace Maths {
var code = Parser.Parse(tokens);
var codeFileName = $@"{fileName}.cs";
context.AddSource(codeFileName, SourceText.From(code, Encoding.UTF8));
}
}
}
public void Initialize(GeneratorInitializationContext context)
public void Initialize(GeneratorInitializationContext context)
{
context.RegisterForPostInitialization((pi) => pi.AddSource("__MathLibrary__.cs", libraryCode));
}

Просмотреть файл

@ -33,7 +33,7 @@ namespace Mustache
context.AddSource($"Mustache{name}", source);
}
}
static string SourceFileFromMustachePath(string name, string template, string hash)
{
Func<object, string> tree = HandlebarsDotNet.Handlebars.Compile(template);

Просмотреть файл

@ -21,7 +21,7 @@ namespace Analyzer1
ProcessSettingsFile(settingsFile, context);
}
}
private void ProcessSettingsFile(AdditionalText xmlFile, GeneratorExecutionContext context)
{
// try and load the settings file
@ -37,7 +37,7 @@ namespace Analyzer1
return;
}
// create a class in the XmlSetting class that represnts this entry, and a static field that contains a singleton instance.
string fileName = Path.GetFileName(xmlFile.Path);
string name = xmlDoc.DocumentElement.GetAttribute("name");
@ -69,7 +69,7 @@ namespace AutoSettings
}}
");
for(int i = 0; i < xmlDoc.DocumentElement.ChildNodes.Count; i++)
for (int i = 0; i < xmlDoc.DocumentElement.ChildNodes.Count; i++)
{
XmlElement setting = (XmlElement)xmlDoc.DocumentElement.ChildNodes[i];
string settingName = setting.GetAttribute("name");
@ -91,7 +91,7 @@ public {settingType} {settingName}
context.AddSource($"Settings_{name}", SourceText.From(sb.ToString(), Encoding.UTF8));
}
public void Initialize(GeneratorInitializationContext context)
{
}

Просмотреть файл

@ -54,7 +54,7 @@ namespace Roslyn.ComponentDebugger
public Task<ICollection<IEnumValue>> GetListedValuesAsync()
{
var values = _referencingProjects.Select(p => new PageEnumValue(new EnumValue() { DisplayName = p.display, Name = p.path})).Cast<IEnumValue>().ToImmutableArray();
var values = _referencingProjects.Select(p => new PageEnumValue(new EnumValue() { DisplayName = p.display, Name = p.path })).Cast<IEnumValue>().ToImmutableArray();
return Task.FromResult<ICollection<IEnumValue>>(values);
}

Просмотреть файл

@ -17,6 +17,6 @@ public partial class RoslynSDKRootTemplateWizard
// add the root project name (the name the user passed in) to the global replacement dictionary
GlobalDictionary["$saferootprojectname$"] = replacementsDictionary["$safeprojectname$"];
GlobalDictionary["$saferootidentifiername$"] = replacementsDictionary["$safeprojectname$"].Replace(".","");
GlobalDictionary["$saferootidentifiername$"] = replacementsDictionary["$safeprojectname$"].Replace(".", "");
}
}

Просмотреть файл

@ -203,7 +203,7 @@ namespace Roslyn.SyntaxVisualizer.Control
private enum UpdateBehavior
{
None,
/// <summary>
/// Update is triggered from the Color property being updated
/// </summary>

Просмотреть файл

@ -105,9 +105,9 @@ namespace Roslyn.SyntaxVisualizer.Control
colorItem.crForeground = BitConverter.ToUInt32(
new byte[] {
selectedColor.R,
selectedColor.G,
selectedColor.B,
selectedColor.R,
selectedColor.G,
selectedColor.B,
0 // Alpha
}, 0);

Просмотреть файл

@ -16,7 +16,7 @@ namespace Roslyn.SyntaxVisualizer.Control
= DependencyProperty.Register(
nameof(Hue),
typeof(double),
typeof(HuePicker),
typeof(HuePicker),
new PropertyMetadata(0.0, OnHueChanged));

Просмотреть файл

@ -20,16 +20,16 @@ namespace Roslyn.SyntaxVisualizer.Control
public static readonly DependencyProperty SaturationProperty
= DependencyProperty.Register(
nameof(Saturation),
typeof(double),
typeof(SaturationBrightnessPicker),
nameof(Saturation),
typeof(double),
typeof(SaturationBrightnessPicker),
new PropertyMetadata(0.0, OnSaturationChanged));
public static readonly DependencyProperty BrightnessProperty
= DependencyProperty.Register(
nameof(Brightness),
typeof(double),
typeof(SaturationBrightnessPicker),
nameof(Brightness),
typeof(double),
typeof(SaturationBrightnessPicker),
new PropertyMetadata(0.0, OnBrightnessChanged));
private readonly SaturationBrightnessPickerAdorner _adorner;

Просмотреть файл

@ -44,7 +44,7 @@ namespace Roslyn.SyntaxVisualizer.Control.SymbolDisplay
}
catch
{
}
}

Просмотреть файл

@ -20,7 +20,7 @@ namespace Roslyn.SyntaxVisualizer.Extension
if (vsTextView != null)
{
var guidTextViewHost = DefGuidList.guidIWpfTextViewHost;
if (((IVsUserData)vsTextView).GetData(ref guidTextViewHost, out var textViewHost) == VSConstants.S_OK &&
if (((IVsUserData)vsTextView).GetData(ref guidTextViewHost, out var textViewHost) == VSConstants.S_OK &&
textViewHost != null)
{
wpfTextView = ((IWpfTextViewHost)textViewHost).TextView;

Просмотреть файл

@ -268,7 +268,7 @@ namespace Roslyn.SyntaxVisualizer.Extension
var activeSemanticModel = ThreadHelper.JoinableTaskFactory.Run(() => document.GetSemanticModelAsync());
// Display the SyntaxTree.
if (( contentType.IsOfType(VisualBasicContentType) || contentType.IsOfType(CSharpContentType) ) && activeSyntaxTree is not null)
if ((contentType.IsOfType(VisualBasicContentType) || contentType.IsOfType(CSharpContentType)) && activeSyntaxTree is not null)
{
syntaxVisualizer.DisplaySyntaxTree(activeSyntaxTree, activeSemanticModel, workspace: document.Project.Solution.Workspace);
}