static void Main(string[] args) { ValueTuple <int, int> tuple = ValueTuple.Create(1, 2); Console.WriteLine(tuple.Item1 + tuple.Item2); }
public void LogRudeEdit(ushort kind, ushort syntaxKind) { RudeEdits.Add(ValueTuple.Create(kind, syntaxKind)); }
public void WriteTimesAndGcs(IEnumerable <ValueTuple <int, int> > trials) => WriteTimesAndGcs(trials.Select(t => ValueTuple.Create(t.Item1, (int?)t.Item2)));
async Task ListEquipmentAsync([Dense] string equipClass = null) { var builder = new EmbedBuilder { Author = new EmbedAuthorBuilder { IconUrl = BotAvatar, Name = "Equipment listing" }, Color = System.Drawing.Color.LightBlue.ToDiscord(), Footer = new EmbedFooterBuilder { IconUrl = BotAvatar, Text = $"{BotUser.Username} Equipment tool" }, Timestamp = DateTime.Now }; IEnumerable <ValueTuple <string, string> > fields; List <Equipment> allEquip = await DataService.GetAllEquipment(true); switch (equipClass?.ToLower()) { case "aura": fields = allEquip.Where(e => e.Class == EquipmentClass.Aura) .GroupBy(e => e.BonusType) .Select(g => ValueTuple.Create(Formatter.Beautify(g.Key), string.Join("\n", g.OrderBy(e => e.Rarity)))); break; case "weapon": case "sword": fields = allEquip.Where(e => e.Class == EquipmentClass.Weapon) .GroupBy(e => e.BonusType) .Select(g => ValueTuple.Create(Formatter.Beautify(g.Key), string.Join("\n", g.OrderBy(e => e.Rarity)))); break; case "hat": case "helmet": fields = allEquip.Where(e => e.Class == EquipmentClass.Hat) .GroupBy(e => e.BonusType) .Select(g => ValueTuple.Create(Formatter.Beautify(g.Key), string.Join("\n", g.OrderBy(e => e.Rarity)))); break; case "slash": fields = allEquip.Where(e => e.Class == EquipmentClass.Slash) .GroupBy(e => e.BonusType) .Select(g => ValueTuple.Create(Formatter.Beautify(g.Key), string.Join("\n", g.OrderBy(e => e.Rarity)))); break; case "suit": case "armor": case "body": fields = allEquip.Where(e => e.Class == EquipmentClass.Suit) .GroupBy(e => e.BonusType) .Select(g => ValueTuple.Create(Formatter.Beautify(g.Key), string.Join("\n", g.OrderBy(e => e.Rarity)))); break; case "removed": fields = allEquip.Where(e => e.Rarity == EquipmentRarity.Removed) .GroupBy(e => e.Class) .Select(g => ValueTuple.Create(Formatter.Beautify(g.Key), string.Join("\n", g.OrderBy(e => e.Name)))); break; default: fields = null; break; } if (fields == null) { builder.WithDescription("Please use one of the following equipment types:\n" + string.Join("\n", Enum.GetNames(typeof(EquipmentClass))).Replace("None", "Removed") + $"\n\n `{Prefix}{CommandName} list [type]`"); } else { builder.WithDescription($"All {equipClass} equipment"); foreach (var field in fields) { builder.AddInlineField(field.Item1, field.Item2); } } await ReplyAsync("", embed : builder.Build()); }
private static async Task <ValueTuple <SyntaxTreeIdentifierInfo, SyntaxTreeContextInfo, SyntaxTreeDeclarationInfo> > CreateInfoAsync(Document document, CancellationToken cancellationToken) { var syntaxFacts = document.GetLanguageService <ISyntaxFactsService>(); var ignoreCase = syntaxFacts != null && !syntaxFacts.IsCaseSensitive; var isCaseSensitive = !ignoreCase; HashSet <string> identifiers; HashSet <string> escapedIdentifiers; GetIdentifierSet(ignoreCase, out identifiers, out escapedIdentifiers); try { var containsForEachStatement = false; var containsLockStatement = false; var containsUsingStatement = false; var containsQueryExpression = false; var containsThisConstructorInitializer = false; var containsBaseConstructorInitializer = false; var containsElementAccess = false; var containsIndexerMemberCref = false; var predefinedTypes = (int)PredefinedType.None; var predefinedOperators = (int)PredefinedOperator.None; var declaredSymbolInfos = new List <DeclaredSymbolInfo>(); if (syntaxFacts != null) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); foreach (var current in root.DescendantNodesAndTokensAndSelf(descendIntoTrivia: true)) { if (current.IsNode) { var node = (SyntaxNode)current; containsForEachStatement = containsForEachStatement || syntaxFacts.IsForEachStatement(node); containsLockStatement = containsLockStatement || syntaxFacts.IsLockStatement(node); containsUsingStatement = containsUsingStatement || syntaxFacts.IsUsingStatement(node); containsQueryExpression = containsQueryExpression || syntaxFacts.IsQueryExpression(node); containsElementAccess = containsElementAccess || syntaxFacts.IsElementAccessExpression(node); containsIndexerMemberCref = containsIndexerMemberCref || syntaxFacts.IsIndexerMemberCRef(node); DeclaredSymbolInfo declaredSymbolInfo; if (syntaxFacts.TryGetDeclaredSymbolInfo(node, out declaredSymbolInfo)) { declaredSymbolInfos.Add(declaredSymbolInfo); } } else { var token = (SyntaxToken)current; containsThisConstructorInitializer = containsThisConstructorInitializer || syntaxFacts.IsThisConstructorInitializer(token); containsBaseConstructorInitializer = containsBaseConstructorInitializer || syntaxFacts.IsBaseConstructorInitializer(token); if (syntaxFacts.IsIdentifier(token) || syntaxFacts.IsGlobalNamespaceKeyword(token)) { var valueText = token.ValueText; identifiers.Add(valueText); if (valueText.Length != token.Width()) { escapedIdentifiers.Add(valueText); } } PredefinedType predefinedType; if (syntaxFacts.TryGetPredefinedType(token, out predefinedType)) { predefinedTypes |= (int)predefinedType; } PredefinedOperator predefinedOperator; if (syntaxFacts.TryGetPredefinedOperator(token, out predefinedOperator)) { predefinedOperators |= (int)predefinedOperator; } } } } var version = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false); return(ValueTuple.Create( new SyntaxTreeIdentifierInfo( version, new BloomFilter(FalsePositiveProbability, isCaseSensitive, identifiers), new BloomFilter(FalsePositiveProbability, isCaseSensitive, escapedIdentifiers)), new SyntaxTreeContextInfo( version, predefinedTypes, predefinedOperators, containsForEachStatement, containsLockStatement, containsUsingStatement, containsQueryExpression, containsThisConstructorInitializer, containsBaseConstructorInitializer, containsElementAccess, containsIndexerMemberCref), new SyntaxTreeDeclarationInfo( version, declaredSymbolInfos))); } finally { Free(ignoreCase, identifiers, escapedIdentifiers); } }
public void ParseTildeStringAsString() { Assert.AreEqual(ValueTuple.Create("key", "aString"), SenderOptions.ParseItem("key~aString")); }
/// <summary> /// Creates a new instance of the compilation info, retaining any already built /// compilation state as the now 'old' state /// </summary> public CompilationTracker Fork( ProjectState newProject, CompilationTranslationAction translate = null, bool clone = false, CancellationToken cancellationToken = default(CancellationToken)) { var state = this.ReadState(); ValueSource <Compilation> baseCompilationSource = state.Compilation; var baseCompilation = baseCompilationSource.GetValue(cancellationToken); if (baseCompilation != null) { // We have some pre-calculated state to incrementally update var newInProgressCompilation = clone ? baseCompilation.Clone() : baseCompilation; var intermediateProjects = state is InProgressState ? ((InProgressState)state).IntermediateProjects : ImmutableArray.Create <ValueTuple <ProjectState, CompilationTranslationAction> >(); var newIntermediateProjects = translate == null ? intermediateProjects : intermediateProjects.Add(ValueTuple.Create(this.ProjectState, translate)); var newState = State.Create(newInProgressCompilation, newIntermediateProjects); return(new CompilationTracker(newProject, newState)); } var declarationOnlyCompilation = state.DeclarationOnlyCompilation; if (declarationOnlyCompilation != null) { if (translate != null) { var intermediateProjects = ImmutableArray.Create <ValueTuple <ProjectState, CompilationTranslationAction> >(ValueTuple.Create(this.ProjectState, translate)); return(new CompilationTracker(newProject, new InProgressState(declarationOnlyCompilation, intermediateProjects))); } return(new CompilationTracker(newProject, new LightDeclarationState(declarationOnlyCompilation))); } // We have nothing. Just make a tracker that only points to the new project. We'll have // to rebuild its compilation from scratch if anyone asks for it. return(new CompilationTracker(newProject)); }
internal async ReusableTask <bool> GetHashAsync(ITorrentManagerInfo manager, int pieceIndex, PieceHash dest) { if (GetHashAsyncOverride != null) { return(await GetHashAsyncOverride(manager, pieceIndex, dest)); } await IOLoop; if (IncrementalHashes.TryGetValue(ValueTuple.Create(manager, pieceIndex), out IncrementalHashData? incrementalHash)) { // Immediately remove it from the dictionary so another thread writing data to using `WriteAsync` can't try to use it IncrementalHashes.Remove(ValueTuple.Create(manager, pieceIndex)); using var lockReleaser = await incrementalHash.Locker.EnterAsync(); // We request the blocks for most pieces sequentially, and most (all?) torrent clients // will process requests in the order they have been received. This means we can optimise // hashing a received piece by hashing each block as it arrives. If blocks arrive out of order then // we'll compute the final hash by reading the data from disk. if (incrementalHash.NextOffsetToHash == manager.TorrentInfo !.BytesPerPiece(pieceIndex)) { if (!incrementalHash.TryGetHashAndReset(dest)) { throw new NotSupportedException("Could not generate SHA1 hash for this piece"); } IncrementalHashCache.Enqueue(incrementalHash); return(true); } } else { // If we have no partial hash data for this piece we could be doing a full // hash check, so let's create a IncrementalHashData for our piece! incrementalHash = IncrementalHashCache.Dequeue(); incrementalHash.PrepareForFirstUse(manager, pieceIndex); } // We can store up to 4MB of pieces in an in-memory queue so that, when we're rate limited // we can process the queue in-order. When we try to hash a piece we need to make sure // that in-memory cache is written to the PieceWriter before we try to Read the data back // to hash it. if (WriteQueue.Count > 0) { await WaitForPendingWrites(); } using var releaser = await incrementalHash.Locker.EnterAsync(); // Note that 'startOffset' may not be the very start of the piece if we have a partial hash. int startOffset = incrementalHash.NextOffsetToHash; int endOffset = manager.TorrentInfo !.BytesPerPiece(pieceIndex); using (BufferPool.Rent(Constants.BlockSize, out Memory <byte> hashBuffer)) { try { while (startOffset != endOffset) { int count = Math.Min(Constants.BlockSize, endOffset - startOffset); if (!await ReadAsync(manager, new BlockInfo(pieceIndex, startOffset, count), hashBuffer).ConfigureAwait(false)) { return(false); } startOffset += count; incrementalHash.AppendData(hashBuffer.Slice(0, count)); } return(incrementalHash.TryGetHashAndReset(dest)); } finally { await IOLoop; IncrementalHashCache.Enqueue(incrementalHash); IncrementalHashes.Remove(ValueTuple.Create(manager, pieceIndex)); } } }
/// <inheritdoc/> public override int GetHashCode() { return(ValueTuple.Create(this.First, this.Last).GetHashCode()); }
public static void FormatValue_EmptyValueTupleTest() { string s = MsgUtils.FormatValue(ValueTuple.Create()); Assert.That(s, Is.EqualTo("()")); }
public static void FormatValue_OneElementValueTupleTest() { string s = MsgUtils.FormatValue(ValueTuple.Create("Hello")); Assert.That(s, Is.EqualTo("(\"Hello\")")); }
private static async Task <ValueTuple <SyntaxTreeIdentifierInfo, SyntaxTreeContextInfo, SyntaxTreeDeclarationInfo> > CreateInfoAsync(Document document, CancellationToken cancellationToken) { var syntaxFacts = document.GetLanguageService <ISyntaxFactsService>(); var ignoreCase = syntaxFacts != null && !syntaxFacts.IsCaseSensitive; var isCaseSensitive = !ignoreCase; HashSet <string> identifiers; HashSet <string> escapedIdentifiers; GetIdentifierSet(ignoreCase, out identifiers, out escapedIdentifiers); try { var containsForEachStatement = false; var containsLockStatement = false; var containsUsingStatement = false; var containsQueryExpression = false; var containsThisConstructorInitializer = false; var containsBaseConstructorInitializer = false; var containsElementAccess = false; var containsIndexerMemberCref = false; var predefinedTypes = (int)PredefinedType.None; var predefinedOperators = (int)PredefinedOperator.None; var declaredSymbolInfos = new List <DeclaredSymbolInfo>(); if (syntaxFacts != null) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); foreach (var current in root.DescendantNodesAndTokensAndSelf(descendIntoTrivia: true)) { if (current.IsNode) { var node = (SyntaxNode)current; containsForEachStatement = containsForEachStatement || syntaxFacts.IsForEachStatement(node); containsLockStatement = containsLockStatement || syntaxFacts.IsLockStatement(node); containsUsingStatement = containsUsingStatement || syntaxFacts.IsUsingStatement(node); containsQueryExpression = containsQueryExpression || syntaxFacts.IsQueryExpression(node); containsElementAccess = containsElementAccess || syntaxFacts.IsElementAccessExpression(node); containsIndexerMemberCref = containsIndexerMemberCref || syntaxFacts.IsIndexerMemberCRef(node); // We've received a number of error reports where DeclaredSymbolInfo.GetSymbolAsync() will // crash because the document's syntax root doesn't contain the span of the node returned // by TryGetDeclaredSymbolInfo(). There are two possibilities for this crash: // 1) syntaxFacts.TryGetDeclaredSymbolInfo() is returning a bad span, or // 2) Document.GetSyntaxRootAsync() (called from DeclaredSymbolInfo.GetSymbolAsync) is // returning a bad syntax root that doesn't represent the original parsed document. // By adding the `root.FullSpan.Contains()` check below, if we get similar crash reports in // the future then we know the problem lies in (2). If, however, the problem is really in // TryGetDeclaredSymbolInfo, then this will at least prevent us from returning bad spans // and will prevent the crash from occurring. DeclaredSymbolInfo declaredSymbolInfo; if (syntaxFacts.TryGetDeclaredSymbolInfo(node, out declaredSymbolInfo) && root.FullSpan.Contains(declaredSymbolInfo.Span)) { declaredSymbolInfos.Add(declaredSymbolInfo); } } else { var token = (SyntaxToken)current; containsThisConstructorInitializer = containsThisConstructorInitializer || syntaxFacts.IsThisConstructorInitializer(token); containsBaseConstructorInitializer = containsBaseConstructorInitializer || syntaxFacts.IsBaseConstructorInitializer(token); if (syntaxFacts.IsIdentifier(token) || syntaxFacts.IsGlobalNamespaceKeyword(token)) { var valueText = token.ValueText; identifiers.Add(valueText); if (valueText.Length != token.Width()) { escapedIdentifiers.Add(valueText); } } PredefinedType predefinedType; if (syntaxFacts.TryGetPredefinedType(token, out predefinedType)) { predefinedTypes |= (int)predefinedType; } PredefinedOperator predefinedOperator; if (syntaxFacts.TryGetPredefinedOperator(token, out predefinedOperator)) { predefinedOperators |= (int)predefinedOperator; } } } } var version = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false); return(ValueTuple.Create( new SyntaxTreeIdentifierInfo( version, new BloomFilter(FalsePositiveProbability, isCaseSensitive, identifiers), new BloomFilter(FalsePositiveProbability, isCaseSensitive, escapedIdentifiers)), new SyntaxTreeContextInfo( version, predefinedTypes, predefinedOperators, containsForEachStatement, containsLockStatement, containsUsingStatement, containsQueryExpression, containsThisConstructorInitializer, containsBaseConstructorInitializer, containsElementAccess, containsIndexerMemberCref), new SyntaxTreeDeclarationInfo( version, declaredSymbolInfos))); } finally { Free(ignoreCase, identifiers, escapedIdentifiers); } }
// Expr public Parameter(string name, string gradReq = "write", Shape shape = null, DType dtype = mx_real_t, float lrMult = 1.0f, float wdMult = 1.0f, Initializer init = null, bool allowDeferredInit = false, bool differentiable = true, string stype = "default", string gradStype = "default") { this._var = CoerceIntoSymbol(null); this._data = CoerceIntoNDArray(null); this._grad = CoerceIntoNDArray(null); this._ctxList = CoerceIntoContext[] (null); this._ctxMap = CoerceIntoObject(null); this._trainer = CoerceIntoTrainer(null); this._deferredInit = CoerceIntoValueTuple <Initializer, Context, Initializer, NDArrayBase>(ValueTuple.Create()); this._differentiable = CoerceIntoBool(differentiable); this._allowDeferredInit = CoerceIntoBool(allowDeferredInit); this._gradReq = CoerceIntoString(null); if (IsTrue(Isinstance(shape, Int))) { var local0 = (int)shape; shape = ValueTuple.Create(local0); } this._shape = CoerceIntoShape(shape); this.Name = name; this._dtype = CoerceIntoDType(dtype); this.LrMult = lrMult; this.WdMult = wdMult; this.GradReq = gradReq; this.Init = init; var validStypes = new [] { "default", "row_sparse", "csr" }; Assert((validStypes.Contains(gradStype)), "(validStypes.Contains(gradStype))"); Assert((validStypes.Contains(stype)), "(validStypes.Contains(stype))"); this._gradStype = CoerceIntoString(gradStype); this._stype = CoerceIntoString(stype); }
protected void GetCompilationReferences( TCompilation compilation, DiagnosticBag diagnostics, out ImmutableArray <MetadataReference> references, out IDictionary <ValueTuple <string, string>, MetadataReference> boundReferenceDirectives, out ImmutableArray <Location> referenceDirectiveLocations) { boundReferenceDirectives = null; ArrayBuilder <MetadataReference> referencesBuilder = ArrayBuilder <MetadataReference> .GetInstance(); ArrayBuilder <Location> referenceDirectiveLocationsBuilder = null; try { foreach (var referenceDirective in compilation.ReferenceDirectives) { if (compilation.Options.MetadataReferenceResolver == null) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataReferencesNotSupported, referenceDirective.Location)); break; } // we already successfully bound #r with the same value: if (boundReferenceDirectives != null && boundReferenceDirectives.ContainsKey(ValueTuple.Create(referenceDirective.Location.SourceTree.FilePath, referenceDirective.File))) { continue; } MetadataReference boundReference = ResolveReferenceDirective(referenceDirective.File, referenceDirective.Location, compilation); if (boundReference == null) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotFound, referenceDirective.Location, referenceDirective.File)); continue; } if (boundReferenceDirectives == null) { boundReferenceDirectives = new Dictionary <ValueTuple <string, string>, MetadataReference>(); referenceDirectiveLocationsBuilder = ArrayBuilder <Location> .GetInstance(); } referencesBuilder.Add(boundReference); referenceDirectiveLocationsBuilder.Add(referenceDirective.Location); boundReferenceDirectives.Add(ValueTuple.Create(referenceDirective.Location.SourceTree.FilePath, referenceDirective.File), boundReference); } // add external reference at the end, so that they are processed first: referencesBuilder.AddRange(compilation.ExternalReferences); // Add all explicit references of the previous script compilation. var previousScriptCompilation = compilation.ScriptCompilationInfo?.PreviousScriptCompilation; if (previousScriptCompilation != null) { referencesBuilder.AddRange(previousScriptCompilation.GetBoundReferenceManager().ExplicitReferences); } if (boundReferenceDirectives == null) { // no directive references resolved successfully: boundReferenceDirectives = SpecializedCollections.EmptyDictionary <ValueTuple <string, string>, MetadataReference>(); } references = referencesBuilder.ToImmutable(); referenceDirectiveLocations = referenceDirectiveLocationsBuilder?.ToImmutableAndFree() ?? ImmutableArray <Location> .Empty; } finally { // Put this in a finally because we have tests that (intentionally) cause ResolveReferenceDirective to throw and // we don't want to clutter the test output with leak reports. referencesBuilder.Free(); } }
public void ParsesTildeDoubleAsDouble() { Assert.AreEqual(ValueTuple.Create("key", 3.14d), SenderOptions.ParseItem("key~3.14")); }
int IVBFileCodeModelEvents.EndEdit() { try { if (_editCount == 1) { RoslynDebug.AssertNotNull(_batchElements); RoslynDebug.AssertNotNull(_invisibleEditor); List <ValueTuple <AbstractKeyedCodeElement, SyntaxPath> >?elementAndPaths = null; if (_batchElements.Count > 0) { foreach (var element in _batchElements) { var node = element.LookupNode(); if (node != null) { elementAndPaths ??= new List <ValueTuple <AbstractKeyedCodeElement, SyntaxPath> >(); elementAndPaths.Add(ValueTuple.Create(element, new SyntaxPath(node))); } } } if (_batchDocument != null) { // perform expensive operations at once var newDocument = State.ThreadingContext.JoinableTaskFactory.Run(() => Simplifier.ReduceAsync(_batchDocument, Simplifier.Annotation, cancellationToken: CancellationToken.None)); _batchDocument.Project.Solution.Workspace.TryApplyChanges(newDocument.Project.Solution); // done using batch document _batchDocument = null; } // Ensure the file is prettylisted, even if we didn't make any edits CodeModelService.EnsureBufferFormatted(_invisibleEditor.TextBuffer); if (elementAndPaths != null) { foreach (var elementAndPath in elementAndPaths) { // make sure the element is there. if (_codeElementTable.TryGetValue(elementAndPath.Item1.NodeKey, out var existingElement)) { elementAndPath.Item1.ReacquireNodeKey(elementAndPath.Item2, CancellationToken.None); } // make sure existing element doesn't go away (weak reference) in the middle of // updating the node key GC.KeepAlive(existingElement); } } _batchMode = false; _batchElements = null; } return(VSConstants.S_OK); } catch (Exception ex) { return(Marshal.GetHRForException(ex)); } finally { ReleaseEditor(); } }
public void ParsesTildeBoolAsBool() { Assert.AreEqual(ValueTuple.Create("key", false), SenderOptions.ParseItem("key~False")); }
public void ParsesEqualsIntAsString() { Assert.AreEqual(ValueTuple.Create("key", "42"), SenderOptions.ParseItem("key=42")); }
public void ParsesTildeIntAsInt() { Assert.AreEqual(ValueTuple.Create("key", 42), SenderOptions.ParseItem("key~42")); }
public void ParsesEqualsTildeAsString() { Assert.AreEqual(ValueTuple.Create("key", "~1"), SenderOptions.ParseItem("key=~1")); }
internal async Task <Solution> SimplifyAsync(Solution solution, IEnumerable <DocumentId> documentIds, bool replacementTextValid, AnnotationTable <RenameAnnotation> renameAnnotations, CancellationToken cancellationToken) { foreach (var documentId in documentIds) { if (this.IsDocumentChanged(documentId)) { var document = solution.GetDocument(documentId); if (replacementTextValid) { var optionSet = solution.Workspace.Options; document = await Simplifier.ReduceAsync(document, Simplifier.Annotation, optionSet, cancellationToken).ConfigureAwait(false); document = await Formatter.FormatAsync(document, Formatter.Annotation, cancellationToken : cancellationToken).ConfigureAwait(false); } // Simplification may have removed escaping and formatted whitespace. We need to update // our list of modified spans accordingly if (_documentToModifiedSpansMap.ContainsKey(documentId)) { _documentToModifiedSpansMap[documentId].Clear(); } if (_documentToComplexifiedSpansMap.ContainsKey(documentId)) { _documentToComplexifiedSpansMap[documentId].Clear(); } var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // First, get all the complexified statements var nodeAnnotations = renameAnnotations.GetAnnotatedNodesAndTokens <RenameNodeSimplificationAnnotation>(root) .Select(x => Tuple.Create(renameAnnotations.GetAnnotations <RenameNodeSimplificationAnnotation>(x).First(), (SyntaxNode)x)); HashSet <SyntaxToken> modifiedTokensInComplexifiedStatements = new HashSet <SyntaxToken>(); foreach (var annotationAndNode in nodeAnnotations) { var oldSpan = annotationAndNode.Item1.OriginalTextSpan; var node = annotationAndNode.Item2; var annotationAndTokens2 = renameAnnotations.GetAnnotatedNodesAndTokens <RenameTokenSimplificationAnnotation>(node) .Select(x => Tuple.Create(renameAnnotations.GetAnnotations <RenameTokenSimplificationAnnotation>(x).First(), (SyntaxToken)x)); List <ValueTuple <TextSpan, TextSpan> > modifiedSubSpans = new List <ValueTuple <TextSpan, TextSpan> >(); foreach (var annotationAndToken in annotationAndTokens2) { modifiedTokensInComplexifiedStatements.Add(annotationAndToken.Item2); modifiedSubSpans.Add(ValueTuple.Create(annotationAndToken.Item1.OriginalTextSpan, annotationAndToken.Item2.Span)); } AddComplexifiedSpan(documentId, oldSpan, node.Span, modifiedSubSpans); } // Now process the rest of the renamed spans var annotationAndTokens = renameAnnotations.GetAnnotatedNodesAndTokens <RenameTokenSimplificationAnnotation>(root) .Where(x => !modifiedTokensInComplexifiedStatements.Contains((SyntaxToken)x)) .Select(x => Tuple.Create(renameAnnotations.GetAnnotations <RenameTokenSimplificationAnnotation>(x).First(), (SyntaxToken)x)); foreach (var annotationAndToken in annotationAndTokens) { AddModifiedSpan(documentId, annotationAndToken.Item1.OriginalTextSpan, annotationAndToken.Item2.Span); } var annotationAndTrivias = renameAnnotations.GetAnnotatedTrivia <RenameTokenSimplificationAnnotation>(root) .Select(x => Tuple.Create(renameAnnotations.GetAnnotations <RenameTokenSimplificationAnnotation>(x).First(), x)); foreach (var annotationAndTrivia in annotationAndTrivias) { AddModifiedSpan(documentId, annotationAndTrivia.Item1.OriginalTextSpan, annotationAndTrivia.Item2.Span); } solution = document.Project.Solution; } } return(solution); }
public void ParsesDoubleEqualsAsString() { Assert.AreEqual(ValueTuple.Create("key", "=1"), SenderOptions.ParseItem("key==1")); }
// Use a member function to construct the value tuple so that Trill doesn't know how to optimize/decompose it public static ValueTuple <T1, T2> CreateValueTuple <T1, T2>(T1 item1, T2 item2) => ValueTuple.Create(item1, item2);
public void ParsesEqualsEmptyAsEmptyString() { Assert.AreEqual(ValueTuple.Create("key", ""), SenderOptions.ParseItem("key=")); }
private static ValueTuple <SyntaxToken, SyntaxToken>?FindAppropriateRangeForCloseBrace(SyntaxToken endToken) { // don't do anything if there is no proper parent var parent = endToken.Parent; if (parent == null || parent.Kind() == SyntaxKind.SkippedTokensTrivia) { return(null); } // cases such as namespace, type, enum, method almost any top level elements if (parent is MemberDeclarationSyntax or SwitchStatementSyntax or SwitchExpressionSyntax) { return(ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken())); } // property decl body or initializer if (parent is AccessorListSyntax) { // include property decl var containerOfList = parent.Parent; if (containerOfList == null) { return(ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken())); } return(ValueTuple.Create(containerOfList.GetFirstToken(), containerOfList.GetLastToken())); } if (parent is AnonymousObjectCreationExpressionSyntax) { return(ValueTuple.Create(parent.GetFirstToken(), parent.GetLastToken())); } if (parent is InitializerExpressionSyntax) { var parentOfParent = parent.Parent; if (parentOfParent == null) { return(ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken())); } // double initializer case such as // { { } if (parentOfParent is InitializerExpressionSyntax) { // if parent block has a missing brace, and current block is on same line, then // don't try to indent inner block. var firstTokenOfInnerBlock = parent.GetFirstToken(); var lastTokenOfInnerBlock = parent.GetLastToken(); var twoTokensOnSameLine = AreTwoTokensOnSameLine(firstTokenOfInnerBlock, lastTokenOfInnerBlock); if (twoTokensOnSameLine) { return(ValueTuple.Create(firstTokenOfInnerBlock, lastTokenOfInnerBlock)); } } // include owner of the initializer node such as creation node return(ValueTuple.Create(parentOfParent.GetFirstToken(), parentOfParent.GetLastToken())); } if (parent is BlockSyntax) { var containerOfBlock = GetTopContainingNode(parent); if (containerOfBlock == null) { return(ValueTuple.Create(GetAppropriatePreviousToken(parent.GetFirstToken()), parent.GetLastToken())); } // things like method, constructor, etc and special cases if (containerOfBlock is MemberDeclarationSyntax || IsSpecialContainingNode(containerOfBlock)) { return(ValueTuple.Create(GetAppropriatePreviousToken(containerOfBlock.GetFirstToken()), containerOfBlock.GetLastToken())); } // double block case on single line case // { { } if (containerOfBlock is BlockSyntax) { // if parent block has a missing brace, and current block is on same line, then // don't try to indent inner block. var firstTokenOfInnerBlock = parent.GetFirstToken(); var lastTokenOfInnerBlock = parent.GetLastToken(); var twoTokensOnSameLine = AreTwoTokensOnSameLine(firstTokenOfInnerBlock, lastTokenOfInnerBlock); if (twoTokensOnSameLine) { return(ValueTuple.Create(firstTokenOfInnerBlock, lastTokenOfInnerBlock)); } } // okay, for block, indent regardless whether it is first one on the line return(ValueTuple.Create(GetPreviousTokenIfNotFirstTokenInTree(parent.GetFirstToken()), parent.GetLastToken())); } // don't do anything return(null); }
public void ParsesEmptyEqualsAsEmptyStringKey() { Assert.AreEqual(ValueTuple.Create("", "aString"), SenderOptions.ParseItem("=aString")); }
public void WriteMillis(IEnumerable <int> millis) => WriteTimesAndGcs(millis.Select(m => ValueTuple.Create(m, new int?())));
public void ParsesTildeEmptyAsNull() { Assert.AreEqual(ValueTuple.Create("key", (String)null), SenderOptions.ParseItem("key~")); }
public override void Initialize() { var computeAverage = Observable.Func(((int, int)tuple) => ((double)tuple.Item1) / tuple.Item2); var recurse = Observable.Recurse <IItem, (int, int), (int, int)>((rec, item, tuple) => item == null ? tuple : Add(rec(item.Next, tuple), item.Value)); resultCache = Observable.Expression(() => computeAverage.Evaluate(recurse.Evaluate(root.Head, ValueTuple.Create(0, 0)))); resultCache.Successors.SetDummy(); }
public virtual void Register(string key, object value, Type type) { DebugCheck.NotNull(value); _initializers.GetOrAdd(ValueTuple.Create(type, key), value); }