提交 3df5f06b 编写于 作者: C CyrusNajmabadi

Inline variables

上级 dde706cb
......@@ -519,9 +519,7 @@ public static int Count<T>(this ImmutableArray<T> items, Func<T, bool> predicate
{
var item = items[i];
var key = keySelector(item);
ArrayBuilder<T> bucket;
if (!accumulator.TryGetValue(key, out bucket))
if (!accumulator.TryGetValue(key, out var bucket))
{
bucket = ArrayBuilder<T>.GetInstance();
accumulator.Add(key, bucket);
......
......@@ -88,8 +88,7 @@ private void EnsureDictionary()
/// </summary>
public void Add(K k, V v)
{
ValueSet valueSet;
if (!this.IsEmpty && _dictionary.TryGetValue(k, out valueSet))
if (!this.IsEmpty && _dictionary.TryGetValue(k, out var valueSet))
{
Debug.Assert(valueSet.Count >= 1);
// Have to re-store the ValueSet in case we upgraded the existing ValueSet from
......@@ -126,8 +125,7 @@ IEnumerator IEnumerable.GetEnumerator()
{
get
{
ValueSet valueSet;
if (!this.IsEmpty && _dictionary.TryGetValue(k, out valueSet))
if (!this.IsEmpty && _dictionary.TryGetValue(k, out var valueSet))
{
Debug.Assert(valueSet.Count >= 1);
return valueSet.Items;
......@@ -139,9 +137,8 @@ IEnumerator IEnumerable.GetEnumerator()
public bool Contains(K key, V value)
{
ValueSet valueSet;
return !this.IsEmpty &&
_dictionary.TryGetValue(key, out valueSet) &&
_dictionary.TryGetValue(key, out var valueSet) &&
valueSet.Contains(value);
}
......
......@@ -32,8 +32,7 @@ public void AddDependencyLocation(string fullPath)
lock (_guard)
{
List<string> paths;
if (!_knownAssemblyPathsBySimpleName.TryGetValue(simpleName, out paths))
if (!_knownAssemblyPathsBySimpleName.TryGetValue(simpleName, out var paths))
{
_knownAssemblyPathsBySimpleName.Add(simpleName, new List<string>() { fullPath });
}
......@@ -65,8 +64,7 @@ private Assembly LoadFromPathUncheckedCore(string fullPath, AssemblyIdentity ide
Assembly loadedAssembly = null;
lock (_guard)
{
Assembly existingAssembly;
if (_loadedAssembliesByPath.TryGetValue(fullPath, out existingAssembly))
if (_loadedAssembliesByPath.TryGetValue(fullPath, out var existingAssembly))
{
loadedAssembly = existingAssembly;
}
......@@ -102,8 +100,7 @@ private Assembly AddToCache(Assembly assembly, string fullPath, AssemblyIdentity
{
// The same assembly may be loaded from two different full paths (e.g. when loaded from GAC, etc.),
// or another thread might have loaded the assembly after we checked above.
Assembly existingAssembly;
if (_loadedAssembliesByIdentity.TryGetValue(identity, out existingAssembly))
if (_loadedAssembliesByIdentity.TryGetValue(identity, out var existingAssembly))
{
assembly = existingAssembly;
}
......@@ -126,8 +123,7 @@ private AssemblyIdentity GetOrAddAssemblyIdentity(string fullPath)
lock (_guard)
{
AssemblyIdentity existingIdentity;
if (_loadedAssemblyIdentitiesByPath.TryGetValue(fullPath, out existingIdentity))
if (_loadedAssemblyIdentitiesByPath.TryGetValue(fullPath, out var existingIdentity))
{
return existingIdentity;
}
......@@ -141,8 +137,7 @@ private AssemblyIdentity AddToCache(string fullPath, AssemblyIdentity identity)
{
lock (_guard)
{
AssemblyIdentity existingIdentity;
if (_loadedAssemblyIdentitiesByPath.TryGetValue(fullPath, out existingIdentity) && existingIdentity != null)
if (_loadedAssemblyIdentitiesByPath.TryGetValue(fullPath, out var existingIdentity) && existingIdentity != null)
{
identity = existingIdentity;
}
......@@ -157,8 +152,7 @@ private AssemblyIdentity AddToCache(string fullPath, AssemblyIdentity identity)
public Assembly Load(string displayName)
{
AssemblyIdentity requestedIdentity;
if (!AssemblyIdentity.TryParseDisplayName(displayName, out requestedIdentity))
if (!AssemblyIdentity.TryParseDisplayName(displayName, out var requestedIdentity))
{
return null;
}
......@@ -166,17 +160,14 @@ public Assembly Load(string displayName)
ImmutableArray<string> candidatePaths;
lock (_guard)
{
Assembly existingAssembly;
// First, check if this loader already loaded the requested assembly:
if (_loadedAssembliesByIdentity.TryGetValue(requestedIdentity, out existingAssembly))
if (_loadedAssembliesByIdentity.TryGetValue(requestedIdentity, out var existingAssembly))
{
return existingAssembly;
}
// Second, check if an assembly file of the same simple name was registered with the loader:
List<string> pathList;
if (!_knownAssemblyPathsBySimpleName.TryGetValue(requestedIdentity.Name, out pathList))
if (!_knownAssemblyPathsBySimpleName.TryGetValue(requestedIdentity.Name, out var pathList))
{
return null;
}
......
......@@ -106,8 +106,7 @@ public void AddRange(IEnumerable<T> values)
/// <returns>true if the value was removed successfully; otherwise false.</returns>
public bool Remove(T value)
{
byte b;
return _dictionary.TryRemove(value, out b);
return _dictionary.TryRemove(value, out var b);
}
/// <summary>
......
......@@ -186,8 +186,7 @@ public IEnumerable<K> Keys
{
get
{
ValueSet set;
return _dictionary.TryGetValue(k, out set) ? set : default(ValueSet);
return _dictionary.TryGetValue(k, out var set) ? set : default(ValueSet);
}
}
......@@ -208,8 +207,7 @@ public MultiDictionary(int capacity, IEqualityComparer<K> comparer)
public void Add(K k, V v)
{
ValueSet set;
_dictionary[k] = _dictionary.TryGetValue(k, out set) ? set.Add(v) : new ValueSet(v);
_dictionary[k] = _dictionary.TryGetValue(k, out var set) ? set.Add(v) : new ValueSet(v);
}
IEnumerator IEnumerable.GetEnumerator()
......
......@@ -142,8 +142,7 @@ internal static bool IsValidClrNamespaceName(this string name)
this string name,
bool isCaseSensitive)
{
string result;
return TryGetWithoutAttributeSuffix(name, isCaseSensitive, out result) ? result : null;
return TryGetWithoutAttributeSuffix(name, isCaseSensitive, out var result) ? result : null;
}
internal static bool TryGetWithoutAttributeSuffix(
......@@ -198,8 +197,7 @@ internal static bool IsValidUnicodeString(this string str)
/// </summary>
internal static string Unquote(this string arg)
{
bool quoted;
return Unquote(arg, out quoted);
return Unquote(arg, out var quoted);
}
internal static string Unquote(this string arg, out bool quoted)
......
......@@ -9,15 +9,13 @@ internal static class WeakReferenceExtensions
{
public static T GetTarget<T>(this WeakReference<T> reference) where T : class
{
T target;
reference.TryGetTarget(out target);
reference.TryGetTarget(out var target);
return target;
}
public static bool IsNull<T>(this WeakReference<T> reference) where T : class
{
T target;
return !reference.TryGetTarget(out target);
return !reference.TryGetTarget(out var target);
}
}
}
......@@ -22,15 +22,13 @@ public FixedObjectBinder(ImmutableDictionary<Type, Func<ObjectReader, object>> r
public override Type GetType(string assemblyName, string typeName)
{
Type type;
_typeMap.TryGetValue(new TypeKey(assemblyName, typeName), out type);
_typeMap.TryGetValue(new TypeKey(assemblyName, typeName), out var type);
return type;
}
public override Func<ObjectReader, object> GetReader(Type type)
{
Func<ObjectReader, object> reader;
_readerMap.TryGetValue(type, out reader);
_readerMap.TryGetValue(type, out var reader);
return reader;
}
}
......
......@@ -335,10 +335,8 @@ private Array ReadArray(DataKind kind)
}
var elementKind = (DataKind)_reader.ReadByte();
// optimization for primitive type array
Type elementType;
if (s_reverseTypeMap.TryGetValue(elementKind, out elementType))
if (s_reverseTypeMap.TryGetValue(elementKind, out var elementType))
{
return this.ReadPrimitiveTypeArrayElements(elementType, elementKind, length);
}
......
......@@ -214,8 +214,7 @@ public unsafe void WriteString(string value)
}
else
{
int id;
if (_dataMap.TryGetId(value, out id))
if (_dataMap.TryGetId(value, out var id))
{
Debug.Assert(id >= 0);
if (id <= byte.MaxValue)
......@@ -474,10 +473,8 @@ private void WriteArray(Array instance)
// get type of array
var elementType = instance.GetType().GetElementType();
// optimization for primitive type array
DataKind elementKind;
if (s_typeMap.TryGetValue(elementType, out elementKind))
if (s_typeMap.TryGetValue(elementType, out var elementKind))
{
this.WritePrimitiveType(elementType, elementKind);
this.WritePrimitiveTypeArrayElements(elementType, elementKind, instance);
......@@ -595,8 +592,7 @@ private void WritePrimitiveType(Type type, DataKind kind)
private void WriteType(Type type)
{
int id;
if (_dataMap.TryGetId(type, out id))
if (_dataMap.TryGetId(type, out var id))
{
Debug.Assert(id >= 0);
if (id <= byte.MaxValue)
......@@ -637,10 +633,8 @@ private void WriteType(Type type)
private void WriteObject(object instance)
{
_cancellationToken.ThrowIfCancellationRequested();
// write object ref if we already know this instance
int id;
if (_dataMap.TryGetId(instance, out id))
if (_dataMap.TryGetId(instance, out var id))
{
Debug.Assert(id >= 0);
if (id <= byte.MaxValue)
......
......@@ -20,8 +20,7 @@ internal sealed class SimpleRecordingObjectBinder : RecordingObjectBinder
public override Type GetType(string assemblyName, string typeName)
{
Type type;
if (!_typeMap.TryGetValue(new TypeKey(assemblyName, typeName), out type))
if (!_typeMap.TryGetValue(new TypeKey(assemblyName, typeName), out var type))
{
Debug.Assert(false, assemblyName + "/" + typeName + " don't exist");
}
......@@ -31,8 +30,7 @@ public override Type GetType(string assemblyName, string typeName)
public override Func<ObjectReader, object> GetReader(Type type)
{
Func<ObjectReader, object> reader;
if (!_readerMap.TryGetValue(type, out reader))
if (!_readerMap.TryGetValue(type, out var reader))
{
Debug.Assert(false, type.ToString() + " reader doesn't exist");
}
......
......@@ -402,9 +402,7 @@ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
var item = this[i];
var key = keySelector(item);
ArrayBuilder<T> bucket;
if (!accumulator.TryGetValue(key, out bucket))
if (!accumulator.TryGetValue(key, out var bucket))
{
bucket = ArrayBuilder<T>.GetInstance();
accumulator.Add(key, bucket);
......
......@@ -18,8 +18,7 @@ public string Name
public async Task<Document> CleanupAsync(Document document, IEnumerable<TextSpan> spans, CancellationToken cancellationToken)
{
// If the old text already exists, use the fast path for formatting.
SourceText oldText;
if (document.TryGetText(out oldText))
if (document.TryGetText(out var oldText))
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var textChanges = await Formatter.GetFormattedTextChangesAsync(root, spans, document.Project.Solution.Workspace, cancellationToken: cancellationToken).ConfigureAwait(false);
......@@ -38,8 +37,7 @@ public async Task<Document> CleanupAsync(Document document, IEnumerable<TextSpan
public async Task<SyntaxNode> CleanupAsync(SyntaxNode root, IEnumerable<TextSpan> spans, Workspace workspace, CancellationToken cancellationToken)
{
// If the old text already exists, use the fast path for formatting.
SourceText oldText;
if (root.SyntaxTree != null && root.SyntaxTree.TryGetText(out oldText))
if (root.SyntaxTree != null && root.SyntaxTree.TryGetText(out var oldText))
{
var changes = await Formatter.GetFormattedTextChangesAsync(root, spans, workspace, cancellationToken: cancellationToken).ConfigureAwait(false);
......
......@@ -238,9 +238,7 @@ public virtual string GetFixAllTitle(FixAllState fixAllState)
{
cancellationToken.ThrowIfCancellationRequested();
var document = changedSolution.GetDocument(documentId);
Document existingDocument;
if (changedDocumentsMap.TryGetValue(documentId, out existingDocument))
if (changedDocumentsMap.TryGetValue(documentId, out var existingDocument))
{
if (existingDocument != null)
{
......
......@@ -216,8 +216,7 @@ public void Append(HashSet<Checksum> searchingChecksumsLeft, Dictionary<Checksum
private void Append(HashSet<Checksum> searchingChecksumsLeft, Dictionary<Checksum, object> result)
{
// only solution with checksum can be in asset storage
SolutionStateChecksums stateChecksums;
Contract.ThrowIfFalse(_state.TryGetStateChecksums(out stateChecksums));
Contract.ThrowIfFalse(_state.TryGetStateChecksums(out var stateChecksums));
stateChecksums.Find(_state, searchingChecksumsLeft, result, _cancellationToken);
}
......
......@@ -17,8 +17,7 @@ internal static partial class Extensions
public static async Task<IEnumerable<SyntaxToken>> GetConstructorInitializerTokensAsync(this Document document, CancellationToken cancellationToken)
{
// model should exist already
SemanticModel model;
if (!document.TryGetSemanticModel(out model))
if (!document.TryGetSemanticModel(out var model))
{
return Contract.FailWithReturn<IEnumerable<SyntaxToken>>("we should never reach here");
}
......@@ -38,8 +37,7 @@ public static async Task<IEnumerable<SyntaxToken>> GetConstructorInitializerToke
this Document document, string identifier, CancellationToken cancellationToken)
{
// model should exist already
SemanticModel model;
if (!document.TryGetSemanticModel(out model))
if (!document.TryGetSemanticModel(out var model))
{
return Contract.FailWithReturn<ImmutableArray<SyntaxToken>>("we should never reach here");
}
......
......@@ -134,12 +134,11 @@ public static partial class SymbolFinder
// then we have a retargeting scenario and want to take our usual path below as if it was a metadata reference
foreach (var sourceProject in solution.Projects)
{
Compilation compilation;
// If our symbol is actually a "regular" source symbol, then we know the compilation is holding the symbol alive
// and thus TryGetCompilation is sufficient. For another example of this pattern, see Solution.GetProject(IAssemblySymbol)
// which we happen to call below.
if (sourceProject.TryGetCompilation(out compilation))
if (sourceProject.TryGetCompilation(out var compilation))
{
if (symbol.ContainingAssembly.Equals(compilation.Assembly))
{
......
......@@ -16,8 +16,7 @@ internal abstract partial class TreeData
public static TreeData Create(SyntaxNode root)
{
// either there is no tree or a tree that is not generated from a text.
var text = default(SourceText);
if (root.SyntaxTree == null || !root.SyntaxTree.TryGetText(out text))
if (root.SyntaxTree == null || !root.SyntaxTree.TryGetText(out var text))
{
return new Node(root);
}
......
......@@ -260,8 +260,7 @@ public PatternMatches GetMatches(string candidate, string dottedContainer)
return null;
}
ImmutableArray<PatternMatch> ignored;
return MatchSegment(candidate, inludeMatchSpans, _fullPatternSegment, wantAllMatches: false, allMatches: out ignored, fuzzyMatch: false) ??
return MatchSegment(candidate, inludeMatchSpans, _fullPatternSegment, wantAllMatches: false, allMatches: out var ignored, fuzzyMatch: false) ??
MatchSegment(candidate, inludeMatchSpans, _fullPatternSegment, wantAllMatches: false, allMatches: out ignored, fuzzyMatch: true);
}
......@@ -451,9 +450,8 @@ private static bool ContainsSpaceOrAsterisk(string text)
return ImmutableArray<PatternMatch>.Empty;
}
ImmutableArray<PatternMatch> matches;
var singleMatch = MatchSegment(candidate, includeMatchSpans, segment,
wantAllMatches: true, fuzzyMatch: fuzzyMatch, allMatches: out matches);
wantAllMatches: true, fuzzyMatch: fuzzyMatch, allMatches: out var matches);
if (singleMatch.HasValue)
{
return ImmutableArray.Create(singleMatch.Value);
......
......@@ -263,8 +263,7 @@ private static void AddConflictingSymbolLocations(IEnumerable<ISymbol> conflicti
{
if (newLocation.IsInSource)
{
Location oldLocation;
if (reverseMappedLocations.TryGetValue(newLocation, out oldLocation))
if (reverseMappedLocations.TryGetValue(newLocation, out var oldLocation))
{
conflictResolution.AddOrReplaceRelatedLocation(new RelatedLocation(oldLocation.SourceSpan, conflictResolution.OldSolution.GetDocument(oldLocation.SourceTree).Id, RelatedLocationType.UnresolvableConflict));
}
......
......@@ -30,9 +30,7 @@ public static IEnumerable<Location> GetMembersWithConflictingSignatures(IMethodS
foreach (var signature in GetAllSignatures(renamedMethod, trimOptionalParameters))
{
IMethodSymbol conflictingSymbol;
if (signatureToConflictingMember.TryGetValue(signature, out conflictingSymbol))
if (signatureToConflictingMember.TryGetValue(signature, out var conflictingSymbol))
{
if (!(conflictingSymbol.PartialDefinitionPart != null && conflictingSymbol.PartialDefinitionPart == renamedMethod) &&
!(conflictingSymbol.PartialImplementationPart != null && conflictingSymbol.PartialImplementationPart == renamedMethod))
......
......@@ -33,8 +33,7 @@ internal bool IsDocumentChanged(DocumentId documentId)
internal void AddModifiedSpan(DocumentId documentId, TextSpan oldSpan, TextSpan newSpan)
{
List<(TextSpan oldSpan, TextSpan newSpan)> spans;
if (!_documentToModifiedSpansMap.TryGetValue(documentId, out spans))
if (!_documentToModifiedSpansMap.TryGetValue(documentId, out var spans))
{
spans = new List<(TextSpan oldSpan, TextSpan newSpan)>();
_documentToModifiedSpansMap[documentId] = spans;
......@@ -45,8 +44,7 @@ internal void AddModifiedSpan(DocumentId documentId, TextSpan oldSpan, TextSpan
internal void AddComplexifiedSpan(DocumentId documentId, TextSpan oldSpan, TextSpan newSpan, List<(TextSpan oldSpan, TextSpan newSpan)> modifiedSubSpans)
{
List<ComplexifiedSpan> spans;
if (!_documentToComplexifiedSpansMap.TryGetValue(documentId, out spans))
if (!_documentToComplexifiedSpansMap.TryGetValue(documentId, out var spans))
{
spans = new List<ComplexifiedSpan>();
_documentToComplexifiedSpansMap[documentId] = spans;
......@@ -57,8 +55,7 @@ internal void AddComplexifiedSpan(DocumentId documentId, TextSpan oldSpan, TextS
internal TextSpan GetAdjustedComplexifiedSpan(TextSpan originalComplexifiedSpan, DocumentId documentId)
{
List<ComplexifiedSpan> complexifiedSpans;
if (!_documentToComplexifiedSpansMap.TryGetValue(documentId, out complexifiedSpans))
if (!_documentToComplexifiedSpansMap.TryGetValue(documentId, out var complexifiedSpans))
{
throw new ArgumentException("documentId");
}
......
......@@ -178,9 +178,7 @@ public static Task<SyntaxTreeIndex> GetSyntaxTreeIndexAsync(this Document docume
/// </summary>
public static async Task<SemanticModel> GetPartialSemanticModelAsync(this Document document, CancellationToken cancellationToken)
{
Compilation compilation;
if (document.Project.TryGetCompilation(out compilation))
if (document.Project.TryGetCompilation(out var compilation))
{
// We already have a compilation, so at this point it's fastest to just get a SemanticModel
return await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
......
......@@ -26,8 +26,7 @@ public bool HasValue
{
get
{
T tmp;
return this.TryGetValue(out tmp);
return this.TryGetValue(out var tmp);
}
}
......
......@@ -60,9 +60,7 @@ public T First
public bool Enqueue(T value)
{
var result = true;
LinkedListNode<T> node;
if (_map.TryGetValue(value, out node))
if (_map.TryGetValue(value, out var node))
{
// Already had this in the list. Return 'false'.
result = false;
......@@ -92,14 +90,12 @@ public T Dequeue()
public bool Contains(T value)
{
LinkedListNode<T> node;
return _map.TryGetValue(value, out node);
return _map.TryGetValue(value, out var node);
}
public void Remove(T value)
{
LinkedListNode<T> node;
_map.TryGetValue(value, out node);
_map.TryGetValue(value, out var node);
if (_map.Remove(value))
{
_list.Remove(node);
......
......@@ -90,8 +90,7 @@ protected override string GetDocumentationForSymbol(string documentationMemberID
}
}
string docComment;
return _docComments.TryGetValue(documentationMemberID, out docComment) ? docComment : "";
return _docComments.TryGetValue(documentationMemberID, out var docComment) ? docComment : "";
}
private static readonly XmlReaderSettings s_xmlSettings = new XmlReaderSettings()
......
......@@ -127,8 +127,7 @@ public static bool AreSimilar(string originalText, string candidateText)
public static bool AreSimilar(string originalText, string candidateText, bool substringsAreSimilar)
{
double unused;
return AreSimilar(originalText, candidateText, substringsAreSimilar, out unused);
return AreSimilar(originalText, candidateText, substringsAreSimilar, out var unused);
}
public static bool AreSimilar(string originalText, string candidateText, out double similarityWeight)
......@@ -158,8 +157,7 @@ internal static int GetThreshold(string value)
public bool AreSimilar(string candidateText)
{
double similarityWeight;
return AreSimilar(candidateText, out similarityWeight);
return AreSimilar(candidateText, out var similarityWeight);
}
public bool AreSimilar(string candidateText, out double similarityWeight)
......
......@@ -138,8 +138,7 @@ public bool TryResolve<TNode>(SyntaxTree syntaxTree, CancellationToken cancellat
public bool TryResolve<TNode>(SyntaxNode root, out TNode node)
where TNode : SyntaxNode
{
SyntaxNodeOrToken nodeOrToken;
if (TryResolve(root, out nodeOrToken) &&
if (TryResolve(root, out var nodeOrToken) &&
nodeOrToken.IsNode &&
nodeOrToken.AsNode() is TNode)
{
......
......@@ -36,8 +36,7 @@ public override bool TryGetValue(out T value)
public override T GetValue(CancellationToken cancellationToken = default(CancellationToken))
{
T value;
if (!_reference.TryGetTarget(out value))
if (!_reference.TryGetTarget(out var value))
{
using (Gate.DisposableWait(cancellationToken))
{
......@@ -54,8 +53,7 @@ public override T GetValue(CancellationToken cancellationToken = default(Cancell
public override async Task<T> GetValueAsync(CancellationToken cancellationToken = default(CancellationToken))
{
T value;
if (!_reference.TryGetTarget(out value))
if (!_reference.TryGetTarget(out var value))
{
using (await Gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
{
......
......@@ -71,9 +71,7 @@ public override bool TryGetValue(out T value)
public override T GetValue(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
T instance;
if (!_weakInstance.TryGetTarget(out instance))
if (!_weakInstance.TryGetTarget(out var instance))
{
Task saveTask = null;
using (this.Gate.DisposableWait(cancellationToken))
......@@ -93,8 +91,7 @@ public override T GetValue(CancellationToken cancellationToken)
public override async Task<T> GetValueAsync(CancellationToken cancellationToken)
{
T instance;
if (!_weakInstance.TryGetTarget(out instance))
if (!_weakInstance.TryGetTarget(out var instance))
{
Task saveTask = null;
using (await this.Gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
......
......@@ -18,8 +18,7 @@ public bool HasValue
{
get
{
T tmp;
return this.TryGetValue(out tmp);
return this.TryGetValue(out var tmp);
}
}
......
......@@ -22,8 +22,7 @@ public override T GetValue(CancellationToken cancellationToken)
{
if (_weakValue != null)
{
T value;
if (_weakValue.TryGetTarget(out value))
if (_weakValue.TryGetTarget(out var value))
{
return value;
}
......
......@@ -19,8 +19,7 @@ public static EventHandler<TArgs> Create<TTarget>(TTarget target, Action<TTarget
return (sender, args) =>
{
TTarget targ;
if (weakTarget.TryGetTarget(out targ))
if (weakTarget.TryGetTarget(out var targ))
{
invoker(targ, sender, args);
}
......
......@@ -48,8 +48,7 @@ public bool HasServices
public override TLanguageService GetService<TLanguageService>()
{
Lazy<ILanguageService, LanguageServiceMetadata> service;
if (TryGetService(typeof(TLanguageService), out service))
if (TryGetService(typeof(TLanguageService), out var service))
{
return (TLanguageService)service.Value;
}
......@@ -76,10 +75,9 @@ internal bool TryGetService(Type serviceType, out Lazy<ILanguageService, Languag
private Lazy<ILanguageService, LanguageServiceMetadata> PickLanguageService(IEnumerable<Lazy<ILanguageService, LanguageServiceMetadata>> services)
{
Lazy<ILanguageService, LanguageServiceMetadata> service;
// workspace specific kind is best
if (TryGetServiceByLayer(_workspaceServices.Workspace.Kind, services, out service))
if (TryGetServiceByLayer(_workspaceServices.Workspace.Kind, services, out var service))
{
return service;
}
......
......@@ -50,8 +50,7 @@ public override Workspace Workspace
public override TWorkspaceService GetService<TWorkspaceService>()
{
Lazy<IWorkspaceService, WorkspaceServiceMetadata> service;
if (TryGetService(typeof(TWorkspaceService), out service))
if (TryGetService(typeof(TWorkspaceService), out var service))
{
return (TWorkspaceService)service.Value;
}
......@@ -79,10 +78,9 @@ private bool TryGetService(Type serviceType, out Lazy<IWorkspaceService, Workspa
private Lazy<IWorkspaceService, WorkspaceServiceMetadata> PickWorkspaceService(IEnumerable<Lazy<IWorkspaceService, WorkspaceServiceMetadata>> services)
{
Lazy<IWorkspaceService, WorkspaceServiceMetadata> service;
// workspace specific kind is best
if (TryGetServiceByLayer(_workspace.Kind, services, out service))
if (TryGetServiceByLayer(_workspace.Kind, services, out var service))
{
return service;
}
......@@ -151,9 +149,7 @@ public override bool IsSupported(string languageName)
public override HostLanguageServices GetLanguageServices(string languageName)
{
var currentServicesMap = _languageServicesMap;
MefLanguageServices languageServices;
if (!currentServicesMap.TryGetValue(languageName, out languageServices))
if (!currentServicesMap.TryGetValue(languageName, out var languageServices))
{
languageServices = ImmutableInterlocked.GetOrAdd(ref _languageServicesMap, languageName, _ => new MefLanguageServices(this, languageName));
}
......@@ -174,9 +170,7 @@ public override IEnumerable<TLanguageService> FindLanguageServices<TLanguageServ
foreach (var language in this.SupportedLanguages)
{
var services = (MefLanguageServices)this.GetLanguageServices(language);
Lazy<ILanguageService, LanguageServiceMetadata> service;
if (services.TryGetService(typeof(TLanguageService), out service))
if (services.TryGetService(typeof(TLanguageService), out var service))
{
if (filter(service.Metadata.Data))
{
......
......@@ -24,8 +24,7 @@ public MetadataReferenceCache(Func<string, MetadataReferenceProperties, Metadata
public MetadataReference GetReference(string path, MetadataReferenceProperties properties)
{
ReferenceSet referenceSet;
if (!_referenceSets.TryGetValue(path, out referenceSet))
if (!_referenceSets.TryGetValue(path, out var referenceSet))
{
referenceSet = ImmutableInterlocked.GetOrAdd(ref _referenceSets, path, new ReferenceSet(this));
}
......@@ -55,10 +54,8 @@ public MetadataReference GetAddOrUpdate(string path, MetadataReferenceProperties
{
using (_gate.DisposableWait())
{
WeakReference<MetadataReference> weakref;
MetadataReference mref = null;
if (!(_references.TryGetValue(properties, out weakref) && weakref.TryGetTarget(out mref)))
if (!(_references.TryGetValue(properties, out var weakref) && weakref.TryGetTarget(out mref)))
{
// try to base this metadata reference off of an existing one, so we don't load the metadata bytes twice.
foreach (var wr in _references.Values)
......
......@@ -30,8 +30,7 @@ public SyntaxTreeInfo(string filePath, ParseOptions options, ValueSource<TextAnd
internal bool TryGetText(out SourceText text)
{
TextAndVersion textAndVersion;
if (this.TextSource.TryGetValue(out textAndVersion))
if (this.TextSource.TryGetValue(out var textAndVersion))
{
text = textAndVersion.Text;
return true;
......@@ -90,8 +89,7 @@ internal sealed class RecoverableSyntaxRoot<TRoot> : RecoverableWeakValueSource<
public RecoverableSyntaxRoot<TRoot> WithSyntaxTree(IRecoverableSyntaxTree<TRoot> containingTree)
{
TRoot root;
if (this.TryGetValue(out root))
if (this.TryGetValue(out var root))
{
var result = new RecoverableSyntaxRoot<TRoot>(_service, root, containingTree);
result._storage = _storage;
......
......@@ -80,9 +80,7 @@ public bool TryGetSyntaxTree(out SyntaxTree syntaxTree)
public bool TryGetSyntaxVersion(out VersionStamp version)
{
version = default(VersionStamp);
VersionStamp textVersion;
if (!this.TryGetTextVersion(out textVersion))
if (!this.TryGetTextVersion(out var textVersion))
{
return false;
}
......@@ -155,10 +153,8 @@ public Task<SyntaxTree> GetSyntaxTreeAsync(CancellationToken cancellationToken =
{
return _syntaxTreeResultTask;
}
// check to see if we already have the tree before actually going async
SyntaxTree tree;
if (TryGetSyntaxTree(out tree))
if (TryGetSyntaxTree(out var tree))
{
// stash a completed result task for this value for the next request (to reduce extraneous allocations of tasks)
// don't use the actual async task because it depends on a specific cancellation token
......@@ -189,8 +185,7 @@ internal SyntaxTree GetSyntaxTreeSynchronously(CancellationToken cancellationTok
public bool TryGetSyntaxRoot(out SyntaxNode root)
{
root = null;
SyntaxTree tree;
return this.TryGetSyntaxTree(out tree) && tree.TryGetRoot(out root) && root != null;
return this.TryGetSyntaxTree(out var tree) && tree.TryGetRoot(out root) && root != null;
}
/// <summary>
......@@ -246,8 +241,7 @@ public async Task<SemanticModel> GetSemanticModelAsync(CancellationToken cancell
return null;
}
SemanticModel semanticModel;
if (this.TryGetSemanticModel(out semanticModel))
if (this.TryGetSemanticModel(out var semanticModel))
{
return semanticModel;
}
......@@ -330,10 +324,7 @@ public async Task<IEnumerable<TextChange>> GetTextChangesAsync(Document oldDocum
// first try to see if text already knows its changes
IList<TextChange> textChanges = null;
SourceText text;
SourceText oldText;
if (this.TryGetText(out text) && oldDocument.TryGetText(out oldText))
if (this.TryGetText(out var text) && oldDocument.TryGetText(out var oldText))
{
if (text == oldText)
{
......
......@@ -479,14 +479,12 @@ internal DocumentState UpdateTree(SyntaxNode newRoot, PreservationMode mode)
// determine encoding
Encoding encoding;
SyntaxTree priorTree;
SourceText priorText;
if (this.TryGetSyntaxTree(out priorTree))
if (this.TryGetSyntaxTree(out var priorTree))
{
// this is most likely available since UpdateTree is normally called after modifying the existing tree.
encoding = priorTree.Encoding;
}
else if (this.TryGetText(out priorText))
else if (this.TryGetText(out var priorText))
{
encoding = priorText.Encoding;
}
......@@ -518,9 +516,7 @@ private VersionStamp GetNewTreeVersionForUpdatedTree(SyntaxNode newRoot, Version
return newTextVersion;
}
TreeAndVersion oldTreeAndVersion;
SyntaxNode oldRoot;
if (!_treeSource.TryGetValue(out oldTreeAndVersion) || !oldTreeAndVersion.Tree.TryGetRoot(out oldRoot))
if (!_treeSource.TryGetValue(out var oldTreeAndVersion) || !oldTreeAndVersion.Tree.TryGetRoot(out var oldRoot))
{
return newTextVersion;
}
......@@ -584,14 +580,12 @@ private static async Task<SourceText> BuildRecoverableTreeTextAsync(SyntaxTree t
private VersionStamp GetNewerVersion()
{
TextAndVersion textAndVersion;
if (this.textAndVersionSource.TryGetValue(out textAndVersion))
if (this.textAndVersionSource.TryGetValue(out var textAndVersion))
{
return textAndVersion.Version.GetNewerVersion();
}
TreeAndVersion treeAndVersion;
if (_treeSource.TryGetValue(out treeAndVersion) && treeAndVersion != null)
if (_treeSource.TryGetValue(out var treeAndVersion) && treeAndVersion != null)
{
return treeAndVersion.Version.GetNewerVersion();
}
......@@ -602,9 +596,7 @@ private VersionStamp GetNewerVersion()
public bool TryGetSyntaxTree(out SyntaxTree syntaxTree)
{
syntaxTree = default(SyntaxTree);
TreeAndVersion treeAndVersion;
if (_treeSource.TryGetValue(out treeAndVersion) && treeAndVersion != null)
if (_treeSource.TryGetValue(out var treeAndVersion) && treeAndVersion != null)
{
syntaxTree = treeAndVersion.Tree;
BindSyntaxTreeToId(syntaxTree, this.Id);
......@@ -634,8 +626,7 @@ internal SyntaxTree GetSyntaxTree(CancellationToken cancellationToken)
public bool TryGetTopLevelChangeTextVersion(out VersionStamp version)
{
TreeAndVersion treeAndVersion;
if (_treeSource.TryGetValue(out treeAndVersion) && treeAndVersion != null)
if (_treeSource.TryGetValue(out var treeAndVersion) && treeAndVersion != null)
{
version = treeAndVersion.Version;
return true;
......@@ -654,8 +645,7 @@ public override async Task<VersionStamp> GetTopLevelChangeTextVersionAsync(Cance
return await this.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
}
TreeAndVersion treeAndVersion;
if (_treeSource.TryGetValue(out treeAndVersion) && treeAndVersion != null)
if (_treeSource.TryGetValue(out var treeAndVersion) && treeAndVersion != null)
{
return treeAndVersion.Version;
}
......@@ -672,8 +662,7 @@ private static void BindSyntaxTreeToId(SyntaxTree tree, DocumentId id)
{
using (s_syntaxTreeToIdMapLock.DisposableWrite())
{
DocumentId existingId;
if (s_syntaxTreeToIdMap.TryGetValue(tree, out existingId))
if (s_syntaxTreeToIdMap.TryGetValue(tree, out var existingId))
{
Contract.ThrowIfFalse(existingId == id);
}
......@@ -688,8 +677,7 @@ public static DocumentId GetDocumentIdForTree(SyntaxTree tree)
{
using (s_syntaxTreeToIdMapLock.DisposableRead())
{
DocumentId id;
s_syntaxTreeToIdMap.TryGetValue(tree, out id);
s_syntaxTreeToIdMap.TryGetValue(tree, out var id);
return id;
}
}
......
......@@ -39,8 +39,7 @@ public override TextAndVersion GetValue(CancellationToken cancellationToken = de
public override bool TryGetValue(out TextAndVersion value)
{
SourceText text;
if (_lazyText.TryGetValue(out text))
if (_lazyText.TryGetValue(out var text))
{
value = TextAndVersion.Create(text, _version, _filePath);
return true;
......
......@@ -31,8 +31,7 @@ internal class MetadataOnlyReference
CancellationToken cancellationToken)
{
solution.Workspace.LogTestMessage($"Looking to see if we already have a skeleton assembly for {projectReference.ProjectId} before we build one...");
MetadataReference reference;
if (TryGetReference(solution, projectReference, finalCompilation, version, out reference))
if (TryGetReference(solution, projectReference, finalCompilation, version, out var reference))
{
solution.Workspace.LogTestMessage($"A reference was found {projectReference.ProjectId} so we're skipping the build.");
return reference;
......@@ -93,8 +92,7 @@ internal class MetadataOnlyReference
SolutionState solution, ProjectReference projectReference, Compilation finalOrDeclarationCompilation, VersionStamp version, out MetadataReference reference)
{
// if we have one from snapshot cache, use it. it will make sure same compilation will get same metadata reference always.
MetadataOnlyReferenceSet referenceSet;
if (s_snapshotCache.TryGetValue(finalOrDeclarationCompilation, out referenceSet))
if (s_snapshotCache.TryGetValue(finalOrDeclarationCompilation, out var referenceSet))
{
solution.Workspace.LogTestMessage($"Found already cached metadata in {nameof(s_snapshotCache)} for the exact compilation");
reference = referenceSet.GetMetadataReference(finalOrDeclarationCompilation, projectReference.Aliases, projectReference.EmbedInteropTypes);
......@@ -129,10 +127,8 @@ internal class MetadataOnlyReference
{
// get map for the branch
var mapFromBranch = s_cache.GetValue(branchId, s_createReferenceSetMap);
// if we have one, return it
MetadataOnlyReferenceSet referenceSet;
if (mapFromBranch.TryGetValue(projectReference.ProjectId, out referenceSet) &&
if (mapFromBranch.TryGetValue(projectReference.ProjectId, out var referenceSet) &&
(version == VersionStamp.Default || referenceSet.Version == version))
{
// record it to snapshot based cache.
......@@ -181,9 +177,7 @@ public MetadataReference GetMetadataReference(Compilation compilation, Immutable
using (_gate.DisposableWait())
{
WeakReference<MetadataReference> weakMetadata;
MetadataReference metadataReference;
if (!_metadataReferences.TryGetValue(key, out weakMetadata) || !weakMetadata.TryGetTarget(out metadataReference))
if (!_metadataReferences.TryGetValue(key, out var weakMetadata) || !weakMetadata.TryGetTarget(out var metadataReference))
{
// here we give out strong reference to compilation. so there is possibility that we end up making 2 compilations for same project alive.
// one for final compilation and one for declaration only compilation. but the final compilation will be eventually kicked out from compilation cache
......
......@@ -37,8 +37,7 @@ internal static Compilation GetCompilationForMetadataReference(ProjectState proj
internal static bool TryGetCompilationForMetadataReference(ProjectState projectState, out Compilation referenceCompilation)
{
referenceCompilation = null;
WeakReference<Compilation> weakReference;
return s_compilationReferenceMap.TryGetValue(projectState, out weakReference) && weakReference.TryGetTarget(out referenceCompilation);
return s_compilationReferenceMap.TryGetValue(projectState, out var weakReference) && weakReference.TryGetTarget(out referenceCompilation);
}
}
}
\ No newline at end of file
......@@ -51,8 +51,7 @@ public IImmutableSet<ProjectId> GetProjectsThatThisProjectDirectlyDependsOn(Proj
throw new ArgumentNullException(nameof(projectId));
}
ImmutableHashSet<ProjectId> projectIds;
if (_referencesMap.TryGetValue(projectId, out projectIds))
if (_referencesMap.TryGetValue(projectId, out var projectIds))
{
return projectIds;
}
......@@ -93,8 +92,7 @@ private ImmutableHashSet<ProjectId> GetProjectsThatDirectlyDependOnThisProject_N
_lazyReverseReferencesMap = this.ComputeReverseReferencesMap();
}
ImmutableHashSet<ProjectId> reverseReferences;
if (_lazyReverseReferencesMap.TryGetValue(projectId, out reverseReferences))
if (_lazyReverseReferencesMap.TryGetValue(projectId, out var reverseReferences))
{
return reverseReferences;
}
......@@ -113,8 +111,7 @@ private ImmutableHashSet<ProjectId> GetProjectsThatDirectlyDependOnThisProject_N
var references = kvp.Value;
foreach (var referencedId in references)
{
HashSet<ProjectId> reverseReferences;
if (!reverseReferencesMap.TryGetValue(referencedId, out reverseReferences))
if (!reverseReferencesMap.TryGetValue(referencedId, out var reverseReferences))
{
reverseReferences = new HashSet<ProjectId>();
reverseReferencesMap.Add(referencedId, reverseReferences);
......@@ -141,8 +138,7 @@ public IImmutableSet<ProjectId> GetProjectsThatThisProjectTransitivelyDependsOn(
// first try without lock for speed
var currentMap = _transitiveReferencesMap;
ImmutableHashSet<ProjectId> transitiveReferences;
if (currentMap.TryGetValue(projectId, out transitiveReferences))
if (currentMap.TryGetValue(projectId, out var transitiveReferences))
{
return transitiveReferences;
}
......@@ -157,8 +153,7 @@ public IImmutableSet<ProjectId> GetProjectsThatThisProjectTransitivelyDependsOn(
private ImmutableHashSet<ProjectId> GetProjectsThatThisProjectTransitivelyDependsOn_NoLock(ProjectId projectId)
{
ImmutableHashSet<ProjectId> transitiveReferences;
if (!_transitiveReferencesMap.TryGetValue(projectId, out transitiveReferences))
if (!_transitiveReferencesMap.TryGetValue(projectId, out var transitiveReferences))
{
using (var pooledObject = SharedPools.Default<HashSet<ProjectId>>().GetPooledObject())
{
......@@ -197,8 +192,7 @@ public IEnumerable<ProjectId> GetProjectsThatTransitivelyDependOnThisProject(Pro
// first try without lock for speed
var currentMap = _reverseTransitiveReferencesMap;
ImmutableHashSet<ProjectId> reverseTransitiveReferences;
if (currentMap.TryGetValue(projectId, out reverseTransitiveReferences))
if (currentMap.TryGetValue(projectId, out var reverseTransitiveReferences))
{
return reverseTransitiveReferences;
}
......@@ -213,9 +207,7 @@ public IEnumerable<ProjectId> GetProjectsThatTransitivelyDependOnThisProject(Pro
private ImmutableHashSet<ProjectId> GetProjectsThatTransitivelyDependOnThisProject_NoLock(ProjectId projectId)
{
ImmutableHashSet<ProjectId> reverseTransitiveReferences;
if (!_reverseTransitiveReferencesMap.TryGetValue(projectId, out reverseTransitiveReferences))
if (!_reverseTransitiveReferencesMap.TryGetValue(projectId, out var reverseTransitiveReferences))
{
using (var pooledObject = SharedPools.Default<HashSet<ProjectId>>().GetPooledObject())
{
......@@ -289,8 +281,7 @@ private IEnumerable<ProjectId> GetTopologicallySortedProjects_NoLock(Cancellatio
if (seenProjects.Add(projectId))
{
// Recurse and add anything this project depends on before adding the project itself.
ImmutableHashSet<ProjectId> projectReferenceIds;
if (_referencesMap.TryGetValue(projectId, out projectReferenceIds))
if (_referencesMap.TryGetValue(projectId, out var projectReferenceIds))
{
TopologicalSort(projectReferenceIds, seenProjects, resultList, cancellationToken);
}
......
......@@ -149,8 +149,7 @@ private static async Task<VersionStamp> ComputeLatestDocumentVersionAsync(Immuta
ImmutableDictionary<DocumentId, DocumentState> newDocumentStates,
ImmutableDictionary<DocumentId, TextDocumentState> newAdditionalDocumentStates)
{
VersionStamp oldVersion;
if (_lazyLatestDocumentTopLevelChangeVersion.TryGetValue(out oldVersion))
if (_lazyLatestDocumentTopLevelChangeVersion.TryGetValue(out var oldVersion))
{
return new AsyncLazy<VersionStamp>(c => ComputeTopLevelChangeTextVersionAsync(oldVersion, newDocument, c), cacheResult: true);
}
......@@ -319,15 +318,13 @@ public bool ContainsAdditionalDocument(DocumentId documentId)
public DocumentState GetDocumentState(DocumentId documentId)
{
DocumentState state;
_documentStates.TryGetValue(documentId, out state);
_documentStates.TryGetValue(documentId, out var state);
return state;
}
public TextDocumentState GetAdditionalDocumentState(DocumentId documentId)
{
TextDocumentState state;
_additionalDocumentStates.TryGetValue(documentId, out state);
_additionalDocumentStates.TryGetValue(documentId, out var state);
return state;
}
......@@ -606,12 +603,9 @@ public ProjectState UpdateDocument(DocumentState newDocument, bool textChanged,
}
var newDocumentStates = this.DocumentStates.SetItem(newDocument.Id, newDocument);
AsyncLazy<VersionStamp> dependentDocumentVersion;
AsyncLazy<VersionStamp> dependentSemanticVersion;
GetLatestDependentVersions(
newDocumentStates, _additionalDocumentStates, oldDocument, newDocument, recalculateDependentVersions, textChanged,
out dependentDocumentVersion, out dependentSemanticVersion);
out var dependentDocumentVersion, out var dependentSemanticVersion);
return this.With(
documentStates: newDocumentStates,
......@@ -630,12 +624,9 @@ public ProjectState UpdateAdditionalDocument(TextDocumentState newDocument, bool
}
var newDocumentStates = this.AdditionalDocumentStates.SetItem(newDocument.Id, newDocument);
AsyncLazy<VersionStamp> dependentDocumentVersion;
AsyncLazy<VersionStamp> dependentSemanticVersion;
GetLatestDependentVersions(
_documentStates, newDocumentStates, oldDocument, newDocument, recalculateDependentVersions, textChanged,
out dependentDocumentVersion, out dependentSemanticVersion);
out var dependentDocumentVersion, out var dependentSemanticVersion);
return this.With(
additionalDocumentStates: newDocumentStates,
......@@ -655,17 +646,14 @@ public ProjectState UpdateAdditionalDocument(TextDocumentState newDocument, bool
if (recalculateDependentVersions)
{
VersionStamp oldVersion;
if (oldDocument.TryGetTextVersion(out oldVersion))
if (oldDocument.TryGetTextVersion(out var oldVersion))
{
VersionStamp documentVersion;
if (!_lazyLatestDocumentVersion.TryGetValue(out documentVersion) || documentVersion == oldVersion)
if (!_lazyLatestDocumentVersion.TryGetValue(out var documentVersion) || documentVersion == oldVersion)
{
recalculateDocumentVersion = true;
}
VersionStamp semanticVersion;
if (!_lazyLatestDocumentTopLevelChangeVersion.TryGetValue(out semanticVersion) || semanticVersion == oldVersion)
if (!_lazyLatestDocumentTopLevelChangeVersion.TryGetValue(out var semanticVersion) || semanticVersion == oldVersion)
{
recalculateSemanticVersion = true;
}
......
......@@ -37,8 +37,7 @@ internal class RecoverableTextAndVersion : ValueSource<TextAndVersion>, ITextVer
public override bool TryGetValue(out TextAndVersion value)
{
SourceText text;
if (_text != null && _text.TryGetValue(out text))
if (_text != null && _text.TryGetValue(out var text))
{
value = TextAndVersion.Create(text, _version, _filePath);
return true;
......@@ -58,8 +57,7 @@ public bool TryGetTextVersion(out VersionStamp version)
// then try to get version from cached value.
if (version == default(VersionStamp))
{
TextAndVersion textAndVersion;
if (this.TryGetValue(out textAndVersion))
if (this.TryGetValue(out var textAndVersion))
{
version = textAndVersion.Version;
}
......
......@@ -207,8 +207,7 @@ internal Document GetDocument(SyntaxTree syntaxTree, ProjectId projectId)
if (document != null)
{
// does this document really have the syntax tree?
SyntaxTree documentTree;
if (document.TryGetSyntaxTree(out documentTree) && documentTree == syntaxTree)
if (document.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree)
{
return document;
}
......
......@@ -156,10 +156,7 @@ public CompilationTracker Clone()
public CompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken)
{
ProjectState inProgressProject;
Compilation inProgressCompilation;
GetPartialCompilationState(solution, docState.Id, out inProgressProject, out inProgressCompilation, cancellationToken);
GetPartialCompilationState(solution, docState.Id, out var inProgressProject, out var inProgressCompilation, cancellationToken);
if (!inProgressCompilation.SyntaxTrees.Contains(tree))
{
......@@ -300,8 +297,7 @@ public bool TryGetCompilation(out Compilation compilation)
public Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken)
{
Compilation compilation;
if (this.TryGetCompilation(out compilation))
if (this.TryGetCompilation(out var compilation))
{
// PERF: This is a hot code path and Task<TResult> isn't cheap,
// so cache the completed tasks to reduce allocations. We also
......@@ -726,11 +722,10 @@ private bool HasMissingReferences(Compilation compilation, IReadOnlyList<Metadat
{
try
{
Compilation compilation;
// if we already have the compilation and its right kind then use it.
if (this.ProjectState.LanguageServices == fromProject.LanguageServices
&& this.TryGetCompilation(out compilation))
&& this.TryGetCompilation(out var compilation))
{
return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes);
}
......@@ -762,10 +757,8 @@ private bool HasMissingReferences(Compilation compilation, IReadOnlyList<Metadat
public MetadataReference GetPartialMetadataReference(SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken)
{
var state = this.ReadState();
// get compilation in any state it happens to be in right now.
Compilation compilation;
if (state.Compilation.TryGetValue(out compilation)
if (state.Compilation.TryGetValue(out var compilation)
&& compilation != null
&& this.ProjectState.LanguageServices == fromProject.LanguageServices)
{
......@@ -790,12 +783,9 @@ public MetadataReference GetPartialMetadataReference(SolutionState solution, Pro
// get or build compilation up to declaration state. this compilation will be used to provide live xml doc comment
var declarationCompilation = await this.GetOrBuildDeclarationCompilationAsync(solution, cancellationToken: cancellationToken).ConfigureAwait(false);
MetadataReference reference;
solution.Workspace.LogTestMessage($"Looking for a cached skeleton assembly for {projectReference.ProjectId} before taking the lock...");
if (!MetadataOnlyReference.TryGetReference(solution, projectReference, declarationCompilation, version, out reference))
if (!MetadataOnlyReference.TryGetReference(solution, projectReference, declarationCompilation, version, out var reference))
{
// using async build lock so we don't get multiple consumers attempting to build metadata-only images for the same compilation.
using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
......
......@@ -315,8 +315,7 @@ private DocumentState GetDocumentState(SyntaxTree syntaxTree, ProjectId projectI
if (document != null)
{
// does this document really have the syntax tree?
SyntaxTree documentTree;
if (document.TryGetSyntaxTree(out documentTree) && documentTree == syntaxTree)
if (document.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree)
{
return document;
}
......@@ -353,8 +352,7 @@ public Task<VersionStamp> GetDependentSemanticVersionAsync(ProjectId projectId,
public ProjectState GetProjectState(ProjectId projectId)
{
ProjectState state;
_projectIdToProjectStateMap.TryGetValue(projectId, out state);
_projectIdToProjectStateMap.TryGetValue(projectId, out var state);
return state;
}
......@@ -371,8 +369,7 @@ public ProjectState GetProjectState(IAssemblySymbol assemblySymbol, Cancellation
// TODO: Remove this loop when we add source assembly symbols to s_assemblyOrModuleSymbolToProjectMap
foreach (var state in _projectIdToProjectStateMap.Values)
{
Compilation compilation;
if (this.TryGetCompilation(state.Id, out compilation))
if (this.TryGetCompilation(state.Id, out var compilation))
{
// if the symbol is the compilation's assembly symbol, we are done
if (compilation.Assembly == assemblySymbol)
......@@ -382,8 +379,7 @@ public ProjectState GetProjectState(IAssemblySymbol assemblySymbol, Cancellation
}
}
ProjectId id;
s_assemblyOrModuleSymbolToProjectMap.TryGetValue(assemblySymbol, out id);
s_assemblyOrModuleSymbolToProjectMap.TryGetValue(assemblySymbol, out var id);
return id == null ? null : this.GetProjectState(id);
}
......@@ -400,8 +396,7 @@ private static CompilationTracker CreateCompilationTracker(ProjectId projectId,
private CompilationTracker GetCompilationTracker(ProjectId projectId)
{
CompilationTracker tracker;
if (!_projectIdToTrackerMap.TryGetValue(projectId, out tracker))
if (!_projectIdToTrackerMap.TryGetValue(projectId, out var tracker))
{
tracker = ImmutableInterlocked.GetOrAdd(ref _projectIdToTrackerMap, projectId, s_createCompilationTrackerFunction, this);
}
......@@ -486,8 +481,7 @@ public SolutionState AddProject(ProjectInfo projectInfo)
continue;
}
ImmutableArray<DocumentId> documentIdsWithPath;
builder[filePath] = builder.TryGetValue(filePath, out documentIdsWithPath)
builder[filePath] = builder.TryGetValue(filePath, out var documentIdsWithPath)
? documentIdsWithPath.Add(documentId)
: ImmutableArray.Create(documentId);
}
......@@ -546,8 +540,7 @@ public SolutionState RemoveProject(ProjectId projectId)
continue;
}
ImmutableArray<DocumentId> documentIdsWithPath;
if (!builder.TryGetValue(filePath, out documentIdsWithPath) || !documentIdsWithPath.Contains(documentId))
if (!builder.TryGetValue(filePath, out var documentIdsWithPath) || !documentIdsWithPath.Contains(documentId))
{
throw new ArgumentException("The given documentId was not found in the linkedFilesMap.");
}
......@@ -1137,9 +1130,7 @@ public SolutionState WithDocumentText(DocumentId documentId, SourceText text, Pr
CheckContainsDocument(documentId);
var oldDocument = this.GetDocumentState(documentId);
SourceText oldText;
if (oldDocument.TryGetText(out oldText) && text == oldText)
if (oldDocument.TryGetText(out var oldText) && text == oldText)
{
return this;
}
......@@ -1184,9 +1175,7 @@ public SolutionState WithAdditionalDocumentText(DocumentId documentId, SourceTex
CheckContainsAdditionalDocument(documentId);
var oldDocument = this.GetAdditionalDocumentState(documentId);
SourceText oldText;
if (oldDocument.TryGetText(out oldText) && text == oldText)
if (oldDocument.TryGetText(out var oldText) && text == oldText)
{
return this;
}
......@@ -1276,11 +1265,8 @@ public SolutionState WithDocumentSyntaxRoot(DocumentId documentId, SyntaxNode ro
CheckContainsDocument(documentId);
var oldDocument = this.GetDocumentState(documentId);
SyntaxTree oldTree;
SyntaxNode oldRoot;
if (oldDocument.TryGetSyntaxTree(out oldTree) &&
oldTree.TryGetRoot(out oldRoot) &&
if (oldDocument.TryGetSyntaxTree(out var oldTree) &&
oldTree.TryGetRoot(out var oldRoot) &&
oldRoot == root)
{
return this;
......@@ -1432,11 +1418,9 @@ private SolutionState WithTextDocumentState(TextDocumentState newDocument, bool
var newStateMap = _projectIdToProjectStateMap.SetItem(projectId, newProjectState);
var newDependencyGraph = withProjectReferenceChange ? CreateDependencyGraph(_projectIds, newStateMap) : _dependencyGraph;
var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph);
// If we have a tracker for this project, then fork it as well (along with the
// translation action and store it in the tracker map.
CompilationTracker tracker;
if (newTrackerMap.TryGetValue(projectId, out tracker))
if (newTrackerMap.TryGetValue(projectId, out var tracker))
{
newTrackerMap = newTrackerMap.Remove(projectId);
......@@ -1468,8 +1452,7 @@ public ImmutableArray<DocumentId> GetDocumentIdsWithFilePath(string filePath)
return ImmutableArray.Create<DocumentId>();
}
ImmutableArray<DocumentId> documentIds;
return _linkedFilesMap.TryGetValue(filePath, out documentIds)
return _linkedFilesMap.TryGetValue(filePath, out var documentIds)
? documentIds
: ImmutableArray.Create<DocumentId>();
}
......@@ -1620,8 +1603,7 @@ public SolutionState WithDocumentText(IEnumerable<DocumentId> documentIds, Sourc
var doc = solution.GetDocumentState(documentId);
if (doc != null)
{
SourceText existingText;
if (!doc.TryGetText(out existingText) || existingText != text)
if (!doc.TryGetText(out var existingText) || existingText != text)
{
solution = solution.WithDocumentText(documentId, text, mode);
}
......@@ -1634,11 +1616,9 @@ public SolutionState WithDocumentText(IEnumerable<DocumentId> documentIds, Sourc
public bool TryGetCompilation(ProjectId projectId, out Compilation compilation)
{
CheckContainsProject(projectId);
CompilationTracker tracker;
compilation = null;
return this.TryGetCompilationTracker(projectId, out tracker)
return this.TryGetCompilationTracker(projectId, out var tracker)
&& tracker.TryGetCompilation(out compilation);
}
......@@ -1688,10 +1668,8 @@ private static void RecordSourceOfAssemblySymbol(ISymbol assemblyOrModuleSymbol,
}
Contract.ThrowIfNull(projectId);
// remember which project is associated with this assembly
ProjectId tmp;
if (!s_assemblyOrModuleSymbolToProjectMap.TryGetValue(assemblyOrModuleSymbol, out tmp))
if (!s_assemblyOrModuleSymbolToProjectMap.TryGetValue(assemblyOrModuleSymbol, out var tmp))
{
// use GetValue to avoid race condition exceptions from Add.
// the first one to set the value wins.
......@@ -1734,8 +1712,7 @@ public Task<MetadataReference> GetMetadataReferenceAsync(ProjectReference projec
{
// Try to get the compilation state for this project. If it doesn't exist, don't do any
// more work.
CompilationTracker state;
if (!_projectIdToTrackerMap.TryGetValue(projectReference.ProjectId, out state))
if (!_projectIdToTrackerMap.TryGetValue(projectReference.ProjectId, out var state))
{
return null;
}
......
......@@ -34,10 +34,8 @@ public SolutionStateChecksums With(Checksum infoChecksum = null, ProjectChecksum
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// verify input
SolutionStateChecksums stateChecksum;
Contract.ThrowIfFalse(state.TryGetStateChecksums(out stateChecksum));
Contract.ThrowIfFalse(state.TryGetStateChecksums(out var stateChecksum));
Contract.ThrowIfFalse(this == stateChecksum);
if (searchingChecksumsLeft.Remove(Checksum))
......@@ -58,10 +56,8 @@ public SolutionStateChecksums With(Checksum infoChecksum = null, ProjectChecksum
foreach (var kv in state.ProjectStates)
{
var projectState = kv.Value;
// solution state checksum can't be created without project state checksums created first
ProjectStateChecksums projectStateChecksums;
Contract.ThrowIfFalse(projectState.TryGetStateChecksums(out projectStateChecksums));
Contract.ThrowIfFalse(projectState.TryGetStateChecksums(out var projectStateChecksums));
projectStateChecksums.Find(projectState, searchingChecksumsLeft, result, cancellationToken);
if (searchingChecksumsLeft.Count == 0)
......@@ -139,10 +135,8 @@ public ProjectStateChecksums(params object[] children) : base(nameof(ProjectStat
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// verify input
ProjectStateChecksums stateChecksum;
Contract.ThrowIfFalse(state.TryGetStateChecksums(out stateChecksum));
Contract.ThrowIfFalse(state.TryGetStateChecksums(out var stateChecksum));
Contract.ThrowIfFalse(this == stateChecksum);
if (searchingChecksumsLeft.Remove(Checksum))
......@@ -206,9 +200,7 @@ public ProjectStateChecksums(params object[] children) : base(nameof(ProjectStat
foreach (var kv in values)
{
var state = kv.Value;
DocumentStateChecksums stateChecksums;
Contract.ThrowIfFalse(state.TryGetStateChecksums(out stateChecksums));
Contract.ThrowIfFalse(state.TryGetStateChecksums(out var stateChecksums));
stateChecksums.Find(state, searchingChecksumsLeft, result, cancellationToken);
if (searchingChecksumsLeft.Count == 0)
......@@ -273,10 +265,8 @@ public DocumentStateChecksums With(Checksum infoChecksum = null, Checksum textCh
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// verify input
DocumentStateChecksums stateChecksum;
Contract.ThrowIfFalse(state.TryGetStateChecksums(out stateChecksum));
Contract.ThrowIfFalse(state.TryGetStateChecksums(out var stateChecksum));
Contract.ThrowIfFalse(this == stateChecksum);
if (searchingChecksumsLeft.Remove(Checksum))
......
......@@ -191,8 +191,7 @@ public bool TryGetText(out SourceText text)
return true;
}
TextAndVersion textAndVersion;
if (this.textAndVersionSource.TryGetValue(out textAndVersion))
if (this.textAndVersionSource.TryGetValue(out var textAndVersion))
{
text = textAndVersion.Text;
return true;
......@@ -213,8 +212,7 @@ public bool TryGetTextVersion(out VersionStamp version)
return versionable.TryGetTextVersion(out version);
}
TextAndVersion textAndVersion;
if (this.textAndVersionSource.TryGetValue(out textAndVersion))
if (this.textAndVersionSource.TryGetValue(out var textAndVersion))
{
version = textAndVersion.Version;
return true;
......@@ -246,14 +244,12 @@ public SourceText GetText(CancellationToken cancellationToken)
public async Task<VersionStamp> GetTextVersionAsync(CancellationToken cancellationToken)
{
// try fast path first
VersionStamp version;
if (TryGetTextVersion(out version))
if (TryGetTextVersion(out var version))
{
return version;
}
TextAndVersion textAndVersion;
if (this.textAndVersionSource.TryGetValue(out textAndVersion))
if (this.textAndVersionSource.TryGetValue(out var textAndVersion))
{
return textAndVersion.Version;
}
......@@ -319,8 +315,7 @@ public TextDocumentState UpdateText(TextLoader loader, PreservationMode mode)
private VersionStamp GetNewerVersion()
{
TextAndVersion textAndVersion;
if (this.textAndVersionSource.TryGetValue(out textAndVersion))
if (this.textAndVersionSource.TryGetValue(out var textAndVersion))
{
return textAndVersion.Version.GetNewerVersion();
}
......
......@@ -15,8 +15,7 @@ internal static class TextExtensions
/// </summary>
public static IEnumerable<Document> GetRelatedDocumentsWithChanges(this SourceText text)
{
Workspace workspace;
if (Workspace.TryGetWorkspace(text.Container, out workspace))
if (Workspace.TryGetWorkspace(text.Container, out var workspace))
{
var ids = workspace.GetRelatedDocumentIds(text.Container);
var sol = workspace.CurrentSolution.WithDocumentText(ids, text, PreservationMode.PreserveIdentity);
......@@ -32,8 +31,7 @@ public static IEnumerable<Document> GetRelatedDocumentsWithChanges(this SourceTe
/// </summary>
public static Document GetOpenDocumentInCurrentContextWithChanges(this SourceText text)
{
Workspace workspace;
if (Workspace.TryGetWorkspace(text.Container, out workspace))
if (Workspace.TryGetWorkspace(text.Container, out var workspace))
{
var id = workspace.GetDocumentIdInCurrentContext(text.Container);
if (id == null || !workspace.CurrentSolution.ContainsDocument(id))
......@@ -53,8 +51,7 @@ public static Document GetOpenDocumentInCurrentContextWithChanges(this SourceTex
/// </summary>
public static IEnumerable<Document> GetRelatedDocuments(this SourceTextContainer container)
{
Workspace workspace;
if (Workspace.TryGetWorkspace(container, out workspace))
if (Workspace.TryGetWorkspace(container, out var workspace))
{
var sol = workspace.CurrentSolution;
var ids = workspace.GetRelatedDocumentIds(container);
......@@ -70,8 +67,7 @@ public static IEnumerable<Document> GetRelatedDocuments(this SourceTextContainer
/// </summary>
public static Document GetOpenDocumentInCurrentContext(this SourceTextContainer container)
{
Workspace workspace;
if (Workspace.TryGetWorkspace(container, out workspace))
if (Workspace.TryGetWorkspace(container, out var workspace))
{
var id = workspace.GetDocumentIdInCurrentContext(container);
return workspace.CurrentSolution.GetDocument(id);
......
......@@ -903,11 +903,10 @@ private static Solution UpdateReferencesAfterAdd(Solution solution)
var pemeta = meta as PortableExecutableReference;
if (pemeta != null)
{
ProjectId matchingProjectId;
// check both Display and FilePath. FilePath points to the actually bits, but Display should match output path if
// the metadata reference is shadow copied.
if ((!string.IsNullOrEmpty(pemeta.Display) && outputAssemblyToProjectIdMap.TryGetValue(pemeta.Display, out matchingProjectId)) ||
if ((!string.IsNullOrEmpty(pemeta.Display) && outputAssemblyToProjectIdMap.TryGetValue(pemeta.Display, out var matchingProjectId)) ||
(!string.IsNullOrEmpty(pemeta.FilePath) && outputAssemblyToProjectIdMap.TryGetValue(pemeta.FilePath, out matchingProjectId)))
{
var newProjRef = new ProjectReference(matchingProjectId, pemeta.Properties.Aliases, pemeta.Properties.EmbedInteropTypes);
......@@ -1226,20 +1225,16 @@ protected virtual void ApplyProjectChanges(ProjectChanges projectChanges)
{
var oldDoc = projectChanges.OldProject.GetDocument(documentId);
var newDoc = projectChanges.NewProject.GetDocument(documentId);
// see whether we can get oldText
SourceText oldText;
if (!oldDoc.TryGetText(out oldText))
if (!oldDoc.TryGetText(out var oldText))
{
// we can't get old text, there is not much we can do except replacing whole text.
var currentText = newDoc.GetTextAsync(CancellationToken.None).WaitAndGetResult_CanCallOnBackground(CancellationToken.None); // needs wait
this.ApplyDocumentTextChanged(documentId, currentText);
return;
}
// see whether we can get new text
SourceText newText;
if (!newDoc.TryGetText(out newText))
if (!newDoc.TryGetText(out var newText))
{
// okay, we have old text, but no new text. let document determine text changes
var textChanges = newDoc.GetTextChangesAsync(oldDoc, CancellationToken.None).WaitAndGetResult_CanCallOnBackground(CancellationToken.None); // needs wait
......
......@@ -39,8 +39,7 @@ internal virtual bool CanChangeActiveContextDocument
private static void RemoveIfEmpty<TKey, TValue>(IDictionary<TKey, ISet<TValue>> dictionary, TKey key)
{
ISet<TValue> values;
if (dictionary.TryGetValue(key, out values))
if (dictionary.TryGetValue(key, out var values))
{
if (values.Count == 0)
{
......@@ -103,19 +102,14 @@ protected void ClearOpenDocument(DocumentId documentId, bool isSolutionClosing =
private DocumentId ClearOpenDocument_NoLock(DocumentId documentId)
{
_stateLock.AssertHasLock();
ISet<DocumentId> openDocIds;
if (_projectToOpenDocumentsMap.TryGetValue(documentId.ProjectId, out openDocIds) && openDocIds != null)
if (_projectToOpenDocumentsMap.TryGetValue(documentId.ProjectId, out var openDocIds) && openDocIds != null)
{
openDocIds.Remove(documentId);
}
RemoveIfEmpty(_projectToOpenDocumentsMap, documentId.ProjectId);
// Stop tracking the buffer or update the documentId associated with the buffer.
TextTracker tracker;
if (_textTrackers.TryGetValue(documentId, out tracker))
if (_textTrackers.TryGetValue(documentId, out var tracker))
{
tracker.Disconnect();
_textTrackers.Remove(documentId);
......@@ -217,8 +211,7 @@ public virtual IEnumerable<DocumentId> GetOpenDocumentIds(ProjectId projectId =
if (projectId != null)
{
ISet<DocumentId> documentIds;
if (_projectToOpenDocumentsMap.TryGetValue(projectId, out documentIds))
if (_projectToOpenDocumentsMap.TryGetValue(projectId, out var documentIds))
{
return documentIds;
}
......@@ -249,8 +242,7 @@ public virtual IEnumerable<DocumentId> GetRelatedDocumentIds(SourceTextContainer
private ImmutableArray<DocumentId> GetRelatedDocumentIds_NoLock(SourceTextContainer container)
{
DocumentId documentId;
if (!_bufferToDocumentInCurrentContextMap.TryGetValue(container, out documentId))
if (!_bufferToDocumentInCurrentContextMap.TryGetValue(container, out var documentId))
{
// it is not an opened file
return ImmutableArray<DocumentId>.Empty;
......@@ -308,8 +300,7 @@ private SourceTextContainer GetOpenDocumentSourceTextContainer_NoLock(DocumentId
private DocumentId GetDocumentIdInCurrentContext_NoLock(SourceTextContainer container)
{
DocumentId docId;
bool foundValue = _bufferToDocumentInCurrentContextMap.TryGetValue(container, out docId);
bool foundValue = _bufferToDocumentInCurrentContextMap.TryGetValue(container, out var docId);
if (foundValue)
{
......@@ -391,10 +382,7 @@ protected void CheckDocumentIsOpen(DocumentId documentId)
private ISet<DocumentId> GetProjectOpenDocuments_NoLock(ProjectId project)
{
_stateLock.AssertHasLock();
ISet<DocumentId> openDocs;
_projectToOpenDocumentsMap.TryGetValue(project, out openDocs);
_projectToOpenDocumentsMap.TryGetValue(project, out var openDocs);
return openDocs;
}
......@@ -415,11 +403,8 @@ private ISet<DocumentId> GetProjectOpenDocuments_NoLock(ProjectId project)
var newText = textContainer.CurrentText;
Solution currentSolution;
SourceText oldText;
VersionStamp version;
if (oldDocument.TryGetText(out oldText) &&
oldDocument.TryGetTextVersion(out version))
if (oldDocument.TryGetText(out var oldText) &&
oldDocument.TryGetTextVersion(out var version))
{
// Optimize the case where we've already got the previous text and version.
var newTextAndVersion = GetProperTextAndVersion(oldText, newText, version, oldDocumentState.FilePath);
......@@ -657,11 +642,9 @@ private DocumentId UpdateCurrentContextMapping_NoLock(SourceTextContainer textCo
private SourceText GetOpenDocumentText(Solution solution, DocumentId documentId)
{
CheckDocumentIsOpen(documentId);
// text should always be preserved, so TryGetText will succeed.
SourceText text;
var doc = solution.GetDocument(documentId);
doc.TryGetText(out text);
// text should always be preserved, so TryGetText will succeed.
doc.TryGetText(out var text);
return text;
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册