Skip to content

Commit

Permalink
chore: use some pattern matching (#10285)
Browse files Browse the repository at this point in the history
* use some pattern matching

* fix build failure

---------

Co-authored-by: Yufei Huang <[email protected]>
  • Loading branch information
SimonCropp and yufeih authored Oct 20, 2024
1 parent f06a6e9 commit 3e17f63
Show file tree
Hide file tree
Showing 37 changed files with 51 additions and 53 deletions.
2 changes: 1 addition & 1 deletion src/Docfx.App/Helpers/DocumentBuilderWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public static void BuildDocument(BuildJsonConfig config, BuildOptions options, T
// Ensure "_enableSearch" adds the right post processor
if (metadata != null && metadata.TryGetValue("_enableSearch", out object value))
{
if (value is bool isSearchable && isSearchable && !postProcessorNames.Contains("ExtractSearchIndex"))
if (value is true && !postProcessorNames.Contains("ExtractSearchIndex"))
{
postProcessorNames = postProcessorNames.Add("ExtractSearchIndex");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public object Handle(object obj, HandleModelAttributesContext context)

protected virtual bool ShouldHandle(object currentObj, object declaringObject, PropInfo currentPropInfo, HandleModelAttributesContext context)
{
return currentPropInfo != null && currentPropInfo.Attr != null;
return currentPropInfo is {Attr: not null};
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ public void Expand(Dictionary<string, ApiReferenceBuildOutput> references, strin

public static List<ApiLanguageValuePair> GetSpecNames(string xref, string[] supportedLanguages, SortedList<string, List<SpecViewModel>> specs = null)
{
if (specs != null && specs.Count > 0)
if (specs is {Count: > 0})
{
return (from spec in specs
where supportedLanguages.Contains(spec.Key)
Expand Down
2 changes: 1 addition & 1 deletion src/Docfx.Build.RestApi/BuildRestApiDocument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ private static void MarkupRecursive(JToken jToken, IHostService host, FileModel
{
if (MarkupKeys.Contains(pair.Key) && pair.Value != null)
{
if (pair.Value is JValue jValue && jValue.Type == JTokenType.String)
if (pair.Value is JValue {Type: JTokenType.String} jValue)
{
jObject[pair.Key] = Markup(host, (string)jValue, model, filter);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Docfx.Build.RestApi/RestApiDocumentProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ private static bool IsSwaggerFile(string filePath)
if (jObject.TryGetValue("swagger", out JToken swaggerValue))
{
var swaggerString = (string)swaggerValue;
if (swaggerString != null && swaggerString.Equals("2.0"))
if (swaggerString is "2.0")
{
return true;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Docfx.Build.SchemaDriven/Models/JsonPointer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public JsonPointer GetParentPointer()
public static bool TryCreate(string raw, out JsonPointer pointer)
{
pointer = null;
if (raw != null && raw.Length > 0 && raw[0] != '/')
if (raw is {Length: > 0} && raw[0] != '/')
{
return false;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Docfx.Build.SchemaDriven/Processors/FileInterpreter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public FileInterpreter(bool exportFileLink, bool updateValue)

public bool CanInterpret(BaseSchema schema)
{
return schema != null && schema.ContentType == ContentType.File;
return schema is {ContentType: ContentType.File};
}

public object Interpret(BaseSchema schema, object value, IProcessContext context, string path)
Expand Down
2 changes: 1 addition & 1 deletion src/Docfx.Build.SchemaDriven/Processors/HrefInterpreter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public HrefInterpreter(bool exportFileLink, bool updateValue, string siteHostNam

public bool CanInterpret(BaseSchema schema)
{
return schema != null && schema.ContentType == ContentType.Href;
return schema is {ContentType: ContentType.Href};
}

public object Interpret(BaseSchema schema, object value, IProcessContext context, string path)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public class MarkdownInterpreter : IInterpreter
{
public bool CanInterpret(BaseSchema schema)
{
return schema != null && schema.ContentType == ContentType.Markdown;
return schema is {ContentType: ContentType.Markdown};
}

public object Interpret(BaseSchema schema, object value, IProcessContext context, string path)
Expand Down
2 changes: 1 addition & 1 deletion src/Docfx.Build.SchemaDriven/Processors/XrefInterpreter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public XrefInterpreter(bool aggregateXrefs, bool resolveXref)

public bool CanInterpret(BaseSchema schema)
{
return schema != null && schema.ContentType == ContentType.Xref;
return schema is {ContentType: ContentType.Xref};
}

public object Interpret(BaseSchema schema, object value, IProcessContext context, string path)
Expand Down
2 changes: 1 addition & 1 deletion src/Docfx.Build/TableOfContents/TocDocumentProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ private void UpdateTocItemHref(TocItemViewModel toc, FileModel model, IDocumentB
toc.OriginalTopicHref = null;

includedFrom = toc.IncludedFrom ?? includedFrom;
if (toc.Items != null && toc.Items.Count > 0)
if (toc.Items is {Count: > 0})
{
foreach (var item in toc.Items)
{
Expand Down
2 changes: 1 addition & 1 deletion src/Docfx.Build/TableOfContents/TocResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ private TocItemInfo ResolveItemCore(TocItemInfo wrapper, Stack<FileAndType> stac
{
case HrefType.AbsolutePath:
case HrefType.RelativeFile:
if (item.Items != null && item.Items.Count > 0)
if (item.Items is {Count: > 0})
{
item.Items = new List<TocItemViewModel>(from i in item.Items
select ResolveItem(new TocItemInfo(file, i), stack) into r
Expand Down
2 changes: 1 addition & 1 deletion src/Docfx.Build/TableOfContents/TocRestructureUtility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ private static void RestructureCore(TocItemViewModel item, List<TocItemViewModel
}
}

if (item.Items != null && item.Items.Count > 0)
if (item.Items is {Count: > 0})
{
var parentItems = new List<TocItemViewModel>(item.Items);
foreach (var i in item.Items)
Expand Down
2 changes: 1 addition & 1 deletion src/Docfx.Build/TemplateProcessors/TemplateManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ private IEnumerable<string> GetTemplateDirectories(IEnumerable<string> names)

public void ProcessTheme(string outputDirectory, bool overwrite)
{
if (_themes != null && _themes.Count > 0)
if (_themes is {Count: > 0})
{
TryExportResourceFiles(_themes, outputDirectory, overwrite);
Logger.LogInfo($"Theme(s) {_themes.ToDelimitedString()} applied.");
Expand Down
2 changes: 1 addition & 1 deletion src/Docfx.Build/XRefMaps/XRefArchiveBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ private async Task<string> DownloadCoreAsync(Uri uri, XRefArchive xa, Cancellati
// Sort is not needed if `map.Sorted == true`.
// But there are some xrefmap files that is not propery sorted by using InvariantCulture.
// (e.g. Unity xrefmap that maintained by community)
if (map.References != null && map.References.Count > 0)
if (map.References is {Count: > 0})
{
map.References.Sort(XRefSpecUidComparer.Instance);
map.Sorted = true;
Expand Down
9 changes: 4 additions & 5 deletions src/Docfx.Common/Path/RelativePath.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,10 @@ public static RelativePath FromUrl(string path)
public static bool IsRelativePath(string path)
{
// TODO : to merge with the PathUtility one
return path != null &&
path.Length > 0 &&
path[0] != '/' &&
path[0] != '\\' &&
path.IndexOfAny(PathUtility.InvalidPathChars) == -1;
return path is {Length: > 0} &&
path[0] != '/' &&
path[0] != '\\' &&
path.IndexOfAny(PathUtility.InvalidPathChars) == -1;
}

public static RelativePath Parse(string path) => TryParseCore(path, true);
Expand Down
4 changes: 2 additions & 2 deletions src/Docfx.Dotnet/DotnetApiCatalog.Toc.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ IEnumerable<TocNode> CreateToc(ISymbol symbol, Compilation compilation)

switch (symbol)
{
case INamespaceSymbol ns when ns.IsGlobalNamespace:
case INamespaceSymbol {IsGlobalNamespace: true} ns:
foreach (var child in ns.GetNamespaceMembers())
foreach (var item in CreateToc(child, compilation))
yield return item;
Expand Down Expand Up @@ -248,7 +248,7 @@ void InsertCategory(TocNodeType type, string name)
case CategoryLayout.Nested:
{
// Skip when parent node is category node.
if (parentTocNode != null && parentTocNode.type == TocNodeType.None)
if (parentTocNode is {type: TocNodeType.None})
return;

// If items contains specified type node. Create new TocNode for category. and move related node to child node.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public void Run(MetadataModel yaml, ResolverContext context)
(member, parent) =>
{
// get all the possible places where link is possible
if (member.Syntax != null && member.Syntax.Content != null)
if (member.Syntax is {Content: not null})
{
SyntaxLanguage[] keys = new SyntaxLanguage[member.Syntax.Content.Count];
member.Syntax.Content.Keys.CopyTo(keys, 0);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public void Run(MetadataModel yaml, ResolverContext context)
page = parent;
current.References = null;
}
if (documentReferences != null && documentReferences.Count > 0)
if (documentReferences is {Count: > 0})
{
foreach (var key in documentReferences.Keys)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ internal class SetDerivedClass : IResolverPipeline

public void Run(MetadataModel yaml, ResolverContext context)
{
if (yaml.Members != null && yaml.Members.Count > 0)
if (yaml.Members is {Count: > 0})
{
UpdateDerivedClassMapping(yaml.Members, context.References);
AppendDerivedClass(yaml.Members);
Expand All @@ -23,7 +23,7 @@ private void UpdateDerivedClassMapping(List<MetadataItem> items, Dictionary<stri
foreach (var item in items ?? Enumerable.Empty<MetadataItem>())
{
var inheritance = item.Inheritance;
if (inheritance != null && inheritance.Count > 0)
if (inheritance is {Count: > 0})
{
var superClass = inheritance[inheritance.Count - 1];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ public override MetadataItem VisitMethod(IMethodSymbol symbol)
}
_generator.GenerateSyntax(symbol, result.Syntax, _filter);

if (symbol.IsOverride && symbol.OverriddenMethod != null)
if (symbol is {IsOverride: true, OverriddenMethod: not null})
{
result.Overridden = AddSpecReference(symbol.OverriddenMethod, typeGenericParameters, methodGenericParameters);
}
Expand Down Expand Up @@ -296,7 +296,7 @@ public override MetadataItem VisitEvent(IEventSymbol symbol)

var typeGenericParameters = symbol.ContainingType.IsGenericType ? symbol.ContainingType.Accept(TypeGenericParameterNameVisitor.Instance) : EmptyListOfString;

if (symbol.IsOverride && symbol.OverriddenEvent != null)
if (symbol is {IsOverride: true, OverriddenEvent: not null})
{
result.Overridden = AddSpecReference(symbol.OverriddenEvent, typeGenericParameters);
}
Expand Down Expand Up @@ -350,7 +350,7 @@ public override MetadataItem VisitProperty(IPropertySymbol symbol)
Debug.Assert(result.Syntax.Return.Type != null);
}

if (symbol.IsOverride && symbol.OverriddenProperty != null)
if (symbol is {IsOverride: true, OverriddenProperty: not null})
{
result.Overridden = AddSpecReference(symbol.OverriddenProperty, typeGenericParameters);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public static string GetId(ISymbol symbol)
return null;
}

if (symbol is INamespaceSymbol namespaceSymbol && namespaceSymbol.IsGlobalNamespace)
if (symbol is INamespaceSymbol {IsGlobalNamespace: true})
{
return GlobalNamespaceId;
}
Expand Down
4 changes: 2 additions & 2 deletions src/Docfx.Dotnet/Parsers/XmlComment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,7 @@ private void ResolveCrefLink(XNode node, string nodeSelector, Action<string, str
if (!success)
{
var detailedInfo = new StringBuilder();
if (_context != null && _context.Source != null)
if (_context is {Source: not null})
{
if (!string.IsNullOrEmpty(_context.Source.Name))
{
Expand Down Expand Up @@ -631,7 +631,7 @@ static void MarkdownXmlDecode(MarkdownObject node)
MarkdownXmlDecode(child);
break;

case LeafBlock leafBlock when leafBlock.Inline is not null:
case LeafBlock {Inline: not null} leafBlock:
foreach (var child in leafBlock.Inline)
MarkdownXmlDecode(child);
break;
Expand Down
2 changes: 1 addition & 1 deletion src/Docfx.Dotnet/SymbolFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ bool IncludeAttributeDefault(ISymbol symbol)
private bool IsSymbolAccessible(ISymbol symbol)
{
// TODO: should we include implicitly declared members like constructors? They are part of the API contract.
if (symbol.IsImplicitlyDeclared && symbol.Kind is not SymbolKind.Namespace)
if (symbol is {IsImplicitlyDeclared: true, Kind: not SymbolKind.Namespace})
return false;

if (_config.IncludeExplicitInterfaceImplementations &&
Expand Down
6 changes: 3 additions & 3 deletions src/Docfx.Dotnet/SymbolFormatter.Syntax.cs
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ private void AddTypedConstant(TypedConstant typedConstant)
AddPunctuation(")");
break;

case TypedConstantKind.Array when !typedConstant.IsNull && typedConstant.Type is not null:
case TypedConstantKind.Array when typedConstant is {IsNull: false, Type: not null}:
AddKeyword("new", "New");
AddSpace();
AddTypeName(typedConstant.Type);
Expand Down Expand Up @@ -460,7 +460,7 @@ private void AddEnumConstant(TypedConstant typedConstant)

private bool ExpandEnumClassName(ISymbol symbol, SymbolDisplayPart part)
{
if (symbol.Kind != SymbolKind.Field && part.Kind == SymbolDisplayPartKind.EnumMemberName && part.Symbol is not null)
if (symbol.Kind != SymbolKind.Field && part is {Kind: SymbolDisplayPartKind.EnumMemberName, Symbol: not null})
{
_parts.Add(new(SymbolDisplayPartKind.EnumName, part.Symbol.ContainingSymbol, part.Symbol.ContainingSymbol.Name));
_parts.Add(new(SymbolDisplayPartKind.Punctuation, null, "."));
Expand All @@ -472,7 +472,7 @@ private bool ExpandEnumClassName(ISymbol symbol, SymbolDisplayPart part)

private bool StaticClassToVBModule(ISymbol symbol, SymbolDisplayPart part)
{
if (Language is SyntaxLanguage.VB && symbol.IsStatic && symbol.Kind is SymbolKind.NamedType &&
if (Language is SyntaxLanguage.VB && symbol is {IsStatic: true, Kind: SymbolKind.NamedType} &&
part.Kind == SymbolDisplayPartKind.Keyword && part.ToString() == "Class")
{
_parts.Add(new(SymbolDisplayPartKind.Keyword, null, "Module"));
Expand Down
2 changes: 1 addition & 1 deletion src/Docfx.Dotnet/SymbolFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ LinkItem ToLinkItem(SymbolDisplayPart part)
if (symbol is null || part.Kind is SymbolDisplayPartKind.TypeParameterName)
return new() { DisplayName = part.ToString() };

if (symbol is INamedTypeSymbol type && type.IsGenericType)
if (symbol is INamedTypeSymbol {IsGenericType: true} type)
symbol = type.ConstructedFrom;

return new()
Expand Down
2 changes: 1 addition & 1 deletion src/Docfx.Dotnet/SymbolHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public static bool IsMember(this ISymbol symbol)

public static bool IsClass(this ISymbol symbol)
{
return symbol.Kind is SymbolKind.NamedType && symbol is INamedTypeSymbol type && type.TypeKind is TypeKind.Class;
return symbol.Kind is SymbolKind.NamedType && symbol is INamedTypeSymbol {TypeKind: TypeKind.Class};
}

public static bool IsEnumMember(this ISymbol symbol)
Expand Down
2 changes: 1 addition & 1 deletion src/Docfx.Dotnet/SymbolUrlResolver.MSLearn.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ internal static string GetUrlFragmentFromUid(string uid)
case '}':
sb.Append("))");
break;
case char c when (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'):
case char and (>= 'a' and <= 'z' or >= '0' and <= '9'):
case '(' or ')' or '*' or '@':
sb.Append(ch);
break;
Expand Down
8 changes: 4 additions & 4 deletions src/Docfx.Dotnet/YamlViewModelExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ private static ReferenceViewModel ToReferenceViewModel(KeyValuePair<string, Refe
Parent = model.Value.Parent,
Definition = model.Value.Definition,
};
if (model.Value.NameParts != null && model.Value.NameParts.Count > 0)
if (model.Value.NameParts is {Count: > 0})
{
result.Name = GetName(model.Value.NameParts, SyntaxLanguage.Default);
var nameForCSharp = GetName(model.Value.NameParts, SyntaxLanguage.CSharp);
Expand Down Expand Up @@ -270,7 +270,7 @@ public static ItemViewModel ToItemViewModel(this MetadataItem model, ExtractMeta
Attributes = model.Attributes,
};

if (model.Parent != null && model.Parent.Name != null && !model.Name.StartsWith(model.Parent.Name))
if (model.Parent is {Name: not null} && !model.Name.StartsWith(model.Parent.Name))
{
result.Id = model.Name.Substring(model.Name.LastIndexOf('.') + 1);
}
Expand Down Expand Up @@ -330,7 +330,7 @@ public static SyntaxDetailViewModel ToSyntaxDetailViewModel(this SyntaxDetail mo
TypeParameters = model.TypeParameters,
Return = model.Return,
};
if (model.Content != null && model.Content.Count > 0)
if (model.Content is {Count: > 0})
{
result.Content = model.Content.GetLanguageProperty(SyntaxLanguage.Default);
var contentForCSharp = model.Content.GetLanguageProperty(SyntaxLanguage.CSharp);
Expand Down Expand Up @@ -379,7 +379,7 @@ public static TValue GetLanguageProperty<TValue>(this SortedList<SyntaxLanguage,

private static void AddChildren(MetadataItem model, PageViewModel result, ExtractMetadataConfig config)
{
if (model.Items != null && model.Items.Count > 0)
if (model.Items is {Count: > 0})
{
foreach (var item in model.Items)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ private static TabItemBlock CreateTabItem(
private static Tuple<string, string, LinkInline> ParseHeading(HeadingBlock block)
{
var child = block.Inline.FirstChild;
if (child != null && child.NextSibling == null && child is LinkInline link)
if (child is {NextSibling: null} and LinkInline link)
{
var m = HrefRegex.Match(link.Url);
if (m.Success)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ public override BlockState TryContinue(BlockProcessor processor, Block block)
public override bool Close(BlockProcessor processor, Block block)
{
var monikerRange = (MonikerRangeBlock)block;
if (monikerRange != null && monikerRange.Closed == false)
if (monikerRange is {Closed: false})
{
_context.LogWarning("invalid-moniker-range", $"No \"::: {EndString}\" found for \"{monikerRange.MonikerRange}\", MonikerRange does not end explicitly.", block);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,8 @@ public PlantUmlCodeBlockRenderer(MarkdownContext context, PlantUmlOptions settin

protected override void Write(HtmlRenderer renderer, CodeBlock obj)
{
if (obj is FencedCodeBlock fencedCodeBlock
&& fencedCodeBlock.Info is string info
&& info.Equals("plantuml", StringComparison.OrdinalIgnoreCase))
if (obj is FencedCodeBlock {Info: string info} fencedCodeBlock
&& info.Equals("plantuml", StringComparison.OrdinalIgnoreCase))
{
IPlantUmlRenderer plantUmlRenderer = rendererFactory.CreateRenderer(_settings);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ private void UpdateLinks(MarkdownObject markdownObject)
}
break;

case LeafBlock leafBlock when leafBlock.Inline != null:
case LeafBlock {Inline: not null} leafBlock:
foreach (var subInline in leafBlock.Inline)
{
UpdateLinks(subInline);
Expand Down
Loading

0 comments on commit 3e17f63

Please sign in to comment.