Merge pull request #3943 from davidwengier/NamingRules

Implement Roslyn naming rules
This commit is contained in:
David Wengier 2021-07-11 20:50:41 +10:00 коммит произвёл GitHub
Родитель 597e45d12e a3a74189a8
Коммит 3806f3c8a4
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
137 изменённых файлов: 946 добавлений и 877 удалений

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

@ -77,6 +77,49 @@ csharp_using_directive_placement = outside_namespace
# xUnit1004: Test methods should not be skipped
dotnet_diagnostic.xUnit1004.severity = refactoring
# Non-private static fields are PascalCase
dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.symbols = non_private_static_fields
dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.style = non_private_static_field_style
dotnet_naming_symbols.non_private_static_fields.applicable_kinds = field
dotnet_naming_symbols.non_private_static_fields.applicable_accessibilities = public, protected, internal, protected_internal, private_protected
dotnet_naming_symbols.non_private_static_fields.required_modifiers = static
dotnet_naming_style.non_private_static_field_style.capitalization = pascal_case
# Non-private readonly fields are PascalCase
dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.symbols = non_private_readonly_fields
dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.style = non_private_readonly_field_style
dotnet_naming_symbols.non_private_readonly_fields.applicable_kinds = field
dotnet_naming_symbols.non_private_readonly_fields.applicable_accessibilities = public, protected, internal, protected_internal, private_protected
dotnet_naming_symbols.non_private_readonly_fields.required_modifiers = readonly
dotnet_naming_style.non_private_readonly_field_style.capitalization = pascal_case
# Constants are PascalCase
dotnet_naming_rule.constants_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.constants_should_be_pascal_case.symbols = constants
dotnet_naming_rule.constants_should_be_pascal_case.style = constant_style
dotnet_naming_symbols.constants.applicable_kinds = field, local
dotnet_naming_symbols.constants.required_modifiers = const
dotnet_naming_style.constant_style.capitalization = pascal_case
# Static fields are camelCase and start with s_
dotnet_naming_rule.static_fields_should_be_camel_case.severity = suggestion
dotnet_naming_rule.static_fields_should_be_camel_case.symbols = static_fields
dotnet_naming_rule.static_fields_should_be_camel_case.style = static_field_style
dotnet_naming_symbols.static_fields.applicable_kinds = field
dotnet_naming_symbols.static_fields.required_modifiers = static
dotnet_naming_style.static_field_style.capitalization = camel_case
dotnet_naming_style.static_field_style.required_prefix = s_
# Instance fields are camelCase and start with _
dotnet_naming_rule.instance_fields_should_be_camel_case.severity = suggestion
dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields
@ -86,3 +129,30 @@ dotnet_naming_symbols.instance_fields.applicable_kinds = field
dotnet_naming_style.instance_field_style.capitalization = camel_case
dotnet_naming_style.instance_field_style.required_prefix = _
# Locals and parameters are camelCase
dotnet_naming_rule.locals_should_be_camel_case.severity = suggestion
dotnet_naming_rule.locals_should_be_camel_case.symbols = locals_and_parameters
dotnet_naming_rule.locals_should_be_camel_case.style = camel_case_style
dotnet_naming_symbols.locals_and_parameters.applicable_kinds = parameter, local
dotnet_naming_style.camel_case_style.capitalization = camel_case
# Local functions are PascalCase
dotnet_naming_rule.local_functions_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.local_functions_should_be_pascal_case.symbols = local_functions
dotnet_naming_rule.local_functions_should_be_pascal_case.style = local_function_style
dotnet_naming_symbols.local_functions.applicable_kinds = local_function
dotnet_naming_style.local_function_style.capitalization = pascal_case
# By default, name items with PascalCase
dotnet_naming_rule.members_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.members_should_be_pascal_case.symbols = all_members
dotnet_naming_rule.members_should_be_pascal_case.style = pascal_case_style
dotnet_naming_symbols.all_members.applicable_kinds = *
dotnet_naming_style.pascal_case_style.capitalization = pascal_case

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

@ -13,8 +13,8 @@ namespace Microsoft.AspNetCore.Razor.Microbenchmarks
public class FullProjectSnapshotHandleSerializationBenchmark
{
// Hardcoded expectations from `ProjectSystem\project.razor.json`
private static readonly string ExpectedFilePath = "C:\\Users\\admin\\location\\blazorserver\\blazorserver.csproj";
private static readonly int ExpectedTagHelperCount = 228;
private const string ExpectedFilePath = "C:\\Users\\admin\\location\\blazorserver\\blazorserver.csproj";
private const int ExpectedTagHelperCount = 228;
private JsonSerializer Serializer { get; set; }
private JsonReader Reader { get; set; }

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

@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Razor.Microbenchmarks
{
public abstract class TagHelperBenchmarkBase
{
protected readonly byte[] _tagHelperBuffer;
protected readonly byte[] TagHelperBuffer;
public TagHelperBenchmarkBase()
{
@ -23,14 +23,14 @@ namespace Microsoft.AspNetCore.Razor.Microbenchmarks
}
var tagHelperFilePath = Path.Combine(current.FullName, "taghelpers.json");
_tagHelperBuffer = File.ReadAllBytes(tagHelperFilePath);
TagHelperBuffer = File.ReadAllBytes(tagHelperFilePath);
// Deserialize from json file.
TagHelperDescriptorJsonConverter.DisableCachingForTesting = true;
DefaultSerializer = new JsonSerializer();
DefaultSerializer.Converters.Add(TagHelperDescriptorJsonConverter.Instance);
using var stream = new MemoryStream(_tagHelperBuffer);
using var stream = new MemoryStream(TagHelperBuffer);
using var reader = new JsonTextReader(new StreamReader(stream));
DefaultTagHelpers = DefaultSerializer.Deserialize<IReadOnlyList<TagHelperDescriptor>>(reader);
TagHelperDescriptorJsonConverter.DisableCachingForTesting = false;

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

@ -45,7 +45,7 @@ namespace Microsoft.AspNetCore.Razor.Microbenchmarks
{
// Deserialize from json file.
IReadOnlyList<TagHelperDescriptor> tagHelpers;
using var stream = new MemoryStream(_tagHelperBuffer);
using var stream = new MemoryStream(TagHelperBuffer);
using var reader = new JsonTextReader(new StreamReader(stream));
tagHelpers = DefaultSerializer.Deserialize<IReadOnlyList<TagHelperDescriptor>>(reader);
}

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

@ -8,10 +8,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Common
{
internal static class RazorCodeDocumentExtensions
{
private static readonly object UnsupportedKey = new object();
private static readonly object SourceTextKey = new object();
private static readonly object CSharpSourceTextKey = new object();
private static readonly object HtmlSourceTextKey = new object();
private static readonly object s_unsupportedKey = new object();
private static readonly object s_sourceTextKey = new object();
private static readonly object s_csharpSourceTextKey = new object();
private static readonly object s_htmlSourceTextKey = new object();
public static bool IsUnsupported(this RazorCodeDocument document)
{
@ -20,7 +20,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Common
throw new ArgumentNullException(nameof(document));
}
var unsupportedObj = document.Items[UnsupportedKey];
var unsupportedObj = document.Items[s_unsupportedKey];
if (unsupportedObj == null)
{
return false;
@ -36,7 +36,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Common
throw new ArgumentNullException(nameof(document));
}
document.Items[UnsupportedKey] = true;
document.Items[s_unsupportedKey] = true;
}
}
}

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

@ -17,7 +17,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.AutoInsert
internal class AutoClosingTagOnAutoInsertProvider : RazorOnAutoInsertProvider
{
// From http://dev.w3.org/html5/spec/Overview.html#elements-0
public static readonly HashSet<string> s_VoidElements = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
public static readonly HashSet<string> VoidElements = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"area",
"base",
@ -239,7 +239,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.AutoInsert
private static AutoClosingBehavior InferAutoClosingBehavior(string name)
{
if (s_VoidElements.Contains(name))
if (VoidElements.Contains(name))
{
return AutoClosingBehavior.SelfClosing;
}

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

@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
{
internal abstract class CSharpCodeActionResolver : BaseCodeActionResolver
{
protected readonly ClientNotifierServiceBase _languageServer;
protected readonly ClientNotifierServiceBase LanguageServer;
public CSharpCodeActionResolver(ClientNotifierServiceBase languageServer)
{
@ -21,7 +21,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
throw new ArgumentNullException(nameof(languageServer));
}
_languageServer = languageServer;
LanguageServer = languageServer;
}
public abstract Task<CodeAction> ResolveAsync(
@ -31,7 +31,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
protected async Task<CodeAction> ResolveCodeActionWithServerAsync(CodeAction codeAction, CancellationToken cancellationToken)
{
var response = await _languageServer.SendRequestAsync(LanguageServerConstants.RazorResolveCodeActionsEndpoint, codeAction).ConfigureAwait(false);
var response = await LanguageServer.SendRequestAsync(LanguageServerConstants.RazorResolveCodeActionsEndpoint, codeAction).ConfigureAwait(false);
var resolvedCodeAction = await response.Returning<CodeAction>(cancellationToken).ConfigureAwait(false);
return resolvedCodeAction;

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

@ -19,7 +19,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
// Usually when we need to format code, we utilize the formatting options provided
// by the platform. However, we aren't provided such options in the case of code actions
// so we use a default (and commonly used) configuration.
private static readonly FormattingOptions DefaultFormattingOptions = new FormattingOptions()
private static readonly FormattingOptions s_defaultFormattingOptions = new FormattingOptions()
{
TabSize = 4,
InsertSpaces = true,
@ -128,7 +128,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
documentSnapshot,
RazorLanguageKind.CSharp,
csharpTextEdits,
DefaultFormattingOptions,
s_defaultFormattingOptions,
cancellationToken,
bypassValidationPasses: true);

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

@ -19,7 +19,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
{
internal class TypeAccessibilityCodeActionProvider : CSharpCodeActionProvider
{
private static readonly IEnumerable<string> SupportedDiagnostics = new[]
private static readonly IEnumerable<string> s_supportedDiagnostics = new[]
{
// `The type or namespace name 'type/namespace' could not be found
// (are you missing a using directive or an assembly reference?)`
@ -74,7 +74,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
var diagnostics = context.Request.Context.Diagnostics.Where(diagnostic =>
diagnostic.Severity == DiagnosticSeverity.Error &&
diagnostic.Code?.IsString == true &&
SupportedDiagnostics.Any(d => diagnostic.Code.Value.String.Equals(d, StringComparison.OrdinalIgnoreCase)));
s_supportedDiagnostics.Any(d => diagnostic.Code.Value.String.Equals(d, StringComparison.OrdinalIgnoreCase)));
if (diagnostics is null || !diagnostics.Any())
{

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

@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
{
internal class CodeActionResolutionEndpoint : IRazorCodeActionResolveHandler
{
private static readonly string CodeActionsResolveProviderCapability = "codeActionsResolveProvider";
private const string CodeActionsResolveProviderCapability = "codeActionsResolveProvider";
private readonly IReadOnlyDictionary<string, RazorCodeActionResolver> _razorCodeActionResolvers;
private readonly IReadOnlyDictionary<string, CSharpCodeActionResolver> _csharpCodeActionResolvers;

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

@ -21,7 +21,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
{
internal class ComponentAccessibilityCodeActionProvider : RazorCodeActionProvider
{
private static readonly Task<IReadOnlyList<RazorCodeAction>> EmptyResult = Task.FromResult<IReadOnlyList<RazorCodeAction>>(null);
private static readonly Task<IReadOnlyList<RazorCodeAction>> s_emptyResult = Task.FromResult<IReadOnlyList<RazorCodeAction>>(null);
private readonly TagHelperFactsService _tagHelperFactsService;
private readonly FilePathNormalizer _filePathNormalizer;
@ -43,25 +43,25 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
var node = context.CodeDocument.GetSyntaxTree().Root.LocateOwner(change);
if (node is null)
{
return EmptyResult;
return s_emptyResult;
}
// Find start tag
var startTag = (MarkupStartTagSyntax)node.Ancestors().FirstOrDefault(n => n is MarkupStartTagSyntax);
if (startTag is null)
{
return EmptyResult;
return s_emptyResult;
}
// Ignore if start tag has dots, as we only handle short tags
if (startTag.Name.Content.Contains("."))
{
return EmptyResult;
return s_emptyResult;
}
if (!IsApplicableTag(startTag))
{
return EmptyResult;
return s_emptyResult;
}
if (IsTagUnknown(startTag, context))
@ -131,12 +131,12 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
// For all the matches, add options for add @using and fully qualify
foreach (var tagHelperPair in matching.Values)
{
if (tagHelperPair.FullyQualified is null)
if (tagHelperPair._fullyQualified is null)
{
continue;
}
var fullyQualifiedName = tagHelperPair.Short.Name;
var fullyQualifiedName = tagHelperPair._short.Name;
// Insert @using
var addUsingCodeAction = AddUsingsCodeActionProviderFactory.CreateAddUsingCodeAction(
@ -178,7 +178,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
{
if (tagHelper.TagMatchingRules.All(rule => TagHelperMatchingConventions.SatisfiesRule(tagName, parentTagName, attributes, rule)))
{
matching.Add(tagHelper.Name, new TagHelperPair { Short = tagHelper });
matching.Add(tagHelper.Name, new TagHelperPair { _short = tagHelper });
}
}
@ -187,9 +187,9 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
{
if (matching.TryGetValue(tagHelper.Name, out var tagHelperPair))
{
if (tagHelperPair != null && tagHelper != tagHelperPair.Short)
if (tagHelperPair != null && tagHelper != tagHelperPair._short)
{
tagHelperPair.FullyQualified = tagHelper;
tagHelperPair._fullyQualified = tagHelper;
}
}
}
@ -257,8 +257,8 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
private class TagHelperPair
{
public TagHelperDescriptor Short = null;
public TagHelperDescriptor FullyQualified = null;
public TagHelperDescriptor _short = null;
public TagHelperDescriptor _fullyQualified = null;
}
}
}

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

@ -20,73 +20,73 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
{
internal class ExtractToCodeBehindCodeActionProvider : RazorCodeActionProvider
{
private static readonly Task<IReadOnlyList<RazorCodeAction>> EmptyResult = Task.FromResult<IReadOnlyList<RazorCodeAction>>(null);
private static readonly Task<IReadOnlyList<RazorCodeAction>> s_emptyResult = Task.FromResult<IReadOnlyList<RazorCodeAction>>(null);
public override Task<IReadOnlyList<RazorCodeAction>> ProvideAsync(RazorCodeActionContext context, CancellationToken cancellationToken)
{
if (context is null)
{
return EmptyResult;
return s_emptyResult;
}
if (!context.SupportsFileCreation)
{
return EmptyResult;
return s_emptyResult;
}
if (!FileKinds.IsComponent(context.CodeDocument.GetFileKind()))
{
return EmptyResult;
return s_emptyResult;
}
var change = new SourceChange(context.Location.AbsoluteIndex, length: 0, newText: string.Empty);
var syntaxTree = context.CodeDocument.GetSyntaxTree();
if (syntaxTree?.Root is null)
{
return EmptyResult;
return s_emptyResult;
}
var owner = syntaxTree.Root.LocateOwner(change);
if (owner == null)
{
Debug.Fail("Owner should never be null.");
return EmptyResult;
return s_emptyResult;
}
var node = owner.Ancestors().FirstOrDefault(n => n.Kind == SyntaxKind.RazorDirective);
if (node == null || !(node is RazorDirectiveSyntax directiveNode))
{
return EmptyResult;
return s_emptyResult;
}
// Make sure we've found a @code or @functions
if (directiveNode.DirectiveDescriptor != ComponentCodeDirective.Directive &&
directiveNode.DirectiveDescriptor != FunctionsDirective.Directive)
{
return EmptyResult;
return s_emptyResult;
}
// No code action if malformed
if (directiveNode.GetDiagnostics().Any(d => d.Severity == RazorDiagnosticSeverity.Error))
{
return EmptyResult;
return s_emptyResult;
}
var csharpCodeBlockNode = directiveNode.Body.DescendantNodes().FirstOrDefault(n => n is CSharpCodeBlockSyntax);
if (csharpCodeBlockNode is null)
{
return EmptyResult;
return s_emptyResult;
}
if (HasUnsupportedChildren(csharpCodeBlockNode))
{
return EmptyResult;
return s_emptyResult;
}
// Do not provide code action if the cursor is inside the code block
if (context.Location.AbsoluteIndex > csharpCodeBlockNode.SpanStart)
{
return EmptyResult;
return s_emptyResult;
}
var actionParams = new ExtractToCodeBehindCodeActionParams()

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

@ -30,7 +30,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
private readonly DocumentResolver _documentResolver;
private readonly FilePathNormalizer _filePathNormalizer;
private static readonly Range StartOfDocumentRange = new Range(new Position(0, 0), new Position(0, 0));
private static readonly Range s_startOfDocumentRange = new Range(new Position(0, 0), new Position(0, 0));
public ExtractToCodeBehindCodeActionResolver(
ForegroundDispatcher foregroundDispatcher,
@ -130,7 +130,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
new TextEdit
{
NewText = codeBehindContent,
Range = StartOfDocumentRange,
Range = s_startOfDocumentRange,
}
},
})

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

@ -12,15 +12,15 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
{
internal class DirectiveAttributeTransitionCompletionItemProvider : DirectiveAttributeCompletionItemProviderBase
{
private static RazorCompletionItem _transitionCompletionItem;
private static RazorCompletionItem s_transitionCompletionItem;
public static RazorCompletionItem TransitionCompletionItem
{
get
{
if (_transitionCompletionItem == null)
if (s_transitionCompletionItem == null)
{
_transitionCompletionItem = new RazorCompletionItem(
s_transitionCompletionItem = new RazorCompletionItem(
displayText: "@...",
insertText: "@",
kind: RazorCompletionItemKind.Directive,
@ -32,14 +32,14 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
// where this directive attribute transition character ("@...") gets provided and then typing
// `@` should re-trigger OR typing `/` should re-trigger.
commitCharacters: new[] { "@", "/", ">" });
_transitionCompletionItem.SetDirectiveCompletionDescription(new DirectiveCompletionDescription(RazorLS.Resources.Blazor_directive_attributes));
s_transitionCompletionItem.SetDirectiveCompletionDescription(new DirectiveCompletionDescription(RazorLS.Resources.Blazor_directive_attributes));
}
return _transitionCompletionItem;
return s_transitionCompletionItem;
}
}
private static readonly IReadOnlyList<RazorCompletionItem> Completions = new[] { TransitionCompletionItem };
private static readonly IReadOnlyList<RazorCompletionItem> s_completions = new[] { TransitionCompletionItem };
public override IReadOnlyList<RazorCompletionItem> GetCompletionItems(RazorSyntaxTree syntaxTree, TagHelperDocumentContext tagHelperDocumentContext, SourceSpan location)
{
@ -61,7 +61,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
if (attribute is MarkupMiscAttributeContentSyntax && attribute.ContainsOnlyWhitespace())
{
// This represents a tag when there's no attribute content <InputText | />.
return Completions;
return s_completions;
}
if (!TryGetAttributeInfo(owner, out var prefixLocation, out var attributeName, out var attributeNameLocation, out _, out _))
@ -82,7 +82,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
}
// This represents a tag when there's no attribute content <InputText | />.
return Completions;
return s_completions;
}
// Internal for testing

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

@ -19,13 +19,13 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
public class OptimizedCompletionListJsonConverter : JsonConverter
{
public static readonly OptimizedCompletionListJsonConverter Instance = new OptimizedCompletionListJsonConverter();
private static readonly ConcurrentDictionary<object, string> CommitCharactersRawJson;
private static readonly JsonSerializer DefaultSerializer;
private static readonly ConcurrentDictionary<object, string> s_commitCharactersRawJson;
private static readonly JsonSerializer s_defaultSerializer;
static OptimizedCompletionListJsonConverter()
{
DefaultSerializer = JsonSerializer.CreateDefault();
CommitCharactersRawJson = new ConcurrentDictionary<object, string>();
s_defaultSerializer = JsonSerializer.CreateDefault();
s_commitCharactersRawJson = new ConcurrentDictionary<object, string>();
}
public override bool CanConvert(Type objectType)
@ -35,7 +35,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var result = DefaultSerializer.Deserialize(reader, objectType);
var result = s_defaultSerializer.Deserialize(reader, objectType);
return result;
}
@ -150,10 +150,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
{
writer.WritePropertyName("commitCharacters");
if (!CommitCharactersRawJson.TryGetValue(completionItem.CommitCharacters, out var jsonString))
if (!s_commitCharactersRawJson.TryGetValue(completionItem.CommitCharacters, out var jsonString))
{
jsonString = JsonConvert.SerializeObject(completionItem.CommitCharacters);
CommitCharactersRawJson.TryAdd(completionItem.CommitCharacters, jsonString);
s_commitCharactersRawJson.TryAdd(completionItem.CommitCharacters, jsonString);
}
writer.WriteRawValue(jsonString);

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

@ -32,7 +32,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
private readonly VSLSPTagHelperTooltipFactory _vsLspTagHelperTooltipFactory;
private readonly ClientNotifierServiceBase _languageServer;
private readonly CompletionListCache _completionListCache;
private static readonly Command RetriggerCompletionCommand = new()
private static readonly Command s_retriggerCompletionCommand = new()
{
Name = "editor.action.triggerSuggest",
Title = RazorLS.Resources.ReTrigger_Completions_Title,
@ -348,7 +348,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
if (razorCompletionItem == DirectiveAttributeTransitionCompletionItemProvider.TransitionCompletionItem)
{
directiveCompletionItem.Command = RetriggerCompletionCommand;
directiveCompletionItem.Command = s_retriggerCompletionCommand;
directiveCompletionItem.Kind = tagHelperCompletionItemKind;
}

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

@ -11,11 +11,11 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
{
internal static class RazorCompletionItemExtensions
{
private readonly static string TagHelperElementCompletionDescriptionKey = "Razor.TagHelperElementDescription";
private readonly static string s_tagHelperElementCompletionDescriptionKey = "Razor.TagHelperElementDescription";
public static void SetTagHelperElementDescriptionInfo(this RazorCompletionItem completionItem, AggregateBoundElementDescription elementDescriptionInfo)
{
completionItem.Items[TagHelperElementCompletionDescriptionKey] = elementDescriptionInfo;
completionItem.Items[s_tagHelperElementCompletionDescriptionKey] = elementDescriptionInfo;
}
public static AggregateBoundElementDescription? GetTagHelperElementDescriptionInfo(this RazorCompletionItem completionItem)
@ -25,7 +25,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
throw new ArgumentNullException(nameof(completionItem));
}
var description = completionItem.Items[TagHelperElementCompletionDescriptionKey] as AggregateBoundElementDescription;
var description = completionItem.Items[s_tagHelperElementCompletionDescriptionKey] as AggregateBoundElementDescription;
return description;
}
}

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

@ -22,8 +22,8 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
internal static readonly IReadOnlyCollection<string> MinimizedAttributeCommitCharacters = new List<string> { "=", " " };
internal static readonly IReadOnlyCollection<string> AttributeCommitCharacters = new List<string> { "=" };
private static readonly IReadOnlyCollection<string> ElementCommitCharacters = new List<string> { " ", ">" };
private static readonly IReadOnlyCollection<string> NoCommitCharacters = new List<string>();
private static readonly IReadOnlyCollection<string> s_elementCommitCharacters = new List<string> { " ", ">" };
private static readonly IReadOnlyCollection<string> s_noCommitCharacters = new List<string>();
private readonly HtmlFactsService _htmlFactsService;
private readonly TagHelperCompletionService _tagHelperCompletionService;
private readonly TagHelperFactsService _tagHelperFactsService;
@ -217,7 +217,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
displayText: completion.Key,
insertText: completion.Key,
RazorCompletionItemKind.TagHelperElement,
ElementCommitCharacters);
s_elementCommitCharacters);
var tagHelperDescriptions = completion.Value.Select(tagHelper => BoundElementDescriptionInfo.From(tagHelper));
var elementDescription = new AggregateBoundElementDescription(tagHelperDescriptions.ToList());
@ -233,7 +233,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
{
if (indexerCompletion)
{
return NoCommitCharacters;
return s_noCommitCharacters;
}
else if (boundAttributes.Any(b => b.TypeName == "System.Boolean"))
{

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

@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
internal const int MaxDocumentTrackingCount = 20;
// Internal for testing
internal readonly Dictionary<string, List<DocumentEntry>> _documentLookup;
internal readonly Dictionary<string, List<DocumentEntry>> DocumentLookup;
private readonly ForegroundDispatcher _foregroundDispatcher;
private ProjectSnapshotManagerBase _projectSnapshotManager;
@ -25,7 +25,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
}
_foregroundDispatcher = foregroundDispatcher;
_documentLookup = new Dictionary<string, List<DocumentEntry>>(FilePathComparer.Instance);
DocumentLookup = new Dictionary<string, List<DocumentEntry>>(FilePathComparer.Instance);
}
public override void TrackDocumentVersion(DocumentSnapshot documentSnapshot, int version)
@ -37,10 +37,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
_foregroundDispatcher.AssertForegroundThread();
if (!_documentLookup.TryGetValue(documentSnapshot.FilePath, out var documentEntries))
if (!DocumentLookup.TryGetValue(documentSnapshot.FilePath, out var documentEntries))
{
documentEntries = new List<DocumentEntry>();
_documentLookup[documentSnapshot.FilePath] = documentEntries;
DocumentLookup[documentSnapshot.FilePath] = documentEntries;
}
if (documentEntries.Count == MaxDocumentTrackingCount)
@ -65,7 +65,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
_foregroundDispatcher.AssertForegroundThread();
if (!_documentLookup.TryGetValue(documentSnapshot.FilePath, out var documentEntries))
if (!DocumentLookup.TryGetValue(documentSnapshot.FilePath, out var documentEntries))
{
version = null;
return false;
@ -106,11 +106,11 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
switch (args.Kind)
{
case ProjectChangeKind.DocumentChanged:
if (_documentLookup.ContainsKey(args.DocumentFilePath) &&
if (DocumentLookup.ContainsKey(args.DocumentFilePath) &&
!_projectSnapshotManager.IsDocumentOpen(args.DocumentFilePath))
{
// Document closed, evict entry.
_documentLookup.Remove(args.DocumentFilePath);
DocumentLookup.Remove(args.DocumentFilePath);
}
break;
}
@ -147,7 +147,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
// Internal for testing
internal bool TryGetLatestVersionFromPath(string filePath, out int? version)
{
if (!_documentLookup.TryGetValue(filePath, out var documentEntries))
if (!DocumentLookup.TryGetValue(filePath, out var documentEntries))
{
version = null;
return false;
@ -163,7 +163,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
{
foreach (var documentPath in projectSnapshot.DocumentFilePaths)
{
if (_documentLookup.ContainsKey(documentPath))
if (DocumentLookup.ContainsKey(documentPath))
{
var document = projectSnapshot.GetDocument(documentPath);
MarkAsLatestVersion(document);

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

@ -11,8 +11,8 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
{
// We mark this as Lazy because construction of an AdhocWorkspace without services will utilize MEF under the covers
// which can be expensive and we don't want to do that until absolutely necessary.
private static readonly Lazy<Workspace> DefaultWorkspace = new Lazy<Workspace>(() => new AdhocWorkspace());
private static readonly Lazy<Workspace> s_defaultWorkspace = new Lazy<Workspace>(() => new AdhocWorkspace());
public override HostServices GetServices() => DefaultWorkspace.Value.Services.HostServices;
public override HostServices GetServices() => s_defaultWorkspace.Value.Services.HostServices;
}
}

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

@ -381,16 +381,16 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
}
}
private static bool _haveAsserted = false;
private static bool s_haveAsserted = false;
private static bool IsRangeWithinDocument(Range range, SourceText sourceText)
{
// This might happen when the document that ranges were created against was not the same as the document we're consulting.
var result = IsPositionWithinDocument(range.Start, sourceText) && IsPositionWithinDocument(range.End, sourceText);
if(!_haveAsserted && !result)
if(!s_haveAsserted && !result)
{
_haveAsserted = true;
s_haveAsserted = true;
Debug.Fail($"Attempted to map a range {range} outside of the Source (line count {sourceText.Lines.Count}.) This could happen if the Roslyn and Razor LSP servers are not in sync.");
}

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

@ -25,8 +25,6 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Definition
private readonly DocumentResolver _documentResolver;
private readonly RazorComponentSearchEngine _componentSearchEngine;
private DefinitionCapability _capability { get; set; }
public RazorDefinitionEndpoint(
ForegroundDispatcher foregroundDispatcher,
DocumentResolver documentResolver,
@ -112,7 +110,6 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Definition
public void SetCapability(DefinitionCapability capability)
{
_capability = capability;
}
internal static async Task<TagHelperBinding> GetOriginTagHelperBindingAsync(

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

@ -18,7 +18,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
private readonly RazorProjectService _projectService;
private readonly FilePathNormalizer _filePathNormalizer;
private readonly Dictionary<string, string> _configurationToProjectMap;
internal readonly Dictionary<string, DelayedProjectInfo> _projectInfoMap;
internal readonly Dictionary<string, DelayedProjectInfo> ProjectInfoMap;
public ProjectConfigurationStateSynchronizer(
ForegroundDispatcher foregroundDispatcher,
@ -44,7 +44,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
_projectService = projectService;
_filePathNormalizer = filePathNormalizer;
_configurationToProjectMap = new Dictionary<string, string>(FilePathComparer.Instance);
_projectInfoMap = new Dictionary<string, DelayedProjectInfo>(FilePathComparer.Instance);
ProjectInfoMap = new Dictionary<string, DelayedProjectInfo>(FilePathComparer.Instance);
}
internal int EnqueueDelay { get; set; } = 250;
@ -141,18 +141,18 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
{
await Task.Delay(EnqueueDelay).ConfigureAwait(true);
var delayedProjectInfo = _projectInfoMap[projectFilePath];
var delayedProjectInfo = ProjectInfoMap[projectFilePath];
UpdateProject(projectFilePath, delayedProjectInfo.FullProjectSnapshotHandle);
}
void EnqueueUpdateProject(string projectFilePath, FullProjectSnapshotHandle snapshotHandle)
{
if (!_projectInfoMap.ContainsKey(projectFilePath))
if (!ProjectInfoMap.ContainsKey(projectFilePath))
{
_projectInfoMap[projectFilePath] = new DelayedProjectInfo();
ProjectInfoMap[projectFilePath] = new DelayedProjectInfo();
}
var delayedProjectInfo = _projectInfoMap[projectFilePath];
var delayedProjectInfo = ProjectInfoMap[projectFilePath];
delayedProjectInfo.FullProjectSnapshotHandle = snapshotHandle;
if (delayedProjectInfo.ProjectUpdateTask is null || delayedProjectInfo.ProjectUpdateTask.IsCompleted)

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

@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.ProjectSystem
internal class DefaultProjectResolver : ProjectResolver
{
// Internal for testing
protected internal readonly HostProject _miscellaneousHostProject;
protected internal readonly HostProject MiscellaneousHostProject;
private readonly ForegroundDispatcher _foregroundDispatcher;
private readonly FilePathNormalizer _filePathNormalizer;
@ -43,7 +43,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.ProjectSystem
_projectSnapshotManagerAccessor = projectSnapshotManagerAccessor;
var miscellaneousProjectPath = Path.Combine(TempDirectory.Instance.DirectoryPath, "__MISC_RAZOR_PROJECT__");
_miscellaneousHostProject = new HostProject(miscellaneousProjectPath, RazorDefaults.Configuration, RazorDefaults.RootNamespace);
MiscellaneousHostProject = new HostProject(miscellaneousProjectPath, RazorDefaults.Configuration, RazorDefaults.RootNamespace);
}
public override bool TryResolveProject(string documentFilePath, out ProjectSnapshot projectSnapshot, bool enforceDocumentInProject = true)
@ -61,7 +61,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.ProjectSystem
{
projectSnapshot = projects[i];
if (projectSnapshot.FilePath == _miscellaneousHostProject.FilePath)
if (projectSnapshot.FilePath == MiscellaneousHostProject.FilePath)
{
if (enforceDocumentInProject &&
IsDocumentInProject(projectSnapshot, documentFilePath))
@ -93,11 +93,11 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.ProjectSystem
{
_foregroundDispatcher.AssertForegroundThread();
var miscellaneousProject = _projectSnapshotManagerAccessor.Instance.GetLoadedProject(_miscellaneousHostProject.FilePath);
var miscellaneousProject = _projectSnapshotManagerAccessor.Instance.GetLoadedProject(MiscellaneousHostProject.FilePath);
if (miscellaneousProject == null)
{
_projectSnapshotManagerAccessor.Instance.ProjectAdded(_miscellaneousHostProject);
miscellaneousProject = _projectSnapshotManagerAccessor.Instance.GetLoadedProject(_miscellaneousHostProject.FilePath);
_projectSnapshotManagerAccessor.Instance.ProjectAdded(MiscellaneousHostProject);
miscellaneousProject = _projectSnapshotManagerAccessor.Instance.GetLoadedProject(MiscellaneousHostProject.FilePath);
}
return miscellaneousProject;

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

@ -21,11 +21,11 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
{
// Internal for testing
internal TimeSpan _publishDelay = TimeSpan.FromSeconds(2);
internal readonly Dictionary<string, IReadOnlyList<RazorDiagnostic>> _publishedDiagnostics;
internal readonly Dictionary<string, IReadOnlyList<RazorDiagnostic>> PublishedDiagnostics;
internal Timer _workTimer;
internal Timer _documentClosedTimer;
private static readonly TimeSpan CheckForDocumentClosedDelay = TimeSpan.FromSeconds(5);
private static readonly TimeSpan s_checkForDocumentClosedDelay = TimeSpan.FromSeconds(5);
private readonly ForegroundDispatcher _foregroundDispatcher;
private readonly ITextDocumentLanguageServer _languageServer;
private readonly Dictionary<string, DocumentSnapshot> _work;
@ -54,7 +54,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
_foregroundDispatcher = foregroundDispatcher;
_languageServer = languageServer;
_publishedDiagnostics = new Dictionary<string, IReadOnlyList<RazorDiagnostic>>(FilePathComparer.Instance);
PublishedDiagnostics = new Dictionary<string, IReadOnlyList<RazorDiagnostic>>(FilePathComparer.Instance);
_work = new Dictionary<string, DocumentSnapshot>(FilePathComparer.Instance);
_logger = loggerFactory.CreateLogger<RazorDiagnosticsPublisher>();
}
@ -106,7 +106,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
{
if (_documentClosedTimer == null)
{
_documentClosedTimer = new Timer(DocumentClosedTimer_Tick, null, CheckForDocumentClosedDelay, Timeout.InfiniteTimeSpan);
_documentClosedTimer = new Timer(DocumentClosedTimer_Tick, null, s_checkForDocumentClosedDelay, Timeout.InfiniteTimeSpan);
}
}
@ -124,15 +124,15 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
// Internal for testing
internal void ClearClosedDocuments()
{
lock (_publishedDiagnostics)
lock (PublishedDiagnostics)
{
var publishedDiagnostics = new Dictionary<string, IReadOnlyList<RazorDiagnostic>>(_publishedDiagnostics);
var publishedDiagnostics = new Dictionary<string, IReadOnlyList<RazorDiagnostic>>(PublishedDiagnostics);
foreach (var entry in publishedDiagnostics)
{
if (!_projectManager.IsDocumentOpen(entry.Key))
{
// Document is now closed, we shouldn't track its diagnostics anymore.
_publishedDiagnostics.Remove(entry.Key);
PublishedDiagnostics.Remove(entry.Key);
// If the last published diagnostics for the document were > 0 then we need to clear them out so the user
// doesn't have a ton of closed document errors that they can't get rid of.
@ -146,7 +146,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
_documentClosedTimer?.Dispose();
_documentClosedTimer = null;
if (_publishedDiagnostics.Count > 0)
if (PublishedDiagnostics.Count > 0)
{
lock (_work)
{
@ -165,16 +165,16 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
var diagnostics = result.GetCSharpDocument().Diagnostics;
lock (_publishedDiagnostics)
lock (PublishedDiagnostics)
{
if (_publishedDiagnostics.TryGetValue(document.FilePath, out var previousDiagnostics) &&
if (PublishedDiagnostics.TryGetValue(document.FilePath, out var previousDiagnostics) &&
diagnostics.SequenceEqual(previousDiagnostics))
{
// Diagnostics are the same as last publish
return;
}
_publishedDiagnostics[document.FilePath] = diagnostics;
PublishedDiagnostics[document.FilePath] = diagnostics;
}
if (!document.TryGetText(out var sourceText))

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

@ -15,10 +15,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
{
internal class RazorFileChangeDetector : IFileChangeDetector
{
private static readonly IReadOnlyList<string> RazorFileExtensions = new[] { ".razor", ".cshtml" };
private static readonly IReadOnlyList<string> s_razorFileExtensions = new[] { ".razor", ".cshtml" };
// Internal for testing
internal readonly Dictionary<string, DelayedFileChangeNotification> _pendingNotifications;
internal readonly Dictionary<string, DelayedFileChangeNotification> PendingNotifications;
private readonly ForegroundDispatcher _foregroundDispatcher;
private readonly FilePathNormalizer _filePathNormalizer;
@ -49,8 +49,8 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
_foregroundDispatcher = foregroundDispatcher;
_filePathNormalizer = filePathNormalizer;
_listeners = listeners;
_watchers = new List<FileSystemWatcher>(RazorFileExtensions.Count);
_pendingNotifications = new Dictionary<string, DelayedFileChangeNotification>(FilePathComparer.Instance);
_watchers = new List<FileSystemWatcher>(s_razorFileExtensions.Count);
PendingNotifications = new Dictionary<string, DelayedFileChangeNotification>(FilePathComparer.Instance);
}
// Internal for testing
@ -94,9 +94,9 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
// Start listening for project file changes (added/removed/renamed).
for (var i = 0; i < RazorFileExtensions.Count; i++)
for (var i = 0; i < s_razorFileExtensions.Count; i++)
{
var extension = RazorFileExtensions[i];
var extension = s_razorFileExtensions[i];
var watcher = new RazorFileSystemWatcher(workspaceDirectory, "*" + extension)
{
NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.CreationTime,
@ -149,9 +149,9 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
protected virtual IReadOnlyList<string> GetExistingRazorFiles(string workspaceDirectory)
{
var existingRazorFiles = Enumerable.Empty<string>();
for (var i = 0; i < RazorFileExtensions.Count; i++)
for (var i = 0; i < s_razorFileExtensions.Count; i++)
{
var extension = RazorFileExtensions[i];
var extension = s_razorFileExtensions[i];
var existingFiles = Directory.GetFiles(workspaceDirectory, "*" + extension, SearchOption.AllDirectories);
existingRazorFiles = existingRazorFiles.Concat(existingFiles);
}
@ -164,10 +164,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
{
lock (_pendingNotificationsLock)
{
if (!_pendingNotifications.TryGetValue(physicalFilePath, out var currentNotification))
if (!PendingNotifications.TryGetValue(physicalFilePath, out var currentNotification))
{
currentNotification = new DelayedFileChangeNotification();
_pendingNotifications[physicalFilePath] = currentNotification;
PendingNotifications[physicalFilePath] = currentNotification;
}
if (currentNotification.ChangeKind != null)
@ -215,10 +215,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
{
lock (_pendingNotificationsLock)
{
var result = _pendingNotifications.TryGetValue(physicalFilePath, out var notification);
var result = PendingNotifications.TryGetValue(physicalFilePath, out var notification);
Debug.Assert(result, "We should always have an associated notification after delaying an update.");
_pendingNotifications.Remove(physicalFilePath);
PendingNotifications.Remove(physicalFilePath);
if (notification.ChangeKind == null)
{

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

@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
{
private readonly RazorConfigurationService _configurationService;
private readonly IOptionsMonitorCache<RazorLSPOptions> _cache;
internal event Action<RazorLSPOptions, string> _onChange;
private event Action<RazorLSPOptions, string> OnChangeEvent;
private RazorLSPOptions _currentValue;
public RazorLSPOptionsMonitor(RazorConfigurationService configurationService, IOptionsMonitorCache<RazorLSPOptions> cache)
@ -43,7 +43,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
public IDisposable OnChange(Action<RazorLSPOptions, string> listener)
{
var disposable = new ChangeTrackerDisposable(this, listener);
_onChange += disposable.OnChange;
OnChangeEvent += disposable.OnChange;
return disposable;
}
@ -62,7 +62,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
var name = Options.DefaultName;
_cache.TryRemove(name);
var options = Get(name);
_onChange?.Invoke(options, name);
OnChangeEvent?.Invoke(options, name);
}
internal class ChangeTrackerDisposable : IDisposable
@ -78,7 +78,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
public void OnChange(RazorLSPOptions options, string name) => _listener.Invoke(options, name);
public void Dispose() => _monitor._onChange -= OnChange;
public void Dispose() => _monitor.OnChangeEvent -= OnChange;
}
}
}

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

@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
internal record RazorLanguageServerCapability(bool LanguageQuery, bool RangeMapping, bool EditMapping, bool MonitorProjectConfigurationFilePath)
{
private const string RazorCapabilityKey = "razor";
private static readonly RazorLanguageServerCapability Default = new RazorLanguageServerCapability(LanguageQuery: true, RangeMapping: true, EditMapping: true, MonitorProjectConfigurationFilePath: true);
private static readonly RazorLanguageServerCapability s_default = new RazorLanguageServerCapability(LanguageQuery: true, RangeMapping: true, EditMapping: true, MonitorProjectConfigurationFilePath: true);
public static void AddTo(ServerCapabilities capabilities)
{
@ -19,7 +19,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
// server capabilities to our client side code having lost the information of the custom capabilities. To avoid this we use the
// experimental bag since it's part of the official LSP spec. This approach enables us to work with any client.
capabilities.Experimental ??= new Dictionary<string, JToken>();
capabilities.Experimental[RazorCapabilityKey] = JToken.FromObject(Default);
capabilities.Experimental[RazorCapabilityKey] = JToken.FromObject(s_default);
}
public static bool TryGet(JToken token, out RazorLanguageServerCapability razorCapability)

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

@ -148,7 +148,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Semantic.Models
MarkupAttributeValueString,
};
private static readonly string[] _tokenModifiers = new string[] {
private static readonly string[] s_tokenModifiers = new string[] {
// Razor
"None",
// C# Modifiers
@ -159,7 +159,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Semantic.Models
public static readonly SemanticTokensLegend Instance = new SemanticTokensLegend
{
TokenModifiers = new Container<string>(_tokenModifiers),
TokenModifiers = new Container<string>(s_tokenModifiers),
TokenTypes = new Container<string>(TokenTypes),
};

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

@ -26,16 +26,16 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
var edits = new List<DiffEdit>();
// Initialize the vectors to use for forward and reverse searches.
var MAX = NewTextLength + OldTextLength;
var Vf = new int[(2 * MAX) + 1];
var Vr = new int[(2 * MAX) + 1];
var max = NewTextLength + OldTextLength;
var vf = new int[(2 * max) + 1];
var vr = new int[(2 * max) + 1];
ComputeDiffRecursive(edits, 0, OldTextLength, 0, NewTextLength, Vf, Vr);
ComputeDiffRecursive(edits, 0, OldTextLength, 0, NewTextLength, vf, vr);
return edits;
}
private void ComputeDiffRecursive(List<DiffEdit> edits, int lowA, int highA, int lowB, int highB, int[] Vf, int[] Vr)
private void ComputeDiffRecursive(List<DiffEdit> edits, int lowA, int highA, int lowB, int highB, int[] vf, int[] vr)
{
while (lowA < highA && lowB < highB && ContentEquals(lowA, lowB))
{
@ -72,55 +72,55 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
else
{
// Find the midpoint of the optimal path.
var (middleX, middleY) = FindMiddleSnake(lowA, highA, lowB, highB, Vf, Vr);
var (middleX, middleY) = FindMiddleSnake(lowA, highA, lowB, highB, vf, vr);
// Recursively find the midpoint of the left half.
ComputeDiffRecursive(edits, lowA, middleX, lowB, middleY, Vf, Vr);
ComputeDiffRecursive(edits, lowA, middleX, lowB, middleY, vf, vr);
// Recursively find the midpoint of the right half.
ComputeDiffRecursive(edits, middleX, highA, middleY, highB, Vf, Vr);
ComputeDiffRecursive(edits, middleX, highA, middleY, highB, vf, vr);
}
}
private (int, int) FindMiddleSnake(int lowA, int highA, int lowB, int highB, int[] Vf, int[] Vr)
private (int, int) FindMiddleSnake(int lowA, int highA, int lowB, int highB, int[] vf, int[] vr)
{
var N = highA - lowA;
var M = highB - lowB;
var delta = N - M;
var n = highA - lowA;
var m = highB - lowB;
var delta = n - m;
var deltaIsEven = delta % 2 == 0;
var MAX = N + M;
var max = n + m;
// Compute the k-line to start the forward and reverse searches.
var forwardK = lowA - lowB;
var reverseK = highA - highB;
// The paper uses negative indexes but we can't do that here. So we'll add an offset.
var forwardOffset = MAX - forwardK;
var reverseOffset = MAX - reverseK;
var forwardOffset = max - forwardK;
var reverseOffset = max - reverseK;
// Initialize the vector
Vf[forwardOffset + forwardK + 1] = lowA;
Vr[reverseOffset + reverseK - 1] = highA;
vf[forwardOffset + forwardK + 1] = lowA;
vr[reverseOffset + reverseK - 1] = highA;
var maxD = Math.Ceiling((double)(M + N) / 2);
for (var D = 0; D <= maxD; D++) // For D ← 0 to ceil((M + N)/2) Do
var maxD = Math.Ceiling((double)(m + n) / 2);
for (var d = 0; d <= maxD; d++) // For D ← 0 to ceil((M + N)/2) Do
{
// Run the algorithm in forward direction.
for (var k = forwardK - D; k <= forwardK + D; k += 2) // For k ← D to D in steps of 2 Do
for (var k = forwardK - d; k <= forwardK + d; k += 2) // For k ← D to D in steps of 2 Do
{
// Find the end of the furthest reaching forward D-path in diagonal k.
int x;
if (k == forwardK - D ||
(k != forwardK + D && Vf[forwardOffset + k - 1] < Vf[forwardOffset + k + 1]))
if (k == forwardK - d ||
(k != forwardK + d && vf[forwardOffset + k - 1] < vf[forwardOffset + k + 1]))
{
// Down
x = Vf[forwardOffset + k + 1];
x = vf[forwardOffset + k + 1];
}
else
{
// Right
x = Vf[forwardOffset + k - 1] + 1;
x = vf[forwardOffset + k - 1] + 1;
}
var y = x - k;
@ -132,17 +132,17 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
y++;
}
Vf[forwardOffset + k] = x;
vf[forwardOffset + k] = x;
if (deltaIsEven)
{
// Can't have overlap here.
}
else if (k > reverseK - D && k < reverseK + D) // If ∆ is odd and k ∈ [∆ (D 1) , ∆ + (D 1)] Then
else if (k > reverseK - d && k < reverseK + d) // If ∆ is odd and k ∈ [∆ (D 1) , ∆ + (D 1)] Then
{
if (Vr[reverseOffset + k] <= Vf[forwardOffset + k]) // If the path overlaps the furthest reaching reverse (D 1)-path in diagonal k Then
if (vr[reverseOffset + k] <= vf[forwardOffset + k]) // If the path overlaps the furthest reaching reverse (D 1)-path in diagonal k Then
{
// The last snake of the forward path is the middle snake.
x = Vf[forwardOffset + k];
x = vf[forwardOffset + k];
y = x - k;
return (x, y);
}
@ -150,20 +150,20 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
}
// Run the algorithm in reverse direction.
for (var k = reverseK - D; k <= reverseK + D; k += 2) // For k ← D to D in steps of 2 Do
for (var k = reverseK - d; k <= reverseK + d; k += 2) // For k ← D to D in steps of 2 Do
{
// Find the end of the furthest reaching reverse D-path in diagonal k+∆.
int x;
if (k == reverseK + D ||
(k != reverseK - D && Vr[reverseOffset + k - 1] < Vr[reverseOffset + k + 1] - 1))
if (k == reverseK + d ||
(k != reverseK - d && vr[reverseOffset + k - 1] < vr[reverseOffset + k + 1] - 1))
{
// Up
x = Vr[reverseOffset + k - 1];
x = vr[reverseOffset + k - 1];
}
else
{
// Left
x = Vr[reverseOffset + k + 1] - 1;
x = vr[reverseOffset + k + 1] - 1;
}
var y = x - k;
@ -175,17 +175,17 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
y--;
}
Vr[reverseOffset + k] = x;
vr[reverseOffset + k] = x;
if (!deltaIsEven)
{
// Can't have overlap here.
}
else if (k >= forwardK - D && k <= forwardK + D) // If ∆ is even and k + ∆ ∈ [D, D] Then
else if (k >= forwardK - d && k <= forwardK + d) // If ∆ is even and k + ∆ ∈ [D, D] Then
{
if (Vr[reverseOffset + k] <= Vf[forwardOffset + k]) // If the path overlaps the furthest reaching forward D-path in diagonal k+∆ Then
if (vr[reverseOffset + k] <= vf[forwardOffset + k]) // If the path overlaps the furthest reaching forward D-path in diagonal k+∆ Then
{
// The last snake of the reverse path is the middle snake.
x = Vf[forwardOffset + k];
x = vf[forwardOffset + k];
y = x - k;
return (x, y);
}

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

@ -20,10 +20,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip
throw new ArgumentNullException(nameof(languageServer));
}
LanguageServer = languageServer;
_languageServer = languageServer;
}
public ClientNotifierServiceBase LanguageServer;
private readonly ClientNotifierServiceBase _languageServer;
public override bool TryCreateTooltip(AggregateBoundElementDescription elementDescriptionInfo, out MarkupContent tooltipContent)
{
@ -192,8 +192,8 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip
private MarkupKind GetMarkupKind()
{
var completionSupportedKinds = LanguageServer.ClientSettings?.Capabilities?.TextDocument?.Completion.Value?.CompletionItem?.DocumentationFormat;
var hoverSupportedKinds = LanguageServer.ClientSettings?.Capabilities?.TextDocument?.Hover.Value?.ContentFormat;
var completionSupportedKinds = _languageServer.ClientSettings?.Capabilities?.TextDocument?.Completion.Value?.CompletionItem?.DocumentationFormat;
var hoverSupportedKinds = _languageServer.ClientSettings?.Capabilities?.TextDocument?.Hover.Value?.ContentFormat;
// For now we're assuming that if you support Markdown for either completions or hovers you support it for both.
// If this assumption is ever untrue we'll have to start informing this class about if a request is for Hover or Completions.

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

@ -11,23 +11,23 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip
{
internal class DefaultVSLSPTagHelperTooltipFactory : VSLSPTagHelperTooltipFactory
{
private static readonly Guid ImageCatalogGuid = new("{ae27a6b0-e345-4288-96df-5eaf394ee369}");
private static readonly Guid s_imageCatalogGuid = new("{ae27a6b0-e345-4288-96df-5eaf394ee369}");
// Internal for testing
internal static readonly VSImageElement ClassGlyph = new(
new VSImageId(ImageCatalogGuid, 463), // KnownImageIds.Type = 463
new VSImageId(s_imageCatalogGuid, 463), // KnownImageIds.Type = 463
RazorLS.Resources.TagHelper_Element_Glyph);
// Internal for testing
internal static readonly VSImageElement PropertyGlyph = new(
new VSImageId(ImageCatalogGuid, 2429), // KnownImageIds.Type = 2429
new VSImageId(s_imageCatalogGuid, 2429), // KnownImageIds.Type = 2429
RazorLS.Resources.TagHelper_Attribute_Glyph);
private static readonly IReadOnlyList<string> CSharpPrimitiveTypes =
private static readonly IReadOnlyList<string> s_cSharpPrimitiveTypes =
new string[] { "bool", "byte", "sbyte", "char", "decimal", "double", "float", "int", "uint",
"nint", "nuint", "long", "ulong", "short", "ushort", "object", "string", "dynamic" };
private static readonly IReadOnlyDictionary<string, string> TypeNameToAlias = new Dictionary<string, string>(StringComparer.Ordinal)
private static readonly IReadOnlyDictionary<string, string> s_typeNameToAlias = new Dictionary<string, string>(StringComparer.Ordinal)
{
{ "Int32", "int" },
{ "Int64", "long" },
@ -40,10 +40,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip
{ "Char", "char" }
};
private static readonly VSClassifiedTextRun Space = new(VSPredefinedClassificationTypeNames.WhiteSpace, " ");
private static readonly VSClassifiedTextRun Dot = new(VSPredefinedClassificationTypeNames.Punctuation, ".");
private static readonly VSClassifiedTextRun NewLine = new(VSPredefinedClassificationTypeNames.WhiteSpace, Environment.NewLine);
private static readonly VSClassifiedTextRun NullableType = new(VSPredefinedClassificationTypeNames.Punctuation, "?");
private static readonly VSClassifiedTextRun s_space = new(VSPredefinedClassificationTypeNames.WhiteSpace, " ");
private static readonly VSClassifiedTextRun s_dot = new(VSPredefinedClassificationTypeNames.Punctuation, ".");
private static readonly VSClassifiedTextRun s_newLine = new(VSPredefinedClassificationTypeNames.WhiteSpace, Environment.NewLine);
private static readonly VSClassifiedTextRun s_nullableType = new(VSPredefinedClassificationTypeNames.Punctuation, "?");
public override bool TryCreateTooltip(AggregateBoundElementDescription elementDescriptionInfo, out VSContainerElement tooltipContent)
{
@ -184,9 +184,9 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip
var reducedReturnTypeName = ReduceTypeName(returnTypeName);
ClassifyReducedTypeName(typeRuns, reducedReturnTypeName);
typeRuns.Add(Space);
typeRuns.Add(s_space);
ClassifyTypeName(typeRuns, descriptionInfo.TypeName);
typeRuns.Add(Dot);
typeRuns.Add(s_dot);
typeRuns.Add(new VSClassifiedTextRun(VSPredefinedClassificationTypeNames.Identifier, descriptionInfo.PropertyName));
// 2. Classify summary
@ -219,7 +219,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip
{
if (partIndex != 0)
{
runs.Add(Dot);
runs.Add(s_dot);
}
var typeNamePart = typeNameParts[partIndex];
@ -293,12 +293,12 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip
}
// Case 1: Type can be aliased as a C# built-in type (e.g. Boolean -> bool, Int32 -> int, etc.).
if (TypeNameToAlias.TryGetValue(typeName, out var aliasedTypeName))
if (s_typeNameToAlias.TryGetValue(typeName, out var aliasedTypeName))
{
runs.Add(new VSClassifiedTextRun(VSPredefinedClassificationTypeNames.Keyword, aliasedTypeName));
}
// Case 2: Type is a C# built-in type (e.g. bool, int, etc.).
else if (CSharpPrimitiveTypes.Contains(typeName))
else if (s_cSharpPrimitiveTypes.Contains(typeName))
{
runs.Add(new VSClassifiedTextRun(VSPredefinedClassificationTypeNames.Keyword, typeName));
}
@ -310,7 +310,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip
if (nullableType)
{
runs.Add(NullableType);
runs.Add(s_nullableType);
}
}
@ -433,14 +433,14 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip
{
if (runs.Count > 0)
{
runs.Add(NewLine);
runs.Add(NewLine);
runs.Add(s_newLine);
runs.Add(s_newLine);
}
runs.AddRange(classification.Type);
if (classification.Documentation.Count > 0)
{
runs.Add(NewLine);
runs.Add(s_newLine);
runs.AddRange(classification.Documentation);
}
}

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

@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip
{
internal abstract class TagHelperTooltipFactoryBase
{
private static readonly IReadOnlyList<char> NewLineChars = new char[] { '\n', '\r' };
private static readonly IReadOnlyList<char> s_newLineChars = new char[] { '\n', '\r' };
// Internal for testing
internal static string ReduceCrefValue(string value)
@ -52,8 +52,8 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip
// Internal for testing
internal static bool TryExtractSummary(string documentation, out string summary)
{
const string summaryStartTag = "<summary>";
const string summaryEndTag = "</summary>";
const string SummaryStartTag = "<summary>";
const string SummaryEndTag = "</summary>";
if (string.IsNullOrEmpty(documentation))
{
@ -61,10 +61,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip
return false;
}
documentation = documentation.Trim(NewLineChars.ToArray());
documentation = documentation.Trim(s_newLineChars.ToArray());
var summaryTagStart = documentation.IndexOf(summaryStartTag, StringComparison.OrdinalIgnoreCase);
var summaryTagEndStart = documentation.IndexOf(summaryEndTag, StringComparison.OrdinalIgnoreCase);
var summaryTagStart = documentation.IndexOf(SummaryStartTag, StringComparison.OrdinalIgnoreCase);
var summaryTagEndStart = documentation.IndexOf(SummaryEndTag, StringComparison.OrdinalIgnoreCase);
if (summaryTagStart == -1 || summaryTagEndStart == -1)
{
// A really wrong but cheap way to check if this is XML
@ -79,7 +79,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip
return false;
}
var summaryContentStart = summaryTagStart + summaryStartTag.Length;
var summaryContentStart = summaryTagStart + SummaryStartTag.Length;
var summaryContentLength = summaryTagEndStart - summaryContentStart;
summary = documentation.Substring(summaryContentStart, summaryContentLength);

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

@ -20,7 +20,7 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin
private const string TempFileExt = ".temp";
// Internal for testing
internal readonly Dictionary<string, Task> _deferredPublishTasks;
internal readonly Dictionary<string, Task> DeferredPublishTasks;
private readonly ILogger<DefaultProjectChangePublisher> _logger;
private readonly JsonSerializer _serializer;
private readonly Dictionary<string, string> _publishFilePathMappings;
@ -44,7 +44,7 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin
};
_serializer.Converters.RegisterOmniSharpRazorConverters();
_publishFilePathMappings = new Dictionary<string, string>(FilePathComparer.Instance);
_deferredPublishTasks = new Dictionary<string, Task>(FilePathComparer.Instance);
DeferredPublishTasks = new Dictionary<string, Task>(FilePathComparer.Instance);
_pendingProjectPublishes = new Dictionary<string, OmniSharpProjectSnapshot>(FilePathComparer.Instance);
_publishLock = new object();
}
@ -137,9 +137,9 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin
{
_pendingProjectPublishes[projectSnapshot.FilePath] = projectSnapshot;
if (!_deferredPublishTasks.TryGetValue(projectSnapshot.FilePath, out var update) || update.IsCompleted)
if (!DeferredPublishTasks.TryGetValue(projectSnapshot.FilePath, out var update) || update.IsCompleted)
{
_deferredPublishTasks[projectSnapshot.FilePath] = PublishAfterDelayAsync(projectSnapshot.FilePath);
DeferredPublishTasks[projectSnapshot.FilePath] = PublishAfterDelayAsync(projectSnapshot.FilePath);
}
}
}

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

@ -34,7 +34,7 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin
private const string CoreCompileTargetName = "CoreCompile";
private const string RazorGenerateDesignTimeTargetName = "RazorGenerateDesignTime";
private const string RazorGenerateComponentDesignTimeTargetName = "RazorGenerateComponentDesignTime";
private static readonly IEnumerable<ILogger> EmptyMSBuildLoggers = Enumerable.Empty<ILogger>();
private static readonly IEnumerable<ILogger> s_emptyMSBuildLoggers = Enumerable.Empty<ILogger>();
private readonly OmniSharpForegroundDispatcher _foregroundDispatcher;
private readonly object _evaluationLock = new object();
@ -79,14 +79,14 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin
if (refreshTargets.Count > 2)
{
var _projectCollection = new ProjectCollection(projectInstance.GlobalProperties);
var project = _projectCollection.LoadProject(projectInstance.ProjectFileLocation.File, projectInstance.ToolsVersion);
var projectCollection = new ProjectCollection(projectInstance.GlobalProperties);
var project = projectCollection.LoadProject(projectInstance.ProjectFileLocation.File, projectInstance.ToolsVersion);
SetTargetFrameworkIfNeeded(project);
var refreshedProjectInstance = project.CreateProjectInstance();
// Force a Razor information refresh
refreshedProjectInstance.Build(refreshTargets.ToArray(), EmptyMSBuildLoggers);
refreshedProjectInstance.Build(refreshTargets.ToArray(), s_emptyMSBuildLoggers);
return refreshedProjectInstance;
}

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

@ -8,22 +8,22 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin
{
internal static class FilePathComparer
{
private static StringComparer _instance;
private static StringComparer s_instance;
public static StringComparer Instance
{
get
{
if (_instance == null && RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
if (s_instance == null && RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
_instance = StringComparer.Ordinal;
s_instance = StringComparer.Ordinal;
}
else if (_instance == null)
else if (s_instance == null)
{
_instance = StringComparer.OrdinalIgnoreCase;
s_instance = StringComparer.OrdinalIgnoreCase;
}
return _instance;
return s_instance;
}
}
}

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

@ -8,22 +8,22 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin
{
internal static class FilePathComparison
{
private static StringComparison? _instance;
private static StringComparison? s_instance;
public static StringComparison Instance
{
get
{
if (_instance == null && RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
if (s_instance == null && RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
_instance = StringComparison.Ordinal;
s_instance = StringComparison.Ordinal;
}
else if (_instance == null)
else if (s_instance == null)
{
_instance = StringComparison.OrdinalIgnoreCase;
s_instance = StringComparison.OrdinalIgnoreCase;
}
return _instance.Value;
return s_instance.Value;
}
}
}

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

@ -18,7 +18,7 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin
{
private const string MSBuildProjectFullPathPropertyName = "MSBuildProjectFullPath";
private const string MSBuildProjectDirectoryPropertyName = "MSBuildProjectDirectory";
private static readonly IReadOnlyList<string> RazorFileExtensions = new[] { ".razor", ".cshtml" };
private static readonly IReadOnlyList<string> s_razorFileExtensions = new[] { ".razor", ".cshtml" };
private readonly Dictionary<string, IReadOnlyList<FileSystemWatcher>> _watcherMap;
private readonly IReadOnlyList<IRazorDocumentChangeListener> _documentChangeListeners;
@ -74,10 +74,10 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin
}
}
var watchers = new List<FileSystemWatcher>(RazorFileExtensions.Count);
for (var i = 0; i < RazorFileExtensions.Count; i++)
var watchers = new List<FileSystemWatcher>(s_razorFileExtensions.Count);
for (var i = 0; i < s_razorFileExtensions.Count; i++)
{
var documentWatcher = new FileSystemWatcher(projectDirectory, "*" + RazorFileExtensions[i])
var documentWatcher = new FileSystemWatcher(projectDirectory, "*" + s_razorFileExtensions[i])
{
NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.CreationTime,
IncludeSubdirectories = true,
@ -90,13 +90,13 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin
{
// Translate file renames into remove / add
if (RazorFileExtensions.Any(extension => args.OldFullPath.EndsWith(extension, StringComparison.Ordinal)))
if (s_razorFileExtensions.Any(extension => args.OldFullPath.EndsWith(extension, StringComparison.Ordinal)))
{
// Renaming from Razor file to something else.
FileSystemWatcher_RazorDocumentEvent(args.OldFullPath, projectInstance, RazorFileChangeKind.Removed);
}
if (RazorFileExtensions.Any(extension => args.FullPath.EndsWith(extension, StringComparison.Ordinal)))
if (s_razorFileExtensions.Any(extension => args.FullPath.EndsWith(extension, StringComparison.Ordinal)))
{
// Renaming into a Razor file. This typically occurs when users go from .cshtml => .razor
FileSystemWatcher_RazorDocumentEvent(args.FullPath, projectInstance, RazorFileChangeKind.Added);
@ -104,7 +104,7 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin
};
watchers.Add(documentWatcher);
var documentOutputWatcher = new FileSystemWatcher(projectDirectory, "*" + RazorFileExtensions[i] + ".g.cs")
var documentOutputWatcher = new FileSystemWatcher(projectDirectory, "*" + s_razorFileExtensions[i] + ".g.cs")
{
NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite,
IncludeSubdirectories = true,
@ -117,13 +117,13 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin
{
// Translate file renames into remove / add
if (RazorFileExtensions.Any(extension => args.OldFullPath.EndsWith(extension + ".g.cs", StringComparison.Ordinal)))
if (s_razorFileExtensions.Any(extension => args.OldFullPath.EndsWith(extension + ".g.cs", StringComparison.Ordinal)))
{
// Renaming from Razor background file to something else.
FileSystemWatcher_RazorDocumentOutputEvent(args.OldFullPath, projectInstance, RazorFileChangeKind.Removed);
}
if (RazorFileExtensions.Any(extension => args.FullPath.EndsWith(extension + ".g.cs", StringComparison.Ordinal)))
if (s_razorFileExtensions.Any(extension => args.FullPath.EndsWith(extension + ".g.cs", StringComparison.Ordinal)))
{
// Renaming into a Razor generated file.
FileSystemWatcher_RazorDocumentOutputEvent(args.FullPath, projectInstance, RazorFileChangeKind.Added);

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

@ -16,7 +16,7 @@ namespace Microsoft.CodeAnalysis.Razor.Completion
[Export(typeof(RazorCompletionItemProvider))]
internal class DirectiveAttributeCompletionItemProvider : DirectiveAttributeCompletionItemProviderBase
{
private static readonly RazorCompletionItem[] NoDirectiveAttributeCompletionItems = Array.Empty<RazorCompletionItem>();
private static readonly RazorCompletionItem[] s_noDirectiveAttributeCompletionItems = Array.Empty<RazorCompletionItem>();
private readonly TagHelperFactsService _tagHelperFactsService;
@ -46,7 +46,7 @@ namespace Microsoft.CodeAnalysis.Razor.Completion
if (!FileKinds.IsComponent(syntaxTree.Options.FileKind))
{
// Directive attributes are only supported in components
return NoDirectiveAttributeCompletionItems;
return s_noDirectiveAttributeCompletionItems;
}
var change = new SourceChange(location, string.Empty);
@ -54,25 +54,25 @@ namespace Microsoft.CodeAnalysis.Razor.Completion
if (owner == null)
{
return NoDirectiveAttributeCompletionItems;
return s_noDirectiveAttributeCompletionItems;
}
if (!TryGetAttributeInfo(owner, out _, out var attributeName, out var attributeNameLocation, out _, out _))
{
// Either we're not in an attribute or the attribute is so malformed that we can't provide proper completions.
return NoDirectiveAttributeCompletionItems;
return s_noDirectiveAttributeCompletionItems;
}
if (!attributeNameLocation.IntersectsWith(location.AbsoluteIndex))
{
// We're trying to retrieve completions on a portion of the name that is not supported (such as a parameter).
return NoDirectiveAttributeCompletionItems;
return s_noDirectiveAttributeCompletionItems;
}
if (!TryGetElementInfo(owner.Parent.Parent, out var containingTagName, out var attributes))
{
// This should never be the case, it means that we're operating on an attribute that doesn't have a tag.
return NoDirectiveAttributeCompletionItems;
return s_noDirectiveAttributeCompletionItems;
}
// At this point we've determined that completions have been requested for the name portion of the selected attribute.
@ -87,7 +87,7 @@ namespace Microsoft.CodeAnalysis.Razor.Completion
return completionItems;
}
return NoDirectiveAttributeCompletionItems;
return s_noDirectiveAttributeCompletionItems;
}
// Internal for testing

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

@ -18,7 +18,7 @@ namespace Microsoft.CodeAnalysis.Razor.Completion
internal static readonly IReadOnlyCollection<string> SingleLineDirectiveCommitCharacters = new string[] { " " };
internal static readonly IReadOnlyCollection<string> BlockDirectiveCommitCharacters = new string[] { " ", "{" };
private static readonly IEnumerable<DirectiveDescriptor> DefaultDirectives = new[]
private static readonly IEnumerable<DirectiveDescriptor> s_defaultDirectives = new[]
{
CSharpCodeParser.AddTagHelperDirectiveDescriptor,
CSharpCodeParser.RemoveTagHelperDirectiveDescriptor,
@ -109,7 +109,7 @@ namespace Microsoft.CodeAnalysis.Razor.Completion
// Internal for testing
internal static List<RazorCompletionItem> GetDirectiveCompletionItems(RazorSyntaxTree syntaxTree)
{
var defaultDirectives = FileKinds.IsComponent(syntaxTree.Options.FileKind) ? Array.Empty<DirectiveDescriptor>() : DefaultDirectives;
var defaultDirectives = FileKinds.IsComponent(syntaxTree.Options.FileKind) ? Array.Empty<DirectiveDescriptor>() : s_defaultDirectives;
var directives = syntaxTree.Options.Directives.Concat(defaultDirectives);
var completionItems = new List<RazorCompletionItem>();
foreach (var directive in directives)

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

@ -14,28 +14,28 @@ namespace Microsoft.CodeAnalysis.Razor.Completion
{
internal class MarkupTransitionCompletionItemProvider : RazorCompletionItemProvider
{
private static readonly IReadOnlyCollection<string> ElementCommitCharacters = new HashSet<string>{ ">" };
private static readonly IReadOnlyCollection<string> s_elementCommitCharacters = new HashSet<string>{ ">" };
private readonly HtmlFactsService _htmlFactsService;
private static RazorCompletionItem _markupTransitionCompletionItem;
private static RazorCompletionItem s_markupTransitionCompletionItem;
public static RazorCompletionItem MarkupTransitionCompletionItem
{
get
{
if (_markupTransitionCompletionItem == null)
if (s_markupTransitionCompletionItem == null)
{
var completionDisplayText = SyntaxConstants.TextTagName;
_markupTransitionCompletionItem = new RazorCompletionItem(
s_markupTransitionCompletionItem = new RazorCompletionItem(
completionDisplayText,
completionDisplayText,
RazorCompletionItemKind.MarkupTransition,
ElementCommitCharacters);
s_elementCommitCharacters);
var completionDescription = new MarkupTransitionCompletionDescription(Resources.MarkupTransition_Description);
_markupTransitionCompletionItem.SetMarkupTransitionCompletionDescription(completionDescription);
s_markupTransitionCompletionItem.SetMarkupTransitionCompletionDescription(completionDescription);
}
return _markupTransitionCompletionItem;
return s_markupTransitionCompletionItem;
}
}

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

@ -8,9 +8,9 @@ namespace Microsoft.CodeAnalysis.Razor.Completion
{
internal static class RazorCompletionItemExtensions
{
private readonly static string AttributeCompletionDescriptionKey = "Razor.AttributeDescription";
private readonly static string DirectiveCompletionDescriptionKey = "Razor.DirectiveDescription";
private readonly static string MarkupTransitionDescriptionKey = "Razor.MarkupTransitionDescription";
private readonly static string s_attributeCompletionDescriptionKey = "Razor.AttributeDescription";
private readonly static string s_directiveCompletionDescriptionKey = "Razor.DirectiveDescription";
private readonly static string s_markupTransitionDescriptionKey = "Razor.MarkupTransitionDescription";
public static void SetAttributeCompletionDescription(this RazorCompletionItem completionItem, AggregateBoundAttributeDescription attributeCompletionDescription)
{
@ -19,7 +19,7 @@ namespace Microsoft.CodeAnalysis.Razor.Completion
throw new ArgumentNullException(nameof(completionItem));
}
completionItem.Items[AttributeCompletionDescriptionKey] = attributeCompletionDescription;
completionItem.Items[s_attributeCompletionDescriptionKey] = attributeCompletionDescription;
}
public static AggregateBoundAttributeDescription GetAttributeCompletionDescription(this RazorCompletionItem completionItem)
@ -29,7 +29,7 @@ namespace Microsoft.CodeAnalysis.Razor.Completion
throw new ArgumentNullException(nameof(completionItem));
}
var attributeCompletionDescription = completionItem.Items[AttributeCompletionDescriptionKey] as AggregateBoundAttributeDescription;
var attributeCompletionDescription = completionItem.Items[s_attributeCompletionDescriptionKey] as AggregateBoundAttributeDescription;
return attributeCompletionDescription;
}
@ -40,7 +40,7 @@ namespace Microsoft.CodeAnalysis.Razor.Completion
throw new ArgumentNullException(nameof(completionItem));
}
completionItem.Items[DirectiveCompletionDescriptionKey] = attributeCompletionDescription;
completionItem.Items[s_directiveCompletionDescriptionKey] = attributeCompletionDescription;
}
public static DirectiveCompletionDescription GetDirectiveCompletionDescription(this RazorCompletionItem completionItem)
@ -50,7 +50,7 @@ namespace Microsoft.CodeAnalysis.Razor.Completion
throw new ArgumentNullException(nameof(completionItem));
}
var attributeCompletionDescription = completionItem.Items[DirectiveCompletionDescriptionKey] as DirectiveCompletionDescription;
var attributeCompletionDescription = completionItem.Items[s_directiveCompletionDescriptionKey] as DirectiveCompletionDescription;
return attributeCompletionDescription;
}
@ -61,7 +61,7 @@ namespace Microsoft.CodeAnalysis.Razor.Completion
throw new ArgumentNullException(nameof(completionItem));
}
completionItem.Items[MarkupTransitionDescriptionKey] = markupTransitionCompletionDescription;
completionItem.Items[s_markupTransitionDescriptionKey] = markupTransitionCompletionDescription;
}
public static MarkupTransitionCompletionDescription GetMarkupTransitionCompletionDescription(this RazorCompletionItem completionItem)
@ -71,7 +71,7 @@ namespace Microsoft.CodeAnalysis.Razor.Completion
throw new ArgumentNullException(nameof(completionItem));
}
var markupTransitionCompletionDescription = completionItem.Items[MarkupTransitionDescriptionKey] as MarkupTransitionCompletionDescription;
var markupTransitionCompletionDescription = completionItem.Items[s_markupTransitionDescriptionKey] as MarkupTransitionCompletionDescription;
return markupTransitionCompletionDescription;
}
}

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

@ -9,7 +9,7 @@ namespace Microsoft.CodeAnalysis.Razor
{
internal class DefaultProjectSnapshotProjectEngineFactory : ProjectSnapshotProjectEngineFactory
{
private readonly static RazorConfiguration DefaultConfiguration = FallbackRazorConfiguration.Latest;
private readonly static RazorConfiguration s_defaultConfiguration = FallbackRazorConfiguration.Latest;
private readonly IFallbackProjectEngineFactory _fallback;
private readonly Lazy<IProjectEngineFactory, ICustomProjectEngineFactoryMetadata>[] _factories;
@ -50,7 +50,7 @@ namespace Microsoft.CodeAnalysis.Razor
//
// We typically want this because the language adds features over time - we don't want to a bunch of errors
// to show up when a document is first opened, and then go away when the configuration loads, we'd prefer the opposite.
configuration ??= DefaultConfiguration;
configuration ??= s_defaultConfiguration;
// If there's no factory to handle the configuration then fall back to a very basic configuration.
//
@ -67,7 +67,7 @@ namespace Microsoft.CodeAnalysis.Razor
throw new ArgumentNullException(nameof(project));
}
return SelectFactory(project.Configuration ?? DefaultConfiguration, requireSerializable: false);
return SelectFactory(project.Configuration ?? s_defaultConfiguration, requireSerializable: false);
}
public override IProjectEngineFactory FindSerializableFactory(ProjectSnapshot project)
@ -77,7 +77,7 @@ namespace Microsoft.CodeAnalysis.Razor
throw new ArgumentNullException(nameof(project));
}
return SelectFactory(project.Configuration ?? DefaultConfiguration, requireSerializable: true);
return SelectFactory(project.Configuration ?? s_defaultConfiguration, requireSerializable: true);
}
private IProjectEngineFactory SelectFactory(RazorConfiguration configuration, bool requireSerializable = false)

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

@ -18,7 +18,7 @@ namespace Microsoft.CodeAnalysis.Razor
internal class DefaultProjectWorkspaceStateGenerator : ProjectWorkspaceStateGenerator, IDisposable
{
// Internal for testing
internal readonly Dictionary<string, UpdateItem> _updates;
internal readonly Dictionary<string, UpdateItem> Updates;
private readonly ForegroundDispatcher _foregroundDispatcher;
private readonly SemaphoreSlim _semaphore;
@ -37,7 +37,7 @@ namespace Microsoft.CodeAnalysis.Razor
_foregroundDispatcher = foregroundDispatcher;
_semaphore = new SemaphoreSlim(initialCount: 1);
_updates = new Dictionary<string, UpdateItem>(FilePathComparer.Instance);
Updates = new Dictionary<string, UpdateItem>(FilePathComparer.Instance);
}
// Used in unit tests to ensure we can control when background work starts.
@ -72,7 +72,7 @@ namespace Microsoft.CodeAnalysis.Razor
return;
}
if (_updates.TryGetValue(projectSnapshot.FilePath, out var updateItem) &&
if (Updates.TryGetValue(projectSnapshot.FilePath, out var updateItem) &&
!updateItem.Task.IsCompleted &&
!updateItem.Cts.IsCancellationRequested)
{
@ -92,7 +92,7 @@ namespace Microsoft.CodeAnalysis.Razor
_foregroundDispatcher.BackgroundScheduler).Unwrap();
updateTask.ConfigureAwait(false);
updateItem = new UpdateItem(updateTask, lcts);
_updates[projectSnapshot.FilePath] = updateItem;
Updates[projectSnapshot.FilePath] = updateItem;
}
public void Dispose()
@ -101,7 +101,7 @@ namespace Microsoft.CodeAnalysis.Razor
_disposed = true;
foreach (var update in _updates)
foreach (var update in Updates)
{
if (!update.Value.Task.IsCompleted &&
!update.Value.Cts.IsCancellationRequested)

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

@ -16,7 +16,7 @@ namespace Microsoft.VisualStudio.Editor.Razor
internal class DefaultTagHelperCompletionService : TagHelperCompletionService
{
private readonly TagHelperFactsService _tagHelperFactsService;
private static readonly HashSet<TagHelperDescriptor> _emptyHashSet = new HashSet<TagHelperDescriptor>();
private static readonly HashSet<TagHelperDescriptor> s_emptyHashSet = new HashSet<TagHelperDescriptor>();
[ImportingConstructor]
public DefaultTagHelperCompletionService(TagHelperFactsService tagHelperFactsService)
@ -302,7 +302,7 @@ namespace Microsoft.VisualStudio.Editor.Razor
{
if (!elementCompletions.ContainsKey(prefixedName))
{
elementCompletions[prefixedName] = _emptyHashSet;
elementCompletions[prefixedName] = s_emptyHashSet;
}
continue;

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

@ -11,7 +11,7 @@ namespace Microsoft.VisualStudio.Editor.Razor
{
internal abstract class HtmlFactsService
{
private static readonly HashSet<string> _htmlSchemaTagNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
private static readonly HashSet<string> s_htmlSchemaTagNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"DOCTYPE",
"a",
@ -150,7 +150,7 @@ namespace Microsoft.VisualStudio.Editor.Razor
public static bool IsHtmlTagName(string name)
{
return _htmlSchemaTagNames.Contains(name);
return s_htmlSchemaTagNames.Contains(name);
}
}
}

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

@ -541,7 +541,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem
private class Entry
{
public ProjectSnapshot SnapshotUnsafe;
private ProjectSnapshot _snapshotUnsafe;
public readonly ProjectState State;
public Entry(ProjectState state)
@ -551,7 +551,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem
public ProjectSnapshot GetSnapshot()
{
return SnapshotUnsafe ??= new DefaultProjectSnapshot(State);
return _snapshotUnsafe ??= new DefaultProjectSnapshot(State);
}
}
}

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

@ -14,11 +14,11 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem
{
internal class DocumentState
{
private static readonly TextAndVersion EmptyText = TextAndVersion.Create(
private static readonly TextAndVersion s_emptyText = TextAndVersion.Create(
SourceText.From(string.Empty),
VersionStamp.Default);
public static readonly Func<Task<TextAndVersion>> EmptyLoader = () => Task.FromResult(EmptyText);
public static readonly Func<Task<TextAndVersion>> EmptyLoader = () => Task.FromResult(s_emptyText);
private readonly object _lock;
@ -287,7 +287,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem
// We utilize a WeakReference here to avoid bloating committed memory. If pieces request document output inbetween GC collections
// then we will provide the weak referenced task; otherwise we require any state requests to be re-computed.
public WeakReference<Task<(RazorCodeDocument, VersionStamp, VersionStamp, VersionStamp)>> TaskUnsafeReference;
private WeakReference<Task<(RazorCodeDocument, VersionStamp, VersionStamp, VersionStamp)>> _taskUnsafeReference;
public ComputedStateTracker(DocumentState state, ComputedStateTracker older = null)
{
@ -299,12 +299,12 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem
{
get
{
if (TaskUnsafeReference == null)
if (_taskUnsafeReference == null)
{
return false;
}
if (TaskUnsafeReference.TryGetTarget(out var taskUnsafe))
if (_taskUnsafeReference.TryGetTarget(out var taskUnsafe))
{
return taskUnsafe.IsCompleted;
}
@ -325,15 +325,15 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem
throw new ArgumentNullException(nameof(document));
}
if (TaskUnsafeReference == null ||
!TaskUnsafeReference.TryGetTarget(out var taskUnsafe))
if (_taskUnsafeReference == null ||
!_taskUnsafeReference.TryGetTarget(out var taskUnsafe))
{
TaskCompletionSource<(RazorCodeDocument, VersionStamp, VersionStamp, VersionStamp)> tcs = null;
lock (_lock)
{
if (TaskUnsafeReference == null ||
!TaskUnsafeReference.TryGetTarget(out taskUnsafe))
if (_taskUnsafeReference == null ||
!_taskUnsafeReference.TryGetTarget(out taskUnsafe))
{
// So this is a bit confusing. Instead of directly calling the Razor parser inside of this lock we create an indirect TaskCompletionSource
// to represent when it completes. The reason behind this is that there are several scenarios in which the Razor parser will run synchronously
@ -342,7 +342,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem
tcs = new(TaskCreationOptions.RunContinuationsAsynchronously);
taskUnsafe = tcs.Task;
TaskUnsafeReference = new WeakReference<Task<(RazorCodeDocument, VersionStamp, VersionStamp, VersionStamp)>>(taskUnsafe);
_taskUnsafeReference = new WeakReference<Task<(RazorCodeDocument, VersionStamp, VersionStamp, VersionStamp)>>(taskUnsafe);
}
}
@ -449,8 +449,8 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem
RazorCodeDocument olderOutput = null;
var olderCSharpOutputVersion = default(VersionStamp);
var olderHtmlOutputVersion = default(VersionStamp);
if (_older?.TaskUnsafeReference != null &&
_older.TaskUnsafeReference.TryGetTarget(out var taskUnsafe))
if (_older?._taskUnsafeReference != null &&
_older._taskUnsafeReference.TryGetTarget(out var taskUnsafe))
{
VersionStamp olderInputVersion;
(olderOutput, olderInputVersion, olderCSharpOutputVersion, olderHtmlOutputVersion) = await taskUnsafe.ConfigureAwait(false);
@ -459,7 +459,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem
// Nothing has changed, we can use the cached result.
lock (_lock)
{
TaskUnsafeReference = _older.TaskUnsafeReference;
_taskUnsafeReference = _older._taskUnsafeReference;
_older = null;
return (olderOutput, olderInputVersion, olderCSharpOutputVersion, olderHtmlOutputVersion);
}

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

@ -28,9 +28,9 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem
ProjectDifference.DocumentAdded |
ProjectDifference.DocumentRemoved;
private static readonly ImmutableDictionary<string, DocumentState> EmptyDocuments = ImmutableDictionary.Create<string, DocumentState>(FilePathComparer.Instance);
private static readonly ImmutableDictionary<string, ImmutableArray<string>> EmptyImportsToRelatedDocuments = ImmutableDictionary.Create<string, ImmutableArray<string>>(FilePathComparer.Instance);
private static readonly IReadOnlyList<TagHelperDescriptor> EmptyTagHelpers = Array.Empty<TagHelperDescriptor>();
private static readonly ImmutableDictionary<string, DocumentState> s_emptyDocuments = ImmutableDictionary.Create<string, DocumentState>(FilePathComparer.Instance);
private static readonly ImmutableDictionary<string, ImmutableArray<string>> s_emptyImportsToRelatedDocuments = ImmutableDictionary.Create<string, ImmutableArray<string>>(FilePathComparer.Instance);
private static readonly IReadOnlyList<TagHelperDescriptor> s_emptyTagHelpers = Array.Empty<TagHelperDescriptor>();
private readonly object _lock;
private RazorProjectEngine _projectEngine;
@ -61,8 +61,8 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem
Services = services;
HostProject = hostProject;
ProjectWorkspaceState = projectWorkspaceState;
Documents = EmptyDocuments;
ImportsToRelatedDocuments = EmptyImportsToRelatedDocuments;
Documents = s_emptyDocuments;
ImportsToRelatedDocuments = s_emptyImportsToRelatedDocuments;
Version = VersionStamp.Create();
DocumentCollectionVersion = Version;
@ -160,7 +160,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem
public HostWorkspaceServices Services { get; }
public IReadOnlyList<TagHelperDescriptor> TagHelpers => ProjectWorkspaceState?.TagHelpers ?? EmptyTagHelpers;
public IReadOnlyList<TagHelperDescriptor> TagHelpers => ProjectWorkspaceState?.TagHelpers ?? s_emptyTagHelpers;
public LanguageVersion CSharpLanguageVersion => ProjectWorkspaceState?.CSharpLanguageVersion ?? LanguageVersion.Default;
@ -342,7 +342,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem
var documents = Documents.ToImmutableDictionary(kvp => kvp.Key, kvp => kvp.Value.WithConfigurationChange(), FilePathComparer.Instance);
// If the host project has changed then we need to recompute the imports map
var importsToRelatedDocuments = EmptyImportsToRelatedDocuments;
var importsToRelatedDocuments = s_emptyImportsToRelatedDocuments;
foreach (var document in documents)
{

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

@ -9,9 +9,9 @@ namespace Microsoft.CodeAnalysis.Razor.Workspaces
{
internal static class RazorCodeDocumentExtensions
{
private static readonly object SourceTextKey = new object();
private static readonly object CSharpSourceTextKey = new object();
private static readonly object HtmlSourceTextKey = new object();
private static readonly object s_sourceTextKey = new object();
private static readonly object s_cSharpSourceTextKey = new object();
private static readonly object s_htmlSourceTextKey = new object();
public static SourceText GetSourceText(this RazorCodeDocument document)
{
@ -20,14 +20,14 @@ namespace Microsoft.CodeAnalysis.Razor.Workspaces
throw new ArgumentNullException(nameof(document));
}
var sourceTextObj = document.Items[SourceTextKey];
var sourceTextObj = document.Items[s_sourceTextKey];
if (sourceTextObj == null)
{
var source = document.Source;
var charBuffer = new char[source.Length];
source.CopyTo(0, charBuffer, 0, source.Length);
var sourceText = SourceText.From(new string(charBuffer));
document.Items[SourceTextKey] = sourceText;
document.Items[s_sourceTextKey] = sourceText;
return sourceText;
}
@ -42,12 +42,12 @@ namespace Microsoft.CodeAnalysis.Razor.Workspaces
throw new ArgumentNullException(nameof(document));
}
var sourceTextObj = document.Items[CSharpSourceTextKey];
var sourceTextObj = document.Items[s_cSharpSourceTextKey];
if (sourceTextObj == null)
{
var csharpDocument = document.GetCSharpDocument();
var sourceText = SourceText.From(csharpDocument.GeneratedCode);
document.Items[CSharpSourceTextKey] = sourceText;
document.Items[s_cSharpSourceTextKey] = sourceText;
return sourceText;
}
@ -62,12 +62,12 @@ namespace Microsoft.CodeAnalysis.Razor.Workspaces
throw new ArgumentNullException(nameof(document));
}
var sourceTextObj = document.Items[HtmlSourceTextKey];
var sourceTextObj = document.Items[s_htmlSourceTextKey];
if (sourceTextObj == null)
{
var htmlDocument = document.GetHtmlDocument();
var sourceText = SourceText.From(htmlDocument.GeneratedHtml);
document.Items[HtmlSourceTextKey] = sourceText;
document.Items[s_htmlSourceTextKey] = sourceText;
return sourceText;
}

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

@ -13,7 +13,7 @@ namespace Microsoft.CodeAnalysis.Razor.Serialization
{
public static readonly TagHelperDescriptorJsonConverter Instance = new TagHelperDescriptorJsonConverter();
private static readonly StringCache _stringCache = new StringCache();
private static readonly StringCache s_stringCache = new StringCache();
public static bool DisableCachingForTesting { private get; set; } = false;
@ -968,7 +968,7 @@ namespace Microsoft.CodeAnalysis.Razor.Serialization
}
// We cache all our stings here to prevent them from balooning memory in our Descriptors.
return _stringCache.GetOrAddValue(str);
return s_stringCache.GetOrAddValue(str);
}
}
}

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

@ -7,13 +7,13 @@ namespace Microsoft.CodeAnalysis.Razor
{
internal static class TagHelperDescriptorCache
{
private static readonly MemoryCache<int, TagHelperDescriptor> CachedTagHelperDescriptors =
private static readonly MemoryCache<int, TagHelperDescriptor> s_cachedTagHelperDescriptors =
new MemoryCache<int, TagHelperDescriptor>(4500);
internal static bool TryGetDescriptor(int hashCode, out TagHelperDescriptor descriptor) =>
CachedTagHelperDescriptors.TryGetValue(hashCode, out descriptor);
s_cachedTagHelperDescriptors.TryGetValue(hashCode, out descriptor);
internal static void Set(int hashCode, TagHelperDescriptor descriptor) =>
CachedTagHelperDescriptors.Set(hashCode, descriptor);
s_cachedTagHelperDescriptors.Set(hashCode, descriptor);
}
}

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

@ -8,7 +8,7 @@ namespace Microsoft.CodeAnalysis.Razor.Tooltip
{
internal static class TypeNameStringResolver
{
private static readonly IReadOnlyDictionary<string, string> PrimitiveDisplayTypeNameLookups = new Dictionary<string, string>(StringComparer.Ordinal)
private static readonly IReadOnlyDictionary<string, string> s_primitiveDisplayTypeNameLookups = new Dictionary<string, string>(StringComparer.Ordinal)
{
[typeof(byte).FullName] = "byte",
[typeof(sbyte).FullName] = "sbyte",
@ -34,7 +34,7 @@ namespace Microsoft.CodeAnalysis.Razor.Tooltip
throw new ArgumentNullException(nameof(typeName));
}
if (PrimitiveDisplayTypeNameLookups.TryGetValue(typeName, out var simpleName))
if (s_primitiveDisplayTypeNameLookups.TryGetValue(typeName, out var simpleName))
{
resolvedName = simpleName;
return true;

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

@ -15,10 +15,10 @@ namespace Microsoft.CodeAnalysis.Remote.Razor
{
private const string ComponentName = "Razor";
private static readonly ImmutableArray<JsonConverter> JsonConverters = new JsonConverterCollection()
private static readonly ImmutableArray<JsonConverter> s_jsonConverters = new JsonConverterCollection()
.RegisterRazorConverters()
.ToImmutableArray();
public static readonly RazorServiceDescriptorsWrapper TagHelperProviderServiceDescriptors = new RazorServiceDescriptorsWrapper(ComponentName, _ => "Razor TagHelper Provider", JsonConverters, new (Type, Type?)[] { (typeof(IRemoteTagHelperProviderService), null) });
public static readonly RazorServiceDescriptorsWrapper TagHelperProviderServiceDescriptors = new RazorServiceDescriptorsWrapper(ComponentName, _ => "Razor TagHelper Provider", s_jsonConverters, new (Type, Type?)[] { (typeof(IRemoteTagHelperProviderService), null) });
}
}

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

@ -13,7 +13,7 @@ namespace Microsoft.CodeAnalysis.Razor
{
internal class RemoteTagHelperResolver : TagHelperResolver
{
private readonly static RazorConfiguration DefaultConfiguration = FallbackRazorConfiguration.MVC_2_0;
private readonly static RazorConfiguration s_defaultConfiguration = FallbackRazorConfiguration.MVC_2_0;
private readonly IFallbackProjectEngineFactory _fallbackFactory;
@ -63,7 +63,7 @@ namespace Microsoft.CodeAnalysis.Razor
// The default configuration currently matches MVC-2.0. Beyond MVC-2.0 we added SDK support for
// properly detecting project versions, so that's a good version to assume when we can't find a
// configuration.
configuration ??= DefaultConfiguration;
configuration ??= s_defaultConfiguration;
// If there's no factory to handle the configuration then fall back to a very basic configuration.
//

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

@ -19,7 +19,7 @@ namespace Microsoft.CodeAnalysis.Razor
internal class BackgroundDocumentGenerator : ProjectSnapshotChangeTrigger
{
// Internal for testing
internal readonly Dictionary<DocumentKey, (ProjectSnapshot project, DocumentSnapshot document)> _work;
internal readonly Dictionary<DocumentKey, (ProjectSnapshot project, DocumentSnapshot document)> Work;
private readonly ForegroundDispatcher _foregroundDispatcher;
private readonly RazorDynamicFileInfoProvider _infoProvider;
@ -44,16 +44,16 @@ namespace Microsoft.CodeAnalysis.Razor
_infoProvider = infoProvider;
_suppressedDocuments = new HashSet<string>(FilePathComparer.Instance);
_work = new Dictionary<DocumentKey, (ProjectSnapshot project, DocumentSnapshot document)>();
Work = new Dictionary<DocumentKey, (ProjectSnapshot project, DocumentSnapshot document)>();
}
public bool HasPendingNotifications
{
get
{
lock (_work)
lock (Work)
{
return _work.Count > 0;
return Work.Count > 0;
}
}
}
@ -160,7 +160,7 @@ namespace Microsoft.CodeAnalysis.Razor
_foregroundDispatcher.AssertForegroundThread();
lock (_work)
lock (Work)
{
if (Suppressed(project, document))
{
@ -169,7 +169,7 @@ namespace Microsoft.CodeAnalysis.Razor
// We only want to store the last 'seen' version of any given document. That way when we pick one to process
// it's always the best version to use.
_work[new DocumentKey(project.FilePath, document.FilePath)] = (project, document);
Work[new DocumentKey(project.FilePath, document.FilePath)] = (project, document);
StartWorker();
}
@ -202,10 +202,10 @@ namespace Microsoft.CodeAnalysis.Razor
OnStartingBackgroundWork();
KeyValuePair<DocumentKey, (ProjectSnapshot project, DocumentSnapshot document)>[] work;
lock (_work)
lock (Work)
{
work = _work.ToArray();
_work.Clear();
work = Work.ToArray();
Work.Clear();
}
OnBackgroundCapturedWorkload();
@ -234,14 +234,14 @@ namespace Microsoft.CodeAnalysis.Razor
OnCompletingBackgroundWork();
lock (_work)
lock (Work)
{
// Resetting the timer allows another batch of work to start.
_timer.Dispose();
_timer = null;
// If more work came in while we were running start the worker again.
if (_work.Count > 0)
if (Work.Count > 0)
{
StartWorker();
}

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

@ -20,7 +20,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Completion
new ClassifiedTextElement(
new ClassifiedTextRun(PredefinedClassificationNames.Comment, "------------")));
private static readonly IReadOnlyDictionary<string, string> KeywordTypeNameLookups = new Dictionary<string, string>(StringComparer.Ordinal)
private static readonly IReadOnlyDictionary<string, string> s_keywordTypeNameLookups = new Dictionary<string, string>(StringComparer.Ordinal)
{
[typeof(byte).FullName] = "byte",
[typeof(sbyte).FullName] = "sbyte",
@ -41,12 +41,12 @@ namespace Microsoft.VisualStudio.Editor.Razor.Completion
// Hardcoding the Guid here to avoid a reference to Microsoft.VisualStudio.ImageCatalog.dll
// that is not present in Visual Studio for Mac
private static readonly Guid ImageCatalogGuid = new Guid("{ae27a6b0-e345-4288-96df-5eaf394ee369}");
private static readonly ImageElement PropertyGlyph = new ImageElement(
new ImageId(ImageCatalogGuid, 2429), // KnownImageIds.Type = 2429
private static readonly Guid s_imageCatalogGuid = new Guid("{ae27a6b0-e345-4288-96df-5eaf394ee369}");
private static readonly ImageElement s_propertyGlyph = new ImageElement(
new ImageId(s_imageCatalogGuid, 2429), // KnownImageIds.Type = 2429
"Razor Attribute Glyph");
private static readonly ClassifiedTextRun SpaceLiteral = new ClassifiedTextRun(PredefinedClassificationNames.Literal, " ");
private static readonly ClassifiedTextRun DotLiteral = new ClassifiedTextRun(PredefinedClassificationNames.Literal, ".");
private static readonly ClassifiedTextRun s_spaceLiteral = new ClassifiedTextRun(PredefinedClassificationNames.Literal, " ");
private static readonly ClassifiedTextRun s_dotLiteral = new ClassifiedTextRun(PredefinedClassificationNames.Literal, ".");
public override ContainerElement CreateClassifiedDescription(AggregateBoundAttributeDescription completionDescription)
{
@ -94,13 +94,13 @@ namespace Microsoft.VisualStudio.Editor.Razor.Completion
descriptionElements.Add(
new ContainerElement(
ContainerElementStyle.Wrapped,
PropertyGlyph,
s_propertyGlyph,
new ClassifiedTextElement(
new ClassifiedTextRun(returnTypeClassification, returnTypeName),
SpaceLiteral,
s_spaceLiteral,
new ClassifiedTextRun(PredefinedClassificationNames.Literal, tagHelperTypeNamePrefix),
new ClassifiedTextRun(PredefinedClassificationNames.Type, tagHelperTypeNameProper),
DotLiteral,
s_dotLiteral,
new ClassifiedTextRun(PredefinedClassificationNames.Identifier, descriptionInfo.PropertyName))));
if (descriptionInfo.Documentation != null)

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

@ -27,12 +27,12 @@ namespace Microsoft.VisualStudio.Editor.Razor.Completion
// Hardcoding the Guid here to avoid a reference to Microsoft.VisualStudio.ImageCatalog.dll
// that is not present in Visual Studio for Mac
private static readonly Guid ImageCatalogGuid = new Guid("{ae27a6b0-e345-4288-96df-5eaf394ee369}");
private static readonly ImageElement DirectiveAttributeImageGlyph = new ImageElement(
new ImageId(ImageCatalogGuid, 3564), // KnownImageIds.Type = 3564
private static readonly Guid s_imageCatalogGuid = new Guid("{ae27a6b0-e345-4288-96df-5eaf394ee369}");
private static readonly ImageElement s_directiveAttributeImageGlyph = new ImageElement(
new ImageId(s_imageCatalogGuid, 3564), // KnownImageIds.Type = 3564
"Razor Directive Attribute.");
private static readonly ImmutableArray<CompletionFilter> DirectiveAttributeCompletionFilters = new[] {
new CompletionFilter("Razor Directive Attrsibute", "r", DirectiveAttributeImageGlyph)
private static readonly ImmutableArray<CompletionFilter> s_directiveAttributeCompletionFilters = new[] {
new CompletionFilter("Razor Directive Attrsibute", "r", s_directiveAttributeImageGlyph)
}.ToImmutableArray();
private readonly VisualStudioRazorParser _parser;
@ -133,8 +133,8 @@ namespace Microsoft.VisualStudio.Editor.Razor.Completion
filterText: razorCompletionItem.DisplayText,
insertText: razorCompletionItem.InsertText,
source: this,
icon: DirectiveAttributeImageGlyph,
filters: DirectiveAttributeCompletionFilters,
icon: s_directiveAttributeImageGlyph,
filters: s_directiveAttributeCompletionFilters,
suffix: string.Empty,
sortText: razorCompletionItem.DisplayText,
attributeIcons: ImmutableArray<ImageElement>.Empty);

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

@ -32,7 +32,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Completion
}.ToImmutableArray();
// Internal for testing
internal readonly VisualStudioRazorParser _parser;
internal readonly VisualStudioRazorParser Parser;
private readonly RazorCompletionFactsService _completionFactsService;
private readonly ForegroundDispatcher _foregroundDispatcher;
@ -57,7 +57,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Completion
}
_foregroundDispatcher = foregroundDispatcher;
_parser = parser;
Parser = parser;
_completionFactsService = completionFactsService;
}
@ -72,7 +72,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Completion
try
{
var codeDocument = await _parser.GetLatestCodeDocumentAsync(triggerLocation.Snapshot, token);
var codeDocument = await Parser.GetLatestCodeDocumentAsync(triggerLocation.Snapshot, token);
if (codeDocument == null)
{
return CompletionContext.Empty;

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

@ -14,7 +14,7 @@ namespace Microsoft.VisualStudio.Editor.Razor
{
public override event EventHandler<EditorSettingsChangedEventArgs> Changed;
private readonly object SettingsAccessorLock = new object();
private readonly object _settingsAccessorLock = new object();
private readonly ForegroundDispatcher _foregroundDispatcher;
private EditorSettings _settings;
@ -29,7 +29,7 @@ namespace Microsoft.VisualStudio.Editor.Razor
{
get
{
lock (SettingsAccessorLock)
lock (_settingsAccessorLock)
{
return _settings;
}
@ -45,7 +45,7 @@ namespace Microsoft.VisualStudio.Editor.Razor
_foregroundDispatcher.AssertForegroundThread();
lock (SettingsAccessorLock)
lock (_settingsAccessorLock)
{
if (!_settings.Equals(updatedSettings))
{

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

@ -13,7 +13,7 @@ namespace Microsoft.VisualStudio.Editor.Razor
[Export(typeof(RazorEditorFactoryService))]
internal class DefaultRazorEditorFactoryService : RazorEditorFactoryService
{
private static readonly object RazorTextBufferInitializationKey = new object();
private static readonly object s_razorTextBufferInitializationKey = new object();
private readonly VisualStudioWorkspaceAccessor _workspaceAccessor;
[ImportingConstructor]
@ -117,7 +117,7 @@ namespace Microsoft.VisualStudio.Editor.Razor
// Internal for testing
internal bool TryInitializeTextBuffer(ITextBuffer textBuffer)
{
if (textBuffer.Properties.ContainsProperty(RazorTextBufferInitializationKey))
if (textBuffer.Properties.ContainsProperty(s_razorTextBufferInitializationKey))
{
// Buffer already initialized.
return true;
@ -143,7 +143,7 @@ namespace Microsoft.VisualStudio.Editor.Razor
var braceSmartIndenter = braceSmartIndenterFactory.Create(tracker);
textBuffer.Properties[typeof(BraceSmartIndenter)] = braceSmartIndenter;
textBuffer.Properties.AddProperty(RazorTextBufferInitializationKey, RazorTextBufferInitializationKey);
textBuffer.Properties.AddProperty(s_razorTextBufferInitializationKey, s_razorTextBufferInitializationKey);
return true;
}

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

@ -24,14 +24,14 @@ namespace Microsoft.VisualStudio.Editor.Razor
public override event EventHandler<DocumentStructureChangedEventArgs> DocumentStructureChanged;
// Internal for testing.
internal TimeSpan IdleDelay = TimeSpan.FromSeconds(3);
internal TimeSpan _idleDelay = TimeSpan.FromSeconds(3);
internal Timer _idleTimer;
internal BackgroundParser _parser;
internal ChangeReference _latestChangeReference;
internal RazorSyntaxTreePartialParser _partialParser;
private readonly object IdleLock = new object();
private readonly object UpdateStateLock = new object();
private readonly object _idleLock = new object();
private readonly object _updateStateLock = new object();
private readonly VisualStudioCompletionBroker _completionBroker;
private readonly VisualStudioDocumentTracker _documentTracker;
private readonly ForegroundDispatcher _dispatcher;
@ -115,7 +115,7 @@ namespace Microsoft.VisualStudio.Editor.Razor
throw new ArgumentNullException(nameof(atOrNewerSnapshot));
}
lock (UpdateStateLock)
lock (_updateStateLock)
{
if (_disposed ||
(_latestParsedSnapshot != null && atOrNewerSnapshot.Version.VersionNumber <= _latestParsedSnapshot.Version.VersionNumber))
@ -167,7 +167,7 @@ namespace Microsoft.VisualStudio.Editor.Razor
StopIdleTimer();
lock (UpdateStateLock)
lock (_updateStateLock)
{
_disposed = true;
foreach (var request in _codeDocumentRequests)
@ -260,12 +260,12 @@ namespace Microsoft.VisualStudio.Editor.Razor
{
_dispatcher.AssertForegroundThread();
lock (IdleLock)
lock (_idleLock)
{
if (_idleTimer == null)
{
// Timer will fire after a fixed delay, but only once.
_idleTimer = NonCapturingTimer.Create(state => ((DefaultVisualStudioRazorParser)state).Timer_Tick(), this, IdleDelay, Timeout.InfiniteTimeSpan);
_idleTimer = NonCapturingTimer.Create(state => ((DefaultVisualStudioRazorParser)state).Timer_Tick(), this, _idleDelay, Timeout.InfiniteTimeSpan);
}
}
}
@ -275,7 +275,7 @@ namespace Microsoft.VisualStudio.Editor.Razor
{
// Can be called from any thread.
lock (IdleLock)
lock (_idleLock)
{
if (_idleTimer != null)
{
@ -485,7 +485,7 @@ namespace Microsoft.VisualStudio.Editor.Razor
private void UpdateParserState(RazorCodeDocument codeDocument, ITextSnapshot snapshot)
{
lock (UpdateStateLock)
lock (_updateStateLock)
{
if (_snapshot != null && snapshot.Version.VersionNumber < _snapshot.Version.VersionNumber)
{
@ -508,7 +508,7 @@ namespace Microsoft.VisualStudio.Editor.Razor
throw new ArgumentNullException(nameof(snapshot));
}
lock (UpdateStateLock)
lock (_updateStateLock)
{
if (_latestParsedSnapshot == null ||
_latestParsedSnapshot.Version.VersionNumber < snapshot.Version.VersionNumber)
@ -522,7 +522,7 @@ namespace Microsoft.VisualStudio.Editor.Razor
private void CompleteCodeDocumentRequestsForSnapshot(RazorCodeDocument codeDocument, ITextSnapshot snapshot)
{
lock (UpdateStateLock)
lock (_updateStateLock)
{
if (_codeDocumentRequests.Count == 0)
{
@ -588,7 +588,7 @@ namespace Microsoft.VisualStudio.Editor.Razor
// Internal for testing
internal class CodeDocumentRequest
{
private readonly object CompletionLock = new object();
private readonly object _completionLock = new object();
private readonly TaskCompletionSource<RazorCodeDocument> _taskCompletionSource;
private readonly CancellationTokenRegistration _cancellationTokenRegistration;
private bool _done;
@ -623,7 +623,7 @@ namespace Microsoft.VisualStudio.Editor.Razor
throw new ArgumentNullException(nameof(codeDocument));
}
lock (CompletionLock)
lock (_completionLock)
{
if (_done)
{
@ -640,7 +640,7 @@ namespace Microsoft.VisualStudio.Editor.Razor
public void Cancel()
{
lock (CompletionLock)
lock (_completionLock)
{
if (_done)
{

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

@ -17,7 +17,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Documents
private readonly FileChangeTrackerFactory _fileChangeTrackerFactory;
private readonly Dictionary<DocumentKey, EditorDocument> _documents;
private readonly Dictionary<string, List<DocumentKey>> _documentsByFilePath;
protected readonly object _lock;
protected readonly object Lock;
public EditorDocumentManagerBase(
ForegroundDispatcher foregroundDispatcher,
@ -38,7 +38,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Documents
_documents = new Dictionary<DocumentKey, EditorDocument>();
_documentsByFilePath = new Dictionary<string, List<DocumentKey>>(FilePathComparer.Instance);
_lock = new object();
Lock = new object();
}
protected ForegroundDispatcher ForegroundDispatcher { get; }
@ -53,7 +53,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Documents
{
ForegroundDispatcher.AssertForegroundThread();
lock (_lock)
lock (Lock)
{
return _documents.TryGetValue(key, out document);
}
@ -63,7 +63,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Documents
{
ForegroundDispatcher.AssertForegroundThread();
lock (_lock)
lock (Lock)
{
if (!_documentsByFilePath.TryGetValue(filePath, out var keys))
{
@ -92,7 +92,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Documents
EditorDocument document;
lock (_lock)
lock (Lock)
{
if (TryGetDocument(key, out document))
{
@ -149,7 +149,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Documents
ForegroundDispatcher.AssertForegroundThread();
lock (_lock)
lock (Lock)
{
if (TryGetMatchingDocuments(filePath, out var documents))
{
@ -173,7 +173,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Documents
ForegroundDispatcher.AssertForegroundThread();
lock (_lock)
lock (Lock)
{
if (TryGetMatchingDocuments(filePath, out var documents))
{

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

@ -13,7 +13,7 @@ namespace Microsoft.VisualStudio.LanguageServer.ContainedLanguage
internal class DefaultFileUriProvider : FileUriProvider
{
private readonly ITextDocumentFactoryService _textDocumentFactory;
private readonly string TextBufferUri = "__MsLspTextBufferUri";
private const string TextBufferUri = "__MsLspTextBufferUri";
[ImportingConstructor]
public DefaultFileUriProvider(ITextDocumentFactoryService textDocumentFactory)

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

@ -19,7 +19,7 @@ namespace Microsoft.VisualStudio.LanguageServer.ContainedLanguage
// Internal for testing
internal TimeSpan _synchronizationTimeout = TimeSpan.FromSeconds(2);
private readonly Dictionary<Uri, DocumentContext> _virtualDocumentContexts;
private readonly object DocumentContextLock = new object();
private readonly object _documentContextLock = new object();
private readonly FileUriProvider _fileUriProvider;
[ImportingConstructor]
@ -51,7 +51,7 @@ namespace Microsoft.VisualStudio.LanguageServer.ContainedLanguage
throw new ArgumentNullException(nameof(virtualDocument));
}
lock (DocumentContextLock)
lock (_documentContextLock)
{
if (!_virtualDocumentContexts.TryGetValue(virtualDocument.Uri, out var documentContext))
{
@ -84,7 +84,7 @@ namespace Microsoft.VisualStudio.LanguageServer.ContainedLanguage
return;
}
lock (DocumentContextLock)
lock (_documentContextLock)
{
if (!_virtualDocumentContexts.TryGetValue(virtualDocumentUri, out var documentContext))
{
@ -108,7 +108,7 @@ namespace Microsoft.VisualStudio.LanguageServer.ContainedLanguage
throw new ArgumentNullException(nameof(args));
}
lock (DocumentContextLock)
lock (_documentContextLock)
{
if (args.Kind == LSPDocumentChangeKind.Added)
{

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

@ -7,7 +7,7 @@ namespace Microsoft.VisualStudio.Text
{
internal static class TextBufferExtensions
{
private static readonly string HostDocumentVersionMarked = "__MsLsp_HostDocumentVersionMarker__";
private const string HostDocumentVersionMarked = "__MsLsp_HostDocumentVersionMarker__";
public static void SetHostDocumentSyncVersion(this ITextBuffer textBuffer, long hostDocumentVersion)
{

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

@ -17,12 +17,12 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor
internal class CSharpVirtualDocumentFactory : VirtualDocumentFactoryBase
{
public static readonly string CSharpClientName = "RazorCSharp";
private static readonly IReadOnlyDictionary<object, object> _languageBufferProperties = new Dictionary<object, object>
private static readonly IReadOnlyDictionary<object, object> s_languageBufferProperties = new Dictionary<object, object>
{
{ LanguageClientConstants.ClientNamePropertyKey, CSharpClientName }
};
private static IContentType _csharpContentType;
private static IContentType s_csharpContentType;
[ImportingConstructor]
public CSharpVirtualDocumentFactory(
@ -38,24 +38,24 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor
{
get
{
if (_csharpContentType == null)
if (s_csharpContentType == null)
{
var contentType = ContentTypeRegistry.GetContentType(RazorLSPConstants.CSharpContentTypeName);
_csharpContentType = new RemoteContentDefinitionType(contentType);
s_csharpContentType = new RemoteContentDefinitionType(contentType);
}
return _csharpContentType;
return s_csharpContentType;
}
}
protected override string HostDocumentContentTypeName => RazorLSPConstants.RazorLSPContentTypeName;
protected override string LanguageFileNameSuffix => RazorLSPConstants.VirtualCSharpFileNameSuffix;
protected override IReadOnlyDictionary<object, object> LanguageBufferProperties => _languageBufferProperties;
protected override IReadOnlyDictionary<object, object> LanguageBufferProperties => s_languageBufferProperties;
protected override VirtualDocument CreateVirtualDocument(Uri uri, ITextBuffer textBuffer) => new CSharpVirtualDocument(uri, textBuffer);
private class RemoteContentDefinitionType : IContentType
{
private static readonly IReadOnlyList<string> ExtendedBaseContentTypes = new[]
private static readonly IReadOnlyList<string> s_extendedBaseContentTypes = new[]
{
"code-languageserver-base",
CodeRemoteContentDefinition.CodeRemoteContentTypeName
@ -83,7 +83,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor
public bool IsOfType(string type)
{
return ExtendedBaseContentTypes.Contains(type) || _innerContentType.IsOfType(type);
return s_extendedBaseContentTypes.Contains(type) || _innerContentType.IsOfType(type);
}
}
}

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

@ -9,34 +9,34 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor
internal class VsEnumBSTR : IVsEnumBSTR
{
// Internal for testing
internal readonly IReadOnlyList<string> _values;
internal readonly IReadOnlyList<string> Values;
private int _currentIndex;
public VsEnumBSTR(IReadOnlyList<string> values)
{
_values = values;
Values = values;
_currentIndex = 0;
}
public int Clone(out IVsEnumBSTR ppEnum)
{
ppEnum = new VsEnumBSTR(_values);
ppEnum = new VsEnumBSTR(Values);
return VSConstants.S_OK;
}
public int GetCount(out uint pceltCount)
{
pceltCount = (uint)_values.Count;
pceltCount = (uint)Values.Count;
return VSConstants.S_OK;
}
public int Next(uint celt, string[] rgelt, out uint pceltFetched)
{
var i = 0;
for (; i < celt && _currentIndex < _values.Count; i++, _currentIndex++)
for (; i < celt && _currentIndex < Values.Count; i++, _currentIndex++)
{
rgelt[i] = _values[_currentIndex];
rgelt[i] = Values[_currentIndex];
}
pceltFetched = (uint)i;
@ -54,7 +54,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor
public int Skip(uint celt)
{
_currentIndex += (int)celt;
return _currentIndex < _values.Count
return _currentIndex < Values.Count
? VSConstants.S_OK
: VSConstants.S_FALSE;
}

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

@ -19,8 +19,8 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor
private const string UseLegacyASPNETCoreEditorSettingTemp = "TextEditor.HTMLX.Specific.UseLegacyASPNETCoreRazorEditor";
private const string UseLegacyASPNETCoreEditorSetting = "TextEditor.HTML.Specific.UseLegacyASPNETCoreRazorEditor";
private static readonly Guid LiveShareHostUIContextGuid = Guid.Parse("62de1aa5-70b0-4934-9324-680896466fe1");
private static readonly Guid LiveShareGuestUIContextGuid = Guid.Parse("fd93f3eb-60da-49cd-af15-acda729e357e");
private static readonly Guid s_liveShareHostUIContextGuid = Guid.Parse("62de1aa5-70b0-4934-9324-680896466fe1");
private static readonly Guid s_liveShareGuestUIContextGuid = Guid.Parse("fd93f3eb-60da-49cd-af15-acda729e357e");
private readonly ProjectHierarchyInspector _projectHierarchyInspector;
private readonly Lazy<IVsUIShellOpenDocument> _vsUIShellOpenDocument;
@ -91,7 +91,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor
public override bool IsLiveShareHost()
{
var context = UIContext.FromUIContextGuid(LiveShareHostUIContextGuid);
var context = UIContext.FromUIContextGuid(s_liveShareHostUIContextGuid);
return context.IsActive;
}
@ -128,7 +128,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor
// Private protected virtual for testing
private protected virtual bool IsLiveShareGuest()
{
var context = UIContext.FromUIContextGuid(LiveShareGuestUIContextGuid);
var context = UIContext.FromUIContextGuid(s_liveShareGuestUIContextGuid);
return context.IsActive;
}
}

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

@ -26,7 +26,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor
[Export(typeof(ProjectSnapshotChangeTrigger))]
internal class DefaultRazorProjectChangePublisher : ProjectSnapshotChangeTrigger
{
internal readonly Dictionary<string, Task> _deferredPublishTasks;
internal readonly Dictionary<string, Task> DeferredPublishTasks;
// Internal for testing
internal bool _active;
@ -70,7 +70,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor
throw new ArgumentNullException(nameof(serviceProvider));
}
_deferredPublishTasks = new Dictionary<string, Task>(FilePathComparer.Instance);
DeferredPublishTasks = new Dictionary<string, Task>(FilePathComparer.Instance);
_pendingProjectPublishes = new Dictionary<string, ProjectSnapshot>(FilePathComparer.Instance);
_publishLock = new object();
@ -105,9 +105,9 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor
// by capturing the sync context.
_pendingProjectPublishes[projectSnapshot.FilePath] = projectSnapshot;
if (!_deferredPublishTasks.TryGetValue(projectSnapshot.FilePath, out var update) || update.IsCompleted)
if (!DeferredPublishTasks.TryGetValue(projectSnapshot.FilePath, out var update) || update.IsCompleted)
{
_deferredPublishTasks[projectSnapshot.FilePath] = PublishAfterDelayAsync(projectSnapshot.FilePath);
DeferredPublishTasks[projectSnapshot.FilePath] = PublishAfterDelayAsync(projectSnapshot.FilePath);
}
}

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

@ -12,7 +12,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Feedback
[Obsolete("Use the LogHub logging infrastructure instead.")]
internal class LegacyHTMLCSharpLanguageServerFeedbackFileLoggerProvider : ILoggerProvider
{
private static readonly string LogFileIdentifier = "HTMLCSharpLanguageServer";
private const string LogFileIdentifier = "HTMLCSharpLanguageServer";
private readonly FeedbackFileLoggerProvider _loggerProvider;

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

@ -20,22 +20,22 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
[ExportLspMethod(Methods.TextDocumentCompletionName)]
internal class CompletionHandler : IRequestHandler<CompletionParams, SumType<CompletionItem[], CompletionList>?>
{
private static readonly IReadOnlyList<string> RazorTriggerCharacters = new[] { "@" };
private static readonly IReadOnlyList<string> CSharpTriggerCharacters = new[] { " ", "(", "=", "#", ".", "<", "[", "{", "\"", "/", ":", "~" };
private static readonly IReadOnlyList<string> HtmlTriggerCharacters = new[] { ":", "@", "#", ".", "!", "*", ",", "(", "[", "-", "<", "&", "\\", "/", "'", "\"", "=", ":", " ", "`" };
private static readonly IReadOnlyList<string> s_razorTriggerCharacters = new[] { "@" };
private static readonly IReadOnlyList<string> s_cSharpTriggerCharacters = new[] { " ", "(", "=", "#", ".", "<", "[", "{", "\"", "/", ":", "~" };
private static readonly IReadOnlyList<string> s_htmlTriggerCharacters = new[] { ":", "@", "#", ".", "!", "*", ",", "(", "[", "-", "<", "&", "\\", "/", "'", "\"", "=", ":", " ", "`" };
public static readonly IReadOnlyList<string> AllTriggerCharacters = new HashSet<string>(
CSharpTriggerCharacters
.Concat(HtmlTriggerCharacters)
.Concat(RazorTriggerCharacters))
s_cSharpTriggerCharacters
.Concat(s_htmlTriggerCharacters)
.Concat(s_razorTriggerCharacters))
.ToArray();
private static readonly IReadOnlyCollection<string> Keywords = new string[] {
private static readonly IReadOnlyCollection<string> s_keywords = new string[] {
"for", "foreach", "while", "switch", "lock",
"case", "if", "try", "do", "using"
};
private static readonly IReadOnlyCollection<string> DesignTimeHelpers = new string[]
private static readonly IReadOnlyCollection<string> s_designTimeHelpers = new string[]
{
"__builder",
"__o",
@ -47,8 +47,8 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
"BuildRenderTree"
};
private static readonly IReadOnlyCollection<CompletionItem> KeywordCompletionItems = GenerateCompletionItems(Keywords);
private static readonly IReadOnlyCollection<CompletionItem> DesignTimeHelpersCompletionItems = GenerateCompletionItems(DesignTimeHelpers);
private static readonly IReadOnlyCollection<CompletionItem> s_keywordCompletionItems = GenerateCompletionItems(s_keywords);
private static readonly IReadOnlyCollection<CompletionItem> s_designTimeHelpersCompletionItems = GenerateCompletionItems(s_designTimeHelpers);
private readonly JoinableTaskFactory _joinableTaskFactory;
private readonly LSPRequestInvoker _requestInvoker;
@ -321,7 +321,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
TextExtent? wordExtent,
CompletionList completionList)
{
var filteredItems = completionList.Items.Except(DesignTimeHelpersCompletionItems, CompletionItemComparer.Instance).ToArray();
var filteredItems = completionList.Items.Except(s_designTimeHelpersCompletionItems, CompletionItemComparer.Instance).ToArray();
// If the current identifier starts with "__", only trim out common design time helpers from the list.
// In all other cases, trim out both common design time helpers and all completion items starting with "__".
@ -368,13 +368,13 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
return context;
}
if (languageKind == RazorLanguageKind.CSharp && CSharpTriggerCharacters.Contains(context.TriggerCharacter))
if (languageKind == RazorLanguageKind.CSharp && s_cSharpTriggerCharacters.Contains(context.TriggerCharacter))
{
// C# trigger character for C# content
return context;
}
if (languageKind == RazorLanguageKind.Html && HtmlTriggerCharacters.Contains(context.TriggerCharacter))
if (languageKind == RazorLanguageKind.Html && s_htmlTriggerCharacters.Contains(context.TriggerCharacter))
{
// HTML trigger character for HTML content
return context;
@ -392,7 +392,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
rewrittenContext.InvokeKind = invokeKind.Value;
}
if (languageKind == RazorLanguageKind.CSharp && RazorTriggerCharacters.Contains(context.TriggerCharacter))
if (languageKind == RazorLanguageKind.CSharp && s_razorTriggerCharacters.Contains(context.TriggerCharacter))
{
// The C# language server will not return any completions for the '@' character unless we
// send the completion request explicitly.
@ -505,7 +505,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
// but once C# starts providing them their completion will be offered instead, at which point we should be able to remove this step.
private static CompletionList IncludeCSharpKeywords(CompletionList completionList)
{
var newList = completionList.Items.Union(KeywordCompletionItems, CompletionItemComparer.Instance);
var newList = completionList.Items.Union(s_keywordCompletionItems, CompletionItemComparer.Instance);
completionList.Items = newList.ToArray();
return completionList;
@ -647,18 +647,18 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
private static bool IsApplicableTriggerCharacter(string triggerCharacter, RazorLanguageKind languageKind)
{
if (RazorTriggerCharacters.Contains(triggerCharacter))
if (s_razorTriggerCharacters.Contains(triggerCharacter))
{
// Razor trigger characters always transition into either C# or HTML, always note as "applicable".
return true;
}
else if (languageKind == RazorLanguageKind.CSharp)
{
return CSharpTriggerCharacters.Contains(triggerCharacter);
return s_cSharpTriggerCharacters.Contains(triggerCharacter);
}
else if (languageKind == RazorLanguageKind.Html)
{
return HtmlTriggerCharacters.Contains(triggerCharacter);
return s_htmlTriggerCharacters.Contains(triggerCharacter);
}
// Unknown trigger character.

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

@ -19,7 +19,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
[Export(typeof(LSPDocumentMappingProvider))]
internal class DefaultLSPDocumentMappingProvider : LSPDocumentMappingProvider
{
private static readonly TextEdit[] EmptyEdits = Array.Empty<TextEdit>();
private static readonly TextEdit[] s_emptyEdits = Array.Empty<TextEdit>();
private readonly LSPRequestInvoker _requestInvoker;
@ -358,7 +358,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
mappingResult.HostDocumentVersion != documentSnapshot.Version))
{
// Couldn't remap the location or the document changed in the meantime. Discard these ranges.
return (null, EmptyEdits);
return (null, s_emptyEdits);
}
return (documentSnapshot, mappingResult.TextEdits);

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

@ -261,18 +261,18 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
private static object FilterReferenceDisplayText(object referenceText)
{
const string codeBehindObjectPrefix = "__o = ";
const string codeBehindBackingFieldSuffix = "k__BackingField";
const string CodeBehindObjectPrefix = "__o = ";
const string CodeBehindBackingFieldSuffix = "k__BackingField";
if (referenceText is string text)
{
if (text.StartsWith(codeBehindObjectPrefix, StringComparison.Ordinal))
if (text.StartsWith(CodeBehindObjectPrefix, StringComparison.Ordinal))
{
return text
.Substring(codeBehindObjectPrefix.Length, text.Length - codeBehindObjectPrefix.Length - 1); // -1 for trailing `;`
.Substring(CodeBehindObjectPrefix.Length, text.Length - CodeBehindObjectPrefix.Length - 1); // -1 for trailing `;`
}
return text.Replace(codeBehindBackingFieldSuffix, string.Empty);
return text.Replace(CodeBehindBackingFieldSuffix, string.Empty);
}
if (referenceText is ClassifiedTextElement textElement &&

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

@ -21,7 +21,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
[ExportLspMethod(Methods.InitializeName)]
internal class InitializeHandler : IRequestHandler<InitializeParams, InitializeResult>
{
private static readonly InitializeResult InitializeResult = new()
private static readonly InitializeResult s_initializeResult = new()
{
Capabilities = new VSServerCapabilities
{
@ -108,7 +108,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
_logger.LogInformation("Providing initialization configuration.");
return Task.FromResult(InitializeResult);
return Task.FromResult(s_initializeResult);
}
[Conditional("DEBUG")]
@ -339,7 +339,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
private async Task VerifyMergedHoverAsync(VSServerCapabilities mergedCapabilities)
{
if (mergedCapabilities.HoverProvider != InitializeResult.Capabilities.HoverProvider)
if (mergedCapabilities.HoverProvider != s_initializeResult.Capabilities.HoverProvider)
{
await _joinableTaskFactory.SwitchToMainThreadAsync();
@ -363,8 +363,8 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
mergedTriggerCharEnumeration = mergedTriggerCharEnumeration.Except(purposefullyRemovedTriggerCharacters);
var mergedTriggerChars = new HashSet<string>(mergedTriggerCharEnumeration);
if (!mergedCommitChars.SetEquals(InitializeResult.Capabilities.CompletionProvider?.AllCommitCharacters!) ||
!mergedTriggerChars.SetEquals(InitializeResult.Capabilities.CompletionProvider?.TriggerCharacters!))
if (!mergedCommitChars.SetEquals(s_initializeResult.Capabilities.CompletionProvider?.AllCommitCharacters!) ||
!mergedTriggerChars.SetEquals(s_initializeResult.Capabilities.CompletionProvider?.TriggerCharacters!))
{
await _joinableTaskFactory.SwitchToMainThreadAsync();
@ -380,9 +380,9 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
var mergedRetriggerChars = new HashSet<string>(mergedRetriggerCharEnumeration);
var mergedWorkDoneProgress = mergedCapabilities.SignatureHelpProvider?.WorkDoneProgress;
if (!mergedTriggerChars.SetEquals(InitializeResult.Capabilities.SignatureHelpProvider?.TriggerCharacters!) ||
!mergedRetriggerChars.SetEquals(InitializeResult.Capabilities.SignatureHelpProvider?.RetriggerCharacters!) ||
mergedWorkDoneProgress != InitializeResult.Capabilities.SignatureHelpProvider?.WorkDoneProgress)
if (!mergedTriggerChars.SetEquals(s_initializeResult.Capabilities.SignatureHelpProvider?.TriggerCharacters!) ||
!mergedRetriggerChars.SetEquals(s_initializeResult.Capabilities.SignatureHelpProvider?.RetriggerCharacters!) ||
mergedWorkDoneProgress != s_initializeResult.Capabilities.SignatureHelpProvider?.WorkDoneProgress)
{
await _joinableTaskFactory.SwitchToMainThreadAsync();
@ -392,7 +392,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
private async Task VerifyMergedDefinitionProviderAsync(VSServerCapabilities mergedCapabilities)
{
if (mergedCapabilities.DefinitionProvider != InitializeResult.Capabilities.DefinitionProvider)
if (mergedCapabilities.DefinitionProvider != s_initializeResult.Capabilities.DefinitionProvider)
{
await _joinableTaskFactory.SwitchToMainThreadAsync();
@ -402,7 +402,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
private async Task VerifyMergedReferencesProviderAsync(VSServerCapabilities mergedCapabilities)
{
if (mergedCapabilities.ReferencesProvider != InitializeResult.Capabilities.ReferencesProvider)
if (mergedCapabilities.ReferencesProvider != s_initializeResult.Capabilities.ReferencesProvider)
{
await _joinableTaskFactory.SwitchToMainThreadAsync();
@ -412,7 +412,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
private async Task VerifyMergedRenameProviderAsync(VSServerCapabilities mergedCapabilities)
{
if (mergedCapabilities.RenameProvider != InitializeResult.Capabilities.RenameProvider)
if (mergedCapabilities.RenameProvider != s_initializeResult.Capabilities.RenameProvider)
{
await _joinableTaskFactory.SwitchToMainThreadAsync();
@ -430,7 +430,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
var filteredMergedTriggerCharacters = mergedTriggerCharacters.Except(purposefullyRemovedTriggerCharacters);
var mergedTriggerChars = new HashSet<string>(filteredMergedTriggerCharacters);
var razorOnTypeFormattingOptions = InitializeResult.Capabilities.DocumentOnTypeFormattingProvider;
var razorOnTypeFormattingOptions = s_initializeResult.Capabilities.DocumentOnTypeFormattingProvider;
var razorTriggerCharacters = new HashSet<string>
{
razorOnTypeFormattingOptions.FirstTriggerCharacter

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

@ -18,10 +18,10 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
[ExportLspMethod(MSLSPMethods.OnAutoInsertName)]
internal class OnAutoInsertHandler : IRequestHandler<DocumentOnAutoInsertParams, DocumentOnAutoInsertResponseItem>
{
private static readonly HashSet<string> HTMLAllowedTriggerCharacters = new HashSet<string>();
private static readonly HashSet<string> CSharpAllowedTriggerCharacters = new() { "'", "/", "\n" };
private static readonly HashSet<string> AllAllowedTriggerCharacters = HTMLAllowedTriggerCharacters
.Concat(CSharpAllowedTriggerCharacters)
private static readonly HashSet<string> s_htmlAllowedTriggerCharacters = new HashSet<string>();
private static readonly HashSet<string> s_cSharpAllowedTriggerCharacters = new() { "'", "/", "\n" };
private static readonly HashSet<string> s_allAllowedTriggerCharacters = s_htmlAllowedTriggerCharacters
.Concat(s_cSharpAllowedTriggerCharacters)
.ToHashSet();
private readonly LSPDocumentManager _documentManager;
@ -78,7 +78,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
throw new ArgumentNullException(nameof(request));
}
if (!AllAllowedTriggerCharacters.Contains(request.Character, StringComparer.Ordinal))
if (!s_allAllowedTriggerCharacters.Contains(request.Character, StringComparer.Ordinal))
{
// We haven't built support for this character yet.
return null;
@ -103,13 +103,13 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
return null;
}
else if (projectionResult.LanguageKind == RazorLanguageKind.Html &&
!HTMLAllowedTriggerCharacters.Contains(request.Character, StringComparer.Ordinal))
!s_htmlAllowedTriggerCharacters.Contains(request.Character, StringComparer.Ordinal))
{
_logger.LogInformation("Inapplicable HTML trigger char.");
return null;
}
else if (projectionResult.LanguageKind == RazorLanguageKind.CSharp &&
!CSharpAllowedTriggerCharacters.Contains(request.Character, StringComparer.Ordinal))
!s_cSharpAllowedTriggerCharacters.Contains(request.Character, StringComparer.Ordinal))
{
_logger.LogInformation("Inapplicable C# trigger char.");
return null;

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

@ -19,9 +19,9 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
[ExportLspMethod(Methods.TextDocumentOnTypeFormattingName)]
internal class OnTypeFormattingHandler : IRequestHandler<DocumentOnTypeFormattingParams, TextEdit[]>
{
private static readonly IReadOnlyList<string> CSharpTriggerCharacters = new[] { "}", ";" };
private static readonly IReadOnlyList<string> HtmlTriggerCharacters = Array.Empty<string>();
private static readonly IReadOnlyList<string> AllTriggerCharacters = CSharpTriggerCharacters.Concat(HtmlTriggerCharacters).ToArray();
private static readonly IReadOnlyList<string> s_cSharpTriggerCharacters = new[] { "}", ";" };
private static readonly IReadOnlyList<string> s_htmlTriggerCharacters = Array.Empty<string>();
private static readonly IReadOnlyList<string> s_allTriggerCharacters = s_cSharpTriggerCharacters.Concat(s_htmlTriggerCharacters).ToArray();
private readonly LSPDocumentManager _documentManager;
private readonly LSPRequestInvoker _requestInvoker;
@ -72,7 +72,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
public async Task<TextEdit[]> HandleRequestAsync(DocumentOnTypeFormattingParams request, ClientCapabilities clientCapabilities, CancellationToken cancellationToken)
{
if (!AllTriggerCharacters.Contains(request.Character, StringComparer.Ordinal))
if (!s_allTriggerCharacters.Contains(request.Character, StringComparer.Ordinal))
{
// Unexpected trigger character.
return null;
@ -175,11 +175,11 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp
{
if (languageKind == RazorLanguageKind.CSharp)
{
return CSharpTriggerCharacters.Contains(triggerCharacter);
return s_cSharpTriggerCharacters.Contains(triggerCharacter);
}
else if (languageKind == RazorLanguageKind.Html)
{
return HtmlTriggerCharacters.Contains(triggerCharacter);
return s_htmlTriggerCharacters.Contains(triggerCharacter);
}
// Unknown trigger character.

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

@ -13,7 +13,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor
[Export(typeof(VirtualDocumentFactory))]
internal class HtmlVirtualDocumentFactory : VirtualDocumentFactoryBase
{
private static IContentType _htmlLSPContentType;
private static IContentType s_htmlLSPContentType;
[ImportingConstructor]
public HtmlVirtualDocumentFactory(
@ -29,12 +29,12 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor
{
get
{
if (_htmlLSPContentType == null)
if (s_htmlLSPContentType == null)
{
_htmlLSPContentType = ContentTypeRegistry.GetContentType(RazorLSPConstants.HtmlLSPContentTypeName);
s_htmlLSPContentType = ContentTypeRegistry.GetContentType(RazorLSPConstants.HtmlLSPContentTypeName);
}
return _htmlLSPContentType;
return s_htmlLSPContentType;
}
}

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

@ -15,7 +15,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Logging
[Export(typeof(HTMLCSharpLanguageServerLogHubLoggerProvider))]
internal class HTMLCSharpLanguageServerLogHubLoggerProvider : ILoggerProvider
{
private static readonly string LogFileIdentifier = "Razor.HTMLCSharpLanguageServerClient";
private const string LogFileIdentifier = "Razor.HTMLCSharpLanguageServerClient";
private LogHubLoggerProvider _loggerProvider;

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

@ -11,7 +11,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Logging
{
// Unique, monotomically increasing ID to identify loghub session to persist
// across server restarts.
private static int _logHubSessionId;
private static int s_logHubSessionId;
private readonly RazorLogHubTraceProvider _traceProvider;
private readonly SemaphoreSlim _initializationSemaphore;
@ -40,7 +40,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Logging
_currentLogWriter.Dispose();
}
var logInstanceNumber = Interlocked.Increment(ref _logHubSessionId);
var logInstanceNumber = Interlocked.Increment(ref s_logHubSessionId);
var traceSource = await _traceProvider.InitializeTraceAsync(logIdentifier, logInstanceNumber, cancellationToken).ConfigureAwait(false);
_currentLogWriter = new DefaultLogHubLogWriter(traceSource);

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

@ -15,7 +15,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Logging
[Export(typeof(RazorLogHubTraceProvider))]
internal class RazorLogHubTraceProvider
{
private static readonly LoggerOptions _logOptions = new(
private static readonly LoggerOptions s_logOptions = new(
requestedLoggingLevel: new LoggingLevelSettings(SourceLevels.Information | SourceLevels.ActivityTracing),
privacySetting: PrivacyFlags.MayContainPersonallyIdentifibleInformation | PrivacyFlags.MayContainPrivateInformation);
@ -34,12 +34,12 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Logging
return null;
}
var _logId = new LogId(
var logId = new LogId(
logName: $"{logIdentifier}.{logHubSessionId}",
serviceId: new ServiceMoniker($"Razor.{logIdentifier}"));
using var traceConfig = await LogHub.TraceConfiguration.CreateTraceConfigurationInstanceAsync(_serviceBroker, cancellationToken).ConfigureAwait(false);
var traceSource = await traceConfig.RegisterLogSourceAsync(_logId, _logOptions, cancellationToken).ConfigureAwait(false);
var traceSource = await traceConfig.RegisterLogSourceAsync(logId, s_logOptions, cancellationToken).ConfigureAwait(false);
return traceSource;
}

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

@ -30,7 +30,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor
[ContentType(RazorLSPConstants.RazorLSPContentTypeName)]
internal class RazorLanguageServerClient : ILanguageClient, ILanguageClientCustomMessage2, ILanguageClientPriority
{
private static readonly string LogFileIdentifier = "Razor.RazorLanguageServerClient";
private const string LogFileIdentifier = "Razor.RazorLanguageServerClient";
private readonly RazorLanguageServerCustomMessageTarget _customMessageTarget;
private readonly ILanguageClientMiddleLayer _middleLayer;

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

@ -105,7 +105,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Documents
{
ForegroundDispatcher.AssertForegroundThread();
lock (_lock)
lock (Lock)
{
// Casts avoid dynamic
if ((object)_runningDocumentTable.GetDocumentData(cookie) is IVsTextBuffer vsTextBuffer)
@ -157,7 +157,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Documents
{
ForegroundDispatcher.AssertForegroundThread();
lock (_lock)
lock (Lock)
{
for (var i = 0; i < documents.Length; i++)
{
@ -170,7 +170,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Documents
{
ForegroundDispatcher.AssertForegroundThread();
lock (_lock)
lock (Lock)
{
if (!_documentsByCookie.TryGetValue(cookie, out var documents))
{
@ -200,7 +200,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Documents
return;
}
lock (_lock)
lock (Lock)
{
// Treat a rename as a close + reopen.
//

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

@ -114,7 +114,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem
if (TryGetIntermediateOutputPath(update.Value.CurrentState, out var intermediatePath))
{
var projectRazorJson = Path.Combine(intermediatePath, "project.razor.json");
_projectConfigurationFilePathStore.Set(hostProject.FilePath, projectRazorJson);
ProjectConfigurationFilePathStore.Set(hostProject.FilePath, projectRazorJson);
}
UpdateProjectUnsafe(hostProject);

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

@ -141,7 +141,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem
if (TryGetIntermediateOutputPath(update.Value.CurrentState, out var intermediatePath))
{
var projectRazorJson = Path.Combine(intermediatePath, "project.razor.json");
_projectConfigurationFilePathStore.Set(hostProject.FilePath, projectRazorJson);
ProjectConfigurationFilePathStore.Set(hostProject.FilePath, projectRazorJson);
}
UpdateProjectUnsafe(hostProject);

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

@ -27,7 +27,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem
private ProjectSnapshotManagerBase _projectManager;
private readonly Dictionary<string, HostDocument> _currentDocuments;
protected readonly ProjectConfigurationFilePathStore _projectConfigurationFilePathStore;
protected readonly ProjectConfigurationFilePathStore ProjectConfigurationFilePathStore;
internal const string BaseIntermediateOutputPathPropertyName = "BaseIntermediateOutputPath";
internal const string IntermediateOutputPathPropertyName = "IntermediateOutputPath";
@ -60,7 +60,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem
_lock = new AsyncSemaphore(initialCount: 1);
_currentDocuments = new Dictionary<string, HostDocument>(FilePathComparer.Instance);
_projectConfigurationFilePathStore = projectConfigurationFilePathStore;
ProjectConfigurationFilePathStore = projectConfigurationFilePathStore;
}
// Internal for testing
@ -184,7 +184,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem
{
Debug.Assert(_currentDocuments.Count == 0);
projectManager.ProjectRemoved(Current);
_projectConfigurationFilePathStore.Remove(Current.FilePath);
ProjectConfigurationFilePathStore.Remove(Current.FilePath);
}
else
{

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

@ -43,7 +43,7 @@ namespace Microsoft.VisualStudio.Mac.LanguageServices.Razor
{
ForegroundDispatcher.AssertForegroundThread();
lock (_lock)
lock (Lock)
{
if (!TryGetMatchingDocuments(filePath, out var documents))
{
@ -59,7 +59,7 @@ namespace Microsoft.VisualStudio.Mac.LanguageServices.Razor
{
ForegroundDispatcher.AssertForegroundThread();
lock (_lock)
lock (Lock)
{
if (!TryGetMatchingDocuments(filePath, out var documents))
{
@ -88,7 +88,7 @@ namespace Microsoft.VisualStudio.Mac.LanguageServices.Razor
return;
}
lock (_lock)
lock (Lock)
{
// Treat a rename as a close + reopen.
//
@ -104,7 +104,7 @@ namespace Microsoft.VisualStudio.Mac.LanguageServices.Razor
{
ForegroundDispatcher.AssertForegroundThread();
lock (_lock)
lock (Lock)
{
for (var i = 0; i < documents.Length; i++)
{

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

@ -20,13 +20,13 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
{
public class AddUsingsCodeActionResolverTest : LanguageServerTestBase
{
private readonly DocumentResolver EmptyDocumentResolver = Mock.Of<DocumentResolver>(r => r.TryResolveDocument(It.IsAny<string>(), out It.Ref<DocumentSnapshot>.IsAny) == false, MockBehavior.Strict);
private readonly DocumentResolver _emptyDocumentResolver = Mock.Of<DocumentResolver>(r => r.TryResolveDocument(It.IsAny<string>(), out It.Ref<DocumentSnapshot>.IsAny) == false, MockBehavior.Strict);
[Fact]
public async Task Handle_MissingFile()
{
// Arrange
var resolver = new AddUsingsCodeActionResolver(new DefaultForegroundDispatcher(), EmptyDocumentResolver);
var resolver = new AddUsingsCodeActionResolver(new DefaultForegroundDispatcher(), _emptyDocumentResolver);
var data = JObject.FromObject(new AddUsingsCodeActionParams()
{
Uri = new Uri("c:/Test.razor"),

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

@ -22,7 +22,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
{
public class AddUsingsCSharpCodeActionResolverTest : LanguageServerTestBase
{
private static readonly CodeAction DefaultResolvedCodeAction = new CodeAction()
private static readonly CodeAction s_defaultResolvedCodeAction = new CodeAction()
{
Title = "@using System.Net",
Data = JToken.FromObject(new object()),
@ -43,7 +43,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
}
};
private static readonly CodeAction DefaultUnresolvedCodeAction = new CodeAction()
private static readonly CodeAction s_defaultUnresolvedCodeAction = new CodeAction()
{
Title = "@using System.Net"
};
@ -55,11 +55,11 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
CreateCodeActionResolver(out var codeActionParams, out var csharpCodeActionResolver);
// Act
var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, DefaultUnresolvedCodeAction, default);
var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, s_defaultUnresolvedCodeAction, default);
// Assert
Assert.Equal(DefaultResolvedCodeAction.Title, returnedCodeAction.Title);
Assert.Equal(DefaultResolvedCodeAction.Data, returnedCodeAction.Data);
Assert.Equal(s_defaultResolvedCodeAction.Title, returnedCodeAction.Title);
Assert.Equal(s_defaultResolvedCodeAction.Data, returnedCodeAction.Data);
var returnedEdits = Assert.Single(returnedCodeAction.Edit.DocumentChanges);
Assert.True(returnedEdits.IsTextDocumentEdit);
var returnedTextDocumentEdit = Assert.Single(returnedEdits.TextDocumentEdit.Edits);
@ -85,10 +85,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
CreateCodeActionResolver(out var codeActionParams, out var csharpCodeActionResolver, languageServer: languageServer);
// Act
var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, DefaultUnresolvedCodeAction, default);
var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, s_defaultUnresolvedCodeAction, default);
// Assert
Assert.Equal(DefaultUnresolvedCodeAction.Title, returnedCodeAction.Title);
Assert.Equal(s_defaultUnresolvedCodeAction.Title, returnedCodeAction.Title);
}
[Fact]
@ -132,10 +132,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
CreateCodeActionResolver(out var codeActionParams, out var csharpCodeActionResolver, languageServer: languageServer);
// Act
var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, DefaultUnresolvedCodeAction, default);
var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, s_defaultUnresolvedCodeAction, default);
// Assert
Assert.Equal(DefaultUnresolvedCodeAction.Title, returnedCodeAction.Title);
Assert.Equal(s_defaultUnresolvedCodeAction.Title, returnedCodeAction.Title);
}
[Fact]
@ -163,10 +163,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
CreateCodeActionResolver(out var codeActionParams, out var csharpCodeActionResolver, languageServer: languageServer);
// Act
var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, DefaultUnresolvedCodeAction, default);
var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, s_defaultUnresolvedCodeAction, default);
// Assert
Assert.Equal(DefaultUnresolvedCodeAction.Title, returnedCodeAction.Title);
Assert.Equal(s_defaultUnresolvedCodeAction.Title, returnedCodeAction.Title);
}
private void CreateCodeActionResolver(
@ -208,7 +208,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
var responseRouterReturns = new Mock<IResponseRouterReturns>(MockBehavior.Strict);
responseRouterReturns
.Setup(l => l.Returning<CodeAction>(It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(resolvedCodeAction ?? DefaultResolvedCodeAction));
.Returns(Task.FromResult(resolvedCodeAction ?? s_defaultResolvedCodeAction));
var languageServer = new Mock<ClientNotifierServiceBase>(MockBehavior.Strict);
languageServer

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

@ -19,11 +19,11 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
{
public class DefaultCSharpCodeActionProviderTest : LanguageServerTestBase
{
private readonly RazorCodeAction[] SupportedCodeActions;
private readonly RazorCodeAction[] _supportedCodeActions;
public DefaultCSharpCodeActionProviderTest()
{
SupportedCodeActions = DefaultCSharpCodeActionProvider
_supportedCodeActions = DefaultCSharpCodeActionProvider
.SupportedDefaultCodeActionNames
.Select(name => new RazorCodeAction() { Name = name })
.ToArray();
@ -49,12 +49,12 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
var provider = new DefaultCSharpCodeActionProvider();
// Act
var providedCodeActions = await provider.ProvideAsync(context, SupportedCodeActions, default);
var providedCodeActions = await provider.ProvideAsync(context, _supportedCodeActions, default);
// Assert
Assert.Equal(SupportedCodeActions.Length, providedCodeActions.Count);
Assert.Equal(_supportedCodeActions.Length, providedCodeActions.Count);
var providedNames = providedCodeActions.Select(action => action.Name);
var expectedNames = SupportedCodeActions.Select(action => action.Name);
var expectedNames = _supportedCodeActions.Select(action => action.Name);
Assert.Equal(expectedNames, providedNames);
}
@ -78,7 +78,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
var provider = new DefaultCSharpCodeActionProvider();
// Act
var providedCodeActions = await provider.ProvideAsync(context, SupportedCodeActions, default);
var providedCodeActions = await provider.ProvideAsync(context, _supportedCodeActions, default);
// Assert
Assert.Empty(providedCodeActions);
@ -104,7 +104,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
var provider = new DefaultCSharpCodeActionProvider();
// Act
var providedCodeActions = await provider.ProvideAsync(context, SupportedCodeActions, default);
var providedCodeActions = await provider.ProvideAsync(context, _supportedCodeActions, default);
// Assert
Assert.Empty(providedCodeActions);

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

@ -24,7 +24,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
{
public class DefaultCSharpCodeActionResolverTest : LanguageServerTestBase
{
private static readonly CodeAction DefaultResolvedCodeAction = new CodeAction()
private static readonly CodeAction s_defaultResolvedCodeAction = new CodeAction()
{
Title = "ResolvedCodeAction",
Data = JToken.FromObject(new object()),
@ -45,7 +45,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
}
};
private static readonly TextEdit[] DefaultFormattedEdits = new TextEdit[]
private static readonly TextEdit[] s_defaultFormattedEdits = new TextEdit[]
{
new TextEdit()
{
@ -53,7 +53,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
}
};
private static readonly CodeAction DefaultUnresolvedCodeAction = new CodeAction()
private static readonly CodeAction s_defaultUnresolvedCodeAction = new CodeAction()
{
Title = "Unresolved Code Action"
};
@ -65,15 +65,15 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
CreateCodeActionResolver(out var codeActionParams, out var csharpCodeActionResolver);
// Act
var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, DefaultUnresolvedCodeAction, default);
var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, s_defaultUnresolvedCodeAction, default);
// Assert
Assert.Equal(DefaultResolvedCodeAction.Title, returnedCodeAction.Title);
Assert.Equal(DefaultResolvedCodeAction.Data, returnedCodeAction.Data);
Assert.Equal(s_defaultResolvedCodeAction.Title, returnedCodeAction.Title);
Assert.Equal(s_defaultResolvedCodeAction.Data, returnedCodeAction.Data);
var returnedEdits = Assert.Single(returnedCodeAction.Edit.DocumentChanges);
Assert.True(returnedEdits.IsTextDocumentEdit);
var returnedTextDocumentEdit = Assert.Single(returnedEdits.TextDocumentEdit.Edits);
Assert.Equal(DefaultFormattedEdits.First(), returnedTextDocumentEdit);
Assert.Equal(s_defaultFormattedEdits.First(), returnedTextDocumentEdit);
}
[Fact]
@ -95,10 +95,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
CreateCodeActionResolver(out var codeActionParams, out var csharpCodeActionResolver, languageServer: languageServer);
// Act
var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, DefaultUnresolvedCodeAction, default);
var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, s_defaultUnresolvedCodeAction, default);
// Assert
Assert.Equal(DefaultUnresolvedCodeAction.Title, returnedCodeAction.Title);
Assert.Equal(s_defaultUnresolvedCodeAction.Title, returnedCodeAction.Title);
}
[Fact]
@ -142,10 +142,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
CreateCodeActionResolver(out var codeActionParams, out var csharpCodeActionResolver, languageServer: languageServer);
// Act
var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, DefaultUnresolvedCodeAction, default);
var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, s_defaultUnresolvedCodeAction, default);
// Assert
Assert.Equal(DefaultUnresolvedCodeAction.Title, returnedCodeAction.Title);
Assert.Equal(s_defaultUnresolvedCodeAction.Title, returnedCodeAction.Title);
}
[Fact]
@ -173,10 +173,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
CreateCodeActionResolver(out var codeActionParams, out var csharpCodeActionResolver, languageServer: languageServer);
// Act
var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, DefaultUnresolvedCodeAction, default);
var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, s_defaultUnresolvedCodeAction, default);
// Assert
Assert.Equal(DefaultUnresolvedCodeAction.Title, returnedCodeAction.Title);
Assert.Equal(s_defaultUnresolvedCodeAction.Title, returnedCodeAction.Title);
}
private void CreateCodeActionResolver(
@ -220,7 +220,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
It.IsAny<FormattingOptions>(),
It.IsAny<CancellationToken>(),
/*bypassValidationPasses:*/ true,
It.IsAny<bool>()) == Task.FromResult(DefaultFormattedEdits), MockBehavior.Strict);
It.IsAny<bool>()) == Task.FromResult(s_defaultFormattedEdits), MockBehavior.Strict);
return razorFormattingService;
}
@ -236,7 +236,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
var responseRouterReturns = new Mock<IResponseRouterReturns>(MockBehavior.Strict);
responseRouterReturns
.Setup(l => l.Returning<CodeAction>(It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(resolvedCodeAction ?? DefaultResolvedCodeAction));
.Returns(Task.FromResult(resolvedCodeAction ?? s_defaultResolvedCodeAction));
var languageServer = new Mock<ClientNotifierServiceBase>(MockBehavior.Strict);
languageServer

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

@ -25,10 +25,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
{
public class CodeActionEndpointTest : LanguageServerTestBase
{
private readonly RazorDocumentMappingService DocumentMappingService = Mock.Of<RazorDocumentMappingService>(s => s.TryMapToProjectedDocumentRange(It.IsAny<RazorCodeDocument>(), It.IsAny<Range>(), out It.Ref<Range>.IsAny) == false, MockBehavior.Strict);
private readonly DocumentResolver EmptyDocumentResolver = Mock.Of<DocumentResolver>(r => r.TryResolveDocument(It.IsAny<string>(), out It.Ref<DocumentSnapshot>.IsAny) == false, MockBehavior.Strict);
private readonly LanguageServerFeatureOptions LanguageServerFeatureOptions = Mock.Of<LanguageServerFeatureOptions>(l => l.SupportsFileManipulation == true, MockBehavior.Strict);
private readonly ClientNotifierServiceBase LanguageServer = Mock.Of<ClientNotifierServiceBase>(MockBehavior.Strict);
private readonly RazorDocumentMappingService _documentMappingService = Mock.Of<RazorDocumentMappingService>(s => s.TryMapToProjectedDocumentRange(It.IsAny<RazorCodeDocument>(), It.IsAny<Range>(), out It.Ref<Range>.IsAny) == false, MockBehavior.Strict);
private readonly DocumentResolver _emptyDocumentResolver = Mock.Of<DocumentResolver>(r => r.TryResolveDocument(It.IsAny<string>(), out It.Ref<DocumentSnapshot>.IsAny) == false, MockBehavior.Strict);
private readonly LanguageServerFeatureOptions _languageServerFeatureOptions = Mock.Of<LanguageServerFeatureOptions>(l => l.SupportsFileManipulation == true, MockBehavior.Strict);
private readonly ClientNotifierServiceBase _languageServer = Mock.Of<ClientNotifierServiceBase>(MockBehavior.Strict);
[Fact]
public async Task Handle_NoDocument()
@ -36,13 +36,13 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
// Arrange
var documentPath = "C:/path/to/Page.razor";
var codeActionEndpoint = new CodeActionEndpoint(
DocumentMappingService,
_documentMappingService,
Array.Empty<RazorCodeActionProvider>(),
Array.Empty<CSharpCodeActionProvider>(),
Dispatcher,
EmptyDocumentResolver,
LanguageServer,
LanguageServerFeatureOptions)
_emptyDocumentResolver,
_languageServer,
_languageServerFeatureOptions)
{
_supportsCodeActionResolve = false
};
@ -69,13 +69,13 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
var documentResolver = CreateDocumentResolver(documentPath, codeDocument);
codeDocument.SetUnsupported();
var codeActionEndpoint = new CodeActionEndpoint(
DocumentMappingService,
_documentMappingService,
Array.Empty<RazorCodeActionProvider>(),
Array.Empty<CSharpCodeActionProvider>(),
Dispatcher,
documentResolver,
LanguageServer,
LanguageServerFeatureOptions)
_languageServer,
_languageServerFeatureOptions)
{
_supportsCodeActionResolve = false
};
@ -101,13 +101,13 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
var codeDocument = CreateCodeDocument("@code {}");
var documentResolver = CreateDocumentResolver(documentPath, codeDocument);
var codeActionEndpoint = new CodeActionEndpoint(
DocumentMappingService,
_documentMappingService,
Array.Empty<RazorCodeActionProvider>(),
Array.Empty<CSharpCodeActionProvider>(),
Dispatcher,
documentResolver,
LanguageServer,
LanguageServerFeatureOptions)
_languageServer,
_languageServerFeatureOptions)
{
_supportsCodeActionResolve = false
};
@ -133,15 +133,15 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
var codeDocument = CreateCodeDocument("@code {}");
var documentResolver = CreateDocumentResolver(documentPath, codeDocument);
var codeActionEndpoint = new CodeActionEndpoint(
DocumentMappingService,
_documentMappingService,
new RazorCodeActionProvider[] {
new MockRazorCodeActionProvider()
},
Array.Empty<CSharpCodeActionProvider>(),
Dispatcher,
documentResolver,
LanguageServer,
LanguageServerFeatureOptions)
_languageServer,
_languageServerFeatureOptions)
{
_supportsCodeActionResolve = false
};
@ -178,7 +178,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
Dispatcher,
documentResolver,
languageServer,
LanguageServerFeatureOptions)
_languageServerFeatureOptions)
{
_supportsCodeActionResolve = false
};
@ -205,15 +205,15 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
var codeDocument = CreateCodeDocument("@code {}");
var documentResolver = CreateDocumentResolver(documentPath, codeDocument);
var codeActionEndpoint = new CodeActionEndpoint(
DocumentMappingService,
_documentMappingService,
new RazorCodeActionProvider[] {
new MockMultipleRazorCodeActionProvider(),
},
Array.Empty<CSharpCodeActionProvider>(),
Dispatcher,
documentResolver,
LanguageServer,
LanguageServerFeatureOptions)
_languageServer,
_languageServerFeatureOptions)
{
_supportsCodeActionResolve = false
};
@ -255,7 +255,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
Dispatcher,
documentResolver,
languageServer,
LanguageServerFeatureOptions)
_languageServerFeatureOptions)
{
_supportsCodeActionResolve = false
};
@ -297,7 +297,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
Dispatcher,
documentResolver,
languageServer,
LanguageServerFeatureOptions)
_languageServerFeatureOptions)
{
_supportsCodeActionResolve = false
};
@ -324,15 +324,15 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
var codeDocument = CreateCodeDocument("@code {}");
var documentResolver = CreateDocumentResolver(documentPath, codeDocument);
var codeActionEndpoint = new CodeActionEndpoint(
DocumentMappingService,
_documentMappingService,
new RazorCodeActionProvider[] {
new MockNullRazorCodeActionProvider()
},
Array.Empty<CSharpCodeActionProvider>(),
Dispatcher,
documentResolver,
LanguageServer,
LanguageServerFeatureOptions)
_languageServer,
_languageServerFeatureOptions)
{
_supportsCodeActionResolve = false
};
@ -375,7 +375,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
Dispatcher,
documentResolver,
languageServer,
LanguageServerFeatureOptions)
_languageServerFeatureOptions)
{
_supportsCodeActionResolve = false
};
@ -402,7 +402,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
var codeDocument = CreateCodeDocument("@code {}");
var documentResolver = CreateDocumentResolver(documentPath, codeDocument);
var codeActionEndpoint = new CodeActionEndpoint(
DocumentMappingService,
_documentMappingService,
new RazorCodeActionProvider[] {
new MockRazorCodeActionProvider(),
new MockRazorCommandProvider(),
@ -411,8 +411,8 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
Array.Empty<CSharpCodeActionProvider>(),
Dispatcher,
documentResolver,
LanguageServer,
LanguageServerFeatureOptions)
_languageServer,
_languageServerFeatureOptions)
{
_supportsCodeActionResolve = true
};
@ -449,7 +449,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
var codeDocument = CreateCodeDocument("@code {}");
var documentResolver = CreateDocumentResolver(documentPath, codeDocument);
var codeActionEndpoint = new CodeActionEndpoint(
DocumentMappingService,
_documentMappingService,
new RazorCodeActionProvider[] {
new MockRazorCodeActionProvider(),
new MockRazorCommandProvider(),
@ -458,8 +458,8 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
Array.Empty<CSharpCodeActionProvider>(),
Dispatcher,
documentResolver,
LanguageServer,
LanguageServerFeatureOptions)
_languageServer,
_languageServerFeatureOptions)
{
_supportsCodeActionResolve = false
};
@ -494,15 +494,15 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
var codeDocument = CreateCodeDocument("@code {}");
var documentResolver = CreateDocumentResolver(documentPath, codeDocument);
var codeActionEndpoint = new CodeActionEndpoint(
DocumentMappingService,
_documentMappingService,
new RazorCodeActionProvider[] {
new MockRazorCodeActionProvider()
},
Array.Empty<CSharpCodeActionProvider>(),
Dispatcher,
documentResolver,
LanguageServer,
LanguageServerFeatureOptions)
_languageServer,
_languageServerFeatureOptions)
{
_supportsCodeActionResolve = false
};
@ -535,15 +535,15 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
var codeDocument = CreateCodeDocument("@code {}");
var documentResolver = CreateDocumentResolver(documentPath, codeDocument);
var codeActionEndpoint = new CodeActionEndpoint(
DocumentMappingService,
_documentMappingService,
new RazorCodeActionProvider[] {
new MockRazorCodeActionProvider()
},
Array.Empty<CSharpCodeActionProvider>(),
Dispatcher,
documentResolver,
LanguageServer,
LanguageServerFeatureOptions)
_languageServer,
_languageServerFeatureOptions)
{
_supportsCodeActionResolve = false
};
@ -586,8 +586,8 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
},
Dispatcher,
documentResolver,
LanguageServer,
LanguageServerFeatureOptions)
_languageServer,
_languageServerFeatureOptions)
{
_supportsCodeActionResolve = false
};
@ -629,7 +629,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
Dispatcher,
documentResolver,
languageServer,
LanguageServerFeatureOptions)
_languageServerFeatureOptions)
{
_supportsCodeActionResolve = false
};

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

@ -20,13 +20,13 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
{
public class CreateComponentCodeActionResolverTest : LanguageServerTestBase
{
private readonly DocumentResolver EmptyDocumentResolver = Mock.Of<DocumentResolver>(r => r.TryResolveDocument(It.IsAny<string>(), out It.Ref<DocumentSnapshot>.IsAny) == false, MockBehavior.Strict);
private readonly DocumentResolver _emptyDocumentResolver = Mock.Of<DocumentResolver>(r => r.TryResolveDocument(It.IsAny<string>(), out It.Ref<DocumentSnapshot>.IsAny) == false, MockBehavior.Strict);
[Fact]
public async Task Handle_MissingFile()
{
// Arrange
var resolver = new CreateComponentCodeActionResolver(new DefaultForegroundDispatcher(), EmptyDocumentResolver);
var resolver = new CreateComponentCodeActionResolver(new DefaultForegroundDispatcher(), _emptyDocumentResolver);
var data = JObject.FromObject(new CreateComponentCodeActionParams()
{
Uri = new Uri("c:/Test.razor"),

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

@ -21,19 +21,19 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions
{
public class ExtractToCodeBehindCodeActionResolverTest : LanguageServerTestBase
{
private readonly DocumentResolver EmptyDocumentResolver;
private readonly DocumentResolver _emptyDocumentResolver;
public ExtractToCodeBehindCodeActionResolverTest()
{
EmptyDocumentResolver = new Mock<DocumentResolver>(MockBehavior.Strict).Object;
Mock.Get(EmptyDocumentResolver).Setup(r => r.TryResolveDocument(It.IsAny<string>(), out It.Ref<DocumentSnapshot>.IsAny)).Returns(false);
_emptyDocumentResolver = new Mock<DocumentResolver>(MockBehavior.Strict).Object;
Mock.Get(_emptyDocumentResolver).Setup(r => r.TryResolveDocument(It.IsAny<string>(), out It.Ref<DocumentSnapshot>.IsAny)).Returns(false);
}
[Fact]
public async Task Handle_MissingFile()
{
// Arrange
var resolver = new ExtractToCodeBehindCodeActionResolver(new DefaultForegroundDispatcher(), EmptyDocumentResolver, FilePathNormalizer);
var resolver = new ExtractToCodeBehindCodeActionResolver(new DefaultForegroundDispatcher(), _emptyDocumentResolver, FilePathNormalizer);
var data = JObject.FromObject(new ExtractToCodeBehindCodeActionParams()
{
Uri = new Uri("c:/Test.razor"),

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

@ -25,7 +25,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
{
public class RazorCompletionEndpointTest : LanguageServerTestBase
{
private readonly IReadOnlyList<ExtendedCompletionItemKinds> SupportedCompletionItemKinds = new[]
private readonly IReadOnlyList<ExtendedCompletionItemKinds> _supportedCompletionItemKinds = new[]
{
ExtendedCompletionItemKinds.Struct,
ExtendedCompletionItemKinds.Keyword,
@ -115,7 +115,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
completionItem.SetDirectiveCompletionDescription(new DirectiveCompletionDescription(description));
// Act
var result = RazorCompletionEndpoint.TryConvert(completionItem, SupportedCompletionItemKinds, out var converted);
var result = RazorCompletionEndpoint.TryConvert(completionItem, _supportedCompletionItemKinds, out var converted);
// Assert
Assert.True(result);
@ -134,7 +134,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
var completionItem = new RazorCompletionItem("testDisplay", "testInsert", RazorCompletionItemKind.Directive);
var description = "Something";
completionItem.SetDirectiveCompletionDescription(new DirectiveCompletionDescription(description));
RazorCompletionEndpoint.TryConvert(completionItem, SupportedCompletionItemKinds, out var converted);
RazorCompletionEndpoint.TryConvert(completionItem, _supportedCompletionItemKinds, out var converted);
// Act & Assert
JsonConvert.SerializeObject(converted);
@ -145,7 +145,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
{
// Arrange
var completionItem = DirectiveAttributeTransitionCompletionItemProvider.TransitionCompletionItem;
RazorCompletionEndpoint.TryConvert(completionItem, SupportedCompletionItemKinds, out var converted);
RazorCompletionEndpoint.TryConvert(completionItem, _supportedCompletionItemKinds, out var converted);
// Act & Assert
JsonConvert.SerializeObject(converted);
@ -158,7 +158,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
var completionItem = DirectiveAttributeTransitionCompletionItemProvider.TransitionCompletionItem;
// Act
var result = RazorCompletionEndpoint.TryConvert(completionItem, SupportedCompletionItemKinds, out var converted);
var result = RazorCompletionEndpoint.TryConvert(completionItem, _supportedCompletionItemKinds, out var converted);
// Assert
Assert.True(result);
@ -179,7 +179,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
var completionItem = MarkupTransitionCompletionItemProvider.MarkupTransitionCompletionItem;
// Act
var result = RazorCompletionEndpoint.TryConvert(completionItem, SupportedCompletionItemKinds, out var converted);
var result = RazorCompletionEndpoint.TryConvert(completionItem, _supportedCompletionItemKinds, out var converted);
// Assert
Assert.True(result);
@ -197,7 +197,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
{
// Arrange
var completionItem = MarkupTransitionCompletionItemProvider.MarkupTransitionCompletionItem;
RazorCompletionEndpoint.TryConvert(completionItem, SupportedCompletionItemKinds, out var converted);
RazorCompletionEndpoint.TryConvert(completionItem, _supportedCompletionItemKinds, out var converted);
// Act & Assert
JsonConvert.SerializeObject(converted);
@ -210,7 +210,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
var completionItem = new RazorCompletionItem("@testDisplay", "testInsert", RazorCompletionItemKind.DirectiveAttribute, new[] { "=", ":" });
// Act
var result = RazorCompletionEndpoint.TryConvert(completionItem, SupportedCompletionItemKinds, out var converted);
var result = RazorCompletionEndpoint.TryConvert(completionItem, _supportedCompletionItemKinds, out var converted);
// Assert
Assert.True(result);
@ -231,7 +231,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
var completionItem = new RazorCompletionItem("format", "format", RazorCompletionItemKind.DirectiveAttributeParameter);
// Act
var result = RazorCompletionEndpoint.TryConvert(completionItem, SupportedCompletionItemKinds, out var converted);
var result = RazorCompletionEndpoint.TryConvert(completionItem, _supportedCompletionItemKinds, out var converted);
// Assert
Assert.True(result);
@ -251,7 +251,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
var completionItem = new RazorCompletionItem("format", "format", RazorCompletionItemKind.TagHelperElement);
// Act
var result = RazorCompletionEndpoint.TryConvert(completionItem, SupportedCompletionItemKinds, out var converted);
var result = RazorCompletionEndpoint.TryConvert(completionItem, _supportedCompletionItemKinds, out var converted);
// Assert
Assert.True(result);
@ -271,7 +271,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion
var completionItem = new RazorCompletionItem("format", "format", RazorCompletionItemKind.TagHelperAttribute);
// Act
var result = RazorCompletionEndpoint.TryConvert(completionItem, SupportedCompletionItemKinds, out var converted);
var result = RazorCompletionEndpoint.TryConvert(completionItem, _supportedCompletionItemKinds, out var converted);
// Assert
Assert.True(result);

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

@ -182,7 +182,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
documentVersionCache.TrackDocumentVersion(document, 1337);
// Assert
var kvp = Assert.Single(documentVersionCache._documentLookup);
var kvp = Assert.Single(documentVersionCache.DocumentLookup);
Assert.Equal(document.FilePath, kvp.Key);
var entry = Assert.Single(kvp.Value);
Assert.True(entry.Document.TryGetTarget(out var actualDocument));
@ -206,7 +206,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
documentVersionCache.TrackDocumentVersion(document, 1337);
// Assert
var kvp = Assert.Single(documentVersionCache._documentLookup);
var kvp = Assert.Single(documentVersionCache.DocumentLookup);
Assert.Equal(DefaultDocumentVersionCache.MaxDocumentTrackingCount, kvp.Value.Count);
Assert.Equal(1337, kvp.Value.Last().Version);
}

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

@ -39,7 +39,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
DefaultProjectResolver projectResolver = null;
var miscProject = new Mock<ProjectSnapshot>(MockBehavior.Strict);
miscProject.Setup(p => p.FilePath)
.Returns(() => projectResolver._miscellaneousHostProject.FilePath);
.Returns(() => projectResolver.MiscellaneousHostProject.FilePath);
miscProject.Setup(p => p.GetDocument(documentFilePath))
.Returns((DocumentSnapshot)null);
projectResolver = CreateProjectResolver(() => new[] { miscProject.Object });
@ -60,7 +60,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
DefaultProjectResolver projectResolver = null;
var miscProject = new Mock<ProjectSnapshot>(MockBehavior.Strict);
miscProject.Setup(p => p.FilePath)
.Returns(() => projectResolver._miscellaneousHostProject.FilePath);
.Returns(() => projectResolver.MiscellaneousHostProject.FilePath);
miscProject.Setup(p => p.GetDocument(documentFilePath)).Returns(Mock.Of<DocumentSnapshot>(MockBehavior.Strict));
projectResolver = CreateProjectResolver(() => new[] { miscProject.Object });
@ -116,7 +116,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
DefaultProjectResolver projectResolver = null;
var miscProject = new Mock<ProjectSnapshot>(MockBehavior.Strict);
miscProject.Setup(p => p.FilePath)
.Returns(() => projectResolver._miscellaneousHostProject.FilePath);
.Returns(() => projectResolver.MiscellaneousHostProject.FilePath);
miscProject.Setup(p => p.GetDocument(documentFilePath)).Returns(Mock.Of<DocumentSnapshot>(MockBehavior.Strict));
var ownerProject = Mock.Of<ProjectSnapshot>(
p => p.FilePath == "C:/path/to/project.csproj" &&
@ -140,7 +140,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
DefaultProjectResolver projectResolver = null;
var miscProject = new Mock<ProjectSnapshot>(MockBehavior.Strict);
miscProject.Setup(p => p.FilePath)
.Returns(() => projectResolver._miscellaneousHostProject.FilePath);
.Returns(() => projectResolver.MiscellaneousHostProject.FilePath);
miscProject.Setup(p => p.GetDocument(documentFilePath)).Returns(Mock.Of<DocumentSnapshot>(MockBehavior.Strict));
var ownerProject = Mock.Of<ProjectSnapshot>(
p => p.FilePath == "C:/path/to/project.csproj" &&
@ -182,7 +182,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
DefaultProjectResolver projectResolver = null;
var miscProject = new Mock<ProjectSnapshot>(MockBehavior.Strict);
miscProject.Setup(p => p.FilePath)
.Returns(() => projectResolver._miscellaneousHostProject.FilePath);
.Returns(() => projectResolver.MiscellaneousHostProject.FilePath);
var expectedProject = miscProject.Object;
projectResolver = CreateProjectResolver(() => new[] { expectedProject });
@ -215,7 +215,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer
// Assert
Assert.Single(projects);
Assert.Equal(projectResolver._miscellaneousHostProject.FilePath, project.FilePath);
Assert.Equal(projectResolver.MiscellaneousHostProject.FilePath, project.FilePath);
}
private DefaultProjectResolver CreateProjectResolver(Func<ProjectSnapshot[]> projectFactory)

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

@ -17,7 +17,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Test
{
public class DefaultRazorComponentSearchEngineTest : LanguageServerTestBase
{
private static readonly ProjectSnapshotManagerAccessor _projectSnapshotManager = CreateProjectSnapshotManagerAccessor();
private static readonly ProjectSnapshotManagerAccessor s_projectSnapshotManager = CreateProjectSnapshotManagerAccessor();
[Fact]
public async Task Handle_SearchFound_GenericComponent()
@ -25,7 +25,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Test
// Arrange
var tagHelperDescriptor1 = CreateRazorComponentTagHelperDescriptor("First", "First.Components", "Component1", typeName: "Component1<TItem>");
var tagHelperDescriptor2 = CreateRazorComponentTagHelperDescriptor("Second", "Second.Components", "Component3", typeName: "Component3<TItem>");
var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, _projectSnapshotManager);
var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, s_projectSnapshotManager);
// Act
var documentSnapshot1 = await searchEngine.TryLocateComponentAsync(tagHelperDescriptor1).ConfigureAwait(false);
@ -42,7 +42,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Test
// Arrange
var tagHelperDescriptor1 = CreateRazorComponentTagHelperDescriptor("First", "First.Components", "Component1");
var tagHelperDescriptor2 = CreateRazorComponentTagHelperDescriptor("Second", "Second.Components", "Component3");
var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, _projectSnapshotManager);
var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, s_projectSnapshotManager);
// Act
var documentSnapshot1 = await searchEngine.TryLocateComponentAsync(tagHelperDescriptor1).ConfigureAwait(false);
@ -58,7 +58,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Test
{
// Arrange
var tagHelperDescriptor = CreateRazorComponentTagHelperDescriptor("First", "Test", "Component2");
var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, _projectSnapshotManager);
var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, s_projectSnapshotManager);
// Act
var documentSnapshot = await searchEngine.TryLocateComponentAsync(tagHelperDescriptor).ConfigureAwait(false);
@ -72,7 +72,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Test
{
// Arrange
var tagHelperDescriptor = CreateRazorComponentTagHelperDescriptor("Third", "First.Components", "Component3");
var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, _projectSnapshotManager);
var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, s_projectSnapshotManager);
// Act
var documentSnapshot = await searchEngine.TryLocateComponentAsync(tagHelperDescriptor).ConfigureAwait(false);
@ -86,7 +86,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Test
{
// Arrange
var tagHelperDescriptor = CreateRazorComponentTagHelperDescriptor("First", "First.Components", "Component2");
var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, _projectSnapshotManager);
var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, s_projectSnapshotManager);
// Act
var documentSnapshot = await searchEngine.TryLocateComponentAsync(tagHelperDescriptor).ConfigureAwait(false);
@ -100,7 +100,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Test
{
// Arrange
var tagHelperDescriptor = CreateRazorComponentTagHelperDescriptor("First", "First.Components", "Component3");
var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, _projectSnapshotManager);
var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, s_projectSnapshotManager);
// Act
var documentSnapshot = await searchEngine.TryLocateComponentAsync(tagHelperDescriptor).ConfigureAwait(false);
@ -114,7 +114,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Test
{
// Arrange
var tagHelperDescriptor = CreateRazorComponentTagHelperDescriptor("AssemblyName", "Test", "Component2");
var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, _projectSnapshotManager);
var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, s_projectSnapshotManager);
// Act
var documentSnapshot = await searchEngine.TryLocateComponentAsync(tagHelperDescriptor).ConfigureAwait(false);

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

@ -155,9 +155,11 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Formatting
private struct HtmlFormatterTextEdit
{
#pragma warning disable CS0649 // Field 'name' is never assigned to, and will always have its default value
#pragma warning disable IDE1006 // Naming Styles - This type is deserialized above so these need to be cased like this
public int Position;
public int Length;
public string NewText;
#pragma warning restore IDE1006 // Naming Styles
#pragma warning restore CS0649 // Field 'name' is never assigned to, and will always have its default value
public TextEdit AsTextEdit(SourceText sourceText)

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

@ -35,8 +35,8 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Formatting
[Collection("FormattingTestSerialRuns")]
public class FormattingTestBase : RazorIntegrationTestBase
{
private static readonly AsyncLocal<string> _fileName = new AsyncLocal<string>();
private static readonly IReadOnlyList<TagHelperDescriptor> _defaultComponents = GetDefaultRuntimeComponents();
private static readonly AsyncLocal<string> s_fileName = new AsyncLocal<string>();
private static readonly IReadOnlyList<TagHelperDescriptor> s_defaultComponents = GetDefaultRuntimeComponents();
public FormattingTestBase()
{
@ -54,8 +54,8 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Formatting
// Used by the test framework to set the 'base' name for test files.
public static string FileName
{
get { return _fileName.Value; }
set { _fileName.Value = value; }
get { return s_fileName.Value; }
set { s_fileName.Value = value; }
}
protected async Task RunFormattingTestAsync(
@ -189,12 +189,12 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Formatting
tagHelpers ??= Array.Empty<TagHelperDescriptor>();
if (fileKind == FileKinds.Component)
{
tagHelpers = tagHelpers.Concat(_defaultComponents).ToArray();
tagHelpers = tagHelpers.Concat(s_defaultComponents).ToArray();
}
var sourceDocument = text.GetRazorSourceDocument(path, path);
// Yes I know "BlazorServer_31 is weird, but thats what is in the taghelpers.json file
const string defaultImports = @"
const string DefaultImports = @"
@using BlazorServer_31
@using BlazorServer_31.Pages
@using BlazorServer_31.Shared
@ -205,7 +205,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Formatting
";
var importsPath = new Uri("file:///path/to/_Imports.razor").AbsolutePath;
var importsSourceText = SourceText.From(defaultImports);
var importsSourceText = SourceText.From(DefaultImports);
var importsDocument = importsSourceText.GetRazorSourceDocument(importsPath, importsPath);
var importsSnapshot = new Mock<DocumentSnapshot>(MockBehavior.Strict);
importsSnapshot.Setup(d => d.GetTextAsync()).Returns(Task.FromResult(importsSourceText));

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше